From c3f14187352753d6f2a92251d5f0abdd0bf76bfe Mon Sep 17 00:00:00 2001 From: Radoslav Karaivanov Date: Mon, 23 Nov 2026 21:23:32 +0200 Subject: [PATCH 1/7] feat(color-picker, color-panel): add the color panel and color swatches Modern CSS colors, such as oklch(), lab(), color() and color-mix(), now parse into sRGB and no longer give NaN. A color that depends on its context, such as currentcolor or var(), clears the value. The area keys move the marker 1 % (10 % with Shift, Page Up/Down and Home/End) at any area size. In input mode, a clear icon shows while a color is set, with clear(), a clear-icon slot and a part (#2647). The text field exposes the field, input, native-input, label, prefix and suffix parts (#2637). The new igc-color-panel is the picker surface as its own element. The picker shows it in its popup, with the same parts and behavior. The new igc-color-swatch and igc-color-swatch-group add swatches as light DOM children of the panel or the picker, in labelled groups. All swatches are one listbox with arrow, Home/End, Enter and Space keys. A swatch can be a no-color swatch or use var(). views and active-view add a swatch view with a view switcher. The new strings show in English until igniteui-i18n-core ships them. The swatch, group and switcher styles are temporary until the design is ready. --- CHANGELOG.md | 16 + api-reference/igc-color-panel.md | 93 ++ api-reference/igc-color-picker.md | 52 +- api-reference/igc-color-swatch-group.md | 18 + api-reference/igc-color-swatch.md | 33 + public-api.json | 127 +- .../color-panel/color-panel.spec.ts | 980 +++++++++++++++ src/components/color-panel/color-panel.ts | 1116 +++++++++++++++++ .../color-panel/color-swatch-group.ts | 31 + src/components/color-panel/color-swatch.ts | 196 +++ src/components/color-panel/common.ts | 84 ++ src/components/color-panel/spec.md | 489 ++++++++ .../color-panel/themes/color-panel.base.scss | 124 ++ .../themes/color-swatch-group.base.scss | 17 + .../color-panel/themes/color-swatch.base.scss | 53 + .../themes/shared/color-panel.bootstrap.scss | 12 + .../themes/shared/color-panel.common.scss | 183 +++ .../themes/shared/color-panel.fluent.scss | 17 + .../themes/shared/color-panel.indigo.scss | 28 + .../themes/shared/color-panel.material.scss | 14 + src/components/color-panel/themes/themes.ts | 34 + .../color-picker/color-picker.spec.ts | 518 +++++++- src/components/color-picker/color-picker.ts | 725 +++-------- .../color-picker/color.property.spec.ts | 71 ++ src/components/color-picker/common.spec.ts | 72 ++ src/components/color-picker/common.ts | 198 ++- src/components/color-picker/i18n.ts | 55 + src/components/color-picker/model.spec.ts | 26 + src/components/color-picker/model.ts | 36 +- .../color-picker/picker-canvas.spec.ts | 141 ++- src/components/color-picker/picker-canvas.ts | 93 +- src/components/color-picker/spec.md | 215 +++- .../color-picker/themes/_swatch.scss | 24 + .../themes/color-picker.base.scss | 98 +- .../themes/shared/color-picker.bootstrap.scss | 8 - .../themes/shared/color-picker.common.scss | 193 +-- .../themes/shared/color-picker.fluent.scss | 8 - .../themes/shared/color-picker.indigo.scss | 19 - .../themes/shared/color-picker.material.scss | 5 - .../date-picker/date-picker.base.ts | 15 +- src/components/types.ts | 1 + src/index.ts | 5 + src/internals/context.ts | 33 +- .../definitions/defineAllComponents.ts | 6 + src/internals/templates/slotted-icon.ts | 25 +- src/internals/testing/helpers.spec.ts | 9 + stories/color-panel.stories.ts | 283 +++++ stories/color-picker.stories.ts | 128 +- 48 files changed, 5714 insertions(+), 1013 deletions(-) create mode 100644 api-reference/igc-color-panel.md create mode 100644 api-reference/igc-color-swatch-group.md create mode 100644 api-reference/igc-color-swatch.md create mode 100644 src/components/color-panel/color-panel.spec.ts create mode 100644 src/components/color-panel/color-panel.ts create mode 100644 src/components/color-panel/color-swatch-group.ts create mode 100644 src/components/color-panel/color-swatch.ts create mode 100644 src/components/color-panel/common.ts create mode 100644 src/components/color-panel/spec.md create mode 100644 src/components/color-panel/themes/color-panel.base.scss create mode 100644 src/components/color-panel/themes/color-swatch-group.base.scss create mode 100644 src/components/color-panel/themes/color-swatch.base.scss create mode 100644 src/components/color-panel/themes/shared/color-panel.bootstrap.scss create mode 100644 src/components/color-panel/themes/shared/color-panel.common.scss create mode 100644 src/components/color-panel/themes/shared/color-panel.fluent.scss create mode 100644 src/components/color-panel/themes/shared/color-panel.indigo.scss create mode 100644 src/components/color-panel/themes/shared/color-panel.material.scss create mode 100644 src/components/color-panel/themes/themes.ts create mode 100644 src/components/color-picker/i18n.ts create mode 100644 src/components/color-picker/themes/_swatch.scss create mode 100644 stories/color-panel.stories.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 13f680b4c..d2d9aa802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ 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 + - 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. + - 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 +35,11 @@ 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. + - 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. - #### 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 +85,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..5e78a13ba --- /dev/null +++ b/api-reference/igc-color-panel.md @@ -0,0 +1,93 @@ +# igc-color-panel + +A color selection surface that stays in the page. + +The user picks a color with the HSV saturation/value canvas, the hue slider +and the optional alpha slider. 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'`. 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`. +- `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 saturation and value canvas. +- `marker`: The marker on the canvas that shows the saturation and value. +- `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. diff --git a/api-reference/igc-color-picker.md b/api-reference/igc-color-picker.md index b31efe06c..ae6aae5bc 100644 --- a/api-reference/igc-color-picker.md +++ b/api-reference/igc-color-picker.md @@ -3,8 +3,8 @@ 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. +and the optional alpha slider. 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,10 +24,13 @@ 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. + 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. - `format`: `'hex' | 'rgb' | 'hsl'`. Default: `'hex'`. Attribute: `format`. The color format of the string value. @@ -44,14 +47,24 @@ defineComponents(IgcColorPickerComponent); anchor is an editable text field with a color swatch prefix. The prefix also opens the picker. - `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`. - `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 +110,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 @@ -141,6 +157,8 @@ 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. ## CSS parts @@ -148,7 +166,13 @@ 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. @@ -163,8 +187,12 @@ 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. ## 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..bf8eb6fd8 --- /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 + string, 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..b188f9c87 100644 --- a/public-api.json +++ b/public-api.json @@ -21,6 +21,7 @@ "ChatTemplateRenderer", "ChipResourceStringsEN", "ColorFormat", + "ColorPanelView", "ColorPickerMode", "ColorPickerResourceStringsEN", "ComboCloseTrigger", @@ -105,8 +106,13 @@ "IgcChipComponentEventMap", "IgcCircularGradientComponent", "IgcCircularProgressComponent", + "IgcColorPanelComponent", + "IgcColorPanelComponentEventMap", "IgcColorPickerComponent", "IgcColorPickerComponentEventMap", + "IgcColorPickerResourceStrings", + "IgcColorSwatchComponent", + "IgcColorSwatchGroupComponent", "IgcComboChangeEventArgs", "IgcComboClosingEventArgs", "IgcComboComponent", @@ -1120,9 +1126,67 @@ ], "cssProperties": [] }, + "igc-color-panel": { + "class": "IgcColorPanelComponent", + "attributes": { + "active-view": "ColorPanelView ('gradient' | 'swatches')", + "format": "ColorFormat ('hex' | 'hsl' | 'rgb')", + "hide-formats": "boolean", + "locale": "string", + "show-alpha": "boolean", + "value": "string", + "views": "string" + }, + "properties": { + "activeView": "ColorPanelView ('gradient' | 'swatches')", + "format": "ColorFormat ('hex' | 'hsl' | '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", + "copy", + "dragging", + "eye-dropper", + "format-select", + "hue", + "inputs-row", + "main-row", + "marker", + "picker-canvas", + "selected", + "swatch", + "swatches", + "view-button", + "view-switcher" + ], + "cssProperties": [] + }, "igc-color-picker": { "class": "IgcColorPickerComponent", "attributes": { + "active-view": "ColorPanelView ('gradient' | 'swatches')", "disabled": "boolean", "format": "ColorFormat ('hex' | 'hsl' | 'rgb')", "hide-formats": "boolean", @@ -1135,9 +1199,11 @@ "required": "boolean", "scroll-strategy": "PopoverScrollStrategy ('close' | 'hide' | 'scroll')", "show-alpha": "boolean", - "value": "string" + "value": "string", + "views": "string" }, "properties": { + "activeView": "ColorPanelView ('gradient' | 'swatches')", "defaultValue": "unknown", "disabled": "boolean", "form": "readonly HTMLFormElement | null", @@ -1150,7 +1216,7 @@ "name": "string", "open": "boolean", "required": "boolean", - "resourceStrings": "Required", + "resourceStrings": "Required", "scrollStrategy": "PopoverScrollStrategy ('close' | 'hide' | 'scroll')", "showAlpha": "boolean", "static formAssociated": "readonly boolean", @@ -1159,11 +1225,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 +1249,90 @@ "igcOpening": "unknown" }, "slots": [ + "", + "clear-icon", "custom-error", "helper-text", "invalid", "value-missing" ], "cssParts": [ + "active", "alpha", "alpha-input", "alpha-row", "anchor", "buttons", + "clear-icon", "color-picker", "copy", "dragging", "empty", "eye-dropper", + "field", "format-select", "hue", + "input", "input-mode", "inputs-row", "label", "main-row", "marker", + "native-input", "picker", "picker-canvas", + "prefix", + "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": { @@ -2802,6 +2922,7 @@ "static register": "() => void" }, "events": { + "change": "Event", "igcColorPicked": "unknown" }, "slots": [], 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..df43a6f48 --- /dev/null +++ b/src/components/color-panel/color-panel.spec.ts @@ -0,0 +1,980 @@ +import { + elementUpdated, + expect, + fixture, + html, + nextFrame, +} from '@open-wc/testing'; +import { resetMouse, sendMouse } from '@web/test-runner-commands'; +import { type SinonSpy, spy } 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 { styles as bootstrap } from '../../styles/themes/light/bootstrap.css.js'; +import IgcColorPickerComponent from '../color-picker/color-picker.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 { 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 getHue = (panel: IgcColorPanelComponent) => + query(panel, '[part="hue"]'); +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"]') + ); + +/** 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 }); +} + +function release(slider: HTMLInputElement): void { + slider.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('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('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('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('#0000ff'); + // 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, else "No color"', () => { + expect(children.map(nameOf)).to.eql([ + 'No color', + 'Green', + 'var(--brand)', + '#ff000080', + ]); + }); + + 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); + + panel.activeView = 'swatches'; + await settled(); + await expect(panel).shadowDom.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']); + }); + }); +}); diff --git a/src/components/color-panel/color-panel.ts b/src/components/color-panel/color-panel.ts new file mode 100644 index 000000000..1d58856b6 --- /dev/null +++ b/src/components/color-panel/color-panel.ts @@ -0,0 +1,1116 @@ +import { + html, + LitElement, + nothing, + type PropertyValues, + type TemplateResult, +} from 'lit'; +import { property } 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, + 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 { I18nMixin } from '#internals/mixins/i18n.js'; +import { partMap } from '#internals/part-map.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 { 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 { colorPickerI18nConfig } from '../color-picker/i18n.js'; +import { + ColorModel, + colorKey, + formatPlaceholders, + parseTypedColor, + opaqueColor, +} from '../color-picker/model.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, + 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; + +/** + * A color selection surface that stays in the page. + * + * The user picks a color with the HSV saturation/value canvas, the hue slider + * and the optional alpha slider. 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 saturation and value canvas. + * @csspart marker - The marker on the canvas that shows the saturation and value. + * @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. + */ +export default class IgcColorPanelComponent extends 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; + + private readonly _panelContext: ColorPanelContext = { + noColorLabel: () => this.resourceStrings.color_picker_no_color, + 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); + } + + //#endregion + + constructor() { + super(); + + // A theme can change the colors of `var()` swatches. + addThemingController(this, all, { + themeChange: this._panelContext.refreshSwatches, + }); + + addContextProvider(this, { + context: colorPanelContext, + value: () => this._panelContext, + watch: ['resourceStrings'], + }); + + // 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._panelContext.refreshSwatches(); + }, + 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, + }); + } + + //#region Lit lifecycle methods + + 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. + if (props.has('activeView') || props.has('views')) { + this._markerStale = true; + } + + if (this._swatchesStale) { + this._hasSlottedSwatches = !isEmpty(this._slottedSwatches()); + } + } + + 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); + + 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 { + 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 _handleCopy(): void { + navigator.clipboard?.writeText(this.value).catch(() => {}); + } + + 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 + + /** 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', opaqueColor(this._color)); + } + + 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 }); + } + } + + //#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 [, s, v] = this._color.toHSV(); + + canvas.x = (s / 100) * rect.width - markerWidth; + canvas.y = ((100 - v) / 100) * rect.height - markerHeight; + } + + //#endregion + + private _renderCanvasGradient(): TemplateResult { + const [, saturation, brightness] = this._color.toHSV(); + + return html` + + + `; + } + + private _renderHueSlider(): TemplateResult { + 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; + + 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 + )} +
+ `; + } + + private _renderAlphaRow(): TemplateResult { + const strings = this.resourceStrings; + + return html` + + + + + + + + `; + } + + private _renderSelect(): TemplateResult { + const strings = this.resourceStrings; + const label = strings.color_picker_format; + + return html` + + + + + + ${strings.color_picker_format_hex} + ${strings.color_picker_format_rgb} + ${strings.color_picker_format_hsl} + + `; + } + + 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 _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)} +
+ `; + } +} + +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..45eb094ac --- /dev/null +++ b/src/components/color-panel/color-swatch.ts @@ -0,0 +1,196 @@ +import { html, LitElement, type PropertyValues } from 'lit'; +import { property } from 'lit/decorators.js'; +import { createRef, ref } from 'lit/directives/ref.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 { resolveSwatch, swatchKey } from './common.js'; +import { styles } from './themes/color-swatch.base.css.js'; + +/** A `var()` reference, the only context that a swatch color resolves. */ +const VAR_REFERENCE = /\bvar\(/i; + +/** + * 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(); + } + ); + + private readonly _fillRef = createRef(); + + /** 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; + + private get _color(): string { + return this.color?.trim() ?? ''; + } + + private get _accessibleName(): string { + return this.label || this._color || this._panel.value?.noColorLabel() || ''; + } + + //#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 + * string, or "No color" for the no-color swatch. + * + * @attr label + */ + @property() + public label?: string; + + //#endregion + + constructor() { + super(); + + // The panel sets `ariaSelected` and the selected state through + // `internalsOf()`. + addInternalsController(this, { + initialARIA: { role: 'option', ariaSelected: 'false' }, + reflectRole: true, + reflectLabel: true, + aria: () => ({ ariaLabel: this._accessibleName }), + }); + } + + //#region Lit lifecycle methods + + public override disconnectedCallback(): void { + super.disconnectedCallback(); + this._panel.value?.refreshSwatches(); + } + + 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._key = ''; + return; + } + + let model = ColorModel.parse(color); + + // The parser rejects `var()`. The fill of the swatch resolves it, after + // the first render. + if ( + model.isEmpty && + VAR_REFERENCE.test(color) && + CSS.supports('color', color) + ) { + const fill = this._fillRef.value; + + this._contextual = true; + + if (fill) { + const style = getComputedStyle(fill); + // An undefined variable or one that is not a color makes the fill + // transparent, which is not the color of the swatch. + const resolved = style.getPropertyValue('--_color').trim(); + + if (resolved && CSS.supports('color', resolved)) { + model = ColorModel.parse(style.backgroundColor); + } + } + } + + this._key = model.isEmpty ? null : colorKey(model); + } + + //#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..1a2f7c364 --- /dev/null +++ b/src/components/color-panel/common.ts @@ -0,0 +1,84 @@ +import type { ColorPanelView } from '../types.js'; + +/** + * Moves the canvas marker to the saturation and value of the color. + * + * @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'); + +/** 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', +] 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..15d47e1ef --- /dev/null +++ b/src/components/color-panel/spec.md @@ -0,0 +1,489 @@ +# 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) + - [Swatches](#swatches) + - [Views](#views) + - [Recent colors](#recent-colors) + - [Events](#events-1) + - [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) + - [Swatches](#swatches-1) + - [Swatch keyboard](#swatch-keyboard) + - [Views](#views-1) + - [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-24 | Review fixes: one selected swatch, `var()` only, a plain swatch fill, the format names from the resource strings, the panel theme files | + +## 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 HSV saturation and value canvas, 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. +- **Three serialization formats**, switchable at run time without altering the represented color. +- **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. + +## 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. + +### 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. +- 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. + +#### 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`. +- **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 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 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. + +#### In the color picker + +The color picker renders a panel in its popup. It passes `format`, `show-alpha`, `hide-formats`, `swatches`, `views`, +`active-view` 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 seven 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"), and the format names `color_picker_format_hex` ("Hex"), `color_picker_format_rgb` ("RGB") and +`color_picker_format_hsl` ("HSL"). Until it does, every locale shows the English text, and `resourceStrings` can +replace them. + +### 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. | +| 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`. | +| 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 saturation and value canvas. | +| `marker` | The marker on the canvas that shows the saturation and value. | +| `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. | + +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. Without it, the name is the color string or "No color". | + +| 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. + +### 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, the empty value for an invalid color and a context color, the hue of a gray kept +for a write of the same color, 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. + +### Swatches + +The a11y audit with groups, the named listbox, the `swatches` property in front of the children, the names (label, +color, "No color", the strings of the panel), 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. + +## 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; it silently does nothing + where it is unavailable or denied. +- 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. +- The selected mark of a swatch, the swatch focus ring, the group label and the view switcher 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`. +- The canvas marker is a `slider` with `aria-valuetext` for both axes. +- The format select and the color value input have visually hidden labels. +- The copy and eye dropper buttons expose visually hidden text. +- The swatch list is a `listbox` named "Color swatches". Each swatch is an `option` with `aria-selected`, named by its + label or its color. 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 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 saturation and value canvas 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..4cca86b89 --- /dev/null +++ b/src/components/color-panel/themes/color-panel.base.scss @@ -0,0 +1,124 @@ +@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); + } +} + +@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..ab65ab6c5 --- /dev/null +++ b/src/components/color-panel/themes/shared/color-panel.common.scss @@ -0,0 +1,183 @@ +@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')); + } + + [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-picker.spec.ts b/src/components/color-picker/color-picker.spec.ts index 9aff60a01..625488dd7 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, @@ -13,6 +14,7 @@ import { } from 'igniteui-i18n-core'; import { ColorPickerResourceStringsBG } from 'igniteui-i18n-resources'; import { spy, stub } from 'sinon'; +import { internalsOf } from '#internals/controllers/internals.js'; import { altKey, arrowDown, @@ -51,6 +53,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 +71,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,7 +91,7 @@ async function pickSwatch( picker.swatches = [color]; await elementUpdated(picker); simulateClick( - picker.renderRoot.querySelector('button[part="swatch"]')! + getPanelRoot(picker).querySelector('[part~="swatch"]')! ); await elementUpdated(picker); } @@ -92,7 +108,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 +123,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 +179,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 +229,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 +393,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 +405,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 +438,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 +505,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 +610,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 +1238,23 @@ 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('#ff0000'); + expect(buttons[0].color).to.equal('#ff0000'); const inputSpy = spy(picker, 'emitEvent'); buttons[1].click(); @@ -1187,12 +1268,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 +1289,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 +1310,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 +1333,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 +1359,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 +1377,7 @@ describe('Color picker', () => { const { value } = picker; const eventSpy = spy(picker, 'emitEvent'); - picker.renderRoot + getPanelRoot(picker) .querySelector('[part="eye-dropper"]')! .click(); picker.disabled = true; @@ -1534,6 +1620,363 @@ 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('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', + ]; + + 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('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 +2014,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..e7f9a317e 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 { 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,38 @@ 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 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 } 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 +82,19 @@ const Slots = setSlots( 'value-missing', 'custom-error', 'invalid', - 'helper-text' + 'helper-text', + 'clear-icon' ); -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. + * and the optional alpha slider. 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,6 +106,8 @@ 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. * * @fires igcOpening - Emitted before the user opens the picker dropdown. Cancelable. * @fires igcOpened - Emitted after the picker dropdown opens on a user action. @@ -143,7 +120,13 @@ function getEyeDropper(): EyeDropperConstructor | undefined { * @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. @@ -158,8 +141,12 @@ 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. * * @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 +160,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 +172,8 @@ export default class IgcColorPickerComponent extends I18nMixin( IgcInputComponent, IgcPopoverComponent, IgcFocusTrapComponent, - IgcSelectComponent, - IgcSelectItemComponent, - IgcPickerCanvasComponent, - IgcDividerComponent, - IgcButtonComponent, - IgcIconButtonComponent, + IgcIconComponent, + IgcColorPanelComponent, IgcValidationContainerComponent, IgcVisuallyHiddenComponent ); @@ -210,8 +193,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 +201,24 @@ 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(); + 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; + }, + }; @query(`#${HELPER_TEXT_ID}`) private readonly _helperText!: IgcValidationContainerComponent | null; @@ -259,16 +248,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._color = color; + } + this._updateColor(); } @@ -320,13 +319,43 @@ 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. + * 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); + } + //#endregion //#region Lifecycle @@ -342,19 +371,10 @@ export default class IgcColorPickerComponent extends I18nMixin( .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, - }); + addContextProvider(this, { + context: colorPickerContext, + value: () => this._pickerContext, + }); addAriaProjector(this, { target: () => this._inputAnchor, @@ -368,11 +388,17 @@ export default class IgcColorPickerComponent extends I18nMixin( 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 +409,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]()); } } @@ -416,235 +442,51 @@ 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 { - 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}%` : ''; - - 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); - } - - /** - * 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}%`; - } - } - - private _handleFormatChange( - event: CustomEvent - ): void { - stopPropagation(event); - this.format = event.detail.value as ColorFormat; - } - private _handleColorInputChange(event: CustomEvent): void { stopPropagation(event); - const input = event.target as IgcInputComponent; - const cleared = !event.detail?.trim(); - const color = ColorModel.parse(event.detail); + const color = parseTypedColor(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); + if (!color) { + (event.target as IgcInputComponent).value = this._color.asString( + this.format + ); return; } this._color = color; // A commit of the text input, so no `igcInput`. this._writeFrom('user', () => this._updateColor()); - this._syncCanvasPosition(); - } - - private _handleEyeDropperClick(): void { - const EyeDropper = getEyeDropper(); - - if (!EyeDropper) return; - - 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(() => {}); } - 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'); - } - } - - //#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 _handlePanelInput(event: CustomEvent): void { + stopPropagation(event); - private _setHostColor(name: string, value: string): void { - if (this._appliedProperties.get(name) !== value) { - this._appliedProperties.set(name, value); - this.style.setProperty(name, value); + if (this._takePanelColor()) { + this._emitInputEvent(); } } - /** 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); + /** The end of a change in the panel. The picker reports it when the focus leaves. */ + private _handlePanelChange(event: CustomEvent): void { + stopPropagation(event); + this._takePanelColor(); } - private _setAlpha(percent: number): void { - const alpha = clamp(percent, 0, 100) / 100; - - if (this._color.alpha === alpha) { + /** A clear by the user: `igcInput` now, `igcChange` when the focus leaves. */ + private _handleClearClick(): void { + if (this.disabled) { return; } - this._color.alpha = alpha; + this._color = ColorModel.empty(); this._applyUserColor(); } + //#endregion + + //#region Internal methods + private _updateColor(): void { this._formValue.setValueAndFormState(this._color.asString(this.format)); this.requestUpdate(); @@ -672,19 +514,28 @@ 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. A disabled picker + * renders its own color into the panel again, for an eye dropper pick that + * ends after the picker is disabled. + */ + 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; + } - const [, s, v] = this._color.toHSV(); - const x = (s / 100) * rect.width - markerWidth; - const y = ((100 - v) / 100) * rect.height - markerHeight; + if (this.disabled) { + this.requestUpdate(); + return false; + } + + // The model of the panel keeps the hue of a gray. + this._color = panel[panelColor](); + this._writeFrom('user', () => this._updateColor()); - this._canvasRef.value.x = x; - this._canvasRef.value.y = y; + return true; } private _emitInputEvent(): void { @@ -709,210 +560,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 @@ -934,13 +587,13 @@ export default class IgcColorPickerComponent extends I18nMixin( * surface. Do not transpose the two. See the `swatch-preview` mixin. */ private _previewStyle(): ReturnType { - const color = this._alphaColor; + const color = colorKey(this._color); return bindIf( color, styleMap({ '--_alpha-preview': color, - '--_color-preview': this._opaqueColor, + '--_color-preview': opaqueColor(this._color), }) ); } @@ -974,11 +627,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,17 +683,22 @@ 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())} + + + `; diff --git a/src/components/color-picker/color.property.spec.ts b/src/components/color-picker/color.property.spec.ts index 591802c84..0e281e84c 100644 --- a/src/components/color-picker/color.property.spec.ts +++ b/src/components/color-picker/color.property.spec.ts @@ -154,6 +154,77 @@ 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, 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/i18n.ts b/src/components/color-picker/i18n.ts new file mode 100644 index 000000000..c6c23183f --- /dev/null +++ b/src/components/color-picker/i18n.ts @@ -0,0 +1,55 @@ +import { + ColorPickerResourceStringsEN, + type IColorPickerResourceStrings, +} from 'igniteui-i18n-core'; +import type { I18nMixinConfig } from '#internals/mixins/i18n.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 clear icon in input mode. */ + color_picker_clear?: string; +} + +/** The resource strings of the color picker and the color panel. */ +export type IgcColorPickerResourceStrings = IColorPickerResourceStrings & + IgcColorPickerPendingResourceStrings; + +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_clear: 'Clear color', + }; + +/** 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..0e5799602 100644 --- a/src/components/color-picker/model.spec.ts +++ b/src/components/color-picker/model.spec.ts @@ -129,6 +129,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', () => { diff --git a/src/components/color-picker/model.ts b/src/components/color-picker/model.ts index c4a5fdccd..87533980f 100644 --- a/src/components/color-picker/model.ts +++ b/src/components/color-picker/model.ts @@ -29,6 +29,37 @@ export function rgbString(rgb: RGB, alpha: number | null = null): string { 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%)', +}; + +/** + * 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. */ @@ -56,8 +87,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()); diff --git a/src/components/color-picker/picker-canvas.spec.ts b/src/components/color-picker/picker-canvas.spec.ts index 468c5d9fe..8392a6ab3 100644 --- a/src/components/color-picker/picker-canvas.spec.ts +++ b/src/components/color-picker/picker-canvas.spec.ts @@ -6,6 +6,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 +19,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() { @@ -142,37 +146,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 +205,107 @@ 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('Pointer interaction', () => { diff --git a/src/components/color-picker/picker-canvas.ts b/src/components/color-picker/picker-canvas.ts index e13d089ee..47a234f7b 100644 --- a/src/components/color-picker/picker-canvas.ts +++ b/src/components/color-picker/picker-canvas.ts @@ -8,6 +8,11 @@ import { arrowLeft, arrowRight, arrowUp, + endKey, + homeKey, + pageDownKey, + pageUpKey, + shiftKey, } from '#internals/controllers/key-bindings.js'; import { registerComponent } from '#internals/definitions/register.js'; import { EventEmitterMixin } from '#internals/mixins/event-emitter.js'; @@ -36,18 +41,60 @@ 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 saturation/value plane of the color panel and the marker that moves + * across it. * - * 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 dragging - Present on the marker while it is being dragged. @@ -131,11 +178,13 @@ export default class IgcPickerCanvasComponent extends EventEmitterMixin this._step(dx, dy)); + } } protected override updated(properties: PropertyValues): void { @@ -186,8 +235,29 @@ export default class IgcPickerCanvasComponent extends EventEmitterMixin