@nextlyhq/ui 0.0.2-alpha.73 → 0.0.2-alpha.74

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
@@ -7,7 +7,7 @@ import { clsx } from "clsx";
7
7
  import { twMerge } from "tailwind-merge";
8
8
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
9
9
  import { Root } from "@radix-ui/react-label";
10
- import { AlertCircle, AlertTriangle, Check, CheckCircle2, ChevronDown, ChevronRight, ChevronUp, Circle, FileQuestion, GripVertical, Info, Loader2, Minus, Pipette, Search, X, XCircle } from "lucide-react";
10
+ import { AlertCircle, AlertTriangle, Check, CheckCircle2, ChevronDown, ChevronRight, ChevronUp, Circle, CircleHelp, FileQuestion, GripVertical, Info, Loader2, Minus, Pipette, Search, TriangleAlert, X, XCircle } from "lucide-react";
11
11
  import { Content, Portal, Provider, Root as Root$1, Trigger } from "@radix-ui/react-tooltip";
12
12
  import * as SeparatorPrimitive from "@radix-ui/react-separator";
13
13
  import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
@@ -24,9 +24,9 @@ import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
24
24
  import * as SelectPrimitive from "@radix-ui/react-select";
25
25
  import { Command as Command$1, defaultFilter, useCommandState } from "cmdk";
26
26
  import { Toaster as Toaster$1, toast } from "sonner";
27
+ import { useVirtualizer } from "@tanstack/react-virtual";
27
28
  import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
28
29
  import * as ResizablePrimitive from "react-resizable-panels";
29
- import { useVirtualizer } from "@tanstack/react-virtual";
30
30
  import * as SliderPrimitive from "@radix-ui/react-slider";
31
31
  // src/lib/utils.ts
32
32
  /**
@@ -63,7 +63,7 @@ function cn(...inputs) {
63
63
  * Note: 'primary' is a semantic alias for 'default' variant for better code readability
64
64
  * @experimental
65
65
  */
