@commmerce/ui 1.16.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Where a colour picker gets the merchant's brand colours and their recent custom colours (since 1.17.0).
3
+ *
4
+ * The picker only needs an object with these three optional methods, so any of these work as `source`:
5
+ * - `app.colors` from `@commmerce/app-bridge` in an app embedded in the admin (the admin answers from the brand
6
+ * settings and remembers recents per staff member);
7
+ * - `httpColorSource({ baseUrl })` for your own server speaking the Colour API below;
8
+ * - `localColorSource(key)` for recents kept in this browser only (no brand colours);
9
+ * - your own object.
10
+ *
11
+ * Colour API (HTTP, JSON; the reference server is examples/color-api):
12
+ * - `GET {baseUrl}/brand-colors` → `{ "colors": [{ "value": "#2e6faf", "name": "Primary" }] }`
13
+ * - `GET {baseUrl}/recent-colors` → `{ "colors": ["#2e6faf", "rgba(222, 0, 0, 0.5)"] }` (newest first)
14
+ * - `POST {baseUrl}/recent-colors` with `{ "color": "#2e6faf" }` → the new list, same shape as GET.
15
+ * The server puts the colour first, removes an earlier copy and keeps at most 16.
16
+ * Recents belong to the signed-in staff member and store; brand colours to the store.
17
+ */
18
+ /** A colour with an optional name, e.g. `{ value: '#2e6faf', name: 'Primary' }`. Any CSS colour or gradient. */
19
+ export interface ColorSwatch {
20
+ value: string;
21
+ name?: string;
22
+ }
23
+ export interface ColorSource {
24
+ /** The store's brand colours, in the order the merchant set them. */
25
+ brandColors?(): Promise<Array<string | ColorSwatch>>;
26
+ /** Recent custom colours, newest first. */
27
+ recentColors?(): Promise<string[]>;
28
+ /** Remember a colour the merchant committed. Returns the new list (newest first) when it has it. */
29
+ addRecentColor?(color: string): Promise<string[] | void>;
30
+ }
31
+ /** How many recent colours a picker shows and a local source keeps. */
32
+ export declare const MAX_RECENT = 16;
33
+ /** Puts `color` first, drops an earlier copy (ignoring case) and keeps at most `max`. */
34
+ export declare function pushRecent(list: readonly string[], color: string, max?: number): string[];
35
+ /**
36
+ * Recents kept in this browser's `localStorage` under `cm-recent-colors:<key>`. Each device has its own list; use
37
+ * `httpColorSource` or App Bridge to follow the merchant across devices. Never throws (private windows, blocked storage).
38
+ */
39
+ export declare function localColorSource(key?: string, max?: number): ColorSource;
40
+ export interface HttpColorSourceOptions {
41
+ /** Base URL of the Colour API, e.g. `/api/colors` or `https://shop.example.com/api/colors`. */
42
+ baseUrl: string;
43
+ /** Extra request headers, e.g. `{ Authorization: 'Bearer …' }`. A function is called for every request. */
44
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
45
+ /** `fetch` credentials mode. Default `same-origin`. */
46
+ credentials?: RequestCredentials;
47
+ /** A `fetch` to use instead of the global one (tests, App Bridge authenticated fetch). */
48
+ fetch?: typeof fetch;
49
+ }
50
+ /** A source backed by the Colour API (see the top of this file). Requests that fail reject; the picker then shows no list. */
51
+ export declare function httpColorSource(opts: HttpColorSourceOptions): ColorSource;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Where a colour picker gets the merchant's brand colours and their recent custom colours (since 1.17.0).
3
+ *
4
+ * The picker only needs an object with these three optional methods, so any of these work as `source`:
5
+ * - `app.colors` from `@commmerce/app-bridge` in an app embedded in the admin (the admin answers from the brand
6
+ * settings and remembers recents per staff member);
7
+ * - `httpColorSource({ baseUrl })` for your own server speaking the Colour API below;
8
+ * - `localColorSource(key)` for recents kept in this browser only (no brand colours);
9
+ * - your own object.
10
+ *
11
+ * Colour API (HTTP, JSON; the reference server is examples/color-api):
12
+ * - `GET {baseUrl}/brand-colors` → `{ "colors": [{ "value": "#2e6faf", "name": "Primary" }] }`
13
+ * - `GET {baseUrl}/recent-colors` → `{ "colors": ["#2e6faf", "rgba(222, 0, 0, 0.5)"] }` (newest first)
14
+ * - `POST {baseUrl}/recent-colors` with `{ "color": "#2e6faf" }` → the new list, same shape as GET.
15
+ * The server puts the colour first, removes an earlier copy and keeps at most 16.
16
+ * Recents belong to the signed-in staff member and store; brand colours to the store.
17
+ */
18
+ /** How many recent colours a picker shows and a local source keeps. */
19
+ export const MAX_RECENT = 16;
20
+ /** Puts `color` first, drops an earlier copy (ignoring case) and keeps at most `max`. */
21
+ export function pushRecent(list, color, max = MAX_RECENT) {
22
+ const key = color.trim().toLowerCase();
23
+ return [color.trim(), ...list.filter((c) => c.trim().toLowerCase() !== key)].slice(0, max);
24
+ }
25
+ /**
26
+ * Recents kept in this browser's `localStorage` under `cm-recent-colors:<key>`. Each device has its own list; use
27
+ * `httpColorSource` or App Bridge to follow the merchant across devices. Never throws (private windows, blocked storage).
28
+ */
29
+ export function localColorSource(key = 'default', max = MAX_RECENT) {
30
+ const id = `cm-recent-colors:${key}`;
31
+ const read = () => {
32
+ try {
33
+ const v = JSON.parse(localStorage.getItem(id) ?? '[]');
34
+ return Array.isArray(v) ? v.filter((c) => typeof c === 'string').slice(0, max) : [];
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ };
40
+ return {
41
+ recentColors: async () => read(),
42
+ async addRecentColor(color) {
43
+ const next = pushRecent(read(), color, max);
44
+ try {
45
+ localStorage.setItem(id, JSON.stringify(next));
46
+ }
47
+ catch { /* storage blocked: keep the list in memory only */ }
48
+ return next;
49
+ },
50
+ };
51
+ }
52
+ /** A source backed by the Colour API (see the top of this file). Requests that fail reject; the picker then shows no list. */
53
+ export function httpColorSource(opts) {
54
+ const base = opts.baseUrl.replace(/\/+$/, '');
55
+ const call = async (path, init = {}) => {
56
+ const extra = typeof opts.headers === 'function' ? await opts.headers() : opts.headers ?? {};
57
+ const res = await (opts.fetch ?? fetch)(`${base}${path}`, {
58
+ credentials: opts.credentials ?? 'same-origin',
59
+ ...init,
60
+ headers: { Accept: 'application/json', ...(init.body ? { 'Content-Type': 'application/json' } : {}), ...extra },
61
+ });
62
+ if (!res.ok)
63
+ throw new Error(`Colour API ${path}: HTTP ${res.status}`);
64
+ const body = await res.json();
65
+ return Array.isArray(body?.colors) ? body.colors : [];
66
+ };
67
+ return {
68
+ brandColors: () => call('/brand-colors'),
69
+ recentColors: async () => (await call('/recent-colors')).filter((c) => typeof c === 'string'),
70
+ addRecentColor: async (color) => (await call('/recent-colors', { method: 'POST', body: JSON.stringify({ color }) }))
71
+ .filter((c) => typeof c === 'string'),
72
+ };
73
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Colour maths for cm-color-picker and cm-color-field (since 1.17.0): parse and write CSS colours and simple
3
+ * gradients, convert between RGB, HSV and HSL. No DOM. Channels: r/g/b 0-255, h 0-360, s/v/l 0-100, a 0-1.
4
+ */
5
+ export interface Rgba {
6
+ r: number;
7
+ g: number;
8
+ b: number;
9
+ a: number;
10
+ }
11
+ export interface Hsva {
12
+ h: number;
13
+ s: number;
14
+ v: number;
15
+ a: number;
16
+ }
17
+ export interface Hsla {
18
+ h: number;
19
+ s: number;
20
+ l: number;
21
+ a: number;
22
+ }
23
+ /** How the picker writes colours. `hex` is `#rrggbb`, or `#rrggbbaa` when the colour is see-through. */
24
+ export type ColorFormat = 'hex' | 'rgb' | 'hsl';
25
+ export interface GradientStop {
26
+ color: Rgba; /** 0-100 */
27
+ position: number;
28
+ }
29
+ export interface Gradient {
30
+ type: 'linear' | 'radial';
31
+ /** Linear only: degrees, 0 = to top, 90 = to right. */
32
+ angle: number;
33
+ stops: GradientStop[];
34
+ }
35
+ /** `#RGB`, `RRGGBB`, `#RRGGBB` (any case, spaces around) -> `#rrggbb`; anything else -> null. */
36
+ export declare function normalizeHex(text: string): string | null;
37
+ /** Parses hex (3, 4, 6, 8 digits), `rgb()`/`rgba()`, `hsl()`/`hsla()` and `transparent`. Other text -> null. */
38
+ export declare function parseColor(text: string): Rgba | null;
39
+ export declare function rgbToHsv({ r, g, b, a }: Rgba): Hsva;
40
+ export declare function hsvToRgb({ h, s, v, a }: Hsva): Rgba;
41
+ export declare function rgbToHsl({ r, g, b, a }: Rgba): Hsla;
42
+ export declare function hslToRgb({ h, s, l, a }: Hsla): Rgba;
43
+ /** `#rrggbb`, ignoring alpha. */
44
+ export declare const toHex6: ({ r, g, b }: Rgba) => string;
45
+ /** Writes a colour: `#rrggbb` / `#rrggbbaa`, `rgb(46, 111, 175)` / `rgba(…, 0.5)`, `hsl(210, 58%, 43%)` / `hsla(…)`. */
46
+ export declare function formatColor(c: Rgba, format?: ColorFormat): string;
47
+ /**
48
+ * Parses `linear-gradient(…)` and `radial-gradient(…)` with colours this file understands, an optional angle or
49
+ * `to <side>` (linear) and an optional shape (radial, read as a circle from the centre). Stops without a position are
50
+ * spread evenly. Returns null for anything else (repeating gradients, colour hints, two positions per stop).
51
+ */
52
+ export declare function parseGradient(text: string): Gradient | null;
53
+ /** Writes a gradient with stops sorted by position, e.g. `linear-gradient(90deg, #2e6faf 0%, #de0000 100%)`. */
54
+ export declare function formatGradient(g: Gradient, format?: ColorFormat): string;
55
+ /** The colour at `position` (0-100) along the gradient's stops, for a stop added by clicking the bar. */
56
+ export declare function colorAt(g: Gradient, position: number): Rgba;
57
+ /** Same colour (ignoring how it is written)? Gradients compare by their written form. */
58
+ export declare function sameColor(x: string, y: string): boolean;
59
+ /** True for any value the picker can show: a colour or a gradient this file parses. */
60
+ export declare const isColorValue: (text: string) => boolean;
package/dist/color.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Colour maths for cm-color-picker and cm-color-field (since 1.17.0): parse and write CSS colours and simple
3
+ * gradients, convert between RGB, HSV and HSL. No DOM. Channels: r/g/b 0-255, h 0-360, s/v/l 0-100, a 0-1.
4
+ */
5
+ const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
6
+ const round = (n, d = 0) => { const f = 10 ** d; return Math.round(n * f) / f; };
7
+ /** `#RGB`, `RRGGBB`, `#RRGGBB` (any case, spaces around) -> `#rrggbb`; anything else -> null. */
8
+ export function normalizeHex(text) {
9
+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());
10
+ if (!m)
11
+ return null;
12
+ const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1];
13
+ return `#${h.toLowerCase()}`;
14
+ }
15
+ function num(token, max) {
16
+ const m = /^(-?\d*\.?\d+(?:e-?\d+)?)(%)?$/i.exec(token.trim());
17
+ if (!m)
18
+ return null;
19
+ const n = parseFloat(m[1]);
20
+ return m[2] ? (n / 100) * max : n;
21
+ }
22
+ function hueOf(token) {
23
+ const m = /^(-?\d*\.?\d+)(deg|turn|rad|grad)?$/i.exec(token.trim());
24
+ if (!m)
25
+ return null;
26
+ const n = parseFloat(m[1]);
27
+ const unit = (m[2] ?? 'deg').toLowerCase();
28
+ const deg = unit === 'turn' ? n * 360 : unit === 'rad' ? (n * 180) / Math.PI : unit === 'grad' ? n * 0.9 : n;
29
+ return ((deg % 360) + 360) % 360;
30
+ }
31
+ /** `1 2 3 / 50%` or `1, 2, 3, 0.5` -> four tokens (alpha may be missing). */
32
+ function args(inner) {
33
+ const s = inner.trim();
34
+ let parts;
35
+ if (s.includes(','))
36
+ parts = s.split(',').map((p) => p.trim());
37
+ else {
38
+ const [main, alpha] = s.split('/').map((p) => p.trim());
39
+ parts = main.split(/\s+/);
40
+ if (alpha !== undefined)
41
+ parts.push(alpha);
42
+ }
43
+ return parts.length === 3 || parts.length === 4 ? parts : null;
44
+ }
45
+ /** Parses hex (3, 4, 6, 8 digits), `rgb()`/`rgba()`, `hsl()`/`hsla()` and `transparent`. Other text -> null. */
46
+ export function parseColor(text) {
47
+ const t = (text ?? '').trim().toLowerCase();
48
+ if (!t)
49
+ return null;
50
+ if (t === 'transparent')
51
+ return { r: 0, g: 0, b: 0, a: 0 };
52
+ const hex = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);
53
+ if (hex) {
54
+ let h = hex[1];
55
+ if (h.length <= 4)
56
+ h = [...h].map((c) => c + c).join('');
57
+ const n = (i) => parseInt(h.slice(i, i + 2), 16);
58
+ return { r: n(0), g: n(2), b: n(4), a: h.length === 8 ? round(n(6) / 255, 3) : 1 };
59
+ }
60
+ const fn = /^(rgba?|hsla?)\((.*)\)$/.exec(t);
61
+ if (!fn)
62
+ return null;
63
+ const p = args(fn[2]);
64
+ if (!p)
65
+ return null;
66
+ const a = p[3] === undefined ? 1 : num(p[3], 1);
67
+ if (a === null)
68
+ return null;
69
+ if (fn[1].startsWith('rgb')) {
70
+ const [r, g, b] = p.slice(0, 3).map((x) => num(x, 255));
71
+ if (r === null || g === null || b === null)
72
+ return null;
73
+ return { r: clamp(Math.round(r), 0, 255), g: clamp(Math.round(g), 0, 255), b: clamp(Math.round(b), 0, 255), a: clamp(round(a, 3), 0, 1) };
74
+ }
75
+ const h = hueOf(p[0]);
76
+ const s = num(p[1].endsWith('%') ? p[1] : `${p[1]}%`, 100), l = num(p[2].endsWith('%') ? p[2] : `${p[2]}%`, 100);
77
+ if (h === null || s === null || l === null)
78
+ return null;
79
+ return { ...hslToRgb({ h, s: clamp(s, 0, 100), l: clamp(l, 0, 100), a: 1 }), a: clamp(round(a, 3), 0, 1) };
80
+ }
81
+ export function rgbToHsv({ r, g, b, a }) {
82
+ const R = r / 255, G = g / 255, B = b / 255;
83
+ const max = Math.max(R, G, B), min = Math.min(R, G, B), d = max - min;
84
+ let h = 0;
85
+ if (d)
86
+ h = max === R ? ((G - B) / d) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
87
+ return { h: ((h * 60) + 360) % 360, s: max ? (d / max) * 100 : 0, v: max * 100, a };
88
+ }
89
+ export function hsvToRgb({ h, s, v, a }) {
90
+ const S = s / 100, V = v / 100;
91
+ const f = (n) => { const k = (n + h / 60) % 6; return V - V * S * Math.max(0, Math.min(k, 4 - k, 1)); };
92
+ return { r: Math.round(f(5) * 255), g: Math.round(f(3) * 255), b: Math.round(f(1) * 255), a };
93
+ }
94
+ export function rgbToHsl({ r, g, b, a }) {
95
+ const R = r / 255, G = g / 255, B = b / 255;
96
+ const max = Math.max(R, G, B), min = Math.min(R, G, B), d = max - min, l = (max + min) / 2;
97
+ const s = d ? d / (1 - Math.abs(2 * l - 1)) : 0;
98
+ return { h: rgbToHsv({ r, g, b, a }).h, s: s * 100, l: l * 100, a };
99
+ }
100
+ export function hslToRgb({ h, s, l, a }) {
101
+ const S = s / 100, L = l / 100, k = (n) => (n + h / 30) % 12, A = S * Math.min(L, 1 - L);
102
+ const f = (n) => L - A * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
103
+ return { r: Math.round(f(0) * 255), g: Math.round(f(8) * 255), b: Math.round(f(4) * 255), a };
104
+ }
105
+ const hex2 = (n) => Math.round(n).toString(16).padStart(2, '0');
106
+ /** `#rrggbb`, ignoring alpha. */
107
+ export const toHex6 = ({ r, g, b }) => `#${hex2(r)}${hex2(g)}${hex2(b)}`;
108
+ /** Writes a colour: `#rrggbb` / `#rrggbbaa`, `rgb(46, 111, 175)` / `rgba(…, 0.5)`, `hsl(210, 58%, 43%)` / `hsla(…)`. */
109
+ export function formatColor(c, format = 'hex') {
110
+ const a = round(clamp(c.a, 0, 1), 2), see = a < 1;
111
+ if (format === 'rgb')
112
+ return see ? `rgba(${c.r}, ${c.g}, ${c.b}, ${a})` : `rgb(${c.r}, ${c.g}, ${c.b})`;
113
+ if (format === 'hsl') {
114
+ const { h, s, l } = rgbToHsl(c);
115
+ const body = `${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%`;
116
+ return see ? `hsla(${body}, ${a})` : `hsl(${body})`;
117
+ }
118
+ return see ? `${toHex6(c)}${hex2(a * 255)}` : toHex6(c);
119
+ }
120
+ /** Splits on commas that aren't inside brackets. */
121
+ function topLevel(s) {
122
+ const out = [];
123
+ let depth = 0, start = 0;
124
+ for (let i = 0; i < s.length; i++) {
125
+ if (s[i] === '(')
126
+ depth++;
127
+ else if (s[i] === ')')
128
+ depth--;
129
+ else if (s[i] === ',' && depth === 0) {
130
+ out.push(s.slice(start, i).trim());
131
+ start = i + 1;
132
+ }
133
+ }
134
+ out.push(s.slice(start).trim());
135
+ return out;
136
+ }
137
+ const SIDES = {
138
+ 'to top': 0, 'to top right': 45, 'to right top': 45, 'to right': 90, 'to bottom right': 135, 'to right bottom': 135,
139
+ 'to bottom': 180, 'to bottom left': 225, 'to left bottom': 225, 'to left': 270, 'to top left': 315, 'to left top': 315,
140
+ };
141
+ /**
142
+ * Parses `linear-gradient(…)` and `radial-gradient(…)` with colours this file understands, an optional angle or
143
+ * `to <side>` (linear) and an optional shape (radial, read as a circle from the centre). Stops without a position are
144
+ * spread evenly. Returns null for anything else (repeating gradients, colour hints, two positions per stop).
145
+ */
146
+ export function parseGradient(text) {
147
+ const m = /^(linear|radial)-gradient\((.*)\)$/i.exec((text ?? '').trim());
148
+ if (!m)
149
+ return null;
150
+ const type = m[1].toLowerCase();
151
+ const parts = topLevel(m[2]);
152
+ let angle = 180;
153
+ const first = parts[0]?.toLowerCase().replace(/\s+/g, ' ') ?? '';
154
+ if (type === 'linear') {
155
+ const deg = hueOf(first);
156
+ if (deg !== null && /[a-z]/.test(first)) {
157
+ angle = deg;
158
+ parts.shift();
159
+ }
160
+ else if (first in SIDES) {
161
+ angle = SIDES[first];
162
+ parts.shift();
163
+ }
164
+ }
165
+ else if (/^(circle|ellipse|closest|farthest|at )/.test(first) && !parseColor(first.split(' ')[0]))
166
+ parts.shift();
167
+ const raw = parts.map((p) => {
168
+ const sp = /^(.*?)(?:\s+(-?\d*\.?\d+)%)?$/.exec(p);
169
+ return { color: parseColor(sp[1]), position: sp[2] === undefined ? undefined : clamp(parseFloat(sp[2]), 0, 100) };
170
+ });
171
+ if (raw.length < 2 || raw.some((s) => !s.color))
172
+ return null;
173
+ const stops = raw.map((s, i) => ({ color: s.color, position: s.position ?? round((i / (raw.length - 1)) * 100, 1) }));
174
+ return { type, angle: Math.round(angle), stops };
175
+ }
176
+ /** Writes a gradient with stops sorted by position, e.g. `linear-gradient(90deg, #2e6faf 0%, #de0000 100%)`. */
177
+ export function formatGradient(g, format = 'hex') {
178
+ const stops = [...g.stops].sort((a, b) => a.position - b.position)
179
+ .map((s) => `${formatColor(s.color, format)} ${round(s.position, 1)}%`).join(', ');
180
+ return g.type === 'radial' ? `radial-gradient(circle, ${stops})` : `linear-gradient(${Math.round(g.angle)}deg, ${stops})`;
181
+ }
182
+ /** The colour at `position` (0-100) along the gradient's stops, for a stop added by clicking the bar. */
183
+ export function colorAt(g, position) {
184
+ const s = [...g.stops].sort((a, b) => a.position - b.position);
185
+ if (position <= s[0].position)
186
+ return { ...s[0].color };
187
+ for (let i = 1; i < s.length; i++) {
188
+ if (position <= s[i].position) {
189
+ const A = s[i - 1], B = s[i], t = (position - A.position) / ((B.position - A.position) || 1);
190
+ const mix = (x, y) => x + (y - x) * t;
191
+ return { r: Math.round(mix(A.color.r, B.color.r)), g: Math.round(mix(A.color.g, B.color.g)), b: Math.round(mix(A.color.b, B.color.b)), a: round(mix(A.color.a, B.color.a), 2) };
192
+ }
193
+ }
194
+ return { ...s[s.length - 1].color };
195
+ }
196
+ /** Same colour (ignoring how it is written)? Gradients compare by their written form. */
197
+ export function sameColor(x, y) {
198
+ const a = parseColor(x), b = parseColor(y);
199
+ if (a && b)
200
+ return a.r === b.r && a.g === b.g && a.b === b.b && Math.abs(a.a - b.a) < 0.005;
201
+ const ga = parseGradient(x), gb = parseGradient(y);
202
+ return !!ga && !!gb && formatGradient(ga) === formatGradient(gb);
203
+ }
204
+ /** True for any value the picker can show: a colour or a gradient this file parses. */
205
+ export const isColorValue = (text) => !!parseColor(text) || !!parseGradient(text);
@@ -1,5 +1,7 @@
1
1
  import { CmLocalizedElement } from '../localize.js';
