@mrpelz/uikit-ish 7.10.0 → 7.11.0

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.
Files changed (57) hide show
  1. package/dist/components/color-picker/color.d.ts +23 -0
  2. package/dist/components/color-picker/color.d.ts.map +1 -0
  3. package/dist/components/color-picker/color.js +150 -0
  4. package/dist/components/color-picker/color.js.map +1 -0
  5. package/dist/components/color-picker/main.d.ts +16 -3
  6. package/dist/components/color-picker/main.d.ts.map +1 -1
  7. package/dist/components/color-picker/main.js +451 -92
  8. package/dist/components/color-picker/main.js.map +1 -1
  9. package/dist/components/color-picker/named-colors.d.ts +3 -0
  10. package/dist/components/color-picker/named-colors.d.ts.map +1 -0
  11. package/dist/components/color-picker/named-colors.js +152 -0
  12. package/dist/components/color-picker/named-colors.js.map +1 -0
  13. package/dist/components/color-picker/props.d.ts +60 -12
  14. package/dist/components/color-picker/props.d.ts.map +1 -1
  15. package/dist/components/color-picker/style.css +201 -21
  16. package/dist/components/edit-menu/main.d.ts.map +1 -1
  17. package/dist/components/edit-menu/main.js +10 -8
  18. package/dist/components/edit-menu/main.js.map +1 -1
  19. package/dist/components/edit-menu/style.css +17 -0
  20. package/dist/components/index.d.ts +2 -2
  21. package/dist/components/index.d.ts.map +1 -1
  22. package/dist/components/index.js.map +1 -1
  23. package/dist/components/menu/main.d.ts +6 -2
  24. package/dist/components/menu/main.d.ts.map +1 -1
  25. package/dist/components/menu/main.js +207 -7
  26. package/dist/components/menu/main.js.map +1 -1
  27. package/dist/components/menu/style.css +6 -2
  28. package/dist/components/popover/main.d.ts +1 -1
  29. package/dist/components/popover/main.d.ts.map +1 -1
  30. package/dist/components/popover/main.js +24 -3
  31. package/dist/components/popover/main.js.map +1 -1
  32. package/dist/components/segmented/main.d.ts.map +1 -1
  33. package/dist/components/segmented/main.js +149 -14
  34. package/dist/components/segmented/main.js.map +1 -1
  35. package/dist/components/segmented/props.d.ts +7 -0
  36. package/dist/components/segmented/props.d.ts.map +1 -1
  37. package/dist/components/segmented/style.css +135 -6
  38. package/dist/components/sheet/main.d.ts +5 -4
  39. package/dist/components/sheet/main.d.ts.map +1 -1
  40. package/dist/components/sheet/main.js +35 -13
  41. package/dist/components/sheet/main.js.map +1 -1
  42. package/dist/components/sheet/props.d.ts +28 -0
  43. package/dist/components/sheet/props.d.ts.map +1 -1
  44. package/dist/components/sheet/style.css +124 -25
  45. package/dist/components/utils/main.d.ts +5 -0
  46. package/dist/components/utils/main.d.ts.map +1 -1
  47. package/dist/components/utils/main.js +8 -1
  48. package/dist/components/utils/main.js.map +1 -1
  49. package/dist/components/viewport/main.d.ts +1 -1
  50. package/dist/components/viewport/main.d.ts.map +1 -1
  51. package/dist/components/viewport/main.js +1 -1
  52. package/dist/components/viewport/main.js.map +1 -1
  53. package/dist/components/viewport/padding.d.ts.map +1 -1
  54. package/dist/components/viewport/padding.js +5 -1
  55. package/dist/components/viewport/padding.js.map +1 -1
  56. package/dist/components/viewport/style.css +22 -3
  57. package/package.json +2 -1
@@ -1,17 +1,22 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import '../button/style.css';
3
+ import '../list/style.css';
3
4
  import '../menu/style.css';
4
5
  import '../page-control/style.css';
5
6
  import '../segmented/style.css';
6
7
  import './style.css';
7
8
  import { Slider as BaseSlider } from '@base-ui/react/slider';
