@nextlyhq/ui 0.0.2-alpha.77 → 0.0.2-alpha.79

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.
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { Slot } from "@radix-ui/react-slot";
3
3
  import { cva } from "class-variance-authority";
4
4
  import * as React from "react";
5
- import { Fragment, cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useRef } from "react";
5
+ import { Fragment, cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
6
6
  import { clsx } from "clsx";
7
7
  import { twMerge } from "tailwind-merge";
8
8
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
@@ -58,7 +58,7 @@ function cn(...inputs) {
58
58
  * - destructive: Destructive action button (red background)
59
59
  * - outline: Outlined button (transparent background, border)
60
60
  * - ghost: Minimal button (transparent, no border)
61
- * - link: Link-style button (underlined text)
61
+ * - link: Link-style button (text colour, underlined at rest)
62
62
  *
63
63
  * Note: 'primary' is a semantic alias for 'default' variant for better code readability
64
64
  * @experimental
@@ -72,7 +72,7 @@ const buttonVariants = cva(`inline-flex items-center justify-center whitespace-n
72
72
  outline: "border border-border text-foreground hover-unified bg-background",
73
73
  secondary: "bg-background border border-border text-foreground hover:bg-primary/5",
74
74
  ghost: "text-foreground border border-transparent hover-unified",
75
- link: "text-primary border border-transparent underline-offset-4 hover:underline"
75
+ link: "text-foreground border border-transparent underline underline-offset-4 hover:decoration-2"
76
76
  },
77
77
  size: {
78
78
  default: "h-[var(--nx-control-height)] px-6 py-2",
@@ -1828,7 +1828,9 @@ AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
1828
1828
  * **Accessibility**:
1829
1829
  * - Full keyboard navigation (Arrow keys, Enter, Escape, Tab)
1830
1830
  * - ARIA roles and attributes (menu, menuitem, menuitemcheckbox, menuitemradio)
1831
- * - Focus management (focus trap, auto-focus first item)
1831
+ * - Focus management (auto-focus first item, focus back to the trigger)
1832
+ * - Not modal by default: the page around an open menu stays in reach and
1833
+ * in the accessibility tree; pass `modal` for a menu that must hold it
1832
1834
  * - Screen reader support (labels, descriptions, indicators)
1833
1835
  * - WCAG 2.2 Level AA compliant
1834
1836
  *
@@ -1904,8 +1906,24 @@ AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
1904
1906
  *
1905
1907
  * @see https://www.radix-ui.com/docs/primitives/components/dropdown-menu - Radix UI DropdownMenu
1906
1908
  */
1907
- /** @public */
1908
- const DropdownMenu = DropdownMenuPrimitive.Root;
1909
+ /**
1910
+ * The menu's root: Radix's, not modal unless a caller asks.
1911
+ *
1912
+ * A menu is a list of choices, not a dialog. A modal one marks everything
1913
+ * around it `aria-hidden` while those controls stay focusable, which hides
1914
+ * the page from a screen reader without taking it out of reach (axe:
1915
+ * `aria-hidden-focus`). Not modal, the menu still closes on Escape, on Tab
1916
+ * and on a press outside, and gives focus back to its trigger; the press
1917
+ * outside also reaches what it was on, and the page can scroll while the
1918
+ * menu is open. A menu that must hold the page still passes `modal`.
1919
+ *
1920
+ * @public
1921
+ */
1922
+ const DropdownMenu = ({ modal = false, ...props }) => /* @__PURE__ */ jsx(DropdownMenuPrimitive.Root, {
1923
+ modal,
1924
+ ...props
1925
+ });
1926
+ DropdownMenu.displayName = "DropdownMenu";
1909
1927
  /** @public */
1910
1928
  const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
1911
1929
  /** @experimental */
@@ -2333,6 +2351,53 @@ function SheetDragHandle({ onDismiss }) {
2333
2351
  children: /* @__PURE__ */ jsx("span", { className: "h-1 w-10 rounded-full bg-border" })
2334
2352
  });
2335
2353
  }
2354
+ /** What the keyboard can reach by Tab: enabled, not hidden, and in the tab order. */
2355
+ const TABBABLE = "a[href], area[href], button:not([disabled]), input:not([disabled]):not([type=\"hidden\"]), select:not([disabled]), textarea:not([disabled]), [tabindex], [contenteditable=\"true\"]";
2356
+ /**
2357
+ * Whether an element is drawn: neither it nor a container it sits in is `display: none` or
2358
+ * `visibility: hidden`. One that is not is no stop for the keyboard, and no edge of a sheet.
2359
+ */
2360
+ function isRendered(element) {
2361
+ for (let node = element; node !== null; node = node.parentElement) {
2362
+ const style = getComputedStyle(node);
2363
+ if (style.display === "none" || style.visibility === "hidden") return false;
2364
+ }
2365
+ return true;
2366
+ }
2367
+ function tabbablesIn(root) {
2368
+ return Array.from(root.querySelectorAll(TABBABLE)).filter((element) => element.tabIndex >= 0 && !element.hidden && !element.matches(":disabled") && !element.hasAttribute("data-radix-focus-guard") && element.closest("[aria-hidden=\"true\"], [inert]") === null && isRendered(element));
2369
+ }
2370
+ /**
2371
+ * Tab at a non-modal sheet's edge, moved out of it as for any other part of the page.
2372
+ *
2373
+ * Radix's dialog keeps its focus scope looping even when it is not modal, so Tab from the
2374
+ * sheet's last control would go round to its first, and Shift+Tab from its first to its last:
2375
+ * a keyboard reader could not get from the sheet back to the page beside it. At those two edges
2376
+ * this sends focus where the browser would: forward to the nearest control after the sheet in
2377
+ * the document, back to the nearest before it. Anywhere else, Tab is left to the browser.
2378
+ * Runs before the focus scope's own handler on the same element, which then finds focus already
2379
+ * outside and does nothing.
2380
+ */
2381
+ function leaveNonModalAtEdge(event) {
2382
+ if (event.defaultPrevented) return;
2383
+ if (event.key !== "Tab" || event.altKey || event.ctrlKey || event.metaKey) return;
2384
+ const sheet = event.currentTarget;
2385
+ const inside = tabbablesIn(sheet);
2386
+ if (document.activeElement === sheet && inside.length > 0) {
2387
+ event.preventDefault();
2388
+ (event.shiftKey ? inside[inside.length - 1] : inside[0])?.focus();
2389
+ return;
2390
+ }
2391
+ const edge = event.shiftKey ? inside[0] : inside[inside.length - 1];
2392
+ if (!(document.activeElement === sheet || edge !== void 0 && document.activeElement === edge)) return;
2393
+ const page = tabbablesIn(sheet.ownerDocument.body).filter((element) => !sheet.contains(element));
2394
+ const before = page.filter((element) => (sheet.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING) !== 0);
2395
+ const after = page.filter((element) => !before.includes(element));
2396
+ const next = event.shiftKey ? before[before.length - 1] ?? page[page.length - 1] : after[0] ?? page[0];
2397
+ if (next === void 0) return;
2398
+ event.preventDefault();
2399
+ next.focus();
2400
+ }
2336
2401
  /**
2337
2402
  * SheetContent
2338
2403
  *
@@ -2347,7 +2412,7 @@ function SheetDragHandle({ onDismiss }) {
2347
2412
  * @param side - Which edge to slide in from: "left", "right", "top", "bottom"
2348
2413
  * @public
2349
2414
  */
2350
- const SheetContent = React.forwardRef(({ side = "right", className, children, dragHandle = false, ...props }, ref) => {
2415
+ const SheetContent = React.forwardRef(({ side = "right", className, children, dragHandle = false, onKeyDown, ...props }, ref) => {
2351
2416
  const portalContainer = usePortalContainer();
2352
2417
  const modal = React.useContext(SheetModalContext);
2353
2418
  const close = React.useRef(null);
@@ -2359,6 +2424,10 @@ const SheetContent = React.forwardRef(({ side = "right", className, children, dr
2359
2424
  "data-slot": "sheet-content",
2360
2425
  className: cn(sheetVariants({ side }), className),
2361
2426
  ...props,
2427
+ onKeyDown: (event) => {
2428
+ onKeyDown?.(event);
2429
+ if (!modal) leaveNonModalAtEdge(event);
2430
+ },
2362
2431
  children: [draggable ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(SheetDragHandle, { onDismiss: () => close.current?.click() }), /* @__PURE__ */ jsx(DialogPrimitive.Close, {
2363
2432
  ref: close,
2364
2433
  hidden: true,
@@ -2479,21 +2548,32 @@ CommandDialogOverlay.displayName = "CommandDialogOverlay";
2479
2548
  * ```
2480
2549
  * @experimental
2481
2550
  */
2482
- const CommandDialog = ({ children, commandProps, contentProps, ...props }) => {
2551
+ const CommandDialog = ({ children, title = "Command palette", description, commandProps, contentProps, ...props }) => {
2483
2552
  const portalContainer = usePortalContainer();
2484
2553
  return /* @__PURE__ */ jsx(DialogPrimitive.Root, {
2485
2554
  ...props,
2486
2555
  children: /* @__PURE__ */ jsxs(DialogPrimitive.Portal, {
2487
2556
  container: portalContainer,
2488
- children: [/* @__PURE__ */ jsx(CommandDialogOverlay, {}), /* @__PURE__ */ jsx(DialogPrimitive.Content, {
2557
+ children: [/* @__PURE__ */ jsx(CommandDialogOverlay, {}), /* @__PURE__ */ jsxs(DialogPrimitive.Content, {
2558
+ ...description === void 0 ? { "aria-describedby": void 0 } : {},
2489
2559
  ...contentProps,
2490
2560
  "data-slot": "command-content",
2491
2561
  className: cn("fixed left-[50%] top-[13vh] z-[100] translate-x-[-50%]", "w-full max-w-lg", "max-h-[80vh]", "sm:max-w-lg", "max-w-full", "m-4 sm:m-0", "overflow-hidden rounded-lg border border-border bg-background shadow-xl", "duration-200", "data-[state=open]:animate-in data-[state=closed]:animate-out", "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", "data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", "data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2"),
2492
- children: /* @__PURE__ */ jsx(Command, {
2493
- ...commandProps,
2494
- className: cn("[&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-2 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:mb-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-3 [&_[cmdk-item]]:py-2 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4", commandProps?.className),
2495
- children
2496
- })
2562
+ children: [
2563
+ /* @__PURE__ */ jsx(DialogPrimitive.Title, {
2564
+ className: "sr-only",
2565
+ children: title
2566
+ }),
2567
+ description === void 0 ? null : /* @__PURE__ */ jsx(DialogPrimitive.Description, {
2568
+ className: "sr-only",
2569
+ children: description
2570
+ }),
2571
+ /* @__PURE__ */ jsx(Command, {
2572
+ ...commandProps,
2573
+ className: cn("[&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-2 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:mb-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-3 [&_[cmdk-item]]:py-2 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4", commandProps?.className),
2574
+ children
2575
+ })
2576
+ ]
2497
2577
  })]
2498
2578
  })
2499
2579
  });
@@ -2513,27 +2593,77 @@ const CommandInput = forwardRef(({ className, ...props }, ref) => /* @__PURE__ *
2513
2593
  })]
2514
2594
  }));
2515
2595
  CommandInput.displayName = "CommandInput";
2596
+ const EmptyNoticeContext = createContext(null);
2597
+ /** Says `notice` from the list's status line while it is mounted. */
2598
+ function SayEmpty({ say, notice }) {
2599
+ useEffect(() => {
2600
+ say(() => notice);
2601
+ return () => say(null);
2602
+ }, [say, notice]);
2603
+ return null;
2604
+ }
2516
2605
  /**
2517
2606
  * CommandList - Scrollable container for command results.
2518
2607
  * Max height 400px per design spec to prevent tall dialogs.
2519
2608
  * @experimental
2520
2609
  */
2521
- const CommandList = forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Command$1.List, {
2522
- ref,
2523
- className: cn("max-h-[400px] overflow-y-auto overflow-x-hidden", "p-2", className),
2524
- ...props
2525
- }));
2610
+ const CommandList = forwardRef(({ className, children, ...props }, ref) => {
2611
+ const [emptyHeld, holdEmpty] = useState(0);
2612
+ const [emptyNotice, setEmptyNotice] = useState(null);
2613
+ const notice = useMemo(() => ({
2614
+ hold: holdEmpty,
2615
+ say: setEmptyNotice
2616
+ }), []);
2617
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Command$1.List, {
2618
+ ref,
2619
+ className: cn("max-h-[400px] overflow-y-auto overflow-x-hidden", "p-2", className),
2620
+ ...props,
2621
+ children: /* @__PURE__ */ jsx(EmptyNoticeContext.Provider, {
2622
+ value: notice,
2623
+ children
2624
+ })
2625
+ }), emptyHeld > 0 ? /* @__PURE__ */ jsx("p", {
2626
+ role: "status",
2627
+ "data-slot": "command-empty-status",
2628
+ className: "sr-only",
2629
+ children: emptyNotice
2630
+ }) : null] });
2631
+ });
2526
2632
  CommandList.displayName = "CommandList";
2527
2633
  /**
2528
2634
  * CommandEmpty - Empty state message when no results found.
2529
2635
  * Centered text with muted color per design spec.
2636
+ *
2637
+ * A message of plain text inside a `CommandList` is drawn in the list but hidden from screen
2638
+ * readers, and the list says it from its own status line outside the list. The list is a
2639
+ * `listbox`, which may own only options and their groups: the library gives the message
2640
+ * `role="presentation"`, set after the props it is given, so the list would own its words, and
2641
+ * axe-core's `aria-required-children` fails a list a search found nothing in. A message holding
2642
+ * anything else, a "Try again" button say, stays where it is, so what it holds can still be
2643
+ * reached; so does one outside a list.
2530
2644
  * @experimental
2531
2645
  */
2532
- const CommandEmpty = forwardRef((props, ref) => /* @__PURE__ */ jsx(Command$1.Empty, {
2533
- ref,
2534
- className: "py-8 px-4 text-center text-sm text-muted-foreground",
2535
- ...props
2536
- }));
2646
+ const CommandEmpty = forwardRef(({ children, "aria-hidden": ariaHidden, ...props }, ref) => {
2647
+ const notice = useContext(EmptyNoticeContext);
2648
+ const words = typeof children === "string" || typeof children === "number" ? String(children) : null;
2649
+ const sayer = words === null ? void 0 : notice?.say;
2650
+ const hold = sayer === void 0 ? void 0 : notice?.hold;
2651
+ useEffect(() => {
2652
+ if (hold === void 0) return void 0;
2653
+ hold((count) => count + 1);
2654
+ return () => hold((count) => count - 1);
2655
+ }, [hold]);
2656
+ return /* @__PURE__ */ jsxs(Command$1.Empty, {
2657
+ ref,
2658
+ className: "py-8 px-4 text-center text-sm text-muted-foreground",
2659
+ "aria-hidden": ariaHidden ?? (sayer === void 0 ? void 0 : true),
2660
+ ...props,
2661
+ children: [children, sayer === void 0 ? null : /* @__PURE__ */ jsx(SayEmpty, {
2662
+ say: sayer,
2663
+ notice: words
2664
+ })]
2665
+ });
2666
+ });
2537
2667
  CommandEmpty.displayName = "CommandEmpty";
2538
2668
  /**
2539
2669
  * CommandGroup - Grouped section of commands with optional heading.
@@ -2548,12 +2678,20 @@ const CommandGroup = forwardRef(({ className, ...props }, ref) => /* @__PURE__ *
2548
2678
  CommandGroup.displayName = "CommandGroup";
2549
2679
  /**
2550
2680
  * CommandSeparator - Visual divider between command groups.
2551
- * 1px line with border border-border color, 8px margin top/bottom.
2681
+ * 1px line in the border colour, 8px margin top/bottom.
2682
+ *
2683
+ * Hidden from screen readers by default. It usually sits inside the list, which is a `listbox`,
2684
+ * and a listbox may own only options and their groups: the library's separator sets
2685
+ * `role="separator"` after the props it is given, so the role cannot be swapped out, and a
2686
+ * screen reader meeting it there finds a child the list should not have (axe-core's
2687
+ * `aria-required-children`). Groups already carry their own headings, so the line adds nothing
2688
+ * to what is announced. Placed outside the list, pass `aria-hidden={false}` to announce it.
2552
2689
  * @experimental
2553
2690
  */
2554
- const CommandSeparator = forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Command$1.Separator, {
2691
+ const CommandSeparator = forwardRef(({ className, "aria-hidden": ariaHidden = true, ...props }, ref) => /* @__PURE__ */ jsx(Command$1.Separator, {
2555
2692
  ref,
2556
2693
  className: cn("h-px bg-border my-2", className),
2694
+ "aria-hidden": ariaHidden,
2557
2695
  ...props
2558
2696
  }));
2559
2697
  CommandSeparator.displayName = "CommandSeparator";
@@ -3041,7 +3179,7 @@ const TableSkeleton = ({ columns = 5, rowCount = 8, hideWrapper = false, hideFoo
3041
3179
  };
3042
3180
  TableSkeleton.displayName = "TableSkeleton";
3043
3181
  // src/lib/color/convert.ts
3044
- const clamp01$2 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3182
+ const clamp01$3 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3045
3183
  /**
3046
3184
  * Wrap a hue into [0, 360), so -30 and 330 are the same angle.
3047
3185
  *
@@ -3061,8 +3199,8 @@ function normalizeHue(hue) {
3061
3199
  */
3062
3200
  function hsvToRgb({ h, s, v }) {
3063
3201
  const hue = normalizeHue(h);
3064
- const sat = clamp01$2(s);
3065
- const val = clamp01$2(v);
3202
+ const sat = clamp01$3(s);
3203
+ const val = clamp01$3(v);
3066
3204
  const sector = hue / 60;
3067
3205
  const chroma = val * sat;
3068
3206
  const x = chroma * (1 - Math.abs(sector % 2 - 1));
@@ -3114,9 +3252,9 @@ function hsvToRgb({ h, s, v }) {
3114
3252
  * @experimental
3115
3253
  */
3116
3254
  function rgbToHsv({ r, g, b }) {
3117
- const red = clamp01$2(r);
3118
- const green = clamp01$2(g);
3119
- const blue = clamp01$2(b);
3255
+ const red = clamp01$3(r);
3256
+ const green = clamp01$3(g);
3257
+ const blue = clamp01$3(b);
3120
3258
  const max = Math.max(red, green, blue);
3121
3259
  const chroma = max - Math.min(red, green, blue);
3122
3260
  let hue = 0;
@@ -3135,10 +3273,10 @@ function rgbToHsv({ r, g, b }) {
3135
3273
  // src/lib/color/hex.ts
3136
3274
  /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, with the hash optional and case ignored. */
3137
3275
  const HEX = /^#?(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
3138
- const clamp01$1 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3276
+ const clamp01$2 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3139
3277
  /** A channel byte as a two-digit lowercase pair. */
3140
3278
  function pair(channel) {
3141
- const value = Number.isFinite(channel) ? clamp01$1(channel) : 0;
3279
+ const value = Number.isFinite(channel) ? clamp01$2(channel) : 0;
3142
3280
  return Math.round(value * 255).toString(16).padStart(2, "0");
3143
3281
  }
3144
3282
  /**
@@ -3188,12 +3326,12 @@ function parseHex(input) {
3188
3326
  * @experimental
3189
3327
  */
3190
3328
  function toHex(color, alpha = 1) {
3191
- const opacity = Number.isFinite(alpha) ? clamp01$1(alpha) : 1;
3329
+ const opacity = Number.isFinite(alpha) ? clamp01$2(alpha) : 1;
3192
3330
  const opaque = `#${pair(color.r)}${pair(color.g)}${pair(color.b)}`;
3193
3331
  return opacity === 1 ? opaque : `${opaque}${pair(opacity)}`;
3194
3332
  }
3195
3333
  // src/lib/color/picker-geometry.ts
3196
- const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3334
+ const clamp01$1 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3197
3335
  /**
3198
3336
  * A pointer position as a fraction of a surface.
3199
3337
  *
@@ -3209,8 +3347,8 @@ const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3209
3347
  */
3210
3348
  function pointOnSurface(clientX, clientY, rect) {
3211
3349
  return {
3212
- x: rect.width === 0 ? 0 : clamp01((clientX - rect.left) / rect.width),
3213
- y: rect.height === 0 ? 0 : clamp01((clientY - rect.top) / rect.height)
3350
+ x: rect.width === 0 ? 0 : clamp01$1((clientX - rect.left) / rect.width),
3351
+ y: rect.height === 0 ? 0 : clamp01$1((clientY - rect.top) / rect.height)
3214
3352
  };
3215
3353
  }
3216
3354
  /**
@@ -3224,8 +3362,8 @@ function pointOnSurface(clientX, clientY, rect) {
3224
3362
  */
3225
3363
  function saturationValueAt(point) {
3226
3364
  return {
3227
- s: clamp01(point.x),
3228
- v: 1 - clamp01(point.y)
3365
+ s: clamp01$1(point.x),
3366
+ v: 1 - clamp01$1(point.y)
3229
3367
  };
3230
3368
  }
3231
3369
  /**
@@ -3239,8 +3377,8 @@ function saturationValueAt(point) {
3239
3377
  */
3240
3378
  function surfacePointFor(s, v) {
3241
3379
  return {
3242
- x: clamp01(s),
3243
- y: 1 - clamp01(v)
3380
+ x: clamp01$1(s),
3381
+ y: 1 - clamp01$1(v)
3244
3382
  };
3245
3383
  }
3246
3384
  /**
@@ -3252,7 +3390,7 @@ function surfacePointFor(s, v) {
3252
3390
  * @experimental
3253
3391
  */
3254
3392
  function hueAt(fraction) {
3255
- const hue = clamp01(fraction) * 360;
3393
+ const hue = clamp01$1(fraction) * 360;
3256
3394
  return hue >= 360 ? 0 : hue;
3257
3395
  }
3258
3396
  /** Where the hue handle sits, as a fraction of the strip. @experimental */
@@ -3275,6 +3413,207 @@ function hueSliderValue(hue, max) {
3275
3413
  const step = Math.round(huePosition(hue) * (max + 1));
3276
3414
  return step > max ? max : step;
3277
3415
  }
3416
+ // src/lib/color/formats.ts
3417
+ const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3418
+ /** A CSS number, optionally signed, with an optional fraction and exponent. */
3419
+ const NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
3420
+ /** A number and the unit written after it: `50%`, `120deg`, `0.5`. */
3421
+ const NUMBER_AND_UNIT = /^(.*?)(%|[a-z]*)$/i;
3422
+ /** One component as written: its number, and the unit after it, if any. */
3423
+ function numberAndUnit(text) {
3424
+ const [, digits = "", unit = ""] = NUMBER_AND_UNIT.exec(text) ?? [];
3425
+ const value = Number(digits);
3426
+ if (!NUMBER.test(digits) || !Number.isFinite(value)) return null;
3427
+ return {
3428
+ value,
3429
+ unit: unit.toLowerCase()
3430
+ };
3431
+ }
3432
+ /** A percentage as [0, 1], or a bare number divided by `whole`. */
3433
+ function fractionOf(text, whole) {
3434
+ if (text === void 0) return null;
3435
+ const part = numberAndUnit(text);
3436
+ if (part === null) return null;
3437
+ if (part.unit === "%") return clamp01(part.value / 100);
3438
+ return part.unit === "" ? clamp01(part.value / whole) : null;
3439
+ }
3440
+ /** Degrees in one of each angle unit CSS takes for a hue. */
3441
+ const DEGREES = {
3442
+ "": 1,
3443
+ deg: 1,
3444
+ grad: 360 / 400,
3445
+ rad: 180 / Math.PI,
3446
+ turn: 360
3447
+ };
3448
+ /** A hue, a bare number of degrees or an angle, as [0, 360). */
3449
+ function hueOf(text) {
3450
+ const part = numberAndUnit(text);
3451
+ const scale = part === null ? void 0 : DEGREES[part.unit];
3452
+ if (part === null || scale === void 0) return null;
3453
+ const degrees = part.value * scale % 360;
3454
+ return degrees < 0 ? degrees + 360 : degrees;
3455
+ }
3456
+ /** Every component separated by commas: `rgb(255, 0, 0, 0.5)`. */
3457
+ function commaComponents(body) {
3458
+ if (body.includes("/")) return null;
3459
+ const parts = body.split(",").map((part) => part.trim());
3460
+ if (parts.length !== 3 && parts.length !== 4) return null;
3461
+ return {
3462
+ channels: parts.slice(0, 3),
3463
+ alpha: parts[3],
3464
+ legacy: true
3465
+ };
3466
+ }
3467
+ /** Channels separated by spaces, the alpha after a slash: `rgb(255 0 0 / 50%)`. */
3468
+ function spaceComponents(body) {
3469
+ const [channelText = "", alpha, extra] = body.split("/");
3470
+ if (extra !== void 0 || alpha?.trim() === "") return null;
3471
+ const channels = channelText.trim().split(/\s+/);
3472
+ return channels.length === 3 ? {
3473
+ channels,
3474
+ alpha: alpha?.trim(),
3475
+ legacy: false
3476
+ } : null;
3477
+ }
3478
+ /**
3479
+ * The components of a colour function, or `null` when its punctuation is
3480
+ * neither of the two grammars CSS has. The two are never mixed: `rgb(0 0 0
3481
+ * 0.5)` and `rgb(0, 0, 0 / 1)` are no colour to a browser, so none here.
3482
+ */
3483
+ function componentsOf(body) {
3484
+ return body.includes(",") ? commaComponents(body) : spaceComponents(body);
3485
+ }
3486
+ /** A colour function, as its name and the text between its brackets. */
3487
+ const FUNCTION = /^(rgba?|hsla?)\(\s*([^()]*?)\s*\)$/i;
3488
+ const isPercent = (text) => text?.endsWith("%") === true;
3489
+ /**
3490
+ * Whether the comma syntax's stricter channels hold: `rgb()` takes three
3491
+ * numbers or three percentages, never a mix, and `hsl()` takes its
3492
+ * saturation and lightness as percentages. A browser drops anything else.
3493
+ */
3494
+ function legacyChannelsHold(rgb, [first, ...rest]) {
3495
+ if (!rgb) return rest.every(isPercent);
3496
+ return rest.every((channel) => isPercent(channel) === isPercent(first));
3497
+ }
3498
+ function readRgb([r, g, b], alpha) {
3499
+ const red = fractionOf(r, 255);
3500
+ const green = fractionOf(g, 255);
3501
+ const blue = fractionOf(b, 255);
3502
+ if (red === null || green === null || blue === null) return null;
3503
+ return {
3504
+ r: red,
3505
+ g: green,
3506
+ b: blue,
3507
+ alpha
3508
+ };
3509
+ }
3510
+ function readHsl([hue = "", sat, light], alpha) {
3511
+ const h = hueOf(hue);
3512
+ const s = fractionOf(sat, 100);
3513
+ const l = fractionOf(light, 100);
3514
+ if (h === null || s === null || l === null) return null;
3515
+ return {
3516
+ ...hslToRgb({
3517
+ h,
3518
+ s,
3519
+ l
3520
+ }),
3521
+ alpha
3522
+ };
3523
+ }
3524
+ /** `rgb()`, `rgba()`, `hsl()` or `hsla()`, or `null` for anything else. */
3525
+ function parseFunction(text) {
3526
+ const [, name = "", body = ""] = FUNCTION.exec(text) ?? [];
3527
+ const parts = name === "" ? null : componentsOf(body);
3528
+ if (parts === null) return null;
3529
+ const rgb = name.toLowerCase().startsWith("rgb");
3530
+ if (parts.legacy && !legacyChannelsHold(rgb, parts.channels)) return null;
3531
+ const alpha = parts.alpha === void 0 ? 1 : fractionOf(parts.alpha, 1);
3532
+ if (alpha === null) return null;
3533
+ return rgb ? readRgb(parts.channels, alpha) : readHsl(parts.channels, alpha);
3534
+ }
3535
+ /**
3536
+ * Read a colour typed or pasted as hex (3, 4, 6 or 8 digits), `rgb()`/`rgba()`
3537
+ * or `hsl()`/`hsla()`, in either the comma or the space syntax, or `null` if
3538
+ * the text is none of them yet.
3539
+ *
3540
+ * `null` rather than a guess, as `parseHex` answers: a field someone is typing
3541
+ * into holds "not a colour yet" most of the time. Components out of range are
3542
+ * clamped, as a browser clamps them.
3543
+ *
3544
+ * @experimental
3545
+ */
3546
+ function parseColour(input) {
3547
+ const text = input.trim();
3548
+ return parseHex(text) ?? parseFunction(text);
3549
+ }
3550
+ /** Which sixth of the hue circle a colour sits in, from its largest channel. */
3551
+ function hueSector({ r, g, b }, max, d) {
3552
+ if (max === r) return ((g - b) / d + 6) % 6;
3553
+ if (max === g) return (b - r) / d + 2;
3554
+ return (r - g) / d + 4;
3555
+ }
3556
+ /** sRGB channels in [0, 1] as hue, saturation and lightness. */
3557
+ function rgbToHsl(color) {
3558
+ const max = Math.max(color.r, color.g, color.b);
3559
+ const min = Math.min(color.r, color.g, color.b);
3560
+ const l = (max + min) / 2;
3561
+ const d = max - min;
3562
+ if (d === 0) return {
3563
+ h: 0,
3564
+ s: 0,
3565
+ l
3566
+ };
3567
+ const s = d / (1 - Math.abs(2 * l - 1));
3568
+ return {
3569
+ h: hueSector(color, max, d) * 60,
3570
+ s,
3571
+ l
3572
+ };
3573
+ }
3574
+ /** Hue, saturation and lightness as sRGB channels in [0, 1]. */
3575
+ function hslToRgb({ h, s, l }) {
3576
+ const a = s * Math.min(l, 1 - l);
3577
+ const f = (n) => {
3578
+ const k = (n + h / 30) % 12;
3579
+ return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
3580
+ };
3581
+ return {
3582
+ r: f(0),
3583
+ g: f(8),
3584
+ b: f(4)
3585
+ };
3586
+ }
3587
+ /** ` / 0.5` for a translucent colour, nothing for an opaque one. */
3588
+ function alphaSuffix(alpha) {
3589
+ const opacity = Number.isFinite(alpha) ? clamp01(alpha) : 1;
3590
+ return opacity === 1 ? "" : ` / ${Math.round(opacity * 100) / 100}`;
3591
+ }
3592
+ /** A channel in [0, 1] as the 0-255 `rgb()` writes. */
3593
+ const byte = (channel) => Math.round(clamp01(Number.isFinite(channel) ? channel : 0) * 255);
3594
+ /** A fraction as a whole percentage. */
3595
+ const percent = (fraction) => `${Math.round(fraction * 100)}%`;
3596
+ /** `hsl()` for a colour, read from its bytes so it names what hex would. */
3597
+ function hslText(color, alpha) {
3598
+ const { h, s, l } = rgbToHsl({
3599
+ r: byte(color.r) / 255,
3600
+ g: byte(color.g) / 255,
3601
+ b: byte(color.b) / 255
3602
+ });
3603
+ return `hsl(${Math.round(h) % 360} ${percent(s)} ${percent(l)}${alphaSuffix(alpha)})`;
3604
+ }
3605
+ /**
3606
+ * Write a colour in one of the three notations: hex as `toHex` writes it, and
3607
+ * the functions in the space-separated syntax, with the alpha after a slash
3608
+ * only when the colour is not opaque.
3609
+ *
3610
+ * @experimental
3611
+ */
3612
+ function formatColour(color, alpha, format) {
3613
+ if (format === "hex") return toHex(color, alpha);
3614
+ if (format === "hsl") return hslText(color, alpha);
3615
+ return `rgb(${byte(color.r)} ${byte(color.g)} ${byte(color.b)}${alphaSuffix(alpha)})`;
3616
+ }
3278
3617
  // src/lib/isomorphic-layout-effect.ts
3279
3618
  /**
3280
3619
  * A layout effect in the browser, a plain effect where there is no DOM.
@@ -3318,6 +3657,21 @@ function toHsva(hex) {
3318
3657
  function toHexString(hsva, withAlpha) {
3319
3658
  return toHex(hsvToRgb(hsva), withAlpha ? hsva.a : 1);
3320
3659
  }
3660
+ /** The notations the field can show, as their buttons name them. */
3661
+ const FORMATS = [
3662
+ {
3663
+ format: "hex",
3664
+ label: "Hex"
3665
+ },
3666
+ {
3667
+ format: "rgb",
3668
+ label: "RGB"
3669
+ },
3670
+ {
3671
+ format: "hsl",
3672
+ label: "HSL"
3673
+ }
3674
+ ];
3321
3675
  /** The last step of the hue strip. Kept beside the input it sizes. */
3322
3676
  const HUE_MAX = 359;
3323
3677
  /**
@@ -3373,8 +3727,10 @@ function isNode(value) {
3373
3727
  return value !== null && typeof value.nodeType === "number";
3374
3728
  }
3375
3729
  /**
3376
- * A colour control: a saturation square, a hue strip, optional alpha, a hex
3377
- * field, and any presets the host supplies.
3730
+ * A colour control: a saturation square, a hue strip, optional alpha, a field
3731
+ * that reads hex, `rgb()` or `hsl()` and shows whichever of the three the
3732
+ * author picks, the screen's eyedropper where the browser has one, and any
3733
+ * presets and recent colours the host supplies. What it reports is hex.
3378
3734
  *
3379
3735
  * Deliberately knows nothing about design tokens. A swatch carries an opaque
3380
3736
  * `value` this component never reads and hands back untouched, so a host can
@@ -3394,8 +3750,9 @@ function isNode(value) {
3394
3750
  * />
3395
3751
  * ```
3396
3752
  */
3397
- function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, recentColors = [], showAlpha = false, className }) {
3753
+ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, recentColors, onRecentSelect, showAlpha = false, className }) {
3398
3754
  const fieldId = React.useId();
3755
+ const [format, setFormat] = React.useState("hex");
3399
3756
  /** The picker's own subtree, for telling a press inside it from a dismissal. */
3400
3757
  const rootRef = React.useRef(null);
3401
3758
  /**
@@ -3427,6 +3784,7 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3427
3784
  const [draftHex, setDraftHex] = React.useState(null);
3428
3785
  const draftRef = React.useRef(null);
3429
3786
  const rendered = toHexString(hsva, showAlpha);
3787
+ const shownText = formatColour(hsvToRgb(hsva), showAlpha ? hsva.a : 1, format);
3430
3788
  useIsomorphicLayoutEffect(() => {
3431
3789
  const incoming = parseHex(color);
3432
3790
  if (incoming && toHex(incoming, showAlpha ? incoming.alpha : 1) !== rendered) {
@@ -3449,7 +3807,8 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3449
3807
  draftRef.current = null;
3450
3808
  if (text === null) return;
3451
3809
  setDraftHex(null);
3452
- const parsed = parseHex(text);
3810
+ if (text.trim() === shownText) return;
3811
+ const parsed = parseColour(text);
3453
3812
  if (!parsed) return;
3454
3813
  setHsva((prev) => hsvaFrom(parsed, parsed.alpha, prev.h));
3455
3814
  onColorChange(toHex(parsed, showAlpha ? parsed.alpha : 1));
@@ -3551,6 +3910,20 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3551
3910
  s: 1,
3552
3911
  v: 1
3553
3912
  }));
3913
+ const formatLabel = FORMATS.find((entry) => entry.format === format)?.label ?? "Hex";
3914
+ const chooseFormat = (next) => {
3915
+ commitDraft();
3916
+ setFormat(next);
3917
+ };
3918
+ const chooseRecent = (recent) => {
3919
+ if (onRecentSelect !== void 0) {
3920
+ dropDraft();
3921
+ onRecentSelect(recent);
3922
+ return;
3923
+ }
3924
+ const parsed = parseColour(recent);
3925
+ if (parsed) commit(hsvaFrom(parsed, parsed.alpha, hsva.h));
3926
+ };
3554
3927
  const pickFromScreen = async () => {
3555
3928
  const ctor = window.EyeDropper;
3556
3929
  if (!ctor) return;
@@ -3568,7 +3941,7 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3568
3941
  };
3569
3942
  return /* @__PURE__ */ jsxs("div", {
3570
3943
  ref: rootRef,
3571
- className: cn("w-64 space-y-3", className),
3944
+ className: cn("w-full max-w-64 space-y-3", className),
3572
3945
  onBlur: (event) => {
3573
3946
  const next = event.relatedTarget;
3574
3947
  const root = rootRef.current;
@@ -3650,18 +4023,32 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3650
4023
  backgroundSize: "100% 100%, 8px 8px"
3651
4024
  }
3652
4025
  })] }),
4026
+ /* @__PURE__ */ jsx("div", {
4027
+ role: "group",
4028
+ "aria-label": "Colour format",
4029
+ className: "bg-muted inline-flex rounded-md p-0.5",
4030
+ children: FORMATS.map((entry) => /* @__PURE__ */ jsx("button", {
4031
+ type: "button",
4032
+ "aria-pressed": entry.format === format,
4033
+ className: cn("text-muted-foreground hover:text-foreground focus-visible:ring-ring min-h-6 min-w-10 rounded px-2 text-xs font-medium focus-visible:ring-2 focus-visible:outline-none", entry.format === format && "bg-background text-foreground shadow-sm"),
4034
+ onClick: () => chooseFormat(entry.format),
4035
+ children: entry.label
4036
+ }, entry.format))
4037
+ }),
3653
4038
  /* @__PURE__ */ jsxs("div", {
3654
4039
  className: "flex items-center gap-2",
3655
4040
  children: [
3656
4041
  /* @__PURE__ */ jsx("label", {
3657
4042
  className: "sr-only",
3658
4043
  htmlFor: `${fieldId}-hex`,
3659
- children: "Hex colour"
4044
+ children: `${formatLabel} colour`
3660
4045
  }),
3661
4046
  /* @__PURE__ */ jsx(Input, {
3662
4047
  id: `${fieldId}-hex`,
3663
4048
  className: "font-mono",
3664
- value: draftHex ?? rendered,
4049
+ spellCheck: false,
4050
+ autoComplete: "off",
4051
+ value: draftHex ?? shownText,
3665
4052
  onChange: (event) => {
3666
4053
  draftRef.current = event.target.value;
3667
4054
  setDraftHex(event.target.value);
@@ -3677,7 +4064,8 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3677
4064
  type: "button",
3678
4065
  variant: "outline",
3679
4066
  size: "icon",
3680
- "aria-label": "Pick a colour from the screen",
4067
+ "aria-label": "Pick from screen",
4068
+ title: "Pick from screen",
3681
4069
  onClick: () => void pickFromScreen(),
3682
4070
  children: /* @__PURE__ */ jsx(Pipette, { className: "size-4" })
3683
4071
  })
@@ -3701,26 +4089,43 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3701
4089
  }
3702
4090
  }, swatch.id))
3703
4091
  })] }),