2
+ import type { ColorSource, ColorSwatch } from '../color-source.js';
2
3
  import './icon.js';
4
+ import './color-picker.js';
3
5
  declare const strings: {
4
6
  /** Accessible name of each swatch with a name: "Blue, #2e6faf". */
5
7
  swatch: string;
@@ -15,6 +17,11 @@ declare const strings: {
15
17
  required: string;
16
18
  /** Validation message for text that isn't a colour. */
17
19
  invalid: string;
20
+ /** Validation message when the field takes RGB, HSL, opacity or gradients (`formats`, `alpha`, `gradient`). */
21
+ invalidAny: string;
22
+ /** Accessible name of the colour box when it takes more than hex. `valueNamed` is used with a label. */
23
+ value: string;
24
+ valueNamed: string;
18
25
  /** Names of the default swatches. */
19
26
  black: string;
20
27
  grey: string;
@@ -34,25 +41,23 @@ declare module '../localize.js' {
34
41
  colorField: typeof strings;
35
42
  }
36
43
  }
37
- /** A swatch: a colour as `#rrggbb` and an optional name for its accessible name and tooltip. */
38
- export interface ColorSwatch {
39
- value: string;
40
- name?: string;
41
- }
42
- /** `#RGB`, `RRGGBB`, `#RRGGBB` (any case, spaces around) -> `#rrggbb`; anything else -> null. */
43
- export declare function normalizeHex(text: string): string | null;
44
+ export type { ColorSwatch } from '../color-source.js';
45
+ export { normalizeHex } from '../color.js';
44
46
  /**
45
47
  * Black or white, whichever contrasts more with the swatch (always 4.5:1 or more). The swatch colour is data, not
46
48
  * a theme colour, so this pairs it with plain black or white rather than a token that changes with the theme.
47
49
  */
48
50
  export declare function checkColor(hex: string): '#000000' | '#ffffff';
49
51
  /**
50
- * Colour field: a palette of swatches, a hex box and, optionally, the browser's colour picker. For colours that
51
- * mean something to the merchant, such as the colour of each lead status. The value is lowercase `#rrggbb`.
52
+ * Colour field: a palette of swatches, a hex box and, optionally, a colour picker (`picker`): the cm-color-picker
53
+ * panel with the store's brand colours, recent colours, opacity, formats and gradients, or the browser's own
54
+ * (`picker="native"`). For colours that mean something to the merchant, such as the colour of each lead status.
55
+ * The value is lowercase `#rrggbb` unless you allow more with `formats`, `alpha` or `gradient`.
52
56
  * Participates in native forms.
53
57
  * @element cm-color-field
54
58
  * @fires input - When the colour changes: a swatch, a complete hex code typed, or the picker moving.
55
59
  * @fires change - When the colour is committed: a swatch picked, the hex box left or Enter pressed, the picker closed.
60
+ * @fires cm-recent-change - From the picker panel: `detail.colors`, the new recent list.
56
61
  * @csspart label - The label.
57
62
  * @csspart swatches - The swatch radio group.
58
63
  * @csspart swatch - Each swatch.
@@ -84,8 +89,36 @@ export declare class CmColorField extends CmLocalizedElement {
84
89
  type: ArrayConstructor;
85
90
  };
86
91
  picker: {
92
+ converter: {
93
+ fromAttribute: (v: string | null) => boolean | "native";
94
+ toAttribute: (v: unknown) => "" | "native" | null;
95
+ };
96
+ reflect: boolean;
97
+ };
98
+ alpha: {
87
99
  type: BooleanConstructor;
88
100
  };
101
+ gradient: {
102
+ type: BooleanConstructor;
103
+ };
104
+ formats: {};
105
+ brandColors: {
106
+ type: ArrayConstructor;
107
+ attribute: string;
108
+ };
109
+ recentColors: {
110
+ type: ArrayConstructor;
111
+ attribute: string;
112
+ };
113
+ source: {
114
+ attribute: boolean;
115
+ };
116
+ recentKey: {
117
+ attribute: string;
118
+ };
119
+ _open: {
120
+ state: boolean;
121
+ };
89
122
  required: {
90
123
  type: BooleanConstructor;
91
124
  reflect: boolean;
@@ -119,8 +152,29 @@ export declare class CmColorField extends CmLocalizedElement {
119
152
  * In HTML, pass JSON: `swatches='["#2e6faf", {"value": "#de0000", "name": "Lost"}]'`.
120
153
  */
121
154
  swatches?: Array<string | ColorSwatch>;
122
- /** Adds a button that opens the browser's own colour picker, for colours outside the palette. */
123
- picker: boolean;
155
+ /**
156
+ * Adds a button that opens a colour picker for colours outside the palette: the Commmerce picker panel (since
157
+ * 1.17.0), or the browser's own with `picker="native"`.
158
+ */
159
+ picker: boolean | 'native';
160
+ /** Allows see-through colours: the picker shows opacity; the value may be `#rrggbbaa`, `rgba()` or `hsla()`. */
161
+ alpha: boolean;
162
+ /** Allows linear and radial gradients from the picker; the value may then be a CSS gradient. */
163
+ gradient: boolean;
164
+ /**
165
+ * Formats the merchant may pick in the picker, space separated: `hex`, `rgb`, `hsl`. Default `hex` only, so the
166
+ * value stays `#rrggbb`. With more, the value is written in the format they chose.
167
+ */
168
+ formats: string;
169
+ /** The store's brand colours, shown first in the picker. In HTML, pass JSON. Wins over `source`. */
170
+ brandColors?: Array<string | ColorSwatch>;
171
+ /** Recent colours for the picker, newest first. Wins over `source`. */
172
+ recentColors?: string[];
173
+ /** Where the picker gets brand and recent colours: `app.colors` (App Bridge), `httpColorSource()` or your own. */
174
+ source?: ColorSource;
175
+ /** Keeps recent colours in this browser under this key when there is no `source`. */
176
+ recentKey: string;
177
+ _open: boolean;
124
178
  /** Shows a red asterisk and blocks form submission until a colour is chosen. */
125
179
  required: boolean;
126
180
  /** Blocks interaction. Also set by a disabled `<fieldset>`. */
@@ -131,6 +185,10 @@ export declare class CmColorField extends CmLocalizedElement {
131
185
  _invalid: boolean;
132
186
  static styles: import("lit").CSSResult[];
133
187
  connectedCallback(): void;
188
+ disconnectedCallback(): void;
189
+ /** Opens or closes the picker panel. */
190
+ show(): void;
191
+ close(): void;
134
192
  get form(): HTMLFormElement | null;
135
193
  get validity(): ValidityState;
136
194
  get validationMessage(): string;
@@ -142,7 +200,7 @@ export declare class CmColorField extends CmLocalizedElement {
142
200
  /** The swatches in use, normalised, with their names. Invalid colours are left out. */
143
201
  get items(): ColorSwatch[];
144
202
  willUpdate(changed: Map<string, unknown>): void;
145
- updated(): void;
203
+ updated(changed: Map<string, unknown>): void;
146
204
  render(): import("lit-html").TemplateResult<1>;
147
205
  }
148
206
  declare global {
@@ -150,4 +208,3 @@ declare global {
150
208
  'cm-color-field': CmColorField;
151
209
  }
152
210
  }
153
- export {};