66
- const buttonVariants = cva("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium cursor-pointer transition-all duration-150 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0 disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed active:scale-[0.98] [&_svg]:text-current", {
66
+ const buttonVariants = cva(`inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium cursor-pointer transition-all duration-150 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring [.overflow-hidden>&]:focus-visible:outline-offset-[-2px] [.overflow-hidden>&]:focus-visible:shadow-[inset_0_0_0_4px_var(--nx-background)] disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed active:scale-[0.98] [&_svg]:text-current`, {
67
67
  variants: {
68
68
  variant: {
69
69
  default: "bg-primary text-primary-foreground border border-transparent hover:opacity-90",
@@ -1376,7 +1376,7 @@ const TabsList = forwardRef(({ className, variant, scrollable = false, ...props
1376
1376
  });
1377
1377
  });
1378
1378
  TabsList.displayName = List.displayName;
1379
- const tabsTriggerVariants = cva("inline-flex items-center justify-center whitespace-nowrap rounded-none bg-transparent px-4 py-2 font-medium cursor-pointer transition-all duration-200 border-b-2 relative -mb-0.5 data-[state=active]:border-b-primary data-[state=active]:text-primary data-[state=inactive]:border-transparent data-[state=inactive]:text-muted-foreground hover:text-primary hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed data-[orientation=vertical]:border-b-0 data-[orientation=vertical]:mb-0 data-[orientation=vertical]:border-r-2 data-[orientation=vertical]:-mr-0.5 data-[orientation=vertical]:data-[state=active]:border-r-primary", {
1379
+ const tabsTriggerVariants = cva("inline-flex items-center justify-center whitespace-nowrap rounded-none bg-transparent px-4 py-2 font-medium cursor-pointer transition-all duration-200 border-b-2 relative -mb-0.5 data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=inactive]:border-transparent data-[state=inactive]:text-muted-foreground hover:text-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed data-[orientation=vertical]:border-b-0 data-[orientation=vertical]:mb-0 data-[orientation=vertical]:border-r-2 data-[orientation=vertical]:-mr-0.5 data-[orientation=vertical]:data-[state=active]:border-r-primary", {
1380
1380
  variants: { size: {
1381
1381
  default: "text-sm",
1382
1382
  sm: "text-xs"
@@ -2387,7 +2387,7 @@ const CommandDialog = ({ children, commandProps, contentProps, ...props }) => {
2387
2387
  children: [/* @__PURE__ */ jsx(CommandDialogOverlay, {}), /* @__PURE__ */ jsx(DialogPrimitive.Content, {
2388
2388
  ...contentProps,
2389
2389
  "data-slot": "command-content",
2390
- className: cn("fixed left-[50%] top-[50%] z-[100] translate-x-[-50%] translate-y-[-50%]", "w-full max-w-lg", "max-h-[85vh]", "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-[48%] data-[state=open]:slide-in-from-top-[48%]"),
2390
+ 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"),
2391
2391
  children: /* @__PURE__ */ jsx(Command, {
2392
2392
  ...commandProps,
2393
2393
  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),
@@ -2464,7 +2464,7 @@ CommandSeparator.displayName = "CommandSeparator";
2464
2464
  */
2465
2465
  const CommandItem = forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Command$1.Item, {
2466
2466
  ref,
2467
- className: cn("relative flex cursor-pointer select-none items-center gap-3", "min-h-[44px] sm:min-h-[36px]", "px-3 py-2.5", "rounded-sm text-base sm:text-sm outline-none", "transition-all duration-200 ease-(--ease-premium)", "hover-unified", "aria-selected:bg-primary/5 aria-selected:text-primary", "data-[selected=true]:bg-primary/5 data-[selected=true]:text-primary", "data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50", className),
2467
+ className: cn("relative flex cursor-pointer select-none items-center gap-3", "min-h-[44px] sm:min-h-[36px]", "px-3 py-2.5", "rounded-sm text-base sm:text-sm outline-none", "transition-all duration-200 ease-(--ease-premium)", "hover-unified", "aria-selected:bg-primary/5 aria-selected:text-foreground", "data-[selected=true]:bg-primary/5 data-[selected=true]:text-foreground", "data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50", className),
2468
2468
  ...props
2469
2469
  }));
2470
2470
  CommandItem.displayName = "CommandItem";
@@ -2712,7 +2712,9 @@ function Toaster({ theme = "system", ...props }) {
2712
2712
  "--normal-border": "var(--nx-border)",
2713
2713
  "--border-radius": "0px",
2714
2714
  "--success-bg": "var(--nx-toast-success-bg)",
2715
- "--success-text": "var(--nx-toast-success-text)"
2715
+ "--success-text": "var(--nx-toast-success-text)",
2716
+ "--warning-bg": "var(--nx-toast-warning-bg)",
2717
+ "--warning-text": "var(--nx-toast-warning-text)"
2716
2718
  },
2717
2719
  ...props
2718
2720
  });
@@ -3612,6 +3614,963 @@ function ColorPicker({ color, onColorChange, swatches = [], onSwatchSelect, rece
3612
3614
  ]
3613
3615
  });
3614
3616
  }
3617
+ // src/components/icon-glyph.tsx
3618
+ /** The shape elements a body may contain. */
3619
+ const SHAPES = /* @__PURE__ */ new Set([
3620
+ "path",
3621
+ "circle",
3622
+ "ellipse",
3623
+ "line",
3624
+ "polygon",
3625
+ "polyline",
3626
+ "rect"
3627
+ ]);
3628
+ /** The attributes a shape may carry: geometry, and its fill. */
3629
+ const GEOMETRY = /* @__PURE__ */ new Set([
3630
+ "d",
3631
+ "cx",
3632
+ "cy",
3633
+ "r",
3634
+ "rx",
3635
+ "ry",
3636
+ "x",
3637
+ "y",
3638
+ "x1",
3639
+ "x2",
3640
+ "y1",
3641
+ "y2",
3642
+ "width",
3643
+ "height",
3644
+ "points",
3645
+ "fill"
3646
+ ]);
3647
+ /** The fills a shape may name: none, or the text colour. */
3648
+ const FILLS = /* @__PURE__ */ new Set(["none", "currentColor"]);
3649
+ /**
3650
+ * Read bodies, by body. A picker draws the same few hundred icons on every
3651
+ * scroll, and reading each once is what keeps a scroll from re-reading them.
3652
+ * Bounded so a host searching several large sets cannot grow it without end.
3653
+ */
3654
+ const readBodies = /* @__PURE__ */ new Map();
3655
+ const READ_BODIES_LIMIT = 4096;
3656
+ /** One element and the attributes after its name, anchored where the last one ended. */
3657
+ const ELEMENT = /\s*<([a-z]+)((?:\s+[a-zA-Z0-9-]+="[^"<>]*")*)\s*\/>/y;
3658
+ const ATTRIBUTE = /([a-zA-Z0-9-]+)="([^"<>]*)"/g;
3659
+ /** A shape's attributes, or `null` when any is not allowed geometry. */
3660
+ function readAttributes(text) {
3661
+ const attributes = {};
3662
+ for (const [, name = "", value = ""] of text.matchAll(ATTRIBUTE)) {
3663
+ if (!(GEOMETRY.has(name) && (name !== "fill" || FILLS.has(value)))) return null;
3664
+ attributes[name] = value;
3665
+ }
3666
+ return attributes;
3667
+ }
3668
+ /** The shape at `at` and where it ends, or `null` when none starts there. */
3669
+ function readShape(body, at) {
3670
+ ELEMENT.lastIndex = at;
3671
+ const match = ELEMENT.exec(body);
3672
+ const tag = match?.[1];
3673
+ if (match === null || tag === void 0 || !SHAPES.has(tag)) return null;
3674
+ const attributes = readAttributes(match[2] ?? "");
3675
+ return attributes === null ? null : {
3676
+ shape: {
3677
+ tag,
3678
+ attributes
3679
+ },
3680
+ end: ELEMENT.lastIndex
3681
+ };
3682
+ }
3683
+ /**
3684
+ * A body read as shapes, or `null` when any part of it is not one: every
3685
+ * element must be an allowed shape, every attribute allowed geometry, and
3686
+ * nothing may sit between the elements but whitespace.
3687
+ */
3688
+ function readBody(body) {
3689
+ const cached = readBodies.get(body);
3690
+ if (cached !== void 0) return cached;
3691
+ let shapes = [];
3692
+ let at = 0;
3693
+ while (shapes !== null && body.slice(at).trim() !== "") {
3694
+ const read = readShape(body, at);
3695
+ if (read === null) shapes = null;
3696
+ else {
3697
+ shapes.push(read.shape);
3698
+ at = read.end;
3699
+ }
3700
+ }
3701
+ if (readBodies.size >= READ_BODIES_LIMIT) readBodies.clear();
3702
+ readBodies.set(body, shapes);
3703
+ return shapes;
3704
+ }
3705
+ /**
3706
+ * An icon from an {@link IconSource}, drawn as an inline SVG in the text
3707
+ * colour.
3708
+ *
3709
+ * Decorative by default (`aria-hidden`): the control around it names the
3710
+ * icon. The body is read into React elements rather than inserted as markup,
3711
+ * and a body that is not a run of plain shapes draws an empty box.
3712
+ *
3713
+ * @experimental
3714
+ */
3715
+ function IconGlyph({ icon, className, ...props }) {
3716
+ const shapes = readBody(icon.body) ?? [];
3717
+ const stroked = icon.stroked !== false;
3718
+ return /* @__PURE__ */ jsx("svg", {
3719
+ xmlns: "http://www.w3.org/2000/svg",
3720
+ viewBox: icon.viewBox,
3721
+ "aria-hidden": "true",
3722
+ focusable: "false",
3723
+ fill: stroked ? "none" : "currentColor",
3724
+ stroke: stroked ? "currentColor" : "none",
3725
+ strokeWidth: stroked ? 2 : void 0,
3726
+ strokeLinecap: stroked ? "round" : void 0,
3727
+ strokeLinejoin: stroked ? "round" : void 0,
3728
+ className: cn("size-4 shrink-0", className),
3729
+ ...props,
3730
+ children: shapes.map((shape, index) => React.createElement(shape.tag, {
3731
+ key: index,
3732
+ ...shape.attributes
3733
+ }))
3734
+ });
3735
+ }
3736
+ /**
3737
+ * An icon's name as a person reads it: `circle-arrow-up` is
3738
+ * `Circle arrow up`.
3739
+ */
3740
+ function iconDisplayName(name) {
3741
+ const words = name.replace(/-/g, " ").trim();
3742
+ return words.charAt(0).toUpperCase() + words.slice(1);
3743
+ }
3744
+ // src/components/icon-picker.tsx
3745
+ /** Icons per row of the results grid. */
3746
+ const COLUMNS = 8;
3747
+ /** One row of the grid: a 38px cell and the 2px gap below it. */
3748
+ const ROW_HEIGHT$1 = 40;
3749
+ /** Rows a Page Up or Page Down moves the highlight by. */
3750
+ const PAGE_ROWS = 5;
3751
+ /** How the picker's headings are set: small capitals in the muted ink. */
3752
+ const HEADING_TEXT = "px-3 pb-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground";
3753
+ /** A heading inside the grid, "Recent" or "All icons": its line and the space above. */
3754
+ const HEADING_HEIGHT = 28;
3755
+ /** How many recently used icons the picker offers: one row of the grid. */
3756
+ const RECENT_SHOWN = COLUMNS;
3757
+ const loads = /* @__PURE__ */ new WeakMap();
3758
+ const loaded = /* @__PURE__ */ new WeakMap();
3759
+ function loadOnce(load) {
3760
+ const existing = loads.get(load);
3761
+ if (existing !== void 0) return existing;
3762
+ const loading = load();
3763
+ loads.set(load, loading);
3764
+ loading.then((source) => loaded.set(load, source), () => {
3765
+ if (loads.get(load) === loading) loads.delete(load);
3766
+ });
3767
+ return loading;
3768
+ }
3769
+ /**
3770
+ * The icon source, loaded once `wanted` turns true, and a way to try again
3771
+ * after a failed load.
3772
+ */
3773
+ function useIconSource(load, wanted) {
3774
+ const [state, setState] = React.useState(() => {
3775
+ const source = loaded.get(load);
3776
+ return source === void 0 ? { status: "loading" } : {
3777
+ status: "ready",
3778
+ source
3779
+ };
3780
+ });
3781
+ const [attempt, setAttempt] = React.useState(0);
3782
+ React.useEffect(() => {
3783
+ if (!wanted) return;
3784
+ let current = true;
3785
+ setState((previous) => previous.status === "ready" ? previous : { status: "loading" });
3786
+ loadOnce(load).then((source) => {
3787
+ if (current) setState({
3788
+ status: "ready",
3789
+ source
3790
+ });
3791
+ }, () => {
3792
+ if (current) setState({ status: "failed" });
3793
+ });
3794
+ return () => {
3795
+ current = false;
3796
+ };
3797
+ }, [
3798
+ load,
3799
+ wanted,
3800
+ attempt
3801
+ ]);
3802
+ return [state, () => setAttempt((n) => n + 1)];
3803
+ }
3804
+ /**
3805
+ * What a stored id draws as, once the source can say, and a way to ask again
3806
+ * after the asking failed.
3807
+ */
3808
+ function useResolvedIcon(source, id) {
3809
+ const [resolved, setResolved] = React.useState(null);
3810
+ const [attempt, setAttempt] = React.useState(0);
3811
+ const ready = source.status === "ready" ? source.source : null;
3812
+ React.useEffect(() => {
3813
+ if (ready === null || !id) return;
3814
+ let current = true;
3815
+ ready.resolve(id).then((icon) => {
3816
+ if (!current) return;
3817
+ setResolved({
3818
+ id,
3819
+ attempt,
3820
+ answer: icon === null ? { status: "missing" } : {
3821
+ status: "found",
3822
+ icon
3823
+ }
3824
+ });
3825
+ }, () => {
3826
+ if (current) setResolved({
3827
+ id,
3828
+ attempt,
3829
+ answer: { status: "failed" }
3830
+ });
3831
+ });
3832
+ return () => {
3833
+ current = false;
3834
+ };
3835
+ }, [
3836
+ ready,
3837
+ id,
3838
+ attempt
3839
+ ]);
3840
+ const retry = () => setAttempt((n) => n + 1);
3841
+ if (!id) return [{ status: "none" }, retry];
3842
+ if (resolved?.id === id && (resolved.answer.status !== "failed" || resolved.attempt === attempt)) return [resolved.answer, retry];
3843
+ return [source.status === "failed" ? { status: "failed" } : { status: "loading" }, retry];
3844
+ }
3845
+ /** The set and name an id carries, read without the set: `lucide:star`. */
3846
+ function partsOf(id) {
3847
+ const colon = id.indexOf(":");
3848
+ return colon === -1 ? {
3849
+ set: "",
3850
+ name: id
3851
+ } : {
3852
+ set: id.slice(0, colon),
3853
+ name: id.slice(colon + 1)
3854
+ };
3855
+ }
3856
+ /** The rows of icons from `start` up to `end`, eight to a row. */
3857
+ function iconRows(start, end) {
3858
+ const rows = [];
3859
+ for (let at = start; at < end; at += COLUMNS) rows.push({
3860
+ kind: "icons",
3861
+ start: at,
3862
+ end: Math.min(end, at + COLUMNS)
3863
+ });
3864
+ return rows;
3865
+ }
3866
+ /**
3867
+ * The grid's rows: the recently used icons under "Recent" and the rest under
3868
+ * `label` ("All icons", or the search's matches) when there are any recent
3869
+ * ones to show, otherwise the icons alone, under the heading above the grid.
3870
+ */
3871
+ function gridRows(recentCount, count, label) {
3872
+ if (recentCount === 0) return iconRows(0, count);
3873
+ return [
3874
+ {
3875
+ kind: "heading",
3876
+ label: "Recent"
3877
+ },
3878
+ ...iconRows(0, recentCount),
3879
+ {
3880
+ kind: "heading",
3881
+ label
3882
+ },
3883
+ ...iconRows(recentCount, count)
3884
+ ];
3885
+ }
3886
+ /** What the icons below the Recent row are: the whole set, or a search's matches. */
3887
+ function resultsLabel(query) {
3888
+ return query === "" ? "All icons" : `Matches for “${query}”`;
3889
+ }
3890
+ /** The rows the arrow and page keys move the highlight up or down by. */
3891
+ const ROW_STEPS = {
3892
+ ArrowUp: -1,
3893
+ ArrowDown: 1,
3894
+ PageUp: -5,
3895
+ PageDown: PAGE_ROWS
3896
+ };
3897
+ /**
3898
+ * Where a key moves the highlight from `active` in the grid's rows, or
3899
+ * `undefined` for a key the grid does not answer. Left and right move by one
3900
+ * icon, across rows; up and down move by rows of icons, past a heading,
3901
+ * keeping the column, or the last icon of a shorter row. Up from the top row
3902
+ * stays put rather than jumping to the first icon.
3903
+ */
3904
+ function stepFrom(key, active, rows) {
3905
+ const icons = rows.filter((row) => row.kind === "icons");
3906
+ const last = icons.at(-1);
3907
+ if (last === void 0) return void 0;
3908
+ if (key === "ArrowLeft") return Math.max(0, active - 1);
3909
+ if (key === "ArrowRight") return Math.min(last.end - 1, active + 1);
3910
+ const step = ROW_STEPS[key];
3911
+ if (step === void 0) return void 0;
3912
+ const at = icons.findIndex((row) => active >= row.start && active < row.end);
3913
+ const from = icons[at];
3914
+ const to = icons[Math.min(icons.length - 1, Math.max(0, at + step))];
3915
+ if (from === void 0 || to === void 0) return void 0;
3916
+ return Math.min(to.end - 1, to.start + (active - from.start));
3917
+ }
3918
+ /** The row an option is drawn in, for scrolling it into view. */
3919
+ function rowOf(rows, index) {
3920
+ return Math.max(0, rows.findIndex((row) => row.kind === "icons" && index >= row.start && index < row.end));
3921
+ }
3922
+ /**
3923
+ * The recently used icons to offer, newest first: the ids the host remembers
3924
+ * that the set still draws, found among the whole set's icons, which the
3925
+ * picker has from the browse it opens on. Offered above a search's matches
3926
+ * too, so an icon used a moment ago is one press away whatever is typed.
3927
+ */
3928
+ function recentAmong(wholeSet, recentIds) {
3929
+ if (wholeSet === null || recentIds === void 0) return [];
3930
+ const byId = new Map(wholeSet.map((icon) => [icon.id, icon]));
3931
+ const recent = [];
3932
+ for (const id of new Set(recentIds)) {
3933
+ const icon = byId.get(id);
3934
+ if (icon !== void 0) recent.push(icon);
3935
+ if (recent.length === RECENT_SHOWN) break;
3936
+ }
3937
+ return recent;
3938
+ }
3939
+ /** What the picker's status line says, for the results in hand. */
3940
+ function announcementFor(results, failed, query) {
3941
+ if (results === null) return failed ? "The icons could not be loaded." : "Loading icons.";
3942
+ if (results.length === 0) return `No icons match “${query}”.`;
3943
+ const icons = `${results.length} ${results.length === 1 ? "icon" : "icons"}`;
3944
+ return query === "" ? `${icons}.` : `${icons} match “${query}”.`;
3945
+ }
3946
+ /**
3947
+ * The results for a query, and the highlighted one among them.
3948
+ *
3949
+ * The latest search wins: results arrive asynchronously, so a slow answer to
3950
+ * "tr" must not replace the answer to "truck" that came back first, and
3951
+ * until the query typed is answered the search is `pending`. Browsing (an
3952
+ * empty query) highlights the chosen icon, once `currentSettled` says which
3953
+ * icon `currentId` is; a search highlights its best match. The highlight is a
3954
+ * place among the options as drawn, which while browsing start with the
3955
+ * Recent row the host's `recentIds` give.
3956
+ */
3957
+ function useIconSearch(source, query, currentId, currentSettled, recentIds) {
3958
+ const [answer, setAnswer] = React.useState(null);
3959
+ const [wholeSet, setWholeSet] = React.useState(null);
3960
+ const [attempt, setAttempt] = React.useState(0);
3961
+ const [active, setActive] = React.useState(0);
3962
+ const [start, setStart] = React.useState(null);
3963
+ const placed = React.useRef(null);
3964
+ const place = React.useEffectEvent((found) => {
3965
+ if (found.status !== "found" || !currentSettled) return;
3966
+ placed.current = {
3967
+ answer: found,
3968
+ wholeSet
3969
+ };
3970
+ const browsing = found.query.trim() === "";
3971
+ const recent = recentAmong(browsing ? found.results : wholeSet, recentIds);
3972
+ const options = [...recent, ...found.results];
3973
+ const chosen = browsing && currentId ? options.findIndex((icon) => icon.id === currentId) : -1;
3974
+ const index = browsing ? Math.max(0, chosen) : found.results.length > 0 ? recent.length : 0;
3975
+ setActive(index);
3976
+ setStart({
3977
+ index,
3978
+ centred: chosen > 0
3979
+ });
3980
+ });
3981
+ const land = React.useEffectEvent((found) => {
3982
+ setAnswer(found);
3983
+ place(found);
3984
+ });
3985
+ const wantsRecent = recentIds !== void 0 && recentIds.length > 0;
3986
+ React.useEffect(() => {
3987
+ if (source === null || !wantsRecent) return;
3988
+ let current = true;
3989
+ source.search("").then((results) => {
3990
+ if (!current) return;
3991
+ setWholeSet(results);
3992
+ }, () => {});
3993
+ return () => {
3994
+ current = false;
3995
+ };
3996
+ }, [source, wantsRecent]);
3997
+ React.useEffect(() => {
3998
+ if (answer !== null && (placed.current?.answer !== answer || placed.current.wholeSet !== wholeSet)) place(answer);
3999
+ }, [
4000
+ answer,
4001
+ currentSettled,
4002
+ wholeSet
4003
+ ]);
4004
+ const latest = React.useRef(0);
4005
+ React.useEffect(() => {
4006
+ if (source === null) return;
4007
+ const search = ++latest.current;
4008
+ source.search(query).then((results) => {
4009
+ if (search === latest.current) land({
4010
+ status: "found",
4011
+ results,
4012
+ query,
4013
+ attempt
4014
+ });
4015
+ }, () => {
4016
+ if (search === latest.current) land({
4017
+ status: "failed",
4018
+ query,
4019
+ attempt
4020
+ });
4021
+ });
4022
+ }, [
4023
+ source,
4024
+ query,
4025
+ attempt
4026
+ ]);
4027
+ const pending = source !== null && (answer === null || answer.query !== query || answer.attempt !== attempt);
4028
+ return {
4029
+ results: answer?.status === "found" ? answer.results : null,
4030
+ answered: answer?.query.trim() ?? "",
4031
+ failed: answer?.status === "failed",
4032
+ pending,
4033
+ active,
4034
+ setActive,
4035
+ start,
4036
+ retry: () => setAttempt((n) => n + 1),
4037
+ wholeSet
4038
+ };
4039
+ }
4040
+ /**
4041
+ * How results awaiting a newer answer are drawn: kept, and dimmed.
4042
+ *
4043
+ * Kept rather than cleared because most answers land within a frame or two,
4044
+ * and a grid emptied on every keystroke would flash its loading line while
4045
+ * the person types. Dimmed only after a short delay for the same reason, so
4046
+ * a quick answer never visibly dims; a slow one fades the stale icons back
4047
+ * to say they are not what Enter chooses. Brightening again has no delay.
4048
+ */
4049
+ function pendingFade(pending) {
4050
+ return cn("transition-opacity", pending && "opacity-50 delay-150");
4051
+ }
4052
+ /** What stands in the grid while there is nothing to choose from. */
4053
+ function PickerMessage({ results, failed, query, onRetry }) {
4054
+ if (results !== null && results.length > 0) return null;
4055
+ if (results === null && failed) return /* @__PURE__ */ jsxs("div", {
4056
+ className: "flex flex-col items-center gap-2 py-8 text-center text-muted-foreground",
4057
+ children: [
4058
+ /* @__PURE__ */ jsx(TriangleAlert, {
4059
+ className: "size-5",
4060
+ "aria-hidden": "true"
4061
+ }),
4062
+ /* @__PURE__ */ jsx("p", { children: "The icons could not be loaded." }),
4063
+ /* @__PURE__ */ jsx(Button, {
4064
+ type: "button",
4065
+ variant: "outline",
4066
+ size: "sm",
4067
+ onClick: onRetry,
4068
+ children: "Try again"
4069
+ })
4070
+ ]
4071
+ });
4072
+ return /* @__PURE__ */ jsx("p", {
4073
+ className: "py-8 text-center text-muted-foreground",
4074
+ children: results === null ? "Loading icons…" : `No icons match “${query}”.`
4075
+ });
4076
+ }
4077
+ /** One icon in the grid: an option of the listbox. */
4078
+ function IconOption({ icon, id, index, count, isActive, isCurrent, isRecent, onHighlight, onChoose }) {
4079
+ return /* @__PURE__ */ jsx("div", {
4080
+ id,
4081
+ role: "option",
4082
+ "aria-selected": isActive,
4083
+ "aria-setsize": count,
4084
+ "aria-posinset": index + 1,
4085
+ "aria-label": `${iconDisplayName(icon.name)}${isRecent ? ", recent" : ""}${isCurrent ? ", current" : ""}`,
4086
+ "data-current": isCurrent || void 0,
4087
+ onMouseDown: (event) => event.preventDefault(),
4088
+ onMouseMove: () => {
4089
+ if (!isActive) onHighlight(index);
4090
+ },
4091
+ onClick: () => onChoose(icon),
4092
+ className: cn("flex h-[38px] cursor-pointer items-center justify-center rounded-md", isCurrent && !isActive && "bg-muted ring-[1.5px] ring-inset ring-primary", isActive ? "bg-primary text-primary-foreground" : "hover:bg-muted"),
4093
+ children: /* @__PURE__ */ jsx(IconGlyph, {
4094
+ icon,
4095
+ className: "size-5"
4096
+ })
4097
+ });
4098
+ }
4099
+ /** The highlighted icon, large, with its name and the words it is found by. */
4100
+ function HighlightedIcon({ icon, className }) {
4101
+ const words = (icon?.tags ?? []).slice(0, 3).join(", ");
4102
+ return /* @__PURE__ */ jsx("div", {
4103
+ className: cn("flex min-h-[57px] items-center gap-2.5 border-t border-border px-3 py-2", className),
4104
+ children: icon === void 0 ? null : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
4105
+ className: "grid size-9 shrink-0 place-items-center rounded-md bg-muted",
4106
+ children: /* @__PURE__ */ jsx(IconGlyph, {
4107
+ icon,
4108
+ className: "size-[22px]"
4109
+ })
4110
+ }), /* @__PURE__ */ jsxs("span", {
4111
+ className: "min-w-0",
4112
+ children: [/* @__PURE__ */ jsx("span", {
4113
+ className: "block truncate font-semibold",
4114
+ children: iconDisplayName(icon.name)
4115
+ }), /* @__PURE__ */ jsx("span", {
4116
+ className: "block truncate text-xs text-muted-foreground",
4117
+ children: words === "" ? icon.name : `${icon.name} · ${words}`
4118
+ })]
4119
+ })] })
4120
+ });
4121
+ }
4122
+ /**
4123
+ * A search-first icon picker: a search box over a grid of the matching icons,
4124
+ * and the highlighted icon's name and tags beneath.
4125
+ *
4126
+ * The search box keeps focus throughout, as a combobox. The arrow keys move a
4127
+ * highlight through the grid (left and right by one icon, up and down by a
4128
+ * row), Page Up and Page Down by several rows, and Enter chooses the
4129
+ * highlighted icon; the first match is highlighted as soon as results arrive,
4130
+ * so typing and pressing Enter chooses the best match. The grid is a listbox
4131
+ * that renders only the rows in view, which is what keeps a set of nearly two
4132
+ * thousand icons quick to open. How many icons match is announced politely.
4133
+ *
4134
+ * @experimental
4135
+ */
4136
+ function IconPicker({ loadIcons, value, onChoose, recentIcons, className }) {
4137
+ const base = React.useId();
4138
+ const listId = `${base}-icons`;
4139
+ const optionId = (index) => `${base}-icon-${index}`;
4140
+ const [sourceState, retryLoad] = useIconSource(loadIcons, true);
4141
+ const source = sourceState.status === "ready" ? sourceState.source : null;
4142
+ const [query, setQuery] = React.useState("");
4143
+ const scrollRef = React.useRef(null);
4144
+ const inputRef = React.useRef(null);
4145
+ const [current] = useResolvedIcon(sourceState, value);
4146
+ const currentId = current.status === "found" ? current.icon.id : value;
4147
+ const { results, answered, failed: searchFailed, pending, active, setActive, start, retry: retrySearch, wholeSet } = useIconSearch(source, query, currentId, current.status !== "loading", recentIcons);
4148
+ const { options, recentCount } = React.useMemo(() => {
4149
+ const recent = recentAmong(wholeSet, recentIcons);
4150
+ return {
4151
+ options: [...recent, ...results ?? []],
4152
+ recentCount: recent.length
4153
+ };
4154
+ }, [
4155
+ results,
4156
+ wholeSet,
4157
+ recentIcons
4158
+ ]);
4159
+ const count = options.length;
4160
+ const rows = React.useMemo(() => gridRows(recentCount, count, resultsLabel(answered)), [
4161
+ recentCount,
4162
+ count,
4163
+ answered
4164
+ ]);
4165
+ const highlighted = pending ? void 0 : options[active];
4166
+ const trimmed = query.trim();
4167
+ const failed = sourceState.status === "failed" || searchFailed && !pending;
4168
+ const retry = () => {
4169
+ if (sourceState.status === "failed") retryLoad();
4170
+ else retrySearch();
4171
+ inputRef.current?.focus();
4172
+ };
4173
+ const virtualizer = useVirtualizer({
4174
+ count: rows.length,
4175
+ getScrollElement: () => scrollRef.current,
4176
+ estimateSize: (index) => rows[index]?.kind === "heading" ? HEADING_HEIGHT : ROW_HEIGHT$1,
4177
+ overscan: 4
4178
+ });
4179
+ const scrollToStart = React.useEffectEvent((at) => {
4180
+ virtualizer.scrollToIndex(at.centred ? rowOf(rows, at.index) : 0, { align: at.centred ? "center" : "start" });
4181
+ });
4182
+ React.useEffect(() => {
4183
+ if (start !== null) scrollToStart(start);
4184
+ }, [start]);
4185
+ const chooseAnswered = (icon) => {
4186
+ if (!pending) onChoose(icon);
4187
+ };
4188
+ const message = /* @__PURE__ */ jsx(PickerMessage, {
4189
+ results,
4190
+ failed,
4191
+ query: answered,
4192
+ onRetry: retry
4193
+ });
4194
+ const onKeyDown = (event) => {
4195
+ if (pending) {
4196
+ if (event.key === "Enter") event.preventDefault();
4197
+ return;
4198
+ }
4199
+ const next = stepFrom(event.key, active, rows);
4200
+ if (next !== void 0) {
4201
+ event.preventDefault();
4202
+ setActive(next);
4203
+ virtualizer.scrollToIndex(rowOf(rows, next), { align: "auto" });
4204
+ return;
4205
+ }
4206
+ if (event.key === "Enter" && highlighted !== void 0) {
4207
+ event.preventDefault();
4208
+ onChoose(highlighted);
4209
+ }
4210
+ };
4211
+ return /* @__PURE__ */ jsxs("div", {
4212
+ className: cn("flex h-[min(452px,70vh,var(--radix-popover-content-available-height,452px))] flex-col text-sm text-foreground", className),
4213
+ children: [
4214
+ /* @__PURE__ */ jsxs("div", {
4215
+ className: "m-2.5 flex items-center gap-1.5 rounded-md border-[1.5px] border-input px-2 py-1.5 focus-within:border-primary",
4216
+ children: [/* @__PURE__ */ jsx(Search, {
4217
+ className: "size-[15px] shrink-0 text-muted-foreground",
4218
+ "aria-hidden": "true"
4219
+ }), /* @__PURE__ */ jsx("input", {
4220
+ ref: inputRef,
4221
+ type: "text",
4222
+ role: "combobox",
4223
+ "aria-label": "Search icons",
4224
+ "aria-expanded": "true",
4225
+ "aria-controls": listId,
4226
+ "aria-autocomplete": "list",
4227
+ "aria-activedescendant": highlighted === void 0 ? void 0 : optionId(active),
4228
+ autoComplete: "off",
4229
+ spellCheck: false,
4230
+ placeholder: "Search icons",
4231
+ value: query,
4232
+ onChange: (event) => setQuery(event.target.value),
4233
+ onKeyDown,
4234
+ className: "min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
4235
+ })]
4236
+ }),
4237
+ recentCount > 0 ? null : /* @__PURE__ */ jsx("p", {
4238
+ className: HEADING_TEXT,
4239
+ children: resultsLabel(trimmed)
4240
+ }),
4241
+ /* @__PURE__ */ jsxs("div", {
4242
+ ref: scrollRef,
4243
+ className: "min-h-0 flex-1 overflow-y-auto px-2.5",
4244
+ children: [
4245
+ recentCount > 0 ? null : message,
4246
+ /* @__PURE__ */ jsx("div", {
4247
+ id: listId,
4248
+ role: "listbox",
4249
+ "aria-label": "Icons",
4250
+ "aria-busy": pending || void 0,
4251
+ className: cn("relative w-full", pendingFade(pending)),
4252
+ style: { height: virtualizer.getTotalSize() },
4253
+ children: virtualizer.getVirtualItems().map((item) => {
4254
+ const row = rows[item.index];
4255
+ if (row === void 0) return null;
4256
+ if (row.kind === "heading") return /* @__PURE__ */ jsx("p", {
4257
+ "aria-hidden": "true",
4258
+ className: cn(HEADING_TEXT, "absolute inset-x-0 top-0 flex items-end px-0.5"),
4259
+ style: {
4260
+ height: HEADING_HEIGHT,
4261
+ transform: `translateY(${item.start}px)`
4262
+ },
4263
+ children: row.label
4264
+ }, item.key);
4265
+ return /* @__PURE__ */ jsx("div", {
4266
+ role: "presentation",
4267
+ className: "absolute inset-x-0 top-0 grid grid-cols-8 gap-0.5",
4268
+ style: { transform: `translateY(${item.start}px)` },
4269
+ children: options.slice(row.start, row.end).map((icon, column) => {
4270
+ const index = row.start + column;
4271
+ return /* @__PURE__ */ jsx(IconOption, {
4272
+ icon,
4273
+ id: optionId(index),
4274
+ index,
4275
+ count,
4276
+ isActive: index === active,
4277
+ isCurrent: icon.id === currentId,
4278
+ isRecent: index < recentCount,
4279
+ onHighlight: setActive,
4280
+ onChoose: chooseAnswered
4281
+ }, icon.id);
4282
+ })
4283
+ }, item.key);
4284
+ })
4285
+ }),
4286
+ recentCount > 0 ? message : null
4287
+ ]
4288
+ }),
4289
+ /* @__PURE__ */ jsx(HighlightedIcon, {
4290
+ icon: options[active],
4291
+ className: pendingFade(pending)
4292
+ }),
4293
+ /* @__PURE__ */ jsx("p", {
4294
+ role: "status",
4295
+ "aria-live": "polite",
4296
+ className: "sr-only",
4297
+ children: announcementFor(results, failed, answered)
4298
+ })
4299
+ ]
4300
+ });
4301
+ }
4302
+ /** The text the field shows and speaks for a value, however it resolved. */
4303
+ function valueTextFor(value, resolved, source, label) {
4304
+ if (!value) return {
4305
+ name: "Choose an icon",
4306
+ set: "",
4307
+ spoken: `${label}: none chosen`
4308
+ };
4309
+ const parts = partsOf(value);
4310
+ const setName = source !== null && parts.set === source.prefix ? source.label : iconDisplayName(parts.set);
4311
+ if (resolved.status === "missing") return {
4312
+ name: parts.name,
4313
+ set: setName === "" ? "Not found" : `${setName} · not found`,
4314
+ spoken: `${label}: ${parts.name}, not found`
4315
+ };
4316
+ if (resolved.status === "failed") {
4317
+ const name = iconDisplayName(parts.name);
4318
+ return {
4319
+ name,
4320
+ set: setName === "" ? "Could not load" : `${setName} · could not load`,
4321
+ spoken: `${label}: ${name}, could not be loaded`
4322
+ };
4323
+ }
4324
+ const name = iconDisplayName(resolved.status === "found" ? resolved.icon.name : parts.name);
4325
+ return {
4326
+ name,
4327
+ set: setName,
4328
+ spoken: `${label}: ${name}`
4329
+ };
4330
+ }
4331
+ /** The tile the chosen icon is drawn in, or what stands in for it. */
4332
+ function IconSwatch({ resolved }) {
4333
+ return /* @__PURE__ */ jsx("span", {
4334
+ className: cn("grid size-7 shrink-0 place-items-center rounded-[5px]", resolved.status === "found" ? "bg-muted" : "border border-dashed border-muted-foreground", resolved.status === "loading" && "animate-pulse bg-muted motion-reduce:animate-none"),
4335
+ children: resolved.status === "found" ? /* @__PURE__ */ jsx(IconGlyph, {
4336
+ icon: resolved.icon,
4337
+ className: "size-[18px]"
4338
+ }) : resolved.status === "missing" ? /* @__PURE__ */ jsx(CircleHelp, {
4339
+ className: "size-[18px] text-muted-foreground",
4340
+ "aria-hidden": "true"
4341
+ }) : resolved.status === "failed" ? /* @__PURE__ */ jsx(TriangleAlert, {
4342
+ className: "size-[18px] text-muted-foreground",
4343
+ "aria-hidden": "true"
4344
+ }) : null
4345
+ });
4346
+ }
4347
+ /** What the field's button shows: the swatch, the name, the set, a chevron. */
4348
+ function IconFieldFace({ resolved, text, empty }) {
4349
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
4350
+ /* @__PURE__ */ jsx(IconSwatch, { resolved }),
4351
+ /* @__PURE__ */ jsxs("span", {
4352
+ className: "min-w-0 flex-1 leading-tight",
4353
+ children: [/* @__PURE__ */ jsx("span", {
4354
+ className: cn("block text-sm font-medium [overflow-wrap:anywhere]", empty && "font-normal text-muted-foreground"),
4355
+ children: text.name
4356
+ }), text.set === "" ? null : /* @__PURE__ */ jsx("span", {
4357
+ className: "text-[11px] text-muted-foreground",
4358
+ children: text.set
4359
+ })]
4360
+ }),
4361
+ /* @__PURE__ */ jsx(ChevronDown, {
4362
+ className: "size-3.5 shrink-0 text-muted-foreground",
4363
+ "aria-hidden": "true"
4364
+ })
4365
+ ] });
4366
+ }
4367
+ /** The warning under a field whose icon the set no longer draws. */
4368
+ function MissingIconWarning({ shown, id }) {
4369
+ if (!shown) return null;
4370
+ return /* @__PURE__ */ jsxs("p", {
4371
+ id,
4372
+ className: "mt-1.5 flex items-start gap-2 rounded-md border border-warning-200 bg-warning-50 px-2.5 py-1.5 text-xs text-warning-900 dark:border-warning-900 dark:bg-warning-950 dark:text-warning-100",
4373
+ children: [/* @__PURE__ */ jsx(TriangleAlert, {
4374
+ className: "mt-px size-3.5 shrink-0",
4375
+ "aria-hidden": "true"
4376
+ }), /* @__PURE__ */ jsx("span", { children: "This icon is no longer available. Choose another." })]
4377
+ });
4378
+ }
4379
+ /**
4380
+ * The button that opens the picker. Every prop it is not given by name goes
4381
+ * to the `<button>`, so a popover trigger can hand it its ref, state and
4382
+ * handlers.
4383
+ */
4384
+ function IconFieldButton({ resolved, text, empty, interactive, invalid, readOnly, ...button }) {
4385
+ return /* @__PURE__ */ jsx("button", {
4386
+ type: "button",
4387
+ ...button,
4388
+ "aria-label": text.spoken,
4389
+ "aria-invalid": invalid || void 0,
4390
+ "aria-disabled": readOnly || void 0,
4391
+ className: cn("flex min-w-0 flex-1 items-center gap-2 rounded-md px-1.5 py-[5px] text-left", "outline-none focus-visible:ring-2 focus-visible:ring-ring", interactive ? "cursor-pointer hover:bg-muted" : "cursor-default"),
4392
+ children: /* @__PURE__ */ jsx(IconFieldFace, {
4393
+ resolved,
4394
+ text,
4395
+ empty
4396
+ })
4397
+ });
4398
+ }
4399
+ /** The bordered row the field's two buttons sit in. */
4400
+ function IconFieldFrame({ invalid, disabled, children }) {
4401
+ return /* @__PURE__ */ jsx("div", {
4402
+ className: cn("flex w-full items-center rounded-md border border-input bg-background", invalid && "border-destructive", disabled && "opacity-50"),
4403
+ children
4404
+ });
4405
+ }
4406
+ /** A button that clears the field, drawn while there is a value to clear. */
4407
+ function ClearIconButton({ shown, onClear }) {
4408
+ if (!shown) return null;
4409
+ return /* @__PURE__ */ jsx("button", {
4410
+ type: "button",
4411
+ "aria-label": "Clear icon",
4412
+ onClick: onClear,
4413
+ className: "mr-1 grid place-items-center rounded p-[3px] text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
4414
+ children: /* @__PURE__ */ jsx(X, {
4415
+ className: "size-[15px]",
4416
+ "aria-hidden": "true"
4417
+ })
4418
+ });
4419
+ }
4420
+ /**
4421
+ * What a field's value draws as and is called, loading the set when there is
4422
+ * an icon to draw or a picker to fill. Opening the picker asks again for
4423
+ * whichever failed to arrive, the set or the value's icon.
4424
+ */
4425
+ function useIconFieldValue(loadIcons, value, label, open) {
4426
+ const [sourceState, retryLoad] = useIconSource(loadIcons, Boolean(value) || open);
4427
+ const [resolved, retryResolve] = useResolvedIcon(sourceState, value);
4428
+ const source = sourceState.status === "ready" ? sourceState.source : null;
4429
+ const retryFailed = React.useEffectEvent(() => {
4430
+ if (sourceState.status === "failed") retryLoad();
4431
+ else if (resolved.status === "failed") retryResolve();
4432
+ });
4433
+ React.useEffect(() => {
4434
+ if (open) retryFailed();
4435
+ }, [open]);
4436
+ return {
4437
+ resolved,
4438
+ text: valueTextFor(value, resolved, source, label)
4439
+ };
4440
+ }
4441
+ /**
4442
+ * A button the field keeps a handle on and hands to the caller's ref too: the
4443
+ * field takes focus back to it after a clear, and a form focuses it from
4444
+ * outside. One callback ref gives the node to both.
4445
+ */
4446
+ function useSharedButtonRef(ref) {
4447
+ const own = React.useRef(null);
4448
+ return [own, React.useCallback((node) => {
4449
+ own.current = node;
4450
+ if (typeof ref === "function") ref(node);
4451
+ else if (ref) ref.current = node;
4452
+ }, [ref])];
4453
+ }
4454
+ /** The warning's id while the warning is drawn, for the button it describes. */
4455
+ function warningIdIf(missing, id) {
4456
+ return missing ? id : void 0;
4457
+ }
4458
+ /** Joins the ids describing an element, or `undefined` when there are none. */
4459
+ function describedByIds(...ids) {
4460
+ const joined = ids.filter((id) => id !== void 0 && id !== "").join(" ");
4461
+ return joined === "" ? void 0 : joined;
4462
+ }
4463
+ /** The popover the field's picker opens in, beside the field. */
4464
+ function IconFieldPopover({ ref, loadIcons, value, recentIcons, onChoose }) {
4465
+ return /* @__PURE__ */ jsx(PopoverContent, {
4466
+ ref,
4467
+ align: "start",
4468
+ collisionPadding: 8,
4469
+ "aria-label": "Choose an icon",
4470
+ className: "w-[min(360px,calc(100vw-32px))] rounded-[10px] p-0 shadow-lg motion-reduce:animate-none",
4471
+ children: /* @__PURE__ */ jsx(IconPicker, {
4472
+ loadIcons,
4473
+ value,
4474
+ recentIcons,
4475
+ onChoose: (icon) => onChoose(icon.id)
4476
+ })
4477
+ });
4478
+ }
4479
+ /**
4480
+ * Whether the field's picker is open, and a setter that opens it only for a
4481
+ * field that can be changed and reports the field left when it closes.
4482
+ */
4483
+ function useReportedOpen(interactive, onBlur) {
4484
+ const [open, setOpen] = React.useState(false);
4485
+ const setOpenAndReport = (next) => {
4486
+ if (next && !interactive) return;
4487
+ setOpen(next);
4488
+ if (!next) onBlur?.();
4489
+ };
4490
+ return [open, setOpenAndReport];
4491
+ }
4492
+ /**
4493
+ * A blur handler for the field's wrapper that reports the field left when
4494
+ * focus moves from its buttons to somewhere outside the field. The picker sits
4495
+ * in a portal, elsewhere in the document, so it is checked by its own node;
4496
+ * its focus events still bubble to the wrapper through React. Focus never
4497
+ * leaves the open picker without closing it, and the close reports, so
4498
+ * nothing is reported while it is open or for focus leaving it.
4499
+ */
4500
+ function focusLeftReporter(open, pickerRef, onBlur) {
4501
+ return (event) => {
4502
+ const picker = pickerRef.current;
4503
+ if (open || picker?.contains(event.target)) return;
4504
+ const next = event.relatedTarget;
4505
+ if (!(next instanceof Node && (event.currentTarget.contains(next) || picker?.contains(next) === true))) onBlur?.();
4506
+ };
4507
+ }
4508
+ /**
4509
+ * A field holding one icon: a button showing the chosen icon, its name and
4510
+ * its set, which opens an {@link IconPicker}, and a button that clears it.
4511
+ *
4512
+ * An id the source no longer draws is shown by its name with a warning, and
4513
+ * kept until someone chooses another: the field never rewrites a stored value
4514
+ * on its own. Escape closes the picker and returns focus to the button.
4515
+ *
4516
+ * @experimental
4517
+ */
4518
+ function IconField({ value, onChange, loadIcons, label = "Icon", id, disabled = false, readOnly = false, invalid = false, "aria-describedby": describedBy, onBlur, recentIcons, ref, className }) {
4519
+ const interactive = !disabled && !readOnly;
4520
+ const [open, setOpenAndReport] = useReportedOpen(interactive, onBlur);
4521
+ const [triggerRef, setTrigger] = useSharedButtonRef(ref);
4522
+ const warningId = React.useId();
4523
+ const { resolved, text } = useIconFieldValue(loadIcons, value, label, open);
4524
+ const missing = resolved.status === "missing";
4525
+ const pickerRef = React.useRef(null);
4526
+ const reportFocusLeft = focusLeftReporter(open, pickerRef, onBlur);
4527
+ return /* @__PURE__ */ jsxs("div", {
4528
+ className: cn("w-full", className),
4529
+ onBlur: reportFocusLeft,
4530
+ children: [/* @__PURE__ */ jsxs(IconFieldFrame, {
4531
+ invalid,
4532
+ disabled,
4533
+ children: [/* @__PURE__ */ jsxs(Popover, {
4534
+ open,
4535
+ onOpenChange: setOpenAndReport,
4536
+ children: [/* @__PURE__ */ jsx(PopoverTrigger, {
4537
+ asChild: true,
4538
+ children: /* @__PURE__ */ jsx(IconFieldButton, {
4539
+ ref: setTrigger,
4540
+ id,
4541
+ "aria-describedby": describedByIds(describedBy, warningIdIf(missing, warningId)),
4542
+ disabled,
4543
+ resolved,
4544
+ text,
4545
+ empty: !value,
4546
+ interactive,
4547
+ invalid,
4548
+ readOnly
4549
+ })
4550
+ }), /* @__PURE__ */ jsx(IconFieldPopover, {
4551
+ ref: pickerRef,
4552
+ loadIcons,
4553
+ value,
4554
+ recentIcons,
4555
+ onChoose: (id) => {
4556
+ onChange(id);
4557
+ setOpenAndReport(false);
4558
+ }
4559
+ })]
4560
+ }), /* @__PURE__ */ jsx(ClearIconButton, {
4561
+ shown: Boolean(value) && interactive,
4562
+ onClear: () => {
4563
+ onChange(null);
4564
+ onBlur?.();
4565
+ triggerRef.current?.focus();
4566
+ }
4567
+ })]
4568
+ }), /* @__PURE__ */ jsx(MissingIconWarning, {
4569
+ shown: missing,
4570
+ id: warningId
4571
+ })]
4572
+ });
4573
+ }
3615
4574
  // src/components/context-menu.tsx
3616
4575
  /**
3617
4576
  * ContextMenu Component
@@ -3944,7 +4903,17 @@ const ResizableHandle = ({ withGrip, className, children, ...props }) => /* @__P
3944
4903
  * @module
3945
4904
  */
3946
4905
  const ROW_HEIGHT = 28;
3947
- const INDENT_PER_LEVEL = 12;
4906
+ /**
4907
+ * How far each level of the tree is indented, in pixels.
4908
+ *
4909
+ * Exported because a consumer that lets rows be dragged to a depth has to step
4910
+ * by the same distance the rows are drawn at: an editor reading a pointer's x
4911
+ * as a depth draws its drop line where a row at that depth would start, and
4912
+ * two separate numbers would put the line a level away from the hand.
4913
+ *
4914
+ * @experimental
4915
+ */
4916
+ const TREE_INDENT_PX = 20;
3948
4917
  /** The text a row can be typed to, falling back to a string label. */
3949
4918
  function textOf(node) {
3950
4919
  if (typeof node.textValue === "string") return node.textValue;
@@ -4056,6 +5025,22 @@ const TreeView = React.forwardRef(({ nodes, expandedIds, defaultExpandedIds, onE
4056
5025
  estimateSize: () => ROW_HEIGHT,
4057
5026
  overscan: 8
4058
5027
  });
5028
+ const revealed = React.useRef(null);
5029
+ React.useEffect(() => {
5030
+ if (selected === null) {
5031
+ revealed.current = null;
5032
+ return;
5033
+ }
5034
+ if (revealed.current === selected) return;
5035
+ const index = rows.findIndex((row) => row.node.id === selected);
5036
+ if (index < 0) return;
5037
+ revealed.current = selected;
5038
+ virtualizer.scrollToIndex(index, { align: "auto" });
5039
+ }, [
5040
+ selected,
5041
+ rows,
5042
+ virtualizer
5043
+ ]);
4059
5044
  const commitExpanded = (next) => {
4060
5045
  const ids = [...next];
4061
5046
  if (expandedIds === void 0) setExpandedState(ids);
@@ -4217,7 +5202,7 @@ const TreeView = React.forwardRef(({ nodes, expandedIds, defaultExpandedIds, onE
4217
5202
  style: {
4218
5203
  height: item.size,
4219
5204
  transform: `translateY(${item.start}px)`,
4220
- paddingLeft: 4 + row.level * INDENT_PER_LEVEL
5205
+ paddingLeft: 4 + row.level * 20
4221
5206
  },
4222
5207
  children: [
4223
5208
  /* @__PURE__ */ jsx("span", {
@@ -5872,6 +6857,6 @@ const PageHeader = forwardRef(({ title, description, breadcrumbs, actions, class
5872
6857
  })]
5873
6858
  }));
5874
6859
  PageHeader.displayName = "PageHeader";
5875
- export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, Avatar, AvatarFallback, AvatarImage, Badge, Bleed, Button, Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, ColorPicker, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, FieldShell, FormActions, FormLabelWithTooltip, FormSection, Grid, Input, Label, PageHeader, PageShell, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, PortalProvider, Progress, RadioGroup, RadioGroupItem, ResizableHandle, ResizablePanel, ResizablePanelGroup, SHELL_MEASURE, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, ShortcutProvider, ShortcutScope, Skeleton, Slider, Spinner, Stack, Stat, Switch, Table, TableBody, TableCaption, TableCell, TableEmpty, TableError, TableFooter, TableHead, TableHeader, TableLoading, TableRow, TableSearch, TableSkeleton, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Toaster, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TreeView, alertVariants, avatarVariants, badgeVariants, buttonVariants, cardVariants, chordMatches, commandDefaultFilter, createShortcutManager, detectApplePlatform, dialogContentVariants, inputVariants, parseKeys, progressVariants, selectTriggerVariants, sheetVariants, spinnerVariants, toast, useActiveShortcuts, useCommandHighlight, useIsomorphicLayoutEffect, usePortalContainer, useShortcutManager, useShortcuts };
6860
+ export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, Avatar, AvatarFallback, AvatarImage, Badge, Bleed, Button, Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, ColorPicker, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, FieldShell, FormActions, FormLabelWithTooltip, FormSection, Grid, IconField, IconGlyph, IconPicker, Input, Label, PageHeader, PageShell, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, PortalProvider, Progress, RadioGroup, RadioGroupItem, ResizableHandle, ResizablePanel, ResizablePanelGroup, SHELL_MEASURE, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, ShortcutProvider, ShortcutScope, Skeleton, Slider, Spinner, Stack, Stat, Switch, TREE_INDENT_PX, Table, TableBody, TableCaption, TableCell, TableEmpty, TableError, TableFooter, TableHead, TableHeader, TableLoading, TableRow, TableSearch, TableSkeleton, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, Toaster, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TreeView, alertVariants, avatarVariants, badgeVariants, buttonVariants, cardVariants, chordMatches, commandDefaultFilter, createShortcutManager, detectApplePlatform, dialogContentVariants, inputVariants, parseKeys, progressVariants, selectTriggerVariants, sheetVariants, spinnerVariants, toast, useActiveShortcuts, useCommandHighlight, useIsomorphicLayoutEffect, usePortalContainer, useShortcutManager, useShortcuts };
5876
6861
 
5877
6862
  //# sourceMappingURL=index.mjs.map