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` +
+ ${this._renderIconButton( + 'copy', + copy.icon, + strings[copy.labelKey], + this._handleCopy + )} + ${this._renderIconButton( + 'eye-dropper', + 'eye_dropper', + strings.color_picker_eye_dropper, + this._handleEyeDropperClick, + !this._supportsEyeDropper + )} +
+ `; + } + + private _renderAlphaRow(): TemplateResult { + const strings = this.resourceStrings; + + return html` + + + + + + + + `; + } + + private _renderSelect(): TemplateResult { + const strings = this.resourceStrings; + const label = strings.color_picker_format; + + return html` + + + + + + ${colorFormats.map( + (format) => + html`${strings[formatNameKeys[format]]}` + )} + + `; + } + + private _renderInputsRow(): TemplateResult { + const label = this.resourceStrings.color_picker_value; + + return html` + ${cache(this.hideFormats ? nothing : this._renderSelect())} + + + + + + `; + } + + private _renderSwatches( + view: ColorPanelView, + views: ColorPanelView[] + ): TemplateResult { + // With only the gradient view, the list shows below the controls. + const below = view === 'gradient' && !views.includes('swatches'); + const shown = + (below || view === 'swatches') && + (!isEmpty(this.swatches) || this._hasSlottedSwatches); + + return html` + ${shown && below ? html`` : nothing} +
+ ${this.swatches.map( + (color) => html` + + ` + )} + +
+ `; + } + + private _renderViewSwitcher(view: ColorPanelView): TemplateResult { + const strings = this.resourceStrings; + const labels: Record = { + gradient: strings.color_picker_view_gradient, + swatches: strings.color_picker_view_swatches, + }; + + return html` + + ${VIEWS.map( + (item) => html` + + ${labels[item]} + + ` + )} + + `; + } + + private _renderContrast(): TemplateResult | typeof nothing { + // The server parses no colors, so the readout waits for the hydration. + if (this._hydrating || this._color.isEmpty || this._contrastColor.isEmpty) { + return nothing; + } + + const strings = this.resourceStrings; + const ratio = contrastRatio(this._color, this._contrastColor); + + return html` +
+ ${formatContrastRatio(ratio, this)} + ${CONTRAST_LEVELS.map(({ nameKey, minimumRatio }) => { + const pass = ratio >= minimumRatio; + const text = pass + ? strings.color_picker_contrast_pass + : strings.color_picker_contrast_fail; + + return html` + ${formatString(text, strings[nameKey])} + `; + })} +
+ `; + } + + private _renderGradientView(): TemplateResult { + return html` + ${this._renderCanvasGradient()} +
+ ${this._renderHueSlider()}${this._renderButtons()} +
+ ${ + this.showAlpha + ? html`
${this._renderAlphaRow()}
` + : nothing + } +
${this._renderInputsRow()}
+ `; + } + + protected override render(): TemplateResult { + const views = parseViews(this.views); + const view = this.activeView; + + return html` +
+ ${views.length > 1 ? this._renderViewSwitcher(view) : nothing} + ${cache(view === 'gradient' ? this._renderGradientView() : nothing)} + ${this._renderSwatches(view, views)} ${this._renderContrast()} +
+ `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'igc-color-panel': IgcColorPanelComponent; + } +} diff --git a/src/components/color-panel/color-swatch-group.ts b/src/components/color-panel/color-swatch-group.ts new file mode 100644 index 000000000..cb7c80756 --- /dev/null +++ b/src/components/color-panel/color-swatch-group.ts @@ -0,0 +1,31 @@ +import { IgcGroupBaseComponent } from '#internals/bases/group.js'; +import { registerComponent } from '#internals/definitions/register.js'; +import { styles as componentBase } from '../../styles/common/component.css.js'; +import IgcColorSwatchComponent from './color-swatch.js'; +import { styles } from './themes/color-swatch-group.base.css.js'; + +/** + * A labelled group of color swatches in a color panel or a color picker. + * + * @element igc-color-swatch-group + * + * @slot label - The label of the group. Its text also names the group. + * @slot - The swatches of the group. + * + * @csspart label - The label element. + */ +export default class IgcColorSwatchGroupComponent extends IgcGroupBaseComponent { + public static readonly tagName = 'igc-color-swatch-group'; + public static override styles = [componentBase, styles]; + + /* blazorSuppress */ + public static register(): void { + registerComponent(IgcColorSwatchGroupComponent, IgcColorSwatchComponent); + } +} + +declare global { + interface HTMLElementTagNameMap { + 'igc-color-swatch-group': IgcColorSwatchGroupComponent; + } +} diff --git a/src/components/color-panel/color-swatch.ts b/src/components/color-panel/color-swatch.ts new file mode 100644 index 000000000..272592fa2 --- /dev/null +++ b/src/components/color-panel/color-swatch.ts @@ -0,0 +1,202 @@ +import { html, LitElement, type PropertyValues } from 'lit'; +import { property } from 'lit/decorators.js'; +import { styleMap } from 'lit/directives/style-map.js'; +import { colorPanelContext } from '#internals/context.js'; +import { addAsyncContextConsumer } from '#internals/controllers/async-consumer.js'; +import { addInternalsController } from '#internals/controllers/internals.js'; +import { registerComponent } from '#internals/definitions/register.js'; +import { styles as componentBase } from '../../styles/common/component.css.js'; +import { ColorModel, type ColorKey, colorKey } from '../color-picker/model.js'; +import { + parseContextColor, + resolveSwatch, + swatchKey, + VAR_REFERENCE, +} from './common.js'; +import { styles } from './themes/color-swatch.base.css.js'; + +/** + * 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. + * + * @element igc-color-swatch + * + * @csspart base - The color fill of the swatch. + * + * @cssstate ig-selected - The color of the swatch is the value of the panel. + */ +export default class IgcColorSwatchComponent extends LitElement { + public static readonly tagName = 'igc-color-swatch'; + public static override styles = [componentBase, styles]; + + /* blazorSuppress */ + public static register(): void { + registerComponent(IgcColorSwatchComponent); + } + + //#region Internal state and properties + + private readonly _panel = addAsyncContextConsumer( + this, + colorPanelContext, + (panel) => { + this.requestUpdate(); + panel.refreshSwatches(); + } + ); + + // The panel sets `ariaSelected` and the selected state through + // `internalsOf()`. + private readonly _internals = addInternalsController(this, { + initialARIA: { role: 'option', ariaSelected: 'false' }, + reflectRole: true, + reflectLabel: true, + }); + + /** The `color` that {@link _key} comes from. */ + private _resolvedColor?: string; + + /** Whether the color has a `var()`, which can resolve to a new color. */ + private _contextual = false; + + private _key: ColorKey | null = null; + + /** The resolved color. A no-color swatch and an invalid color have none. */ + private _model?: ColorModel; + + private get _color(): string { + return this.color?.trim() ?? ''; + } + + private get _accessibleName(): string { + const panel = this._panel.value; + + if (this.label) return this.label; + if (!this._color) return panel?.noColorLabel() ?? ''; + + return (this._model && panel?.swatchName(this._model)) || this._color; + } + + //#endregion + + //#region Public attributes and properties + + /** + * 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. + * + * @attr color + */ + @property() + public color?: string; + + /** + * 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. + * + * @attr label + */ + @property() + public label?: string; + + //#endregion + + //#region Lit lifecycle methods + + public override disconnectedCallback(): void { + super.disconnectedCallback(); + this._panel.value?.refreshSwatches(); + } + + protected override willUpdate(): void { + this._syncName(); + } + + protected override updated(props: PropertyValues): void { + // A no-color swatch has no `color` in the first changed properties. + if (this._resolvedColor === undefined || props.has('color')) { + this[resolveSwatch](); + this._panel.value?.refreshSwatches(); + } + } + + //#endregion + + //#region Internal API + + /** @internal */ + public get [swatchKey](): ColorKey | null { + return this._key; + } + + /** @internal */ + public [resolveSwatch](): void { + const color = this._color; + + if (color === this._resolvedColor && !this._contextual) { + return; + } + + this._resolvedColor = color; + this._contextual = false; + + if (!color) { + this._setModel(); + return; + } + + let model = ColorModel.parse(color); + + // The parser rejects `var()`. It resolves from the swatch. + if (model.isEmpty && VAR_REFERENCE.test(color)) { + this._contextual = true; + model = parseContextColor(this, color); + } + + this._setModel(model.isEmpty ? undefined : model); + } + + /** Names the swatch at once: the model changes after the render. */ + private _setModel(model?: ColorModel): void { + this._model = model; + + if (model) { + this._key = colorKey(model); + } else { + // An invalid color has no key. The no-color swatch has the empty key. + this._key = this._color ? null : ''; + } + + this._syncName(); + } + + private _syncName(): void { + this._internals.setARIA({ ariaLabel: this._accessibleName }); + } + + //#endregion + + protected override render() { + const color = this._color; + + return html` + + `; + } +} + +declare global { + interface HTMLElementTagNameMap { + 'igc-color-swatch': IgcColorSwatchComponent; + } +} diff --git a/src/components/color-panel/common.ts b/src/components/color-panel/common.ts new file mode 100644 index 000000000..4cdb48097 --- /dev/null +++ b/src/components/color-panel/common.ts @@ -0,0 +1,127 @@ +import { isServer } from 'lit'; +import { readWithStyles } from '#internals/utils/dom.js'; +import { ColorModel } from '../color-picker/model.js'; +import type { ColorPanelView } from '../types.js'; + +/** + * Moves the canvas marker to the position of the color on the area. + * + * @internal + */ +export const syncMarker = Symbol('syncMarker'); + +/** + * A copy of the color model of the panel. It keeps the hue of a gray, which a + * color string does not carry. + * + * @internal + */ +export const panelColor = Symbol('panelColor'); + +/** + * Reads the color of a swatch again. A color with `var()` resolves from the + * computed style of the swatch. + * + * @internal + */ +export const resolveSwatch = Symbol('resolveSwatch'); + +/** + * The resolved color of a swatch as a color key: an empty key for the + * no-color swatch, `null` for a color that does not resolve. + * + * @internal + */ +export const swatchKey = Symbol('swatchKey'); + +/** A `var()` reference, the only context that a swatch color resolves. */ +export const VAR_REFERENCE = /\bvar\(/i; + +/** The custom property that resolves a context color. */ +const CONTEXT_PROPERTY = '--_context-color'; + +/** + * Parses a color that depends on its context, such as `var()`, + * `currentcolor`, `light-dark()` or a system color, from the computed style of + * `element`. An invalid color, an undefined variable and a server render give + * an empty color. + */ +export function parseContextColor( + element: HTMLElement, + value: string +): ColorModel { + if (isServer || !CSS.supports('color', value)) { + return ColorModel.empty(); + } + + const styles = { + [CONTEXT_PROPERTY]: value, + 'outline-color': `var(${CONTEXT_PROPERTY})`, + }; + + return readWithStyles(element, styles, (style) => { + // An undefined variable, or one that is not a color, leaves no color. + const resolved = style.getPropertyValue(CONTEXT_PROPERTY).trim(); + + return resolved && CSS.supports('color', resolved) + ? ColorModel.parse(style.outlineColor) + : ColorModel.empty(); + }); +} + +/** The custom state of the selected swatch. */ +export const SWATCH_SELECTED_STATE = 'ig-selected'; + +/** + * The parts of the panel that the color picker exposes as its own. All parts + * except `base`, which the popup of the picker replaces. + */ +export const panelParts = [ + 'picker-canvas', + 'marker', + 'dragging', + 'main-row', + 'alpha-row', + 'inputs-row', + 'buttons', + 'hue', + 'alpha', + 'alpha-input', + 'copy', + 'eye-dropper', + 'format-select', + 'swatches', + 'swatch', + 'selected', + 'view-switcher', + 'view-button', + 'active', + 'contrast', + 'contrast-ratio', + 'contrast-mark', + 'pass', + 'fail', +] as const; + +/** The views of the panel, in the order of the view switcher. */ +export const VIEWS: readonly ColorPanelView[] = ['gradient', 'swatches']; + +/** + * The views in a `views` token list, in the order of the switcher. Unknown + * tokens drop out. A list without a known view gives the gradient view. + */ +export function parseViews(views: string | null | undefined): ColorPanelView[] { + const tokens = new Set(views?.split(/\s+/)); + const known = VIEWS.filter((view) => tokens.has(view)); + + return known.length ? known : ['gradient']; +} + +/** The view that shows: `active` when `views` has it, else the first view. */ +export function resolveView( + views: string | null | undefined, + active: ColorPanelView +): ColorPanelView { + const list = parseViews(views); + return list.includes(active) ? active : list[0]; +} diff --git a/src/components/color-panel/spec.md b/src/components/color-panel/spec.md new file mode 100644 index 000000000..4bab3db52 --- /dev/null +++ b/src/components/color-panel/spec.md @@ -0,0 +1,672 @@ +# Color panel specification + +- [Color panel specification](#color-panel-specification) + - [Revision history](#revision-history) + - [Overview](#overview) + - [Key features](#key-features) + - [Acceptance criteria](#acceptance-criteria) + - [User stories](#user-stories) + - [End-user stories](#end-user-stories) + - [Developer stories](#developer-stories) + - [Functionality](#functionality) + - [End-user experience](#end-user-experience) + - [Developer experience](#developer-experience) + - [Basic initialization](#basic-initialization) + - [Value and format](#value-and-format) + - [The OKLCH area](#the-oklch-area) + - [Swatches](#swatches) + - [Views](#views) + - [Recent colors](#recent-colors) + - [Events](#events-1) + - [Value text and color names](#value-text-and-color-names) + - [Copy](#copy) + - [Contrast](#contrast) + - [In the color picker](#in-the-color-picker) + - [Styling](#styling) + - [Localization](#localization) + - [Keyboard interactions](#keyboard-interactions) + - [API](#api) + - [Properties and attributes](#properties-and-attributes) + - [Methods](#methods) + - [Events](#events) + - [Slots](#slots) + - [CSS Shadow parts](#css-shadow-parts) + - [CSS custom properties](#css-custom-properties) + - [igc-color-swatch](#igc-color-swatch) + - [igc-color-swatch-group](#igc-color-swatch-group) + - [Test scenarios](#test-scenarios) + - [Rendering](#rendering) + - [Value and format](#value-and-format-1) + - [Events](#events-2) + - [Eye dropper](#eye-dropper) + - [Marker](#marker) + - [Value text](#value-text) + - [Copy](#copy-1) + - [Swatches](#swatches-1) + - [Swatch keyboard](#swatch-keyboard) + - [Views](#views-1) + - [Contrast](#contrast-1) + - [OKLCH area](#oklch-area) + - [Assumptions and limitations](#assumptions-and-limitations) + - [Accessibility](#accessibility) + - [ARIA roles and properties](#aria-roles-and-properties) + - [Keyboard support](#keyboard-support) + - [Right to Left support](#right-to-left-support) + +## Revision history + +| Version | Date | Notes | +| ------: | ---------- | --------------------- | +| 1 | 2026-11-23 | Initial specification | +| 2 | 2026-11-23 | Swatch elements and groups, the swatch listbox, the no-color swatch, `var()` swatches, the gradient and swatch views | +| 3 | 2026-11-23 | Review fixes: one selected swatch, `var()` only, a plain swatch fill, the format names from the resource strings, the panel theme files | +| 4 | 2026-11-23 | The `oklch` format | +| 5 | 2026-11-23 | Enter applies the draft of a color picker in the confirm mode | +| 6 | 2026-11-23 | The value text of the sliders, color names and the copy feedback | +| 7 | 2026-11-24 | The contrast readout: `contrast-against`, the WCAG 2 ratio and the AA and AAA levels | +| 8 | 2026-11-24 | The OKLCH area: in the `oklch` format, the area is lightness by chroma and the hue slider is the OKLCH hue | + +## Overview + +The `igc-color-panel` component is the color selection surface of the [color picker](../color-picker/spec.md), +alone in the page. It holds an area (HSV saturation by value, or OKLCH lightness by chroma in the `oklch` format), a +hue slider, an optional alpha slider and alpha +input, a format select, a color value input, a copy action, an eye dropper action and an optional swatch list. + +The swatches are `igc-color-swatch` children, optionally in labelled `igc-color-swatch-group` children. The panel has +two views: the gradient view with the canvas and the inputs, and the swatch view with the swatch list. + +The panel is not a form control: it has no `name`, no validation and no form reset. It suits theme editors, +sidebars and other places where the controls stay visible. The color picker shows a panel in its popup. + +### Key features + +- **The surface of the color picker**: the same canvas, sliders, inputs, buttons and swatches. +- **Swatch elements**: swatches as light DOM children, in labelled groups, with a no-color swatch and `var()` colors + that follow the page. +- **Two views**: the gradient view and the swatch view, with a view switcher when both are available. +- **Any CSS color string**: hex, `rgb()`, `hsl()`, named colors and the other notations, such as `oklch()`, `lab()`, + `color()` and `color-mix()`, are parsed into sRGB and normalized. +- **Four serialization formats**, `hex`, `rgb`, `hsl` and `oklch`, switchable at run time without altering the + represented color. +- **Contrast readout**: the WCAG 2 contrast ratio of the color over a background that the app sets, with the AA and + AAA levels for normal text. +- **Change events per gesture**: `igcInput` while the user changes the color, `igcChange` when the change ends, as + for a native range input. +- **Themeable**: the themes of the color picker, and shadow parts for every region. + +### Acceptance criteria + +The `igc-color-panel` must: + +- be WAI-ARIA compliant. +- parse any valid CSS color string assigned to `value`, and clip a color outside the sRGB gamut to it; an empty, + whitespace-only or invalid string clears the value, and so does a color that depends on its context. +- serialize `value` in the current `format`, and keep the color when the format changes. +- keep the canvas marker, the sliders and the inputs synchronized with the color. +- emit `igcInput` for each change of the user, and `igcChange` when a change ends with a color that differs from the + last reported color. +- emit no events for a value from code or a format change. +- keep the events of its inner elements inside. +- show its swatches as the options of one listbox, with one tab stop, and mark the swatch that has the color of the + value as selected. +- show the swatch view, the gradient view or both, as `views` sets. +- show the WCAG 2 contrast ratio of the value over `contrast-against`, and the AA and AAA levels for normal text, + while both colors are set. + +## User stories + +### End-user stories + +As an end-user, I expect to be able to: + +- drag inside the gradient area to adjust saturation and brightness, and move the marker with the keyboard. +- drag the hue slider to change the base color, and the alpha slider to change the opacity. +- type an exact color string or an alpha percentage. +- switch between the hex, RGB and HSL notations. +- pick a swatch, copy the color, or pick a color from the screen where the browser supports it. +- see which swatch has the current color, and move between the swatches with the arrow keys. +- clear the color with the no-color swatch. +- switch between the gradient and the swatches when the panel offers both. +- see whether the color has enough contrast with the background that it goes on. + +### Developer stories + +As a developer, I expect to be able to: + +- place the panel in a page and read and write its `value` as a string. +- choose the notation of `value` through `format`. +- show live changes with `igcInput` and save finished changes with `igcChange`. +- show the alpha controls, hide the format select, and provide swatches. +- group the swatches under labels, use my design tokens as swatch colors, and keep a list of recent colors. +- offer a swatch-only panel, or both views with a switcher. +- show the contrast of the color with a background of my design, also a design token. +- style each region through its shadow part. + +## Functionality + +### End-user experience + +The panel shows the controls of the color picker popup in place. Every change of the user updates all the controls +at once. + +### Developer experience + +#### Basic initialization + +```html + +``` + +#### Value and format + +```html + + +``` + +`value` follows the rules of the [color picker value](../color-picker/spec.md#value-and-formats): any CSS color +converts to sRGB, a color outside the gamut clips, and a color that depends on its context, such as `currentcolor`, +clears the value. Reading `value` gives the color in the current `format`. + +A write of the same color, in any notation, keeps the internal color. This keeps the hue of a gray, which a color +string does not carry. A wrapper that writes every property on each render, such as `@lit/react`, does not reset the +hue slider. + +#### The OKLCH area + +In the `oklch` format, the area shows the OKLCH lightness (0 % at the bottom to 100 % at the top) by the chroma (0 at +the left to 0.33 at the right) at the OKLCH hue of the hue slider. The chroma axis has the same scale for every hue, +just past the largest sRGB chroma (0.3225, at hue 328), so the marker position equals the L and C of the color text. +The hue slider is the OKLCH hue, from 0 to 360, and its track shows the cusp of each hue: its most chromatic sRGB +color. In the other formats, the area is HSV saturation by value and the hue slider is the HSV hue. + +The model is sRGB, so part of each OKLCH area is out of gamut. The area paints only the sRGB colors; beyond the gamut +edge it is transparent, and the panel surface shows. A drag or a key beyond the gamut edge keeps the lightness and cuts +the chroma back to the edge, as CSS gamut mapping does, and the marker stops at the edge. A pick that gives the same +color reports nothing, so Arrow Right at the edge does nothing. A move of the hue slider to a hue with less +gamut cuts the chroma back too. + +At the hue of blue (264.05), the black-to-blue edge of sRGB is a thin spike apart from the rest of the area, because +every color from black to `#0000ff` has that hue. The area paints the spike as a line 1 px wide, so the marker of a +pure blue sits on it. + +The color keeps its OKLCH lightness, chroma and hue, as it keeps HSV, so a gray keeps the hue that the user set. A +gray takes the hue of the other space through the cusp: HSV hue 210 gives the OKLCH hue of `hsv(210 100% 100%)`, about +256, and back the same way. An empty value starts at white with the hue slider at 29, the OKLCH hue of red. + +The OKLCH area is a canvas that the panel paints in CSS pixels, at most once per frame, when the hue or the size +changes. The alpha of a pixel is the share of it inside the gamut, so the gamut edge is smooth and has no steps. A +server render shows the area without colors until the client paints. + +#### Swatches + +The swatches of the panel are `igc-color-swatch` children. A swatch has a `color` (any CSS color) and an optional +`label`. An `igc-color-swatch-group` puts swatches under a label, which also names the group. + +```html + + + + Brand + + + + +``` + +- **Swatch list.** All swatches are the options of one listbox, named "Color swatches". The swatches of the `swatches` + property come first, then the children in document order. A swatch can be in any child element, not only in a + group. The list lays out the swatches in rows of eight; a group starts a new row and its swatches take the same + columns. Without swatches, the list does not show. +- **Pick.** A click, Enter or Space on a swatch sets its color as the value, in the current + format. A pick is one change: one `igcInput` and one `igcChange`. In the popup of a color picker in the + [confirm mode](../color-picker/spec.md#confirm-mode), Enter on a swatch, the canvas marker or a slider + also applies the draft. +- **Selected swatch.** The first swatch that has the color of the value, alpha included, is selected: `aria-selected` + is true and the swatch has the `ig-selected` custom state. The list is a single-select listbox, so a second swatch + with the same color is not selected. A swatch of the `swatches` property also gets the `selected` part. +- **No-color swatch.** A swatch without a `color` (or an empty string in `swatches`) is the no-color swatch. It shows + the "no color" mark of the empty anchor, it is selected while the value is empty, and a pick clears the value. +- **`var()` colors.** A swatch resolves `var()` from its own computed style. A pick writes the resolved color, and the + selected state compares the resolved color. Other values that depend on the context, such as `currentcolor` or + `light-dark()` without `var()`, are invalid. The panel reads the colors again when a swatch connects or changes its color, when the theme + changes and when the size of the panel changes, as when a hidden panel shows. A custom property that changes at another time takes effect at the next of these. + Before hydration, a server-rendered swatch shows its color but no selected state. +- **Invalid colors.** A swatch with an invalid color, or a `var()` that does not resolve to a color, is never + selected, and a pick of it does nothing. +- **Names.** A swatch is named by its `label`, else by its [color name](#value-text-and-color-names), such as "vibrant + red". The name of a color that is not opaque adds its alpha, such as "vibrant red, alpha 50%". A swatch with an invalid + color is named by its color string. The no-color swatch without a `label` is named by the `color_picker_no_color` + string of the panel ("No color"). + +#### Views + +`views` is a space-separated list of `gradient` and `swatches`. The default is `gradient`. + +| `views` | On screen | +| -------------------- | ----------------------------------------------------------------------------- | +| `gradient` | The gradient view, with the swatch list below the inputs. | +| `swatches` | The swatch list only. | +| `gradient swatches` | A view switcher at the top, and the view that `active-view` sets. | + +In the swatch view, the swatch list is the only content. The swatch list shows below the gradient controls only when +the panel has no swatch view. `active-view` sets the view on screen; the switcher updates it and emits no event, as the +calendar does for its views. A view that `views` does not have gives the first view of `views`, and reading +`activeView` returns the view on screen. Unknown tokens drop out. + +```html + +``` + +#### Recent colors + +The panel has no API for recent colors. The app owns the list: an `igcChange` handler adds the new color to a swatch +group, for example at the start of a "Recent" group, and removes the oldest swatch over a limit. The app also decides +where to keep the list between visits. The `RecentColors` story of the color picker shows the recipe. + +```ts +picker.addEventListener('igcChange', ({ detail }) => { + if (!detail) return; + const swatch = document.createElement('igc-color-swatch'); + swatch.color = detail; + recentGroup.querySelector('[slot="label"]')!.after(swatch); +}); +``` + +#### Events + +The panel emits `igcInput` for each change of the user, and `igcChange` when the change ends. It emits `igcChange` only +when the color differs from the color of the last `igcChange` or of the last value from code. A change that returns to +that color emits no `igcChange`. + +| User action | `igcInput` | `igcChange` | +| --------------------------------------------------- | ----------- | ---------------------------- | +| A drag on the canvas | Each move | At the release | +| A step key on the canvas marker | Each key | Each key | +| A drag of the hue or alpha slider | Each move | At the release | +| A key on the hue or alpha slider | Each key | Each key | +| Typing in the alpha input | Each edit | At the commit (blur, Enter) | +| Arrow Up or Arrow Down in the alpha input | Each key | Each key | +| A commit of the color value input (blur, Enter) | None | At the commit | +| A swatch pick (click, Enter, Space) | Once | Once | +| An eye dropper pick | Once | Once | +| A format switch | None | None | +| A view switch | None | None | + +A commit of the color value input emits no `igcInput`, as in the color picker. A value from code and a format change +emit no events. + +#### Value text and color names + +Assistive technology reads a value text for each slider: + +| Control | Value text | Example | +| ------------- | ------------------------------------------------------ | -------------------------------------------------- | +| Hue slider | The angle and the name of the hue at the slider position | 120 degrees, green | +| Hue slider in `oklch` | The OKLCH angle and the name of that hue | 328 degrees, magenta | +| Alpha slider | The alpha percentage | 50% | +| Canvas marker | The saturation, the brightness and the color name | Saturation 100%, brightness 67%, dark vibrant blue | +| Canvas marker in `oklch` | The lightness, the chroma and the color name | Lightness 70%, chroma 0.322, vibrant magenta | + +The numbers use the number format of the locale. A color name has a hue word and can have a lightness word and a +chroma word before it: + +- Lightness: very dark, dark, light, very light. +- Chroma: grayish, vibrant. +- Hue: red, orange, brown, yellow, yellow green, green, cyan, blue, purple, magenta, pink. + +A color with almost no chroma is black, white or gray, and a gray can have a lightness word. The panel calculates the +words from the OKLCH lightness, chroma and hue of the color: + +- The hue word comes from the OKLCH hue. A dark orange is brown, and brown is never vibrant. A very light red is pink. +- The lightness word compares the color with the most chromatic sRGB color of its hue. Pure yellow and pure blue have no + lightness word, and navy is "dark blue". +- The chroma word compares the chroma with an estimate of the most chroma that sRGB has at the lightness and hue of + the color. The estimate is a triangle of black, white and the most chromatic color of the hue. + +The words and their order come from the resource strings, and `color_picker_value_with_name` joins a value and a name. +See [Localization](#localization). While the value is empty, the value text of the canvas marker has no color name. The +hue slider still names its hue, which is the hue of the canvas. + +#### Copy + +The copy button writes the value to the clipboard. After a copy, the button shows a check icon and the name "Copied" +for one second. After a failure, it shows an error icon and the name "Copy failed". A copy without the clipboard API, +as outside a secure context, fails. Only the latest copy shows its result, and a copy that ends after the panel leaves +the page shows nothing. The panel has no live region, so a screen reader can miss the new name. + +#### Contrast + +```html + +``` + +With `contrast-against`, the panel shows a contrast readout at its bottom, in both views. The readout gives the WCAG 2 +contrast ratio of the value over that color, such as "Contrast 4.54:1", and a mark for each level for normal text: +"AA pass" or "AA fail" for 4.5:1, and "AAA pass" or "AAA fail" for 7:1. The ratio comes from the relative luminance of +the two colors in linear sRGB. A value with alpha goes over the `contrast-against` color, and a `contrast-against` +color with alpha goes over white, as the browser paints them. The ratio shows two decimals at most and drops the +others, so a ratio below a level never reads as that level: 4.4999 reads "4.49". + +`contrast-against` takes any CSS color. A color that depends on its context, such as a `var()`, `currentcolor`, +`light-dark()` or a system color, resolves from the computed style of the panel, as a `var()` swatch does. The panel +reads it again when `contrast-against` changes, when the theme changes and when the size of the panel changes, as when +a hidden panel shows. An empty value, an empty or invalid `contrast-against`, and a `var()` that is not a color hide the +readout. + +The readout follows each change of the color. It has no live region. A server render has no readout; it shows after +the hydration. + +#### In the color picker + +The color picker renders a panel in its popup. It passes `format`, `show-alpha`, `hide-formats`, `swatches`, `views`, +`active-view`, `contrast-against` and its resource strings to the panel, and takes each change of the panel as a change of the user. It +forwards its swatch and group children to the panel through a nested slot. A format or a view that the user picks in +the panel updates the `format` or the `activeView` of the picker. The events of the panel do +not leave the picker; the picker emits its own `igcInput`, and its `igcChange` when the focus leaves it. The picker +forwards the parts of the panel as its own parts, except `base`. In the popup, the popup paints the surface and the +`base` part of the panel has no background, border or radius. + +#### Styling + +The panel uses the themes of the color picker. Alone in the page, its `base` part paints the surface: the picker +background, border and border radius, with no elevation. + +```css +igc-color-panel::part(base) { + border-radius: 12px; +} +``` + +### Localization + +The panel uses the strings of the color picker, from the `igniteui-i18n-core` package, through the `locale` and +`resourceStrings` properties. The [color picker localization](../color-picker/spec.md#localization) lists the keys. In +the color picker, the panel takes the strings of the picker. + +The panel uses strings that `igniteui-i18n-core` does not ship yet: `color_picker_no_color` ("No color"), +`color_picker_swatches` ("Color swatches"), `color_picker_view_gradient` ("Gradient"), `color_picker_view_swatches` +("Swatches"), the format names `color_picker_format_hex` ("Hex"), `color_picker_format_rgb` ("RGB"), +`color_picker_format_hsl` ("HSL") and `color_picker_format_oklch` ("OKLCH"), the copy names `color_picker_copied` +("Copied") and `color_picker_copy_failed` ("Copy failed"), `color_picker_value_with_name` ("{0}, {1}") and the color +name strings `color_picker_name_*`, and the contrast strings `color_picker_contrast_ratio` ("Contrast {0}:1"), +`color_picker_contrast_pass` ("{0} pass"), `color_picker_contrast_fail` ("{0} fail"), `color_picker_contrast_aa` ("AA") +and `color_picker_contrast_aaa` ("AAA"), and the OKLCH area strings `color_picker_canvas_oklch_label` ("Lightness and +chroma") and `color_picker_canvas_oklch_value` ("Lightness {0}%, chroma {1}"). Until it does, every locale shows the English text, and `resourceStrings` can +replace them. + +A color name takes the words of `color_picker_name_*` in the order of `color_picker_name_pattern` ("{0} {1} {2}"): +`{0}` is the lightness word, `{1}` the chroma word and `{2}` the hue word. A word that a color does not have leaves no +extra space, so a language that puts the adjectives after the noun uses "{2} {0} {1}", and a language with no spaces +uses "{0}{1}{2}". `color_picker_name_with_alpha` ("{0}, alpha {1}") adds the alpha to the name of a swatch. + +In the contrast strings, `{0}` is the ratio, in the number format of the locale, or the name of the level. In +`color_picker_canvas_oklch_value`, `{0}` is the lightness in whole percent and `{1}` the chroma with 3 decimals, in the +number format of the locale. + +### Keyboard interactions + +| Key combination | Result | +| ------------------------------------------ | ---------------------------------------------------------------------------------------- | +| Arrow keys | With the canvas marker focused, moves it 1 % of the canvas in the direction of the arrow. | +| Shift + Arrow keys | With the canvas marker focused, moves it 10 % of the canvas. | +| Page Up / Page Down | With the canvas marker focused, moves it 10 % up or down. | +| Home / End | With the canvas marker focused, moves it 10 % left or right. | +| Arrow Up / Arrow Down | In the alpha input, steps the alpha by 1 %. | +| Arrow Left / Arrow Right | In the swatch list, moves the focus to the previous or next swatch, in reading order. The ends wrap. | +| Arrow Up / Arrow Down | In the swatch list, moves the focus to the nearest swatch in the row above or below. | +| Home / End | In the swatch list, moves the focus to the first or last swatch. | +| Enter / Space | In the swatch list, picks the focused swatch. | +| Enter | In a color picker in the confirm mode, on a swatch, the canvas marker or a slider, also applies the draft. | +| Tab | Moves focus between the controls of the panel. The swatch list is one tab stop. | + +The arrow keys in the swatch list move the focus only; they do not pick. The tab stop of the list is the focused +swatch, else the selected swatch, else the first swatch. The rows come from the layout, so a group and a theme that +changes the column count count. + +The hue and alpha sliders are native range inputs and keep their keys. + +## API + +### Properties and attributes + +| Property | Attribute | Reflected | Type | Default | Description | +| --------------- | ------------ | --------- | ----------------------------- | ------- | ----------------------------------------------------------------------------------------------------- | +| value | value | No | `string` | `''` | The value as a CSS color string, in `format`. Accepts any CSS color and clips it to sRGB. A color that depends on its context clears it. | +| format | format | No | `ColorFormat` | `hex` | The color format of the string value. A format change renders `value` in the new notation. | +| showAlpha | show-alpha | No | `boolean` | false | Whether to show the alpha slider and input. | +| hideFormats | hide-formats | No | `boolean` | false | Whether the format select is hidden. | +| swatches | Not set | No | `string[]` | `[]` | Pre-defined color strings, rendered as swatches in front of the swatch children. An empty string gives the no-color swatch. | +| views | views | No | `string` | `gradient` | The views, a space-separated list of `gradient` and `swatches`. Both show a view switcher. | +| activeView | active-view | No | `ColorPanelView` | `gradient` | The view on screen. The switcher sets it. A view that `views` does not have gives the first view of `views`. | +| contrastAgainst | contrast-against | No | `string` | `''` | 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 | locale | No | `string` | Not set | The locale for the resource strings. Falls back to the inherited locale, then the global one. | +| resourceStrings | Not set | No | `ColorPickerResourceStrings` | EN | The texts of the component. The strings that you set replace the strings of the current locale. | + +### Methods + +The panel has no public methods. + +### Events + +| Name | Cancellable | Detail | Description | +| --------- | ----------- | -------- | --------------------------------------------------------------------------------------------------- | +| igcInput | false | `string` | Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eye dropper. | +| igcChange | false | `string` | Emitted when the user ends a change of the color. See [Events](#events-1). | + +The events of the inner inputs, the format select, the view switcher and the canvas stay inside the panel. + +### Slots + +| Name | Description | +| --------- | -------------------------------------------------------------------------------------------------- | +| (default) | The `igc-color-swatch` and `igc-color-swatch-group` children, shown in the swatch list after the swatches of `swatches`. | + +### CSS Shadow parts + +| Part | Description | +| --------------- | --------------------------------------------------------------------------- | +| `base` | The wrapper of the panel. Alone in the page, it paints the surface. | +| `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 and eye dropper 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 eye dropper 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. | + +A swatch child is not a part of the panel. Style it with the `igc-color-swatch` selector, its `base` part and its +`ig-selected` custom state. + +### CSS custom properties + +The panel has no public custom properties. The `--_` variables in its styles, for example `--_current-color`, are +internal. A swatch takes the color picker theme variables from the panel that shows it. + +### igc-color-swatch + +A color option of the swatch list. It has no theme of its own; it takes the variables of the panel. + +| Property | Attribute | Reflected | Type | Default | Description | +| -------- | --------- | --------- | -------- | ------- | --------------------------------------------------------------------------- | +| color | color | No | `string` | Not set | Any CSS color, also `var()`. Without a color, the swatch is the no-color swatch. | +| label | label | No | `string` | Not set | 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. | + +| Part | Description | +| ------ | ---------------------------------------------------------------------- | +| `base` | The color fill. | + +| Custom state | Description | +| ------------- | ------------------------------------------------- | +| `ig-selected` | The color of the swatch is the value of the panel. | + +### igc-color-swatch-group + +A labelled group of swatches. It shares its base with `igc-select-group` and `igc-dropdown-group`. + +| Slot | Description | +| --------- | ---------------------------------------------------- | +| `label` | The label of the group. Its text also names the group. | +| (default) | The swatches of the group. | + +| Part | Description | +| ------- | ------------------ | +| `label` | The label element. | + +## Test scenarios + +The panel suite is [`color-panel.spec.ts`](./color-panel.spec.ts). The canvas, the color model, the parser, the +converters and the property-based tests live with the color picker; see the +[color picker test scenarios](../color-picker/spec.md#test-scenarios). The color picker suite also covers the panel in +the popup through the picker. The color name rule has its own suite, `color-name.spec.ts`, with the color picker, and +so has the contrast ratio, `contrast.spec.ts` and `contrast.property.spec.ts`. + +### Rendering + +The a11y audit, the controls in the `base` part, the alpha row, the format select and the swatches, the surface alone +in the page, and no surface in the color picker popup. + +### Value and format + +Any CSS color in the current format, a color and the placeholder in `oklch`, the empty value for an invalid color and a +context color, the hue of a gray kept for a write of the same color, the format names from the resource strings, and +no events for a value from code or a format switch. + +### Events + +`igcInput` and `igcChange` for the sliders, the canvas keys, a canvas drag, the color value commit, a swatch, the alpha +input and its keys; no `igcChange` for a change back to the reported color or to a value from code; the events of the +inner elements stay inside. + +### Eye dropper + +A pick emits `igcInput` and `igcChange`. + +### Marker + +The marker moves to a value from code, and takes its place when a hidden panel shows. + +### Value text + +The angle and the hue name of the hue slider, the alpha percentage of the alpha slider, the color name in the value text +of the canvas marker and no name for an empty value, the numbers in the format of the locale, and the words and the +order from the resource strings. + +### Copy + +The check icon and "Copied" for one second after a copy, the error icon and "Copy failed" after a failure and without a +clipboard, the a11y audit in both states, the timer restarted by a second copy, only the result of the latest copy, no +result for a copy that ends after a disconnect, and the copy icon again after a disconnect. + +### Swatches + +The a11y audit with groups, the named listbox, the `swatches` property in front of the children, the names (label, +color name with alpha, "No color", the words and the locale of the panel, the color string of an invalid color, a new +name for a new color), the group name, the selected swatch with alpha, only the first of two +swatches with the same color selected, the `selected` part, the no-color swatch selected while empty, a `var()` swatch +resolved again when the panel shows, the events of a pick, a pick that clears, invalid colors and `var()` values, +swatches that the app adds and removes, and no list without swatches. + +### Swatch keyboard + +One tab stop, the arrows in reading order with the wrap, the swap in right-to-left, the rows up and down, a shorter +row, Home and End, Enter and Space as one change, no pick on an arrow, and the tab stop on a clicked swatch. + +### Views + +The a11y audit of both views, the gradient view with the list below it, the switcher for both views, the swatch view, a +switch with no events, the marker after a switch back, the first view for a view that `views` does not have, and +unknown tokens. + +### Contrast + +The a11y audit, no readout without `contrast-against`, the ratio and the AA and AAA marks with their parts, the +attribute, a color that the user commits, the alpha of the value and of `contrast-against`, no readout for an empty +value, an invalid color, an undefined `var()` or a `var()` that is not a color, `currentcolor`, `light-dark()` and a +`var()` resolved from the panel, a `var()` read again when the panel shows and when the theme changes, the readout at +the end of the panel in both views, and the strings and the number format of the locale. `contrast.spec.ts` covers the +ratio of known pairs, the alpha of both colors and the cut decimals; `contrast.property.spec.ts` covers the range from +1 to 21 and the same ratio for both orders of two opaque colors. + +### OKLCH area + +The a11y audit, the area and the marker at the lightness and chroma of the value, the OKLCH hue on the hue slider with +its value text, the cusp track and the cusp thumb, and back to HSV in `hex`; the marker name and value text with the +resource strings and the locale; a pick at the OKLCH hue with one `igcInput`; a pick beyond the gamut edge that keeps +the lightness, cuts the chroma and stops the marker, and a second one with no event; no event for +Arrow Right at the edge; a hue move that cuts the chroma and moves the marker; a gray that keeps its hue; +the hue of an HSV gray through the cusp on a format switch; and an empty value at white with the hue at 29. The color +picker suites cover the gamut runs, the blue spike, the cut-back, the cusps, the paint +(`oklch.spec.ts`, `oklch.property.spec.ts`), the OKLCH space of the model and the canvas of the OKLCH area. + +## Assumptions and limitations + +- The color model is sRGB. See the [color picker limitations](../color-picker/spec.md#assumptions-and-limitations). +- The eye dropper button is rendered enabled only where the platform implements the `EyeDropper` API. Support is + captured once, at construction time. +- Copying to the clipboard depends on the `navigator.clipboard` API and a secure context. Where it is unavailable or + denied, the copy button shows "Copy failed". +- Color names are approximate. The rule that picks the words is the same in all locales; only the words and their + order change. +- The panel has no `disabled` property. To make it inactive, set `inert` on it. +- A `var()` swatch reads its color again only at the times that [Swatches](#swatches) lists. A context color in + `contrast-against` reads its color again only at the times that [Contrast](#contrast) lists. +- The OKLCH area shows the sRGB gamut only; the model stays sRGB. At the hue of blue the black-to-blue edge is a thin + spike, a line 1 px wide. The out-of-gamut look is provisional until the design team gives one. +- A paint of the OKLCH area takes a few milliseconds, once per frame at most during a hue drag. +- The contrast readout gives the WCAG 2 ratio and the levels for normal text only. It has no levels for large text + (3:1 and 4.5:1), no APCA value and no contrast lines on the canvas. +- The selected mark of a swatch, the swatch focus ring, the group label, the view switcher and the contrast readout + use provisional styles until the design team gives them. +- In the Material, Fluent and Indigo themes the picker border color is transparent and the popup shows its edge with + an elevation. Alone in the page, the panel has no elevation, so it has no visible edge on a background of the same + color. Style `::part(base)` to add one. Bootstrap draws a border. + +## Accessibility + +### ARIA roles and properties + +- The host has no role. The controls inside have their own names. +- The hue and alpha sliders are native range inputs labelled through `aria-label`. Their `aria-valuetext` gives the + angle and the hue name, and the alpha percentage. +- The canvas marker is a `slider` with `aria-valuetext` for both axes and the color name. In the `oklch` format it is + named "Lightness and chroma". The painted OKLCH area is hidden from assistive technology. +- The format select and the color value input have visually hidden labels. +- The copy and eye dropper buttons expose visually hidden text. After a copy, the name of the copy button is "Copied" + or "Copy failed" for one second. +- The swatch list is a `listbox` named "Color swatches". Each swatch is an `option` with `aria-selected`, named by its + label or its color name. A swatch group is a `group` named by its label. The swatch mirrors its role and name onto + content attributes, so that tools that read only attributes, such as axe, see them. +- The contrast readout is plain text: the ratio and one mark for each level. Each mark says "pass" or "fail" in text, + so the result does not depend on the color of the mark. The readout has no live region, so a screen reader reads a + new ratio only when the user moves to it. +- The view switcher is a button group in single selection: a `radiogroup` of two `radio` buttons with + `aria-checked`. The texts of the buttons name the views. + +### Keyboard support + +Already covered by the [relevant section of the specification](#keyboard-interactions). + +### Right to Left support + +The sliders and the layout follow the document direction. The area does not mirror, so an +arrow key moves its marker in the direction of the arrow. In the swatch list, the order of the swatches follows the +direction, and Arrow Left and Arrow Right swap. diff --git a/src/components/color-panel/themes/color-panel.base.scss b/src/components/color-panel/themes/color-panel.base.scss new file mode 100644 index 000000000..9fa6e639b --- /dev/null +++ b/src/components/color-panel/themes/color-panel.base.scss @@ -0,0 +1,145 @@ +@use 'styles/utilities' as *; + +:host { + display: inline-block; + + // Keeps the z-index of the parts inside the component. + isolation: isolate; + + input[type='range'] { + appearance: none; + width: 100%; + } + + // The row track sizing and inline spacing are declared in the common styles, + // where the `--_picker-rows-*` custom properties the themes override live. + [part='main-row'], + [part='alpha-row'], + [part='inputs-row'] { + display: grid; + + &:empty { + display: none; + } + } + + [part='main-row'] { + margin-block-end: sizable(rem(8px), rem(12px), rem(16px)); + + input { + grid-column: 1 / span 2; + } + } + + [part='alpha-row'] { + margin-block: var(--_alpha-row-spacing); + + input { + grid-column: 1 / span 2; + } + } + + [part='alpha-input'] { + min-width: fit-content; + } + + [part='inputs-row'] { + padding-block-end: var(--_input-row-spacing); + + igc-input { + grid-column: 1 / -1; + } + + &:has(igc-select) { + igc-input { + grid-column: 2 / -1; + } + } + } + + [part='buttons'] { + display: flex; + } + + // The track and thumb presentation is declared in the common styles - each + // vendor pseudo-element needs its own rule there, since a selector list + // containing one the engine doesn't know is discarded whole. + [part='hue'], + [part='alpha'] { + grid-column: 1 / span 3; + } + + // Alone in the page, the panel has the size of the color picker popup. + [part~='base'] { + display: grid; + width: var(--_picker-popover-size); + + &:has([part~='alpha-row']:not(:empty)) { + [part='main-row'] { + margin-block-end: 0; + } + } + } + + [part='picker-canvas'] { + border-width: rem(1px); + border-style: solid; + margin-inline: rem(16px); + margin-block: rem(16px) sizable(rem(16px), rem(20px), rem(24px)); + } + + [part='swatches'] { + display: grid; + grid-column: 1 / -1; + width: 100%; + padding: var(--_swatches-spacing); + row-gap: var(--_swatches-row-gap); + justify-content: space-between; + overflow: hidden; + } + + // TODO: provisional spacing until the design team gives a view switcher. + [part~='view-switcher'] { + display: block; + margin: rem(16px) var(--_picker-rows-inline-spacing) 0; + } + + // The swatch view, under the view switcher. + [part~='view-switcher'] + [part~='swatches'] { + padding-block-start: rem(16px); + } + + // TODO: provisional until the design team gives a contrast readout. + [part~='contrast'] { + @include type-style('body-2'); + + display: flex; + flex-wrap: wrap; + align-items: center; + gap: rem(8px); + padding: 0 var(--_picker-rows-inline-spacing) rem(16px); + } + + [part~='contrast-ratio'] { + margin-inline-end: auto; + } + + [part~='contrast-mark'] { + padding-inline: rem(6px); + border: rem(1px) solid; + border-radius: rem(4px); + } +} + +@media (forced-colors: active) { + :host { + [part='picker-canvas'], + [part='hue']::-webkit-slider-runnable-track { + forced-color-adjust: none; + } + + [part='hue']::-webkit-slider-runnable-track { + outline: rem(1px) solid CanvasText; + } + } +} diff --git a/src/components/color-panel/themes/color-swatch-group.base.scss b/src/components/color-panel/themes/color-swatch-group.base.scss new file mode 100644 index 000000000..8008b8ae7 --- /dev/null +++ b/src/components/color-panel/themes/color-swatch-group.base.scss @@ -0,0 +1,17 @@ +@use 'styles/utilities' as *; + +// The group spans the swatch list, and its swatches take the columns of the +// list. +:host { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + row-gap: var(--_swatches-row-gap, #{rem(12px)}); +} + +[part~='label'] { + @include type-style('subtitle-2'); + + grid-column: 1 / -1; + margin: 0; +} diff --git a/src/components/color-panel/themes/color-swatch.base.scss b/src/components/color-panel/themes/color-swatch.base.scss new file mode 100644 index 000000000..d2b2b09ca --- /dev/null +++ b/src/components/color-panel/themes/color-swatch.base.scss @@ -0,0 +1,53 @@ +@use 'styles/utilities' as *; +@use 'components/color-picker/themes/swatch' as *; + +// A swatch takes the color picker theme variables from the color panel that +// shows it, so it has no theme of its own. +:host { + display: inline-block; + inline-size: var(--swatch-size); + block-size: var(--swatch-size); + border-radius: var(--swatch-border-radius); + cursor: pointer; + outline-offset: rem(1px); +} + +:host(:focus-visible) { + outline: rem(2px) solid var(--_swatch-focus-color); +} + +// The color fills the border box, under the border, as the swatch button did. +// The background color also holds the color that a `var()` resolves to. +[part~='base'] { + display: block; + block-size: 100%; + border: rem(1px) solid var(--swatch-border-color); + border-radius: inherit; + background-color: var(--_color); +} + +[part~='base'][data-empty] { + background-color: contrast-color('gray', 900); + background-image: empty-swatch-image(var(--invalid-color)); +} + +// TODO: a provisional mark until the design team gives one. +:host(:state(ig-selected)) [part~='base'] { + box-shadow: + inset 0 0 0 rem(2px) var(--picker-background), + inset 0 0 0 rem(3px) var(--swatch-border-color); +} + +@media (forced-colors: active) { + [part~='base'] { + forced-color-adjust: none; + } + + :host(:state(ig-selected)) { + outline: rem(2px) solid Highlight; + } + + :host(:focus-visible) { + outline-color: CanvasText; + } +} diff --git a/src/components/color-panel/themes/shared/color-panel.bootstrap.scss b/src/components/color-panel/themes/shared/color-panel.bootstrap.scss new file mode 100644 index 000000000..5909cbec8 --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.bootstrap.scss @@ -0,0 +1,12 @@ +@use 'styles/utilities' as *; + +:host { + --_picker-column-gap: #{sizable(rem(12px), rem(12px), rem(16px))}; + --_picker-buttons-gap: #{sizable(rem(8px), rem(4px), rem(4px))}; + --_swatches-spacing: #{sizable(rem(16px), rem(16px), rem(24px))} #{rem(16px)} #{rem(16px)} #{rem(16px)}; + --_picker-rows-grid-template-columns: #{minmax(auto, sizable(rem(174px), rem(190px), rem(212px))) 0 sizable(rem(72px), rem(80px), rem(100px))}; + + [part='inputs-row'] { + grid-template-columns: max(sizable(rem(96px), rem(104px), rem(120px))) 1fr; + } +} diff --git a/src/components/color-panel/themes/shared/color-panel.common.scss b/src/components/color-panel/themes/shared/color-panel.common.scss new file mode 100644 index 000000000..b5a4d326b --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.common.scss @@ -0,0 +1,196 @@ +@use 'styles/utilities' as *; +@use 'components/color-picker/themes/light/themes' as *; +@use 'components/color-picker/themes/swatch' as *; + +// The panel takes the color picker theme. +$theme: $material; + +@mixin slider-track { + height: var(--_slider-track-size); + border-radius: var-get($theme, 'slider-track-border-radius'); + + // Dont use border otherwise the thumb will be misaligned. + box-shadow: inset 0 0 0 rem(1px) var-get($theme, 'slider-track-border-color'); +} + +// `$fill` differs per slider: the hue thumb shows the pure hue it selects, the +// alpha thumb shows the color actually picked on the canvas. +@mixin slider-thumb($fill) { + // Resetting `appearance` on the input alone is not enough in Chromium - the + // thumb keeps its native rendering and ignores everything below until the + // pseudo-element itself opts out. + appearance: none; + border-radius: 50%; + width: var(--_slider-thumb-size); + height: var(--_slider-thumb-size); + background-color: $fill; + border: rem(2px) solid var-get($theme, 'slider-thumb-border-color'); + box-shadow: var(--ig-elevation-1); + + // This has to be explicitly set to avoid the thumb being clipped by the + // track. + box-sizing: border-box; + margin: 0; +} + +// Vendor pseudo-elements must never share a selector list: a list containing a +// pseudo-element the engine doesn't recognize is invalid as a whole, so pairing +// `::-moz-range-track,::-webkit-slider-runnable-track` makes Chrome drop the +// -webkit- half too. Each gets its own rule, emitted from here. +@mixin slider($thumb-fill) { + &::-webkit-slider-runnable-track { + @include slider-track(); + @content; + } + + &::-moz-range-track { + @include slider-track(); + @content; + } + + &::-webkit-slider-thumb { + @include slider-thumb($thumb-fill); + } + + &::-moz-range-thumb { + @include slider-thumb($thumb-fill); + } +} + +:host { + --component-size: var(--ig-size, #{var-get($theme, 'default-size')}); + --_picker-popover-size: #{sizable(rem(290px), rem(314px), rem(360px))}; + --_input-row-spacing: #{rem(16px)}; + --_alpha-row-spacing: #{sizable(rem(8px), rem(12px), rem(16px))}; + --_swatches-spacing: #{rem(16px)}; + --_swatches-row-gap: #{rem(12px)}; + --_picker-rows-grid-template-columns: #{sizable(rem(90px), rem(100px), rem(115px))} auto #{sizable(rem(62px), rem(72px), rem(88px))}; + --_picker-rows-inline-spacing: #{rem(16px)}; + --_picker-column-gap: #{sizable(rem(14px), rem(12px), rem(16px))}; + --_picker-buttons-gap: var(--_picker-column-gap); + + // Always a fully saturated hue - the component overwrites this on every + // update. Black would never be a valid value for it: it is the hue the + // saturation/value plane is built from, not a color that can be picked. + --_current-color: hsl(0deg 100% 50%); + --_slider-track-size: #{rem(16px)}; + --_slider-thumb-size: #{rem(16px)}; + + // The focus ring of a swatch, which takes it from the panel. + // TODO: provisional until the design team gives one. + --_swatch-focus-color: #{var-get($theme, 'anchor-outline-color')}; + --_transparency-grid: #{transparency-grid( + var-get($theme, 'transparency-grid-odd'), + var-get($theme, 'transparency-grid-even') + )}; + + // The gradients span the travel of the thumb center and follow the range + // direction, which is right to left in RTL. + --_slider-track-direction: to right; + --_slider-track-inset: calc(var(--_slider-thumb-size) / 2); + + // Pure hues at equal steps give `hsl(h 100% 50%)` at each point. + --_hue-slider-track: linear-gradient( + var(--_slider-track-direction), + #f00 var(--_slider-track-inset), + #ff0, #0f0, #0ff, #00f, #f0f, + #f00 calc(100% - var(--_slider-track-inset)) + ); + --_alpha-color: var(--_selected-color, var(--_current-color)); + --_alpha-slider-track: + linear-gradient( + var(--_slider-track-direction), + rgb(from var(--_alpha-color) r g b / 0%) var(--_slider-track-inset), + rgb(from var(--_alpha-color) r g b / 100%) calc(100% - var(--_slider-track-inset)) + ), + var(--_transparency-grid); + --_alpha-track-position: 0 0; + --_alpha-track-size: contain, var(--_slider-track-size) var(--_slider-track-size); + + input[type='range'] { + background: transparent; + cursor: pointer; + } + + [part='hue'] { + @include slider(var(--_current-color)) { + background: var(--_hue-slider-track); + } + } + + [part='alpha'] { + @include slider(var(--_alpha-color)) { + background-image: var(--_alpha-slider-track); + background-position: var(--_alpha-track-position); + background-size: var(--_alpha-track-size); + } + } + + [part='main-row'], + [part='alpha-row'], + [part='inputs-row'] { + padding-inline: var(--_picker-rows-inline-spacing); + column-gap: var(--_picker-column-gap); + } + + [part='main-row'], + [part='alpha-row'] { + grid-template-columns: var(--_picker-rows-grid-template-columns); + + input { + margin: 0; + } + } + + // Alone in the page, the panel paints the surface of the popup. + [part~='base'] { + background: var-get($theme, 'picker-background'); + border-radius: var-get($theme, 'picker-border-radius'); + border: rem(1px) solid var-get($theme, 'picker-border-color'); + + igc-divider { + --ig-divider-color: #{var-get($theme, 'swatch-separator-color')}; + + grid-column: 1 / -1; + } + + &:has([part~='swatches']:not([hidden])) { + --_input-row-spacing: #{sizable(rem(16px), rem(16px), rem(24px))}; + } + } + + [part='swatches'] { + grid-template-columns: repeat(8, var-get($theme, 'swatch-size')); + } + + // TODO: provisional until the design team gives a contrast readout. + [part~='contrast'] { + color: var-get($theme, 'label-color'); + } + + [part~='pass'] { + border-color: color('success', 500); + } + + [part~='fail'] { + border-color: color('error', 500); + } + + [part='picker-canvas'] { + border-color: var-get($theme, 'picker-canvas-border-color'); + border-radius: var-get($theme, 'picker-border-radius'); + + > igc-picker-canvas { + border-radius: calc(var-get($theme, 'picker-border-radius') - rem(1px)); + } + } + + [part='buttons'] { + column-gap: var(--_picker-buttons-gap); + } +} + +:host(:dir(rtl)), +:host([dir='rtl']) { + --_slider-track-direction: to left; +} diff --git a/src/components/color-panel/themes/shared/color-panel.fluent.scss b/src/components/color-panel/themes/shared/color-panel.fluent.scss new file mode 100644 index 000000000..c60281e0d --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.fluent.scss @@ -0,0 +1,17 @@ +@use 'styles/utilities' as *; + +:host { + --_picker-column-gap: #{sizable(rem(12px), rem(12px), rem(16px))}; + --_swatches-spacing: #{sizable(rem(16px), rem(16px), rem(24px)) rem(16px) rem(16px) rem(16px)}; + --_picker-buttons-gap: #{sizable(rem(12px), rem(4px), rem(4px))}; + --_picker-rows-grid-template-columns: #{1fr auto #{sizable(rem(60px), rem(68px), rem(80px))}}; + + igc-input::part(prefix), + igc-input::part(suffix) { + background: transparent !important; + } + + [part='inputs-row'] { + grid-template-columns: max(sizable(rem(96px), rem(104px), rem(112px))) 1fr; + } +} diff --git a/src/components/color-panel/themes/shared/color-panel.indigo.scss b/src/components/color-panel/themes/shared/color-panel.indigo.scss new file mode 100644 index 000000000..25069148f --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.indigo.scss @@ -0,0 +1,28 @@ +@use 'styles/utilities' as *; +@use 'components/color-picker/themes/light/themes' as *; + +$theme: $indigo; + +:host { + // The anchor outline is a faint tint in this theme. + --_swatch-focus-color: #{var-get($theme, 'label-color')}; + --_alpha-row-spacing: #{sizable(rem(8px), rem(12px), rem(16px))}; + --_picker-rows-grid-template-columns: #{minmax(auto, sizable(rem(190px), rem(210px), rem(244px))) 0 sizable(rem(56px), rem(60px), rem(68px))}; + --_swatches-row-gap: #{rem(12px)}; + --_picker-buttons-gap: #{sizable(rem(8px), rem(4px), rem(4px))}; + --_picker-column-gap: #{sizable(rem(12px), rem(12px), rem(16px))}; + + [part='inputs-row'] { + grid-template-columns: min(sizable(rem(96px), rem(104px), rem(112px))) 1fr; + } + + [part~='base'] { + &:has([part~='swatches']:not([hidden])) { + --_input-row-spacing: #{sizable(rem(20px), rem(24px), rem(28px))}; + } + } + + [part='swatches'] { + padding-block-start: 0; + } +} diff --git a/src/components/color-panel/themes/shared/color-panel.material.scss b/src/components/color-panel/themes/shared/color-panel.material.scss new file mode 100644 index 000000000..176860936 --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.material.scss @@ -0,0 +1,14 @@ +@use 'styles/utilities' as *; +@use 'components/color-picker/themes/light/themes' as *; + +$theme: $material; + +:host { + // The anchor outline is transparent in this theme. + --_swatch-focus-color: #{var-get($theme, 'label-color')}; + --_swatches-spacing: #{sizable(rem(16px), rem(16px), rem(24px)) rem(16px) rem(16px) rem(16px)}; + + [part='inputs-row'] { + grid-template-columns: max(sizable(rem(96px), rem(104px), rem(112px))) 1fr; + } +} diff --git a/src/components/color-panel/themes/themes.ts b/src/components/color-panel/themes/themes.ts new file mode 100644 index 000000000..ff0faeb38 --- /dev/null +++ b/src/components/color-panel/themes/themes.ts @@ -0,0 +1,34 @@ +import type { ComponentThemes } from '#theming/types.js'; +// The color picker theme variables. The panel takes the color picker theme. +import { styles as bootstrapDark } from '../../color-picker/themes/dark/color-picker.bootstrap.css.js'; +import { styles as fluentDark } from '../../color-picker/themes/dark/color-picker.fluent.css.js'; +import { styles as indigoDark } from '../../color-picker/themes/dark/color-picker.indigo.css.js'; +import { styles as materialDark } from '../../color-picker/themes/dark/color-picker.material.css.js'; +import { styles as bootstrapLight } from '../../color-picker/themes/light/color-picker.bootstrap.css.js'; +import { styles as fluentLight } from '../../color-picker/themes/light/color-picker.fluent.css.js'; +import { styles as indigoLight } from '../../color-picker/themes/light/color-picker.indigo.css.js'; +import { styles as materialLight } from '../../color-picker/themes/light/color-picker.material.css.js'; +import { styles as shared } from '../../color-picker/themes/light/color-picker.shared.css.js'; +// Shared Styles +import { styles as bootstrap } from './shared/color-panel.bootstrap.css.js'; +import { styles as fluent } from './shared/color-panel.fluent.css.js'; +import { styles as indigo } from './shared/color-panel.indigo.css.js'; +import { styles as material } from './shared/color-panel.material.css.js'; + +const light = { + shared, + bootstrap: [bootstrap, bootstrapLight], + material: [material, materialLight], + fluent: [fluent, fluentLight], + indigo: [indigo, indigoLight], +}; + +const dark = { + shared, + bootstrap: [bootstrap, bootstrapLight, bootstrapDark], + material: [material, materialLight, materialDark], + fluent: [fluent, fluentLight, fluentDark], + indigo: [indigo, indigoLight, indigoDark], +}; + +export const all: ComponentThemes = { light, dark }; diff --git a/src/components/color-picker/color-name.property.spec.ts b/src/components/color-picker/color-name.property.spec.ts new file mode 100644 index 000000000..ed3919c16 --- /dev/null +++ b/src/components/color-picker/color-name.property.spec.ts @@ -0,0 +1,70 @@ +import { expect } from '@open-wc/testing'; + +import { fc } from '#internals/testing/fast-check-setup.spec.js'; +import { formatColorName } from './color-name.js'; +import type { RGB } from './converters.js'; +import { type ColorPickerStrings, colorPickerI18nConfig } from './i18n.js'; + +const strings = colorPickerI18nConfig.defaultEN as ColorPickerStrings; + +const byte = fc.integer({ min: 0, max: 255 }); +const rgb = fc.tuple(byte, byte, byte); + +const LIGHTNESS = ['very dark', 'dark', 'light', 'very light']; +const CHROMA = ['grayish', 'vibrant']; +const HUES = [ + 'red', + 'orange', + 'brown', + 'yellow', + 'yellow green', + 'green', + 'cyan', + 'blue', + 'purple', + 'magenta', + 'pink', + 'black', + 'white', + 'gray', +]; + +const any = (words: string[]) => `(?:${words.join('|')})`; + +/** The word orders of English, French and Japanese, and the names they allow. */ +const ORDERS: [pattern: string, name: RegExp][] = [ + [ + '{0} {1} {2}', + new RegExp(`^(?:${any(LIGHTNESS)} )?(?:${any(CHROMA)} )?${any(HUES)}$`), + ], + [ + '{2} {0} {1}', + new RegExp(`^${any(HUES)}(?: ${any(LIGHTNESS)})?(?: ${any(CHROMA)})?$`), + ], + ['{0}{1}{2}', new RegExp(`^${any(LIGHTNESS)}?${any(CHROMA)}?${any(HUES)}$`)], +]; + +describe('Color name properties', () => { + it('names every 8-bit color with the words in the order of the pattern', () => { + fc.assert( + fc.property(rgb, fc.constantFrom(...ORDERS), (color, [pattern, name]) => { + expect( + formatColorName(color as RGB, { + ...strings, + color_picker_name_pattern: pattern, + }) + ).to.match(name); + }) + ); + }); + + it('names a color with equal channels black, white or a gray', () => { + fc.assert( + fc.property(byte, (channel) => { + expect(formatColorName([channel, channel, channel], strings)).to.match( + /^(?:(?:very )?(?:dark|light) )?gray$|^black$|^white$/ + ); + }) + ); + }); +}); diff --git a/src/components/color-picker/color-name.spec.ts b/src/components/color-picker/color-name.spec.ts new file mode 100644 index 000000000..c89241af7 --- /dev/null +++ b/src/components/color-picker/color-name.spec.ts @@ -0,0 +1,117 @@ +import { expect } from '@open-wc/testing'; + +import { + type ColorNameParts, + colorNameParts, + formatOklchAreaValue, + pureHueWord, +} from './color-name.js'; +import type { RGB } from './converters.js'; +import { type ColorPickerStrings, colorPickerI18nConfig } from './i18n.js'; +import { ColorModel } from './model.js'; + +function hex(value: string): RGB { + return ColorModel.parse(value).toRGB(); +} + +function words({ lightness, chroma, hue }: ColorNameParts): string { + return [lightness, chroma, hue].filter(Boolean).join(' '); +} + +describe('Color names', () => { + it('names the colors with no hue by lightness', () => { + const names = [ + '#000000', + '#222222', + '#696969', + '#808080', + '#c0c0c0', + '#dcdcdc', + '#ffffff', + ].map((color) => words(colorNameParts(hex(color)))); + + expect(names).to.eql([ + 'black', + 'very_dark gray', + 'dark gray', + 'gray', + 'light gray', + 'very_light gray', + 'white', + ]); + }); + + it('gives the pure colors no lightness word', () => { + const names = [ + '#ff0000', + '#ffff00', + '#00ff00', + '#00ffff', + '#0000ff', + '#ff00ff', + ].map((color) => words(colorNameParts(hex(color)))); + + expect(names).to.eql([ + 'vibrant red', + 'vibrant yellow', + 'vibrant green', + 'vibrant cyan', + 'vibrant blue', + 'vibrant magenta', + ]); + }); + + it('compares the lightness with the most chromatic color of the hue', () => { + // Pure yellow is far lighter than pure blue, and neither is "light". + expect(words(colorNameParts(hex('#000080')))).to.equal('dark blue'); + expect(words(colorNameParts(hex('#0000aa')))).to.equal('dark vibrant blue'); + expect(words(colorNameParts(hex('#808000')))).to.equal('dark yellow'); + expect(words(colorNameParts(hex('#6495ed')))).to.equal('light blue'); + expect(words(colorNameParts(hex('#e6e6fa')))).to.equal('very_light blue'); + }); + + it('names a color with little chroma grayish', () => { + expect(words(colorNameParts(hex('#708090')))).to.equal('grayish blue'); + expect(words(colorNameParts(hex('#8fbc8f')))).to.equal('grayish green'); + }); + + it('names a dark orange brown and a very light red pink', () => { + expect(words(colorNameParts(hex('#d2691e')))).to.equal('brown'); + expect(words(colorNameParts(hex('#8b4513')))).to.equal('dark brown'); + expect(words(colorNameParts(hex('#ffa500')))).to.equal('vibrant orange'); + expect(words(colorNameParts(hex('#ffe4e1')))).to.equal('very_light pink'); + expect(words(colorNameParts(hex('#ff69b4')))).to.equal('vibrant pink'); + }); + + it('names the hue of the pure color of an HSV hue', () => { + const hues = [0, 30, 60, 90, 120, 180, 210, 240, 270, 300, 330, 360]; + + expect(hues.map(pureHueWord)).to.eql([ + 'red', + 'orange', + 'yellow', + 'yellow_green', + 'green', + 'cyan', + 'blue', + 'blue', + 'purple', + 'magenta', + 'pink', + 'red', + ]); + }); +}); + +describe('OKLCH area value text', () => { + const resourceStrings = colorPickerI18nConfig.defaultEN as ColorPickerStrings; + + it('gives the lightness and the chroma in the number format of the locale', () => { + expect( + formatOklchAreaValue(70.4, 0.32162, { resourceStrings, locale: 'en' }) + ).to.equal('Lightness 70%, chroma 0.322'); + expect( + formatOklchAreaValue(70.4, 0.32162, { resourceStrings, locale: 'ar-EG' }) + ).to.equal('Lightness ٧٠%, chroma ٠٫٣٢٢'); + }); +}); diff --git a/src/components/color-picker/color-name.ts b/src/components/color-picker/color-name.ts new file mode 100644 index 000000000..8cc66afc4 --- /dev/null +++ b/src/components/color-picker/color-name.ts @@ -0,0 +1,221 @@ +import { getNumberFormatter } from 'igniteui-i18n-core'; +import { formatString } from '#internals/utils/strings.js'; +import { converter, type RGB } from './converters.js'; +import type { ColorPickerI18n, ColorPickerStrings } from './i18n.js'; +import type { ColorModel } from './model.js'; +import { type AreaSpace, cusp, pureHueOklch } from './oklch.js'; + +type ColorLightnessWord = 'very_dark' | 'dark' | 'light' | 'very_light'; + +type ColorChromaWord = 'grayish' | 'vibrant'; + +type ColorHueWord = + | 'red' + | 'orange' + | 'brown' + | 'yellow' + | 'yellow_green' + | 'green' + | 'cyan' + | 'blue' + | 'purple' + | 'magenta' + | 'pink' + | 'black' + | 'white' + | 'gray'; + +type ColorNameWord = ColorLightnessWord | ColorChromaWord | ColorHueWord; + +/** The words of a color name. Only the hue word is always there. */ +export interface ColorNameParts { + lightness?: ColorLightnessWord; + chroma?: ColorChromaWord; + hue: ColorHueWord; +} + +/** The OKLCH hue where each hue word ends. Above 345 the hue is pink. */ +const HUE_WORDS: ReadonlyArray = [ + [20, 'pink'], + [42, 'red'], + [80, 'orange'], + [115, 'yellow'], + [138, 'yellow_green'], + [165, 'green'], + [210, 'cyan'], + [290, 'blue'], + [325, 'purple'], + [345, 'magenta'], +]; + +/** Below this OKLCH chroma, a color has no hue. */ +const ACHROMATIC_CHROMA = 0.02; + +/** The lightness word limits of a gray (OKLCH lightness 0-100). */ +const GRAY_LIMITS = [30, 55, 70, 85] as const; + +/** The lightness word limits of a color, from -1 (black) to 1 (white) around the cusp. */ +const SHADE_LIMITS = [-0.6, -0.25, 0.25, 0.6] as const; + +function hueWord(oklchHue: number): ColorHueWord { + return HUE_WORDS.find(([end]) => oklchHue < end)?.[1] ?? 'pink'; +} + +function lightnessWord( + value: number, + [veryDark, dark, light, veryLight]: readonly number[] +): ColorLightnessWord | undefined { + if (value < veryDark) return 'very_dark'; + if (value < dark) return 'dark'; + if (value > veryLight) return 'very_light'; + if (value > light) return 'light'; + return undefined; +} + +/** + * The words that name an sRGB color. Lightness and chroma compare with the + * most chromatic color of the hue, so pure yellow and pure blue are not light + * or dark. + */ +export function colorNameParts(rgb: RGB): ColorNameParts { + const [lightness, chroma, hue] = converter.rgb.oklch(rgb); + + if (chroma < ACHROMATIC_CHROMA) { + if (lightness < 18) return { hue: 'black' }; + if (lightness > 97) return { hue: 'white' }; + return { lightness: lightnessWord(lightness, GRAY_LIMITS), hue: 'gray' }; + } + + const [cuspLightness, cuspChroma] = cusp(hue); + const darker = lightness < cuspLightness; + const shade = darker + ? lightness / cuspLightness - 1 + : (lightness - cuspLightness) / (100 - cuspLightness); + // An estimate of the most chroma of sRGB at this lightness: the sRGB slice of + // a hue is close to a triangle of black, white and the cusp. + const maxChroma = + cuspChroma * + (darker + ? lightness / cuspLightness + : (100 - lightness) / (100 - cuspLightness)); + const saturation = chroma / maxChroma; + + const parts: ColorNameParts = { + lightness: lightnessWord(shade, SHADE_LIMITS), + hue: hueWord(hue), + }; + + if (saturation < 0.4) { + parts.chroma = 'grayish'; + } else if (saturation > 0.75 && chroma > 0.7 * cuspChroma) { + parts.chroma = 'vibrant'; + } + + // Brown is a dark orange and is never vibrant. Pink is a very light red. + if (parts.hue === 'orange' && lightness < 65) { + parts.hue = 'brown'; + parts.chroma = parts.chroma === 'vibrant' ? undefined : parts.chroma; + } else if (parts.hue === 'red' && parts.lightness === 'very_light') { + parts.hue = 'pink'; + } + + return parts; +} + +/** The hue word of the pure color of an HSV hue, for the hue slider. */ +export function pureHueWord(hsvHue: number): ColorHueWord { + return hueWord(pureHueOklch(hsvHue)[2]); +} + +function word(strings: ColorPickerStrings, token?: ColorNameWord): string { + return token ? strings[`color_picker_name_${token}`] : ''; +} + +/** The localized name of an sRGB color, such as "dark vibrant blue". */ +export function formatColorName(rgb: RGB, strings: ColorPickerStrings): string { + const { lightness, chroma, hue } = colorNameParts(rgb); + + return formatString( + strings.color_picker_name_pattern, + word(strings, lightness), + word(strings, chroma), + word(strings, hue) + ) + .replace(/\s+/g, ' ') + .trim(); +} + +/** A share (0-1) as a percentage in the number format of the locale. */ +export function formatPercent(share: number, locale: string): string { + return getNumberFormatter().formatNumber(share, locale, { style: 'percent' }); +} + +/** The name of a swatch color, with its alpha when it is not opaque. */ +export function formatSwatchName( + color: ColorModel, + { resourceStrings, locale }: ColorPickerI18n +): string { + const name = formatColorName(color.toRGB(), resourceStrings); + + return color.alpha < 1 + ? formatString( + resourceStrings.color_picker_name_with_alpha, + name, + formatPercent(color.alpha, locale) + ) + : name; +} + +/** A value text and a color name, such as "120 degrees, green". */ +export function formatValueWithName( + value: string, + name: string, + strings: ColorPickerStrings +): string { + return formatString(strings.color_picker_value_with_name, value, name); +} + +/** + * The value text of the hue slider: the angle and the name of the hue. `hue` + * is an HSV or an OKLCH hue, as `space` says. An HSV hue takes the name of its + * pure color. + */ +export function formatHueValue( + hue: number, + { resourceStrings, locale }: ColorPickerI18n, + space: AreaSpace +): string { + const angle = getNumberFormatter().formatNumber(hue, locale, { + style: 'unit', + unit: 'degree', + unitDisplay: 'long', + }); + const name = space === 'oklch' ? hueWord(hue) : pureHueWord(hue); + + return formatValueWithName( + angle, + word(resourceStrings, name), + resourceStrings + ); +} + +/** + * The value text of the OKLCH area: the lightness in whole percent and the + * chroma with 3 decimals, in the number format of the locale. + */ +export function formatOklchAreaValue( + lightness: number, + chroma: number, + { resourceStrings, locale }: ColorPickerI18n +): string { + const formatter = getNumberFormatter(); + + return formatString( + resourceStrings.color_picker_canvas_oklch_value, + formatter.formatNumber(Math.round(lightness), locale), + formatter.formatNumber(chroma, locale, { + minimumFractionDigits: 3, + maximumFractionDigits: 3, + }) + ); +} diff --git a/src/components/color-picker/color-picker.spec.ts b/src/components/color-picker/color-picker.spec.ts index 9aff60a01..da13b19d9 100644 --- a/src/components/color-picker/color-picker.spec.ts +++ b/src/components/color-picker/color-picker.spec.ts @@ -5,6 +5,7 @@ import { html, nextFrame, } from '@open-wc/testing'; +import { sendMouse } from '@web/test-runner-commands'; import { ColorPickerResourceStringsEN, type IColorPickerResourceStrings, @@ -12,14 +13,17 @@ import { setCurrentI18n, } from 'igniteui-i18n-core'; import { ColorPickerResourceStringsBG } from 'igniteui-i18n-resources'; -import { spy, stub } from 'sinon'; +import { type SinonSpy, spy, stub } from 'sinon'; +import { internalsOf } from '#internals/controllers/internals.js'; import { altKey, arrowDown, arrowRight, arrowUp, endKey, + enterKey, escapeKey, + spaceBar, } from '#internals/controllers/key-bindings.js'; import { defineComponents } from '#internals/definitions/defineComponents.js'; import { runDisabledPopupTests } from '#internals/testing/disabled-popup.spec.js'; @@ -30,6 +34,7 @@ import { runExternalLabelAssociationTests, } from '#internals/testing/form-testbed.spec.js'; import { + axeHiddenLabelOptions, isFocused, isUnderPageLayer, withDocumentSheets, @@ -51,6 +56,8 @@ import { isUserChange } from '#internals/user-change.js'; import { formatString } from '#internals/utils/strings.js'; import { configureTheme } from '#theming/config.js'; import { styles as bootstrap } from '../../styles/themes/light/bootstrap.css.js'; +import type IgcColorPanelComponent from '../color-panel/color-panel.js'; +import type IgcColorSwatchComponent from '../color-panel/color-swatch.js'; import type IgcInputComponent from '../input/input.js'; import type IgcSelectComponent from '../select/select.js'; import IgcColorPickerComponent from './color-picker.js'; @@ -67,6 +74,18 @@ function getAnchor(picker: IgcColorPickerComponent): HTMLElement { return picker.renderRoot.querySelector('[part~="anchor"]')!; } +/** The color panel that the picker shows in its popup. */ +function getPanel(picker: IgcColorPickerComponent): IgcColorPanelComponent { + return picker.renderRoot.querySelector('igc-color-panel')!; +} + +/** The shadow root of the color panel, which holds the picker controls. */ +function getPanelRoot( + picker: IgcColorPickerComponent +): HTMLElement | DocumentFragment { + return getPanel(picker).renderRoot; +} + /** Picks `color` from a swatch, as the user does. */ async function pickSwatch( picker: IgcColorPickerComponent, @@ -75,11 +94,16 @@ async function pickSwatch( picker.swatches = [color]; await elementUpdated(picker); simulateClick( - picker.renderRoot.querySelector('button[part="swatch"]')! + getPanelRoot(picker).querySelector('[part~="swatch"]')! ); await elementUpdated(picker); } +/** The text field of the input mode anchor. */ +function getAnchorField(picker: IgcColorPickerComponent): IgcInputComponent { + return picker.renderRoot.querySelector('igc-input[slot="anchor"]')!; +} + /** The native input of the input mode anchor, which the ARIA projection targets. */ function getAnchorNativeInput(host: HTMLElement): HTMLInputElement { return (host as IgcColorPickerComponent).renderRoot @@ -92,7 +116,7 @@ function isAnchorEmpty(picker: IgcColorPickerComponent): boolean { } function getColorInput(picker: IgcColorPickerComponent): IgcInputComponent { - return picker.renderRoot.querySelector('#color-input')!; + return getPanelRoot(picker).querySelector('#color-input')!; } function commitColorInput(input: IgcInputComponent, value: string): void { @@ -107,15 +131,15 @@ function commitColorInput(input: IgcInputComponent, value: string): void { } function getHueSlider(picker: IgcColorPickerComponent): HTMLInputElement { - return picker.renderRoot.querySelector('[part="hue"]')!; + return getPanelRoot(picker).querySelector('[part="hue"]')!; } function getAlphaSlider(picker: IgcColorPickerComponent): HTMLInputElement { - return picker.renderRoot.querySelector('[part="alpha"]')!; + return getPanelRoot(picker).querySelector('[part="alpha"]')!; } function getAlphaInput(picker: IgcColorPickerComponent): IgcInputComponent { - return picker.renderRoot.querySelector('#alpha')!; + return getPanelRoot(picker).querySelector('#alpha')!; } function getAlphaEditor(picker: IgcColorPickerComponent): HTMLInputElement { @@ -163,11 +187,11 @@ function press(node: Element, key: string): KeyboardEvent { } function getCanvas(picker: IgcColorPickerComponent): IgcPickerCanvasComponent { - return picker.renderRoot.querySelector('igc-picker-canvas')!; + return getPanelRoot(picker).querySelector('igc-picker-canvas')!; } function getFormatSelect(picker: IgcColorPickerComponent): IgcSelectComponent { - return picker.renderRoot.querySelector('#format-select')!; + return getPanelRoot(picker).querySelector('#format-select')!; } /** The opaque half and the translucent whole of the anchor swatch preview. */ @@ -213,7 +237,7 @@ async function expectSliderTracks( function getLabels(picker: IgcColorPickerComponent) { const root = picker.renderRoot; const text = (selector: string) => - root.querySelector(selector)!.textContent!.trim(); + getPanelRoot(picker).querySelector(selector)!.textContent!.trim(); const marker = getCanvas(picker).renderRoot.querySelector('[part~="marker"]')!; @@ -377,9 +401,9 @@ describe('Color picker', () => { picker.open = true; await elementUpdated(picker); - expect(picker.style.getPropertyValue('--_current-color')).to.equal( - 'hsl(0 100% 50%)' - ); + expect( + getPanel(picker).style.getPropertyValue('--_current-color') + ).to.equal('hsl(0 100% 50%)'); expect(getCanvas(picker).currentColor).to.equal('hsl(0 100% 50%)'); expect(getHueSlider(picker).value).to.equal('0'); }); @@ -389,9 +413,9 @@ describe('Color picker', () => { await elementUpdated(picker); // An empty color is white, not the pure hue of the plane. - expect(picker.style.getPropertyValue('--_selected-color')).to.equal( - 'rgb(255 255 255)' - ); + expect( + getPanel(picker).style.getPropertyValue('--_selected-color') + ).to.equal('rgb(255 255 255)'); expect(getCanvas(picker).markerColor).to.equal('rgb(255 255 255)'); }); @@ -422,7 +446,7 @@ describe('Color picker', () => { // Not a `spinbutton`: that role breaks how screen readers announce typing. // The alpha slider carries the range semantics. const editor = getAlphaEditor(picker); - const label = picker.renderRoot.querySelector('label[for="alpha"]')!; + const label = getPanelRoot(picker).querySelector('label[for="alpha"]')!; expect(editor.role).to.be.null; expect(editor.getAttribute('aria-valuenow')).to.be.null; @@ -489,7 +513,7 @@ describe('Color picker', () => { it('labels the color value input', async () => { const label = () => - picker.renderRoot + getPanelRoot(picker) .querySelector('label[for="color-input"]')! .textContent!.trim(); @@ -594,6 +618,67 @@ describe('Color picker', () => { expect(isAnchorEmpty(picker)).to.be.true; } }); + + it('clears the value for a color that depends on its context', async () => { + for (const value of ['currentcolor', 'var(--brand)', 'Canvas']) { + picker.value = '#ff0000'; + await elementUpdated(picker); + + picker.value = value; + await elementUpdated(picker); + + expect(picker.value, value).to.equal(''); + expect(isAnchorEmpty(picker), value).to.be.true; + } + }); + }); + + describe('Colors outside the legacy syntax', () => { + beforeEach(async () => { + picker = await createDefaultColorPicker(); + }); + + it('writes an oklch() value in the active format', async () => { + picker.value = 'oklch(70% 0.1 200)'; + await elementUpdated(picker); + + expect(picker.value).to.equal('#40b1b7'); + + picker.format = 'rgb'; + await elementUpdated(picker); + + expect(picker.value).to.equal('rgb(64 177 183)'); + }); + + it('clips a color outside the sRGB gamut', async () => { + picker.value = 'color(display-p3 1 0 0)'; + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + }); + + it('commits a typed lab() color', async () => { + picker.open = true; + await elementUpdated(picker); + + commitColorInput(getColorInput(picker), 'lab(50% 40 30)'); + await elementUpdated(picker); + + expect(picker.value).to.equal('#bb5846'); + }); + + it('reverts a typed color that depends on its context', async () => { + picker.value = '#ff0000'; + picker.open = true; + await elementUpdated(picker); + + const input = getColorInput(picker); + commitColorInput(input, 'currentcolor'); + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + expect(input.value).to.equal('#ff0000'); + }); }); describe('Color value input', () => { @@ -1161,19 +1246,25 @@ describe('Color picker', () => { }); it('does not render swatches by default', () => { - expect(picker.renderRoot.querySelector('[part="swatches"]')).to.be.null; + expect( + getPanelRoot(picker).querySelector('[part="swatches"]') + ?.hidden + ).to.be.true; }); it('renders and selects a swatch', async () => { picker.swatches = ['#ff0000', '#00ff00']; await elementUpdated(picker); - const buttons = picker.renderRoot.querySelectorAll( - 'button[part="swatch"]' - ); + const buttons = + getPanelRoot(picker).querySelectorAll( + '[part~="swatch"]' + ); expect(buttons.length).to.equal(2); - expect(buttons[0].ariaLabel).to.equal('#ff0000'); - expect(buttons[0].dataset.color).to.equal('#ff0000'); + expect(internalsOf(buttons[0])?.getARIA('ariaLabel')).to.equal( + 'vibrant red' + ); + expect(buttons[0].color).to.equal('#ff0000'); const inputSpy = spy(picker, 'emitEvent'); buttons[1].click(); @@ -1187,12 +1278,13 @@ describe('Color picker', () => { picker.swatches = ['#ff0000', '#00ff00']; await elementUpdated(picker); - const buttons = picker.renderRoot.querySelectorAll( - 'button[part="swatch"]' - ); + const buttons = + getPanelRoot(picker).querySelectorAll( + '[part~="swatch"]' + ); - // The color comes from `data-color`, so the label does not change it. - buttons[1].ariaLabel = 'Vert'; + // The color comes from `color`, so the label does not change it. + buttons[1].label = 'Vert'; buttons[1].click(); await elementUpdated(picker); @@ -1207,8 +1299,8 @@ describe('Color picker', () => { picker.disabled = true; await elementUpdated(picker); - picker.renderRoot - .querySelector('button[part="swatch"]')! + getPanelRoot(picker) + .querySelector('[part~="swatch"]')! .click(); await elementUpdated(picker); @@ -1228,7 +1320,9 @@ describe('Color picker', () => { it('copies the value to the clipboard', async () => { const writeText = stub(navigator.clipboard, 'writeText').resolves(); - picker.renderRoot.querySelector('[part="copy"]')!.click(); + simulateClick( + getPanelRoot(picker).querySelector('[part="copy"]')! + ); expect(writeText).calledWith('#ff0000'); writeText.restore(); @@ -1249,7 +1343,9 @@ describe('Color picker', () => { it('disables the eye dropper button', async () => { picker = await createDefaultColorPicker(); - const button = picker.renderRoot.querySelector('[part="eye-dropper"]')!; + const button = getPanelRoot(picker).querySelector( + '[part="eye-dropper"]' + )!; expect(button.hasAttribute('disabled')).to.be.true; }); }); @@ -1273,7 +1369,7 @@ describe('Color picker', () => { it('picks a color via the EyeDropper API', async () => { picker = await createDefaultColorPicker(); - const button = picker.renderRoot.querySelector( + const button = getPanelRoot(picker).querySelector( '[part="eye-dropper"]' )!; expect(button.hasAttribute('disabled')).to.be.false; @@ -1291,7 +1387,7 @@ describe('Color picker', () => { const { value } = picker; const eventSpy = spy(picker, 'emitEvent'); - picker.renderRoot + getPanelRoot(picker) .querySelector('[part="eye-dropper"]')! .click(); picker.disabled = true; @@ -1301,6 +1397,38 @@ describe('Color picker', () => { expect(picker.value).to.equal(value); expect(eventSpy).not.calledWith('igcInput'); }); + + describe('in the confirm mode', () => { + beforeEach(async () => { + picker = await fixture( + html`` + ); + simulateClick( + getPanelRoot(picker).querySelector('[part~="eye-dropper"]')! + ); + }); + + it('takes a pick into the draft', async () => { + await new Promise((resolve) => setTimeout(resolve)); + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#112233'); + }); + + it('ignores a pick that ends after the popup closes', async () => { + picker.open = false; + await new Promise((resolve) => setTimeout(resolve)); + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#ff0000'); + }); + }); }); }); @@ -1378,11 +1506,344 @@ describe('Color picker', () => { }); }); + describe('Confirm mode', () => { + beforeEach(async () => { + picker = await fixture( + html`` + ); + }); + + function getPart(name: string): HTMLElement { + return picker.renderRoot.querySelector(`[part~="${name}"]`)!; + } + + function valueEvents(eventSpy: SinonSpy): string[] { + return eventSpy + .getCalls() + .map((call) => call.args[0]) + .filter((name) => name === 'igcInput' || name === 'igcChange'); + } + + it('is accessible', async () => { + await expect(picker).shadowDom.to.be.accessible(axeHiddenLabelOptions); + await expect(picker).lightDom.to.be.accessible(axeHiddenLabelOptions); + }); + + it('shows the preview, Cancel and Apply only in the confirm mode', async () => { + expect(getPart('footer').hidden).to.be.false; + expect(getPart('preview-initial').getAttribute('aria-label')).to.equal( + 'Initial color' + ); + expect(getPart('cancel-button').textContent!.trim()).to.equal('Cancel'); + expect(getPart('apply-button').textContent!.trim()).to.equal('Apply'); + + picker.selectionCommit = 'immediate'; + await elementUpdated(picker); + + expect(getPart('footer').hidden).to.be.true; + expect(getPart('actions')).to.be.null; + }); + + it('shows the content of the footer slot in both modes', async () => { + const content = document.createElement('a'); + content.slot = 'footer'; + content.href = '#'; + content.textContent = 'More colors'; + + picker.selectionCommit = 'immediate'; + picker.append(content); + await elementUpdated(picker); + + expect(getPart('footer').hidden).to.be.false; + expect(content.assignedSlot?.name).to.equal('footer'); + }); + + it('keeps a change in the popup as a draft', async () => { + const eventSpy = spy(picker, 'emitEvent'); + + await pickSwatch(picker, '#00ff00'); + + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#00ff00'); + expect(getAnchorPreview(picker).alpha).to.equal('rgb(255 0 0 / 1)'); + expect( + getPart('preview-initial').style.getPropertyValue('--_alpha-preview') + ).to.equal('rgb(255 0 0 / 1)'); + expect( + getPart('preview-current').style.getPropertyValue('--_alpha-preview') + ).to.equal('rgb(0 255 0 / 1)'); + expect(valueEvents(eventSpy)).to.be.empty; + }); + + it('applies the draft with one igcChange and closes', async () => { + await pickSwatch(picker, '#00ff00'); + const eventSpy = spy(picker, 'emitEvent'); + + simulateClick(getPart('apply-button')); + await elementUpdated(picker); + + expect(picker.value).to.equal('#00ff00'); + expect(picker.open).to.be.false; + expect(isFocused(getAnchor(picker))).to.be.true; + expect(valueEvents(eventSpy)).to.eql(['igcChange']); + expect(eventSpy).calledWith('igcChange', { detail: '#00ff00' }); + + // The focus leaves after the report. + picker.blur(); + expect(valueEvents(eventSpy)).to.eql(['igcChange']); + }); + + it('emits no igcChange for an Apply without a change', async () => { + const eventSpy = spy(picker, 'emitEvent'); + + simulateClick(getPart('apply-button')); + await elementUpdated(picker); + + expect(picker.open).to.be.false; + expect(valueEvents(eventSpy)).to.be.empty; + }); + + for (const [name, close] of [ + ['Cancel', () => simulateClick(getPart('cancel-button'))], + ['Escape', () => simulateKeyboard(picker, escapeKey)], + ['Alt + Arrow Up', () => simulateKeyboard(picker, [altKey, arrowUp])], + ['an outside click', () => simulateClick(document.body)], + [ + 'a scroll close', + async () => { + picker.scrollStrategy = 'close'; + await elementUpdated(picker); + await simulateScroll(picker.parentElement!, { top: 0 }); + }, + ], + ['hide()', () => picker.hide()], + [ + 'open = false', + () => { + picker.open = false; + }, + ], + [ + 'disabling', + () => { + picker.disabled = true; + }, + ], + ] as const) { + it(`drops the draft on ${name}`, async () => { + const eventSpy = spy(picker, 'emitEvent'); + + await pickSwatch(picker, '#00ff00'); + await close(); + await elementUpdated(picker); + + expect(picker.open).to.be.false; + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#ff0000'); + expect(valueEvents(eventSpy)).to.be.empty; + }); + } + + it('keeps the draft on Cancel, and applies it on Apply, when the app cancels the close', async () => { + picker.addEventListener('igcClosing', (event) => event.preventDefault()); + await pickSwatch(picker, '#00ff00'); + + simulateClick(getPart('cancel-button')); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(getPanel(picker).value).to.equal('#00ff00'); + + simulateClick(getPart('apply-button')); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(picker.value).to.equal('#00ff00'); + }); + + it('shows the value in the text field of the input mode', async () => { + picker.mode = 'input'; + await elementUpdated(picker); + await pickSwatch(picker, '#00ff00'); + + expect(getAnchorField(picker).value).to.equal('#ff0000'); + expect(getAnchorPreview(picker).alpha).to.equal('rgb(255 0 0 / 1)'); + }); + + it('shows the contrast of the draft', async () => { + picker.contrastAgainst = 'white'; + await pickSwatch(picker, '#000000'); + + const ratio = getPanelRoot(picker).querySelector( + '[part="contrast-ratio"]' + ); + + expect(picker.value).to.equal('#ff0000'); + expect(ratio?.textContent).to.equal('Contrast 21:1'); + }); + + it('takes an alpha commit into the draft', async () => { + picker.showAlpha = true; + picker.format = 'rgb'; + await elementUpdated(picker); + const eventSpy = spy(picker, 'emitEvent'); + + clearAlpha(picker); + typeIntoAlpha(picker, '40'); + commitColorInput(getAlphaInput(picker), '40%'); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(picker.value).to.equal('rgb(255 0 0)'); + expect(getPanel(picker).value).to.equal('rgb(255 0 0 / 0.4)'); + expect(valueEvents(eventSpy)).to.be.empty; + }); + + it('applies on Enter on a swatch, and only picks on Space', async () => { + picker.swatches = ['#00ff00', '#0000ff']; + await elementUpdated(picker); + const [green, blue] = + getPanelRoot(picker).querySelectorAll( + '[part~="swatch"]' + ); + + blue.focus(); + simulateKeyboard(blue, spaceBar); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(getPanel(picker).value).to.equal('#0000ff'); + + green.focus(); + simulateKeyboard(green, enterKey); + await elementUpdated(picker); + + expect(picker.open).to.be.false; + expect(picker.value).to.equal('#00ff00'); + }); + + it('applies on Enter on the canvas marker and on a slider', async () => { + const marker = + getCanvas(picker).renderRoot.querySelector( + '[part~="marker"]' + )!; + + simulateKeyboard(marker, arrowDown); + simulateKeyboard(marker, enterKey); + await elementUpdated(picker); + + expect(picker.open).to.be.false; + expect(picker.value).to.not.equal('#ff0000'); + + await picker.show(); + const hue = getHueSlider(picker); + simulateInput(hue, { value: '120' }); + simulateKeyboard(hue, enterKey); + await elementUpdated(picker); + + expect(picker.open).to.be.false; + expect(ColorModel.parse(picker.value).h).to.be.closeTo(120, 1); + }); + + it('commits a typed color into the draft, and Enter there does not apply', async () => { + const input = getColorInput(picker); + + commitColorInput(input, 'blue'); + simulateKeyboard(input.renderRoot.querySelector('input')!, enterKey); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#0000ff'); + }); + + it('restores the initial color from the preview', async () => { + await pickSwatch(picker, '#00ff00'); + + simulateClick(getPart('preview-initial')); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + expect(getPanel(picker).value).to.equal('#ff0000'); + }); + + it('ends the draft for a new value from code, and keeps it for the same color', async () => { + await pickSwatch(picker, '#00ff00'); + + picker.value = 'rgb(255 0 0)'; + await elementUpdated(picker); + expect(getPanel(picker).value).to.equal('#00ff00'); + + picker.value = '#0000ff'; + await elementUpdated(picker); + expect(getPanel(picker).value).to.equal('#0000ff'); + }); + + it('keeps the draft in a new format', async () => { + await pickSwatch(picker, '#00ff00'); + + picker.format = 'rgb'; + await elementUpdated(picker); + + expect(picker.value).to.equal('rgb(255 0 0)'); + expect(getPanel(picker).value).to.equal('rgb(0 255 0)'); + }); + + it('drops the draft when the confirm mode ends', async () => { + await pickSwatch(picker, '#00ff00'); + + picker.selectionCommit = 'immediate'; + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + expect(getPanel(picker).value).to.equal('#ff0000'); + }); + + it('drops the draft and clears as a user change on the clear icon', async () => { + picker.mode = 'input'; + await elementUpdated(picker); + await pickSwatch(picker, '#00ff00'); + const eventSpy = spy(picker, 'emitEvent'); + + simulateClick(getPart('clear-icon')); + await elementUpdated(picker); + + expect(picker.value).to.equal(''); + expect(getPanel(picker).value).to.equal(''); + expect(valueEvents(eventSpy)).to.eql(['igcInput']); + }); + + it('drops the draft for a commit of the text field of the input mode', async () => { + picker.mode = 'input'; + await elementUpdated(picker); + await pickSwatch(picker, '#00ff00'); + + commitColorInput(getAnchorField(picker), '#0000ff'); + await elementUpdated(picker); + + expect(picker.value).to.equal('#0000ff'); + expect(getPanel(picker).value).to.equal('#0000ff'); + }); + + it('keeps Enter for the controls in the immediate mode', async () => { + picker.selectionCommit = 'immediate'; + await elementUpdated(picker); + + const hue = getHueSlider(picker); + simulateKeyboard(hue, enterKey); + await elementUpdated(picker); + + expect(picker.open).to.be.true; + }); + }); + describe('Input mode', () => { function getInputAnchor(): IgcInputComponent { - return picker.renderRoot.querySelector( - 'igc-input[slot="anchor"]' - )!; + return getAnchorField(picker); } beforeEach(async () => { @@ -1534,6 +1995,410 @@ describe('Color picker', () => { expect(getInputAnchor().invalid).to.equal(picker.invalid); }); + + describe('Clear icon', () => { + function getClearIcon(): HTMLElement | null { + return picker.renderRoot.querySelector('[part="clear-icon"]'); + } + + it('shows the clear icon in the suffix only while a color is set', async () => { + expect(getClearIcon()).to.be.null; + + picker.value = '#ff0000'; + await elementUpdated(picker); + + const icon = getClearIcon()!; + expect(icon.slot).to.equal('suffix'); + expect(icon.parentElement).to.equal(getInputAnchor()); + + picker.value = ''; + await elementUpdated(picker); + + expect(getClearIcon()).to.be.null; + }); + + it('names the clear icon as a button', async () => { + picker.value = '#ff0000'; + await elementUpdated(picker); + + const icon = getClearIcon()!; + expect(icon.role).to.equal('button'); + expect(icon.ariaLabel).to.equal('Clear color'); + + picker.resourceStrings = { color_picker_clear: 'Effacer' }; + await elementUpdated(picker); + + expect(getClearIcon()!.ariaLabel).to.equal('Effacer'); + }); + + it('has no clear icon in default mode', async () => { + picker = await fixture( + html`` + ); + + expect(getClearIcon()).to.be.null; + }); + + it('fills its container, so the clear icon does not change its width', async () => { + const container = await fixture( + html`
+ +
` + ); + picker = container.querySelector('igc-color-picker')!; + const field = getInputAnchor(); + + expect(field.getBoundingClientRect().width).to.equal(400); + + picker.value = '#ff0000'; + await elementUpdated(picker); + + expect(getClearIcon()).to.exist; + expect(field.getBoundingClientRect().width).to.equal(400); + }); + + it('clears with igcInput, and reports igcChange when the focus leaves', async () => { + picker.value = '#ff0000'; + await elementUpdated(picker); + + picker.dispatchEvent( + new FocusEvent('focusin', { relatedTarget: null }) + ); + const eventSpy = spy(picker, 'emitEvent'); + + simulateClick(getClearIcon()!); + await elementUpdated(picker); + + expect(picker.value).to.equal(''); + expect(getInputAnchor().value).to.equal(''); + expect(isAnchorEmpty(picker)).to.be.true; + expect(eventSpy).calledOnceWith('igcInput', { detail: '' }); + + picker.dispatchEvent( + new FocusEvent('focusout', { relatedTarget: null }) + ); + + expect(eventSpy).calledTwice; + expect(eventSpy.secondCall).calledWith('igcChange', { detail: '' }); + }); + + it('keeps the focus in the text field on a click', async () => { + picker.value = '#ff0000'; + await elementUpdated(picker); + + const native = getAnchorNativeInput(picker); + native.focus(); + + const { x, y, width, height } = getClearIcon()!.getBoundingClientRect(); + await sendMouse({ + type: 'click', + position: [Math.round(x + width / 2), Math.round(y + height / 2)], + }); + await elementUpdated(picker); + + expect(picker.value).to.equal(''); + expect(native.matches(':focus')).to.be.true; + }); + + it('renders the content of the clear-icon slot', async () => { + picker = await fixture( + html` + x + ` + ); + + const slot = getClearIcon()!.querySelector( + 'slot[name="clear-icon"]' + )!; + + expect(slot.assignedElements()).to.have.lengthOf(1); + }); + + it('changes nothing on a click while disabled', async () => { + picker.value = '#ff0000'; + picker.disabled = true; + await elementUpdated(picker); + + const eventSpy = spy(picker, 'emitEvent'); + simulateClick(getClearIcon()!); + await elementUpdated(picker); + + expect(picker.value).to.equal('#ff0000'); + expect(eventSpy).not.called; + }); + + it('clear() clears the value and the text, with no events', async () => { + picker.value = '#ff0000'; + await elementUpdated(picker); + + picker.dispatchEvent( + new FocusEvent('focusin', { relatedTarget: null }) + ); + const eventSpy = spy(picker, 'emitEvent'); + + picker.clear(); + await elementUpdated(picker); + + expect(picker.value).to.equal(''); + expect(getInputAnchor().value).to.equal(''); + expect(getClearIcon()).to.be.null; + + picker.dispatchEvent( + new FocusEvent('focusout', { relatedTarget: null }) + ); + + expect(eventSpy).not.called; + }); + }); + + describe('Field parts', () => { + /** Parts of the picker and the parts of the field they name. */ + const forwarded = { + input: 'container', + 'native-input': 'input', + label: 'label', + prefix: 'prefix', + suffix: 'suffix', + }; + + it('exposes the text field as `field` and forwards its parts', () => { + const field = getInputAnchor(); + + expect(field.getAttribute('part')).to.equal('field'); + expect(field.getAttribute('exportparts')).to.equal( + 'container: input, input: native-input, label, prefix, suffix' + ); + }); + + it('styles the text field through the parts, not the inputs of the picker', async () => { + const sheet = new CSSStyleSheet(); + sheet.replaceSync( + ['field', ...Object.keys(forwarded)] + .map( + (name) => + `igc-color-picker::part(${name}) { --probe-${name}: on; }` + ) + .join('\n') + ); + + await withDocumentSheets([sheet], async () => { + picker.value = '#ff0000'; + picker.open = true; + await elementUpdated(picker); + + const field = getInputAnchor(); + const probe = (element: Element, name: string) => + getComputedStyle(element) + .getPropertyValue(`--probe-${name}`) + .trim(); + + expect(probe(field, 'field')).to.equal('on'); + expect(probe(getColorInput(picker), 'field')).to.equal(''); + + for (const [name, inner] of Object.entries(forwarded)) { + const element = field.renderRoot.querySelector( + `[part~="${inner}"]` + )!; + + expect(element, name).to.exist; + expect(probe(element, name), name).to.equal('on'); + } + }); + }); + }); + }); + + describe('Color panel', () => { + const panelParts = [ + 'picker-canvas', + 'marker', + 'dragging', + 'main-row', + 'alpha-row', + 'inputs-row', + 'buttons', + 'hue', + 'alpha', + 'alpha-input', + 'copy', + 'eye-dropper', + 'format-select', + 'swatches', + 'swatch', + 'selected', + 'view-switcher', + 'view-button', + 'active', + 'contrast', + 'contrast-ratio', + 'contrast-mark', + 'pass', + 'fail', + ]; + + beforeEach(async () => { + picker = await createDefaultColorPicker(); + }); + + it('shows the color panel in the popup', () => { + const popup = picker.renderRoot.querySelector('[part="picker"]')!; + + expect(popup.querySelector('igc-color-panel')).to.equal(getPanel(picker)); + }); + + it('forwards the parts of the panel as its own', () => { + expect( + getPanel(picker) + .getAttribute('exportparts')! + .split(',') + .map((part) => part.trim()) + ).to.eql(panelParts); + }); + + it('styles the controls of the panel through its parts', async () => { + const sheet = new CSSStyleSheet(); + sheet.replaceSync('igc-color-picker::part(hue) { --probe: on; }'); + + await withDocumentSheets([sheet], async () => { + picker.open = true; + await elementUpdated(picker); + + expect( + getComputedStyle(getHueSlider(picker)) + .getPropertyValue('--probe') + .trim() + ).to.equal('on'); + }); + }); + + it('passes its options and strings to the panel', async () => { + picker.format = 'rgb'; + picker.showAlpha = true; + picker.hideFormats = true; + picker.swatches = ['#ff0000']; + picker.resourceStrings = { color_picker_hue: 'Tone' }; + await elementUpdated(picker); + + const panel = getPanel(picker); + + expect(panel.format).to.equal('rgb'); + expect(panel.showAlpha).to.be.true; + expect(panel.hideFormats).to.be.true; + expect(panel.swatches).to.eql(['#ff0000']); + expect(panel.resourceStrings.color_picker_hue).to.equal('Tone'); + }); + + it('shows the OKLCH area in the popup for the oklch format', async () => { + picker.format = 'oklch'; + picker.value = '#ff00ff'; + picker.open = true; + await elementUpdated(picker); + + const canvas = getPanelRoot(picker).querySelector('igc-picker-canvas')!; + + expect(canvas.space).to.equal('oklch'); + expect(getHueSlider(picker).value).to.equal('328'); + }); + + it('passes contrastAgainst to the panel', async () => { + picker.value = '#000000'; + picker.contrastAgainst = 'white'; + await elementUpdated(picker); + + const panel = getPanel(picker); + const ratio = panel.renderRoot.querySelector('[part="contrast-ratio"]'); + + expect(panel.contrastAgainst).to.equal('white'); + expect(ratio?.textContent).to.equal('Contrast 21:1'); + }); + + it('keeps the value of the panel equal to its own', async () => { + picker.value = 'oklch(70% 0.1 200)'; + await elementUpdated(picker); + + expect(getPanel(picker).value).to.equal(picker.value); + + picker.format = 'hsl'; + await elementUpdated(picker); + + expect(getPanel(picker).value).to.equal(picker.value); + }); + + it('keeps the events of the panel inside', async () => { + const leaked: Event[] = []; + + for (const type of ['igcInput', 'igcChange']) { + picker.addEventListener(type, (event) => { + if (event.composedPath()[0] !== picker) { + leaked.push(event); + } + }); + } + + picker.open = true; + await elementUpdated(picker); + await pickSwatch(picker, '#00ff00'); + + expect(leaked).to.be.empty; + }); + + it('shows its swatch children in the swatch list of the panel', async () => { + picker = await fixture(html` + + + + Brand + + + + `); + picker.open = true; + await elementUpdated(picker); + await nextFrame(); + await elementUpdated(picker); + + const [green, blue] = + picker.querySelectorAll('igc-color-swatch'); + const list = + getPanelRoot(picker).querySelector('[part="swatches"]')!; + + expect(list.hidden).to.be.false; + expect( + list.querySelector('slot')!.assignedElements({ flatten: true }) + ).to.eql([green, blue.parentElement]); + + // The swatch list is a stop of the focus trap of the popup. + const trap = picker.renderRoot.querySelector('igc-focus-trap')!; + expect(trap.focusableElements).to.include(green); + + const eventSpy = spy(picker, 'emitEvent'); + simulateClick(blue); + await elementUpdated(picker); + + expect(picker.value).to.equal('#0000ff'); + expect(eventSpy).calledWith('igcInput', { detail: '#0000ff' }); + }); + + it('passes its views and takes the view of the switcher', async () => { + picker.views = 'gradient swatches'; + picker.activeView = 'swatches'; + picker.open = true; + await elementUpdated(picker); + + const panel = getPanel(picker); + expect(panel.views).to.equal('gradient swatches'); + expect(panel.activeView).to.equal('swatches'); + + simulateClick( + getPanelRoot(picker).querySelector( + '[part~="view-button"][value="gradient"]' + )! + ); + await elementUpdated(picker); + + expect(picker.activeView).to.equal('gradient'); + expect(panel.activeView).to.equal('gradient'); + }); }); describe('Rendering', () => { @@ -1571,23 +2436,24 @@ describe('Color picker', () => { picker.open = true; await elementUpdated(picker); - expect(picker.renderRoot.querySelector('[part="alpha-row"]')).to.be.null; + expect(getPanelRoot(picker).querySelector('[part="alpha-row"]')).to.be + .null; picker.showAlpha = true; await elementUpdated(picker); - expect(picker.renderRoot.querySelector('[part="alpha-row"]')).to.exist; + expect(getPanelRoot(picker).querySelector('[part="alpha-row"]')).to.exist; }); it('hides the format select when hideFormats is set', async () => { picker = await createDefaultColorPicker(); picker.open = true; await elementUpdated(picker); - expect(picker.renderRoot.querySelector('#format-select')).to.exist; + expect(getPanelRoot(picker).querySelector('#format-select')).to.exist; picker.hideFormats = true; await elementUpdated(picker); - expect(picker.renderRoot.querySelector('#format-select')).to.be.null; + expect(getPanelRoot(picker).querySelector('#format-select')).to.be.null; }); it('runs the slider tracks in the direction of the ranges', async () => { diff --git a/src/components/color-picker/color-picker.ts b/src/components/color-picker/color-picker.ts index 3cf08e16e..7e609f25d 100644 --- a/src/components/color-picker/color-picker.ts +++ b/src/components/color-picker/color-picker.ts @@ -1,28 +1,27 @@ -import { ColorPickerResourceStringsEN } from 'igniteui-i18n-core'; import { html, nothing, type PropertyValues, type TemplateResult } from 'lit'; -import { property, query } from 'lit/decorators.js'; -import { cache } from 'lit/directives/cache.js'; -import { guard } from 'lit/directives/guard.js'; +import { property, query, state } from 'lit/decorators.js'; import { ifDefined } from 'lit/directives/if-defined.js'; import { live } from 'lit/directives/live.js'; import { createRef, ref } from 'lit/directives/ref.js'; import { styleMap } from 'lit/directives/style-map.js'; import { IgcBaseComboBoxComponent } from '#internals/bases/combo-box.js'; +import { + type ColorPickerContext, + colorPickerContext, +} from '#internals/context.js'; import { addAriaProjector, ariaBindings, HELPER_TEXT_ID, hostAria, } from '#internals/controllers/aria-projection.js'; +import { addContextProvider } from '#internals/controllers/context-provider.js'; import { addKeybindings, altKey, arrowDown, - arrowRight, arrowUp, - endKey, escapeKey, - isKey, } from '#internals/controllers/key-bindings.js'; import { addSlotController, setSlots } from '#internals/controllers/slot.js'; import { shadowOptions } from '#internals/decorators/shadow-options.js'; @@ -34,33 +33,45 @@ import type { FormValueTransformers } from '#internals/mixins/forms/form-transfo import { createFormValueState } from '#internals/mixins/forms/form-value.js'; import { I18nMixin } from '#internals/mixins/i18n.js'; import { partMap } from '#internals/part-map.js'; -import { isEmpty } from '#internals/utils/arrays.js'; +import { renderClearIcon } from '#internals/templates/slotted-icon.js'; import { addSafeEventListener, focusLeftHost, - getElementFromPath, stopPropagation, } from '#internals/utils/events.js'; import { bindIf } from '#internals/utils/lit.js'; -import { asNumber, clamp } from '#internals/utils/math.js'; import { all } from '#themes/color-picker/themes/themes.js'; import { addThemingController } from '#theming/theming-controller.js'; import { styles as componentBase } from '../../styles/common/component.css.js'; import IgcButtonComponent from '../button/button.js'; -import IgcIconButtonComponent from '../button/icon-button.js'; -import IgcDividerComponent from '../divider/divider.js'; +import { renderConfirmButtons } from '../button/confirm-buttons.js'; +import IgcColorPanelComponent from '../color-panel/color-panel.js'; +import { + panelColor, + panelParts, + resolveView, + syncMarker, +} from '../color-panel/common.js'; import IgcFocusTrapComponent from '../focus-trap/focus-trap.js'; +import IgcIconComponent from '../icon/icon.js'; import IgcInputComponent from '../input/input.js'; import IgcPopoverComponent from '../popover/popover.js'; -import IgcSelectItemComponent from '../select/select-item.js'; -import IgcSelectComponent from '../select/select.js'; -import type { ColorFormat, ColorPickerMode } from '../types.js'; +import type { + ColorFormat, + ColorPanelView, + ColorPickerMode, + ColorPickerSelectionCommit, +} from '../types.js'; import IgcValidationContainerComponent from '../validation-container/validation-container.js'; import IgcVisuallyHiddenComponent from '../visually-hidden/visually-hidden.js'; -import { ColorModel, rgbString } from './model.js'; -import IgcPickerCanvasComponent, { - type PickerCanvasEventDetail, -} from './picker-canvas.js'; +import { colorPickerI18nConfig } from './i18n.js'; +import { + ColorModel, + colorKey, + formatPlaceholders, + parseTypedColor, + opaqueColor, +} from './model.js'; import { styles } from './themes/color-picker.base.css.js'; import { styles as shared } from './themes/shared/color-picker.common.css.js'; import { colorPickerValidators } from './validators.js'; @@ -78,48 +89,21 @@ const Slots = setSlots( 'value-missing', 'custom-error', 'invalid', - 'helper-text' + 'helper-text', + 'clear-icon', + 'footer' ); -const i18n = { - defaultEN: ColorPickerResourceStringsEN, -}; - -/** The color string shape of each format. Shown while the input is empty. */ -const formatPlaceholders: Record = { - hex: '#rrggbb', - rgb: 'rgb(r g b)', - hsl: 'hsl(h s% l%)', -}; - -/** 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 parts of the color panel that the picker exposes as its own. */ +const exportedPanelParts = panelParts.join(', '); /** * 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 @@ -131,22 +115,31 @@ function getEyeDropper(): EyeDropperConstructor | undefined { * @slot custom-error - Renders content when setCustomValidity(message) is set. * @slot invalid - Renders content when the component is in invalid state (validity.valid = false). * @slot helper-text - Renders content below the picker. + * @slot clear-icon - Renders the clear icon in input mode. + * @slot - The color swatches and swatch groups. The picker shows them in the swatch list of its popup. + * @slot footer - Renders content below the color panel in the popup. In the confirm mode of `selectionCommit`, the preview, Cancel and Apply show after it. * * @fires igcOpening - Emitted before the user opens the picker dropdown. Cancelable. * @fires igcOpened - Emitted after the picker dropdown opens on a user action. * @fires igcClosing - Emitted before the user closes the picker dropdown. Cancelable. * @fires igcClosed - Emitted after the picker dropdown closes on a user action. - * @fires igcInput - Emitted when the user changes the color with the canvas, the sliders, the alpha input, a swatch or the eyedropper. - * @fires igcChange - Emitted when the focus leaves the component after the user changed the color. + * @fires igcInput - 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. + * @fires igcChange - Emitted when the focus leaves the component after the user changed the color, and when the user applies the draft of the confirm mode. * * @csspart color-picker - The wrapper of the anchor, the label and the helper text. * @csspart anchor - The trigger element that opens the picker (the button in default mode, or the swatch prefix in input mode). * @csspart empty - Applied alongside `anchor` when no color value is set, rendering a checkered background. * @csspart input-mode - Added to the anchor part in input mode. - * @csspart label - The label rendered after the anchor in default mode. + * @csspart label - The label: the element after the anchor in default mode, or the label of the text field in input mode. + * @csspart 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. + * @csspart input - The container of the text field in input mode. + * @csspart native-input - The native input of the text field in input mode. + * @csspart prefix - The prefix wrapper of the text field in input mode. It holds the anchor. + * @csspart suffix - The suffix wrapper of the text field in input mode. It holds the clear icon. + * @csspart clear-icon - The clear icon wrapper in input mode. It shows while a color is set. * @csspart picker - The popover container holding the canvas, sliders, inputs and swatches. - * @csspart picker-canvas - The saturation and value canvas. - * @csspart marker - The marker on the canvas that shows the saturation and value. + * @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. @@ -158,8 +151,24 @@ function getEyeDropper(): EyeDropperConstructor | undefined { * @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 container of the pre-defined color swatches. - * @csspart swatch - An individual color swatch button. + * @csspart swatches - The swatch list. + * @csspart swatch - A swatch of the `swatches` property. + * @csspart selected - Added to the swatch part when the swatch has the color of the value. + * @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. + * @csspart footer - The container below the color panel in the popup. It holds the `footer` slot and, in the confirm mode, the actions. + * @csspart actions - The container of the preview, Cancel and Apply in the confirm mode. + * @csspart preview - The preview of the initial color and the draft in the confirm mode. + * @csspart preview-initial - The button that shows the initial color and restores it. + * @csspart preview-current - The color of the draft. + * @csspart cancel-button - The Cancel button of the confirm mode. + * @csspart apply-button - The Apply button of the confirm mode. * * @cssproperty --ig-helper-min-lines - The minimum number of lines below the control for the helper text and the validation messages: `1`, `2` or `3`. A message that shows then uses space that is already there, so the content below does not move. Set it on a container, such as a form, to apply it to all the controls in it. Default is `0`. * @@ -173,7 +182,7 @@ export default class IgcColorPickerComponent extends I18nMixin( typeof IgcBaseComboBoxComponent >(IgcBaseComboBoxComponent) ), - i18n + colorPickerI18nConfig ) { public static readonly tagName = 'igc-color-picker'; public static override styles = [componentBase, styles, shared]; @@ -185,12 +194,9 @@ export default class IgcColorPickerComponent extends I18nMixin( IgcInputComponent, IgcPopoverComponent, IgcFocusTrapComponent, - IgcSelectComponent, - IgcSelectItemComponent, - IgcPickerCanvasComponent, - IgcDividerComponent, IgcButtonComponent, - IgcIconButtonComponent, + IgcIconComponent, + IgcColorPanelComponent, IgcValidationContainerComponent, IgcVisuallyHiddenComponent ); @@ -210,8 +216,7 @@ export default class IgcColorPickerComponent extends I18nMixin( // The same color in another format is the same value. isSameValue: (a, b) => a === b || - ColorModel.parse(a).asString('rgb', true) === - ColorModel.parse(b).asString('rgb', true), + colorKey(ColorModel.parse(a)) === colorKey(ColorModel.parse(b)), }; protected override readonly _formValue = createFormValueState(this, { @@ -219,17 +224,32 @@ export default class IgcColorPickerComponent extends I18nMixin( transformers: IgcColorPickerComponent._transformers, }); - private readonly _alphaInputRef = createRef(); - private readonly _canvasRef = createRef(); + private readonly _panelRef = createRef(); private readonly _anchorRef = createRef< HTMLButtonElement | IgcInputComponent >(); - private readonly _supportsEyeDropper = Boolean(getEyeDropper()); private _color = ColorModel.empty(); - /** The last value written for each host custom property. */ - private readonly _appliedProperties = new Map(); + /** The color in the popup in the confirm mode, until Apply. */ + @state() + private _draft?: ColorModel; + + private readonly _themes = addThemingController(this, all); + + private _activeView: ColorPanelView = 'gradient'; + + /** The link of the color panel to this picker. */ + private readonly _pickerContext: ColorPickerContext = { + setFormat: (format) => { + this.format = format; + }, + setActiveView: (view) => { + this.activeView = view; + }, + isConfirmMode: () => this._isConfirmMode, + applyDraft: () => this._handleApply(), + }; @query(`#${HELPER_TEXT_ID}`) private readonly _helperText!: IgcValidationContainerComponent | null; @@ -238,6 +258,10 @@ export default class IgcColorPickerComponent extends I18nMixin( return this.mode === 'input'; } + private get _isConfirmMode(): boolean { + return this.selectionCommit === 'confirm'; + } + /** The text input of input mode. After a mode change, the ref keeps the old anchor until the render. */ private get _inputAnchor(): IgcInputComponent | undefined { const anchor = this._anchorRef.value; @@ -259,16 +283,26 @@ export default class IgcColorPickerComponent extends I18nMixin( public label?: string; /** - * The value of the component as a CSS color string. Accepts hex, rgb(a), - * hsl(a) and named colors. + * 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. + * 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) { - this._color = ColorModel.parse(value); + const color = ColorModel.parse(value); + + // The same color keeps the hue of a gray, which a color string does not + // carry, as in the color panel. + if (colorKey(color) !== colorKey(this._color)) { + this._setColor(color); + } + this._updateColor(); } @@ -320,13 +354,68 @@ export default class IgcColorPickerComponent extends I18nMixin( public mode: ColorPickerMode = 'default'; /** - * 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. + * 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. + * + * @attr selection-commit + * @default 'immediate' + */ + @property({ attribute: 'selection-commit' }) + public selectionCommit: ColorPickerSelectionCommit = 'immediate'; + + /** + * 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. */ @property({ attribute: false }) public swatches: string[] = []; + /** + * 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. + * + * @attr views + * @default 'gradient' + */ + @property() + public views = 'gradient'; + + /** + * 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`. + * + * @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 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. + * + * @attr contrast-against + */ + @property({ attribute: 'contrast-against' }) + public contrastAgainst = ''; + //#endregion //#region Lifecycle @@ -334,27 +423,17 @@ export default class IgcColorPickerComponent extends I18nMixin( constructor() { super(); - addThemingController(this, all); addSafeEventListener(this, 'focusout', this._handleFocusOut); addKeybindings(this, { skip: () => this.disabled }) - .set(escapeKey, this._handleKeyboardClosing, { when: () => this.open }) + .set(escapeKey, this._closeToAnchor, { when: () => this.open }) .set([altKey, arrowDown], this._handleAnchorClick) - .set([altKey, arrowUp], this._handleKeyboardClosing); - - addKeybindings(this, { - skip: () => this.disabled || !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, - }); + .set([altKey, arrowUp], this._closeToAnchor); + + addContextProvider(this, { + context: colorPickerContext, + value: () => this._pickerContext, + }); addAriaProjector(this, { target: () => this._inputAnchor, @@ -363,16 +442,34 @@ export default class IgcColorPickerComponent extends I18nMixin( }); } + protected override willUpdate(props: PropertyValues): void { + super.willUpdate(props); + + // Every close but Apply drops the draft, also a close for `disabled`. + if ( + (props.has('open') || props.has('selectionCommit')) && + !(this.open && this._isConfirmMode) + ) { + this._draft = undefined; + } + } + protected override update(props: PropertyValues): void { if (props.has('format')) { this._serializeInFormat(); } - this._applyColorProperties(); - super.update(props); } + /** Waits also for the color panel, which renders after the picker. */ + protected override async getUpdateComplete(): Promise { + const complete = await super.getUpdateComplete(); + const panelComplete = await this._panelRef.value?.updateComplete; + + return complete && (panelComplete ?? true); + } + protected override firstUpdated(): void { // The helper text renders after the anchor, so a host description misses it. if (!this._isInputMode && this.ariaDescribedByElements?.length) { @@ -383,9 +480,9 @@ export default class IgcColorPickerComponent extends I18nMixin( protected override updated(props: PropertyValues): void { super.updated(props); - if (props.has('open') || props.has('value')) { + if (props.has('open') && this.open) { // Wait for the paint, then sync the marker position with the color. - requestAnimationFrame(() => this._syncCanvasPosition()); + requestAnimationFrame(() => this._panelRef.value?.[syncMarker]()); } } @@ -401,7 +498,7 @@ export default class IgcColorPickerComponent extends I18nMixin( //#region Event handlers - private async _handleKeyboardClosing(): Promise { + private async _closeToAnchor(): Promise { if (await this._hide(true)) { this._anchorRef.value?.focus(); } @@ -416,235 +513,67 @@ export default class IgcColorPickerComponent extends I18nMixin( this._reportChange(this.value); } - private _handleCanvasColorPicked( - event: CustomEvent - ): void { - stopPropagation(event); - - this._color.setSaturationAndValue(event.detail.x, 100 - event.detail.y); - this._applyUserColor(); - } - - private _handleHueValueChange(event: Event): void { - stopPropagation(event); - - this._color.h = asNumber((event.target as HTMLInputElement).value); - this._applyUserColor(); - } - - private _handleAlphaSliderValueChange(event: Event): void { + private _handleColorInputChange(event: CustomEvent): void { stopPropagation(event); - this._setAlpha(asNumber((event.target as HTMLInputElement).value)); - } - - /** - * 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}%` : ''; + const color = parseTypedColor(event.detail); - this._writeAlphaText(input, text, Math.min(typed, caretLimit(text))); - - if (digits) { - this._setAlpha(percent); + if (!color) { + (event.target as IgcInputComponent).value = this._color.asString( + this.format + ); + return; } - } - /** - * 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); - } - - /** - * 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); - } + this._setColor(color); + // A commit of the text input, so no `igcInput`. + this._writeFrom('user', () => this._updateColor()); } - private _handleAlphaInputChange(event: CustomEvent): void { + private _handlePanelInput(event: CustomEvent): void { stopPropagation(event); - const input = event.target as IgcInputComponent; - - if (!input.value) { - input.value = `${this._alphaPercent}%`; + if (this._takePanelColor()) { + this._emitInputEvent(); } } - private _handleFormatChange( - event: CustomEvent - ): void { + /** The end of a change in the panel. The picker reports it when the focus leaves. */ + private _handlePanelChange(event: CustomEvent): void { stopPropagation(event); - this.format = event.detail.value as ColorFormat; + this._takePanelColor(); } - private _handleColorInputChange(event: CustomEvent): void { - stopPropagation(event); - - const input = event.target as IgcInputComponent; - const cleared = !event.detail?.trim(); - const color = ColorModel.parse(event.detail); - - // An invalid and non-empty value reverts the input to the current color. - // An empty value clears the color. - if (!cleared && color.isEmpty) { - input.value = this._color.asString(this.format); + /** A clear by the user: `igcInput` now, `igcChange` when the focus leaves. */ + private _handleClearClick(): void { + if (this.disabled) { return; } - this._color = color; - // A commit of the text input, so no `igcInput`. - this._writeFrom('user', () => this._updateColor()); - this._syncCanvasPosition(); + this._setColor(ColorModel.empty()); + this._applyUserColor(); } - private _handleEyeDropperClick(): void { - const EyeDropper = getEyeDropper(); - - if (!EyeDropper) return; + private _handleApply(): void { + this._writeFrom('user', () => { + if (this._draft) { + this._setColor(this._draft); + this._updateColor(); + } - new EyeDropper() - .open() - .then((result) => { - // The pick can end after the picker is disabled. - if (!this.disabled) { - this._commitValue(result.sRGBHex, 'igcInput'); - } - }) - .catch(() => {}); - } - - private _handleCopy(): void { - navigator.clipboard?.writeText(this.value).catch(() => {}); + this._reportChange(this.value); + }); + this._closeToAnchor(); } - private _handleSwatchClick(event: Event): void { - const swatch = getElementFromPath( - 'button[part="swatch"]', - event - ); - const color = swatch?.dataset.color; - - if (color && !this.disabled) { - this._commitValue(color, 'igcInput'); - } + private _handleRestoreClick(): void { + this._draft = undefined; } //#endregion //#region Internal methods - /** The current color with its alpha, independent of `format`. */ - private get _alphaColor(): string { - return this._color.asString('rgb', true); - } - - /** - * The current color with an opaque alpha. An empty color gives white, where - * the alpha ramp and the canvas marker start. The anchor still shows "no - * color", because {@link _previewStyle} uses {@link _alphaColor}. - */ - private get _opaqueColor(): string { - return rgbString(this._color.toRGB()); - } - - /** 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 saturation/value plane and the hue thumb use. */ - private get _currentColor(): string { - return `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', this._opaqueColor); - } - - 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 _updateColor(): void { this._formValue.setValueAndFormState(this._color.asString(this.format)); this.requestUpdate(); @@ -656,6 +585,12 @@ export default class IgcColorPickerComponent extends I18nMixin( this._emitInputEvent(); } + /** A new color ends the draft. */ + private _setColor(color: ColorModel): void { + this._color = color; + this._draft = undefined; + } + /** * Renders the current color in the active format. * @@ -672,19 +607,36 @@ export default class IgcColorPickerComponent extends I18nMixin( } } - private _syncCanvasPosition(): void { - if (!this._canvasRef.value || !this.open) return; + /** + * Writes the color of the panel as a change of the user, or into the draft + * in the confirm mode. A disabled picker, or a closed one in the confirm + * mode, renders its own color into the panel again, for an eye dropper pick + * that ends after that. Returns whether the value changed. + */ + private _takePanelColor(): boolean { + const panel = this._panelRef.value; - const rect = this._canvasRef.value.getBoundingClientRect(); - const { width: markerWidth, height: markerHeight } = - this._canvasRef.value.getMarkerDimensions(); + if (!panel) { + return false; + } + + if (this.disabled || (this._isConfirmMode && !this.open)) { + this.requestUpdate(); + return false; + } + + // The model of the panel keeps the hue of a gray. + const color = panel[panelColor](); - const [, s, v] = this._color.toHSV(); - const x = (s / 100) * rect.width - markerWidth; - const y = ((100 - v) / 100) * rect.height - markerHeight; + if (this._isConfirmMode) { + this._draft = color; + return false; + } + + this._setColor(color); + this._writeFrom('user', () => this._updateColor()); - this._canvasRef.value.x = x; - this._canvasRef.value.y = y; + return true; } private _emitInputEvent(): void { @@ -709,210 +661,12 @@ export default class IgcColorPickerComponent extends I18nMixin( super.blur(); } - //#endregion - - //#region Canvas area rendering - - private _renderCanvasGradient(): TemplateResult { - const [, saturation, brightness] = this._color.toHSV(); - - return html` - - - `; - } - - //#endregion - - //#region Hue row and buttons rendering - - private _renderHueSlider(): TemplateResult { - return html` - - `; - } - - private _renderIconButton( - part: string, - icon: string, - label: string, - handler: () => void, - disabled = false - ): TemplateResult { - return html` - - ${label} - - `; - } - - private _renderPickerButtons(): TemplateResult { - const strings = this.resourceStrings; - - return html` -
- ${this._renderIconButton( - 'copy', - 'copy_content', - strings.color_picker_copy, - this._handleCopy - )} - ${this._renderIconButton( - 'eye-dropper', - 'eye_dropper', - strings.color_picker_eye_dropper, - this._handleEyeDropperClick, - !this._supportsEyeDropper - )} -
- `; - } - - //#endregion - - //#region Alpha row rendering - - private _renderAlphaRow(): TemplateResult { - const strings = this.resourceStrings; - - return html` - - - - - - - - `; - } - - //#endregion - - //#region Color formats and input row rendering - - private _renderSelect(): TemplateResult { - const label = this.resourceStrings.color_picker_format; - - return html` - - - - - - Hex - RGB - HSL - - `; - } - - private _renderInputsRow(): TemplateResult { - const label = this.resourceStrings.color_picker_value; - - return html` - ${cache(this.hideFormats ? nothing : this._renderSelect())} - - - - - - `; - } - - //#endregion - - //#region Swatches rendering - - private _renderSwatches(): TemplateResult | typeof nothing { - return !isEmpty(this.swatches) - ? html` - -
- ${this.swatches.map( - (color) => html` - - ` - )} -
- ` - : nothing; + /** + * Clears the value and the text of the input. As for a value set from code, + * the component emits no events. + */ + public clear(): void { + this.value = ''; } //#endregion @@ -933,14 +687,14 @@ export default class IgcColorPickerComponent extends I18nMixin( * `--_alpha-preview` paints the color with its real alpha over the whole * surface. Do not transpose the two. See the `swatch-preview` mixin. */ - private _previewStyle(): ReturnType { - const color = this._alphaColor; + private _previewStyle(model = this._color): ReturnType { + const color = colorKey(model); return bindIf( color, styleMap({ '--_alpha-preview': color, - '--_color-preview': this._opaqueColor, + '--_color-preview': opaqueColor(model), }) ); } @@ -974,11 +728,23 @@ export default class IgcColorPickerComponent extends I18nMixin( `; } + private _renderClearIcon(): TemplateResult | typeof nothing { + return this._color.isEmpty + ? nothing + : renderClearIcon( + 'clear-icon', + this._handleClearClick, + this.resourceStrings.color_picker_clear + ); + } + private _renderInputAnchor(): TemplateResult { return html` + ${this._renderClearIcon()} `; } @@ -1017,22 +784,81 @@ export default class IgcColorPickerComponent extends I18nMixin( aria-label=${this.resourceStrings.color_picker_dialog_label} aria-modal="false" > - ${this._renderCanvasGradient()} -
- ${this._renderHueSlider()}${this._renderPickerButtons()} -
- ${ - this.showAlpha - ? html`
${this._renderAlphaRow()}
` - : nothing - } -
${this._renderInputsRow()}
- ${guard([this.swatches], () => this._renderSwatches())} + + + + ${this._renderFooter()} `; } + private _renderFooter(): TemplateResult { + const confirm = this._isConfirmMode; + + return html` +
+ + ${confirm ? this._renderActions() : nothing} +
+ `; + } + + private _renderActions(): TemplateResult { + const strings = this.resourceStrings; + const draft = this._draft ?? this._color; + + return html` +
+
+ + +
+ ${renderConfirmButtons({ + theme: this._themes.theme, + cancel: { + part: 'cancel-button', + label: strings.color_picker_cancel, + onClick: this._closeToAnchor, + }, + confirm: { + part: 'apply-button', + label: strings.color_picker_apply, + onClick: this._handleApply, + }, + })} +
+ `; + } + protected override render(): TemplateResult { return html`
diff --git a/src/components/color-picker/color.property.spec.ts b/src/components/color-picker/color.property.spec.ts index 591802c84..7da1ccb5b 100644 --- a/src/components/color-picker/color.property.spec.ts +++ b/src/components/color-picker/color.property.spec.ts @@ -5,7 +5,7 @@ import { expectCloseTo } from '#internals/testing/helpers.spec.js'; import type { ColorFormat } from '../types.js'; import { isValidColor, normalizeColor, parseColor } from './common.js'; import { converter, type RGB } from './converters.js'; -import { ColorModel, getContext } from './model.js'; +import { ColorModel, colorFormats, getContext } from './model.js'; const EPSILON = 1e-6; @@ -20,6 +20,7 @@ const tenths = (max: number) => */ const channel = tenths(2550); const byte = fc.integer({ min: 0, max: 255 }); +const bytes = fc.tuple(byte, byte, byte); const alpha = fc.double({ min: 0, max: 1, noNaN: true }); const rgb = fc.tuple(channel, channel, channel); const hsl = fc.tuple(tenths(3599), tenths(1000), tenths(1000)); @@ -49,6 +50,16 @@ const operation = fc.oneof( fc.record({ key: fc.constant('sv'), value: fc.tuple(number, number) }) ); +/** + * Whether the engine converts OKLCH with the CSS Color 4 matrices. Chromium + * does not, so a channel near 0 can come back one step off there. This color + * shows it. + */ +function hasSpecOklab(): boolean { + const color = ColorModel.parse('oklch(67.93% 0.22066 143.91)'); + return color.asString('hex') === '#01b825'; +} + function expectInRange(values: number[], max: number[]) { values.forEach((value, i) => { expect(Number.isNaN(value), `${values}`).to.be.false; @@ -62,7 +73,7 @@ describe('Color properties', () => { describe('Converters', () => { it('round-trips integer channels through hex exactly', () => { fc.assert( - fc.property(fc.tuple(byte, byte, byte), (value) => { + fc.property(bytes, (value) => { const hex = converter.rgb.hex(value); expect(hex).to.match(/^[0-9a-f]{6}$/); @@ -123,6 +134,7 @@ describe('Color properties', () => { expectInRange(converter.rgb.hsv(rgbValue), [360, 100, 100]); expectInRange(converter.hsl.rgb(hslValue), [255, 255, 255]); expectInRange(converter.hsl.hsv(hslValue), [360, 100, 100]); + expectInRange(converter.rgb.oklch(rgbValue), [100, 0.33, 360]); }) ); }); @@ -154,18 +166,92 @@ describe('Color properties', () => { ); }); + it('reads any `color(srgb)` color as whole channels in range', () => { + // A channel outside 0-1 is outside the gamut. Firefox may map it into + // the gamut, not clip it, so only the range is checked there. + const unit = fc.integer({ min: -500, max: 1500 }).map((v) => v / 1000); + + fc.assert( + fc.property(fc.tuple(unit, unit, unit), alpha, (channels, a) => { + const [r, g, b] = channels; + const parsed = parseColor(`color(srgb ${r} ${g} ${b} / ${a})`, ctx); + + for (const channel of parsed.value) { + expect(Number.isInteger(channel), `${parsed.value}`).to.be.true; + } + expectInRange(parsed.value, [255, 255, 255]); + expect(parsed.alpha).to.be.closeTo(a, 1 / 255 + EPSILON); + + if (channels.every((channel) => channel >= 0 && channel <= 1)) { + expectCloseTo( + parsed.value, + channels.map((channel) => channel * 255), + 0.5 + EPSILON + ); + } + }) + ); + }); + + it('parses any color outside the legacy syntax into sRGB', () => { + const unit = fc.integer({ min: 0, max: 1000 }).map((v) => v / 1000); + const modernColor = fc.oneof( + fc + .tuple( + fc.integer({ min: 0, max: 100 }), + fc.integer({ min: 0, max: 400 }).map((v) => v / 1000), + fc.integer({ min: 0, max: 360 }) + ) + .map(([l, c, h]) => `oklch(${l}% ${c} ${h})`), + fc + .tuple( + fc.integer({ min: 0, max: 100 }), + fc.integer({ min: -150, max: 150 }), + fc.integer({ min: -150, max: 150 }) + ) + .map(([l, a, b]) => `lab(${l}% ${a} ${b})`), + fc + .tuple( + fc.constantFrom( + 'display-p3', + 'rec2020', + 'a98-rgb', + 'prophoto-rgb', + 'srgb-linear', + 'xyz' + ), + unit, + unit, + unit + ) + .map(([space, ...values]) => `color(${space} ${values.join(' ')})`) + ); + + fc.assert( + fc.property(modernColor, (value) => { + const model = ColorModel.parse(value); + + expect(model.isEmpty, value).to.be.false; + expect(model.asString('hex'), value).to.match(/^#[0-9a-f]{6}$/); + }) + ); + }); + it('parses the string of a color model back to the same color', () => { const tolerance: Record = { hex: 0.5, rgb: 0.5, hsl: 5, + // Half a step to the whole channel, up to 0.46 of a step from the + // decimals, and up to 0.47 more in Chromium. + oklch: hasSpecOklab() ? 1 : 1.5, }; fc.assert( fc.property( rgb, alpha, - fc.constantFrom('hex', 'rgb', 'hsl'), + fc.constantFrom(...colorFormats), fc.boolean(), (value, a, format, forceAlpha) => { const model = new ColorModel(value as RGB, a); @@ -178,6 +264,17 @@ describe('Color properties', () => { ) ); }); + + it('gives an 8-bit color back from its oklch string', () => { + const tolerance = hasSpecOklab() ? 0 : 1; + + fc.assert( + fc.property(bytes, (value) => { + const text = new ColorModel(value).asString('oklch'); + expectCloseTo(ColorModel.parse(text).toRGB(), value, tolerance); + }) + ); + }); }); describe('Model', () => { diff --git a/src/components/color-picker/common.spec.ts b/src/components/color-picker/common.spec.ts index 5dd89f16c..9b9ff483a 100644 --- a/src/components/color-picker/common.spec.ts +++ b/src/components/color-picker/common.spec.ts @@ -70,6 +70,70 @@ describe('parseColor', () => { expect(result.value).to.deep.equal([0, 0, 0]); expect(result.alpha).to.equal(1); }); + + it('clips a `color(srgb)` serialization and reads `none` as 0', () => { + const result = parseColor( + 'oklch(1 0.4 30)', + serializingContext('color(srgb 1.2 none -0.1 / 0.25)') + ); + + expect(result).to.deep.equal({ value: [255, 0, 0], alpha: 0.25 }); + }); + + it('rejects a serialization in an unknown notation', () => { + const ctx = serializingContext('oklch(0.7 0.1 200)'); + + expect(tryParseColor('oklch(70% 0.1 200)', ctx)).to.be.null; + expect(isValidColor('oklch(70% 0.1 200)', ctx)).to.be.false; + }); + }); + + describe('notations outside the legacy syntax', () => { + // The same sRGB result in Chromium, Firefox and WebKit. + const cases: [string, ParsedColor][] = [ + ['oklch(70% 0.1 200)', { value: [64, 177, 183], alpha: 1 }], + ['oklab(0.7 -0.05 0.1)', { value: [154, 167, 82], alpha: 1 }], + ['lab(50% 40 30 / 0.3)', { value: [187, 88, 70], alpha: 0.3 }], + ['lch(50% 40 30)', { value: [178, 93, 87], alpha: 1 }], + ['color(srgb 1 0 0 / 0.5)', { value: [255, 0, 0], alpha: 0.5 }], + ['color(srgb none 0.5 0)', { value: [0, 128, 0], alpha: 1 }], + ['color(xyz 0.5 0.5 0.5)', { value: [204, 183, 180], alpha: 1 }], + ['rgb(from red r g 100)', { value: [255, 0, 100], alpha: 1 }], + ['color-mix(in oklch, red, blue)', { value: [186, 0, 194], alpha: 1 }], + ]; + + for (const [color, expected] of cases) { + it(`parses ${color} into sRGB`, () => { + expect(parseColor(color, ctx)).to.deep.equal(expected); + }); + } + + it('clips a color outside the sRGB gamut', () => { + expect(parseColor('color(display-p3 1 0 0)', ctx).value).to.deep.equal([ + 255, 0, 0, + ]); + }); + }); + + describe('colors that depend on their context', () => { + const contextColors = [ + 'currentcolor', + 'CurrentColor', + 'var(--brand)', + 'light-dark(red, blue)', + 'Canvas', + 'ButtonFace', + 'AccentColor', + 'color-mix(in srgb, currentcolor, red)', + 'rgb(from currentcolor r g b)', + ]; + + for (const color of contextColors) { + it(`rejects ${color}`, () => { + expect(tryParseColor(color, ctx)).to.be.null; + expect(isValidColor(color, ctx)).to.be.false; + }); + } }); describe('hex color parsing', () => { @@ -265,4 +329,12 @@ describe('tryParseColor', () => { expect(tryParseColor('', ctx)).to.be.null; expect(tryParseColor('#ff0000', null)).to.be.null; }); + + it('cannot turn invalid text into a color through the relative conversion', () => { + const ctx = makeTestContext(); + + // Inside `color(from ...)`, the open comment would hide the rest. + expect(tryParseColor('red srgb r g b) /*', ctx)).to.be.null; + expect(tryParseColor('oklch(0.7 0.1 200) srgb r g b) /*', ctx)).to.be.null; + }); }); diff --git a/src/components/color-picker/common.ts b/src/components/color-picker/common.ts index 0d16fb71f..76cb71cdf 100644 --- a/src/components/color-picker/common.ts +++ b/src/components/color-picker/common.ts @@ -1,11 +1,82 @@ -import { asNumber } from '#internals/utils/math.js'; +import { asNumber, clamp } from '#internals/utils/math.js'; import type { RGB } from './converters.js'; const RGBA_RE = /^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i; +const SRGB_RE = /^color\(srgb\s+(\S+)\s+(\S+)\s+(\S+?)(?:\s*\/\s*(\S+?))?\)$/i; const HEX_RE = /.{2}/g; const HEX_WITHOUT_HASH_RE = /^[0-9a-f]{3,4}$|^[0-9a-f]{6}$|^[0-9a-f]{8}$/i; +/** A canvas serialization in the legacy sRGB syntax: hex, `rgb()` or `rgba()`. */ +const LEGACY_RE = /^(?:#|rgba?\()/i; + +/** + * The colors that take their value from a context: the element + * (`currentcolor`), the page (`var()`), the color scheme (`light-dark()`) or + * the platform (the system colors). A color value must not change with its + * context, so they are invalid. + */ +const CONTEXT_COLORS = [ + 'currentcolor', + 'var', + 'light-dark', + // System colors + 'accentcolor', + 'accentcolortext', + 'activetext', + 'buttonborder', + 'buttonface', + 'buttontext', + 'canvas', + 'canvastext', + 'field', + 'fieldtext', + 'graytext', + 'highlight', + 'highlighttext', + 'linktext', + 'mark', + 'marktext', + 'selecteditem', + 'selecteditemtext', + 'visitedtext', + // Deprecated system colors + 'activeborder', + 'activecaption', + 'appworkspace', + 'background', + 'buttonhighlight', + 'buttonshadow', + 'captiontext', + 'inactiveborder', + 'inactivecaption', + 'inactivecaptiontext', + 'infobackground', + 'infotext', + 'menu', + 'menutext', + 'scrollbar', + 'threeddarkshadow', + 'threedface', + 'threedhighlight', + 'threedlightshadow', + 'threedshadow', + 'window', + 'windowframe', + 'windowtext', +]; + +/** + * Finds a context color as a whole CSS identifier, also inside a function such + * as `color-mix()`. The canvas of Chromium and WebKit resolves `currentcolor` + * to black and a system color to its light value, so this check runs before + * the canvas. + */ +const CONTEXT_COLOR_RE = new RegExp( + `(?:^|[^\\w-])(?:${CONTEXT_COLORS.join('|')})(?![\\w-])`, + 'i' +); + export interface ParsedColor { value: RGB; alpha: number; @@ -20,18 +91,20 @@ export function normalizeColor(colorString: string): string { return HEX_WITHOUT_HASH_RE.test(trimmed) ? `#${trimmed}` : trimmed; } -/** Parses a hex, rgb(a), hsl(a) or named color, or returns `null` for an invalid one. */ +/** + * Parses a CSS color into sRGB, or returns `null` for an invalid one or a + * color that depends on its context. + */ export function tryParseColor( colorString: string, ctx: OffscreenCanvasRenderingContext2D | null ): ParsedColor | null { - const serialized = serializeColor(normalizeColor(colorString), ctx); - return serialized === null ? null : fromSerialized(serialized); + return readColor(normalizeColor(colorString), ctx); } /** - * Parses a hex, rgb(a), hsl(a) or named color into RGB values and alpha. - * An invalid color, or no canvas context, gives black. + * Parses a CSS color into sRGB values and alpha. An invalid color, a color + * that depends on its context, or no canvas context gives black. */ export function parseColor( colorString: string, @@ -40,50 +113,103 @@ export function parseColor( return tryParseColor(colorString, ctx) ?? { value: [0, 0, 0], alpha: 1 }; } -/** Reads the RGB values and the alpha from a canvas serialization. */ -function fromSerialized(color: string): ParsedColor { - const result: ParsedColor = { - value: [0, 0, 0], - alpha: 1, - }; +/** Whether a string is a valid CSS color that does not depend on its context. */ +export function isValidColor( + colorString: string, + ctx: OffscreenCanvasRenderingContext2D | null +): boolean { + return readColor(colorString, ctx) !== null; +} + +function readColor( + colorString: string, + ctx: OffscreenCanvasRenderingContext2D | null +): ParsedColor | null { + const serialized = serializeColor(colorString, ctx); + return serialized === null ? null : fromSerialized(serialized); +} + +/** + * Reads the RGB values and the alpha from a serialization of + * {@link serializeColor}, or returns `null` for another notation. + */ +function fromSerialized(color: string): ParsedColor | null { + const srgbMatch = SRGB_RE.exec(color); + + if (srgbMatch) { + // A channel outside 0-1 is outside the sRGB gamut, so it clips. + // `none` reads as 0. + const [r, g, b] = srgbMatch + .slice(1, 4) + .map((part) => clamp(Math.round(asNumber(part) * 255), 0, 255)); + const alpha = srgbMatch[4]; + + return { + value: [r, g, b], + alpha: alpha === undefined ? 1 : clamp(asNumber(alpha), 0, 1), + }; + } const rgbaMatch = RGBA_RE.exec(color); if (rgbaMatch) { const [r, g, b, a] = rgbaMatch.slice(3).map((part) => asNumber(part)); - result.value = [r, g, b]; - result.alpha = a ?? 1; - } else { - const hexValue = color.replace('#', ''); - const matches = hexValue.match(HEX_RE); - - if (!matches) { - return result; - } - - const [r, g, b, a] = matches.map((part) => Number.parseInt(part, 16)); - result.value = [r, g, b]; - - if (matches.length === 4 && a !== undefined) { - result.alpha = a / 255; - } + return { value: [r, g, b], alpha: a ?? 1 }; } - return result; + if (!color.startsWith('#')) { + return null; + } + + const matches = color.slice(1).match(HEX_RE); + + if (!matches) { + return null; + } + + const [r, g, b, a] = matches.map((part) => Number.parseInt(part, 16)); + + return { + value: [r, g, b], + alpha: matches.length === 4 && a !== undefined ? a / 255 : 1, + }; } /** - * The canvas serialization of a valid color, or `null`. An invalid color - * leaves the fill unchanged, so two baselines differ. + * The serialization of a valid color as hex, `rgb()`, `rgba()` or + * `color(srgb r g b / a)`, or `null`. + * + * Chromium and WebKit keep the notation of a color outside the legacy sRGB + * syntax, such as `oklch()`, `lab()` or `color(display-p3 ...)`. Relative color + * syntax converts it to `color(srgb ...)`, where a color outside the sRGB gamut + * has channels outside 0-1. Firefox serializes every color as hex or `rgba()`. + * + * The relative color wraps the serialization of the canvas, not the input, so + * text in the input, such as an open comment, cannot change the color. */ function serializeColor( colorString: string, ctx: OffscreenCanvasRenderingContext2D | null ): string | null { - if (!colorString?.trim() || !ctx) { + if (!colorString?.trim() || !ctx || CONTEXT_COLOR_RE.test(colorString)) { return null; } + const serialized = canvasSerialize(colorString, ctx); + + return serialized === null || LEGACY_RE.test(serialized) + ? serialized + : canvasSerialize(`color(from ${serialized} srgb r g b / alpha)`, ctx); +} + +/** + * The canvas serialization of a valid color, or `null`. An invalid color + * leaves the fill unchanged, so two baselines differ. + */ +function canvasSerialize( + colorString: string, + ctx: OffscreenCanvasRenderingContext2D +): string | null { ctx.fillStyle = '#000'; ctx.fillStyle = colorString; const onBlack = ctx.fillStyle; @@ -94,11 +220,3 @@ function serializeColor( return onBlack === onWhite ? onBlack : null; } - -/** Whether a string is a valid CSS color. */ -export function isValidColor( - colorString: string, - ctx: OffscreenCanvasRenderingContext2D | null -): boolean { - return serializeColor(colorString, ctx) !== null; -} diff --git a/src/components/color-picker/contrast.property.spec.ts b/src/components/color-picker/contrast.property.spec.ts new file mode 100644 index 000000000..dc7278402 --- /dev/null +++ b/src/components/color-picker/contrast.property.spec.ts @@ -0,0 +1,23 @@ +import { expect } from '@open-wc/testing'; + +import { fc } from '#internals/testing/fast-check-setup.spec.js'; +import { contrastRatio } from './contrast.js'; +import { ColorModel } from './model.js'; + +const byte = fc.integer({ min: 0, max: 255 }); +const opaque = fc + .tuple(byte, byte, byte) + .map(([r, g, b]) => ColorModel.parse(`rgb(${r} ${g} ${b})`)); + +describe('Contrast ratio properties', () => { + it('is from 1 to 21 and the same for both orders of two opaque colors', () => { + fc.assert( + fc.property(opaque, opaque, (a, b) => { + const value = contrastRatio(a, b); + + expect(value).to.be.within(1, 21 + 1e-9); + expect(contrastRatio(b, a)).to.be.closeTo(value, 1e-9); + }) + ); + }); +}); diff --git a/src/components/color-picker/contrast.spec.ts b/src/components/color-picker/contrast.spec.ts new file mode 100644 index 000000000..c8c694ccb --- /dev/null +++ b/src/components/color-picker/contrast.spec.ts @@ -0,0 +1,40 @@ +import { expect } from '@open-wc/testing'; + +import { contrastRatio, formatContrastRatio } from './contrast.js'; +import { type ColorPickerStrings, colorPickerI18nConfig } from './i18n.js'; +import { ColorModel } from './model.js'; + +const resourceStrings = colorPickerI18nConfig.defaultEN as ColorPickerStrings; + +function ratio(color: string, background: string): number { + return contrastRatio(ColorModel.parse(color), ColorModel.parse(background)); +} + +describe('Contrast ratio', () => { + it('gives the WCAG 2 ratio of two opaque colors', () => { + expect(ratio('#000', '#fff')).to.be.closeTo(21, 1e-9); + expect(ratio('#808080', '#808080')).to.equal(1); + expect(ratio('#767676', '#fff')).to.be.closeTo(4.5422, 1e-4); + expect(ratio('#777777', '#fff')).to.be.closeTo(4.4781, 1e-4); + expect(ratio('#595959', '#fff')).to.be.closeTo(7.0047, 1e-4); + }); + + it('puts the color over the background with its alpha', () => { + // Half black over white is #808080 with a channel of 127.5. + expect(ratio('rgb(0 0 0 / 0.5)', '#fff')).to.be.closeTo(3.9767, 1e-4); + expect(ratio('rgb(0 0 0 / 0)', '#fff')).to.equal(1); + }); + + it('puts the background over white with its alpha', () => { + expect(ratio('#000', 'transparent')).to.be.closeTo(21, 1e-9); + expect(ratio('#fff', 'rgb(0 0 0 / 0.5)')).to.be.closeTo(3.9767, 1e-4); + }); + + it('formats the ratio with two decimals at most, cut and not rounded', () => { + const i18n = { resourceStrings, locale: 'en' }; + + expect(formatContrastRatio(4.4999, i18n)).to.equal('Contrast 4.49:1'); + expect(formatContrastRatio(4.5422, i18n)).to.equal('Contrast 4.54:1'); + expect(formatContrastRatio(21, i18n)).to.equal('Contrast 21:1'); + }); +}); diff --git a/src/components/color-picker/contrast.ts b/src/components/color-picker/contrast.ts new file mode 100644 index 000000000..4ab124d86 --- /dev/null +++ b/src/components/color-picker/contrast.ts @@ -0,0 +1,58 @@ +import { getNumberFormatter } from 'igniteui-i18n-core'; +import { formatString } from '#internals/utils/strings.js'; +import { linearize, type RGB } from './converters.js'; +import type { ColorPickerI18n } from './i18n.js'; +import type { ColorModel } from './model.js'; + +/** The WCAG 2 levels for normal text. */ +export const CONTRAST_LEVELS = [ + { nameKey: 'color_picker_contrast_aa', minimumRatio: 4.5 }, + { nameKey: 'color_picker_contrast_aaa', minimumRatio: 7 }, +] as const; + +const WHITE: RGB = [255, 255, 255]; + +/** A color with its alpha over an opaque color, as the browser paints in sRGB. */ +function composite(top: RGB, alpha: number, bottom: RGB): RGB { + return top.map( + (channel, i) => channel * alpha + bottom[i] * (1 - alpha) + ) as RGB; +} + +/** The WCAG 2 relative luminance of an sRGB color, from 0 to 1. */ +function luminance(rgb: RGB): number { + const [r, g, b] = rgb.map(linearize); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +/** + * The WCAG 2 contrast ratio of a color over a background, from 1 to 21. The + * background goes over white and the color over the background, each with its + * alpha. + */ +export function contrastRatio( + color: ColorModel, + background: ColorModel +): number { + const bottom = composite(background.toRGB(), background.alpha, WHITE); + const top = luminance(composite(color.toRGB(), color.alpha, bottom)); + const base = luminance(bottom); + + return (Math.max(top, base) + 0.05) / (Math.min(top, base) + 0.05); +} + +/** + * The text of a contrast ratio, such as "Contrast 4.54:1". The ratio is cut to + * two decimals, so it never reads as a level that it fails. + */ +export function formatContrastRatio( + ratio: number, + { resourceStrings, locale }: ColorPickerI18n +): string { + const value = getNumberFormatter().formatNumber(ratio, locale, { + maximumFractionDigits: 2, + roundingMode: 'trunc', + }); + + return formatString(resourceStrings.color_picker_contrast_ratio, value); +} diff --git a/src/components/color-picker/converters.spec.ts b/src/components/color-picker/converters.spec.ts index a8ce1dc82..b1cd92a53 100644 --- a/src/components/color-picker/converters.spec.ts +++ b/src/components/color-picker/converters.spec.ts @@ -1,7 +1,13 @@ import { expect } from '@open-wc/testing'; import { expectCloseTo } from '#internals/testing/helpers.spec.js'; -import { converter, type HSL, type HSV, type RGB } from './converters.js'; +import { + converter, + type HSL, + type HSV, + type OKLCH, + type RGB, +} from './converters.js'; /** Tolerance for the accumulated float error of a conversion round-trip. */ const EPSILON = 0.5; @@ -65,6 +71,43 @@ describe('Color converters', () => { }); }); + describe('rgb -> oklch', () => { + const tolerance = 1e-4; + + // The values of the CSS Color 4 sample code. + it('converts known colors', () => { + for (const [rgb, oklch] of [ + [ + [255, 0, 0], + [62.7955, 0.25768, 29.2339], + ], + [ + [0, 255, 0], + [86.644, 0.29483, 142.4953], + ], + [ + [0, 0, 255], + [45.2014, 0.31321, 264.052], + ], + ] as [RGB, OKLCH][]) { + expectTupleCloseTo(converter.rgb.oklch(rgb), oklch, tolerance); + } + }); + + it('reports no chroma for achromatic colors', () => { + for (const [gray, lightness] of [ + [0, 0], + [128, 59.9871], + [255, 100], + ]) { + const [l, c] = converter.rgb.oklch([gray, gray, gray]); + + expect(l, `${gray}`).to.be.closeTo(lightness, tolerance); + expect(c, `${gray}`).to.be.below(1e-6); + } + }); + }); + describe('hsl -> hsv', () => { it('converts colors at or below 50% lightness', () => { expectTupleCloseTo(converter.hsl.hsv([120, 100, 50]), [120, 100, 100]); diff --git a/src/components/color-picker/converters.ts b/src/components/color-picker/converters.ts index 085f6a1f1..ce48e9525 100644 --- a/src/components/color-picker/converters.ts +++ b/src/components/color-picker/converters.ts @@ -1,4 +1,4 @@ -import { clamp } from '#internals/utils/math.js'; +import { clamp, modulo } from '#internals/utils/math.js'; const ONE_THIRD = 1 / 3; const TWO_THIRDS = 2 / 3; @@ -6,6 +6,121 @@ const TWO_THIRDS = 2 / 3; export type RGB = [number, number, number]; export type HSL = [number, number, number]; export type HSV = [number, number, number]; +export type OKLCH = [number, number, number]; + +/** + * Linear sRGB to LMS: the product of the sRGB to XYZ and the XYZ to LMS + * matrices of CSS Color 4, as Firefox and Safari convert. + */ +const LINEAR_SRGB_TO_LMS = [ + [0.41222146947076305, 0.5363325372617348, 0.05144599326750221], + [0.21190349581782522, 0.6806995506452344, 0.10739695353694056], + [0.08830245919005643, 0.2817188391361215, 0.6299787016738222], +]; + +const LMS_TO_OKLAB = [ + [0.210454268309314, 0.7936177747023054, -0.0040720430116193], + [1.9779985324311684, -2.4285922420485799, 0.450593709617411], + [0.0259040424655478, 0.7827717124575296, -0.8086757549230774], +]; + +function multiply3x3(matrix: number[][], [x, y, z]: number[]): number[] { + return matrix.map((row) => row[0] * x + row[1] * y + row[2] * z); +} + +function invert3x3([ + [a, b, c], + [d, e, f], + [g, h, i], +]: readonly number[][]): number[][] { + const det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g); + + return [ + [(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det], + [(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det], + [(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; +} + +// The exact inverses, so an OKLCH color converts back to the same sRGB. +/** OKLab to the cube roots of LMS. */ +export const OKLAB_TO_LMS: readonly number[][] = invert3x3(LMS_TO_OKLAB); +/** LMS to linear sRGB. */ +export const LMS_TO_LINEAR_SRGB: readonly number[][] = + invert3x3(LINEAR_SRGB_TO_LMS); + +// Scalars, not arrays: a paint of the OKLCH area converts every pixel. Each +// name gives the output and the input: `lFromA` is the weight of `a` in L. +const [ + [lFromLightness, lFromA, lFromB], + [mFromLightness, mFromA, mFromB], + [sFromLightness, sFromA, sFromB], +] = OKLAB_TO_LMS; +const [ + [redFromL, redFromM, redFromS], + [greenFromL, greenFromM, greenFromS], + [blueFromL, blueFromM, blueFromS], +] = LMS_TO_LINEAR_SRGB; + +/** + * The linear sRGB channels (0-1) of an OKLab color with a lightness of 0-1. + * A color outside sRGB has channels outside 0-1. Writes into `out`, so a loop + * over many pixels makes no arrays. + */ +export function oklabToLinearSrgb( + lightness: number, + a: number, + b: number, + out: number[] = [0, 0, 0] +): number[] { + const lRoot = lFromLightness * lightness + lFromA * a + lFromB * b; + const mRoot = mFromLightness * lightness + mFromA * a + mFromB * b; + const sRoot = sFromLightness * lightness + sFromA * a + sFromB * b; + const long = lRoot * lRoot * lRoot; + const medium = mRoot * mRoot * mRoot; + const short = sRoot * sRoot * sRoot; + + out[0] = redFromL * long + redFromM * medium + redFromS * short; + out[1] = greenFromL * long + greenFromM * medium + greenFromS * short; + out[2] = blueFromL * long + blueFromM * medium + blueFromS * short; + return out; +} + +/** The cosine and sine of a hue in degrees: its direction on the a-b plane. */ +export function hueDirection(hue: number): [cos: number, sin: number] { + const angle = (hue * Math.PI) / 180; + return [Math.cos(angle), Math.sin(angle)]; +} + +/** The alpha part of a CSS color function, such as ` / 0.5`, or `''` for none. */ +export function alphaPart(alpha: number | null): string { + return alpha === null ? '' : ` / ${alpha}`; +} + +/** Formats RGB channels (0-255) and an optional alpha as a CSS `rgb()` color. */ +export function rgbString(rgb: RGB, alpha: number | null = null): string { + const [r, g, b] = rgb.map(Math.round); + return `rgb(${r} ${g} ${b}${alphaPart(alpha)})`; +} + +/** An sRGB channel (0-255) in linear light (0-1). */ +export function linearize(channel: number): number { + const c = channel / 255; + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +} + +/** + * A channel in linear light (0-1) as an sRGB channel (0-255): the inverse of + * `linearize`. + */ +export function delinearize(channel: number): number { + const c = + channel <= 0.0031308 + ? channel * 12.92 + : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055; + + return c * 255; +} export const converter = Object.freeze({ rgb: { @@ -82,6 +197,26 @@ export const converter = Object.freeze({ return [h * 360, s * 100, v * 100]; }, + /** Lightness (0-100), chroma (0 to about 0.32 in sRGB) and hue (0-360). */ + oklch: (rgb: RGB): OKLCH => { + const lms = multiply3x3(LINEAR_SRGB_TO_LMS, rgb.map(linearize)); + const [l, a, b] = multiply3x3(LMS_TO_OKLAB, lms.map(Math.cbrt)); + const h = (Math.atan2(b, a) * 180) / Math.PI; + + return [l * 100, Math.hypot(a, b), modulo(h, 360)]; + }, + }, + oklch: { + /** + * The sRGB channels (0-255) of a lightness (0-100), chroma and hue (0-360). + * A color outside sRGB gives channels outside 0-255. + */ + rgb: ([l, c, h]: OKLCH): RGB => { + const [cos, sin] = hueDirection(h); + const linear = oklabToLinearSrgb(l / 100, c * cos, c * sin); + + return linear.map(delinearize) as RGB; + }, }, hsl: { rgb: (hsl: HSL): RGB => { diff --git a/src/components/color-picker/i18n.ts b/src/components/color-picker/i18n.ts new file mode 100644 index 000000000..ddf6ec8cf --- /dev/null +++ b/src/components/color-picker/i18n.ts @@ -0,0 +1,181 @@ +import { + ColorPickerResourceStringsEN, + type IColorPickerResourceStrings, +} from 'igniteui-i18n-core'; +import type { I18nMixinConfig } from '#internals/mixins/i18n.js'; +import type { ColorFormat } from '../types.js'; + +/** + * The color picker strings that `igniteui-i18n-core` does not ship yet. Until + * it does, every locale shows the English text. + * + * TODO: remove when `IColorPickerResourceStrings` has these keys. + */ +export interface IgcColorPickerPendingResourceStrings { + /** The name of a no-color swatch without a label. */ + color_picker_no_color?: string; + /** The name of the swatch list. */ + color_picker_swatches?: string; + /** The text of the view switcher button of the gradient view. */ + color_picker_view_gradient?: string; + /** The text of the view switcher button of the swatch view. */ + color_picker_view_swatches?: string; + /** The name of the hex format in the format select. */ + color_picker_format_hex?: string; + /** The name of the RGB format in the format select. */ + color_picker_format_rgb?: string; + /** The name of the HSL format in the format select. */ + color_picker_format_hsl?: string; + /** The name of the OKLCH format in the format select. */ + color_picker_format_oklch?: string; + /** The name of the clear icon in input mode. */ + color_picker_clear?: string; + /** The text of the Apply button of the confirm mode. */ + color_picker_apply?: string; + /** The text of the Cancel button of the confirm mode. */ + color_picker_cancel?: string; + /** The name of the preview button that restores the initial color. */ + color_picker_initial_color?: string; + /** The name of the copy button after a copy. */ + color_picker_copied?: string; + /** The name of the copy button after a failed copy. */ + color_picker_copy_failed?: string; + /** The word order of a color name: `{0}` lightness, `{1}` chroma, `{2}` hue. */ + color_picker_name_pattern?: string; + /** A color name with its alpha: `{0}` name, `{1}` percentage. */ + color_picker_name_with_alpha?: string; + /** A slider value text with a color name: `{0}` value, `{1}` name. */ + color_picker_value_with_name?: string; + /** The lightness word "very dark" of a color name. */ + color_picker_name_very_dark?: string; + /** The lightness word "dark" of a color name. */ + color_picker_name_dark?: string; + /** The lightness word "light" of a color name. */ + color_picker_name_light?: string; + /** The lightness word "very light" of a color name. */ + color_picker_name_very_light?: string; + /** The chroma word "grayish" of a color name. */ + color_picker_name_grayish?: string; + /** The chroma word "vibrant" of a color name. */ + color_picker_name_vibrant?: string; + /** The hue word "red" of a color name. */ + color_picker_name_red?: string; + /** The hue word "orange" of a color name. */ + color_picker_name_orange?: string; + /** The hue word "brown" of a color name: a dark orange. */ + color_picker_name_brown?: string; + /** The hue word "yellow" of a color name. */ + color_picker_name_yellow?: string; + /** The hue word "yellow green" of a color name. */ + color_picker_name_yellow_green?: string; + /** The hue word "green" of a color name. */ + color_picker_name_green?: string; + /** The hue word "cyan" of a color name. */ + color_picker_name_cyan?: string; + /** The hue word "blue" of a color name. */ + color_picker_name_blue?: string; + /** The hue word "purple" of a color name. */ + color_picker_name_purple?: string; + /** The hue word "magenta" of a color name. */ + color_picker_name_magenta?: string; + /** The hue word "pink" of a color name. */ + color_picker_name_pink?: string; + /** The name "black" of a very dark color with almost no chroma. */ + color_picker_name_black?: string; + /** The name "white" of a very light color with almost no chroma. */ + color_picker_name_white?: string; + /** The hue word "gray" of a color with almost no chroma. */ + color_picker_name_gray?: string; + /** The contrast ratio of the value over `contrastAgainst`: `{0}` ratio. */ + color_picker_contrast_ratio?: string; + /** A WCAG level that the contrast ratio passes: `{0}` level name. */ + color_picker_contrast_pass?: string; + /** A WCAG level that the contrast ratio fails: `{0}` level name. */ + color_picker_contrast_fail?: string; + /** The name of the WCAG level AA (contrast 4.5:1). */ + color_picker_contrast_aa?: string; + /** The name of the WCAG level AAA (contrast 7:1). */ + color_picker_contrast_aaa?: string; + /** The name of the area marker in the OKLCH format. */ + color_picker_canvas_oklch_label?: string; + /** The value text of the area marker in the OKLCH format: `{0}` lightness, `{1}` chroma. */ + color_picker_canvas_oklch_value?: string; +} + +/** The resource strings of the color picker and the color panel. */ +export type IgcColorPickerResourceStrings = IColorPickerResourceStrings & + IgcColorPickerPendingResourceStrings; + +/** The resolved strings: every key has a value. */ +export type ColorPickerStrings = Required; + +/** The strings and the locale of a color picker or a color panel. */ +export interface ColorPickerI18n { + readonly resourceStrings: ColorPickerStrings; + readonly locale: string; +} + +const PendingResourceStringsEN: Required = + { + color_picker_no_color: 'No color', + color_picker_swatches: 'Color swatches', + color_picker_view_gradient: 'Gradient', + color_picker_view_swatches: 'Swatches', + color_picker_format_hex: 'Hex', + color_picker_format_rgb: 'RGB', + color_picker_format_hsl: 'HSL', + color_picker_format_oklch: 'OKLCH', + color_picker_clear: 'Clear color', + color_picker_apply: 'Apply', + color_picker_cancel: 'Cancel', + color_picker_initial_color: 'Initial color', + color_picker_copied: 'Copied', + color_picker_copy_failed: 'Copy failed', + color_picker_name_pattern: '{0} {1} {2}', + color_picker_name_with_alpha: '{0}, alpha {1}', + color_picker_value_with_name: '{0}, {1}', + color_picker_name_very_dark: 'very dark', + color_picker_name_dark: 'dark', + color_picker_name_light: 'light', + color_picker_name_very_light: 'very light', + color_picker_name_grayish: 'grayish', + color_picker_name_vibrant: 'vibrant', + color_picker_name_red: 'red', + color_picker_name_orange: 'orange', + color_picker_name_brown: 'brown', + color_picker_name_yellow: 'yellow', + color_picker_name_yellow_green: 'yellow green', + color_picker_name_green: 'green', + color_picker_name_cyan: 'cyan', + color_picker_name_blue: 'blue', + color_picker_name_purple: 'purple', + color_picker_name_magenta: 'magenta', + color_picker_name_pink: 'pink', + color_picker_name_black: 'black', + color_picker_name_white: 'white', + color_picker_name_gray: 'gray', + color_picker_contrast_ratio: 'Contrast {0}:1', + color_picker_contrast_pass: '{0} pass', + color_picker_contrast_fail: '{0} fail', + color_picker_contrast_aa: 'AA', + color_picker_contrast_aaa: 'AAA', + color_picker_canvas_oklch_label: 'Lightness and chroma', + color_picker_canvas_oklch_value: 'Lightness {0}%, chroma {1}', + }; + +/** The resource string of the name of each format in the format select. */ +export const formatNameKeys = { + hex: 'color_picker_format_hex', + rgb: 'color_picker_format_rgb', + hsl: 'color_picker_format_hsl', + oklch: 'color_picker_format_oklch', +} as const satisfies Record; + +/** The i18n configuration that the color picker and the color panel share. */ +export const colorPickerI18nConfig: I18nMixinConfig = + { + defaultEN: { + ...ColorPickerResourceStringsEN, + ...PendingResourceStringsEN, + }, + }; diff --git a/src/components/color-picker/model.spec.ts b/src/components/color-picker/model.spec.ts index 269d06d58..f04ad4696 100644 --- a/src/components/color-picker/model.spec.ts +++ b/src/components/color-picker/model.spec.ts @@ -1,6 +1,7 @@ import { expect } from '@open-wc/testing'; import { ColorModel } from './model.js'; +import { cuspHsvHue, gamutChroma, pureHueOklch } from './oklch.js'; describe('ColorModel', () => { describe('constructor and factory methods', () => { @@ -129,6 +130,32 @@ describe('ColorModel', () => { expect(color.isEmpty).to.be.true; }); + + it('parses a color outside the legacy syntax into sRGB', () => { + const color = ColorModel.parse('oklch(70% 0.1 200 / 0.5)'); + + expect(color.toRGB()).to.deep.equal([64, 177, 183]); + expect(color.alpha).to.equal(0.5); + expect(color.asString('hex')).to.equal('#40b1b780'); + }); + + it('clips a color outside the sRGB gamut', () => { + expect(ColorModel.parse('color(display-p3 1 0 0)').toRGB()).to.deep.equal( + [255, 0, 0] + ); + }); + + it('returns an empty color for a color that depends on its context', () => { + for (const value of [ + 'currentcolor', + 'var(--brand)', + 'light-dark(red, blue)', + 'Canvas', + 'color-mix(in srgb, currentcolor, red)', + ]) { + expect(ColorModel.parse(value).isEmpty, value).to.be.true; + } + }); }); describe('RGB property setters', () => { @@ -403,6 +430,36 @@ describe('ColorModel', () => { expect(hslString).to.match(/^hsl\(\d+ \d+% \d+%\)$/); }); }); + + describe('oklch format', () => { + it('writes the lightness in percent, the chroma and the hue', () => { + for (const [rgb, oklch] of [ + [[255, 0, 0], 'oklch(62.8% 0.25768 29.23)'], + [[63, 81, 181], 'oklch(47.82% 0.15892 271.4)'], + // A gray has no hue. + [[0, 0, 0], 'oklch(0% 0 0)'], + [[128, 128, 128], 'oklch(59.99% 0 0)'], + [[255, 255, 255], 'oklch(100% 0 0)'], + // A hue of 359.9992 rounds to 360. + [[48, 1, 21], 'oklch(20.21% 0.07918 0)'], + ] as const) { + expect(new ColorModel([...rgb]).asString('oklch')).to.equal(oklch); + } + }); + + it('writes the alpha when it is below 1 or forced', () => { + const color = new ColorModel([255, 0, 0], 0.5); + + expect(color.asString('oklch')).to.equal( + 'oklch(62.8% 0.25768 29.23 / 0.5)' + ); + + color.alpha = 1; + expect(color.asString('oklch', true)).to.equal( + 'oklch(62.8% 0.25768 29.23 / 1)' + ); + }); + }); }); describe('color space conversions', () => { @@ -617,4 +674,85 @@ describe('ColorModel', () => { expect(color.r).to.equal(128); }); }); + + describe('OKLCH space', () => { + it('keeps the OKLCH lightness, chroma and hue of a color', () => { + const [l, c, h] = ColorModel.parse('#0000ff').toOKLCH(); + + expect(l).to.be.closeTo(45.2, 0.05); + expect(c).to.be.closeTo(0.3132, 1e-4); + expect(h).to.be.closeTo(264.05, 0.01); + }); + + it('sets the lightness and chroma and keeps the hue', () => { + const color = ColorModel.parse('#808080'); + + color.setOklchHue(140); + color.setLightnessAndChroma(70, 0.05); + + expect(color.toOKLCH()).to.eql([70, 0.05, 140]); + expect(color.asString('oklch')).to.equal('oklch(70% 0.05 140)'); + }); + + it('keeps the lightness and cuts a chroma beyond the gamut back to the edge', () => { + const color = ColorModel.parse('#808080'); + + color.setOklchHue(110); + color.setLightnessAndChroma(99, 0.25); + + const [l, c] = color.toOKLCH(); + + expect(l).to.equal(99); + expect(c).to.equal(gamutChroma([99, 0.25, 110])); + expect(c).to.be.below(0.25); + }); + + it('cuts the chroma for a hue with less gamut', () => { + const color = ColorModel.parse('#ff00ff'); + const [l, c] = color.toOKLCH(); + + color.setOklchHue(110); + + expect(color.toOKLCH()).to.eql([l, gamutChroma([l, c, 110]), 110]); + }); + + it('keeps the OKLCH hue of a gray, and gives HSV the hue of its cusp', () => { + const color = ColorModel.parse('#808080'); + + color.setOklchHue(264); + color.setLightnessAndChroma(50, 0); + + expect(color.toOKLCH()[2]).to.equal(264); + expect(color.toHSV()[0]).to.be.closeTo(cuspHsvHue(264), 1e-6); + expect(color.toHSV()[1]).to.equal(0); + expect(color.h).to.be.closeTo(cuspHsvHue(264), 1e-6); + }); + + it('gives a gray from HSV the OKLCH hue of the cusp of its HSV hue', () => { + const color = ColorModel.fromHSV(210, 50, 50); + + color.setSaturationAndValue(0, 50); + + expect(color.toOKLCH()[1]).to.equal(0); + expect(color.toOKLCH()[2]).to.be.closeTo(pureHueOklch(210)[2], 1e-9); + }); + + it('starts an empty color at white with the OKLCH hue of red', () => { + const [l, c, h] = ColorModel.empty().toOKLCH(); + + expect(l).to.be.closeTo(100, 1e-6); + expect(c).to.equal(0); + expect(h).to.be.closeTo(pureHueOklch(0)[2], 1e-9); + }); + + it('keeps the hues of a gray in a clone', () => { + const color = ColorModel.fromHSV(210, 50, 50); + color.setSaturationAndValue(0, 50); + + const clone = color.clone(); + + expect(clone.toHSV()).to.eql(color.toHSV()); + expect(clone.toOKLCH()).to.eql(color.toOKLCH()); + }); + }); }); diff --git a/src/components/color-picker/model.ts b/src/components/color-picker/model.ts index c4a5fdccd..49674d653 100644 --- a/src/components/color-picker/model.ts +++ b/src/components/color-picker/model.ts @@ -1,7 +1,21 @@ -import { clamp } from '#internals/utils/math.js'; +import { clamp, roundPrecise } from '#internals/utils/math.js'; import type { ColorFormat } from '../types.js'; import { tryParseColor } from './common.js'; -import { converter, type HSL, type HSV, type RGB } from './converters.js'; +import { + alphaPart, + converter, + type HSL, + type HSV, + type OKLCH, + type RGB, + rgbString, +} from './converters.js'; +import { + cuspHsvHue, + gamutChroma, + isAchromatic, + pureHueOklch, +} from './oklch.js'; export type { ColorFormat }; @@ -23,19 +37,56 @@ function makeCanvasContext() { } export const getContext = makeCanvasContext(); -/** Formats RGB channels (0-255) and an optional alpha as a CSS `rgb()` color. */ -export function rgbString(rgb: RGB, alpha: number | null = null): string { - const [r, g, b] = rgb.map(Math.round); - return `rgb(${r} ${g} ${b}${alpha === null ? '' : ` / ${alpha}`})`; +/** The color string shape of each format. Shown while a color text is empty. */ +export const formatPlaceholders: Record = { + hex: '#rrggbb', + rgb: 'rgb(r g b)', + hsl: 'hsl(h s% l%)', + oklch: 'oklch(l% c h)', +}; + +/** + * The formats in the key order of `formatPlaceholders`, which is the order of + * the format select. + */ +export const colorFormats = Object.keys( + formatPlaceholders +) as readonly ColorFormat[]; + +/** + * A color with its alpha in one notation, to compare two colors. The empty + * key is no color. + */ +export type ColorKey = string; + +export function colorKey(color: ColorModel): ColorKey { + return color.asString('rgb', true); +} + +/** The color with an opaque alpha. An empty color gives white. */ +export function opaqueColor(color: ColorModel): string { + return rgbString(color.toRGB()); +} + +/** + * The color of a committed color text. An empty text gives an empty color. An + * invalid text gives `null`: the input shows the current color again. + */ +export function parseTypedColor(text: string | undefined): ColorModel | null { + const color = ColorModel.parse(text ?? ''); + return color.isEmpty && text?.trim() ? null : color; } /** - * A color that keeps its RGB, HSL and HSV values in sync. + * A color that keeps its RGB, HSL, HSV and OKLCH values in sync. A gray keeps + * the hue that the user set, and the HSV and OKLCH hues of a gray match + * through the cusp of the hue. */ export class ColorModel { private _rgb: RGB; private _hsl: HSL; private _hsv: HSV; + private _oklch: OKLCH; private _alpha: number; private _empty = false; @@ -56,8 +107,9 @@ export class ColorModel { } /** - * Parses a hex, rgb(a), hsl(a) or named color. - * An empty or invalid string gives an empty color. + * Parses a CSS color into sRGB. A color outside the sRGB gamut clips. An + * empty or invalid string, or a color that depends on its context, such as + * `currentcolor`, gives an empty color. */ public static parse(color: string): ColorModel { const parsed = tryParseColor(color, getContext()); @@ -93,6 +145,7 @@ export class ColorModel { this._rgb = [value[0], value[1], value[2]]; this._hsl = converter.rgb.hsl(this._rgb); this._hsv = converter.rgb.hsv(this._rgb); + this._oklch = this._oklchFromRgb(); this._alpha = clamp(alpha, 0, 1); } @@ -101,12 +154,11 @@ export class ColorModel { return this._empty; } - /** Rebuilds the two color spaces that were not the one just written to. */ + /** Rebuilds the color spaces that were not the one just written to. */ private _syncFrom(space: ColorSpace): void { switch (space) { case 'rgb': - this._hsl = converter.rgb.hsl(this._rgb); - this._hsv = converter.rgb.hsv(this._rgb); + this._syncHslHsv(); break; case 'hsl': this._rgb = converter.hsl.rgb(this._hsl); @@ -117,6 +169,46 @@ export class ColorModel { this._hsl = converter.hsv.hsl(this._hsv); break; } + + this._oklch = this._oklchFromRgb(); + } + + /** Rebuilds HSL and HSV from RGB. */ + private _syncHslHsv(): void { + this._hsl = converter.rgb.hsl(this._rgb); + this._hsv = converter.rgb.hsv(this._rgb); + } + + /** The OKLCH values of the RGB channels. A gray takes the hue of its HSV cusp. */ + private _oklchFromRgb(): OKLCH { + const oklch = converter.rgb.oklch(this._rgb); + + if (isAchromatic(oklch[1])) { + oklch[1] = 0; + oklch[2] = pureHueOklch(this._hsv[0])[2]; + } + + return oklch; + } + + /** Rebuilds RGB, HSL and HSV. A gray takes the HSV hue of its OKLCH cusp. */ + private _syncFromOklch(): void { + const rgb = converter.oklch + .rgb(this._oklch) + .map((channel) => clamp(channel, 0, 255)) as RGB; + const gray = isAchromatic(this._oklch[1]); + + if (gray) { + // Rounding leaves the channels a little apart, which gives a gray a hue. + rgb.fill((rgb[0] + rgb[1] + rgb[2]) / 3); + } + + this._rgb = rgb; + this._syncHslHsv(); + + if (gray) { + this._hsl[0] = this._hsv[0] = cuspHsvHue(this._oklch[2]); + } } /** Writes one channel and syncs the other color spaces. */ @@ -128,7 +220,7 @@ export class ColorModel { ): void { this._empty = false; - // Safe to hold onto: `_syncFrom` only replaces the *other* two tuples. + // Safe to hold onto: `_syncFrom` only replaces the *other* tuples. const channels = space === 'rgb' ? this._rgb : space === 'hsl' ? this._hsl : this._hsv; @@ -223,6 +315,44 @@ export class ColorModel { this._syncFrom('hsv'); } + /** Writes OKLCH values and returns whether the gamut edge cut the chroma. */ + private _setOklch(color: OKLCH): boolean { + const [lightness, chroma, hue] = color; + const inGamut = gamutChroma(color); + + this._empty = false; + this._oklch = [lightness, inGamut, hue]; + this._syncFromOklch(); + return inGamut < chroma; + } + + /** + * Sets the OKLCH lightness and chroma in one update and keeps the hue and + * alpha. A chroma beyond the sRGB gamut is cut back to the gamut edge. + * + * @param lightness - OKLCH lightness (0-100) + * @param chroma - OKLCH chroma (0 and up) + * @returns Whether the chroma was cut. + */ + public setLightnessAndChroma(lightness: number, chroma: number): boolean { + return this._setOklch([ + clamp(lightness, 0, 100), + Math.max(chroma, 0), + this._oklch[2], + ]); + } + + /** + * Sets the OKLCH hue (0-360) and keeps the lightness and alpha. A chroma + * beyond the sRGB gamut at the new hue is cut back to the gamut edge. + * + * @returns Whether the chroma was cut. + */ + public setOklchHue(hue: number): boolean { + const [lightness, chroma] = this._oklch; + return this._setOklch([lightness, chroma, clamp(hue, 0, 360)]); + } + /** * Converts the color to a CSS color string. An empty color renders as an * empty string. @@ -249,13 +379,25 @@ export class ColorModel { return rgbString(this._rgb, alpha); case 'hsl': { const [h, s, l] = this._hsl.map(Math.round); - return `hsl(${h} ${s}% ${l}%${alpha === null ? '' : ` / ${alpha}`})`; + return `hsl(${h} ${s}% ${l}%${alphaPart(alpha)})`; + } + case 'oklch': { + // The fewest decimals that give every 8-bit color back in Firefox and + // Safari. Chromium uses other OKLab matrices and can be one step off. + const [l, c, h] = converter.rgb.oklch(this._rgb); + // A gray has no hue. + const hue = isAchromatic(c) ? 0 : roundPrecise(h, 2) % 360; + return `oklch(${roundPrecise(l, 2)}% ${roundPrecise(c, 5)} ${hue}${alphaPart(alpha)})`; } } } public clone(): ColorModel { const color = new ColorModel(this._rgb, this._alpha); + // The other spaces keep the hue of a gray. + color._hsl = [...this._hsl]; + color._hsv = [...this._hsv]; + color._oklch = [...this._oklch]; color._empty = this._empty; return color; } @@ -280,4 +422,9 @@ export class ColorModel { public toHSV(): HSV { return [...this._hsv]; } + + /** Lightness (0-100), chroma and hue (0-360). A gray keeps its hue. */ + public toOKLCH(): OKLCH { + return [...this._oklch]; + } } diff --git a/src/components/color-picker/oklch.property.spec.ts b/src/components/color-picker/oklch.property.spec.ts new file mode 100644 index 000000000..b0dc3d915 --- /dev/null +++ b/src/components/color-picker/oklch.property.spec.ts @@ -0,0 +1,45 @@ +import { expect } from '@open-wc/testing'; + +import { fc } from '#internals/testing/fast-check-setup.spec.js'; +import { expectCloseTo } from '#internals/testing/helpers.spec.js'; +import { converter } from './converters.js'; +import { gamutChroma } from './oklch.js'; + +const byte = fc.integer({ min: 0, max: 255 }); +const lightness = fc.double({ min: 0, max: 100, noNaN: true }); +const chroma = fc.double({ min: 0, max: 0.4, noNaN: true }); +const hue = fc.double({ min: 0, max: 359.999, noNaN: true }); + +describe('OKLCH gamut properties', () => { + it('cuts a chroma back into the sRGB gamut, never up', () => { + fc.assert( + fc.property(lightness, chroma, hue, (l, c, h) => { + const cut = gamutChroma([l, c, h]); + const rgb = converter.oklch.rgb([l, cut, h]); + + expect(cut).to.be.at.most(c); + for (const channel of rgb) { + expect(channel).to.be.within(-0.01, 255.01); + } + }) + ); + }); + + it('keeps the chroma of every 8-bit color', () => { + fc.assert( + fc.property(byte, byte, byte, (r, g, b) => { + const [l, c, h] = converter.rgb.oklch([r, g, b]); + expect(gamutChroma([l, c, h])).to.be.closeTo(c, 1e-9); + }) + ); + }); + + it('converts an 8-bit color to OKLCH and back', () => { + fc.assert( + fc.property(byte, byte, byte, (r, g, b) => { + const back = converter.oklch.rgb(converter.rgb.oklch([r, g, b])); + expectCloseTo(back, [r, g, b], 1e-6); + }) + ); + }); +}); diff --git a/src/components/color-picker/oklch.spec.ts b/src/components/color-picker/oklch.spec.ts new file mode 100644 index 000000000..52bb4f370 --- /dev/null +++ b/src/components/color-picker/oklch.spec.ts @@ -0,0 +1,170 @@ +import { expect } from '@open-wc/testing'; + +import { roundPrecise } from '#internals/utils/math.js'; +import { converter, type RGB } from './converters.js'; +import { + cusp, + cuspHsvHue, + gamutChroma, + gamutRuns, + isAchromatic, + OKLCH_AREA_CHROMA, + oklchHueTrack, + paintOklchArea, + pureHueOklch, +} from './oklch.js'; + +const BLUE = converter.rgb.oklch([0, 0, 255]); + +function round(values: readonly (readonly number[])[], digits = 4) { + return values.map((run) => run.map((value) => roundPrecise(value, digits))); +} + +describe('OKLCH gamut', () => { + it('gives one range from gray to the gamut edge for most rows', () => { + const red = converter.rgb.oklch([255, 0, 0]); + + expect(round(gamutRuns(red[0], red[2]))).to.eql([[0, 0.2577]]); + expect(round(gamutRuns(50, 140))).to.eql([[0, 0.161]]); + }); + + it('gives the black-to-blue edge as a spike apart from the rest', () => { + const [lightness, chroma, hue] = BLUE; + const runs = gamutRuns(lightness, hue); + + expect(runs).to.have.length(2); + expect(runs[1][0]).to.be.closeTo(chroma, 1e-6); + expect(runs[1][1]).to.be.closeTo(chroma, 1e-6); + }); + + it('gives only a gray at black and at white', () => { + for (const lightness of [0, 100]) { + const runs = gamutRuns(lightness, 120); + + expect(runs).to.have.length(1); + expect(runs[0][0]).to.equal(0); + expect(runs[0][1]).to.be.below(1e-6); + } + }); + + it('keeps a chroma in the gamut, and cuts one beyond it back to the nearest range below', () => { + const [lightness, chroma, hue] = BLUE; + const [[, bodyEnd]] = gamutRuns(lightness, hue); + + expect(gamutChroma([50, 0.1, 140])).to.equal(0.1); + expect(gamutChroma([50, 0.3, 140])).to.be.closeTo(0.161, 1e-3); + // Between the body and the spike, and past the spike. + expect(gamutChroma([lightness, chroma - 0.01, hue])).to.equal(bodyEnd); + expect(gamutChroma([lightness, 0.33, hue])).to.be.closeTo(chroma, 1e-6); + expect(gamutChroma([lightness, chroma, hue])).to.equal(chroma); + }); + + it('keeps every 8-bit primary and secondary color', () => { + const colors: RGB[] = [ + [255, 0, 0], + [255, 255, 0], + [0, 255, 0], + [0, 255, 255], + [0, 0, 255], + [255, 0, 255], + [0, 0, 128], + ]; + + for (const rgb of colors) { + const [l, c, h] = converter.rgb.oklch(rgb); + expect(gamutChroma([l, c, h]), `${rgb}`).to.be.closeTo(c, 1e-9); + } + }); + + it('treats a chroma that rounds to 0 at 5 decimals as a gray', () => { + expect(isAchromatic(0.000004)).to.be.true; + expect(isAchromatic(0.00001)).to.be.false; + }); +}); + +describe('OKLCH cusps', () => { + it('maps an OKLCH hue to the HSV hue of its cusp and back', () => { + for (const hsvHue of [0, 60, 120, 200, 300]) { + const oklchHue = pureHueOklch(hsvHue)[2]; + expect(cuspHsvHue(oklchHue)).to.be.closeTo(hsvHue, 1e-4); + } + }); + + it('gives the most chromatic sRGB color of a hue', () => { + const cyan = pureHueOklch(200); + const [lightness, chroma] = cusp(cyan[2]); + + // The cache holds half degrees. + expect(lightness).to.be.closeTo(cyan[0], 0.5); + expect(chroma).to.be.closeTo(cyan[1], 5e-3); + }); + + it('builds the hue slider track from 37 cusp colors in the slider direction', () => { + const track = oklchHueTrack(); + + expect(track).to.match( + /^linear-gradient\(var\(--_slider-track-direction\), rgb\([^)]+\) var\(--_slider-track-inset\), / + ); + expect(track).to.match( + /, rgb\([^)]+\) calc\(100% - var\(--_slider-track-inset\)\)\)$/ + ); + expect(track.match(/rgb\(/g)).to.have.length(37); + }); +}); + +describe('OKLCH area paint', () => { + const width = 100; + const height = 80; + + function paint(hue: number): ImageData { + const image = new ImageData(width, height); + paintOklchArea(image, hue); + return image; + } + + /** The row of a lightness: the lightness at its center, and its pixels. */ + function rowAt(image: ImageData, y: number) { + const lightness = (1 - (y + 0.5) / height) * 100; + const pixels = Array.from({ length: width }, (_, x) => + Array.from(image.data.slice((y * width + x) * 4, (y * width + x + 1) * 4)) + ); + + return { lightness, pixels }; + } + + /** The pixel of a row at a chroma. */ + function at(pixels: number[][], chroma: number): number[] { + return pixels[Math.floor((chroma / OKLCH_AREA_CHROMA) * width)]; + } + + it('paints the gamut and leaves the rest transparent', () => { + const { pixels } = rowAt(paint(140), 40); + const [r, g, b, a] = pixels[0]; + + expect(at(pixels, 0.05)[3]).to.equal(255); + expect(at(pixels, 0.3)[3]).to.equal(0); + // A gray at the left edge. + expect(a).to.equal(255); + expect(Math.max(r, g, b) - Math.min(r, g, b)).to.be.at.most(2); + }); + + it('gives the pixels at the gamut edge a share of the alpha', () => { + const { lightness, pixels } = rowAt(paint(140), 40); + const [[, end]] = gamutRuns(lightness, 140); + const alphas = pixels.map(([, , , a]) => a); + const edge = Math.floor((end / OKLCH_AREA_CHROMA) * width); + + expect(alphas.slice(0, edge - 1).every((a) => a === 255)).to.be.true; + expect(alphas.slice(edge + 2).every((a) => a === 0)).to.be.true; + expect(alphas.some((a) => a > 0 && a < 255)).to.be.true; + }); + + it('paints the blue spike as a line apart from the rest of the row', () => { + const hue = BLUE[2]; + const { lightness, pixels } = rowAt(paint(hue), 50); + const [[, bodyEnd], [spike]] = gamutRuns(lightness, hue); + + expect(at(pixels, spike)[3]).to.be.above(127); + expect(at(pixels, (bodyEnd + spike) / 2)[3]).to.equal(0); + }); +}); diff --git a/src/components/color-picker/oklch.ts b/src/components/color-picker/oklch.ts new file mode 100644 index 000000000..47734eaa8 --- /dev/null +++ b/src/components/color-picker/oklch.ts @@ -0,0 +1,426 @@ +import { clamp, roundPrecise } from '#internals/utils/math.js'; +import { getOrInsertComputed } from '#internals/utils/objects.js'; +import { + converter, + delinearize, + hueDirection, + LMS_TO_LINEAR_SRGB, + OKLAB_TO_LMS, + type OKLCH, + oklabToLinearSrgb, + rgbString, +} from './converters.js'; + +/** The axes of the area: HSV saturation by value, or OKLCH lightness by chroma. */ +export type AreaSpace = 'hsv' | 'oklch'; + +/** + * The end of the chroma axis of the OKLCH area, for every hue: just past the + * largest sRGB chroma, 0.3225 at hue 328. + */ +export const OKLCH_AREA_CHROMA = 0.33; + +/** A linear channel this far outside 0-1 is still in the sRGB gamut. */ +const GAMUT_TOLERANCE = 1e-7; + +/** The upper bound of the chroma search: no sRGB color has more. */ +const CHROMA_LIMIT = 0.4; + +/** Whether a chroma is too small for a hue: the chroma of a gray. */ +export function isAchromatic(chroma: number): boolean { + return roundPrecise(chroma, 5) === 0; +} + +/** A chroma range of one row of the OKLCH area that is in the sRGB gamut. */ +type GamutRun = readonly [start: number, end: number]; + +/** A cubic of the chroma `c`: `constant + linear c + quadratic c² + cubic c³`. */ +type Cubic = readonly [ + constant: number, + linear: number, + quadratic: number, + cubic: number, +]; + +// Index access, not destructuring: this runs in the inner loop of a paint. +function evaluate(cubic: Cubic, c: number): number { + return ((cubic[3] * c + cubic[2]) * c + cubic[1]) * c + cubic[0]; +} + +/** + * The linear sRGB channels along one row of the OKLCH area, as cubics of the + * chroma: each cube root of LMS is linear in the chroma. + */ +function channelCubics(lightness: number, hue: number): Cubic[] { + const [cos, sin] = hueDirection(hue); + const l = lightness / 100; + const slopes = OKLAB_TO_LMS.map(([, a, b]) => a * cos + b * sin); + + return LMS_TO_LINEAR_SRGB.map((row) => { + const cubic: [number, number, number, number] = [0, 0, 0, 0]; + + row.forEach((weight, j) => { + const s = slopes[j]; + // (l + s c)³ expanded. + cubic[0] += weight * l * l * l; + cubic[1] += weight * 3 * l * l * s; + cubic[2] += weight * 3 * l * s * s; + cubic[3] += weight * s * s * s; + }); + + return cubic; + }); +} + +/** The chromas where the slope of a cubic is 0, in order. */ +function turningPoints([, linear, quadratic, cubic]: Cubic): number[] { + // The slope is `linear + slopeLinear c + slopeSquare c²`. + const slopeSquare = 3 * cubic; + const slopeLinear = 2 * quadratic; + + if (Math.abs(slopeSquare) < 1e-12) { + return Math.abs(slopeLinear) < 1e-12 ? [] : [-linear / slopeLinear]; + } + + const discriminant = slopeLinear * slopeLinear - 4 * slopeSquare * linear; + + if (discriminant < 0) { + return []; + } + + const vertex = -slopeLinear / (2 * slopeSquare); + const spread = Math.sqrt(discriminant) / Math.abs(2 * slopeSquare); + return [vertex - spread, vertex + spread]; +} + +/** Adds the chromas in `[0, CHROMA_LIMIT)` where a cubic equals `target`. */ +function addRoots(cubic: Cubic, target: number, roots: number[]): void { + const edges = turningPoints(cubic); + let low = 0; + let lowOffset = evaluate(cubic, low) - target; + + edges.push(CHROMA_LIMIT); + + // Between two turning points a cubic has at most one root. + for (const edge of edges) { + if (edge <= low) continue; + + const high = Math.min(edge, CHROMA_LIMIT); + const highOffset = evaluate(cubic, high) - target; + + if (lowOffset === 0) { + roots.push(low); + } else if (lowOffset * highOffset < 0) { + // Bisection. Inline, as it runs for every row of a paint. + let from = low; + let to = high; + + while (to - from > 1e-10) { + const middle = (from + to) / 2; + + if ((evaluate(cubic, middle) - target) * lowOffset > 0) { + from = middle; + } else { + to = middle; + } + } + + roots.push((from + to) / 2); + } + + if (high === CHROMA_LIMIT) return; + + low = high; + lowOffset = highOffset; + } +} + +/** + * The chroma ranges of a row of the OKLCH area, at a lightness (0-100) and a + * hue, that are in the sRGB gamut. A row can have more than one range: at the + * hue of blue, the black-to-blue edge of sRGB is a thin spike apart from the + * rest, and a range can be a single chroma. + */ +export function gamutRuns(lightness: number, hue: number): GamutRun[] { + const cubics = channelCubics(lightness, hue); + const inside = (c: number) => { + for (const cubic of cubics) { + const channel = evaluate(cubic, c); + + if (channel < -GAMUT_TOLERANCE || channel > 1 + GAMUT_TOLERANCE) { + return false; + } + } + return true; + }; + const breaks = [0, CHROMA_LIMIT]; + + for (const cubic of cubics) { + addRoots(cubic, 0, breaks); + addRoots(cubic, 1, breaks); + } + + breaks.sort((x, y) => x - y); + + const runs: [number, number][] = []; + const add = (start: number, end: number) => { + const last = runs.at(-1); + + if (last && start - last[1] < 1e-9) { + last[1] = Math.max(last[1], end); + } else { + runs.push([start, end]); + } + }; + + for (let i = 0; i < breaks.length; i++) { + const start = breaks[i]; + const end = breaks[i + 1]; + + if (start === end) continue; + + if (end !== undefined && inside((start + end) / 2)) { + add(start, end); + } else if (inside(start)) { + // Two channels meet the gamut edge at one chroma. + add(start, start); + } + } + + return runs; +} + +/** + * The most chroma, up to the chroma of `color`, that sRGB has at its lightness + * and hue: its own chroma when it is in the gamut, else the end of the nearest + * range below it. + */ +export function gamutChroma([lightness, chroma, hue]: OKLCH): number { + // A chroma a rounding step before a single-chroma range is on it. + const run = gamutRuns(lightness, hue).findLast( + ([start]) => chroma >= start - 1e-9 + ); + + return run ? Math.min(chroma, run[1]) : 0; +} + +/** The OKLCH values of the pure color of an HSV hue. */ +export function pureHueOklch(hsvHue: number): OKLCH { + return converter.rgb.oklch(converter.hsv.rgb([hsvHue, 100, 100])); +} + +const RED_HUE = pureHueOklch(0)[2]; + +/** + * The HSV hue whose pure color has an OKLCH hue: the HSV hue of the cusp. + * The OKLCH hue rises with the HSV hue from red. + */ +export function cuspHsvHue(oklchHue: number, tolerance = 1e-6): number { + const unwrap = (h: number) => (h < RED_HUE ? h + 360 : h); + const target = unwrap(oklchHue); + let low = 0; + let high = 360; + + while (high - low > tolerance) { + const middle = (low + high) / 2; + + if (unwrap(pureHueOklch(middle)[2]) < target) { + low = middle; + } else { + high = middle; + } + } + + return (low + high) / 2; +} + +/** The cusps by OKLCH hue in half degrees. */ +const cusps = new Map(); + +/** The OKLCH values of the cusp of an OKLCH hue: its most chromatic sRGB color. */ +export function cusp(oklchHue: number): OKLCH { + return getOrInsertComputed(cusps, Math.round(oklchHue * 2), (key) => + pureHueOklch(cuspHsvHue(key / 2, 0.01)) + ); +} + +/** The cusp of an OKLCH hue as a CSS `rgb()` color. */ +export function cuspColor(oklchHue: number): string { + return rgbString(converter.oklch.rgb(cusp(oklchHue))); +} + +/** The steps of the gamma table of the area paint. */ +const GAMMA_STEPS = 4096; + +let gammaTable: Uint8ClampedArray | undefined; + +/** + * 8-bit sRGB values of linear light in `GAMMA_STEPS` steps. A step is less + * than one 8-bit value, also near black, and a paint needs no `pow` call. + */ +function getGammaTable(): Uint8ClampedArray { + gammaTable ??= Uint8ClampedArray.from({ length: GAMMA_STEPS + 1 }, (_, i) => + delinearize(i / GAMMA_STEPS) + ); + return gammaTable; +} + +/** A gamut range of a line of the area, in pixels from the left edge. */ +type PixelRun = [start: number, end: number]; + +/** The integral of `clamp(v, 0, 1)` from 0 to `v`. */ +function rampIntegral(v: number): number { + if (v <= 0) return 0; + return v >= 1 ? v - 0.5 : (v * v) / 2; +} + +/** + * The share of pixel column `x` that lies left of an edge, on average while + * the edge moves from `from` to `to` across a row: a box filter of the edge. + */ +function shareLeftOf(from: number, to: number, x: number): number { + const a = from - x; + const b = to - x; + + return Math.abs(b - a) < 1e-6 + ? clamp((a + b) / 2, 0, 1) + : (rampIntegral(b) - rampIntegral(a)) / (b - a); +} + +/** + * Adds to `coverage` the share of each pixel of a half row that the gamut + * covers, with each run moving from its place on the top line to its place on + * the bottom line. A run narrower than a pixel is a line: it is 1 px wide + * across its direction. + */ +function addHalfRowCoverage( + coverage: Float32Array, + top: PixelRun[], + bottom: PixelRun[] +): void { + for (let i = 0; i < Math.max(top.length, bottom.length); i++) { + // A run on one line only stays in place across the half row. + let [s0, e0] = top[i] ?? bottom[i]; + let [s1, e1] = bottom[i] ?? top[i]; + + if (e0 - s0 < 1 && e1 - s1 < 1) { + const m0 = (s0 + e0) / 2; + const m1 = (s1 + e1) / 2; + // The line moves `m1 - m0` across a half row of 0.5 px. + const half = Math.hypot(1, (m1 - m0) * 2) / 2; + + [s0, e0, s1, e1] = [m0 - half, m0 + half, m1 - half, m1 + half]; + } + + const innerStart = Math.max(s0, s1); + const innerEnd = Math.min(e0, e1); + const last = Math.min(Math.ceil(Math.max(e0, e1)), coverage.length); + + for (let x = Math.max(Math.floor(Math.min(s0, s1)), 0); x < last; x++) { + const share = + x >= innerStart && x + 1 <= innerEnd + ? 1 + : shareLeftOf(e0, e1, x) - shareLeftOf(s0, s1, x); + + coverage[x] += share / 2; + } + } +} + +/** `u` moved into the nearest run. */ +function intoRuns(u: number, runs: PixelRun[]): number { + let nearest = u; + let distance = Number.POSITIVE_INFINITY; + + // An index loop: this runs for every pixel of a paint. + for (let i = 0; i < runs.length; i++) { + const inside = clamp(u, runs[i][0], runs[i][1]); + const gap = Math.abs(inside - u); + + if (gap < distance) { + distance = gap; + nearest = inside; + } + } + + return nearest; +} + +/** + * Paints the OKLCH area of a hue into `image`: lightness from 100 % at the top + * edge to 0 at the bottom edge, chroma from 0 at the left edge to + * `OKLCH_AREA_CHROMA` at the right edge. The alpha of a pixel is the share of + * it inside the sRGB gamut, so the gamut edge is smooth and the rest is + * transparent. A gamut range narrower than a pixel, such as the blue spike, + * paints as a 1 px line. + */ +export function paintOklchArea(image: ImageData, hue: number): void { + const { width, height, data } = image; + const [cos, sin] = hueDirection(hue); + const linear = [0, 0, 0]; + // Pixel `x` covers the chroma from `x / scale` to `(x + 1) / scale`. + const scale = width / OKLCH_AREA_CHROMA; + const gamma = getGammaTable(); + const coverage = new Float32Array(width); + const toByte = (channel: number) => + gamma[Math.round(clamp(channel, 0, 1) * GAMMA_STEPS)]; + // The gamut runs of the line `y` px below the top edge. + const runsAt = (y: number): PixelRun[] => + gamutRuns(100 * (1 - y / height), hue).map(([start, end]) => [ + start * scale, + end * scale, + ]); + + data.fill(0); + + let top = runsAt(0); + + for (let y = 0; y < height; y++) { + const middle = runsAt(y + 0.5); + const bottom = runsAt(y + 1); + const lightness = 1 - (y + 0.5) / height; + + coverage.fill(0); + addHalfRowCoverage(coverage, top, middle); + addHalfRowCoverage(coverage, middle, bottom); + + for (let x = 0; x < width; x++) { + const alpha = Math.round(Math.min(coverage[x], 1) * 255); + + if (!alpha) continue; + + // An edge pixel takes the color of the gamut edge. + const chroma = intoRuns(x + 0.5, middle) / scale; + const i = (y * width + x) * 4; + + oklabToLinearSrgb(lightness, chroma * cos, chroma * sin, linear); + data[i] = toByte(linear[0]); + data[i + 1] = toByte(linear[1]); + data[i + 2] = toByte(linear[2]); + data[i + 3] = alpha; + } + + top = bottom; + } +} + +/** The hues of the stops of the OKLCH hue slider track, every 10 degrees. */ +const TRACK_HUES = Array.from({ length: 37 }, (_, i) => i * 10); + +let hueTrack: string | undefined; + +/** + * The track of the hue slider in the OKLCH format: the cusp of each OKLCH + * hue, inset by half a thumb at both ends, in the direction of the slider. + */ +export function oklchHueTrack(): string { + if (!hueTrack) { + const stops = TRACK_HUES.map(cuspColor); + + stops[0] += ' var(--_slider-track-inset)'; + stops[stops.length - 1] += ' calc(100% - var(--_slider-track-inset))'; + hueTrack = `linear-gradient(var(--_slider-track-direction), ${stops.join(', ')})`; + } + + return hueTrack; +} diff --git a/src/components/color-picker/picker-canvas.spec.ts b/src/components/color-picker/picker-canvas.spec.ts index 468c5d9fe..33d1b7a61 100644 --- a/src/components/color-picker/picker-canvas.spec.ts +++ b/src/components/color-picker/picker-canvas.spec.ts @@ -1,4 +1,10 @@ -import { elementUpdated, expect, fixture, html } from '@open-wc/testing'; +import { + elementUpdated, + expect, + fixture, + html, + nextFrame, +} from '@open-wc/testing'; import { spy } from 'sinon'; import { @@ -6,6 +12,11 @@ import { arrowLeft, arrowRight, arrowUp, + endKey, + homeKey, + pageDownKey, + pageUpKey, + shiftKey, } from '#internals/controllers/key-bindings.js'; import { defineComponents } from '#internals/definitions/defineComponents.js'; import { @@ -14,7 +25,6 @@ import { simulatePointerDown, simulatePointerMove, } from '#internals/testing/simulate.spec.js'; -import { asPercent } from '#internals/utils/math.js'; import IgcPickerCanvasComponent from './picker-canvas.js'; async function createCanvas() { @@ -71,14 +81,14 @@ describe('Picker canvas', () => { ); }); - it('formats `aria-valuetext` with `markerValueFormat`', async () => { + it('takes the `aria-valuetext` from `markerValueText`', async () => { canvas.saturation = 62.4; canvas.brightness = 37.8; - canvas.markerValueFormat = 'Sättigung {0} %, Helligkeit {1} %'; + canvas.markerValueText = 'Sättigung 62 %, Helligkeit 38 %, dunkles Blau'; await elementUpdated(canvas); expect(getMarker(canvas).getAttribute('aria-valuetext')).to.equal( - 'Sättigung 62 %, Helligkeit 38 %' + 'Sättigung 62 %, Helligkeit 38 %, dunkles Blau' ); }); @@ -142,37 +152,47 @@ describe('Picker canvas', () => { }); describe('Keyboard interaction', () => { - it('moves the marker with arrow keys and emits `igcColorPicked`', () => { + it('moves the marker with arrow keys and emits `igcColorPicked`', async () => { + const { width, height } = canvas.getMarkerDimensions(); + const rect = canvas.getBoundingClientRect(); + + // The marker center at 0%, 0%. + canvas.x = -width; + canvas.y = -height; + await elementUpdated(canvas); + const eventSpy = spy(canvas, 'emitEvent'); simulateKeyboard(canvas, arrowRight); - expect(canvas.x).to.equal(1); + expect(canvas.x).to.be.closeTo(rect.width / 100 - width, 1e-9); expect(eventSpy).calledOnce; simulateKeyboard(canvas, arrowDown); - expect(canvas.y).to.equal(1); + expect(canvas.y).to.be.closeTo(rect.height / 100 - height, 1e-9); simulateKeyboard(canvas, arrowLeft); - expect(canvas.x).to.equal(0); + expect(canvas.x).to.equal(-width); simulateKeyboard(canvas, arrowUp); - expect(canvas.y).to.equal(0); + expect(canvas.y).to.equal(-height); expect(eventSpy.callCount).to.equal(4); }); - it('emits rounded percentages relative to the canvas size', () => { - const eventSpy = spy(canvas, 'emitEvent'); + it('emits whole percentages of the canvas size', async () => { const { width, height } = canvas.getMarkerDimensions(); - const rect = canvas.getBoundingClientRect(); + + // The marker center at 0%, 0%. + canvas.x = -width; + canvas.y = -height; + await elementUpdated(canvas); + + const eventSpy = spy(canvas, 'emitEvent'); simulateKeyboard(canvas, arrowRight); expect(eventSpy).calledWith('igcColorPicked', { - detail: { - x: Math.round(asPercent(1 + width, rect.width)), - y: Math.round(asPercent(height, rect.height)), - }, + detail: { x: 1, y: 0 }, bubbles: false, }); }); @@ -191,6 +211,165 @@ describe('Picker canvas', () => { expect(canvas.y).to.equal(-height); expect(eventSpy).not.called; }); + + describe('Steps in percent', () => { + /** Puts the marker center at `x`% and `y`% of the canvas. */ + async function placeMarker(x: number, y: number): Promise { + const rect = canvas.getBoundingClientRect(); + const { width, height } = canvas.getMarkerDimensions(); + + canvas.x = (x / 100) * rect.width - width; + canvas.y = (y / 100) * rect.height - height; + await elementUpdated(canvas); + } + + /** Presses `key` and returns the detail of the `igcColorPicked` it emits. */ + function press(key: string | string[]): unknown { + const eventSpy = spy(canvas, 'emitEvent'); + + try { + simulateKeyboard(canvas, key); + return eventSpy.lastCall?.args[1]?.detail; + } finally { + eventSpy.restore(); + } + } + + it('steps 1% of an axis with an arrow key', async () => { + await placeMarker(50, 50); + + expect(press(arrowRight)).to.deep.equal({ x: 51, y: 50 }); + expect(press(arrowDown)).to.deep.equal({ x: 51, y: 51 }); + expect(press(arrowLeft)).to.deep.equal({ x: 50, y: 51 }); + expect(press(arrowUp)).to.deep.equal({ x: 50, y: 50 }); + }); + + it('steps 10% with Shift + Arrow, Page Up, Page Down, Home and End', async () => { + await placeMarker(50, 50); + + const steps: [string | string[], { x: number; y: number }][] = [ + [[shiftKey, arrowRight], { x: 60, y: 50 }], + [[shiftKey, arrowDown], { x: 60, y: 60 }], + [[shiftKey, arrowLeft], { x: 50, y: 60 }], + [[shiftKey, arrowUp], { x: 50, y: 50 }], + [pageDownKey, { x: 50, y: 60 }], + [pageUpKey, { x: 50, y: 50 }], + [endKey, { x: 60, y: 50 }], + [homeKey, { x: 50, y: 50 }], + ]; + + for (const [key, detail] of steps) { + expect(press(key), String(key)).to.deep.equal(detail); + } + }); + + it('moves the same percentage at another canvas size', async () => { + canvas.style.width = '150px'; + await placeMarker(20, 20); + + const rect = canvas.getBoundingClientRect(); + const { width, height } = canvas.getMarkerDimensions(); + + expect(rect.width).to.equal(150); + + expect(press([shiftKey, arrowRight])).to.deep.equal({ x: 30, y: 20 }); + expect(canvas.x + width).to.be.closeTo(0.3 * rect.width, 1e-9); + + expect(press(arrowDown)).to.deep.equal({ x: 30, y: 21 }); + expect(canvas.y + height).to.be.closeTo(0.21 * rect.height, 1e-9); + }); + + it('snaps only the axis that moves to a whole percent', async () => { + await placeMarker(40.4, 50); + const x = canvas.x; + + expect(press(arrowDown)).to.deep.equal({ x: 40, y: 51 }); + expect(canvas.x).to.equal(x); + }); + + it('stops at the edges of the canvas', async () => { + await placeMarker(95, 98); + + expect(press(endKey)).to.deep.equal({ x: 100, y: 98 }); + expect(press(pageDownKey)).to.deep.equal({ x: 100, y: 100 }); + expect(press(arrowRight)).to.be.undefined; + expect(press(arrowDown)).to.be.undefined; + }); + + it('moves the marker in the direction of the arrow in RTL', async () => { + canvas.dir = 'rtl'; + await placeMarker(50, 50); + + expect(press(arrowRight)).to.deep.equal({ x: 51, y: 50 }); + expect(press(homeKey)).to.deep.equal({ x: 41, y: 50 }); + }); + + it('does nothing while the canvas has no size', async () => { + canvas.style.display = 'none'; + await elementUpdated(canvas); + + expect(press(arrowRight)).to.be.undefined; + expect(press(endKey)).to.be.undefined; + }); + }); + }); + + describe('OKLCH area', () => { + /** The alpha of the area at a share (0-1) across and down its canvas. */ + function alphaAt(across: number, down: number): number { + const plane = canvas.renderRoot.querySelector('canvas')!; + const x = Math.round(across * (plane.width - 1)); + const y = Math.round(down * (plane.height - 1)); + + return plane.getContext('2d')!.getImageData(x, y, 1, 1).data[3]; + } + + beforeEach(async () => { + canvas.space = 'oklch'; + canvas.hue = 140; + await elementUpdated(canvas); + await nextFrame(); + }); + + it('paints the gamut of the hue on a canvas, in CSS pixels', () => { + const plane = canvas.renderRoot.querySelector('canvas')!; + + expect(canvas.getAttribute('space')).to.equal('oklch'); + expect(plane.getAttribute('aria-hidden')).to.equal('true'); + expect([plane.width, plane.height]).to.eql([ + canvas.clientWidth, + canvas.clientHeight, + ]); + // Green at lightness 50 % reaches chroma 0.161 of 0.33. + expect(alphaAt(0.2, 0.5)).to.equal(255); + expect(alphaAt(0.9, 0.5)).to.equal(0); + }); + + it('paints again for a new hue', async () => { + canvas.hue = 328; + await elementUpdated(canvas); + await nextFrame(); + + // Magenta at lightness 70 % reaches chroma 0.32. + expect(alphaAt(0.9, 0.3)).to.equal(255); + }); + + it('has no canvas in the HSV space', async () => { + canvas.space = 'hsv'; + await elementUpdated(canvas); + + expect(canvas.renderRoot.querySelector('canvas')).to.be.null; + }); + + it('lets a listener move the marker again', () => { + canvas.addEventListener('igcColorPicked', () => { + canvas.x = 10; + }); + + simulateKeyboard(canvas, arrowRight); + + expect(canvas.x).to.equal(10); + }); }); describe('Pointer interaction', () => { diff --git a/src/components/color-picker/picker-canvas.ts b/src/components/color-picker/picker-canvas.ts index e13d089ee..411d412c0 100644 --- a/src/components/color-picker/picker-canvas.ts +++ b/src/components/color-picker/picker-canvas.ts @@ -1,5 +1,5 @@ import { ColorPickerResourceStringsEN } from 'igniteui-i18n-core'; -import { html, LitElement, type PropertyValues } from 'lit'; +import { html, LitElement, nothing, type PropertyValues } from 'lit'; import { property, query, state } from 'lit/decorators.js'; import { styleMap } from 'lit/directives/style-map.js'; import { @@ -8,7 +8,13 @@ import { arrowLeft, arrowRight, arrowUp, + endKey, + homeKey, + pageDownKey, + pageUpKey, + shiftKey, } from '#internals/controllers/key-bindings.js'; +import { addResizeObserverController } from '#internals/controllers/resize-observer.js'; import { registerComponent } from '#internals/definitions/register.js'; import { EventEmitterMixin } from '#internals/mixins/event-emitter.js'; import { partMap } from '#internals/part-map.js'; @@ -19,6 +25,7 @@ import { import { asPercent, clamp } from '#internals/utils/math.js'; import { formatString } from '#internals/utils/strings.js'; import { styles as componentBase } from '../../styles/common/component.css.js'; +import { type AreaSpace, paintOklchArea } from './oklch.js'; import { styles } from './themes/picker-canvas.base.css.js'; export interface IgcPickerCanvasEventMap { @@ -36,20 +43,62 @@ type CanvasGeometry = { marker: { width: number; height: number }; }; +/** + * The keys that move the marker, and their steps in percent of each axis. + * An arrow moves the marker in its own direction, also in RTL, because the + * plane does not mirror. + */ +const KEY_STEPS: ReadonlyArray< + readonly [keys: string | string[], dx: number, dy: number] +> = [ + [arrowLeft, -1, 0], + [arrowRight, 1, 0], + [arrowUp, 0, -1], + [arrowDown, 0, 1], + [[shiftKey, arrowLeft], -10, 0], + [[shiftKey, arrowRight], 10, 0], + [[shiftKey, arrowUp], 0, -10], + [[shiftKey, arrowDown], 0, 10], + [pageUpKey, 0, -10], + [pageDownKey, 0, 10], + [homeKey, -10, 0], + [endKey, 10, 0], +]; + +/** + * Moves a marker offset by `delta` percent of `size`, to a whole percent + * within the canvas. `half` is the half-marker offset of the axis. + */ +function stepOffset( + offset: number, + half: number, + size: number, + delta: number +): number { + const percent = clamp( + Math.round(asPercent(offset + half, size) + delta), + 0, + 100 + ); + + return (percent / 100) * size - half; +} + /* blazorSuppress */ /** - * The saturation/value plane of {@link IgcColorPickerComponent} and the marker - * that moves across it. + * The area of the color panel and the marker that moves across it: the HSV + * saturation by value, or the OKLCH lightness by chroma at a hue. * - * An internal building block of `igc-color-picker` - it is registered so the - * picker can render it, but it is not part of the public component surface and + * An internal building block of the color panel - it is registered so the + * panel can render it, but it is not part of the public component surface and * is not exported from the package entry point. * * @element igc-picker-canvas * * @fires igcColorPicked - Emitted when a color is picked on the canvas. Does not bubble. + * @fires change - Emitted when a change ends, as for a range input: at the end of a drag and after each key. * - * @csspart marker - The draggable marker indicating the picked saturation/value. + * @csspart marker - The draggable marker on the area that shows the picked color. * @csspart dragging - Present on the marker while it is being dragged. */ export default class IgcPickerCanvasComponent extends EventEmitterMixin( @@ -65,19 +114,37 @@ export default class IgcPickerCanvasComponent extends EventEmitterMixin this._step(dx, dy)); + } + + addResizeObserverController(this, { + callback: () => this._schedulePaint(), + requestUpdate: false, + }); + } + + public override disconnectedCallback(): void { + super.disconnectedCallback(); + cancelAnimationFrame(this._paintFrame); + this._paintFrame = 0; } protected override updated(properties: PropertyValues): void { + if (properties.has('space') || properties.has('hue')) { + this._schedulePaint(); + } + if (properties.has('currentColor')) { this.style.color = this.currentColor; } @@ -173,7 +256,11 @@ export default class IgcPickerCanvasComponent extends EventEmitterMixin { + this._paintFrame = 0; + this._paint(); + }); + } + + /** Paints the OKLCH area in CSS pixels; the browser scales it up. */ + private _paint(): void { + const canvas = this._areaCanvas; + const context = canvas?.getContext('2d'); + const { clientWidth: width, clientHeight: height } = this; + + if (!(canvas && context && width && height)) { + return; + } + + // A write to the canvas size clears it, even with the same size. + if (canvas.width !== width || canvas.height !== height) { + canvas.width = width; + canvas.height = height; + } + + if (this._image?.width !== width || this._image.height !== height) { + this._image = context.createImageData(width, height); + } + + paintOklchArea(this._image, this.hue); + context.putImageData(this._image, 0, 0); + } + + /** + * Moves the marker by percentages of the canvas, so a step is the same at + * every canvas size. Only the axis that moves snaps to a whole percent. + */ + private _step(dx: number, dy: number): void { + const geometry = this._measure(); + const { rect, marker } = geometry; + + // A hidden canvas has no size to step against. + if (!(rect.width && rect.height)) { + return; + } + + this._commitPosition( + dx ? stepOffset(this.x, marker.width, rect.width, dx) : this.x, + dy ? stepOffset(this.y, marker.height, rect.height, dy) : this.y, + geometry + ); + this._emitChange(); } - private _onArrowKey({ dx, dy }: { dx: number; dy: number }): void { - this._commitPosition(this.x + dx, this.y + dy, this._measure()); + private _emitChange(): void { + this.dispatchEvent(new Event('change', { bubbles: true })); } private _move(event: PointerEvent): void { @@ -218,6 +359,7 @@ export default class IgcPickerCanvasComponent extends EventEmitterMixin
`, @@ -332,7 +410,7 @@ export const Formats: Story = { docs: { description: { story: - '`format` sets the notation of `value`. The first three pickers hold the same translucent color, and the text under each one shows the `value` string that the component reports. The format switcher in the picker changes the notation, not the color, so it emits no `igcInput` or `igcChange`. `hide-formats` removes the switcher and locks the notation, as in the last picker. `show-alpha` adds the alpha slider and input in whole percent. The anchor then shows the opaque color over its left half and the real opacity over the full surface.', + '`format` sets the notation of `value`. The first four pickers hold the same translucent color, and the text under each one shows the `value` string that the component reports. The format switcher in the picker changes the notation, not the color, so it emits no `igcInput` or `igcChange`. `hide-formats` removes the switcher and locks the notation, as in the last picker. `show-alpha` adds the alpha slider and input in whole percent. The anchor then shows the opaque color over its left half and the real opacity over the full surface.', }, }, actions: { handles: [] }, @@ -357,6 +435,7 @@ export const Formats: Story = { ['Hex', 'hex', false], ['RGB', 'rgb', false], ['HSL', 'hsl', false], + ['OKLCH', 'oklch', false], ['HSL only', 'hsl', true], ] as const ).map( @@ -509,13 +588,121 @@ export const Swatches: Story = { }, }; +export const RecentColors: Story = { + argTypes: disableStoryControls(metadata), + parameters: { + docs: { + description: { + story: + 'Recent colors that the app keeps. The `igcChange` handler adds each committed color to the start of the "Recent" swatch group, and keeps at most 8. The component has no API for recent colors: the swatch groups are light DOM children, so the app owns the list, its order and its storage. The "Palette" group stays the same, and its first swatch has no color.', + }, + }, + actions: { handles: [] }, + }, + render: () => { + const limit = 8; + + const addRecent = (event: CustomEvent) => { + const picker = event.currentTarget as IgcColorPickerComponent; + const group = picker.querySelector('#recent-colors'); + const color = event.detail; + + if (!(color && group)) { + return; + } + + // The same color moves to the start. + for (const swatch of group.querySelectorAll('igc-color-swatch')) { + if (swatch.color === color) { + swatch.remove(); + } + } + + const swatch = document.createElement('igc-color-swatch'); + swatch.color = color; + group.querySelector('[slot="label"]')?.after(swatch); + + for (const extra of Array.from( + group.querySelectorAll('igc-color-swatch') + ).slice(limit)) { + extra.remove(); + } + }; + + return html` + ${samples} +
+ +

Commit a color to add it to "Recent".

+ + Recent + + + Palette + + + + + + + + + +
+
+ `; + }, +}; + +export const ConfirmMode: Story = { + argTypes: disableStoryControls(metadata), + parameters: { + docs: { + description: { + story: + 'With `selection-commit="confirm"`, the changes in the popup are a draft. `value`, shown under the picker, keeps its color, and the picker emits no `igcInput`. Apply, or Enter on the canvas marker, a slider or a swatch, applies the draft with one `igcChange`. Cancel, Escape and an outside click drop it. The preview shows the initial color first and the draft second; a click on the initial color restores it. The text in the popup comes from the `footer` slot.', + }, + }, + actions: { handles: [] }, + }, + render: () => html` + ${samples} +
+
+ + showValue(event.currentTarget as IgcColorPickerComponent)} + > + Enter applies. Escape cancels. + + #2a9d8f +
+
+ `, +}; + export const ThemeEditor: Story = { argTypes: disableStoryControls(metadata), parameters: { docs: { description: { story: - 'A theme editor with a live preview. Each picker writes its value to a CSS custom property on `igcInput`, so the preview follows every drag. The editor also checks the WCAG contrast ratio of the text on the surface and of the white button label on the primary color. If a ratio is less than 4.5:1, it calls `setCustomValidity()` and the `custom-error` slot shows the ratio. The message shows when focus leaves the changed picker.', + 'A theme editor with a live preview. Each picker writes its value to a CSS custom property on `igcInput`, so the preview follows every drag. The editor also checks the WCAG contrast ratio of the text on the surface and of the white button label on the primary color. If a ratio is less than 4.5:1, it calls `setCustomValidity()` and the `custom-error` slot shows the ratio. The message shows when focus leaves the changed picker. The popups of the Primary and Text pickers show the same ratios: `contrast-against` is white for the primary color and `var(--surface)` for the text.', }, }, actions: { handles: [] }, @@ -612,6 +799,7 @@ export const ThemeEditor: Story = { name="primary" label="Primary" value="#3f51b5" + contrast-against="white" .swatches=${palette} @igcInput=${update} > @@ -633,6 +821,7 @@ export const ThemeEditor: Story = { name="text" label="Text" value="#212121" + contrast-against="var(--surface)" .swatches=${['#000000', '#212121', '#424242', '#757575', '#ffffff']} @igcInput=${update} >