8
- import { cloneElement, createContext, forwardRef, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, } from 'react';
9
+ import { useRender } from '@base-ui/react/use-render';
10
+ import { Children, cloneElement, createContext, forwardRef, Fragment, isValidElement, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
9
11
  import { Button } from '../button/main.js';
12
+ import { List } from '../list/main.js';
10
13
  import { Menu } from '../menu/main.js';
11
14
  import { PageControl } from '../page-control/main.js';
12
15
  import { Segmented } from '../segmented/main.js';
13
- import { cn, useTouchHold, withStyle } from '../utils/main.js';
16
+ import { Checkmark, cn, useForwardedRef, useTouchHold, withStyle, } from '../utils/main.js';
14
17
  import { Viewport } from '../viewport/main.js';
18
+ import { codeGroups, parseCssColor } from './color.js';
19
+ import { cssNamedColors } from './named-colors.js';
15
20
  // A color picker and a color well, in the app's popover (a regular width)
16
21
  // or sheet (compact), its header the app's (a `Toolbar`: the
17
22
  // eyedropper, “Colors”, close):
@@ -20,9 +25,10 @@ import { Viewport } from '../viewport/main.js';
20
25
  // corners 18px, the selected one outlined white (3px);
21
26
  // - Spectrum: hues across, light to dark down (white at the top, pure hues
22
27
  // halfway, black at the bottom), its corners 18px, the color ringed;
23
- // - Sliders: red, green and blue (0 to 255), each a channel's row (see
24
- // `ChannelRow`): its title (all caps), a slider mixing from the color
25
- // (the channel at 0 to 255), and its value, typed;
28
+ // - Sliders: red, green and blue (0 to 255; or 0 to 100%, see `Sliders`),
29
+ // each a channel's row (see `ChannelRow`): its title (all caps), a slider
30
+ // mixing from the color (the channel along its range), and its value,
31
+ // typed;
26
32
  // - Each channel's row kept above the keyboard as its field's typed into
27
33
  // (a `Viewport.KeyboardAccessory`; in a `Viewport.Provider`);
28
34
  // - Opacity (optional: its part, `Opacity`), a channel's row too: the
@@ -39,6 +45,10 @@ import { Viewport } from '../viewport/main.js';
39
45
  // opacity, always opaque).
40
46
  // - The eyedropper (`ColorPicker.Eyedropper`) is the browser's
41
47
  // (`EyeDropper`; not where it has none, e.g. Safari).
48
+ // - The system's color picker (`ColorPicker.SystemColors`) is a color
49
+ // input's (over its button, pressed itself: on iOS, nothing else opens
50
+ // it; with the opacity rendered, its alpha too where the input has one,
51
+ // e.g. Safari; else its colors opaque, the opacity kept).
42
52
  // - Saved colors are deleted by their menu (a secondary click: right click,
43
53
  // long press).
44
54
  // eslint-disable-next-line unicorn/no-unnecessary-parameters
@@ -119,14 +129,28 @@ const sameColor = (a, b) => Math.round(a.r) === Math.round(b.r) &&
119
129
  const unregister = () => undefined;
120
130
  const PickerContext = createContext({
121
131
  color: { a: 1, b: 0, g: 0, r: 0 },
132
+ hasOpacity: false,
122
133
  registerOpacity: () => unregister,
123
134
  setColor: () => undefined,
124
135
  });
125
136
  /**
126
- * A color picker: its color, for its
127
- * parts (`Panel`, `Eyedropper`), in the app's popover or sheet.
137
+ * Its modes (see `Root`): the one shown, chosen by its `Modes`; the first
138
+ * `Mode` (or `View`) unless a default is given.
128
139
  */
129
- const Root = forwardRef(({ className, defaultValue = '#000000', onValueChange, style, value, ...props }, ref) => {
140
+ const PanelContext = createContext({
141
+ isGridHeight: false,
142
+ mode: null,
143
+ registerGridHeight: () => unregister,
144
+ registerMode: () => undefined,
145
+ setMode: () => undefined,
146
+ });
147
+ /**
148
+ * A color picker: its color and its mode, for its parts (`Header`,
149
+ * `Modes`, `Panel`, `Eyedropper`, anywhere in it), in the app's popover or
150
+ * sheet. Its element (`render`) may be the sheet's popup, so its modes'
151
+ * control can be in the sheet's header, not scrolling.
152
+ */
153
+ const Root = forwardRef(({ className, defaultMode, defaultValue = '#000000', mode: modeProp, onModeChange, onValueChange, render, style, value, ...props }, ref) => {
130
154
  const [own, setOwn] = useState(defaultValue);
131
155
  // Its `Opacity`s rendered: without one, the color opaque (its alpha,
132
156
  // if given one, dropped).
@@ -140,6 +164,7 @@ const Root = forwardRef(({ className, defaultValue = '#000000', onValueChange, s
140
164
  }, []);
141
165
  const state = useMemo(() => ({
142
166
  color,
167
+ hasOpacity,
143
168
  registerOpacity,
144
169
  // Uncontrolled: its own state; controlled, only the app's `value`.
145
170
  setColor: (next, details) => {
@@ -152,55 +177,68 @@ const Root = forwardRef(({ className, defaultValue = '#000000', onValueChange, s
152
177
  // (By its hex value.)
153
178
  // eslint-disable-next-line react-hooks/exhaustive-deps
154
179
  [value ?? own, onValueChange, hasOpacity]);
155
- return (_jsx(PickerContext.Provider, { value: state, children: _jsx("div", { ref: ref, style: withStyle({
156
- // (For its parts.)
157
- '--uikit-color-picker-color': formatColor(color),
158
- '--uikit-color-picker-color-opaque': formatColor({
159
- ...color,
160
- a: 1,
161
- }),
162
- }, style), ...props, className: cn('uikit-color-picker-root', className), "data-color-picker-part": "root" }) }));
163
- });
164
- /**
165
- * Its panel's modes (see `Panel`): the one shown, chosen by its `Modes`;
166
- * the first `Mode` (or `View`) unless a default is given.
167
- */
168
- const PanelContext = createContext({
169
- mode: null,
170
- registerMode: () => undefined,
171
- setMode: () => undefined,
172
- });
173
- /**
174
- * Its panel: its modes (`Modes`, a `Mode` each; a `View` each, paired by
175
- * their `value`s), the opacity, the color and the saved colors, as
176
- * composed (in its padding, its parts spaced).
177
- */
178
- const Panel = forwardRef(({ className, defaultMode, mode: modeProp, onModeChange, ...props }, ref) => {
179
180
  const [ownMode, setOwnMode] = useState(defaultMode);
180
181
  // (Without a default: the first mode, as it's rendered.)
181
182
  const [firstMode, setFirstMode] = useState();
182
183
  // (Controlled from the start: none yet, before its first mode is
183
184
  // known, not undefined, which would leave its control uncontrolled.)
184
185
  const mode = modeProp ?? ownMode ?? firstMode ?? null;
185
- const panel = useMemo(() => ({
186
+ // Its views of the grid's height (a `Grid`, a `Spectrum`): with one,
187
+ // all as high (see `View`).
188
+ const [gridHeights, setGridHeights] = useState(0);
189
+ const registerGridHeight = useCallback(() => {
190
+ setGridHeights((count) => count + 1);
191
+ return () => setGridHeights((count) => count - 1);
192
+ }, []);
193
+ const modes = useMemo(() => ({
194
+ isGridHeight: gridHeights > 0,
186
195
  mode,
187
- registerMode: (value) => setFirstMode((first) => first ?? value),
196
+ registerGridHeight,
197
+ registerMode: (next) => setFirstMode((first) => first ?? next),
188
198
  // Uncontrolled: its own state; controlled, only the app's `mode`.
189
199
  setMode: (next, details) => {
190
200
  if (modeProp === undefined)
191
201
  setOwnMode(next);
192
202
  onModeChange?.(next, details);
193
203
  },
194
- }), [mode, modeProp, onModeChange]);
195
- return (_jsx(PanelContext.Provider, { value: panel, children: _jsx("div", { ref: ref, ...props, className: cn('uikit-color-picker-panel', className), "data-color-picker-part": "panel" }) }));
204
+ }), [gridHeights, mode, modeProp, onModeChange, registerGridHeight]);
205
+ const element = useRender({
206
+ defaultTagName: 'div',
207
+ props: {
208
+ style: withStyle({
209
+ // (For its parts.)
210
+ '--uikit-color-picker-color': formatColor(color),
211
+ '--uikit-color-picker-color-opaque': formatColor({
212
+ ...color,
213
+ a: 1,
214
+ }),
215
+ }, style),
216
+ ...props,
217
+ className: cn('uikit-color-picker-root', className),
218
+ 'data-color-picker-part': 'root',
219
+ },
220
+ ref,
221
+ render,
222
+ });
223
+ return (_jsx(PickerContext.Provider, { value: state, children: _jsx(PanelContext.Provider, { value: modes, children: element }) }));
196
224
  });
225
+ /**
226
+ * Its panel: its modes' control (`Modes`, unless elsewhere, e.g. a sheet's
227
+ * header) and views (a `View` each, paired with its `Mode` by their
228
+ * `value`s), the opacity, the color and the saved colors, as composed (in
229
+ * its padding, its parts spaced).
230
+ */
231
+ const Panel = forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, ...props, className: cn('uikit-color-picker-panel', className), "data-color-picker-part": "panel" })));
197
232
  /**
198
233
  * Its modes' control: a segmented control (its `Mode`s, its highlight),
199
- * choosing the `View` shown; 24px above it.
234
+ * choosing the `View` shown; 24px above it (in its panel, or at the end of
235
+ * a header).
200
236
  */
201
237
  const Modes = forwardRef(({ children, ...props }, ref) => {
202
238
  const { mode, setMode } = useContext(PanelContext);
203
- return (_jsxs(Segmented.Root, { ref: ref, "aria-label": "Mode", ...props, value: mode, onValueChange: (next, details) => setMode(String(next), details), children: [children, _jsx(Segmented.Highlight, {})] }));
239
+ return (_jsxs(Segmented.Root, { ref: ref, "aria-label": "Mode",
240
+ // (Its modes, however many, scrolled when they don't fit.)
241
+ overflow: "scroll", ...props, className: cn('uikit-color-picker-modes', props.className), value: mode, onValueChange: (next, details) => setMode(String(next), details), children: [children, _jsx(Segmented.Highlight, {})] }));
204
242
  });
205
243
  /** A mode, in its `Modes`: its label, choosing its `View` (by `value`). */
206
244
  const Mode = forwardRef(({ value, ...props }, ref) => {
@@ -208,18 +246,6 @@ const Mode = forwardRef(({ value, ...props }, ref) => {
208
246
  useLayoutEffect(() => registerMode(value), [registerMode, value]);
209
247
  return (_jsx(Segmented.Item, { ref: ref, value: value, ...props }));
210
248
  });
211
- /**
212
- * A mode's view (by `value`, its `Mode`'s): shown while it's chosen; all
213
- * as high as the grid (so a popover doesn't move as they're switched).
214
- */
215
- const View = forwardRef(({ className, value, ...props }, ref) => {
216
- const { mode, registerMode } = useContext(PanelContext);
217
- // (A mode, too: without `Modes`, its only view shown.)
218
- useLayoutEffect(() => registerMode(value), [registerMode, value]);
219
- if (mode !== value)
220
- return null;
221
- return (_jsx("div", { ref: ref, "data-color-picker-view": value, ...props, className: cn('uikit-color-picker-view', className), "data-color-picker-part": "view" }));
222
- });
223
249
  /** Swatches in rows (a gray row, then hues by lightness), its corners 18px. */
224
250
  const Grid = forwardRef(({ className, ...props }, ref) => {
225
251
  const { color, setColor } = useContext(PickerContext);
@@ -270,33 +296,90 @@ const Spectrum = forwardRef(({ className, ...props }, ref) => {
270
296
  top: `${String((1 - l) * 100)}%`,
271
297
  } }) }));
272
298
  });
299
+ /**
300
+ * A mode's view (by `value`, its `Mode`'s): shown while it's chosen. With a
301
+ * view of the grid's height (a `Grid` or `Spectrum` in it) among them, all
302
+ * as high (so a popover doesn't move as they're switched); without, each as
303
+ * high as its content (e.g. sliders alone).
304
+ */
305
+ const View = forwardRef(({ children, className, value, ...props }, ref) => {
306
+ const { isGridHeight, mode, registerGridHeight, registerMode } = useContext(PanelContext);
307
+ // (A mode, too: without `Modes`, its only view shown.)
308
+ useLayoutEffect(() => registerMode(value), [registerMode, value]);
309
+ // (Rendered or not: its own height known by its children's types.)
310
+ const isOwnGridHeight = Children.toArray(children).some((child) => isValidElement(child) &&
311
+ (child.type === Grid || child.type === Spectrum));
312
+ useLayoutEffect(() => (isOwnGridHeight ? registerGridHeight() : undefined), [isOwnGridHeight, registerGridHeight]);
313
+ if (mode !== value)
314
+ return null;
315
+ return (_jsx("div", { ref: ref, "data-color-picker-view": value, ...props, className: cn('uikit-color-picker-view', className), "data-color-picker-part": "view", "data-grid-height": isGridHeight ? '' : undefined, children: children }));
316
+ });
273
317
  /**
274
318
  * A gradient's stops, across a channel's track (from where its knob's
275
319
  * center is at its least to where it is at its most), evenly.
276
320
  */
277
321
  const trackStops = (colors) => colors
278
- .map((stop, index) => `${stop} calc(20px + (100% - 40px) * ${String(index / Math.max(colors.length - 1, 1))})`)
322
+ .map((stop, index) => `${stop} calc(var(--uikit-color-picker-channel-size) / 2 + (100% - var(--uikit-color-picker-channel-size)) * ${String(index / Math.max(colors.length - 1, 1))})`)
279
323
  .join(', ');
280
324
  /**
281
325
  * A channel's row (the sliders', the opacity's): its title (all caps,
282
- * secondary), a slider (40px high, mixing from the color: its gradient
283
- * the color with the channel along its range; its knob 36px, in the color,
284
- * ringed white, 3px) and its value (a 75px by 40px field on the system
285
- * fill, 8px corners, Body emphasized: typed, committed on Enter or as it's
286
- * left).
326
+ * secondary), a slider (32px high, mixing from the color: its gradient
327
+ * the color with the channel along its range; its knob as high, in the
328
+ * color, ringed white, 3px) and its value (a 75px by 32px field on the system
329
+ * fill, 8px corners, Body emphasized: typed, applied as it's typed, within
330
+ * its range).
331
+ */
332
+ /**
333
+ * A typed field's handlers (a channel's value, the code): focused, all of
334
+ * it selected (to type over); left (or Enter), `onLeave` (its value again,
335
+ * e.g. emptied) and its selection collapsed (kept, the next tap would be on
336
+ * selected text). The tap focusing it is on its text, selected: Chrome opens
337
+ * its context menu for that; not for this tap (a later press, held, opens
338
+ * it).
287
339
  */
340
+ const useFieldSelection = (onLeave) => {
341
+ // Focused by a tap (until its click).
342
+ const focusingRef = useRef(false);
343
+ return {
344
+ onBlur: (event) => {
345
+ onLeave();
346
+ focusingRef.current = false;
347
+ const { length } = event.currentTarget.value;
348
+ event.currentTarget.setSelectionRange(length, length);
349
+ },
350
+ onClick: () => {
351
+ focusingRef.current = false;
352
+ },
353
+ onContextMenu: (event) => {
354
+ if (focusingRef.current)
355
+ event.preventDefault();
356
+ },
357
+ onFocus: (event) => {
358
+ focusingRef.current = true;
359
+ event.currentTarget.select();
360
+ },
361
+ onKeyDown: (event) => {
362
+ if (event.key === 'Enter')
363
+ onLeave();
364
+ },
365
+ };
366
+ };
288
367
  const ChannelRow = ({ fieldLabel, isCheckered = false, label, max, onValueChange, stops, thumbColor, unit, value, }) => {
289
368
  const [draft, setDraft] = useState(undefined);
369
+ const selection = useFieldSelection(() => setDraft(undefined));
290
370
  // Held, its touch doesn't scroll (see `useTouchHold`).
291
371
  const holdHandlers = useTouchHold('x');
292
- const commit = (event) => {
293
- if (draft === undefined)
372
+ // Typed: its digits (a whole number), within its range, applied at once;
373
+ // shown as applied (e.g. 300 as 255), or empty while it's typed over.
374
+ const type = (text, event) => {
375
+ const digits = text.replaceAll(/\D/gu, '');
376
+ if (digits === '') {
377
+ setDraft('');
294
378
  return;
295
- const next = Number.parseFloat(draft);
296
- if (Number.isFinite(next)) {
297
- onValueChange(clamp(Math.round(next), 0, max), event);
298
379
  }
299
- setDraft(undefined);
380
+ const next = clamp(Number.parseInt(digits, 10), 0, max);
381
+ setDraft(String(next));
382
+ onValueChange(next, event);
300
383
  };
301
384
  return (_jsxs(Viewport.KeyboardAccessory, { className: "uikit-color-picker-channel", "data-color-picker-part": "channel", gap: 20, children: [_jsx("div", { "aria-hidden": "true", className: "uikit-color-picker-channel-title", "data-color-picker-part": "channel-title", children: label }), _jsxs("div", { className: "uikit-color-picker-channel-row", "data-color-picker-part": "channel-row", children: [_jsx(BaseSlider.Root, { "aria-label": label, max: max, min: 0, style: { display: 'contents' }, thumbAlignment: "center", value: value, onValueChange: (next, { event }) => onValueChange(next, event), children: _jsx(BaseSlider.Control, { className: "uikit-color-picker-channel-control", "data-base-ui-swipe-ignore": "", "data-checkered": isCheckered ? '' : undefined, "data-color-picker-part": "channel-control",
302
385
  // (Its knob's place, for the hole in its gradient: the slider's
@@ -305,12 +388,10 @@ const ChannelRow = ({ fieldLabel, isCheckered = false, label, max, onValueChange
305
388
  '--uikit-color-picker-channel-position': value / max,
306
389
  '--uikit-color-picker-channel-stops': trackStops(stops),
307
390
  '--uikit-color-picker-channel-thumb': thumbColor,
308
- }, ...holdHandlers, children: _jsx(BaseSlider.Track, { children: _jsx(BaseSlider.Thumb, { className: "uikit-color-picker-channel-thumb", "data-color-picker-part": "channel-thumb" }) }) }) }), _jsxs("label", { className: "uikit-color-picker-channel-field", "data-color-picker-part": "channel-field", children: [_jsx("input", { "aria-label": fieldLabel ?? `${label} value`, inputMode: "numeric", value: draft ?? String(value), onBlur: (event) => commit(event), onChange: (event) => setDraft(event.currentTarget.value),
309
- // Focused, all of it (to type over).
310
- onFocus: (event) => event.currentTarget.select(), onKeyDown: (event) => {
311
- if (event.key === 'Enter')
312
- commit(event);
313
- } }), unit ? _jsx("span", { "aria-hidden": "true", children: unit }) : null] })] })] }));
391
+ }, ...holdHandlers, children: _jsx(BaseSlider.Track, { children: _jsx(BaseSlider.Thumb, { className: "uikit-color-picker-channel-thumb", "data-color-picker-part": "channel-thumb" }) }) }) }), _jsxs("label", { className: "uikit-color-picker-channel-field", "data-color-picker-part": "channel-field", children: [_jsx("input", { "aria-label": fieldLabel ?? `${label} value`, inputMode: "numeric", value: draft ?? String(value),
392
+ // (Left, or Enter: its value again, e.g. emptied; see
393
+ // `useFieldSelection`.)
394
+ onChange: (event) => type(event.currentTarget.value, event), ...selection }), unit ? _jsx("span", { "aria-hidden": "true", children: unit }) : null] })] })] }));
314
395
  };