3704
- recentColors.length > 0 && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
3705
- className: "text-muted-foreground mb-1 text-xs",
3706
- children: "Recent"
3707
- }), /* @__PURE__ */ jsx("div", {
3708
- className: "flex flex-wrap gap-1",
3709
- children: recentColors.map((recent) => /* @__PURE__ */ jsx("button", {
3710
- type: "button",
3711
- title: recent,
3712
- "aria-label": recent,
3713
- className: "size-6 rounded border shadow-sm",
3714
- style: { backgroundColor: recent },
3715
- onClick: () => {
3716
- const parsed = parseHex(recent);
3717
- if (parsed) commit(hsvaFrom(parsed, parsed.alpha, hsva.h));
3718
- }
3719
- }, recent))
3720
- })] })
4092
+ recentColors === void 0 ? null : /* @__PURE__ */ jsx(RecentColors, {
4093
+ colors: recentColors,
4094
+ onChoose: chooseRecent
4095
+ })
3721
4096
  ]
3722
4097
  });
3723
4098
  }
4099
+ /**
4100
+ * The host's recent colours, under their heading, each a swatch named by its
4101
+ * value. Shown while there are none too, saying what will appear there, so
4102
+ * the place is known before it is filled.
4103
+ */
4104
+ function RecentColors({ colors, onChoose }) {
4105
+ const headingId = React.useId();
4106
+ return /* @__PURE__ */ jsxs("div", {
4107
+ role: "group",
4108
+ "aria-labelledby": headingId,
4109
+ children: [/* @__PURE__ */ jsx("p", {
4110
+ id: headingId,
4111
+ className: "text-muted-foreground mb-1 text-xs",
4112
+ children: "Recent colours"
4113
+ }), colors.length === 0 ? /* @__PURE__ */ jsx("p", {
4114
+ className: "text-muted-foreground text-xs",
4115
+ children: "Colours you type or pick show here."
4116
+ }) : /* @__PURE__ */ jsx("div", {
4117
+ className: "flex flex-wrap gap-1",
4118
+ children: colors.map((recent) => /* @__PURE__ */ jsx("button", {
4119
+ type: "button",
4120
+ title: recent,
4121
+ "aria-label": recent,
4122
+ className: "size-6 rounded border shadow-sm",
4123
+ style: { backgroundColor: recent },
4124
+ onClick: () => onChoose(recent)
4125
+ }, recent))
4126
+ })]
4127
+ });
4128
+ }
3724
4129
  // src/components/icon-glyph.tsx
3725
4130
  /** The shape elements a body may contain. */
3726
4131
  const SHAPES = /* @__PURE__ */ new Set([