315
396
  /** Hue (0–360°), saturation and lightness (0–100%). */
316
397
  const hsl = {
@@ -356,42 +437,80 @@ const rgb = {
356
437
  from: ({ b, g, r }) => [r, g, b].map((channel) => Math.round(channel)),
357
438
  to: ([r = 0, g = 0, b = 0]) => ({ b, g, r }),
358
439
  };
440
+ const rgbKeys = ['r', 'g', 'b'];
441
+ /**
442
+ * Red, green and blue in percent (0–100%): coarser than bytes, so a channel
443
+ * set leaves the others as they are (not as rounded, see `set`).
444
+ */
445
+ const rgbPercentage = {
446
+ channels: [
447
+ { label: 'Red', max: 100, unit: '%' },
448
+ { label: 'Green', max: 100, unit: '%' },
449
+ { label: 'Blue', max: 100, unit: '%' },
450
+ ],
451
+ from: ({ b, g, r }) => [r, g, b].map((channel) => Math.round((channel / 255) * 100)),
452
+ set: ({ b, g, r }, index, value) => ({
453
+ b,
454
+ g,
455
+ r,
456
+ [rgbKeys[index] ?? 'r']: (value * 255) / 100,
457
+ }),
458
+ to: ([r = 0, g = 0, b = 0]) => ({
459
+ b: (b * 255) / 100,
460
+ g: (g * 255) / 100,
461
+ r: (r * 255) / 100,
462
+ }),
463
+ };
359
464
  const models = { cmyk, hsl, rgb };
465
+ /** A model's color, one channel set (see `Model`'s `set`). */
466
+ const withChannel = (model, color, values, index, value) => model.set
467
+ ? model.set(color, index, value)
468
+ : model.to(values.with(index, value));
360
469
  /**
361
470
  * A channel's track's colors: the color with the channel along its range,
362
471
  * enough of them to be exact (linear between them): a hue around (every
363
472
  * 60°), a lightness through the pure hue (halfway), the others its ends.
364
473
  */
365
- const trackColors = (model, values, index) => {
474
+ const trackColors = (model, color, values, index) => {
366
475
  const { max } = model.channels[index] ?? { max: 1 };
367
476
  const steps = model === hsl ? ([6, 1, 2][index] ?? 1) : 1;
368
- return Array.from({ length: steps + 1 }, (_, step) => {
369
- const next = values.with(index, (max * step) / steps);
370
- return formatColor({ ...model.to(next), a: 1 });
371
- });
477
+ return Array.from({ length: steps + 1 }, (_, step) => formatColor({
478
+ ...withChannel(model, color, values, index, (max * step) / steps),
479
+ a: 1,
480
+ }));
372
481
  };
373
482
  /**
374
- * Sliders: a color model's channels (`model`: red, green and blue; hue,
375
- * saturation and lightness; cyan, magenta, yellow and black), each mixing
376
- * from the color, its value typed too.
483
+ * Sliders: a color model's channels (`model`: red, green and blue, in bytes
484
+ * or percent, its `range`; hue, saturation and lightness; cyan, magenta,
485
+ * yellow and black), each mixing from the color, its value typed too; then
486
+ * its children (e.g. the `Code`), spaced as the channels.
377
487
  */
378
- const Sliders = forwardRef(({ className, model: modelName = 'rgb', ...props }, ref) => {
488
+ const Sliders = forwardRef(({ children, className, model: modelName = 'rgb', range = 'byte', ...props }, ref) => {
379
489
  const { color, setColor } = useContext(PickerContext);
380
- const model = models[modelName];
490
+ const model = modelName === 'rgb' && range === 'percentage'
491
+ ? rgbPercentage
492
+ : models[modelName];
381
493
  const opaque = formatColor({ ...color, a: 1 });
382
- // Its values as last set, while they're the color's: so a hue isn't
383
- // lost to a gray (no saturation), nor inks to black (all of it).
494
+ // Its values as last set, while they're the color's (and its model's):
495
+ // so a hue isn't lost to a gray (no saturation), nor inks to black (all
496
+ // of it).
384
497
  const [last, setLast] = useState();
385
- const values = last?.color === opaque ? last.values : model.from(color);
386
- return (_jsx("div", { ref: ref, ...props, className: cn('uikit-color-picker-sliders', className), "data-color-picker-part": "sliders", "data-model": modelName, children: model.channels.map(({ label, max, unit }, index) => (_jsx(ChannelRow, { label: label, max: max, stops: trackColors(model, values, index), thumbColor: opaque, unit: unit, value: values[index] ?? 0, onValueChange: (next, event) => {
387
- const nextValues = values.with(index, next);
388
- const nextColor = { ...model.to(nextValues), a: color.a };
389
- setLast({
390
- color: formatColor({ ...nextColor, a: 1 }),
391
- values: nextValues,
392
- });
393
- setColor(nextColor, { event, reason: 'sliders' });
394
- } }, label))) }));
498
+ const values = last?.color === opaque && last.model === model
499
+ ? last.values
500
+ : model.from(color);
501
+ return (_jsxs("div", { ref: ref, ...props, className: cn('uikit-color-picker-sliders', className), "data-color-picker-part": "sliders", "data-model": modelName, "data-range": modelName === 'rgb' ? range : undefined, children: [model.channels.map(({ label, max, unit }, index) => (_jsx(ChannelRow, { label: label, max: max, stops: trackColors(model, color, values, index), thumbColor: opaque, unit: unit, value: values[index] ?? 0, onValueChange: (next, event) => {
502
+ const nextValues = values.with(index, next);
503
+ const nextColor = {
504
+ ...withChannel(model, color, values, index, next),
505
+ a: color.a,
506
+ };
507
+ setLast({
508
+ color: formatColor({ ...nextColor, a: 1 }),
509
+ model,
510
+ values: nextValues,
511
+ });
512
+ setColor(nextColor, { event, reason: 'sliders' });
513
+ } }, label))), children] }));
395
514
  });
396
515
  /**
397
516
  * The opacity: the color fading in over a checkerboard, in percent; 22px
@@ -415,7 +534,7 @@ const SavedSwatch = ({ hex, onDelete }) => {
415
534
  const { color, setColor } = useContext(PickerContext);
416
535
  const swatch = parseColor(hex);
417
536
  // Its menu (a secondary click: right click, or a long press): delete it.
418
- return (_jsxs(Menu.Root, { children: [_jsx(Menu.Trigger, { openOn: "secondaryClick", render: _jsx("button", { "aria-label": hex, "aria-pressed": sameColor(swatch, color) && swatch.a === color.a, style: { backgroundColor: hex }, type: "button", onClick: (event) => setColor(swatch, { event, reason: 'saved' }) }) }), _jsx(Menu.Portal, { children: _jsx(Menu.Positioner, { children: _jsx(Menu.Popup, { children: _jsx(Menu.Item, { destructive: true, onClick: (event) => onDelete(event), children: _jsx(Menu.Label, { children: "Delete" }) }) }) }) })] }));
537
+ return (_jsxs(Menu.Root, { children: [_jsx(Menu.Trigger, { openOn: "secondaryClick", render: _jsx("button", { "aria-label": hex, "aria-pressed": sameColor(swatch, color) && swatch.a === color.a, style: { '--uikit-color-picker-color': hex }, type: "button", onClick: (event) => setColor(swatch, { event, reason: 'saved' }) }) }), _jsx(Menu.Portal, { children: _jsx(Menu.Positioner, { children: _jsx(Menu.Popup, { children: _jsx(Menu.Item, { destructive: true, onClick: (event) => onDelete(event), children: _jsx(Menu.Label, { children: "Delete" }) }) }) }) })] }));
419
538
  };
420
539
  /**
421
540
  * The color (82px, 18px corners; translucent, over black and white) beside
@@ -518,8 +637,242 @@ const Eyedropper = ({ render, ...props }) => {
518
637
  onClick: pick,
519
638
  })) : (_jsx(Button.Root, { "aria-label": "Eyedropper", ...props, onClick: pick }));
520
639
  };
640
+ /** Whether the browser has a color input (its picker the system's). */
641
+ const hasColorInput = () => {
642
+ if (typeof document === 'undefined')
643
+ return false;
644
+ const input = document.createElement('input');
645
+ input.type = 'color';
646
+ return input.type === 'color';
647
+ };
648
+ /**
649
+ * Whether its color input has an alpha (its `alpha` attribute: e.g.
650
+ * Safari's; without, a value with one is invalid, black).
651
+ */
652
+ const hasColorInputAlpha = () => typeof HTMLInputElement !== 'undefined' &&
653
+ 'alpha' in HTMLInputElement.prototype;
654
+ /**
655
+ * Its system colors (a leading button, after the eyedropper): a `Button`
656
+ * (or what it renders), opening the system's color picker: a color input's
657
+ * (none without one), over the button, transparent: pressed itself (on iOS,
658
+ * nothing else opens it: neither `showPicker` nor a click, see WebKit's bug
659
+ * 261703), the button showing the press; the button clicking it from the
660
+ * keyboard. With the opacity rendered, its alpha too, where the input has
661
+ * one (its `alpha`: e.g. Safari); else its colors opaque, the opacity kept.
662
+ */
663
+ const SystemColors = ({ render, ...props }) => {
664
+ const { color, hasOpacity, setColor } = useContext(PickerContext);
665
+ // (Its input, as rendered: for its button's press.)
666
+ const [input, setInput] = useState(null);
667
+ if (!hasColorInput())
668
+ return null;
669
+ // (With the opacity, the input's alpha too, where it has one.)
670
+ const hasAlpha = hasOpacity && hasColorInputAlpha();
671
+ const open = () => input?.click();
672
+ return (_jsxs("span", { className: "uikit-color-picker-system-colors", "data-color-picker-part": "system-colors", children: [render ? (cloneElement(render, {
673
+ 'aria-label': 'System colors',
674
+ ...props,
675
+ onClick: open,
676
+ })) : (_jsx(Button.Root, { "aria-label": "System colors", ...props, onClick: open })), _jsx("input", { ref: setInput, ...(hasAlpha ? { alpha: true } : {}), "aria-hidden": "true", className: "uikit-color-picker-system-colors-input", disabled: props.disabled, tabIndex: -1, type: "color",
677
+ // (The color, as it is: its picker opened from it.)
678
+ value: formatColor(hasAlpha ? color : { ...color, a: 1 }).toLowerCase(),
679
+ // (As it's picked, live; without its alpha, the opacity kept.)
680
+ onChange: (event) => {
681
+ // (Any CSS color, with an alpha: see color.ts.)
682
+ const picked = parseCssColor(event.currentTarget.value);
683
+ if (!picked)
684
+ return;
685
+ setColor(hasAlpha ? picked : { ...picked, a: color.a }, {
686
+ event,
687
+ reason: 'system-colors',
688
+ });
689
+ } })] }));
690
+ };
691
+ /**
692
+ * Its code (a row; its place the app's: e.g. under the sliders), as high as a
693
+ * channel's, its field where a channel's value is: “Hex” (a channel's title,
694
+ * beside them, centered), then its children (e.g. a `CodeCopy`), the color's
695
+ * hex code typed (`#` before it, not typed: its digits, applied as they make
696
+ * a code, 3, 4, 6 or 8 of them; with an alpha, 4 or 8), at its end. Kept above the keyboard as it's typed into (as a
697
+ * channel's row).
698
+ */
699
+ const Code = forwardRef(({ children, className, ...props }, ref) => {
700
+ const { color, setColor } = useContext(PickerContext);
701
+ const [draft, setDraft] = useState(undefined);
702
+ const selection = useFieldSelection(() => setDraft(undefined));
703
+ const type = (text, event) => {
704
+ const digits = text
705
+ .replaceAll(/[^\da-f]/giu, '')
706
+ .slice(0, 8)
707
+ .toUpperCase();
708
+ setDraft(digits);
709
+ if (![3, 4, 6, 8].includes(digits.length))
710
+ return;
711
+ const typed = parseColor(`#${digits}`);
712
+ // (Without an alpha typed, the color's kept.)
713
+ setColor(digits.length % 4 === 0 ? typed : { ...typed, a: color.a }, {
714
+ event,
715
+ reason: 'code',
716
+ });
717
+ };
718
+ return (_jsx(Viewport.KeyboardAccessory, { ref: ref, gap: 20, ...props, className: cn('uikit-color-picker-code', className), "data-color-picker-part": "code", children: _jsxs("div", { className: "uikit-color-picker-channel-row uikit-color-picker-code-row", "data-color-picker-part": "code-row", children: [_jsx("div", { "aria-hidden": "true", className: "uikit-color-picker-channel-title", "data-color-picker-part": "code-title", children: "Hex" }), children, _jsxs("label", { className: "uikit-color-picker-channel-field uikit-color-picker-code-field", "data-color-picker-part": "code-field", children: [_jsx("span", { "aria-hidden": "true", children: "#" }), _jsx("input", { spellcheck: false, "aria-label": "Hex color", autoCapitalize: "characters", autoComplete: "off", autoCorrect: "off", value: draft ?? formatColor(color).slice(1), onChange: (event) => type(event.currentTarget.value, event), ...selection })] })] }) }));
719
+ });
521
720
  /** A color well: its color, opening the picker. */
522
721
  const Well = forwardRef(({ className, color, size = 'small', style, ...props }, ref) => (_jsx("button", { ref: ref, "aria-label": "Color", "data-color": color === undefined ? undefined : '', "data-size": size, style: withStyle({ '--uikit-color-picker-well-color': color }, style), type: "button", ...props, className: cn('uikit-color-picker-well', className), "data-color-picker-part": "well" })));
722
+ // How long a copy shows as done (its checkmark).
723
+ const copiedFor = 1500;
724
+ /**
725
+ * Its code's copy button: a `Button` (or what it renders, its content the
726
+ * app's: e.g. a symbol), opening a menu of the color's codes (see color.ts):
727
+ * hex's, then a submenu each of the others' groups, each code its format and
728
+ * its values (`Menu.Label`, `Menu.Subtitle`). One picked, copied to the
729
+ * clipboard (`onCodeCopy`); for a moment, a checkmark instead of its content
730
+ * (`data-copied`). Its place the app's (in a `Code`, or not).
731
+ */
732
+ const CodeCopy = ({ children, onCodeCopy, render, ...props }) => {
733
+ const { color } = useContext(PickerContext);
734
+ const [isCopied, setIsCopied] = useState(false);
735
+ useEffect(() => {
736
+ if (!isCopied)
737
+ return undefined;
738
+ const timeout = setTimeout(() => setIsCopied(false), copiedFor);
739
+ return () => clearTimeout(timeout);
740
+ }, [isCopied]);
741
+ const copy = (code, event) => {
742
+ navigator.clipboard
743
+ .writeText(code)
744
+ .then(() => {
745
+ setIsCopied(true);
746
+ onCodeCopy?.(code, event);
747
+ })
748
+ .catch(() => undefined);
749
+ };
750
+ // (Hex's: its color in a well at its end, inert.)
751
+ const item = ({ code, label, subtitle, well }) => (_jsxs(Menu.Item, { onClick: (event) => copy(code, event), children: [_jsx(Menu.Label, { children: label }), _jsx(Menu.Subtitle, { children: subtitle }), well === undefined ? null : (_jsx(Well, { inert: true, "aria-hidden": "true", className: "uikit-color-picker-code-copy-well", color: well, tabIndex: -1 }))] }, code));
752
+ const content = isCopied ? (_jsx(Button.Icon, { children: _jsx(Checkmark, {}) })) : (children);
753
+ const trigger = render ? (cloneElement(render, {
754
+ 'aria-label': 'Copy color code',
755
+ ...props,
756
+ 'data-copied': isCopied ? '' : undefined,
757
+ }, content)) : (_jsx(Button.Root, { "aria-label": "Copy color code", ...props, "data-copied": isCopied ? '' : undefined, children: content }));
758
+ return (_jsxs(Menu.Root, { children: [_jsx(Menu.Trigger, { render: trigger }), _jsx(Menu.Portal, { children: _jsx(Menu.Positioner, { children: _jsx(Menu.Popup, { children: codeGroups(color, formatColor({ ...color, a: 1 })).map(([title, codes], index) => index === 0 ? (_jsx(Fragment, { children: codes.map((entry) => item(entry)) }, title)) : (_jsxs(Menu.SubmenuRoot, { children: [_jsx(Menu.SubmenuTrigger, { children: _jsx(Menu.Label, { children: title }) }), _jsx(Menu.Portal, { children: _jsx(Menu.Positioner, { children: _jsx(Menu.Popup, { children: codes.map((entry) => item(entry)) }) }) })] }, title))) }) }) })] }));
759
+ };
760
+ /**
761
+ * Its named colors' rows (see `Named`): one registered (its label's first
762
+ * letter, for the index), while mounted.
763
+ */
764
+ const NamedContext = createContext(() => unregister);
765
+ /** The scroll container `element` is in (its block axis), or the page. */
766
+ const scrollerOf = (element) => {
767
+ for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
768
+ const { overflowY } = getComputedStyle(parent);
769
+ if (overflowY === 'auto' || overflowY === 'scroll')
770
+ return parent;
771
+ }
772
+ return document.scrollingElement ?? document.documentElement;
773
+ };
774
+ /** A row at the top of its scroll container (below its scroll padding). */
775
+ const jumpTo = (element) => {
776
+ const scroller = scrollerOf(element);
777
+ const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingBlockStart) || 0;
778
+ const top = scroller === document.scrollingElement
779
+ ? 0
780
+ : scroller.getBoundingClientRect().top;
781
+ scroller.scrollTo({
782
+ top: scroller.scrollTop + element.getBoundingClientRect().top - top - padding,
783
+ });
784
+ };
785
+ /**
786
+ * A row in view (between its scroll container's scroll paddings: e.g. a
787
+ * sheet's header), at once: already, it stays; else, centered there.
788
+ */
789
+ const revealCentered = (element) => {
790
+ const scroller = scrollerOf(element);
791
+ const style = getComputedStyle(scroller);
792
+ const paddingStart = Number.parseFloat(style.scrollPaddingBlockStart) || 0;
793
+ const paddingEnd = Number.parseFloat(style.scrollPaddingBlockEnd) || 0;
794
+ const scrollerTop = scroller === document.scrollingElement
795
+ ? 0
796
+ : scroller.getBoundingClientRect().top;
797
+ const { bottom, height, top } = element.getBoundingClientRect();
798
+ const viewStart = scrollerTop + paddingStart;
799
+ const viewHeight = scroller.clientHeight - paddingStart - paddingEnd;
800
+ if (top >= viewStart && bottom <= viewStart + viewHeight)
801
+ return;
802
+ scroller.scrollTo({
803
+ behavior: 'instant',
804
+ top: scroller.scrollTop + top - viewStart - (viewHeight - height) / 2,
805
+ });
806
+ };
807
+ /**
808
+ * Its named colors (a mode's content, e.g. “Named”): one list of their rows
809
+ * (`NamedColor`s: e.g. the app's, `CssNamedColors`'), as high as they are
810
+ * (scrolled by its container: e.g. a sheet's content, a popover's body). At
811
+ * its end (in its panel's inset), an index of their labels' first letters,
812
+ * kept centered in view as it's scrolled; one picked, the first row with it
813
+ * at the top (below the container's scroll padding: e.g. a sheet's header).
814
+ * Shown, the color's row in view at once (see `revealCentered`).
815
+ */
816
+ const Named = forwardRef(({ children, className, ...props }, forwardedRef) => {
817
+ const ref = useForwardedRef(forwardedRef);
818
+ // Shown (e.g. its mode chosen): the color's row in view, at once.
819
+ useLayoutEffect(() => {
820
+ const picked = ref.current?.querySelector('[data-color-picker-part="named-color"][data-picked]');
821
+ if (picked)
822
+ revealCentered(picked);
823
+ }, [ref]);
824
+ const [entries, setEntries] = useState([]);
825
+ const register = useCallback((entry) => {
826
+ // (In the document's order; rows apart, neither in the other: only
827
+ // following, or not.)
828
+ setEntries((current) => [...current, entry].toSorted((a, b) => a.element.compareDocumentPosition(b.element) ===
829
+ Node.DOCUMENT_POSITION_FOLLOWING
830
+ ? -1
831
+ : 1));
832
+ return () => setEntries((current) => current.filter((other) => other !== entry));
833
+ }, []);
834
+ // Each letter's first row.
835
+ const letters = useMemo(() => {
836
+ const first = new Map();
837
+ for (const { element, label } of entries) {
838
+ if (!first.has(label))
839
+ first.set(label, element);
840
+ }
841
+ return [...first];
842
+ }, [entries]);
843
+ return (_jsx(NamedContext.Provider, { value: register, children: _jsxs("div", { ref: ref, ...props, className: cn('uikit-color-picker-named', className), "data-color-picker-part": "named", children: [_jsx(List.Root, { listStyle: "insetGrouped", children: _jsx(List.Section, { children: _jsx(List.Group, { children: children }) }) }), letters.length > 0 ? (_jsx("div", { className: "uikit-color-picker-named-index", "data-color-picker-part": "named-index", children: _jsx(List.Index, { "aria-label": "Index", children: letters.map(([letter, element]) => (_jsx(List.IndexItem, { onClick: () => jumpTo(element), children: letter }, letter))) }) })) : null] }) }));
844
+ });
845
+ /**
846
+ * A named color's row (in a `Named`): its color in a well (inert), its label
847
+ * (or its color), a checkmark while it's the color (its opacity aside); its
848
+ * label's first letter in the index. Pressed, the color (its opacity kept,
849
+ * as a grid swatch's).
850
+ */
851
+ const NamedColor = forwardRef(({ children, color: cssColor, ...props }, forwardedRef) => {
852
+ const { color, setColor } = useContext(PickerContext);
853
+ const register = useContext(NamedContext);
854
+ const ref = useForwardedRef(forwardedRef);
855
+ const named = useMemo(() => parseCssColor(cssColor), [cssColor]);
856
+ const isPicked = named !== undefined && sameColor(named, color);
857
+ const letter = (typeof children === 'string' ? children : cssColor)
858
+ .charAt(0)
859
+ .toUpperCase();
860
+ useLayoutEffect(() => {
861
+ const { current: element } = ref;
862
+ return element ? register({ element, label: letter }) : undefined;
863
+ }, [letter, ref, register]);
864
+ return (_jsxs(List.Item, { ref: ref, ...props, "data-color-picker-part": "named-color", "data-picked": isPicked ? '' : undefined, children: [_jsx(List.Leading, { children: _jsx(Well, { inert: true, "aria-hidden": "true", color: cssColor, tabIndex: -1 }) }), _jsx(List.Content, { children: _jsx(List.Title, { "aria-pressed": isPicked, render: _jsx("button", { type: "button" }), onClick: (event) => {
865
+ if (!named)
866
+ return;
867
+ setColor({ ...named, a: color.a }, { event, reason: 'named' });
868
+ }, children: children ?? cssColor }) }), _jsx(List.Trailing, { children: isPicked ? _jsx(List.Checkmark, {}) : null })] }));
869
+ });
870
+ /**
871
+ * The CSS named colors (148, synonyms too: e.g. gray and grey; not
872
+ * `transparent`; see named-colors.ts), as a `Named`'s rows, labeled by their
873
+ * names.
874
+ */
875
+ const CssNamedColors = () => (_jsx(_Fragment, { children: cssNamedColors.map((name) => (_jsx(NamedColor, { color: name }, name))) }));
523
876
  export const ColorPicker = {
524
877
  Root,
525
878
  Header,
@@ -533,6 +886,12 @@ export const ColorPicker = {
533
886
  Opacity,
534
887
  Swatches,
535
888
  Eyedropper,
889
+ SystemColors,
890
+ Code,
891
+ CodeCopy,
892
+ Named,
893
+ NamedColor,
894
+ CssNamedColors,
536
895
  Well,
537
896
  };
538
897
  //# sourceMappingURL=main.js.map