@cloudwick/astral-ui-cli 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1118,7 +1118,7 @@ async function promptForConfig({
1118
1118
  // package.json
1119
1119
  var package_default = {
1120
1120
  name: "@cloudwick/astral-ui-cli",
1121
- version: "2.2.0",
1121
+ version: "2.3.0",
1122
1122
  description: "CLI for installing Astral UI components in any codebase",
1123
1123
  main: "dist/index.js",
1124
1124
  bin: {
@@ -1774,7 +1774,6 @@ export const checkboxVariants = tv({
1774
1774
  "dependencies": [
1775
1775
  "tailwind-variants",
1776
1776
  "react",
1777
- "react-dom",
1778
1777
  "tailwind-merge"
1779
1778
  ],
1780
1779
  "internalDependencies": [
@@ -2411,7 +2410,7 @@ DropdownItem.displayName = "DropdownItem";
2411
2410
  },
2412
2411
  "multiselecttransfer": {
2413
2412
  "name": "multiSelectTransfer",
2414
- "description": 'The MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based trigger with two ways to pick options: a lightweight **dropdown** for quick selection and a full-screen **transfer-list modal** for managing large or ordered selections across an **Available** and a **Selected** panel. Committed selections render as removable pills in the trigger, collapsing to a "+N More" badge past a configurable limit. It supports both controlled and uncontrolled usage, client- and server-side filtering, infinite scroll, and optional reordering. **When to use:** - Selecting multiple items (permissions, columns, tags, members) from a pool that can be browsed quickly or curated in depth - Form fields where the current selection should stay visible as pills - Workflows that need a "confirm before commit" step (Cancel/Done in the modal) - Large, possibly paginated option sets that benefit from windowing and infinite scroll - Ordered selections where the position of chosen items matters (`reorderable`) **Component Architecture:** - Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts` - Composes the standalone `TransferList` inside a `Modal` for the full-management view - Dropdown and transfer-list panels window (virtualize) large option sets - Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook - Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`) - Client-side filtering via the shared `matchesQuery` util when no filter handler is given - Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList` - Dark-mode aware and RTL-safe (logical spacing properties throughout)',
2413
+ "description": 'The MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based trigger with two ways to pick options: a lightweight **dropdown** for quick selection and a full-screen **transfer-list modal** for managing large or ordered selections across an **Available** and a **Selected** panel. Committed selections render as removable pills in the trigger, collapsing to a "+N More" badge past a configurable limit. It supports both controlled and uncontrolled usage, client- and server-side filtering, infinite scroll, and optional reordering. **When to use:** - Selecting multiple items (permissions, columns, tags, members) from a pool that can be browsed quickly or curated in depth - Form fields where the current selection should stay visible as pills - Workflows that need a "confirm before commit" step (Cancel/Done in the modal) - Large, possibly paginated option sets that benefit from windowing and infinite scroll - Ordered selections where the position of chosen items matters (`reorderable`) **Component Architecture:** - Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts` - Composes the standalone `TransferList` inside a `Modal` for the full-management view - Dropdown and transfer-list panels window (virtualize) large option sets - Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook - Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`) - Both surfaces\' search inputs can be turned off with `searchable={false}`; the dropdown\'s option list then takes focus and owns the keyboard, as each TransferList panel\'s list already does - Client-side filtering via the shared `matchesQuery` util when no filter handler is given - Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList` - Dark-mode aware and RTL-safe (logical spacing properties throughout)',
2415
2414
  "dependencies": [
2416
2415
  "react",
2417
2416
  "tailwind-variants",
@@ -2422,9 +2421,9 @@ DropdownItem.displayName = "DropdownItem";
2422
2421
  "transferList",
2423
2422
  "adpIcon",
2424
2423
  "tooltip",
2424
+ "checkbox",
2425
2425
  "modal",
2426
2426
  "button",
2427
- "checkbox",
2428
2427
  "loader",
2429
2428
  "card"
2430
2429
  ],
@@ -2439,7 +2438,7 @@ DropdownItem.displayName = "DropdownItem";
2439
2438
  },
2440
2439
  {
2441
2440
  "name": "types.ts",
2442
- "content": 'import type { ReactNode } from "react";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport type { ITransferListItem } from "../transferList/types";\n\nexport enum EMultiSelectTransferSizes {\n MD = "md",\n LG = "lg"\n}\n\nexport type TMultiSelectTransferSize = `${EMultiSelectTransferSizes}`;\n\n// Options feed straight into the composed TransferList, so an option IS a transfer-list item.\n// Aliased to ITransferListItem (not redeclared) so the shared shape lives in one place.\nexport type TMultiSelectTransferOption = ITransferListItem;\n\n/**\n * Async option source. Paged: `cursor`, `hasMore` and `total` on the resolved page are all honoured.\n */\nexport type TMultiSelectTransferLoadOptions = TLoadOptions<TMultiSelectTransferOption>;\n\nexport interface IMultiSelectTransferProps {\n /** Unique id for the trigger. A generated id is used when omitted. */\n id?: string;\n /** Custom className for the wrapper. */\n className?: string;\n /** Label displayed above the trigger. */\n label?: ReactNode;\n /** Text shown in the trigger while nothing is selected. @default "Select..." */\n placeholder?: string;\n /** Helper text displayed below the trigger. */\n helperText?: ReactNode;\n /** Display error styling. @default false */\n error?: boolean;\n /** Disable all interaction. @default false */\n disabled?: boolean;\n /** Trigger size variant. @default "md" */\n size?: TMultiSelectTransferSize;\n\n /**\n * Options to choose from; treated as the result for the current query in server mode. Ignored (with\n * a dev warning) when `loadOptions` is set \u2014 pass `initialOptions` to seed the list instead.\n */\n options?: TMultiSelectTransferOption[];\n /** Selected options. Passing this makes the component controlled. */\n value?: TMultiSelectTransferOption[];\n /** Fired with the next selection when the dropdown or modal commits. */\n onChange?: ( selected: TMultiSelectTransferOption[]) => void;\n\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search (dropdown\n * commit/cancel, or opening the transfer list modal).\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, paging, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /** Placeholder for the dropdown filter input and the transfer list modal\'s panel search inputs. @default "Search..." */\n searchPlaceholder?: string;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n\n // Consumer-owned paging, the escape-hatch counterpart to `onFilterChange` above. Both are ignored\n // when `loadOptions` is set, which derives them from the cursor the loader returns.\n /** Whether more options can be loaded; arms the dropdown\'s infinite-scroll sentinel. Ignored when `loadOptions` is set. @default false */\n hasMore?: boolean;\n /** Fired when the infinite-scroll sentinel at the bottom of the option list scrolls into view. Ignored when `loadOptions` is set. */\n onLoadMore?: () => void;\n /** Loader replaces rows on search fetch, appends on load-more. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n\n /** Max pills shown in the trigger before showing "+N More". @default 3 */\n maxVisiblePills?: number;\n\n /** Title rendered in the transfer list modal header. */\n transferListTitle?: ReactNode;\n /** Subtitle rendered under the modal title. */\n transferListSubtitle?: ReactNode;\n /** Fully custom modal header node; overrides title/subtitle when provided. */\n transferListHeader?: ReactNode;\n /** Called when the transfer list CTA is clicked (before the modal opens). */\n onOpenTransferList?: () => void;\n\n /** Enable reordering (drag + arrows) of selected items in the transfer list. */\n reorderable?: boolean;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the transfer list reload icon. */\n isReloading?: boolean;\n /** Tooltip for the transfer list reload button. */\n reloadTooltip?: string;\n /** Custom content rendered under the transfer list available panel search. */\n availablePanelHeaderSlot?: ReactNode;\n /** Custom content rendered under the transfer list selected panel search. */\n selectedPanelHeaderSlot?: ReactNode;\n /** Label for the modal cancel button. @default "Cancel" */\n cancelLabel?: ReactNode;\n /** Label for the modal commit button. @default "Done" */\n doneLabel?: ReactNode;\n\n /**\n * Server-side option source. When provided, the component owns the option list, paging, the request\n * lifecycle and the loading state; `options` / `hasMore` / `onLoadMore` / `isLoading` are ignored and\n * `onFilterChange` becomes notification-only. Responsible for mapping the payload to\n * `TMultiSelectTransferOption` \u2014 envelopes and domain filtering are the consumer\'s business. Options\n * are stored exactly as returned, so extra fields survive. A fresh inline arrow is fine: the loader\n * is read through a ref.\n */\n loadOptions?: TMultiSelectTransferLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame of both surfaces instead of a loader, and stay put while the baseline fetch revalidates over\n * them (the dropdown\'s spinner appends below the rows, as it does for any load in flight). They do not\n * suppress that fetch: pair with `prefetch="never"` if the seed is the whole list until the user types.\n * Seed rows carry no cursor, so nothing pages until a real page lands.\n * A *search* replaces them, since seed rows are not results for a query; clearing it brings them back until\n * a fetched baseline does. Async mode only \u2014 ignored (dev warning) without `loadOptions`, where the rows\n * belong in `options`.\n */\n initialOptions?: readonly TMultiSelectTransferOption[];\n /**\n * When to fetch the unfiltered first page.\n * - `"open"` \u2014 when the dropdown or the transfer-list modal first opens, whichever comes first.\n * - `"mount"` \u2014 at render, so the first open shows rows instead of a loader. The trigger renders its\n * committed chips either way, so this buys latency rather than fixing an empty-looking control.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent pickers. When it changes, cached pages are dropped and the\n * list is repopulated. Compose several parents into one scalar. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in place of the rows when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shown under the loaded rows when a page append rejects; a failed page never blanks the list. @default "Couldn\'t load more." */\n loadMoreErrorMessage?: ReactNode;\n /** Label for the retry button beside `loadMoreErrorMessage`. @default "Retry" */\n retryLabel?: string;\n /** Shows the reload button in async mode, wired to re-run the current query from page one. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders the message and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n'
2441
+ "content": 'import type { ReactNode } from "react";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport type { ITransferListItem } from "../transferList/types";\n\nexport enum EMultiSelectTransferSizes {\n MD = "md",\n LG = "lg"\n}\n\nexport type TMultiSelectTransferSize = `${EMultiSelectTransferSizes}`;\n\n// Options feed straight into the composed TransferList, so an option IS a transfer-list item.\n// Aliased to ITransferListItem (not redeclared) so the shared shape lives in one place.\nexport type TMultiSelectTransferOption = ITransferListItem;\n\n/**\n * Async option source. Paged: `cursor`, `hasMore` and `total` on the resolved page are all honoured.\n */\nexport type TMultiSelectTransferLoadOptions = TLoadOptions<TMultiSelectTransferOption>;\n\nexport interface IMultiSelectTransferProps {\n /** Unique id for the trigger. A generated id is used when omitted. */\n id?: string;\n /** Custom className for the wrapper. */\n className?: string;\n /** Label displayed above the trigger. */\n label?: ReactNode;\n /** Text shown in the trigger while nothing is selected. @default "Select..." */\n placeholder?: string;\n /** Helper text displayed below the trigger. */\n helperText?: ReactNode;\n /** Display error styling. @default false */\n error?: boolean;\n /** Disable all interaction. @default false */\n disabled?: boolean;\n /** Trigger size variant. @default "md" */\n size?: TMultiSelectTransferSize;\n\n /**\n * Options to choose from; treated as the result for the current query in server mode. Ignored (with\n * a dev warning) when `loadOptions` is set \u2014 pass `initialOptions` to seed the list instead.\n */\n options?: TMultiSelectTransferOption[];\n /** Selected options. Passing this makes the component controlled. */\n value?: TMultiSelectTransferOption[];\n /** Fired with the next selection when the dropdown or modal commits. */\n onChange?: ( selected: TMultiSelectTransferOption[]) => void;\n\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search (dropdown\n * commit/cancel, or opening the transfer list modal).\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, paging, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /**\n * Renders the dropdown\'s search input and the transfer list modal\'s two panel search inputs. With\n * `false` the dropdown\'s option list becomes the focused widget on open and owns the keyboard\n * (`role="listbox"` plus `aria-activedescendant`), so Escape, Tab, the arrows, Home/End and Enter\n * behave as they do with the input present, and Space activates the active row. Only the ability to\n * narrow the list is gone, which suits short, fixed option sets. The reload button is unaffected.\n * @default true\n */\n searchable?: boolean;\n /** Placeholder for the dropdown filter input and the transfer list modal\'s panel search inputs. @default "Search..." */\n searchPlaceholder?: string;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n\n // Consumer-owned paging, the escape-hatch counterpart to `onFilterChange` above. Both are ignored\n // when `loadOptions` is set, which derives them from the cursor the loader returns.\n /** Whether more options can be loaded; arms the dropdown\'s infinite-scroll sentinel. Ignored when `loadOptions` is set. @default false */\n hasMore?: boolean;\n /** Fired when the infinite-scroll sentinel at the bottom of the option list scrolls into view. Ignored when `loadOptions` is set. */\n onLoadMore?: () => void;\n /** Loader replaces rows on search fetch, appends on load-more. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n\n /** Max pills shown in the trigger before showing "+N More". @default 3 */\n maxVisiblePills?: number;\n\n /** Title rendered in the transfer list modal header. */\n transferListTitle?: ReactNode;\n /** Subtitle rendered under the modal title. */\n transferListSubtitle?: ReactNode;\n /** Fully custom modal header node; overrides title/subtitle when provided. */\n transferListHeader?: ReactNode;\n /** Called when the transfer list CTA is clicked (before the modal opens). */\n onOpenTransferList?: () => void;\n\n /** Enable reordering (drag + arrows) of selected items in the transfer list. */\n reorderable?: boolean;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the transfer list reload icon. */\n isReloading?: boolean;\n /** Tooltip for the transfer list reload button. */\n reloadTooltip?: string;\n /** Custom content rendered under the transfer list available panel search. */\n availablePanelHeaderSlot?: ReactNode;\n /** Custom content rendered under the transfer list selected panel search. */\n selectedPanelHeaderSlot?: ReactNode;\n /** Label for the modal cancel button. @default "Cancel" */\n cancelLabel?: ReactNode;\n /** Label for the modal commit button. @default "Done" */\n doneLabel?: ReactNode;\n\n /**\n * Server-side option source. When provided, the component owns the option list, paging, the request\n * lifecycle and the loading state; `options` / `hasMore` / `onLoadMore` / `isLoading` are ignored and\n * `onFilterChange` becomes notification-only. Responsible for mapping the payload to\n * `TMultiSelectTransferOption` \u2014 envelopes and domain filtering are the consumer\'s business. Options\n * are stored exactly as returned, so extra fields survive. A fresh inline arrow is fine: the loader\n * is read through a ref.\n */\n loadOptions?: TMultiSelectTransferLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame of both surfaces instead of a loader, and stay put while the baseline fetch revalidates over\n * them (the dropdown\'s spinner appends below the rows, as it does for any load in flight). They do not\n * suppress that fetch: pair with `prefetch="never"` if the seed is the whole list until the user types.\n * Seed rows carry no cursor, so nothing pages until a real page lands.\n * A *search* replaces them, since seed rows are not results for a query; clearing it brings them back until\n * a fetched baseline does. Async mode only \u2014 ignored (dev warning) without `loadOptions`, where the rows\n * belong in `options`.\n */\n initialOptions?: readonly TMultiSelectTransferOption[];\n /**\n * When to fetch the unfiltered first page.\n * - `"open"` \u2014 when the dropdown or the transfer-list modal first opens, whichever comes first.\n * - `"mount"` \u2014 at render, so the first open shows rows instead of a loader. The trigger renders its\n * committed chips either way, so this buys latency rather than fixing an empty-looking control.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent pickers. When it changes, cached pages are dropped and the\n * list is repopulated. Compose several parents into one scalar. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in place of the rows when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shown under the loaded rows when a page append rejects; a failed page never blanks the list. @default "Couldn\'t load more." */\n loadMoreErrorMessage?: ReactNode;\n /** Label for the retry button beside `loadMoreErrorMessage`. @default "Retry" */\n retryLabel?: string;\n /** Shows the reload button in async mode, wired to re-run the current query from page one. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders the message and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n'
2443
2442
  },
2444
2443
  {
2445
2444
  "name": "multiSelectTransferVariants.ts",
@@ -2457,6 +2456,9 @@ export const multiSelectTransferVariants = tv({
2457
2456
  filterInput: "w-full outline-none bg-transparent text-secondary-500 dark:text-secondary-200" +
2458
2457
  " placeholder:text-secondary-200 dark:placeholder:text-secondary-400 rounded border border-secondary-100 dark:border-secondary-500 p-2",
2459
2458
  optionsList: "max-h-60 overflow-y-auto",
2459
+ // The listbox is the focused widget whenever the search input is hidden, so it carries its own
2460
+ // focus ring \u2014 the treatment TransferList's panel listbox already has.
2461
+ optionsListbox: "outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary-400",
2460
2462
  // "No options" when empty and not mid search-fetch.
2461
2463
  noOptionsMessage: "px-4 py-2.5 text-center text-secondary-400 dark:text-secondary-300",
2462
2464
  // Loader row (replaces on search fetch, appends on load-more \u2014 see dropdown).
@@ -2544,11 +2546,16 @@ export const multiSelectTransferVariants = tv({
2544
2546
  checked: {
2545
2547
  true: { optionItem: "bg-frostBlue dark:bg-secondary-700" },
2546
2548
  false: {}
2549
+ },
2550
+ // With the search input hidden only the reload button is left in the header row, at its end.
2551
+ searchable: {
2552
+ false: { dropdownHeader: "justify-end" }
2547
2553
  }
2548
2554
  },
2549
2555
  defaultVariants: {
2550
2556
  error: false,
2551
2557
  size: "md",
2558
+ searchable: true,
2552
2559
  disabled: false,
2553
2560
  checked: false
2554
2561
  }
@@ -2563,6 +2570,10 @@ export const multiSelectTransferVariants = tv({
2563
2570
  "name": "multiSelectTransferPill.tsx",
2564
2571
  "content": 'import * as React from "react";\n\nimport { useIsTruncated } from "@hooks";\nimport { ADPIcon, iconList } from "../adpIcon";\nimport { Tooltip } from "../tooltip";\nimport { type TMultiSelectTransferOption } from "./types";\n\ninterface IMultiSelectTransferPillProps {\n option: TMultiSelectTransferOption;\n /** tv() class for the pill container (doubles as the truncation observer root). */\n pillClass: string;\n /** tv() class for the (truncating) label. */\n pillLabelClass: string;\n /** tv() class for the dismiss button. */\n pillDismissClass: string;\n onRemove: ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => void;\n}\n\n/**\n * A single selected pill in the trigger. Its own component (not inlined in the map) so it can run\n * {@link useIsTruncated} per pill: the full label is surfaced in a Tooltip only when the label is\n * actually clipped, instead of on every pill hover.\n *\n * The Tooltip always wraps the label (gated via its `canOpen` prop) rather than being swapped in\n * and out - that keeps the measured label element mounted so the truncation observer never loses\n * its target. `triggerElementClassName` makes the Tooltip\'s trigger span a shrinkable flex box so\n * the nested label still truncates against the pill\'s max-width. Non-string (ReactNode) labels\n * have no text to show, so they render plainly.\n */\nexport function MultiSelectTransferPill({\n option,\n pillClass,\n pillLabelClass,\n pillDismissClass,\n onRemove\n}: IMultiSelectTransferPillProps ): React.ReactElement {\n const { ref: labelRef, containerRef: pillRef, isTruncated } = useIsTruncated<HTMLSpanElement, HTMLSpanElement>();\n const isStringLabel = typeof option.label === "string";\n\n return (\n <span ref={pillRef} className={pillClass}>\n {isStringLabel ? (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={option.label as string}\n triggerElementClassName="flex min-w-0 max-w-full"\n trigger={\n <span ref={labelRef} className={pillLabelClass}>\n {option.label}\n </span>\n }\n />\n ) : (\n <span className={pillLabelClass}>{option.label}</span>\n )}\n <button\n type="button"\n aria-label={`Remove ${option.value}`}\n className={pillDismissClass}\n onClick={( e ) => onRemove( option, e )}\n >\n <ADPIcon icon={iconList.cross} size="xs" />\n </button>\n </span>\n );\n}\n\nMultiSelectTransferPill.displayName = "MultiSelectTransferPill";\n'
2565
2572
  },
2573
+ {
2574
+ "name": "multiSelectTransferOptionRow.tsx",
2575
+ "content": 'import * as React from "react";\n\nimport { Checkbox } from "../checkbox";\nimport { useIsTruncated } from "@hooks";\n\ninterface IOptionRowProps {\n id: string;\n label: React.ReactNode;\n checked: boolean;\n active: boolean;\n disabled?: boolean;\n onToggle: () => void;\n onActivate: () => void;\n optionItemClass: string | undefined;\n optionLabelWrapClass: string;\n optionLabelClass: string;\n}\n\n/**\n * A single dropdown row (both "Select All" and regular options): checkbox + label. Measures\n * its own label via `useIsTruncated` so the hover/focus expand affordance (see\n * multiSelectTransferVariants\' optionLabel) only ever shows up on rows whose text is actually\n * clipped.\n *\n * Rows are not individually tabbable: focus sits on the single tab stop above them \u2014 the filter input\n * (a combobox) where the search is shown, otherwise the listbox itself \u2014 and keyboard navigation is\n * driven from there by `aria-activedescendant` / arrow keys. `active` marks the row the arrow keys\n * have landed on so it can be highlighted and scrolled into view; the pointer path still toggles on\n * click / activates on hover.\n */\nexport function OptionRow({\n id,\n label,\n checked,\n active,\n disabled,\n onToggle,\n onActivate,\n optionItemClass,\n optionLabelWrapClass,\n optionLabelClass\n}: IOptionRowProps ): React.ReactElement {\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n data-active={active || undefined}\n data-truncated={isLabelTruncated || undefined}\n className={optionItemClass}\n onClick={() => {\n if ( !disabled ) {\n onToggle();\n }\n }}\n onMouseMove={() => {\n if ( !disabled && !active ) {\n onActivate();\n }\n }}\n >\n {/* The row div owns the toggle; the checkbox is presentational (readOnly). */}\n <Checkbox checked={checked} disabled={disabled} readOnly tabIndex={-1} />\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{label}</span>\n </span>\n </div>\n );\n}\n'
2576
+ },
2566
2577
  {
2567
2578
  "name": "multiSelectTransferModal.tsx",
2568
2579
  "content": `import * as React from "react";
@@ -2589,6 +2600,8 @@ interface IMultiSelectTransferModalProps {
2589
2600
  reloadTooltip?: string;
2590
2601
  onReload?: () => void;
2591
2602
  isReloading?: boolean;
2603
+ /** Renders both panels' search inputs; forwarded straight to TransferList. */
2604
+ searchable?: boolean;
2592
2605
  searchPlaceholder?: string;
2593
2606
  availablePanelHeaderSlot?: React.ReactNode;
2594
2607
  selectedPanelHeaderSlot?: React.ReactNode;
@@ -2631,6 +2644,7 @@ export function MultiSelectTransferModal({
2631
2644
  reloadTooltip,
2632
2645
  onReload,
2633
2646
  isReloading,
2647
+ searchable,
2634
2648
  searchPlaceholder,
2635
2649
  availablePanelHeaderSlot,
2636
2650
  selectedPanelHeaderSlot,
@@ -2684,6 +2698,7 @@ export function MultiSelectTransferModal({
2684
2698
  reloadTooltip={reloadTooltip}
2685
2699
  onReload={onReload}
2686
2700
  isReloading={isReloading}
2701
+ searchable={searchable}
2687
2702
  searchPlaceholder={searchPlaceholder}
2688
2703
  availablePanelHeaderSlot={availablePanelHeaderSlot}
2689
2704
  selectedPanelHeaderSlot={selectedPanelHeaderSlot}
@@ -2714,13 +2729,17 @@ export function MultiSelectTransferModal({
2714
2729
  MultiSelectTransferModal.displayName = "MultiSelectTransferModal";
2715
2730
  `
2716
2731
  },
2732
+ {
2733
+ "name": "multiSelectTransferDropdownHeader.tsx",
2734
+ "content": 'import * as React from "react";\n\nimport { ReloadButton } from "../button/reloadButton";\n\ninterface IMultiSelectTransferDropdownHeaderProps {\n /** tv() class for the strip itself, resolved by the dropdown that owns the variant config. */\n headerClass: string;\n /** tv() class for the search input. */\n filterInputClass: string;\n\n /** Renders the search input. With `false` the header holds only the reload affordance. */\n searchable: boolean;\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterKeyUp: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterBlur: ( e: React.FocusEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n /** The listbox this combobox drives, and the row its activedescendant points at. */\n listboxId: string;\n activeDescendant?: string;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The chrome above the dropdown\'s option list: the search input \u2014 a combobox driving the listbox\n * below it through `aria-activedescendant` \u2014 and the optional reload button. With neither on screen\n * it renders nothing, so the rows start at the top of the dropdown rather than under an empty bar.\n */\nexport function MultiSelectTransferDropdownHeader({\n headerClass,\n filterInputClass,\n searchable,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n onFilterKeyUp,\n onFilterBlur,\n searchPlaceholder,\n listboxId,\n activeDescendant,\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownHeaderProps ): React.ReactElement | null {\n if ( !searchable && typeof onReload !== "function" ) {\n return null;\n }\n\n return (\n <div className={headerClass}>\n {searchable && (\n <input\n type="text"\n value={filterQuery}\n onChange={onFilterInput}\n onKeyDown={onFilterKeyDown}\n onKeyUp={onFilterKeyUp}\n onBlur={onFilterBlur}\n placeholder={searchPlaceholder}\n className={filterInputClass}\n role="combobox"\n aria-expanded="true"\n aria-controls={listboxId}\n aria-activedescendant={activeDescendant}\n aria-autocomplete="list"\n aria-label="Search options"\n autoFocus\n />\n )}\n <ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />\n </div>\n );\n}\n\nMultiSelectTransferDropdownHeader.displayName = "MultiSelectTransferDropdownHeader";\n'
2735
+ },
2717
2736
  {
2718
2737
  "name": "multiSelectTransferDropdown.tsx",
2719
- "content": 'import * as React from "react";\nimport { useId, useMemo, useRef } from "react";\nimport { cn } from "tailwind-variants";\n\nimport { Checkbox } from "../checkbox";\nimport { Loader } from "../loader";\nimport { Button } from "../button";\nimport { ReloadButton } from "../button/reloadButton";\n\nimport { useIsTruncated, useListboxKeyboardNav, type TSentinelRef } from "@hooks";\nimport { keyboardKeys } from "@constants";\nimport type { TTransferListValue } from "../transferList/types";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport type { TMultiSelectTransferOption, TMultiSelectTransferSize } from "./types";\n\n// Past this many rows the options list is windowed (virtualized) instead of fully rendered, so a\n// very large option set doesn\'t mount thousands of rows (each with its own ResizeObserver).\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before rows are measured; measureElement corrects it.\nconst ESTIMATED_OPTION_HEIGHT = 40;\n// Keys blocked during search fetch (see handleKeyDown).\nconst navigationKeys = new Set([\n keyboardKeys.arrowDown,\n keyboardKeys.arrowUp,\n keyboardKeys.home,\n keyboardKeys.end,\n keyboardKeys.enter\n]);\n\ninterface IOptionRowProps {\n id: string;\n label: React.ReactNode;\n checked: boolean;\n active: boolean;\n disabled?: boolean;\n onToggle: () => void;\n onActivate: () => void;\n optionItemClass: string | undefined;\n optionLabelWrapClass: string;\n optionLabelClass: string;\n}\n\n/**\n * A single dropdown row (both "Select All" and regular options): checkbox + label. Measures\n * its own label via `useIsTruncated` so the hover/focus expand affordance (see\n * multiSelectTransferVariants\' optionLabel) only ever shows up on rows whose text is actually\n * clipped.\n *\n * Rows are not individually tabbable: focus stays on the filter input (a combobox) and keyboard\n * navigation is driven by `aria-activedescendant` / arrow keys from there. `active` marks the row\n * the arrow keys have landed on so it can be highlighted and scrolled into view; the pointer path\n * still toggles on click / activates on hover.\n */\nfunction OptionRow({\n id,\n label,\n checked,\n active,\n disabled,\n onToggle,\n onActivate,\n optionItemClass,\n optionLabelWrapClass,\n optionLabelClass\n}: IOptionRowProps ): React.ReactElement {\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n\n return (\n <div\n id={id}\n role="option"\n aria-selected={checked}\n aria-disabled={disabled}\n data-active={active || undefined}\n data-truncated={isLabelTruncated || undefined}\n className={optionItemClass}\n onClick={() => {\n if ( !disabled ) {\n onToggle();\n }\n }}\n onMouseMove={() => {\n if ( !disabled && !active ) {\n onActivate();\n }\n }}\n >\n {/* The row div owns the toggle; the checkbox is presentational (readOnly). */}\n <Checkbox checked={checked} disabled={disabled} readOnly tabIndex={-1} />\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{label}</span>\n </span>\n </div>\n );\n}\n\n/** A navigable row in the dropdown: the optional "Select All" pseudo-row or a real option. */\ntype TDropdownRow =\n | { kind: "select-all" }\n | { kind: "option"; option: TMultiSelectTransferOption };\n\ninterface IMultiSelectTransferDropdownProps {\n error?: boolean;\n size: TMultiSelectTransferSize;\n disabled?: boolean;\n\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLInputElement> ) => void;\n onFilterKeyUp: ( e: React.KeyboardEvent<HTMLInputElement> ) => void;\n onFilterBlur: ( e: React.FocusEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n /** Readonly so the option source\'s pool can be passed through without a defensive copy. */\n options: readonly TMultiSelectTransferOption[];\n selectedValues: Set<TTransferListValue>;\n onOptionToggle: ( option: TMultiSelectTransferOption ) => void;\n\n hasSelectAll: boolean;\n areAllSelected: boolean;\n onSelectAll: () => void;\n\n /** Any load in flight; renders the loader row below the list. */\n isLoading?: boolean;\n /**\n * Loader (or error) takes the rows\' place rather than appending below them. Required, and supplied\n * by the option source rather than re-derived here, so the hook is the single source of this\n * predicate \u2014 two components deriving it differently is how they drifted.\n */\n isSearchFetch: boolean;\n sentinelRef: TSentinelRef;\n\n /** Replaces the rows when set: the whole list failed to load. */\n loadError?: React.ReactNode;\n /** Shown below the loaded rows when a page append failed. */\n loadMoreError?: React.ReactNode;\n /** Fired by the retry button beside `loadMoreError`. */\n onRetryLoadMore?: () => void;\n retryLabel?: string;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The open-state dropdown for MultiSelectTransfer: a search input, an optional "Select All"\n * row, the (draft-checked) option list, and the infinite-scroll sentinel.\n */\nexport function MultiSelectTransferDropdown({\n error,\n size,\n disabled,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n onFilterKeyUp,\n onFilterBlur,\n searchPlaceholder,\n options,\n selectedValues,\n onOptionToggle,\n hasSelectAll,\n areAllSelected,\n onSelectAll,\n isLoading,\n isSearchFetch,\n sentinelRef,\n loadError,\n loadMoreError,\n onRetryLoadMore,\n retryLabel = "Retry",\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownProps ): React.ReactElement {\n const {\n dropdownContainer,\n dropdownHeader,\n filterInput,\n optionsList,\n noOptionsMessage,\n loaderRow,\n errorMessage,\n loadMoreErrorRow,\n optionItem,\n optionLabelWrap,\n optionLabel\n } = multiSelectTransferVariants({ error, size, disabled });\n\n const listboxId = useId();\n const listRef = useRef<HTMLDivElement>( null );\n\n // The error occupies the loader\'s slot, so it inherits the same nav-key and activedescendant gate.\n const areRowsReplaced = isSearchFetch === true || loadError !== undefined;\n\n // Flat list of navigable rows in render order: the "Select All" pseudo-row (if shown) followed\n // by the options. Drives arrow-key navigation and aria-activedescendant.\n const rows = useMemo<TDropdownRow[]>(\n () => [\n ...( hasSelectAll ? [{ kind: "select-all" as const }] : []),\n ...options.map(( option ) => ({ kind: "option" as const, option }))\n ],\n [ hasSelectAll, options ]\n );\n\n const isRowDisabled = ( row: TDropdownRow ): boolean =>\n row.kind === "option" && Boolean( row.option.isDisabled );\n\n const rowId = ( index: number ): string => `${listboxId}-row-${index}`;\n\n // A stable key for the current option set, so the active row resets to the first selectable\n // row only when the list actually changes (e.g. after filtering) - not on every re-render,\n // which would fight the user\'s arrow-key position. Memoized so it recomputes only with `rows`.\n const rowsKey = useMemo(\n () => rows.map(( r ) => ( r.kind === "option" ? r.option.value : "select-all" )).join( "\\n" ),\n [rows]\n );\n\n // Windowing kicks in only past the threshold; below it every row renders directly (no\n // virtualization). The virtualizer scroll element is the options list itself (max-h-60 overflow-y-auto).\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: rows.length,\n isItemDisabled: ( index ) => isRowDisabled( rows[index]),\n resetKey: rowsKey,\n scrollElementRef: listRef,\n optionId: rowId,\n estimateSize: ESTIMATED_OPTION_HEIGHT,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const activateRow = ( index: number ) => {\n const row = rows[index];\n if ( !row ) {\n return;\n }\n if ( row.kind === "select-all" ) {\n onSelectAll();\n } else if ( !row.option.isDisabled ) {\n onOptionToggle( row.option );\n }\n };\n\n // Nav keys handled here; Escape/Tab/delete-hold delegated to parent.\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n // Ignore nav keys during search fetch \u2014 stale rows still in memory.\n if ( areRowsReplaced && navigationKeys.has( e.key )) {\n e.preventDefault();\n return;\n }\n switch ( e.key ) {\n case keyboardKeys.arrowDown:\n e.preventDefault();\n moveActive( 1 );\n break;\n case keyboardKeys.arrowUp:\n e.preventDefault();\n moveActive( -1 );\n break;\n case keyboardKeys.home:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case keyboardKeys.end:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( rows.length - 1, -1 ));\n break;\n case keyboardKeys.enter:\n e.preventDefault();\n activateRow( activeIndex );\n break;\n default:\n onFilterKeyDown( e );\n }\n };\n\n // Dropped while the rows are unmounted, so it never points at an id that has left the DOM.\n const activeDescendant =\n !areRowsReplaced && activeIndex >= 0 && rows.length > 0 ? rowId( activeIndex ) : undefined;\n\n const rowKey = ( row: TDropdownRow ): string | number => ( row.kind === "option" ? row.option.value : "select-all" );\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderRow = ( row: TDropdownRow, index: number ): React.ReactElement => {\n const isActive = index === activeIndex;\n const activeClass = isActive && "bg-frostBlue dark:bg-secondary-800";\n if ( row.kind === "select-all" ) {\n return (\n <OptionRow\n key="select-all"\n id={rowId( index )}\n label="Select All"\n checked={areAllSelected}\n active={isActive}\n onToggle={onSelectAll}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn( optionItem({ checked: areAllSelected }), activeClass )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n }\n const opt = row.option;\n const isChecked = selectedValues.has( opt.value );\n return (\n <OptionRow\n key={opt.value}\n id={rowId( index )}\n label={opt.label}\n checked={isChecked}\n active={isActive}\n disabled={opt.isDisabled}\n onToggle={() => onOptionToggle( opt )}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn(\n optionItem({ checked: isChecked }),\n !opt.isDisabled && activeClass,\n opt.isDisabled && "opacity-50 cursor-not-allowed"\n )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n };\n\n // Lazy fn avoids virtualizer/measure work on loader-only renders.\n const renderOptionRows = (): React.ReactNode => ( shouldVirtualize ? (\n <div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={rowKey( rows[virtualRow.index])}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderRow( rows[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n ) : (\n <>\n {rows.map(( row, index ) => renderRow( row, index ))}\n {/* Infinite scroll sentinel */}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </>\n ));\n\n return (\n <div className={dropdownContainer()}>\n <div className={dropdownHeader()}>\n <input\n type="text"\n value={filterQuery}\n onChange={onFilterInput}\n onKeyDown={handleKeyDown}\n onKeyUp={onFilterKeyUp}\n onBlur={onFilterBlur}\n placeholder={searchPlaceholder}\n className={filterInput()}\n role="combobox"\n aria-expanded="true"\n aria-controls={listboxId}\n aria-activedescendant={activeDescendant}\n aria-autocomplete="list"\n aria-label="Search options"\n autoFocus\n />\n\n <ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />\n </div>\n\n {/* Outer scroll: loader/error/empty sit outside listbox (not valid listbox children). */}\n <div ref={listRef} className={optionsList()}>\n <div id={listboxId} role="listbox" aria-multiselectable="true" aria-busy={isLoading}>\n {!areRowsReplaced && options.length > 0 && renderOptionRows()}\n </div>\n {/* role="alert" is assertive: the user\'s action did not do what they asked. */}\n {loadError !== undefined && (\n <div className={errorMessage()} role="alert">{loadError}</div>\n )}\n {!areRowsReplaced && options.length === 0 && (\n <div className={noOptionsMessage()}>No options</div>\n )}\n {/* A failed page append keeps the rows and offers Retry. Only this button retries, so a\n sentinel that never left the viewport cannot hammer a failing endpoint. */}\n {loadMoreError !== undefined && (\n <div className={loadMoreErrorRow()} role="alert">\n <span>{loadMoreError}</span>\n {typeof onRetryLoadMore === "function" && (\n <Button size="xs" variant="outline" color="secondary" onClick={onRetryLoadMore}>\n {retryLabel}\n </Button>\n )}\n </div>\n )}\n {isLoading && (\n <div className={loaderRow()} role="status" aria-label="Loading">\n <Loader size="sm" />\n </div>\n )}\n </div>\n </div>\n );\n}\n\nMultiSelectTransferDropdown.displayName = "MultiSelectTransferDropdown";\n'
2738
+ "content": 'import * as React from "react";\nimport { useEffect, useId, useMemo, useRef } from "react";\nimport { cn } from "tailwind-variants";\n\nimport { Loader } from "../loader";\nimport { Button } from "../button";\n\nimport { useListboxKeyboardNav, type TSentinelRef } from "@hooks";\nimport { keyboardKeys } from "@constants";\nimport type { TTransferListValue } from "../transferList/types";\nimport { MultiSelectTransferDropdownHeader } from "./multiSelectTransferDropdownHeader";\nimport { OptionRow } from "./multiSelectTransferOptionRow";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport type { TMultiSelectTransferOption, TMultiSelectTransferSize } from "./types";\n\n// Past this many rows the options list is windowed (virtualized) instead of fully rendered, so a\n// very large option set doesn\'t mount thousands of rows (each with its own ResizeObserver).\nconst VIRTUALIZE_THRESHOLD = 100;\n// Approximate row height (px) used before rows are measured; measureElement corrects it.\nconst ESTIMATED_OPTION_HEIGHT = 40;\n// Keys blocked during search fetch (see handleKeyDown).\nconst navigationKeys = new Set([\n keyboardKeys.arrowDown,\n keyboardKeys.arrowUp,\n keyboardKeys.home,\n keyboardKeys.end,\n keyboardKeys.enter\n]);\n\n/** A navigable row in the dropdown: the optional "Select All" pseudo-row or a real option. */\ntype TDropdownRow =\n | { kind: "select-all" }\n | { kind: "option"; option: TMultiSelectTransferOption };\n\ninterface IMultiSelectTransferDropdownProps {\n error?: boolean;\n size: TMultiSelectTransferSize;\n disabled?: boolean;\n\n /** Renders the in-dropdown search input. With `false` the option list itself owns focus. */\n searchable: boolean;\n filterQuery: string;\n onFilterInput: ( e: React.ChangeEvent<HTMLInputElement> ) => void;\n onFilterKeyDown: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterKeyUp: ( e: React.KeyboardEvent<HTMLElement> ) => void;\n onFilterBlur: ( e: React.FocusEvent<HTMLInputElement> ) => void;\n searchPlaceholder: string;\n\n /** Readonly so the option source\'s pool can be passed through without a defensive copy. */\n options: readonly TMultiSelectTransferOption[];\n selectedValues: Set<TTransferListValue>;\n onOptionToggle: ( option: TMultiSelectTransferOption ) => void;\n\n hasSelectAll: boolean;\n areAllSelected: boolean;\n onSelectAll: () => void;\n\n /** Any load in flight; renders the loader row below the list. */\n isLoading?: boolean;\n /**\n * Loader (or error) takes the rows\' place rather than appending below them. Required, and supplied\n * by the option source rather than re-derived here, so the hook is the single source of this\n * predicate \u2014 two components deriving it differently is how they drifted.\n */\n isSearchFetch: boolean;\n sentinelRef: TSentinelRef;\n\n /** Replaces the rows when set: the whole list failed to load. */\n loadError?: React.ReactNode;\n /** Shown below the loaded rows when a page append failed. */\n loadMoreError?: React.ReactNode;\n /** Fired by the retry button beside `loadMoreError`. */\n onRetryLoadMore?: () => void;\n retryLabel?: string;\n\n reloadTooltip?: string;\n onReload?: () => void;\n isReloading?: boolean;\n}\n\n/**\n * The open-state dropdown for MultiSelectTransfer: an optional search input, an optional "Select All"\n * row, the (draft-checked) option list, and the infinite-scroll sentinel.\n */\nexport function MultiSelectTransferDropdown({\n error,\n size,\n disabled,\n searchable,\n filterQuery,\n onFilterInput,\n onFilterKeyDown,\n onFilterKeyUp,\n onFilterBlur,\n searchPlaceholder,\n options,\n selectedValues,\n onOptionToggle,\n hasSelectAll,\n areAllSelected,\n onSelectAll,\n isLoading,\n isSearchFetch,\n sentinelRef,\n loadError,\n loadMoreError,\n onRetryLoadMore,\n retryLabel = "Retry",\n reloadTooltip,\n onReload,\n isReloading\n}: IMultiSelectTransferDropdownProps ): React.ReactElement {\n const {\n dropdownContainer,\n optionsList,\n optionsListbox,\n noOptionsMessage,\n loaderRow,\n errorMessage,\n loadMoreErrorRow,\n optionItem,\n optionLabelWrap,\n optionLabel,\n dropdownHeader,\n filterInput\n } = multiSelectTransferVariants({ error, size, disabled, searchable });\n\n const listboxId = useId();\n const listRef = useRef<HTMLDivElement>( null );\n const listboxRef = useRef<HTMLDivElement>( null );\n\n // The error occupies the loader\'s slot, so it inherits the same nav-key and activedescendant gate.\n const areRowsReplaced = isSearchFetch === true || loadError !== undefined;\n\n // Flat list of navigable rows in render order: the "Select All" pseudo-row (if shown) followed\n // by the options. Drives arrow-key navigation and aria-activedescendant.\n const rows = useMemo<TDropdownRow[]>(\n () => [\n ...( hasSelectAll ? [{ kind: "select-all" as const }] : []),\n ...options.map(( option ) => ({ kind: "option" as const, option }))\n ],\n [ hasSelectAll, options ]\n );\n\n const isRowDisabled = ( row: TDropdownRow ): boolean =>\n row.kind === "option" && Boolean( row.option.isDisabled );\n\n const rowId = ( index: number ): string => `${listboxId}-row-${index}`;\n\n // A stable key for the current option set, so the active row resets to the first selectable\n // row only when the list actually changes (e.g. after filtering) - not on every re-render,\n // which would fight the user\'s arrow-key position. Memoized so it recomputes only with `rows`.\n const rowsKey = useMemo(\n () => rows.map(( r ) => ( r.kind === "option" ? r.option.value : "select-all" )).join( "\\n" ),\n [rows]\n );\n\n // Windowing kicks in only past the threshold; below it every row renders directly (no\n // virtualization). The virtualizer scroll element is the options list itself (max-h-60 overflow-y-auto).\n const {\n activeIndex,\n setActiveIndex,\n moveActive,\n firstEnabledIndex,\n virtualizer: rowVirtualizer,\n shouldVirtualize\n } = useListboxKeyboardNav({\n itemCount: rows.length,\n isItemDisabled: ( index ) => isRowDisabled( rows[index]),\n resetKey: rowsKey,\n scrollElementRef: listRef,\n optionId: rowId,\n estimateSize: ESTIMATED_OPTION_HEIGHT,\n virtualizeThreshold: VIRTUALIZE_THRESHOLD\n });\n\n const activateRow = ( index: number ) => {\n const row = rows[index];\n if ( !row ) {\n return;\n }\n if ( row.kind === "select-all" ) {\n onSelectAll();\n } else if ( !row.option.isDisabled ) {\n onOptionToggle( row.option );\n }\n };\n\n // Nav keys handled here; Escape/Tab/delete-hold delegated to parent.\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLElement> ) => {\n // Space activates the active row only while the list owns focus. With the search input present it\n // is a literal character in the query and has to reach the input untouched.\n const isActivateKey = e.key === keyboardKeys.enter || ( !searchable && e.key === keyboardKeys.space );\n // Ignore nav keys during search fetch \u2014 stale rows still in memory.\n if ( areRowsReplaced && ( navigationKeys.has( e.key ) || isActivateKey )) {\n e.preventDefault();\n return;\n }\n if ( isActivateKey ) {\n e.preventDefault();\n activateRow( activeIndex );\n return;\n }\n switch ( e.key ) {\n case keyboardKeys.arrowDown:\n e.preventDefault();\n moveActive( 1 );\n break;\n case keyboardKeys.arrowUp:\n e.preventDefault();\n moveActive( -1 );\n break;\n case keyboardKeys.home:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( 0, 1 ));\n break;\n case keyboardKeys.end:\n e.preventDefault();\n setActiveIndex( firstEnabledIndex( rows.length - 1, -1 ));\n break;\n default:\n onFilterKeyDown( e );\n }\n };\n\n // Dropped while the rows are unmounted, so it never points at an id that has left the DOM.\n const activeDescendant =\n !areRowsReplaced && activeIndex >= 0 && rows.length > 0 ? rowId( activeIndex ) : undefined;\n\n // With no search input to autofocus, the list is what the dropdown opens onto: a keyboard user has\n // to land on something that answers the arrow keys, and the trigger behind the open dropdown answers\n // only Escape. The dropdown mounts on open, so this runs once per open.\n useEffect(() => {\n if ( !searchable ) {\n listboxRef.current?.focus();\n }\n }, [searchable]);\n\n // Everything the search input carries as the focused widget \u2014 the tab stop, the activedescendant\n // cursor and the nav-key handler \u2014 sits on the listbox instead when the input is hidden. The\n // combobox role does not move with them: without a text box there is no combobox, which leaves the\n // focused-listbox shape each TransferList panel already uses. The tab stop stays even with no rows,\n // so Escape is never stranded on an empty or loading list.\n const listboxFocusProps: React.HTMLAttributes<HTMLDivElement> = searchable\n ? {}\n : {\n tabIndex: 0,\n "aria-label": "Options",\n "aria-activedescendant": activeDescendant,\n onKeyDown: handleKeyDown\n };\n\n const rowKey = ( row: TDropdownRow ): string | number => ( row.kind === "option" ? row.option.value : "select-all" );\n\n // Shared row renderer so the windowed and full-render paths produce identical rows.\n const renderRow = ( row: TDropdownRow, index: number ): React.ReactElement => {\n const isActive = index === activeIndex;\n const activeClass = isActive && "bg-frostBlue dark:bg-secondary-800";\n if ( row.kind === "select-all" ) {\n return (\n <OptionRow\n key="select-all"\n id={rowId( index )}\n label="Select All"\n checked={areAllSelected}\n active={isActive}\n onToggle={onSelectAll}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn( optionItem({ checked: areAllSelected }), activeClass )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n }\n const opt = row.option;\n const isChecked = selectedValues.has( opt.value );\n return (\n <OptionRow\n key={opt.value}\n id={rowId( index )}\n label={opt.label}\n checked={isChecked}\n active={isActive}\n disabled={opt.isDisabled}\n onToggle={() => onOptionToggle( opt )}\n onActivate={() => setActiveIndex( index )}\n optionItemClass={cn(\n optionItem({ checked: isChecked }),\n !opt.isDisabled && activeClass,\n opt.isDisabled && "opacity-50 cursor-not-allowed"\n )}\n optionLabelWrapClass={optionLabelWrap()}\n optionLabelClass={optionLabel()}\n />\n );\n };\n\n // Lazy fn avoids virtualizer/measure work on loader-only renders.\n const renderOptionRows = (): React.ReactNode => ( shouldVirtualize ? (\n <div className="relative w-full" style={{ height: rowVirtualizer.getTotalSize() }}>\n {rowVirtualizer.getVirtualItems().map(( virtualRow ) => (\n <div\n key={rowKey( rows[virtualRow.index])}\n data-index={virtualRow.index}\n ref={rowVirtualizer.measureElement}\n className="absolute inset-x-0 top-0"\n style={{ transform: `translateY(${virtualRow.start}px)` }}\n >\n {renderRow( rows[virtualRow.index], virtualRow.index )}\n </div>\n ))}\n {/* Sentinel pinned to the bottom of the full scroll height. */}\n <div ref={sentinelRef} className="absolute bottom-0 h-px w-px" aria-hidden="true" />\n </div>\n ) : (\n <>\n {rows.map(( row, index ) => renderRow( row, index ))}\n {/* Infinite scroll sentinel */}\n <div ref={sentinelRef} className="h-px" aria-hidden="true" />\n </>\n ));\n\n return (\n <div className={dropdownContainer()}>\n <MultiSelectTransferDropdownHeader\n headerClass={dropdownHeader()}\n filterInputClass={filterInput()}\n searchable={searchable}\n filterQuery={filterQuery}\n onFilterInput={onFilterInput}\n onFilterKeyDown={handleKeyDown}\n onFilterKeyUp={onFilterKeyUp}\n onFilterBlur={onFilterBlur}\n searchPlaceholder={searchPlaceholder}\n listboxId={listboxId}\n activeDescendant={activeDescendant}\n reloadTooltip={reloadTooltip}\n onReload={onReload}\n isReloading={isReloading}\n />\n\n {/* Outer scroll: loader/error/empty sit outside listbox (not valid listbox children). */}\n <div ref={listRef} className={optionsList()}>\n <div\n ref={listboxRef}\n id={listboxId}\n role="listbox"\n aria-multiselectable="true"\n aria-busy={isLoading}\n className={optionsListbox()}\n {...listboxFocusProps}\n >\n {!areRowsReplaced && options.length > 0 && renderOptionRows()}\n </div>\n {/* role="alert" is assertive: the user\'s action did not do what they asked. */}\n {loadError !== undefined && (\n <div className={errorMessage()} role="alert">{loadError}</div>\n )}\n {!areRowsReplaced && options.length === 0 && (\n <div className={noOptionsMessage()}>No options</div>\n )}\n {/* A failed page append keeps the rows and offers Retry. Only this button retries, so a\n sentinel that never left the viewport cannot hammer a failing endpoint. */}\n {loadMoreError !== undefined && (\n <div className={loadMoreErrorRow()} role="alert">\n <span>{loadMoreError}</span>\n {typeof onRetryLoadMore === "function" && (\n <Button size="xs" variant="outline" color="secondary" onClick={onRetryLoadMore}>\n {retryLabel}\n </Button>\n )}\n </div>\n )}\n {isLoading && (\n <div className={loaderRow()} role="status" aria-label="Loading">\n <Loader size="sm" />\n </div>\n )}\n </div>\n </div>\n );\n}\n\nMultiSelectTransferDropdown.displayName = "MultiSelectTransferDropdown";\n'
2720
2739
  },
2721
2740
  {
2722
2741
  "name": "multiSelectTransfer.tsx",
2723
- "content": 'import * as React from "react";\nimport { useState, useRef, useEffect, useId, useCallback, useMemo } from "react";\nimport mergeRefs from "react-merge-refs";\n\nimport { keyboardKeys } from "@constants";\nimport { useFilterQuery, useInfiniteScroll, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport { MultiSelectTransferDropdown } from "./multiSelectTransferDropdown";\nimport { MultiSelectTransferTrigger } from "./multiSelectTransferTrigger";\nimport { MultiSelectTransferModal } from "./multiSelectTransferModal";\nimport { useMultiSelectTransferOptionSource } from "./useMultiSelectTransferOptionSource";\nimport { useMultiSelectTransferDraft } from "./useMultiSelectTransferDraft";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport {\n EMultiSelectTransferSizes,\n type TMultiSelectTransferOption,\n type IMultiSelectTransferProps\n} from "./types";\n\n/**\n * A pill trigger over a dropdown option list, with a two-panel transfer-list modal as its second\n * surface. The forwarded ref lands on the wrapper `<div>`.\n */\nexport const MultiSelectTransfer = React.forwardRef<\n HTMLDivElement,\n IMultiSelectTransferProps\n>( function MultiSelectTransfer({\n id,\n className,\n label,\n placeholder = "Select options...",\n helperText,\n error = false,\n disabled = false,\n size = EMultiSelectTransferSizes.MD,\n options,\n value,\n onChange,\n filterValue,\n onFilterChange,\n searchPlaceholder = "Search...",\n filterDebounceMs = 300,\n hasMore = false,\n onLoadMore,\n isLoading = false,\n maxVisiblePills = 3,\n transferListTitle,\n transferListSubtitle,\n transferListHeader,\n onOpenTransferList,\n reorderable = false,\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n availablePanelHeaderSlot,\n selectedPanelHeaderSlot,\n cancelLabel = "Cancel",\n doneLabel = "Done",\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n retryLabel = "Retry",\n showReloadButton = false,\n onLoadError\n}, forwardedRef ) {\n const [ isOpen, setIsOpen ] = useState( false );\n const [ pendingSelected, setPendingSelected ] = useState<TMultiSelectTransferOption[]>([]);\n const [ isModalOpen, setIsModalOpen ] = useState( false );\n\n // Committed selection shown as pills in the trigger. When the consumer passes `value` the\n // component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render without a parent wiring up onChange.\n const isControlled = value !== undefined;\n const [ internalValue, setInternalValue ] = useState<TMultiSelectTransferOption[]>( value ?? []);\n const currentValue = isControlled ? value : internalValue;\n\n const containerRef = useRef<HTMLDivElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the outside-click check tests against it).\n // Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n const triggerRef = useRef<HTMLDivElement>( null );\n const generatedId = useId();\n const triggerId = id ?? generatedId;\n\n // Owns the async/legacy mode decision, the option pool, the paging trio, and the replace-vs-append\n // loader question. Declared before useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useMultiSelectTransferOptionSource({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n showReloadButton,\n onLoadError,\n hasMore,\n onLoadMore,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n const { clearLoadMoreMode, ensureDefaults } = optionSource;\n\n // Filter query (useFilterQuery); resetFilter notifies server-side consumers on clear.\n const {\n filterQuery,\n handleFilterInput: onQueryInput,\n setFilterQuery: setQuery,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter: resetQuery\n } = useFilterQuery({ filterValue, onFilterChange: optionSource.onFilterQueryChange, filterDebounceMs });\n\n const resetFilter = useCallback(() => {\n clearLoadMoreMode();\n resetQuery();\n }, [ clearLoadMoreMode, resetQuery ]);\n\n // Keep the pending (draft) selection in sync when the parent changes `value` while the\n // dropdown is open. Keyed on the values\' contents (not the array reference) so an unrelated\n // parent re-render passing a new array can\'t wipe the user\'s in-progress draft; it fires\n // only on a real external change or when the dropdown (re)opens.\n const valueRef = useRef( currentValue );\n valueRef.current = currentValue;\n const valueKey = useMemo(() => currentValue.map(( o ) => o.value ).join( "\\n" ), [currentValue]);\n useEffect(() => {\n if ( isOpen ) {\n setPendingSelected( valueRef.current );\n }\n }, [ valueKey, isOpen ]);\n\n // Keep the latest draft in a ref so the outside-click listener can commit it without\n // re-subscribing on every toggle.\n const pendingSelectedRef = useRef( pendingSelected );\n pendingSelectedRef.current = pendingSelected;\n\n // Commit the pending (draft) selection and close the dropdown. Used by outside-click and\n // by toggling the trigger closed.\n const commitSelection = useCallback(() => {\n if ( !isControlled ) {\n setInternalValue( pendingSelectedRef.current );\n }\n onChange?.( pendingSelectedRef.current );\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n }, [ onChange, isControlled, resetFilter ]);\n\n // Infinite-scroll sentinel for the dropdown options list (gated on the open state). The in-flight\n // gate is `isLoadingMore`, not the blanket `isLoading`: a search fetch tearing the observer down and\n // re-arming it is a spurious extra page request.\n const sentinelRef = useInfiniteScroll({\n hasMore: optionSource.hasMore,\n isLoading: optionSource.isLoadingMore,\n onLoadMore: optionSource.onLoadMore,\n enabled: isOpen\n });\n\n // Prefetch the baseline on the first OPEN of either surface by default \u2014 the trigger\'s CTA can open\n // the modal without the dropdown ever being opened, and that path needs a populated pool just as\n // much. `prefetch="mount"` instead fills the pool at render, so the first open of either surface\n // shows rows rather than a loader.\n usePrefetchBaseline({ prefetch: prefetch ?? "open", isOpen: isOpen || isModalOpen, optionsKey, ensureDefaults });\n\n // Route an optionsKey CHANGE into the clear path, which drops the search view and lets\n // ensureDefaults lazily repopulate. Skipped on mount so a seeded `filterValue` isn\'t reset on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n // Close dropdown on outside click and commit the pending selection. Disabled while the\n // transfer-list modal is open: the modal renders in a body portal (outside containerRef),\n // so a click inside it would otherwise be treated as an outside click and close the dropdown.\n useEffect(() => {\n const handleOutsideClick = ( e: MouseEvent ) => {\n if ( containerRef.current && !containerRef.current.contains( e.target as Node )) {\n commitSelection();\n }\n };\n if ( isOpen && !isModalOpen ) {\n document.addEventListener( "mousedown", handleOutsideClick );\n }\n return () => document.removeEventListener( "mousedown", handleOutsideClick );\n }, [ isOpen, isModalOpen, commitSelection ]);\n\n // The modal draft is a projection of the loaded pool, so a newly-paged option shows up in Available\n // with no synchronising effect and an item the user already moved is never yanked back. The query is\n // passed only in async mode: there the pool is a server answer the draft\'s snapshot must be matched\n // against, whereas in legacy mode the panel owns its own local search and filters the draft itself.\n const { draftAvailable, draftSelected, onDraftChange, seedDraft } = useMultiSelectTransferDraft(\n optionSource.options,\n isModalOpen,\n optionSource.isAsync ? filterQuery : ""\n );\n\n // Typing ends load-more mode \u2014 the keystroke\'s fetch is a search, so the loader must replace rows.\n const handleFilterInput = useCallback(\n ( e: React.ChangeEvent<HTMLInputElement> ) => {\n clearLoadMoreMode();\n onQueryInput( e );\n },\n [ onQueryInput, clearLoadMoreMode ]\n );\n\n // TransferList reports its panel search as a plain string rather than a change event.\n const handleAvailableSearchChange = useCallback(\n ( query: string ) => {\n clearLoadMoreMode();\n setQuery( query );\n },\n [ setQuery, clearLoadMoreMode ]\n );\n\n const handleTriggerClick = () => {\n if ( disabled ) {\n return;\n }\n if ( isOpen ) {\n commitSelection();\n } else {\n setPendingSelected( currentValue );\n setIsOpen( true );\n }\n };\n\n // Discard the in-progress draft, close the dropdown, and return focus to the trigger so a\n // keyboard user is never stranded on <body>.\n const cancelDropdown = () => {\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n triggerRef.current?.focus();\n };\n\n const handleTriggerKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n // Ignore keys bubbling up from the nested CTA button (Open transfer list); it handles its\n // own activation. Only act when the trigger itself is the focused target.\n if ( e.target !== e.currentTarget ) {\n return;\n }\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n handleTriggerClick();\n }\n if ( e.key === keyboardKeys.escape ) {\n cancelDropdown();\n }\n };\n\n const handleDropdownKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n handleFilterKeyDown( e );\n if ( e.key === keyboardKeys.escape ) {\n e.preventDefault();\n cancelDropdown();\n return;\n }\n // Tab is the keyboard analog of clicking away: commit the draft and let focus move on\n // naturally (no preventDefault). Escape above still cancels/discards.\n if ( e.key === keyboardKeys.tab ) {\n commitSelection();\n }\n };\n\n // When no server-side filter is in play, filter options client-side. Memoized so a stable\n // array identity flows into the (virtualized) dropdown\'s row memo.\n const displayedOptions = useMemo(\n () => ( optionSource.isServerFiltered\n ? optionSource.options\n : optionSource.options.filter(( opt ) => matchesQuery( opt, filterQuery ))),\n [ optionSource.isServerFiltered, optionSource.options, filterQuery ]\n );\n\n // Set of the draft-selected values for O(1) membership checks in the options list and Select All.\n const pendingValues = useMemo(\n () => new Set( pendingSelected.map(( p ) => p.value )),\n [pendingSelected]\n );\n\n const selectableOptions = useMemo(\n () => displayedOptions.filter(( o ) => !o.isDisabled ),\n [displayedOptions]\n );\n const areAllSelected = useMemo(\n () => selectableOptions.length > 0 && selectableOptions.every(( o ) => pendingValues.has( o.value )),\n [ selectableOptions, pendingValues ]\n );\n\n const handleOptionToggle = ( option: TMultiSelectTransferOption ) => {\n setPendingSelected(( prev ) => {\n const exists = prev.some(( o ) => o.value === option.value );\n return exists ? prev.filter(( o ) => o.value !== option.value ) : [ ...prev, option ];\n });\n };\n\n const handleSelectAll = () => {\n setPendingSelected(( prev ) => {\n const prevValues = new Set( prev.map(( p ) => p.value ));\n if ( areAllSelected ) {\n const selectableValues = new Set( selectableOptions.map(( o ) => o.value ));\n return prev.filter(( p ) => !selectableValues.has( p.value ));\n }\n return [ ...prev, ...selectableOptions.filter(( o ) => !prevValues.has( o.value )) ];\n });\n };\n\n const handleRemovePill = ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => {\n e.stopPropagation();\n if ( disabled ) {\n return;\n }\n const next = currentValue.filter(( o ) => o.value !== option.value );\n if ( !isControlled ) {\n setInternalValue( next );\n }\n onChange?.( next );\n };\n\n const handleOpenTransferList = ( e: React.MouseEvent ) => {\n e.stopPropagation();\n // Every other route out of the dropdown commits its draft, and the CTA is no exception: options\n // ticked in the menu carry into the modal instead of being dropped. Available is derived from\n // the pool minus the seed, so only the selection is seeded.\n if ( isOpen ) {\n // Seed from the draft rather than waiting for the committed value to come back round through\n // `value`; commitSelection then closes the dropdown and clears the draft/filter.\n seedDraft( pendingSelectedRef.current );\n commitSelection();\n } else {\n resetFilter();\n seedDraft( currentValue );\n }\n setIsModalOpen( true );\n onOpenTransferList?.();\n };\n\n // Both close paths reset the filter, like every other close in this component: the modal\'s Available\n // panel shares one useFilterQuery instance with the dropdown, so a query left behind here would be\n // the dropdown\'s query the next time it opens.\n const handleTransferDone = () => {\n if ( !isControlled ) {\n setInternalValue( draftSelected );\n }\n onChange?.( draftSelected );\n setIsModalOpen( false );\n resetFilter();\n };\n\n const handleTransferCancel = () => {\n setIsModalOpen( false );\n resetFilter();\n };\n\n const { base, label: labelClass, helperText: helperTextClass } =\n multiSelectTransferVariants({ error, size, disabled });\n\n return (\n <div ref={rootRef} className={base({ class: className })}>\n {label !== undefined && (\n <label htmlFor={triggerId} className={labelClass()}>\n {label}\n </label>\n )}\n\n <div className="relative">\n <MultiSelectTransferTrigger\n id={triggerId}\n ref={triggerRef}\n error={error}\n size={size}\n disabled={disabled}\n isOpen={isOpen}\n value={currentValue}\n placeholder={placeholder}\n maxVisiblePills={maxVisiblePills}\n onClick={handleTriggerClick}\n onKeyDown={handleTriggerKeyDown}\n onRemovePill={handleRemovePill}\n onOpenTransferList={handleOpenTransferList}\n />\n\n {isOpen && (\n <MultiSelectTransferDropdown\n error={error}\n size={size}\n disabled={disabled}\n filterQuery={filterQuery}\n onFilterInput={handleFilterInput}\n onFilterKeyDown={handleDropdownKeyDown}\n onFilterKeyUp={handleFilterKeyUp}\n onFilterBlur={handleFilterBlur}\n searchPlaceholder={searchPlaceholder}\n options={displayedOptions}\n selectedValues={pendingValues}\n onOptionToggle={handleOptionToggle}\n hasSelectAll={selectableOptions.length >= 2}\n areAllSelected={areAllSelected}\n onSelectAll={handleSelectAll}\n isLoading={optionSource.isLoading}\n isSearchFetch={optionSource.isSearchFetch}\n sentinelRef={sentinelRef}\n loadError={optionSource.loadError}\n loadMoreError={optionSource.loadMoreError}\n onRetryLoadMore={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n />\n )}\n </div>\n\n {helperText && <div className={helperTextClass()}>{helperText}</div>}\n\n <MultiSelectTransferModal\n showModal={isModalOpen}\n availableItems={draftAvailable}\n selectedItems={draftSelected}\n onChange={onDraftChange}\n onCancel={handleTransferCancel}\n onDone={handleTransferDone}\n header={transferListHeader}\n title={transferListTitle}\n subtitle={transferListSubtitle}\n reorderable={reorderable}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n searchPlaceholder={searchPlaceholder}\n availablePanelHeaderSlot={availablePanelHeaderSlot}\n selectedPanelHeaderSlot={selectedPanelHeaderSlot}\n hasMoreAvailable={optionSource.hasMore}\n onLoadMoreAvailable={optionSource.onLoadMore}\n // Replace-loader semantics apply only in async mode. In legacy mode, `isLoading` drives an\n // APPEND loader (via `isLoadingMore`) with the rows kept, so this stays undefined.\n isLoadingAvailable={optionSource.isAsync ? optionSource.isSearchFetch : undefined}\n isLoadingMoreAvailable={optionSource.isLoadingMore}\n availableLoadError={optionSource.loadError}\n availableLoadMoreError={optionSource.loadMoreError}\n onRetryLoadMoreAvailable={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n availableTotalCount={optionSource.total}\n {...( optionSource.isAsync\n // Over a paged pool a client-side panel search would only search the pages that happen to be\n // loaded. One query, one useFilterQuery instance: the dropdown is always closed while the\n // modal is open, so the two can never contend. The SELECTED panel\'s search stays local \u2014 it\n // is a plain array and there is no server to ask.\n ? { availableSearchTerm: filterQuery, onAvailableSearchChange: handleAvailableSearchChange }\n : {})}\n cancelLabel={cancelLabel}\n doneLabel={doneLabel}\n />\n </div>\n );\n});\n\nMultiSelectTransfer.displayName = "MultiSelectTransfer";\n'
2742
+ "content": 'import * as React from "react";\nimport { useState, useRef, useEffect, useId, useCallback, useMemo } from "react";\nimport mergeRefs from "react-merge-refs";\n\nimport { keyboardKeys } from "@constants";\nimport { useFilterQuery, useIgnoredPropWarning, useInfiniteScroll, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport { MultiSelectTransferDropdown } from "./multiSelectTransferDropdown";\nimport { MultiSelectTransferTrigger } from "./multiSelectTransferTrigger";\nimport { MultiSelectTransferModal } from "./multiSelectTransferModal";\nimport { useMultiSelectTransferOptionSource } from "./useMultiSelectTransferOptionSource";\nimport { useMultiSelectTransferDraft } from "./useMultiSelectTransferDraft";\nimport { multiSelectTransferVariants } from "./multiSelectTransferVariants";\nimport {\n EMultiSelectTransferSizes,\n type TMultiSelectTransferOption,\n type IMultiSelectTransferProps\n} from "./types";\n\n/**\n * A pill trigger over a dropdown option list, with a two-panel transfer-list modal as its second\n * surface. The forwarded ref lands on the wrapper `<div>`.\n */\nexport const MultiSelectTransfer = React.forwardRef<\n HTMLDivElement,\n IMultiSelectTransferProps\n>( function MultiSelectTransfer({\n id,\n className,\n label,\n placeholder = "Select options...",\n helperText,\n error = false,\n disabled = false,\n size = EMultiSelectTransferSizes.MD,\n options,\n value,\n onChange,\n filterValue,\n onFilterChange,\n searchable = true,\n searchPlaceholder = "Search...",\n filterDebounceMs = 300,\n hasMore = false,\n onLoadMore,\n isLoading = false,\n maxVisiblePills = 3,\n transferListTitle,\n transferListSubtitle,\n transferListHeader,\n onOpenTransferList,\n reorderable = false,\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n availablePanelHeaderSlot,\n selectedPanelHeaderSlot,\n cancelLabel = "Cancel",\n doneLabel = "Done",\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n retryLabel = "Retry",\n showReloadButton = false,\n onLoadError\n}, forwardedRef ) {\n const [ isOpen, setIsOpen ] = useState( false );\n const [ pendingSelected, setPendingSelected ] = useState<TMultiSelectTransferOption[]>([]);\n const [ isModalOpen, setIsModalOpen ] = useState( false );\n\n // Committed selection shown as pills in the trigger. When the consumer passes `value` the\n // component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render without a parent wiring up onChange.\n const isControlled = value !== undefined;\n const [ internalValue, setInternalValue ] = useState<TMultiSelectTransferOption[]>( value ?? []);\n const currentValue = isControlled ? value : internalValue;\n\n const containerRef = useRef<HTMLDivElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the outside-click check tests against it).\n // Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n const triggerRef = useRef<HTMLDivElement>( null );\n const generatedId = useId();\n const triggerId = id ?? generatedId;\n\n // Owns the async/legacy mode decision, the option pool, the paging trio, and the replace-vs-append\n // loader question. Declared before useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useMultiSelectTransferOptionSource({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n loadMoreErrorMessage,\n showReloadButton,\n onLoadError,\n hasMore,\n onLoadMore,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n const { clearLoadMoreMode, ensureDefaults } = optionSource;\n\n // Filter query (useFilterQuery); resetFilter notifies server-side consumers on clear.\n const {\n filterQuery,\n handleFilterInput: onQueryInput,\n setFilterQuery: setQuery,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter: resetQuery\n } = useFilterQuery({ filterValue, onFilterChange: optionSource.onFilterQueryChange, filterDebounceMs });\n\n // With no search input on either surface nothing can produce a query: the debounce never runs and the\n // clear path has nothing to clear, so the handler is dead code at the call site.\n useIgnoredPropWarning(\n !searchable && onFilterChange !== undefined,\n "MultiSelectTransfer: `onFilterChange` is ignored when `searchable={false}` \u2014 there is no search input to produce a query."\n );\n\n const resetFilter = useCallback(() => {\n clearLoadMoreMode();\n resetQuery();\n }, [ clearLoadMoreMode, resetQuery ]);\n\n // Keep the pending (draft) selection in sync when the parent changes `value` while the\n // dropdown is open. Keyed on the values\' contents (not the array reference) so an unrelated\n // parent re-render passing a new array can\'t wipe the user\'s in-progress draft; it fires\n // only on a real external change or when the dropdown (re)opens.\n const valueRef = useRef( currentValue );\n valueRef.current = currentValue;\n const valueKey = useMemo(() => currentValue.map(( o ) => o.value ).join( "\\n" ), [currentValue]);\n useEffect(() => {\n if ( isOpen ) {\n setPendingSelected( valueRef.current );\n }\n }, [ valueKey, isOpen ]);\n\n // Keep the latest draft in a ref so the outside-click listener can commit it without\n // re-subscribing on every toggle.\n const pendingSelectedRef = useRef( pendingSelected );\n pendingSelectedRef.current = pendingSelected;\n\n // Commit the pending (draft) selection and close the dropdown. Used by outside-click and\n // by toggling the trigger closed.\n const commitSelection = useCallback(() => {\n if ( !isControlled ) {\n setInternalValue( pendingSelectedRef.current );\n }\n onChange?.( pendingSelectedRef.current );\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n }, [ onChange, isControlled, resetFilter ]);\n\n // Infinite-scroll sentinel for the dropdown options list (gated on the open state). The in-flight\n // gate is `isLoadingMore`, not the blanket `isLoading`: a search fetch tearing the observer down and\n // re-arming it is a spurious extra page request.\n const sentinelRef = useInfiniteScroll({\n hasMore: optionSource.hasMore,\n isLoading: optionSource.isLoadingMore,\n onLoadMore: optionSource.onLoadMore,\n enabled: isOpen\n });\n\n // Prefetch the baseline on the first OPEN of either surface by default \u2014 the trigger\'s CTA can open\n // the modal without the dropdown ever being opened, and that path needs a populated pool just as\n // much. `prefetch="mount"` instead fills the pool at render, so the first open of either surface\n // shows rows rather than a loader.\n usePrefetchBaseline({ prefetch: prefetch ?? "open", isOpen: isOpen || isModalOpen, optionsKey, ensureDefaults });\n\n // Route an optionsKey CHANGE into the clear path, which drops the search view and lets\n // ensureDefaults lazily repopulate. Skipped on mount so a seeded `filterValue` isn\'t reset on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n // Close dropdown on outside click and commit the pending selection. Disabled while the\n // transfer-list modal is open: the modal renders in a body portal (outside containerRef),\n // so a click inside it would otherwise be treated as an outside click and close the dropdown.\n useEffect(() => {\n const handleOutsideClick = ( e: MouseEvent ) => {\n if ( containerRef.current && !containerRef.current.contains( e.target as Node )) {\n commitSelection();\n }\n };\n if ( isOpen && !isModalOpen ) {\n document.addEventListener( "mousedown", handleOutsideClick );\n }\n return () => document.removeEventListener( "mousedown", handleOutsideClick );\n }, [ isOpen, isModalOpen, commitSelection ]);\n\n // The modal draft is a projection of the loaded pool, so a newly-paged option shows up in Available\n // with no synchronising effect and an item the user already moved is never yanked back. The query is\n // passed only in async mode: there the pool is a server answer the draft\'s snapshot must be matched\n // against, whereas in legacy mode the panel owns its own local search and filters the draft itself.\n const { draftAvailable, draftSelected, onDraftChange, seedDraft } = useMultiSelectTransferDraft(\n optionSource.options,\n isModalOpen,\n optionSource.isAsync ? filterQuery : ""\n );\n\n // Typing ends load-more mode \u2014 the keystroke\'s fetch is a search, so the loader must replace rows.\n const handleFilterInput = useCallback(\n ( e: React.ChangeEvent<HTMLInputElement> ) => {\n clearLoadMoreMode();\n onQueryInput( e );\n },\n [ onQueryInput, clearLoadMoreMode ]\n );\n\n // TransferList reports its panel search as a plain string rather than a change event.\n const handleAvailableSearchChange = useCallback(\n ( query: string ) => {\n clearLoadMoreMode();\n setQuery( query );\n },\n [ setQuery, clearLoadMoreMode ]\n );\n\n const handleTriggerClick = () => {\n if ( disabled ) {\n return;\n }\n if ( isOpen ) {\n commitSelection();\n } else {\n setPendingSelected( currentValue );\n setIsOpen( true );\n }\n };\n\n // Discard the in-progress draft, close the dropdown, and return focus to the trigger so a\n // keyboard user is never stranded on <body>.\n const cancelDropdown = () => {\n setIsOpen( false );\n setPendingSelected([]);\n resetFilter();\n triggerRef.current?.focus();\n };\n\n const handleTriggerKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n // Ignore keys bubbling up from the nested CTA button (Open transfer list); it handles its\n // own activation. Only act when the trigger itself is the focused target.\n if ( e.target !== e.currentTarget ) {\n return;\n }\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n handleTriggerClick();\n }\n if ( e.key === keyboardKeys.escape ) {\n cancelDropdown();\n }\n };\n\n const handleDropdownKeyDown = ( e: React.KeyboardEvent<HTMLElement> ) => {\n handleFilterKeyDown( e );\n if ( e.key === keyboardKeys.escape ) {\n e.preventDefault();\n cancelDropdown();\n return;\n }\n // Tab is the keyboard analog of clicking away: commit the draft and let focus move on\n // naturally (no preventDefault). Escape above still cancels/discards.\n if ( e.key === keyboardKeys.tab ) {\n commitSelection();\n }\n };\n\n // When no server-side filter is in play, filter options client-side. Memoized so a stable\n // array identity flows into the (virtualized) dropdown\'s row memo.\n const displayedOptions = useMemo(\n () => ( optionSource.isServerFiltered\n ? optionSource.options\n : optionSource.options.filter(( opt ) => matchesQuery( opt, filterQuery ))),\n [ optionSource.isServerFiltered, optionSource.options, filterQuery ]\n );\n\n // Set of the draft-selected values for O(1) membership checks in the options list and Select All.\n const pendingValues = useMemo(\n () => new Set( pendingSelected.map(( p ) => p.value )),\n [pendingSelected]\n );\n\n const selectableOptions = useMemo(\n () => displayedOptions.filter(( o ) => !o.isDisabled ),\n [displayedOptions]\n );\n const areAllSelected = useMemo(\n () => selectableOptions.length > 0 && selectableOptions.every(( o ) => pendingValues.has( o.value )),\n [ selectableOptions, pendingValues ]\n );\n\n const handleOptionToggle = ( option: TMultiSelectTransferOption ) => {\n setPendingSelected(( prev ) => {\n const exists = prev.some(( o ) => o.value === option.value );\n return exists ? prev.filter(( o ) => o.value !== option.value ) : [ ...prev, option ];\n });\n };\n\n const handleSelectAll = () => {\n setPendingSelected(( prev ) => {\n const prevValues = new Set( prev.map(( p ) => p.value ));\n if ( areAllSelected ) {\n const selectableValues = new Set( selectableOptions.map(( o ) => o.value ));\n return prev.filter(( p ) => !selectableValues.has( p.value ));\n }\n return [ ...prev, ...selectableOptions.filter(( o ) => !prevValues.has( o.value )) ];\n });\n };\n\n const handleRemovePill = ( option: TMultiSelectTransferOption, e: React.MouseEvent ) => {\n e.stopPropagation();\n if ( disabled ) {\n return;\n }\n const next = currentValue.filter(( o ) => o.value !== option.value );\n if ( !isControlled ) {\n setInternalValue( next );\n }\n onChange?.( next );\n };\n\n const handleOpenTransferList = ( e: React.MouseEvent ) => {\n e.stopPropagation();\n // Every other route out of the dropdown commits its draft, and the CTA is no exception: options\n // ticked in the menu carry into the modal instead of being dropped. Available is derived from\n // the pool minus the seed, so only the selection is seeded.\n if ( isOpen ) {\n // Seed from the draft rather than waiting for the committed value to come back round through\n // `value`; commitSelection then closes the dropdown and clears the draft/filter.\n seedDraft( pendingSelectedRef.current );\n commitSelection();\n } else {\n resetFilter();\n seedDraft( currentValue );\n }\n setIsModalOpen( true );\n onOpenTransferList?.();\n };\n\n // Both close paths reset the filter, like every other close in this component: the modal\'s Available\n // panel shares one useFilterQuery instance with the dropdown, so a query left behind here would be\n // the dropdown\'s query the next time it opens.\n const handleTransferDone = () => {\n if ( !isControlled ) {\n setInternalValue( draftSelected );\n }\n onChange?.( draftSelected );\n setIsModalOpen( false );\n resetFilter();\n };\n\n const handleTransferCancel = () => {\n setIsModalOpen( false );\n resetFilter();\n };\n\n const { base, label: labelClass, helperText: helperTextClass } =\n multiSelectTransferVariants({ error, size, disabled });\n\n return (\n <div ref={rootRef} className={base({ class: className })}>\n {label !== undefined && (\n <label htmlFor={triggerId} className={labelClass()}>\n {label}\n </label>\n )}\n\n <div className="relative">\n <MultiSelectTransferTrigger\n id={triggerId}\n ref={triggerRef}\n error={error}\n size={size}\n disabled={disabled}\n isOpen={isOpen}\n value={currentValue}\n placeholder={placeholder}\n maxVisiblePills={maxVisiblePills}\n onClick={handleTriggerClick}\n onKeyDown={handleTriggerKeyDown}\n onRemovePill={handleRemovePill}\n onOpenTransferList={handleOpenTransferList}\n />\n\n {isOpen && (\n <MultiSelectTransferDropdown\n error={error}\n size={size}\n disabled={disabled}\n searchable={searchable}\n filterQuery={filterQuery}\n onFilterInput={handleFilterInput}\n onFilterKeyDown={handleDropdownKeyDown}\n onFilterKeyUp={handleFilterKeyUp}\n onFilterBlur={handleFilterBlur}\n searchPlaceholder={searchPlaceholder}\n options={displayedOptions}\n selectedValues={pendingValues}\n onOptionToggle={handleOptionToggle}\n hasSelectAll={selectableOptions.length >= 2}\n areAllSelected={areAllSelected}\n onSelectAll={handleSelectAll}\n isLoading={optionSource.isLoading}\n isSearchFetch={optionSource.isSearchFetch}\n sentinelRef={sentinelRef}\n loadError={optionSource.loadError}\n loadMoreError={optionSource.loadMoreError}\n onRetryLoadMore={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n />\n )}\n </div>\n\n {helperText && <div className={helperTextClass()}>{helperText}</div>}\n\n <MultiSelectTransferModal\n showModal={isModalOpen}\n availableItems={draftAvailable}\n selectedItems={draftSelected}\n onChange={onDraftChange}\n onCancel={handleTransferCancel}\n onDone={handleTransferDone}\n header={transferListHeader}\n title={transferListTitle}\n subtitle={transferListSubtitle}\n reorderable={reorderable}\n reloadTooltip={reloadTooltip}\n onReload={optionSource.onReload}\n isReloading={optionSource.isReloading}\n searchable={searchable}\n searchPlaceholder={searchPlaceholder}\n availablePanelHeaderSlot={availablePanelHeaderSlot}\n selectedPanelHeaderSlot={selectedPanelHeaderSlot}\n hasMoreAvailable={optionSource.hasMore}\n onLoadMoreAvailable={optionSource.onLoadMore}\n // Replace-loader semantics apply only in async mode. In legacy mode, `isLoading` drives an\n // APPEND loader (via `isLoadingMore`) with the rows kept, so this stays undefined.\n isLoadingAvailable={optionSource.isAsync ? optionSource.isSearchFetch : undefined}\n isLoadingMoreAvailable={optionSource.isLoadingMore}\n availableLoadError={optionSource.loadError}\n availableLoadMoreError={optionSource.loadMoreError}\n onRetryLoadMoreAvailable={optionSource.onRetryLoadMore}\n retryLabel={retryLabel}\n availableTotalCount={optionSource.total}\n {...( optionSource.isAsync && searchable\n // Over a paged pool a client-side panel search would only search the pages that happen to be\n // loaded. One query, one useFilterQuery instance: the dropdown is always closed while the\n // modal is open, so the two can never contend. The SELECTED panel\'s search stays local \u2014 it\n // is a plain array and there is no server to ask. With the searches hidden there is no query\n // to thread at all.\n ? { availableSearchTerm: filterQuery, onAvailableSearchChange: handleAvailableSearchChange }\n : {})}\n cancelLabel={cancelLabel}\n doneLabel={doneLabel}\n />\n </div>\n );\n});\n\nMultiSelectTransfer.displayName = "MultiSelectTransfer";\n'
2724
2743
  },
2725
2744
  {
2726
2745
  "name": "index.ts",
@@ -2728,7 +2747,7 @@ MultiSelectTransferModal.displayName = "MultiSelectTransferModal";
2728
2747
  },
2729
2748
  {
2730
2749
  "name": "README.md",
2731
- "content": '# MultiSelectTransfer Component\n\n## Component Overview\n\nThe MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based\ntrigger with two ways to pick options: a lightweight **dropdown** for quick selection and\na full-screen **transfer-list modal** for managing large or ordered selections across an\n**Available** and a **Selected** panel. Committed selections render as removable pills in\nthe trigger, collapsing to a "+N More" badge past a configurable limit. It supports both\ncontrolled and uncontrolled usage, client- and server-side filtering, infinite scroll, and\noptional reordering.\n\n**When to use:**\n- Selecting multiple items (permissions, columns, tags, members) from a pool that can be\n browsed quickly or curated in depth\n- Form fields where the current selection should stay visible as pills\n- Workflows that need a "confirm before commit" step (Cancel/Done in the modal)\n- Large, possibly paginated option sets that benefit from windowing and infinite scroll\n- Ordered selections where the position of chosen items matters (`reorderable`)\n\n**Component Architecture:**\n- Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts`\n- Composes the standalone `TransferList` inside a `Modal` for the full-management view\n- Dropdown and transfer-list panels window (virtualize) large option sets\n- Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook\n- Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`)\n- Client-side filtering via the shared `matchesQuery` util when no filter handler is given\n- Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList`\n- Dark-mode aware and RTL-safe (logical spacing properties throughout)\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nexport function Example() {\n const options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" }\n ];\n\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Favorite Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n />\n );\n}\n```\n\n> **Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/multiSelectTransfer` or `@components/multiSelectTransfer`.\n\n## Component Props\n\n`MultiSelectTransfer` is a function component and does **not** forward a ref.\n\n| Prop | Type | Default | Required | Description |\n|---|---|---|---|---|\n| `options` | `TMultiSelectTransferOption[]` | \u2014 | No | Options shown in the dropdown and projected into the transfer-list Available panel. Ignored (dev warning) when `loadOptions` is set. |\n| `value` | `TMultiSelectTransferOption[]` | `undefined` | No | Controlled selection. Omit to run uncontrolled (the component owns selection internally). |\n| `onChange` | `(selected: TMultiSelectTransferOption[]) => void` | \u2014 | No | Fired when a selection is committed (dropdown close, modal Done, or pill removal). |\n| `id` | `string` | auto (`useId`) | No | Id for the trigger, wired to the `label` via `htmlFor`. |\n| `className` | `string` | \u2014 | No | Extra classes on the root container. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | No | Forwarded to the root container \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n| `label` | `ReactNode` | `undefined` | No | Label rendered above the trigger. |\n| `placeholder` | `string` | `"Select options..."` | No | Text shown in the trigger when nothing is selected. |\n| `helperText` | `ReactNode` | `undefined` | No | Helper text rendered below the trigger. |\n| `error` | `boolean` | `false` | No | Apply error styling to the trigger and helper text. |\n| `disabled` | `boolean` | `false` | No | Disable all interaction. |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Control size variant. |\n| `maxVisiblePills` | `number` | `3` | No | Max pills shown in the trigger before collapsing to "+N More". |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown search input and re-syncs it whenever this value changes (not fully controlled \u2014 see Technical Details). |\n| `onFilterChange` | `(query: string) => void` | \u2014 | No | Server-side filter handler. When provided, client-side filtering is skipped. |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the dropdown filter input and the transfer-list modal\'s panel search inputs. |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously. |\n| `hasMore` | `boolean` | `false` | No | Whether more options can be loaded (drives infinite scroll). |\n| `onLoadMore` | `() => void` | \u2014 | No | Called when the infinite-scroll sentinel becomes visible. |\n| `isLoading` | `boolean` | `false` | No | A load is in flight. Replaces the option rows for a search fetch; appends a loader below them for a load-more. |\n| `transferListTitle` | `ReactNode` | `undefined` | No | Title in the transfer-list modal header. |\n| `transferListSubtitle` | `ReactNode` | `undefined` | No | Subtitle under the modal title. |\n| `transferListHeader` | `ReactNode` | `undefined` | No | Fully custom modal header; overrides `transferListTitle`/`transferListSubtitle`. |\n| `onOpenTransferList` | `() => void` | \u2014 | No | Called when the transfer-list CTA is clicked, before the modal opens. |\n| `reorderable` | `boolean` | `false` | No | Enable drag + arrow reordering of the Selected panel in the modal. |\n| `onReload` | `() => void` | \u2014 | No | Shows a reload button (dropdown and modal) and is fired on click. |\n| `isReloading` | `boolean` | `false` | No | Spins the reload icon. |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip for the reload button. |\n| `availablePanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Available panel search. |\n| `selectedPanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Selected panel search. |\n| `cancelLabel` | `ReactNode` | `"Cancel"` | No | Label for the modal cancel button. |\n| `doneLabel` | `ReactNode` | `"Done"` | No | Label for the modal commit button. |\n| `loadOptions` | `(query, meta) => Promise<TMultiSelectTransferOption[] \\| IOptionPage<...>>` | \u2014 | No | Async, paged option source. Switches the component into [async mode](#async-mode-loadoptions). |\n| `initialOptions` | `readonly TMultiSelectTransferOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only. |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered first page. `"open"` when the dropdown \u2014 or the transfer-list modal, whichever comes first \u2014 opens; `"mount"` at render, so the first open shows rows instead of a loader; `"never"` only once the user types. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `loadErrorMessage` | `ReactNode` | `"Couldn\'t load options."` | No | Shown in place of the rows when a load rejects. |\n| `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load more."` | No | Shown under the loaded rows when a page append rejects. |\n| `retryLabel` | `string` | `"Retry"` | No | Label for the retry button beside `loadMoreErrorMessage`. |\n| `showReloadButton` | `boolean` | `false` | No | Shows the reload button in async mode, wired to re-run the current query from page one. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | No | Notified when a load rejects (the component renders the message and swallows it). |\n\n### `TMultiSelectTransferOption`\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `value` | `string \\| number` | Yes | Stable unique identifier for the option. |\n| `label` | `ReactNode` | Yes | Display content for the option, pill, and transfer-list row. |\n| `searchValue` | `string` | No | Plain text used for client-side search matching. Set this when `label` is custom JSX so the option stays findable by its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Prevents the option from being selected or moved; excluded from "Select all". |\n\n## Sizes\n\nTwo sizes are available via the `size` prop:\n\n- **`md`** (default) \u2014 standard density, `text-base` labels; use in typical forms.\n- **`lg`** \u2014 roomier padding and `text-md` labels; use in prominent or touch-oriented UIs.\n\n```tsx\n<MultiSelectTransfer label="Medium" options={options} size="md" />\n<MultiSelectTransfer label="Large" options={options} size="lg" />\n```\n\n## Usage Patterns\n\n### Controlled vs. Uncontrolled\n\n- **Controlled** \u2014 pass `value` and `onChange`. The parent owns the selection; pills reflect\n `value` exactly. Required if you need to read or reset the selection externally.\n- **Uncontrolled** \u2014 omit `value` (optionally still pass `onChange` to observe changes). The\n component tracks the committed selection internally, so pills still render without any\n parent wiring.\n\n### Two ways to select\n\n1. **Dropdown** \u2014 clicking the trigger opens a searchable list with per-option checkboxes and\n a "Select all". Selection is a **draft**: it commits when the dropdown closes (outside\n click, toggling the trigger, the transfer-list CTA, or `Tab`) and discards on `Escape`.\n2. **Transfer-list modal** \u2014 clicking the expand CTA opens a two-panel modal seeded from the\n current selection. Opening it from an open dropdown commits that dropdown\'s draft first, so\n options ticked in the menu arrive on the Selected side rather than being dropped. Moves are a\n **draft** committed on **Done** and discarded on **Cancel**.\n\n### Filtering\n\n- **Client-side (default)** \u2014 options are filtered locally against the query. No handler needed.\n- **Server-side** \u2014 pass `onFilterChange`; the component stops filtering locally and hands you\n the (debounced) query so you can fetch and update `options` yourself. While Backspace/Delete is\n held the debounce waits for keyup (or blur), so a long-press cannot fire a search mid-hold.\n- **Async (`loadOptions`)** \u2014 the component owns the option list, paging, the request lifecycle and\n the loading state. See [Async mode](#async-mode-loadoptions).\n- When the (client- or server-filtered) list has no matches, the dropdown shows a **"No options"**\n notice \u2014 the same copy as `Select`. While a search fetch is in flight (`isLoading`), the loader\n replaces that notice so an empty-and-loading menu never flashes "No options" mid-request.\n- Wherever the component clears the query itself \u2014 committing or cancelling the dropdown, or opening\n the transfer list modal \u2014 `onFilterChange("")` fires too (only if the query was non-empty), so your\n `options` never stay filtered by a query the user can no longer see. On modal open that also means\n the modal\'s Available panel gets the full list back.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above leaves three things at every call site: the results state, a\nmonotonic-ticket guard against out-of-order responses (debouncing limits how often a request *starts*,\nnot how many are in flight), and \u2014 for a paged source \u2014 page accumulation plus the\n"is this loader replacing rows or appending them?" distinction. `loadOptions` moves all of it inside:\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n loadOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return {\n options: res.rows.map((r) => ({ value: r.id, label: r.name })),\n cursor: res.nextToken, // absent/null \u21D2 no further pages\n total: res.totalCount // renders as "(loaded of total)" in the modal panel header\n };\n }}\n/>\n```\n\n`meta` carries `{ signal, cursor, page, reason }`; `reason` is `"defaults" | "search" | "more" | "reload"`.\nReturn a bare array for an unpaged source. Honouring `meta.signal` is optional \u2014 ordering is guaranteed\nby an internal per-slot ticket either way. A fresh inline arrow is fine: the loader is read through a ref.\n\nBehaviour worth knowing:\n\n- **Paging acts on the *active* bucket.** The empty-query baseline and the current search each carry\n their own cursor and page count, so paging a search and paging the baseline never interfere \u2014 and\n clearing the search back to the baseline resumes *its* paging from *its* cursor.\n- **Clearing the search restores the cached baseline with no request.** Pass `refetchOnClear` to also\n revalidate; stale rows stay on screen while it runs.\n- **A failed page keeps the rows** and offers **Retry** below them, and the infinite-scroll sentinel\n disarms until you press it \u2014 a sentinel still sitting in the viewport must not hammer a failing\n endpoint. Retry re-requests the *same* page; the cursor never advanced. A whole-list failure (the\n first page, a search, a reload) shows `loadErrorMessage` in place of the rows instead.\n- **Pages are appended with dedupe on `value`.** Server paging over an unstable sort returns\n duplicates, and both surfaces key their rows by `value`.\n- **The modal\'s Available search is server-side in async mode**, sharing the dropdown\'s single\n debounced query \u2014 over a paged pool, filtering only the pages that happen to be loaded would be a\n lie. Closing the modal (**Done** or **Cancel**) clears that query, so it never leaks into the\n dropdown. The **Selected** panel\'s search is always local: that side is a plain array with no server\n to ask, and there is nothing to page.\n- **The modal\'s Available panel is a projection** of the loaded pool minus the draft selection. A page\n that lands while the modal is open simply appears; an item the user already moved right is never\n yanked back. A committed option the pool never returned is supplied from a snapshot taken at open \u2014\n matched locally against the active query, so it cannot surface as a result for a search it does not\n match.\n\n This replaced an append-only fold effect, and it changes two things on the **non-async path too**\n (see [Migration notes](#migration-notes)).\n- **"Select All"** covers the loaded rows the active search leaves visible \u2014 never every server-side\n match. Toggling it off removes only those visible rows from the draft, so a selection made under an\n earlier query survives. The row is shown only when at least two selectable options are on screen.\n- **`optionsKey` does not clear the committed selection** \u2014 same reasoning as `Select`: that is a\n domain rule, and clearing a controlled `value` from inside means firing an `onChange` nobody asked for.\n- Options are stored exactly as returned, so extra fields you hang on an option survive and reach\n `onChange` as the same object.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame of both surfaces instead of a loader, and stay on\nscreen while the baseline fetch revalidates over them \u2014 the dropdown\'s spinner appends *below* the rows,\nas it does for any load in flight, so the revalidation is visible without hiding anything. This is the\none thing `prefetch` cannot do: `prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n initialOptions={ssrRows} // painted immediately, in the dropdown and the modal\n loadOptions={fetchRows} // still runs, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a\nheavy source you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<MultiSelectTransfer initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty list on both surfaces.\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query; clearing it\nbrings them back until a fetched baseline does. And seed rows only mean something to the async source \u2014\npassing `initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong\nin `options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Migration notes\n\nAdding `loadOptions` is opt-in and every new prop is optional, so no call site has to change. Two\n**runtime** behaviours of the transfer-list modal did change for existing (non-async) consumers,\nbecause the modal\'s Available panel is now derived from `options` rather than folded into owned state:\n\n| Situation | Before | Now |\n|---|---|---|\n| An item is moved back from Selected to Available | It was **appended to the end** of Available | It returns to its position in `options` |\n| The parent **shrinks** `options` while the modal is open | Previously-shown rows **lingered** in Available | They disappear, matching the new `options` |\n\nNeither loses a selection or changes what `onChange` reports \u2014 the committed value is unaffected in\nboth cases. The first is a visible row-ordering difference; the second makes the panel honest about\nwhat the parent is actually offering. If you depended on either, own the pool yourself and drive the\n`TransferList` directly instead of through `MultiSelectTransfer`.\n\nEverything else on the legacy path is unchanged, including the `hasMore` / `onLoadMore` / `isLoading`\ntrio and the append-vs-replace loader behaviour in both the dropdown and the modal.\n\n## Practical Examples\n\n### 1. Controlled selection with a live count\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" },\n { value: "mint", label: "Mint" }\n];\n\nfunction FlavorPicker() {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n helperText={`${selected.length} selected`}\n />\n );\n}\n```\n\n### 2. Validation and error state in a form\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n Button,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction PermissionsField({ options }: { options: TMultiSelectTransferOption[] }) {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [touched, setTouched] = useState(false);\n const hasError = touched && selected.length === 0;\n\n const handleSubmit = () => {\n setTouched(true);\n if (selected.length === 0) return;\n // submit selected...\n };\n\n return (\n <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>\n <MultiSelectTransfer\n label="Permissions"\n placeholder="Assign permissions..."\n options={options}\n value={selected}\n onChange={setSelected}\n error={hasError}\n helperText={hasError ? "Select at least one permission." : undefined}\n />\n <Button type="submit">Save</Button>\n </form>\n );\n}\n```\n\n### 3. Server-side filtering with debounce\n\n```tsx\nimport { useEffect, useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction RemoteUserPicker() {\n const [query, setQuery] = useState("");\n const [options, setOptions] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n fetchUsers(query)\n .then((users) => {\n if (active) setOptions(users.map((u) => ({ value: u.id, label: u.name })));\n })\n .finally(() => active && setIsLoading(false));\n return () => { active = false; };\n }, [query]);\n\n return (\n <MultiSelectTransfer\n label="Assignees"\n placeholder="Select users..."\n options={options}\n value={selected}\n onChange={setSelected}\n onFilterChange={setQuery}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\n### 4. Paginated options with infinite scroll and reload\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst PAGE_SIZE = 20;\n\nfunction PaginatedPicker() {\n const [loaded, setLoaded] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n\n const loadMore = async () => {\n if (isLoading) return;\n setIsLoading(true);\n const page = await fetchPage(loaded.length, PAGE_SIZE);\n setLoaded((prev) => [...prev, ...page.items]);\n setHasMore(page.hasMore);\n setIsLoading(false);\n };\n\n const reload = async () => {\n setIsReloading(true);\n const page = await fetchPage(0, PAGE_SIZE);\n setLoaded(page.items);\n setHasMore(page.hasMore);\n setIsReloading(false);\n };\n\n return (\n <MultiSelectTransfer\n label="Items"\n placeholder="Select items..."\n options={loaded}\n value={selected}\n onChange={setSelected}\n hasMore={hasMore}\n onLoadMore={loadMore}\n isLoading={isLoading}\n onReload={reload}\n isReloading={isReloading}\n />\n );\n}\n```\n\n### 5. Ordered selection via the transfer-list modal\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction ColumnManager({ columns }: { columns: TMultiSelectTransferOption[] }) {\n const [visible, setVisible] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Visible columns"\n placeholder="No columns selected..."\n options={columns}\n value={visible}\n onChange={setVisible}\n reorderable\n maxVisiblePills={2}\n transferListTitle="Manage columns"\n transferListSubtitle="Choose which columns appear and in what order."\n doneLabel="Apply"\n />\n );\n}\n```\n\n## Styling and Customization\n\n- Use `className` to add classes to the root container.\n- The `size` and `error` props cover the common visual states.\n- For deeper theming, import the exported variants and compose them directly:\n\n```tsx\nimport { multiSelectTransferVariants } from "@components/multiSelectTransfer";\n\nconst { trigger, pill } = multiSelectTransferVariants({ size: "lg", error: false });\n```\n\nDark mode follows the library convention (a `.dark` class on a root ancestor); all slots\nship dark-mode styles. Spacing uses logical properties (`ps-`, `pe-`, `ms-`, `me-`) so the\ncontrol mirrors correctly in RTL layouts.\n\n## Technical Details\n\n- **State management:** The trigger shows a **committed** selection while the dropdown and\n modal each maintain their own **draft**. Drafts commit on close/Done and discard on\n Escape/Cancel, giving a clear "confirm before apply" model. In uncontrolled mode the\n committed value is held internally; in controlled mode it tracks `value`.\n- **Draft preservation:** The dropdown draft is keyed on the option values\' contents, not the\n array reference, so an unrelated parent re-render that passes a new `value` array cannot wipe\n an in-progress draft \u2014 it re-syncs only on a genuine external change or on (re)open.\n- **Filtering:** Without `onFilterChange`, options are filtered client-side via `matchesQuery`\n and memoized for stable identity. `matchesQuery` matches an option\'s `searchValue` first, then a\n string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom JSX so\n they stay findable by their visible text. With `onFilterChange`, filtering is delegated to the parent\n and the query is debounced (`filterDebounceMs`); a pending debounce is cancelled on unmount, on an\n external `filterValue` reset, and whenever the component clears the query itself \u2014 where\n `onFilterChange("")` fires immediately instead, so a stale query can never overtake the reset.\n While Backspace/Delete is held the debounce is deferred until keyup (or blur), so a long-press\n cannot fire mid-hold. `filterValue` is a seed plus an external sync rather than a fully controlled\n value: the input owns its own text, a *new* `filterValue` overwrites it, and re-passing the same\n one does not pull it back \u2014 feed `onFilterChange` into the state you pass as `filterValue` to keep\n them in step. All of that lives in the shared `useFilterQuery` hook, which `Select` also uses, so\n the identically-named props on both components behave identically by construction.\n- **Virtualization:** Both the dropdown options list and the modal panels window large option\n sets (past ~100 items) so multi-thousand-item lists open and filter without mounting every row.\n- **Infinite scroll:** An `IntersectionObserver` sentinel (via `useInfiniteScroll`) calls\n `onLoadMore` when scrolled into view, gated on the open state. While the modal is open, newly\n loaded options are folded into the Available draft without duplicating or reclaiming items the\n user has already moved to Selected.\n- **Loading UI:** `isLoading` covers two situations with opposite needs, and the component tells them\n apart by whether the sentinel above asked for the load. A **search fetch** replaces the option rows\n with the loader \u2014 they belong to the previous query, so leaving them clickable would let the user\n pick an option the incoming results no longer contain (`Select` does the same). An empty-and-loading\n menu therefore shows the loader alone rather than "No options". Arrow/Enter are ignored while those\n rows are gone, so the keyboard cannot reach one either, and the listbox is marked `aria-busy`. A\n **load-more** is adding to those rows, so the loader is appended below them and the scroll position\n survives \u2014 a load-more stays a load-more until it finishes, even if the consumer flips `isLoading`\n a render or two after `onLoadMore`.\n- **Modal portal:** The transfer-list modal renders in a body portal. The dropdown\'s\n outside-click listener is suspended while the modal is open so a click inside the portal is not\n misread as an outside click.\n- **Pill overflow:** The trigger shows up to `maxVisiblePills` pills, then a "+N More" badge.\n Long pill labels truncate to a max width and surface the full text via a `Tooltip` only when\n actually clipped.\n\n## Accessibility\n\n**Implemented:**\n- The trigger is a keyboard-operable control: `role="button"`, `aria-haspopup="listbox"`, and\n `aria-expanded` reflecting the open state.\n- The trigger is focusable (`tabIndex={0}`) when enabled and removed from the tab order\n (`tabIndex={-1}`) when `disabled`.\n- Keyboard support on the trigger: `Enter`/`Space` toggle the dropdown; `Escape` closes and\n discards the draft.\n- Keyboard support in the dropdown: `Escape` cancels/discards and returns focus to the trigger\n so a keyboard user is never stranded on `<body>`; `Tab` commits the draft and lets focus move\n on naturally.\n- The `label` is associated with the trigger via `htmlFor`/`id` (auto-generated when `id` is\n omitted).\n- The transfer-list CTA and reload buttons carry descriptive `aria-label`/tooltip text.\n- Disabled options are excluded from selection and from "Select all".\n\n**Best Practices:**\n- Always provide a `label` (or an external `aria-label`) so the control is announced.\n- Use `error` together with `helperText` to communicate validation state visibly rather than by\n color alone.\n- Keep option `label`s meaningful as text \u2014 pills, tooltips, and screen readers all render them.\n- Provide stable, unique `value`s; reusing a value across options breaks selection tracking and\n keys.\n- When filtering server-side, keep `isLoading` accurate so assistive tech and users get correct\n loading feedback.\n'
2750
+ "content": '# MultiSelectTransfer Component\n\n## Component Overview\n\nThe MultiSelectTransfer is a multi-select form control that pairs a compact, pill-based\ntrigger with two ways to pick options: a lightweight **dropdown** for quick selection and\na full-screen **transfer-list modal** for managing large or ordered selections across an\n**Available** and a **Selected** panel. Committed selections render as removable pills in\nthe trigger, collapsing to a "+N More" badge past a configurable limit. It supports both\ncontrolled and uncontrolled usage, client- and server-side filtering, infinite scroll, and\noptional reordering.\n\n**When to use:**\n- Selecting multiple items (permissions, columns, tags, members) from a pool that can be\n browsed quickly or curated in depth\n- Form fields where the current selection should stay visible as pills\n- Workflows that need a "confirm before commit" step (Cancel/Done in the modal)\n- Large, possibly paginated option sets that benefit from windowing and infinite scroll\n- Ordered selections where the position of chosen items matters (`reorderable`)\n\n**Component Architecture:**\n- Styled with `tailwind-variants` (`tv()`) slots \u2014 see `multiSelectTransferVariants.ts`\n- Composes the standalone `TransferList` inside a `Modal` for the full-management view\n- Dropdown and transfer-list panels window (virtualize) large option sets\n- Infinite scroll via the shared `useInfiniteScroll` (`IntersectionObserver`) hook\n- Debounced server-side filtering via the shared `useFilterQuery` hook (also used by `Select`)\n- Both surfaces\' search inputs can be turned off with `searchable={false}`; the dropdown\'s option list\n then takes focus and owns the keyboard, as each TransferList panel\'s list already does\n- Client-side filtering via the shared `matchesQuery` util when no filter handler is given\n- Reuses `ADPIcon`, `Tooltip` (for clipped pill labels), and `TransferList`\n- Dark-mode aware and RTL-safe (logical spacing properties throughout)\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nexport function Example() {\n const options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" }\n ];\n\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Favorite Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n />\n );\n}\n```\n\n> **Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/multiSelectTransfer` or `@components/multiSelectTransfer`.\n\n## Component Props\n\n`MultiSelectTransfer` is a function component and does **not** forward a ref.\n\n| Prop | Type | Default | Required | Description |\n|---|---|---|---|---|\n| `options` | `TMultiSelectTransferOption[]` | \u2014 | No | Options shown in the dropdown and projected into the transfer-list Available panel. Ignored (dev warning) when `loadOptions` is set. |\n| `value` | `TMultiSelectTransferOption[]` | `undefined` | No | Controlled selection. Omit to run uncontrolled (the component owns selection internally). |\n| `onChange` | `(selected: TMultiSelectTransferOption[]) => void` | \u2014 | No | Fired when a selection is committed (dropdown close, modal Done, or pill removal). |\n| `id` | `string` | auto (`useId`) | No | Id for the trigger, wired to the `label` via `htmlFor`. |\n| `className` | `string` | \u2014 | No | Extra classes on the root container. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | No | Forwarded to the root container \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n| `label` | `ReactNode` | `undefined` | No | Label rendered above the trigger. |\n| `placeholder` | `string` | `"Select options..."` | No | Text shown in the trigger when nothing is selected. |\n| `helperText` | `ReactNode` | `undefined` | No | Helper text rendered below the trigger. |\n| `error` | `boolean` | `false` | No | Apply error styling to the trigger and helper text. |\n| `disabled` | `boolean` | `false` | No | Disable all interaction. |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Control size variant. |\n| `maxVisiblePills` | `number` | `3` | No | Max pills shown in the trigger before collapsing to "+N More". |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown search input and re-syncs it whenever this value changes (not fully controlled \u2014 see Technical Details). |\n| `onFilterChange` | `(query: string) => void` | \u2014 | No | Server-side filter handler. When provided, client-side filtering is skipped. |\n| `searchable` | `boolean` | `true` | No | Renders the dropdown\'s search input and the modal\'s two panel searches. With `false` the dropdown\'s option list takes focus on open and owns the keyboard (`role="listbox"` plus `aria-activedescendant`, no combobox); the reload button, "Select all", paging and Escape/Tab are unaffected, and `onFilterChange` is ignored (dev warning). |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the dropdown filter input and the transfer-list modal\'s panel search inputs. Ignored when `searchable={false}`. |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously. |\n| `hasMore` | `boolean` | `false` | No | Whether more options can be loaded (drives infinite scroll). |\n| `onLoadMore` | `() => void` | \u2014 | No | Called when the infinite-scroll sentinel becomes visible. |\n| `isLoading` | `boolean` | `false` | No | A load is in flight. Replaces the option rows for a search fetch; appends a loader below them for a load-more. |\n| `transferListTitle` | `ReactNode` | `undefined` | No | Title in the transfer-list modal header. |\n| `transferListSubtitle` | `ReactNode` | `undefined` | No | Subtitle under the modal title. |\n| `transferListHeader` | `ReactNode` | `undefined` | No | Fully custom modal header; overrides `transferListTitle`/`transferListSubtitle`. |\n| `onOpenTransferList` | `() => void` | \u2014 | No | Called when the transfer-list CTA is clicked, before the modal opens. |\n| `reorderable` | `boolean` | `false` | No | Enable drag + arrow reordering of the Selected panel in the modal. |\n| `onReload` | `() => void` | \u2014 | No | Shows a reload button (dropdown and modal) and is fired on click. |\n| `isReloading` | `boolean` | `false` | No | Spins the reload icon. |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip for the reload button. |\n| `availablePanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Available panel search. |\n| `selectedPanelHeaderSlot` | `ReactNode` | `undefined` | No | Custom content under the modal Selected panel search. |\n| `cancelLabel` | `ReactNode` | `"Cancel"` | No | Label for the modal cancel button. |\n| `doneLabel` | `ReactNode` | `"Done"` | No | Label for the modal commit button. |\n| `loadOptions` | `(query, meta) => Promise<TMultiSelectTransferOption[] \\| IOptionPage<...>>` | \u2014 | No | Async, paged option source. Switches the component into [async mode](#async-mode-loadoptions). |\n| `initialOptions` | `readonly TMultiSelectTransferOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only. |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered first page. `"open"` when the dropdown \u2014 or the transfer-list modal, whichever comes first \u2014 opens; `"mount"` at render, so the first open shows rows instead of a loader; `"never"` only once the user types. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `loadErrorMessage` | `ReactNode` | `"Couldn\'t load options."` | No | Shown in place of the rows when a load rejects. |\n| `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load more."` | No | Shown under the loaded rows when a page append rejects. |\n| `retryLabel` | `string` | `"Retry"` | No | Label for the retry button beside `loadMoreErrorMessage`. |\n| `showReloadButton` | `boolean` | `false` | No | Shows the reload button in async mode, wired to re-run the current query from page one. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | No | Notified when a load rejects (the component renders the message and swallows it). |\n\n### `TMultiSelectTransferOption`\n\n| Field | Type | Required | Description |\n|---|---|---|---|\n| `value` | `string \\| number` | Yes | Stable unique identifier for the option. |\n| `label` | `ReactNode` | Yes | Display content for the option, pill, and transfer-list row. |\n| `searchValue` | `string` | No | Plain text used for client-side search matching. Set this when `label` is custom JSX so the option stays findable by its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Prevents the option from being selected or moved; excluded from "Select all". |\n\n## Sizes\n\nTwo sizes are available via the `size` prop:\n\n- **`md`** (default) \u2014 standard density, `text-base` labels; use in typical forms.\n- **`lg`** \u2014 roomier padding and `text-md` labels; use in prominent or touch-oriented UIs.\n\n```tsx\n<MultiSelectTransfer label="Medium" options={options} size="md" />\n<MultiSelectTransfer label="Large" options={options} size="lg" />\n```\n\n## Usage Patterns\n\n### Controlled vs. Uncontrolled\n\n- **Controlled** \u2014 pass `value` and `onChange`. The parent owns the selection; pills reflect\n `value` exactly. Required if you need to read or reset the selection externally.\n- **Uncontrolled** \u2014 omit `value` (optionally still pass `onChange` to observe changes). The\n component tracks the committed selection internally, so pills still render without any\n parent wiring.\n\n### Two ways to select\n\n1. **Dropdown** \u2014 clicking the trigger opens a searchable list (`searchable={false}` drops the search\n box and nothing else) with per-option checkboxes and a "Select all". Selection is a **draft**: it\n commits when the dropdown closes (outside click, toggling the trigger, the transfer-list CTA, or\n `Tab`) and discards on `Escape`.\n2. **Transfer-list modal** \u2014 clicking the expand CTA opens a two-panel modal seeded from the\n current selection. Opening it from an open dropdown commits that dropdown\'s draft first, so\n options ticked in the menu arrive on the Selected side rather than being dropped. Moves are a\n **draft** committed on **Done** and discarded on **Cancel**.\n\n### Filtering\n\n- **Client-side (default)** \u2014 options are filtered locally against the query. No handler needed.\n- **Server-side** \u2014 pass `onFilterChange`; the component stops filtering locally and hands you\n the (debounced) query so you can fetch and update `options` yourself. While Backspace/Delete is\n held the debounce waits for keyup (or blur), so a long-press cannot fire a search mid-hold.\n- **Async (`loadOptions`)** \u2014 the component owns the option list, paging, the request lifecycle and\n the loading state. See [Async mode](#async-mode-loadoptions).\n- **No search at all** \u2014 `searchable={false}` hides the dropdown\'s search input *and* the modal\'s two\n panel searches, so nothing on either surface can produce a query. Everything else stays: the reload\n button, "Select all", infinite scroll and the full keyboard model. `onFilterChange` never fires and\n is dev-warned if passed, and in async mode `loadOptions` is only ever called with an empty query \u2014\n paging still works, searching does not.\n- When the (client- or server-filtered) list has no matches, the dropdown shows a **"No options"**\n notice \u2014 the same copy as `Select`. While a search fetch is in flight (`isLoading`), the loader\n replaces that notice so an empty-and-loading menu never flashes "No options" mid-request.\n- Wherever the component clears the query itself \u2014 committing or cancelling the dropdown, or opening\n the transfer list modal \u2014 `onFilterChange("")` fires too (only if the query was non-empty), so your\n `options` never stay filtered by a query the user can no longer see. On modal open that also means\n the modal\'s Available panel gets the full list back.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above leaves three things at every call site: the results state, a\nmonotonic-ticket guard against out-of-order responses (debouncing limits how often a request *starts*,\nnot how many are in flight), and \u2014 for a paged source \u2014 page accumulation plus the\n"is this loader replacing rows or appending them?" distinction. `loadOptions` moves all of it inside:\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n loadOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return {\n options: res.rows.map((r) => ({ value: r.id, label: r.name })),\n cursor: res.nextToken, // absent/null \u21D2 no further pages\n total: res.totalCount // renders as "(loaded of total)" in the modal panel header\n };\n }}\n/>\n```\n\n`meta` carries `{ signal, cursor, page, reason }`; `reason` is `"defaults" | "search" | "more" | "reload"`.\nReturn a bare array for an unpaged source. Honouring `meta.signal` is optional \u2014 ordering is guaranteed\nby an internal per-slot ticket either way. A fresh inline arrow is fine: the loader is read through a ref.\n\nBehaviour worth knowing:\n\n- **Paging acts on the *active* bucket.** The empty-query baseline and the current search each carry\n their own cursor and page count, so paging a search and paging the baseline never interfere \u2014 and\n clearing the search back to the baseline resumes *its* paging from *its* cursor.\n- **Clearing the search restores the cached baseline with no request.** Pass `refetchOnClear` to also\n revalidate; stale rows stay on screen while it runs.\n- **A failed page keeps the rows** and offers **Retry** below them, and the infinite-scroll sentinel\n disarms until you press it \u2014 a sentinel still sitting in the viewport must not hammer a failing\n endpoint. Retry re-requests the *same* page; the cursor never advanced. A whole-list failure (the\n first page, a search, a reload) shows `loadErrorMessage` in place of the rows instead.\n- **Pages are appended with dedupe on `value`.** Server paging over an unstable sort returns\n duplicates, and both surfaces key their rows by `value`.\n- **The modal\'s Available search is server-side in async mode**, sharing the dropdown\'s single\n debounced query \u2014 over a paged pool, filtering only the pages that happen to be loaded would be a\n lie. Closing the modal (**Done** or **Cancel**) clears that query, so it never leaks into the\n dropdown. The **Selected** panel\'s search is always local: that side is a plain array with no server\n to ask, and there is nothing to page.\n- **The modal\'s Available panel is a projection** of the loaded pool minus the draft selection. A page\n that lands while the modal is open simply appears; an item the user already moved right is never\n yanked back. A committed option the pool never returned is supplied from a snapshot taken at open \u2014\n matched locally against the active query, so it cannot surface as a result for a search it does not\n match.\n\n This replaced an append-only fold effect, and it changes two things on the **non-async path too**\n (see [Migration notes](#migration-notes)).\n- **"Select All"** covers the loaded rows the active search leaves visible \u2014 never every server-side\n match. Toggling it off removes only those visible rows from the draft, so a selection made under an\n earlier query survives. The row is shown only when at least two selectable options are on screen.\n- **`optionsKey` does not clear the committed selection** \u2014 same reasoning as `Select`: that is a\n domain rule, and clearing a controlled `value` from inside means firing an `onChange` nobody asked for.\n- Options are stored exactly as returned, so extra fields you hang on an option survive and reach\n `onChange` as the same object.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame of both surfaces instead of a loader, and stay on\nscreen while the baseline fetch revalidates over them \u2014 the dropdown\'s spinner appends *below* the rows,\nas it does for any load in flight, so the revalidation is visible without hiding anything. This is the\none thing `prefetch` cannot do: `prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<MultiSelectTransfer\n label="Rows"\n initialOptions={ssrRows} // painted immediately, in the dropdown and the modal\n loadOptions={fetchRows} // still runs, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a\nheavy source you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<MultiSelectTransfer initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty list on both surfaces.\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query; clearing it\nbrings them back until a fetched baseline does. And seed rows only mean something to the async source \u2014\npassing `initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong\nin `options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Migration notes\n\nAdding `loadOptions` is opt-in and every new prop is optional, so no call site has to change. Two\n**runtime** behaviours of the transfer-list modal did change for existing (non-async) consumers,\nbecause the modal\'s Available panel is now derived from `options` rather than folded into owned state:\n\n| Situation | Before | Now |\n|---|---|---|\n| An item is moved back from Selected to Available | It was **appended to the end** of Available | It returns to its position in `options` |\n| The parent **shrinks** `options` while the modal is open | Previously-shown rows **lingered** in Available | They disappear, matching the new `options` |\n\nNeither loses a selection or changes what `onChange` reports \u2014 the committed value is unaffected in\nboth cases. The first is a visible row-ordering difference; the second makes the panel honest about\nwhat the parent is actually offering. If you depended on either, own the pool yourself and drive the\n`TransferList` directly instead of through `MultiSelectTransfer`.\n\nEverything else on the legacy path is unchanged, including the `hasMore` / `onLoadMore` / `isLoading`\ntrio and the append-vs-replace loader behaviour in both the dropdown and the modal.\n\n## Practical Examples\n\n### 1. Controlled selection with a live count\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst options: TMultiSelectTransferOption[] = [\n { value: "chocolate", label: "Chocolate" },\n { value: "vanilla", label: "Vanilla" },\n { value: "strawberry", label: "Strawberry" },\n { value: "mint", label: "Mint" }\n];\n\nfunction FlavorPicker() {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Flavors"\n placeholder="Select flavors..."\n options={options}\n value={selected}\n onChange={setSelected}\n helperText={`${selected.length} selected`}\n />\n );\n}\n```\n\n### 2. Validation and error state in a form\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n Button,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction PermissionsField({ options }: { options: TMultiSelectTransferOption[] }) {\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [touched, setTouched] = useState(false);\n const hasError = touched && selected.length === 0;\n\n const handleSubmit = () => {\n setTouched(true);\n if (selected.length === 0) return;\n // submit selected...\n };\n\n return (\n <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>\n <MultiSelectTransfer\n label="Permissions"\n placeholder="Assign permissions..."\n options={options}\n value={selected}\n onChange={setSelected}\n error={hasError}\n helperText={hasError ? "Select at least one permission." : undefined}\n />\n <Button type="submit">Save</Button>\n </form>\n );\n}\n```\n\n### 3. Server-side filtering with debounce\n\n```tsx\nimport { useEffect, useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction RemoteUserPicker() {\n const [query, setQuery] = useState("");\n const [options, setOptions] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n let active = true;\n setIsLoading(true);\n fetchUsers(query)\n .then((users) => {\n if (active) setOptions(users.map((u) => ({ value: u.id, label: u.name })));\n })\n .finally(() => active && setIsLoading(false));\n return () => { active = false; };\n }, [query]);\n\n return (\n <MultiSelectTransfer\n label="Assignees"\n placeholder="Select users..."\n options={options}\n value={selected}\n onChange={setSelected}\n onFilterChange={setQuery}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\n### 4. Paginated options with infinite scroll and reload\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nconst PAGE_SIZE = 20;\n\nfunction PaginatedPicker() {\n const [loaded, setLoaded] = useState<TMultiSelectTransferOption[]>([]);\n const [selected, setSelected] = useState<TMultiSelectTransferOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isReloading, setIsReloading] = useState(false);\n const [hasMore, setHasMore] = useState(true);\n\n const loadMore = async () => {\n if (isLoading) return;\n setIsLoading(true);\n const page = await fetchPage(loaded.length, PAGE_SIZE);\n setLoaded((prev) => [...prev, ...page.items]);\n setHasMore(page.hasMore);\n setIsLoading(false);\n };\n\n const reload = async () => {\n setIsReloading(true);\n const page = await fetchPage(0, PAGE_SIZE);\n setLoaded(page.items);\n setHasMore(page.hasMore);\n setIsReloading(false);\n };\n\n return (\n <MultiSelectTransfer\n label="Items"\n placeholder="Select items..."\n options={loaded}\n value={selected}\n onChange={setSelected}\n hasMore={hasMore}\n onLoadMore={loadMore}\n isLoading={isLoading}\n onReload={reload}\n isReloading={isReloading}\n />\n );\n}\n```\n\n### 5. Ordered selection via the transfer-list modal\n\n```tsx\nimport { useState } from "react";\nimport {\n MultiSelectTransfer,\n type TMultiSelectTransferOption\n} from "@cloudwick/astral-ui";\n\nfunction ColumnManager({ columns }: { columns: TMultiSelectTransferOption[] }) {\n const [visible, setVisible] = useState<TMultiSelectTransferOption[]>([]);\n\n return (\n <MultiSelectTransfer\n label="Visible columns"\n placeholder="No columns selected..."\n options={columns}\n value={visible}\n onChange={setVisible}\n reorderable\n maxVisiblePills={2}\n transferListTitle="Manage columns"\n transferListSubtitle="Choose which columns appear and in what order."\n doneLabel="Apply"\n />\n );\n}\n```\n\n## Styling and Customization\n\n- Use `className` to add classes to the root container.\n- The `size` and `error` props cover the common visual states.\n- For deeper theming, import the exported variants and compose them directly:\n\n```tsx\nimport { multiSelectTransferVariants } from "@components/multiSelectTransfer";\n\nconst { trigger, pill } = multiSelectTransferVariants({ size: "lg", error: false });\n```\n\nDark mode follows the library convention (a `.dark` class on a root ancestor); all slots\nship dark-mode styles. Spacing uses logical properties (`ps-`, `pe-`, `ms-`, `me-`) so the\ncontrol mirrors correctly in RTL layouts.\n\n## Technical Details\n\n- **State management:** The trigger shows a **committed** selection while the dropdown and\n modal each maintain their own **draft**. Drafts commit on close/Done and discard on\n Escape/Cancel, giving a clear "confirm before apply" model. In uncontrolled mode the\n committed value is held internally; in controlled mode it tracks `value`.\n- **Focus model:** With the search input shown it is the dropdown\'s combobox \u2014 focused on open and\n carrying `aria-controls` and `aria-activedescendant` over the listbox beneath it. With\n `searchable={false}` there is no combobox to relocate: the listbox itself becomes the single tab\n stop, is focused on open, carries `aria-activedescendant`, and owns the same key handler \u2014 the shape\n each `TransferList` panel\'s listbox already uses. Escape still cancels back to the trigger, Tab still\n commits, and `Space` activates the active row (with the input present it is a literal character in\n the query). There is no type-ahead in either mode.\n- **Draft preservation:** The dropdown draft is keyed on the option values\' contents, not the\n array reference, so an unrelated parent re-render that passes a new `value` array cannot wipe\n an in-progress draft \u2014 it re-syncs only on a genuine external change or on (re)open.\n- **Filtering:** Without `onFilterChange`, options are filtered client-side via `matchesQuery`\n and memoized for stable identity. `matchesQuery` matches an option\'s `searchValue` first, then a\n string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom JSX so\n they stay findable by their visible text. With `onFilterChange`, filtering is delegated to the parent\n and the query is debounced (`filterDebounceMs`); a pending debounce is cancelled on unmount, on an\n external `filterValue` reset, and whenever the component clears the query itself \u2014 where\n `onFilterChange("")` fires immediately instead, so a stale query can never overtake the reset.\n While Backspace/Delete is held the debounce is deferred until keyup (or blur), so a long-press\n cannot fire mid-hold. `filterValue` is a seed plus an external sync rather than a fully controlled\n value: the input owns its own text, a *new* `filterValue` overwrites it, and re-passing the same\n one does not pull it back \u2014 feed `onFilterChange` into the state you pass as `filterValue` to keep\n them in step. All of that lives in the shared `useFilterQuery` hook, which `Select` also uses, so\n the identically-named props on both components behave identically by construction.\n- **Virtualization:** Both the dropdown options list and the modal panels window large option\n sets (past ~100 items) so multi-thousand-item lists open and filter without mounting every row.\n- **Infinite scroll:** An `IntersectionObserver` sentinel (via `useInfiniteScroll`) calls\n `onLoadMore` when scrolled into view, gated on the open state. While the modal is open, newly\n loaded options are folded into the Available draft without duplicating or reclaiming items the\n user has already moved to Selected.\n- **Loading UI:** `isLoading` covers two situations with opposite needs, and the component tells them\n apart by whether the sentinel above asked for the load. A **search fetch** replaces the option rows\n with the loader \u2014 they belong to the previous query, so leaving them clickable would let the user\n pick an option the incoming results no longer contain (`Select` does the same). An empty-and-loading\n menu therefore shows the loader alone rather than "No options". Arrow/Enter are ignored while those\n rows are gone, so the keyboard cannot reach one either, and the listbox is marked `aria-busy`. A\n **load-more** is adding to those rows, so the loader is appended below them and the scroll position\n survives \u2014 a load-more stays a load-more until it finishes, even if the consumer flips `isLoading`\n a render or two after `onLoadMore`.\n- **Modal portal:** The transfer-list modal renders in a body portal. The dropdown\'s\n outside-click listener is suspended while the modal is open so a click inside the portal is not\n misread as an outside click.\n- **Pill overflow:** The trigger shows up to `maxVisiblePills` pills, then a "+N More" badge.\n Long pill labels truncate to a max width and surface the full text via a `Tooltip` only when\n actually clipped.\n\n## Accessibility\n\n**Implemented:**\n- The trigger is a keyboard-operable control: `role="button"`, `aria-haspopup="listbox"`, and\n `aria-expanded` reflecting the open state.\n- The trigger is focusable (`tabIndex={0}`) when enabled and removed from the tab order\n (`tabIndex={-1}`) when `disabled`.\n- Keyboard support on the trigger: `Enter`/`Space` toggle the dropdown; `Escape` closes and\n discards the draft.\n- Keyboard support in the dropdown: `Escape` cancels/discards and returns focus to the trigger\n so a keyboard user is never stranded on `<body>`; `Tab` commits the draft and lets focus move\n on naturally.\n- The `label` is associated with the trigger via `htmlFor`/`id` (auto-generated when `id` is\n omitted).\n- The transfer-list CTA and reload buttons carry descriptive `aria-label`/tooltip text.\n- The dropdown\'s search input is a `combobox` (`aria-controls` / `aria-activedescendant` /\n `aria-autocomplete="list"`) over the option `listbox`. With `searchable={false}` no combobox is\n rendered: the `listbox` takes `tabIndex={0}` and `aria-activedescendant` itself and is focused on\n open, so Arrow/Home/End/Enter/Space/Escape/Tab are unchanged. It stays focusable while the rows are\n replaced by a loader or an error, so Escape is never stranded.\n- Disabled options are excluded from selection and from "Select all".\n\n**Best Practices:**\n- Always provide a `label` (or an external `aria-label`) so the control is announced.\n- Use `error` together with `helperText` to communicate validation state visibly rather than by\n color alone.\n- Keep option `label`s meaningful as text \u2014 pills, tooltips, and screen readers all render them.\n- Provide stable, unique `value`s; reusing a value across options breaks selection tracking and\n keys.\n- When filtering server-side, keep `isLoading` accurate so assistive tech and users get correct\n loading feedback.\n'
2732
2751
  }
2733
2752
  ],
2734
2753
  "directories": []
@@ -3284,7 +3303,7 @@ export const scrollbarVariants = tv({
3284
3303
  },
3285
3304
  "select": {
3286
3305
  "name": "select",
3287
- "description": 'The Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality, custom rendering, and keyboard navigation. **When to use:** - Form fields requiring single selection from options - Filtering interfaces - Settings and preferences selection - Any scenario requiring choice from predefined list **Component Architecture:** - Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation - Styled with Tailwind CSS and `tailwind-variants` (`tv()`) - Search input lives inside the dropdown; filtering is client-side by default, or delegated to the parent via `onFilterChange` (see [Filtering](#filtering)) - Accessible with proper ARIA attributes',
3306
+ "description": 'The Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality (hidden with `searchable={false}`), custom rendering, and keyboard navigation. **When to use:** - Form fields requiring single selection from options - Filtering interfaces - Settings and preferences selection - Any scenario requiring choice from predefined list **Component Architecture:** - Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation - Styled with Tailwind CSS and `tailwind-variants` (`tv()`) - Search input lives inside the dropdown unless `searchable={false}` hides it; filtering is client-side by default, or delegated to the parent via `onFilterChange` (see [Filtering](#filtering)) - Accessible with proper ARIA attributes',
3288
3307
  "dependencies": [
3289
3308
  "react-select",
3290
3309
  "react",
@@ -3303,7 +3322,7 @@ export const scrollbarVariants = tv({
3303
3322
  "files": [
3304
3323
  {
3305
3324
  "name": "utils.ts",
3306
- "content": 'import { type StylesConfig, type GroupBase } from "react-select";\nimport { type TSelectSize, type IOption } from "./types";\n\n// Synthetic Select-All row value, injected in select.tsx. Never query-matched \u2014 it is an affordance\n// over the result set, not a member of it.\nexport const SELECT_ALL_VALUE = "select-all";\n\nconst isSelectable = ( option: IOption ): boolean =>\n option.value !== SELECT_ALL_VALUE && !option.isDisabled;\n\n// An entry is a group only when its `options` field is actually a list. Options are stored exactly as\n// returned by the consumer, so one may legitimately carry an unrelated `options` data field; keying the\n// branch on the key alone would send it down the group path and throw on `.filter`.\nconst isGroup = ( entry: IOption | GroupBase<IOption> ): entry is GroupBase<IOption> =>\n "options" in entry && Array.isArray(( entry as GroupBase<IOption> ).options );\n\n// The real, enabled options, with groups flattened so the Select-All affordance reaches their\n// children \u2014 a group has no `value` of its own, so a list of nothing but groups would otherwise\n// resolve to nothing selectable. Sync mode may mix loose options and groups freely; both shapes go\n// through one pass and the result stays in render order. Narrowing the result by the active query\n// gives what "all" refers to: the enabled options currently on screen.\nexport const getSelectableOptions = (\n options: readonly ( IOption | GroupBase<IOption> )[]\n): IOption[] => {\n const selectable: IOption[] = [];\n options.forEach(( entry ) => {\n if ( isGroup( entry )) {\n selectable.push( ...entry.options.filter( isSelectable ));\n } else if ( isSelectable( entry )) {\n selectable.push( entry );\n }\n });\n return selectable;\n};\n\n// True when every selectable option is already in the draft. An empty selectable set is never\n// "all selected". Shared by the Select-All toggle and the row\'s checked state (both resolved in\n// select.tsx) so the two agree on one definition. Takes an already-narrowed option list rather than\n// the raw one, and the draft as a value Set, which is what keeps the check off a linear scan.\nexport const areAllSelectableSelected = (\n selectable: readonly IOption[],\n draftValues: ReadonlySet<IOption["value"]>\n): boolean => selectable.length > 0 && selectable.every(( o ) => draftValues.has( o.value ));\n\nexport const reactSelectCustomStyles = <\n IsMulti extends boolean,\n Group extends GroupBase<IOption>\n>(\n error: boolean,\n size: TSelectSize,\n multiSelect: boolean\n): StylesConfig<IOption, IsMulti, Group> => {\n return {\n container: ( base ) => ({\n ...base,\n display: "flex",\n flexDirection: "column",\n gap: "0.5rem"\n }),\n control: ( base, state ) => ({\n ...base,\n display: "flex",\n alignItems: "center",\n gap: "0.5rem",\n borderRadius: "0.5rem",\n padding: size === "md" ? "0.2rem 0.75rem" : "0.2rem 1rem",\n "&:hover": {\n borderColor: "inherit"\n },\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F1AE9D"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-700))"\n : state.isFocused\n ? "rgb(var(--primary-500))"\n : "rgb(var(--gray-200))",\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-50))"\n : base.backgroundColor,\n "&:disabled": {\n color: "rgb(var(--secondary-200))"\n },\n // Dark mode styles\n ".dark &": {\n backgroundColor: state.isDisabled\n ? "rgb(var(--secondary-800))"\n : "rgb(var(--iridium))",\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F38176"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-400))"\n : "rgb(var(--secondary-500))",\n "&:disabled": {\n color: "rgb(var(--secondary-300))"\n },\n color: "rgb(var(--secondary-400))"\n }\n }),\n menu: ( base ) => ({\n ...base,\n boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",\n borderRadius: "0.5rem",\n overflow: "hidden",\n border: "1px solid rgb(var(--secondary-50))",\n // Dark mode styles\n ".dark &": {\n backgroundColor: "rgb(var(--iridium))",\n borderColor: "rgb(var(--secondary-500))"\n }\n }),\n menuList: ( base ) => ({\n ...base,\n padding: 0\n }),\n // Loose options and groups may be mixed in one list, and react-select renders a loose option as a\n // SIBLING of the group before it with nothing marking where the group ended \u2014 so it reads as one of\n // that group\'s members. The rule closes each group off. Scoped to groups that are followed by\n // something, so a trailing group never draws a line against the menu\'s own edge.\n group: ( base ) => ({\n ...base,\n "&:not(:last-child)": {\n borderBottom: "1px solid rgb(var(--gray-200))",\n marginBottom: "0.5rem",\n ".dark &": { borderBottomColor: "rgb(var(--secondary-500))" }\n }\n }),\n // react-select\'s default heading is a hardcoded grey that ignores dark mode, and its 12px inset\n // leaves the label out of line with the option rows it heads.\n groupHeading: ( base ) => ({\n ...base,\n padding: "0 1rem",\n fontWeight: 600,\n color: "rgb(var(--secondary-400))",\n ".dark &": { color: "rgb(var(--secondary-300))" }\n }),\n menuPortal: ( base ) => ({\n ...base,\n zIndex: 2020\n }),\n option: ( base, state ) => ({\n ...base,\n ...( multiSelect ? { display: "flex", alignItems: "center" } : {}),\n color: "rgb(var(--secondary-500))",\n fontWeight: "normal",\n padding: "0.625rem 1rem",\n transition: "200ms ease-in-out",\n position: "relative",\n backgroundColor: "transparent",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--secondary-500))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {},\n // Dark mode styles\n ".dark &": {\n color: "rgb(var(--secondary-200))",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--gray-800))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {}\n }\n }),\n indicatorsContainer: ( base ) => ({ ...base, display: "flex", alignItems: "center", gap: "8px" }),\n valueContainer: ( base ) => ({ ...base, padding: 0, ...multiSelect ? { gap: "0.25rem" } : {} }),\n clearIndicator: ( base ) => ({ ...base, padding: 0 }),\n multiValue: ( base, state ) => ({\n ...base,\n margin: "0 0.5rem 0 0",\n borderRadius: "0.25rem",\n // Cap each chip and let its label truncate (react-select\'s multiValueLabel already sets\n // overflow:hidden + text-overflow:ellipsis) so one long value can\'t stretch the control.\n maxWidth: size === "md" ? "12rem" : "14rem",\n minWidth: 0,\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-100))"\n : "rgb(var(--gray-50))",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n backgroundColor: "rgb(var(--secondary-600))",\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueLabel: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueRemove: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n paddingLeft: "0!important",\n display: state.data.isFixed ? "none" : "flex",\n alignItems: "center",\n justifyContent: "center",\n marginStart: "-0.5rem",\n "&:hover": {\n backgroundColor: "transparent",\n color: "inherit"\n }\n }),\n input: ( base ) => ({\n ...base,\n margin: 0,\n padding: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-500))",\n ".dark &": { color: "rgb(var(--secondary-200))" }\n }),\n singleValue: ( base, state ) => ({\n ...base,\n margin: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n placeholder: ( base ) => ({\n ...base,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-200))",\n ".dark &": { color: "rgb(var(--secondary-400))" }\n })\n };\n};'
3325
+ "content": 'import { type StylesConfig, type GroupBase } from "react-select";\nimport { type TSelectSize, type IOption } from "./types";\n\n// Synthetic Select-All row value, injected in select.tsx. Never query-matched \u2014 it is an affordance\n// over the result set, not a member of it.\nexport const SELECT_ALL_VALUE = "select-all";\n\nconst isSelectable = ( option: IOption ): boolean =>\n option.value !== SELECT_ALL_VALUE && !option.isDisabled;\n\n// The "Create ..." row react-select\'s Creatable appends to the option list, which it marks with\n// `__isNew__`. It is an action rather than a member of the pool: picking it produces an option that\n// does not exist yet, so it carries none of a real row\'s selection affordances.\nexport const isCreateOption = ( option: IOption ): boolean =>\n ( option as IOption & { __isNew__?: boolean }).__isNew__ === true;\n\n// The option a create produces, as an ordinary option. react-select stamps `__isNew__` on what it hands\n// to `onChange` as well as on the Create row, and within this component that mark means one thing: this\n// row is the Create affordance, so it has no checkbox and no part in filtering. An option that merely\n// came from a create is not that, so the mark comes off before it reaches either the list or the\n// consumer \u2014 who is invited to put it straight back into `options`, where it would otherwise land as a\n// second Create row.\nexport const toPoolOption = ( option: IOption ): IOption => {\n const pooled = { ...option } as IOption & { __isNew__?: boolean };\n delete pooled.__isNew__;\n return pooled;\n};\n\n// An entry is a group only when its `options` field is actually a list. Options are stored exactly as\n// returned by the consumer, so one may legitimately carry an unrelated `options` data field; keying the\n// branch on the key alone would send it down the group path and throw on `.filter`.\nconst isGroup = ( entry: IOption | GroupBase<IOption> ): entry is GroupBase<IOption> =>\n "options" in entry && Array.isArray(( entry as GroupBase<IOption> ).options );\n\n// The real, enabled options, with groups flattened so the Select-All affordance reaches their\n// children \u2014 a group has no `value` of its own, so a list of nothing but groups would otherwise\n// resolve to nothing selectable. Sync mode may mix loose options and groups freely; both shapes go\n// through one pass and the result stays in render order. Narrowing the result by the active query\n// gives what "all" refers to: the enabled options currently on screen.\nexport const getSelectableOptions = (\n options: readonly ( IOption | GroupBase<IOption> )[]\n): IOption[] => {\n const selectable: IOption[] = [];\n options.forEach(( entry ) => {\n if ( isGroup( entry )) {\n selectable.push( ...entry.options.filter( isSelectable ));\n } else if ( isSelectable( entry )) {\n selectable.push( entry );\n }\n });\n return selectable;\n};\n\n// Every value the pool already accounts for, groups flattened and disabled rows included: what a\n// created option is checked against before it is added, so a value the consumer supplies keeps its own\n// row rather than gaining a second one. Disabled rows count \u2014 an option the consumer has deliberately\n// put out of reach is still spoken for.\nexport const getPooledValues = (\n options: readonly ( IOption | GroupBase<IOption> )[]\n): Set<IOption["value"]> => {\n const values = new Set<IOption["value"]>();\n options.forEach(( entry ) => {\n if ( isGroup( entry )) {\n entry.options.forEach(( option ) => values.add( option.value ));\n } else {\n values.add( entry.value );\n }\n });\n return values;\n};\n\n// True when every selectable option is already in the draft. An empty selectable set is never\n// "all selected". Shared by the Select-All toggle and the row\'s checked state (both resolved in\n// select.tsx) so the two agree on one definition. Takes an already-narrowed option list rather than\n// the raw one, and the draft as a value Set, which is what keeps the check off a linear scan.\nexport const areAllSelectableSelected = (\n selectable: readonly IOption[],\n draftValues: ReadonlySet<IOption["value"]>\n): boolean => selectable.length > 0 && selectable.every(( o ) => draftValues.has( o.value ));\n\nexport const reactSelectCustomStyles = <\n IsMulti extends boolean,\n Group extends GroupBase<IOption>\n>(\n error: boolean,\n size: TSelectSize,\n multiSelect: boolean\n): StylesConfig<IOption, IsMulti, Group> => {\n return {\n container: ( base ) => ({\n ...base,\n display: "flex",\n flexDirection: "column",\n gap: "0.5rem"\n }),\n control: ( base, state ) => ({\n ...base,\n display: "flex",\n alignItems: "center",\n gap: "0.5rem",\n borderRadius: "0.5rem",\n padding: size === "md" ? "0.2rem 0.75rem" : "0.2rem 1rem",\n "&:hover": {\n borderColor: "inherit"\n },\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F1AE9D"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-700))"\n : state.isFocused\n ? "rgb(var(--primary-500))"\n : "rgb(var(--gray-200))",\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-50))"\n : base.backgroundColor,\n "&:disabled": {\n color: "rgb(var(--secondary-200))"\n },\n // Dark mode styles\n ".dark &": {\n backgroundColor: state.isDisabled\n ? "rgb(var(--secondary-800))"\n : "rgb(var(--iridium))",\n boxShadow: state.isFocused\n ? error\n ? "0px 0px 2px 2px #F38176"\n : "0px 0px 2px 2px #99CBFA"\n : base.boxShadow,\n borderColor: error\n ? "rgb(var(--error-400))"\n : "rgb(var(--secondary-500))",\n "&:disabled": {\n color: "rgb(var(--secondary-300))"\n },\n color: "rgb(var(--secondary-400))"\n }\n }),\n menu: ( base ) => ({\n ...base,\n boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",\n borderRadius: "0.5rem",\n overflow: "hidden",\n border: "1px solid rgb(var(--secondary-50))",\n // Dark mode styles\n ".dark &": {\n backgroundColor: "rgb(var(--iridium))",\n borderColor: "rgb(var(--secondary-500))"\n }\n }),\n menuList: ( base ) => ({\n ...base,\n padding: 0\n }),\n // Loose options and groups may be mixed in one list, and react-select renders a loose option as a\n // SIBLING of the group before it with nothing marking where the group ended \u2014 so it reads as one of\n // that group\'s members. The rule closes each group off. Scoped to groups that are followed by\n // something, so a trailing group never draws a line against the menu\'s own edge.\n group: ( base ) => ({\n ...base,\n "&:not(:last-child)": {\n borderBottom: "1px solid rgb(var(--gray-200))",\n marginBottom: "0.5rem",\n ".dark &": { borderBottomColor: "rgb(var(--secondary-500))" }\n }\n }),\n // react-select\'s default heading is a hardcoded grey that ignores dark mode, and its 12px inset\n // leaves the label out of line with the option rows it heads.\n groupHeading: ( base ) => ({\n ...base,\n padding: "0 1rem",\n fontWeight: 600,\n color: "rgb(var(--secondary-400))",\n ".dark &": { color: "rgb(var(--secondary-300))" }\n }),\n menuPortal: ( base ) => ({\n ...base,\n zIndex: 2020\n }),\n option: ( base, state ) => ({\n ...base,\n ...( multiSelect ? { display: "flex", alignItems: "center" } : {}),\n color: "rgb(var(--secondary-500))",\n fontWeight: "normal",\n padding: "0.625rem 1rem",\n transition: "200ms ease-in-out",\n position: "relative",\n backgroundColor: "transparent",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--secondary-500))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {},\n // Dark mode styles\n ".dark &": {\n color: "rgb(var(--secondary-200))",\n "&:after":\n state.isSelected && !multiSelect\n ? {\n content: "\\"\\"",\n position: "absolute",\n height: "8px",\n width: "16px",\n transform: "rotate(-45deg)",\n border: "2px solid rgb(var(--gray-800))",\n right: "0.4rem",\n top: "35%",\n borderTop: 0,\n borderRight: 0\n }\n : {}\n }\n }),\n indicatorsContainer: ( base ) => ({ ...base, display: "flex", alignItems: "center", gap: "8px" }),\n valueContainer: ( base ) => ({ ...base, padding: 0, ...multiSelect ? { gap: "0.25rem" } : {} }),\n clearIndicator: ( base ) => ({ ...base, padding: 0 }),\n multiValue: ( base, state ) => ({\n ...base,\n margin: "0 0.5rem 0 0",\n borderRadius: "0.25rem",\n // Cap each chip and let its label truncate (react-select\'s multiValueLabel already sets\n // overflow:hidden + text-overflow:ellipsis) so one long value can\'t stretch the control.\n maxWidth: size === "md" ? "12rem" : "14rem",\n minWidth: 0,\n backgroundColor: state.isDisabled\n ? "rgb(var(--gray-100))"\n : "rgb(var(--gray-50))",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n backgroundColor: "rgb(var(--secondary-600))",\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueLabel: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n multiValueRemove: ( base, state ) => ({\n ...base,\n padding: "0.25rem",\n paddingLeft: "0!important",\n display: state.data.isFixed ? "none" : "flex",\n alignItems: "center",\n justifyContent: "center",\n marginStart: "-0.5rem",\n "&:hover": {\n backgroundColor: "transparent",\n color: "inherit"\n }\n }),\n input: ( base ) => ({\n ...base,\n margin: 0,\n padding: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-500))",\n ".dark &": { color: "rgb(var(--secondary-200))" }\n }),\n singleValue: ( base, state ) => ({\n ...base,\n margin: 0,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: state.isDisabled\n ? "rgb(var(--secondary-300))"\n : "rgb(var(--secondary-500))",\n ".dark &": {\n color: state.isDisabled\n ? "rgb(var(--secondary-400))"\n : "rgb(var(--secondary-200))"\n }\n }),\n placeholder: ( base ) => ({\n ...base,\n fontSize: size === "md" ? "0.875rem" : "1rem",\n color: "rgb(var(--secondary-200))",\n ".dark &": { color: "rgb(var(--secondary-400))" }\n })\n };\n};'
3307
3326
  },
3308
3327
  {
3309
3328
  "name": "useSelectOutsideClose.ts",
@@ -3333,25 +3352,27 @@ export function useSelectOutsideClose({
3333
3352
  return undefined;
3334
3353
  }
3335
3354
  const handlePointerDown = ( e: MouseEvent ) => {
3336
- const target = e.target as HTMLElement | null;
3337
- // Ignore events whose target detached during a re-render \u2014 react-select swaps its
3338
- // control input when the menu opens, so the opening mousedown's target leaves the
3339
- // DOM and would otherwise be mistaken for an outside click.
3340
- if ( !target || !target.isConnected ) {
3355
+ // Outsideness is read off the event's dispatch path, which names every element the mousedown
3356
+ // travelled through even once the DOM has moved on. react-select swaps the control input of
3357
+ // the Select being opened, so the clicked node is frequently detached by the time this
3358
+ // listener runs and its ancestors are no longer reachable from it.
3359
+ const path = e.composedPath();
3360
+ const target = ( path[0] ?? e.target ) as HTMLElement | null;
3361
+ if ( !target ) {
3341
3362
  return;
3342
3363
  }
3343
3364
  // Clicks inside the (possibly portaled) menu keep it open.
3344
- const insideMenu = menuNodeRef.current?.contains( target );
3345
- if ( insideMenu ) {
3365
+ const menuNode = menuNodeRef.current;
3366
+ if ( menuNode && path.includes( menuNode )) {
3346
3367
  return;
3347
3368
  }
3348
3369
  // The per-chip remove "\xD7" and the clear-all control have their own react-select handlers;
3349
3370
  // don't hijack those into a menu close.
3350
- if ( target.closest( ".select__multi-value__remove, .select__clear-indicator" )) {
3371
+ if ( target.closest?.( ".select__multi-value__remove, .select__clear-indicator" )) {
3351
3372
  return;
3352
3373
  }
3353
- // Everything else \u2014 the control body/chevron (toggle-closed) or a truly outside click \u2014
3354
- // commits the draft and closes.
3374
+ // Everything else \u2014 the control body/chevron (toggle-closed), another Select's control, or a
3375
+ // truly outside click \u2014 commits the draft and closes.
3355
3376
  commitAndClose();
3356
3377
  };
3357
3378
  // Defer attaching the listener so the click that opened the menu cannot immediately
@@ -3373,7 +3394,7 @@ export function useSelectOutsideClose({
3373
3394
  },
3374
3395
  {
3375
3396
  "name": "types.ts",
3376
- "content": 'import type {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n ReactNode,\n ReactElement,\n MutableRefObject,\n RefObject\n} from "react";\nimport type { Props as ReactSelectProps, GroupBase } from "react-select";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport { type TIconType } from "../adpIcon";\n\n/**\n * Available sizes for the Select component\n */\nexport enum ESelectSizes {\n MD = "md",\n LG = "lg"\n}\n\n/**\n * Size type derived from available sizes\n */\nexport type TSelectSize = `${ESelectSizes}`;\n\n/**\n * Option type for Select component\n */\nexport interface IOption {\n label: ReactNode;\n value: any;\n /** Plain-text used for searching when `label` is a ReactNode. Takes precedence over label/value. */\n searchValue?: string;\n isFixed?: boolean;\n isDisabled?: boolean;\n}\n\n/**\n * Async option source. Page one only: a resolved page that reports `hasMore` is dev-warned, and no\n * further page is ever requested.\n */\nexport type TSelectLoadOptions = TLoadOptions<IOption>;\n\n/** Latest input modality. Drives which signal shows an option\'s full-text overlay. */\nexport type TSelectInteractionMode = "pointer" | "keyboard";\n\n/** Options as react-select accepts them \u2014 sync mode may carry groups; async mode never does. */\nexport type TSelectOptions<Group extends GroupBase<IOption> = GroupBase<IOption>> =\n readonly ( IOption | Group )[];\n\n/**\n * Props for the Select component\n */\nexport interface ISelectProps<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n> extends Omit<\n ReactSelectProps<IOption, IsMulti, Group>,\n // `inputValue`, `onInputChange` and `isSearchable` are intentionally omitted: this component\n // owns an internal search box (see `searchPlaceholder`) and controls react-select\'s inputValue\n // itself, so these react-select props would silently no-op if forwarded.\n // `isLoading` and `filterOption` are omitted and re-declared below (not forwarded to react-select).\n "options" | "value" | "className" | "inputValue" | "onInputChange" | "isSearchable" | "isLoading"\n | "filterOption"\n > {\n /** Unique id for the select input */\n id?: string;\n /** Custom className for wrapper */\n className?: string;\n /** Label displayed above select */\n label?: ReactNode;\n /** Select size variant */\n size?: TSelectSize;\n /** Options or groups to render. Ignored (dev warning) when `loadOptions` is set \u2014 seed with `initialOptions` instead. */\n options?: ReactSelectProps<IOption, IsMulti, Group>["options"];\n /** Current value of the select */\n value?: ReactSelectProps<IOption, IsMulti, Group>["value"];\n /** Helper text displayed below */\n helperText?: ReactNode;\n /** Display error styling */\n error?: boolean;\n /** Disable the select */\n disabled?: boolean;\n /** Enable creatable select */\n creatable?: boolean;\n /** Field touched state */\n touched?: boolean;\n /** Max number of visible values in multi */\n maxVisibleValues?: number;\n /** Label for truncated values */\n maxVisibleValuesMsg?: string;\n /** Custom footer in menu */\n menuFooter?: ReactNode;\n /** Prefix icon for the control */\n prefixIcon?: TIconType | ReactNode;\n /** Suffix icon for the control */\n suffixIcon?: TIconType | ReactNode;\n /** Placeholder text for the search input inside the dropdown */\n searchPlaceholder?: string;\n /** Tooltip for the select reload button. */\n reloadTooltip?: string;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the select reload button. */\n isReloading?: boolean;\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. Applies in both modes. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search.\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n /** Replaces option list with loader. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n /**\n * Custom client-side match, replacing the shared `matchesQuery` default.\n *\n * @deprecated Use `onFilterChange` instead, which does the same job without a second filtering axis:\n * it hands you the query and treats `options` as already filtered, so your predicate lives in your own\n * `useMemo` rather than in a react-select callback. Pair with `filterDebounceMs={0}` to keep filtering\n * synchronous. Ignored entirely when filtering is already delegated (`onFilterChange`/`loadOptions`),\n * and scheduled for removal in the next major.\n *\n * ```tsx\n * const visible = useMemo(() => all.filter(( o ) => myMatch( o, query )), [ all, query ]);\n * <Select options={visible} onFilterChange={setQuery} filterDebounceMs={0} />\n * ```\n */\n filterOption?: ReactSelectProps<IOption, IsMulti, Group>["filterOption"];\n\n /**\n * Server-side option source. When provided, `Select` owns the option list, the request lifecycle and\n * the loading state; `options` is ignored (dev warning) and `onFilterChange` becomes\n * notification-only. Responsible for mapping the payload to `IOption` \u2014 envelopes and domain\n * filtering are the consumer\'s business. Options are stored exactly as returned, so extra fields\n * survive. A fresh inline arrow is fine: the loader is read through a ref.\n *\n * Page one only: `cursor` / `hasMore` / `total` in the result are ignored.\n */\n loadOptions?: TSelectLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame, so there is no loader to sit through, and they stay put while the baseline fetch revalidates\n * over them. They do not suppress that fetch: pair with `prefetch="never"` if the seed is the whole list\n * until the user types. A *search* replaces them, since seed rows are not results for a query; clearing it\n * brings them back until a fetched baseline lands. Async mode only \u2014 ignored (dev warning) without\n * `loadOptions`, where the rows belong in `options`.\n */\n initialOptions?: readonly IOption[];\n /**\n * When to fetch the unfiltered baseline.\n * - `"open"` \u2014 on first menu open. Right for forms with several server-filtered Selects, where paying\n * for menus the user may never open is the worse trade.\n * - `"mount"` \u2014 at render, before any interaction. Use when the list is near-certain to be needed and\n * a visible-but-empty Select would read as broken.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. Costs one request per menu close. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent selects. When it changes, cached results are dropped and\n * the list is repopulated \u2014 immediately if the menu is open, otherwise on next open. Compose several\n * parents into one scalar: ``optionsKey={`${domainId}|${accessType}`}``. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in the menu when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shows the menu\'s reload button in async mode, wired to re-run the current query. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders `loadErrorMessage` and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n\n/**\n * Per-render option config for the SelectOption component. react-select keys custom components by\n * reference and remounts them whenever that reference changes; the `customComponents` object in\n * select.tsx is rebuilt every render. Feeding these live values through context (rather than a\n * closure inside a freshly-created Option) lets SelectOption keep a stable module-level identity,\n * so react-select re-renders it in place instead of remounting - which is what keeps the\n * `useIsTruncated` measurement (and the hover-expand affordance) from flickering.\n */\nexport interface ISelectOptionContext {\n /**\n * In-progress multi-select draft, as a value Set. Drives checkboxes / Select All while the\n * committed value drives the control. A Set rather than the array: every option row tests its own\n * membership, so an array would make one menu render O(options x draft).\n */\n draftValues?: ReadonlySet<IOption["value"]>;\n /**\n * Checked state of the Select All row: every option the query currently leaves VISIBLE is in the\n * draft. Resolved on the Select, which is the only place that knows the visible set \u2014 react-select\n * hands each option its unfiltered `options` array, so deriving it here would report unchecked\n * even with every visible row ticked.\n */\n areAllSelected?: boolean;\n /** Toggle a single option in the multi-select draft. */\n onToggleDraftOption?: ( option: IOption ) => void;\n /** Toggle Select All / Deselect All on the multi-select draft (shared with the keyboard path). */\n onSelectAll?: () => void;\n /** tv() class for the label wrapper. */\n optionLabelWrapClass: string;\n /** tv() class for the (truncating) label. */\n optionLabelClass: string;\n /** tv() class for the hover/focus full-text overlay. */\n optionOverlayClass: string;\n /**\n * Latest input modality, shared across every option. The full-text overlay follows the pointer\n * (local `isHovered`) while the user is using the mouse, and react-select\'s `isFocused` while\n * they\'re navigating by keyboard. Without this, react-select\'s `isFocused` - which lingers on the\n * last-focused option after the pointer leaves, and is also set by mouse hover - keeps an\n * overlay visible after the mouse has moved away (and shows two at once mid-transition).\n *\n * State on the Select, not a shared ref: this decides what an option renders, and writing a ref\n * schedules no re-render. Setting the mode it already holds is a no-op React bails out of, so\n * hovering along a list costs a render only at a genuine modality switch.\n */\n interactionMode: TSelectInteractionMode;\n /** Records the modality the user just used. See {@link ISelectOptionContext.interactionMode}. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\n/**\n * Per-instance menu config via context (keeps SelectMenu\'s stable identity).\n */\nexport interface ISelectMenuContext {\n /** Current search text (controls react-select\'s inputValue). */\n filterQuery: string;\n /** Updates the query and (debounced) notifies `onFilterChange`. */\n onFilterInput: ( e: ChangeEvent<HTMLInputElement> ) => void;\n /** Marks Backspace/Delete held; defer debounce until keyup. */\n onFilterKeyDown: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On Backspace/Delete release, starts the deferred debounce. */\n onFilterKeyUp: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On blur during hold, flush deferred debounce. */\n onFilterBlur: ( e: FocusEvent<HTMLInputElement> ) => void;\n /** Placeholder for the search input. */\n searchPlaceholder: string;\n /** Optional custom footer rendered below the option list. */\n menuFooter?: ReactNode;\n /** Close the menu, discarding the multi-select draft. */\n closeMenu: () => void;\n /** Commit the multi-select draft, then close. */\n commitAndClose: () => void;\n /** tv() class for the search container. */\n searchContainerClass: string;\n /** tv() class for the search input. */\n searchInputClass: string;\n /** tv() class for the loader shown in place of the option list. */\n loaderClass: string;\n /** Replaces the option list with the loader. */\n isLoading?: boolean;\n /** Replaces the option list when set (async load failure). */\n loadError?: ReactNode;\n /** tv() class for the error container. */\n errorClass: string;\n /** Ref to the search input; focused when the menu opens. */\n searchInputRef: RefObject<HTMLInputElement>;\n /** Captures the menu\'s (possibly portaled) DOM node for the outside-click check. */\n menuNodeRef: MutableRefObject<HTMLDivElement | null>;\n /** Ref to the component wrapper, used to reach react-select\'s hidden control input. */\n containerRef: RefObject<HTMLDivElement>;\n /** Shown when provided; fired on reload-button click. */\n onReload?: () => void;\n /** Spins/disables the reload button. */\n isReloading?: boolean;\n /** Reload-button tooltip / aria-label. */\n reloadTooltip?: string;\n /** Records the input modality (see {@link ISelectOptionContext.interactionMode}); set to "keyboard" here. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\nexport interface IOptionLabelOverlayProps {\n anchorRef: RefObject<HTMLElement>;\n className: string;\n children: ReactNode;\n}\n\nexport interface ITruncatedMultiValueProps {\n /** The plain-text label, used as the Tooltip title. */\n label: string;\n /** react-select\'s rendered chip (MultiValueContainer + label + remove). */\n chip: ReactElement;\n}\n\nexport interface ISelectComponentsConfig {\n prefixIcon?: TIconType | ReactNode;\n suffixIcon?: TIconType | ReactNode;\n maxVisibleValues: number;\n maxVisibleValuesMsg?: string;\n disabled: boolean;\n}\n'
3397
+ "content": 'import type {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n ReactNode,\n ReactElement,\n MutableRefObject,\n RefObject\n} from "react";\nimport type { Props as ReactSelectProps, GroupBase } from "react-select";\n\nimport type { TLoadOptions, TPrefetch } from "@hooks";\nimport { type TIconType } from "../adpIcon";\n\n/**\n * Available sizes for the Select component\n */\nexport enum ESelectSizes {\n MD = "md",\n LG = "lg"\n}\n\n/**\n * Size type derived from available sizes\n */\nexport type TSelectSize = `${ESelectSizes}`;\n\n/**\n * Option type for Select component\n */\nexport interface IOption {\n label: ReactNode;\n value: any;\n /** Plain-text used for searching when `label` is a ReactNode. Takes precedence over label/value. */\n searchValue?: string;\n isFixed?: boolean;\n isDisabled?: boolean;\n}\n\n/**\n * Async option source. Page one only: a resolved page that reports `hasMore` is dev-warned, and no\n * further page is ever requested.\n */\nexport type TSelectLoadOptions = TLoadOptions<IOption>;\n\n/** Latest input modality. Drives which signal shows an option\'s full-text overlay. */\nexport type TSelectInteractionMode = "pointer" | "keyboard";\n\n/** Options as react-select accepts them \u2014 sync mode may carry groups; async mode never does. */\nexport type TSelectOptions<Group extends GroupBase<IOption> = GroupBase<IOption>> =\n readonly ( IOption | Group )[];\n\n/**\n * Props for the Select component\n */\nexport interface ISelectProps<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n> extends Omit<\n ReactSelectProps<IOption, IsMulti, Group>,\n // `inputValue`, `onInputChange` and `isSearchable` are intentionally omitted: this component\n // owns an internal search box (see `searchPlaceholder`) and controls react-select\'s inputValue\n // itself, so these react-select props would silently no-op if forwarded.\n // `isLoading` and `filterOption` are omitted and re-declared below (not forwarded to react-select).\n // `tabSelectsValue` is omitted because Tab commits the multi-select draft and leaves: selecting the\n // focused option on the way out would toggle a value the user never chose.\n "options" | "value" | "className" | "inputValue" | "onInputChange" | "isSearchable" | "isLoading"\n | "filterOption" | "tabSelectsValue"\n > {\n /** Unique id for the select input */\n id?: string;\n /** Custom className for wrapper */\n className?: string;\n /** Label displayed above select */\n label?: ReactNode;\n /** Select size variant */\n size?: TSelectSize;\n /** Options or groups to render. Ignored (dev warning) when `loadOptions` is set \u2014 seed with `initialOptions` instead. */\n options?: ReactSelectProps<IOption, IsMulti, Group>["options"];\n /** Current value of the select */\n value?: ReactSelectProps<IOption, IsMulti, Group>["value"];\n /** Helper text displayed below */\n helperText?: ReactNode;\n /** Display error styling */\n error?: boolean;\n /** Disable the select */\n disabled?: boolean;\n /** Enable creatable select */\n creatable?: boolean;\n /** Field touched state */\n touched?: boolean;\n /** Max number of visible values in multi */\n maxVisibleValues?: number;\n /** Label for truncated values */\n maxVisibleValuesMsg?: string;\n /** Custom footer in menu */\n menuFooter?: ReactNode;\n /** Prefix icon for the control */\n prefixIcon?: TIconType | ReactNode;\n /** Suffix icon for the control */\n suffixIcon?: TIconType | ReactNode;\n /**\n * Renders the search input inside the dropdown. With `false` the menu opens straight onto the option\n * list and the control keeps the whole keyboard model: arrows and PageUp/PageDown move the focused\n * option, Home/End jump to its ends, Enter or Space selects, Escape closes and discards the\n * multi-select draft, Tab commits it. Space and Home/End work only in this mode \u2014 with a search input\n * on screen they belong to the text field. The reload button is independent of this and still renders\n * when `onReload` / `showReloadButton` is set.\n * @default true\n */\n searchable?: boolean;\n /** Placeholder text for the search input inside the dropdown. Ignored when `searchable={false}`. */\n searchPlaceholder?: string;\n /** Tooltip for the select reload button. */\n reloadTooltip?: string;\n /** The reload button is shown when this is provided. Fired when the reload button is clicked. */\n onReload?: () => void;\n /** Spins the select reload button. */\n isReloading?: boolean;\n /** Seeds/re-syncs dropdown search; semi-controlled \u2014 pair with onFilterChange. Applies in both modes. */\n filterValue?: string;\n /**\n * Debounced search-query callback; also called with "" when the component clears search.\n *\n * Without `loadOptions`: switches off local filtering \u2014 `options` is treated as already filtered\n * for the query \u2014 and the fetch, loading state, and response ordering are the consumer\'s\n * responsibility.\n *\n * With `loadOptions`: notification-only, for analytics or `filterValue` syncing.\n */\n onFilterChange?: ( query: string ) => void;\n /** Debounce for the search query, in both sync and `loadOptions` mode. Set to 0 to disable. @default 300 */\n filterDebounceMs?: number;\n /** Replaces option list with loader. OR-ed with the loader\'s own state, so it still applies in async mode. @default false */\n isLoading?: boolean;\n /**\n * Custom client-side match, replacing the shared `matchesQuery` default.\n *\n * @deprecated Use `onFilterChange` instead, which does the same job without a second filtering axis:\n * it hands you the query and treats `options` as already filtered, so your predicate lives in your own\n * `useMemo` rather than in a react-select callback. Pair with `filterDebounceMs={0}` to keep filtering\n * synchronous. Ignored entirely when filtering is already delegated (`onFilterChange`/`loadOptions`),\n * and scheduled for removal in the next major.\n *\n * ```tsx\n * const visible = useMemo(() => all.filter(( o ) => myMatch( o, query )), [ all, query ]);\n * <Select options={visible} onFilterChange={setQuery} filterDebounceMs={0} />\n * ```\n */\n filterOption?: ReactSelectProps<IOption, IsMulti, Group>["filterOption"];\n\n /**\n * Server-side option source. When provided, `Select` owns the option list, the request lifecycle and\n * the loading state; `options` is ignored (dev warning) and `onFilterChange` becomes\n * notification-only. Responsible for mapping the payload to `IOption` \u2014 envelopes and domain\n * filtering are the consumer\'s business. Options are stored exactly as returned, so extra fields\n * survive. A fresh inline arrow is fine: the loader is read through a ref.\n *\n * Page one only: `cursor` / `hasMore` / `total` in the result are ignored.\n */\n loadOptions?: TSelectLoadOptions;\n /**\n * Seed rows for a list you already have \u2014 an SSR payload, a route loader, a warm cache. They paint on the\n * first frame, so there is no loader to sit through, and they stay put while the baseline fetch revalidates\n * over them. They do not suppress that fetch: pair with `prefetch="never"` if the seed is the whole list\n * until the user types. A *search* replaces them, since seed rows are not results for a query; clearing it\n * brings them back until a fetched baseline lands. Async mode only \u2014 ignored (dev warning) without\n * `loadOptions`, where the rows belong in `options`.\n */\n initialOptions?: readonly IOption[];\n /**\n * When to fetch the unfiltered baseline.\n * - `"open"` \u2014 on first menu open. Right for forms with several server-filtered Selects, where paying\n * for menus the user may never open is the worse trade.\n * - `"mount"` \u2014 at render, before any interaction. Use when the list is near-certain to be needed and\n * a visible-but-empty Select would read as broken.\n * - `"never"` \u2014 no baseline at all; fetch only once the user types. For heavy lists.\n *\n * Async mode only \u2014 ignored (dev warning) without `loadOptions`, where `options` are already on screen\n * and there is nothing to fetch.\n * @default "open"\n */\n prefetch?: TPrefetch;\n /** Clearing the search revalidates the cached baseline instead of just restoring it. Costs one request per menu close. @default false */\n refetchOnClear?: boolean;\n /**\n * Identity of the option set, for dependent selects. When it changes, cached results are dropped and\n * the list is repopulated \u2014 immediately if the menu is open, otherwise on next open. Compose several\n * parents into one scalar: ``optionsKey={`${domainId}|${accessType}`}``. Does NOT clear the selection.\n */\n optionsKey?: string | number;\n /** Shown in the menu when `loadOptions` rejects. @default "Couldn\'t load options." */\n loadErrorMessage?: ReactNode;\n /** Shows the menu\'s reload button in async mode, wired to re-run the current query. @default false */\n showReloadButton?: boolean;\n /** Notified when a load rejects (the component renders `loadErrorMessage` and swallows it). */\n onLoadError?: ( error: unknown ) => void;\n}\n\n/**\n * Per-render option config for the SelectOption component. react-select keys custom components by\n * reference and remounts them whenever that reference changes; the `customComponents` object in\n * select.tsx is rebuilt every render. Feeding these live values through context (rather than a\n * closure inside a freshly-created Option) lets SelectOption keep a stable module-level identity,\n * so react-select re-renders it in place instead of remounting - which is what keeps the\n * `useIsTruncated` measurement (and the hover-expand affordance) from flickering.\n */\nexport interface ISelectOptionContext {\n /**\n * In-progress multi-select draft, as a value Set. Drives checkboxes / Select All while the\n * committed value drives the control. A Set rather than the array: every option row tests its own\n * membership, so an array would make one menu render O(options x draft).\n */\n draftValues?: ReadonlySet<IOption["value"]>;\n /**\n * Checked state of the Select All row: every option the query currently leaves VISIBLE is in the\n * draft. Resolved on the Select, which is the only place that knows the visible set \u2014 react-select\n * hands each option its unfiltered `options` array, so deriving it here would report unchecked\n * even with every visible row ticked.\n */\n areAllSelected?: boolean;\n /** Toggle a single option in the multi-select draft. */\n onToggleDraftOption?: ( option: IOption ) => void;\n /** Toggle Select All / Deselect All on the multi-select draft (shared with the keyboard path). */\n onSelectAll?: () => void;\n /** tv() class for the label wrapper. */\n optionLabelWrapClass: string;\n /** tv() class for the (truncating) label. */\n optionLabelClass: string;\n /** tv() class for the hover/focus full-text overlay. */\n optionOverlayClass: string;\n /**\n * Latest input modality, shared across every option. The full-text overlay follows the pointer\n * (local `isHovered`) while the user is using the mouse, and react-select\'s `isFocused` while\n * they\'re navigating by keyboard. Without this, react-select\'s `isFocused` - which lingers on the\n * last-focused option after the pointer leaves, and is also set by mouse hover - keeps an\n * overlay visible after the mouse has moved away (and shows two at once mid-transition).\n *\n * State on the Select, not a shared ref: this decides what an option renders, and writing a ref\n * schedules no re-render. Setting the mode it already holds is a no-op React bails out of, so\n * hovering along a list costs a render only at a genuine modality switch.\n */\n interactionMode: TSelectInteractionMode;\n /** Records the modality the user just used. See {@link ISelectOptionContext.interactionMode}. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\n/**\n * Per-instance menu config via context (keeps SelectMenu\'s stable identity).\n */\nexport interface ISelectMenuContext {\n /** Current search text (controls react-select\'s inputValue). */\n filterQuery: string;\n /** Updates the query and (debounced) notifies `onFilterChange`. */\n onFilterInput: ( e: ChangeEvent<HTMLInputElement> ) => void;\n /** Marks Backspace/Delete held; defer debounce until keyup. */\n onFilterKeyDown: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On Backspace/Delete release, starts the deferred debounce. */\n onFilterKeyUp: ( e: KeyboardEvent<HTMLInputElement> ) => void;\n /** On blur during hold, flush deferred debounce. */\n onFilterBlur: ( e: FocusEvent<HTMLInputElement> ) => void;\n /** Renders the in-dropdown search input; the reload button is independent of it. */\n searchable: boolean;\n /** Placeholder for the search input. */\n searchPlaceholder: string;\n /** Optional custom footer rendered below the option list. */\n menuFooter?: ReactNode;\n /** Close the menu, discarding the multi-select draft. */\n closeMenu: () => void;\n /** Commit the multi-select draft, then close. */\n commitAndClose: () => void;\n /** tv() class for the search container. */\n searchContainerClass: string;\n /** tv() class for the search input. */\n searchInputClass: string;\n /** tv() class for the loader shown in place of the option list. */\n loaderClass: string;\n /** Replaces the option list with the loader. */\n isLoading?: boolean;\n /** Replaces the option list when set (async load failure). */\n loadError?: ReactNode;\n /** tv() class for the error container. */\n errorClass: string;\n /** Ref to the search input; focused when the menu opens. */\n searchInputRef: RefObject<HTMLInputElement>;\n /** Captures the menu\'s (possibly portaled) DOM node for the outside-click check. */\n menuNodeRef: MutableRefObject<HTMLDivElement | null>;\n /** Ref to the component wrapper, used to reach react-select\'s hidden control input. */\n containerRef: RefObject<HTMLDivElement>;\n /** Shown when provided; fired on reload-button click. */\n onReload?: () => void;\n /** Spins/disables the reload button. */\n isReloading?: boolean;\n /** Reload-button tooltip / aria-label. */\n reloadTooltip?: string;\n /** Records the input modality (see {@link ISelectOptionContext.interactionMode}); set to "keyboard" here. */\n onInteractionMode: ( mode: TSelectInteractionMode ) => void;\n}\n\nexport interface IOptionLabelOverlayProps {\n anchorRef: RefObject<HTMLElement>;\n className: string;\n children: ReactNode;\n}\n\nexport interface ITruncatedMultiValueProps {\n /** The plain-text label, used as the Tooltip title. */\n label: string;\n /** react-select\'s rendered chip (MultiValueContainer + label + remove). */\n chip: ReactElement;\n}\n\nexport interface ISelectComponentsConfig {\n prefixIcon?: TIconType | ReactNode;\n suffixIcon?: TIconType | ReactNode;\n maxVisibleValues: number;\n maxVisibleValuesMsg?: string;\n disabled: boolean;\n}\n'
3377
3398
  },
3378
3399
  {
3379
3400
  "name": "selectVariants.ts",
@@ -3407,10 +3428,15 @@ export const selectVariants = tv({
3407
3428
  error: {
3408
3429
  true: { helperText: "text-error-700 dark:text-error-400" },
3409
3430
  false: { helperText: "text-secondary-400 dark:text-secondary-200" }
3431
+ },
3432
+ // With the search input gone the strip holds only the reload button, which belongs at its end.
3433
+ searchable: {
3434
+ false: { menuSearchContainer: "justify-end" }
3410
3435
  }
3411
3436
  },
3412
3437
  defaultVariants: {
3413
- error: false
3438
+ error: false,
3439
+ searchable: true
3414
3440
  }
3415
3441
  });
3416
3442
  `
@@ -3433,20 +3459,11 @@ import {
3433
3459
  type MenuProps
3434
3460
  } from "react-select";
3435
3461
 
3436
- import { keyboardKeys } from "@constants";
3437
3462
  import { ReloadButton } from "../button/reloadButton";
3438
3463
  import { Loader } from "../loader";
3464
+ import { focusMenuInput, getControlInput, handleMenuKey } from "./selectKeyboard";
3439
3465
  import { type IOption, type ISelectMenuContext } from "./types";
3440
3466
 
3441
- // Forwarded to react-select's hidden input so option nav works while focus is in the search box.
3442
- const forwardedKeys = new Set([
3443
- keyboardKeys.arrowDown,
3444
- keyboardKeys.arrowUp,
3445
- keyboardKeys.enter,
3446
- keyboardKeys.pageDown,
3447
- keyboardKeys.pageUp
3448
- ]);
3449
-
3450
3467
  export const SelectMenuContext = createContext<ISelectMenuContext | null>( null );
3451
3468
 
3452
3469
  /**
@@ -3461,10 +3478,13 @@ export function SelectMenu<
3461
3478
  const ctx = useContext( SelectMenuContext );
3462
3479
  const searchInputRef = ctx?.searchInputRef ?? null;
3463
3480
  const menuNodeRef = ctx?.menuNodeRef ?? null;
3481
+ const containerRef = ctx?.containerRef ?? null;
3464
3482
 
3465
3483
  useEffect(() => {
3466
- searchInputRef?.current?.focus();
3467
- }, [searchInputRef]);
3484
+ if ( searchInputRef && containerRef ) {
3485
+ focusMenuInput({ searchInputRef, containerRef });
3486
+ }
3487
+ }, [ searchInputRef, containerRef ]);
3468
3488
 
3469
3489
  // Captures the menu DOM for the outside-click check while still handing the node to react-select.
3470
3490
  // MenuPlacer passes a ref OBJECT, not a callback; dropping it strands its layout effect on
@@ -3487,6 +3507,7 @@ export function SelectMenu<
3487
3507
  }
3488
3508
 
3489
3509
  const {
3510
+ searchable,
3490
3511
  filterQuery,
3491
3512
  onFilterInput,
3492
3513
  onFilterKeyDown,
@@ -3494,56 +3515,36 @@ export function SelectMenu<
3494
3515
  onFilterBlur,
3495
3516
  searchPlaceholder,
3496
3517
  menuFooter,
3497
- closeMenu,
3498
- commitAndClose,
3499
3518
  searchContainerClass,
3500
3519
  searchInputClass,
3501
3520
  loaderClass,
3502
3521
  isLoading,
3503
3522
  loadError,
3504
3523
  errorClass,
3505
- containerRef,
3506
3524
  onReload,
3507
3525
  isReloading,
3508
- reloadTooltip,
3509
- onInteractionMode
3526
+ reloadTooltip
3510
3527
  } = ctx;
3511
3528
 
3512
3529
  const handleSearchKeyDown = ( e: KeyboardEvent<HTMLInputElement> ) => {
3513
3530
  onFilterKeyDown( e );
3514
3531
  // Stop bubbling to SelectContainer so Backspace doesn't remove multi-select values.
3515
3532
  e.stopPropagation();
3516
- if ( e.key === keyboardKeys.escape ) {
3517
- e.preventDefault();
3518
- closeMenu();
3519
- // Refocus control after close (search input unmounts).
3520
- containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" )?.focus();
3533
+ if ( handleMenuKey( e, ctx ) !== "navigate" ) {
3521
3534
  return;
3522
3535
  }
3523
- // Tab commits like an outside click; Escape above still cancels.
3524
- if ( e.key === keyboardKeys.tab ) {
3525
- commitAndClose();
3526
- return;
3527
- }
3528
- if ( forwardedKeys.has( e.key )) {
3529
- // Block nav while loading OR while the error has taken the list's place \u2014 react-select still
3530
- // tracks the previous focusedOption, so Enter would select a row that has left the screen.
3531
- if ( isLoading || loadError ) {
3532
- e.preventDefault();
3533
- return;
3534
- }
3535
- onInteractionMode( "keyboard" );
3536
- const rsInput = containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" );
3537
- if ( rsInput ) {
3538
- rsInput.dispatchEvent(
3539
- new KeyboardEvent( "keydown", { key: e.key, code: e.code, bubbles: true, cancelable: true })
3540
- );
3541
- e.preventDefault();
3542
- }
3536
+ // Focus sits in the search box, so react-select's container handler never sees the key: relay it
3537
+ // to the control input it listens behind.
3538
+ const rsInput = getControlInput( ctx.containerRef );
3539
+ if ( rsInput ) {
3540
+ rsInput.dispatchEvent(
3541
+ new KeyboardEvent( "keydown", { key: e.key, code: e.code, bubbles: true, cancelable: true })
3542
+ );
3543
+ e.preventDefault();
3543
3544
  }
3544
3545
  };
3545
3546
 
3546
- // Override react-select's onMenuMouseDown so the search field can keep focus.
3547
+ // Override react-select's onMenuMouseDown so the focused input keeps focus.
3547
3548
  const handleMenuMouseDown = ( e: MouseEvent<HTMLDivElement> ) => {
3548
3549
  if ( e.button !== 0 ) {
3549
3550
  return;
@@ -3553,7 +3554,7 @@ export function SelectMenu<
3553
3554
  return;
3554
3555
  }
3555
3556
  e.preventDefault();
3556
- searchInputRef?.current?.focus();
3557
+ focusMenuInput( ctx );
3557
3558
  };
3558
3559
 
3559
3560
  return (
@@ -3562,21 +3563,28 @@ export function SelectMenu<
3562
3563
  innerRef={setMenuRef}
3563
3564
  innerProps={{ ...innerProps, onMouseDown: handleMenuMouseDown }}
3564
3565
  >
3565
- <div className={searchContainerClass}>
3566
- <input
3567
- ref={searchInputRef}
3568
- type="text"
3569
- value={filterQuery}
3570
- onChange={onFilterInput}
3571
- onKeyDown={handleSearchKeyDown}
3572
- onKeyUp={onFilterKeyUp}
3573
- onBlur={onFilterBlur}
3574
- placeholder={searchPlaceholder}
3575
- className={searchInputClass}
3576
- aria-label="Search options"
3577
- />
3578
- <ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />
3579
- </div>
3566
+ {/* The strip carries the search input, the reload button, or both. \`onReload\` is the resolved
3567
+ control (an async load failure forces it on), so it is the same truth ReloadButton reads and
3568
+ the two can never disagree about whether the strip has anything to hold. */}
3569
+ {( searchable || typeof onReload === "function" ) && (
3570
+ <div className={searchContainerClass}>
3571
+ {searchable && (
3572
+ <input
3573
+ ref={searchInputRef}
3574
+ type="text"
3575
+ value={filterQuery}
3576
+ onChange={onFilterInput}
3577
+ onKeyDown={handleSearchKeyDown}
3578
+ onKeyUp={onFilterKeyUp}
3579
+ onBlur={onFilterBlur}
3580
+ placeholder={searchPlaceholder}
3581
+ className={searchInputClass}
3582
+ aria-label="Search options"
3583
+ />
3584
+ )}
3585
+ <ReloadButton onReload={onReload} isReloading={isReloading} tooltip={reloadTooltip} />
3586
+ </div>
3587
+ )}
3580
3588
  {/* Loader, then error, then rows. All three are mutually exclusive by construction, so no two
3581
3589
  live regions ever coexist. The first two replace the list so stale rows can't be clicked;
3582
3590
  that also hides "No options". role="alert" on the error is deliberately assertive \u2014 the
@@ -3594,15 +3602,98 @@ export function SelectMenu<
3594
3602
  }
3595
3603
 
3596
3604
  SelectMenu.displayName = "SelectMenu";
3605
+ `
3606
+ },
3607
+ {
3608
+ "name": "selectKeyboard.ts",
3609
+ "content": `import { type KeyboardEvent, type RefObject } from "react";
3610
+
3611
+ import { keyboardKeys } from "@constants";
3612
+ import { type ISelectMenuContext } from "./types";
3613
+
3614
+ // The keys react-select's own option navigation acts on wherever focus sits.
3615
+ const menuNavKeys = new Set([
3616
+ keyboardKeys.arrowDown,
3617
+ keyboardKeys.arrowUp,
3618
+ keyboardKeys.enter,
3619
+ keyboardKeys.pageDown,
3620
+ keyboardKeys.pageUp
3621
+ ]);
3622
+
3623
+ // react-select navigates on these too, but only once no search box owns the typing: in a text field
3624
+ // Space is a character and Home/End are caret moves, and the field keeps them to itself.
3625
+ const controlNavKeys = new Set([
3626
+ keyboardKeys.space,
3627
+ keyboardKeys.home,
3628
+ keyboardKeys.end
3629
+ ]);
3630
+
3631
+ /** What the shared handler leaves for its caller to do. */
3632
+ export type TSelectKeyOutcome = "handled" | "navigate" | "ignored";
3633
+
3634
+ /** The slice of the menu context the shared handler reads, so callers can pass the context whole. */
3635
+ export type TSelectKeyContext = Pick<
3636
+ ISelectMenuContext,
3637
+ "closeMenu" | "commitAndClose" | "containerRef" | "searchable" | "searchInputRef" | "isLoading" | "loadError" |
3638
+ "onInteractionMode"
3639
+ >;
3640
+
3641
+ /** The refs that locate the two inputs focus can live in. */
3642
+ export type TSelectFocusRefs = Pick<ISelectMenuContext, "searchInputRef" | "containerRef">;
3643
+
3644
+ /**
3645
+ * react-select's hidden control input \u2014 the focus holder whenever the search box is absent. Queried
3646
+ * fresh every time: react-select rebuilds this node whenever the custom Input's identity changes.
3647
+ */
3648
+ export function getControlInput( containerRef: RefObject<HTMLDivElement> ): HTMLInputElement | null {
3649
+ return containerRef.current?.querySelector<HTMLInputElement>( ".select__control input" ) ?? null;
3650
+ }
3651
+
3652
+ /** Focus follows the search box while it exists, and the control input otherwise. */
3653
+ export function focusMenuInput({ searchInputRef, containerRef }: TSelectFocusRefs ): void {
3654
+ ( searchInputRef.current ?? getControlInput( containerRef ))?.focus();
3655
+ }
3656
+
3657
+ /**
3658
+ * The open menu's keyboard model, shared by the search box and by the control. Escape discards the
3659
+ * draft and closes, Tab commits it and closes, and navigation keys are refused while the loader or
3660
+ * the error notice stands in for the list. "navigate" means react-select's own option navigation
3661
+ * still has to see the key.
3662
+ */
3663
+ export function handleMenuKey( e: KeyboardEvent<Element>, ctx: TSelectKeyContext ): TSelectKeyOutcome {
3664
+ if ( e.key === keyboardKeys.escape ) {
3665
+ e.preventDefault();
3666
+ ctx.closeMenu();
3667
+ // The search box unmounts with the menu, so the control input is the only landing place.
3668
+ getControlInput( ctx.containerRef )?.focus();
3669
+ return "handled";
3670
+ }
3671
+ // Tab commits like an outside click; Escape above still cancels.
3672
+ if ( e.key === keyboardKeys.tab ) {
3673
+ ctx.commitAndClose();
3674
+ return "handled";
3675
+ }
3676
+ if ( !menuNavKeys.has( e.key ) && !( !ctx.searchable && controlNavKeys.has( e.key ))) {
3677
+ return "ignored";
3678
+ }
3679
+ // Block nav while loading OR while the error has taken the list's place \u2014 react-select still
3680
+ // tracks the previous focusedOption, so Enter would select a row that has left the screen.
3681
+ if ( ctx.isLoading || ctx.loadError ) {
3682
+ e.preventDefault();
3683
+ return "handled";
3684
+ }
3685
+ ctx.onInteractionMode( "keyboard" );
3686
+ return "navigate";
3687
+ }
3597
3688
  `
3598
3689
  },
3599
3690
  {
3600
3691
  "name": "selectComponents.tsx",
3601
- "content": 'import * as React from "react";\nimport { type ReactElement } from "react";\nimport {\n components,\n type GroupBase,\n type OptionProps,\n type MultiValueProps,\n type MultiValueRemoveProps,\n type DropdownIndicatorProps,\n type ValueContainerProps,\n type InputProps\n} from "react-select";\nimport { cx } from "tailwind-variants";\n\nimport { keyboardKeys } from "@constants";\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { Tooltip } from "../tooltip";\nimport { ADPIcon, iconList, type TIconType } from "../adpIcon";\nimport { SELECT_ALL_VALUE } from "./utils";\nimport {\n type IOption,\n type ISelectOptionContext,\n type IOptionLabelOverlayProps,\n type ITruncatedMultiValueProps,\n type ISelectComponentsConfig\n} from "./types";\n\n// One shared identity for "no draft", so a single-select option never allocates one per render.\nconst EMPTY_DRAFT: ReadonlySet<IOption["value"]> = new Set();\n\nexport const SelectOptionContext = React.createContext<ISelectOptionContext>({\n optionLabelWrapClass: "",\n optionLabelClass: "",\n optionOverlayClass: "",\n interactionMode: "pointer",\n onInteractionMode: () => {}\n});\n\n/**\n * The full-text overlay shown for a truncated option on hover/focus. Rendered `position:fixed`\n * and positioned from the label wrapper\'s viewport rect, so it escapes the scrollable menu\'s\n * overflow clipping (no ancestor establishes a containing block via transform/filter/etc.) - a\n * plain absolute overlay stays trapped inside the menu and gets clipped at whichever edge it\n * grows toward. It stays in the option\'s DOM subtree (not portaled) so it still inherits the\n * theme (`.dark`) and RTL context. The height is measured at the final width, then the top is\n * clamped so the box never spills past the viewport bottom (it shifts up for the last options).\n * pointer-events:none keeps the hover on the row beneath it, so it can\'t cause a hover flicker.\n */\nfunction OptionLabelOverlay({ anchorRef, className, children }: IOptionLabelOverlayProps ): ReactElement {\n const overlayRef = React.useRef<HTMLDivElement>( null );\n const [ style, setStyle ] = React.useState<React.CSSProperties | null>( null );\n\n React.useLayoutEffect(() => {\n const anchor = anchorRef.current;\n const overlay = overlayRef.current;\n if ( !anchor || !overlay ) {\n return undefined;\n }\n const position = () => {\n const rect = anchor.getBoundingClientRect();\n // Size the overlay to the label width first, so its wrapped height is measured correctly.\n overlay.style.position = "fixed";\n overlay.style.left = `${rect.left}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.top = `${rect.top}px`;\n overlay.style.visibility = "hidden";\n const margin = 8;\n const maxTop = window.innerHeight - margin - overlay.offsetHeight;\n const top = rect.top > maxTop ? Math.max( margin, maxTop ) : rect.top;\n setStyle({ position: "fixed", left: rect.left, top, width: rect.width, zIndex: 9999 });\n };\n position();\n // A position:fixed box doesn\'t follow its anchor, so re-pin it whenever the anchor moves:\n // scrolling the menu (capture=true catches the scrollable ancestor, whose scroll doesn\'t\n // bubble) or a viewport resize. Without this the overlay floats away from its option row.\n window.addEventListener( "scroll", position, true );\n window.addEventListener( "resize", position );\n return () => {\n window.removeEventListener( "scroll", position, true );\n window.removeEventListener( "resize", position );\n };\n }, [ anchorRef, children ]);\n\n return (\n <div\n ref={overlayRef}\n className={className}\n style={style ?? { position: "fixed", top: 0, left: 0, visibility: "hidden" }}\n >\n {children}\n </div>\n );\n}\n\n/**\n * A single dropdown option (handles Select All, multi-select checkboxes, and the selected\n * checkmark). Defined at module level with a stable identity so react-select never remounts it;\n * live selection state arrives via {@link SelectOptionContext}. The label truncates to one line\n * and, only when genuinely clipped (`useIsTruncated`), shows its full text on hover/focus in a\n * `position:fixed` overlay - see {@link OptionLabelOverlay}.\n */\nexport function SelectOption<\n IsMulti extends boolean = boolean,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( props: OptionProps<IOption, IsMulti, Group> ): ReactElement {\n const {\n draftValues,\n areAllSelected,\n onToggleDraftOption,\n onSelectAll,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode\n } = React.useContext( SelectOptionContext );\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n const [ isHovered, setIsHovered ] = React.useState( false );\n\n const optionStyles = props.getStyles( "option", props );\n const isSelectAllRow = props.data.value === SELECT_ALL_VALUE;\n // Multi-select selection is driven by the in-progress draft (not react-select\'s value, which is\n // the committed selection feeding the control). Single-select keeps react-select\'s own state.\n const draft = draftValues ?? EMPTY_DRAFT;\n const optionSelected = props.isMulti\n ? ( isSelectAllRow ? Boolean( areAllSelected ) : draft.has( props.data.value ))\n : props.isSelected;\n\n const baseClassName = props.cx(\n {\n option: true,\n "option--is-disabled": props.isDisabled,\n "option--is-focused": props.isFocused,\n "option--is-selected": optionSelected\n },\n props.className\n );\n\n // Toggle the draft for multi-select (mouse path). stopPropagation keeps react-select from also\n // firing its own onChange against the committed value.\n const handleToggle = ( e: React.SyntheticEvent ) => {\n e.stopPropagation();\n if ( props.isDisabled || props.data.isFixed ) {\n return;\n }\n if ( isSelectAllRow ) {\n onSelectAll?.();\n } else {\n onToggleDraftOption?.( props.data );\n }\n };\n\n // react-select\'s own `state.isSelected` reflects the *committed* value, not the in-progress\n // multi-select draft - so it never lights up a checked-but-uncommitted row, and the inline\n // `style` from `optionStyles` can\'t respond to that anyway (nested selectors like `.dark &`\n // are dropped when applied as a plain `style` attribute). Drive the background entirely from\n // our own `optionSelected` (checked-aware for multi, same as isSelected for single) via\n // classes instead, so it\'s consistent for both select modes and both themes.\n const bgClass = optionSelected\n ? "!bg-frostBlue dark:!bg-secondary-700"\n : props.isFocused\n ? "!bg-frostBlue dark:!bg-secondary-800"\n : "!bg-transparent dark:!bg-iridium";\n\n // Show the full-text overlay only for genuinely-clipped labels. Which signal drives it depends on\n // the current input modality: the pointer path uses local `isHovered` (which clears on\n // mouseleave, so only the row actually under the cursor shows, never a stale one); the keyboard\n // path uses react-select\'s `isFocused`. Honoring `isFocused` unconditionally would leave the\n // overlay stuck on the last-focused row after the mouse moved off it (react-select keeps that\n // focus, and sets it on hover too), which is the "both overlays stay visible" bug.\n const showOverlay = isLabelTruncated &&\n ( interactionMode === "keyboard" ? props.isFocused : isHovered );\n\n return (\n <div\n style={optionStyles as React.CSSProperties}\n onMouseEnter={() => {\n onInteractionMode( "pointer" );\n setIsHovered( true );\n }}\n onMouseLeave={() => setIsHovered( false )}\n className={cx(\n baseClassName,\n "select__custom-option",\n bgClass,\n props.isMulti && "select__custom-option--is-multi"\n )}\n >\n {props.isMulti && (\n <Checkbox\n className="me-2"\n onChange={handleToggle}\n checked={optionSelected}\n disabled={props.isDisabled || props.data.isFixed}\n />\n )}\n <components.Option\n {...props}\n className={cx( "!p-0 !bg-transparent", props.isMulti && "flex-1 min-w-0" )}\n innerProps={{\n ...props.innerProps,\n ...( props.isMulti ? { onClick: handleToggle } : {})\n }}\n >\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{props.children}</span>\n </span>\n {showOverlay && (\n <OptionLabelOverlay anchorRef={labelWrapRef} className={optionOverlayClass}>\n {props.children}\n </OptionLabelOverlay>\n )}\n </components.Option>\n </div>\n );\n}\n\nSelectOption.displayName = "SelectOption";\n\n/**\n * Wraps a multi-select chip so its full label is surfaced in a Tooltip, but only when the chip\'s\n * label is actually clipped by react-select\'s `maxWidth` (measured against the rendered\n * `.select__multi-value__label`, whose class comes from `classNamePrefix="select"`). The Tooltip\n * always wraps the chip and is gated via its `canOpen` prop rather than being swapped in and out,\n * so the measured label node stays mounted and the ResizeObserver never loses its target. The\n * `contents` wrapper carries no box of its own, so the chip lays out exactly as it would\n * unwrapped; it exists only to scope the label lookup to this chip.\n */\nfunction TruncatedMultiValue({ label, chip }: ITruncatedMultiValueProps ): ReactElement {\n const wrapRef = React.useRef<HTMLSpanElement>( null );\n const [ isTruncated, setIsTruncated ] = React.useState( false );\n\n React.useLayoutEffect(() => {\n const labelEl = wrapRef.current?.querySelector<HTMLElement>( ".select__multi-value__label" ) ?? null;\n if ( !labelEl ) {\n return undefined;\n }\n const measure = () => setIsTruncated( labelEl.scrollWidth > labelEl.clientWidth );\n measure();\n const observer = new ResizeObserver( measure );\n observer.observe( labelEl );\n return () => observer.disconnect();\n }, [label]);\n\n return (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={label}\n trigger={<span ref={wrapRef} className="contents">{chip}</span>}\n />\n );\n}\n\nTruncatedMultiValue.displayName = "TruncatedMultiValue";\n\n/**\n * Builds the react-select custom components that are independent of the in-dropdown\n * search/focus machinery (kept in select.tsx) and of per-option selection state (the Option is\n * the stable {@link SelectOption} above). These are stateless, so recreating them per render is\n * harmless - react-select only remounts the focus-sensitive Menu component.\n */\nexport function createSelectComponents<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( config: ISelectComponentsConfig ) {\n const {\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n } = config;\n\n // Dropdown indicator icon\n const DropdownIndicator = ( props: DropdownIndicatorProps<IOption, IsMulti, Group> ) => {\n const {\n selectProps: { menuIsOpen }\n } = props;\n return (\n <ADPIcon size="xs" icon={menuIsOpen ? iconList.upArrow : iconList.downArrow} />\n );\n };\n\n // Custom value container to handle prefix/suffix icons and truncation\n const ValueContainer = (\n { children, ...props }: ValueContainerProps<IOption, IsMulti, Group>\n ) => {\n const values = props.getValue();\n // Split the chips (which carry `props.data`) from the search input in a single pass.\n const withData: React.ReactNode[] = [];\n const inputChild: React.ReactNode[] = [];\n React.Children.toArray( children ).forEach(( c ) => {\n const target = ( c as ReactElement ).props.data ? withData : inputChild;\n target.push( c );\n });\n return (\n <>\n {prefixIcon &&\n ( typeof prefixIcon === "string" ? (\n <ADPIcon icon={prefixIcon as TIconType} size="xs" />\n ) : (\n prefixIcon\n ))}\n <components.ValueContainer {...props}>\n {withData}\n {values.length > maxVisibleValues && (\n <div\n className={cx(\n "text-secondary-400 dark:text-secondary-300",\n "select__truncated-multi-value",\n disabled && "select__truncated-multi-value--is-disabled"\n )}\n >\n +{values.length - maxVisibleValues}{" "}\n {maxVisibleValuesMsg ?? "More"}\n </div>\n )}\n {inputChild}\n </components.ValueContainer>\n {suffixIcon &&\n ( typeof suffixIcon === "string" ? (\n <ADPIcon icon={suffixIcon as TIconType} size="xs" />\n ) : (\n suffixIcon\n ))}\n </>\n );\n };\n\n // Hide extra MultiValue components\n const MultiValue = ( props: MultiValueProps<IOption> ) => {\n if ( props.index !== undefined && props.index >= maxVisibleValues ) {\n return null;\n }\n const chip = <components.MultiValue {...props} />;\n // Surface the full label in a Tooltip, but only when the chip\'s label is actually truncated\n // (see TruncatedMultiValue). Non-string labels have no text to show, so render the chip as-is.\n if ( typeof props.data.label !== "string" ) {\n return chip;\n }\n return <TruncatedMultiValue label={props.data.label} chip={chip} />;\n };\n\n // react-select\'s default remove control is a mouse-only `<div role="button">` with no tabIndex,\n // so a pill\'s "x" can never be reached or activated by keyboard. Make it a real tab stop\n // (per chip, regardless of truncation) that removes on Enter/Space. stopPropagation keeps the\n // key from bubbling to the control, which would otherwise treat Enter/Space as open/select.\n const MultiValueRemove = ( props: MultiValueRemoveProps<IOption, IsMulti, Group> ) => {\n const { onClick } = props.innerProps;\n return (\n <components.MultiValueRemove\n {...props}\n innerProps={{\n ...props.innerProps,\n tabIndex: disabled ? -1 : 0,\n onKeyDown: ( e: React.KeyboardEvent ) => {\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n e.stopPropagation();\n onClick?.( e as unknown as React.MouseEvent<HTMLDivElement> );\n }\n }\n }}\n />\n );\n };\n\n /*\n * The control input must remain present and focusable so react-select\'s click-to-open\n * flow works (onControlMouseDown \u2192 focusInput \u2192 onInputFocus \u2192 openMenu). We make it\n * read-only and visually hidden so all actual typing happens in the dropdown search input.\n */\n const Input = ( props: InputProps<IOption, IsMulti, Group> ) => {\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n if ( e.key === keyboardKeys.backspace ) {\n const vals = props.getValue();\n if ( vals.length > maxVisibleValues ) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n return (\n <components.Input\n {...props}\n readOnly\n onKeyDown={handleKeyDown}\n style={{ ...( props.style as React.CSSProperties ), opacity: 0, width: 0, position: "absolute" }}\n />\n );\n };\n\n return { DropdownIndicator, ValueContainer, MultiValue, MultiValueRemove, Input };\n}\n'
3692
+ "content": 'import * as React from "react";\nimport { type ReactElement } from "react";\nimport {\n components,\n type GroupBase,\n type OptionProps,\n type MultiValueProps,\n type MultiValueRemoveProps,\n type DropdownIndicatorProps,\n type ValueContainerProps,\n type InputProps\n} from "react-select";\nimport { cx } from "tailwind-variants";\n\nimport { keyboardKeys } from "@constants";\nimport { useIsTruncated } from "@hooks";\nimport { Checkbox } from "../checkbox";\nimport { Tooltip } from "../tooltip";\nimport { ADPIcon, iconList, type TIconType } from "../adpIcon";\nimport { isCreateOption, SELECT_ALL_VALUE } from "./utils";\nimport {\n type IOption,\n type ISelectOptionContext,\n type IOptionLabelOverlayProps,\n type ITruncatedMultiValueProps,\n type ISelectComponentsConfig\n} from "./types";\n\n// One shared identity for "no draft", so a single-select option never allocates one per render.\nconst EMPTY_DRAFT: ReadonlySet<IOption["value"]> = new Set();\n\nexport const SelectOptionContext = React.createContext<ISelectOptionContext>({\n optionLabelWrapClass: "",\n optionLabelClass: "",\n optionOverlayClass: "",\n interactionMode: "pointer",\n onInteractionMode: () => {}\n});\n\n/**\n * The full-text overlay shown for a truncated option on hover/focus. Rendered `position:fixed`\n * and positioned from the label wrapper\'s viewport rect, so it escapes the scrollable menu\'s\n * overflow clipping (no ancestor establishes a containing block via transform/filter/etc.) - a\n * plain absolute overlay stays trapped inside the menu and gets clipped at whichever edge it\n * grows toward. It stays in the option\'s DOM subtree (not portaled) so it still inherits the\n * theme (`.dark`) and RTL context. The height is measured at the final width, then the top is\n * clamped so the box never spills past the viewport bottom (it shifts up for the last options).\n * pointer-events:none keeps the hover on the row beneath it, so it can\'t cause a hover flicker.\n */\nfunction OptionLabelOverlay({ anchorRef, className, children }: IOptionLabelOverlayProps ): ReactElement {\n const overlayRef = React.useRef<HTMLDivElement>( null );\n const [ style, setStyle ] = React.useState<React.CSSProperties | null>( null );\n\n React.useLayoutEffect(() => {\n const anchor = anchorRef.current;\n const overlay = overlayRef.current;\n if ( !anchor || !overlay ) {\n return undefined;\n }\n const position = () => {\n const rect = anchor.getBoundingClientRect();\n // Size the overlay to the label width first, so its wrapped height is measured correctly.\n overlay.style.position = "fixed";\n overlay.style.left = `${rect.left}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.top = `${rect.top}px`;\n overlay.style.visibility = "hidden";\n const margin = 8;\n const maxTop = window.innerHeight - margin - overlay.offsetHeight;\n const top = rect.top > maxTop ? Math.max( margin, maxTop ) : rect.top;\n setStyle({ position: "fixed", left: rect.left, top, width: rect.width, zIndex: 9999 });\n };\n position();\n // A position:fixed box doesn\'t follow its anchor, so re-pin it whenever the anchor moves:\n // scrolling the menu (capture=true catches the scrollable ancestor, whose scroll doesn\'t\n // bubble) or a viewport resize. Without this the overlay floats away from its option row.\n window.addEventListener( "scroll", position, true );\n window.addEventListener( "resize", position );\n return () => {\n window.removeEventListener( "scroll", position, true );\n window.removeEventListener( "resize", position );\n };\n }, [ anchorRef, children ]);\n\n return (\n <div\n ref={overlayRef}\n className={className}\n style={style ?? { position: "fixed", top: 0, left: 0, visibility: "hidden" }}\n >\n {children}\n </div>\n );\n}\n\n/**\n * A single dropdown option (handles Select All, multi-select checkboxes, and the selected\n * checkmark). Defined at module level with a stable identity so react-select never remounts it;\n * live selection state arrives via {@link SelectOptionContext}. The label truncates to one line\n * and, only when genuinely clipped (`useIsTruncated`), shows its full text on hover/focus in a\n * `position:fixed` overlay - see {@link OptionLabelOverlay}.\n */\nexport function SelectOption<\n IsMulti extends boolean = boolean,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( props: OptionProps<IOption, IsMulti, Group> ): ReactElement {\n const {\n draftValues,\n areAllSelected,\n onToggleDraftOption,\n onSelectAll,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode\n } = React.useContext( SelectOptionContext );\n const { ref: labelRef, containerRef: labelWrapRef, isTruncated: isLabelTruncated } = useIsTruncated<HTMLSpanElement>();\n const [ isHovered, setIsHovered ] = React.useState( false );\n\n const optionStyles = props.getStyles( "option", props );\n const isSelectAllRow = props.data.value === SELECT_ALL_VALUE;\n // The Create row makes an option that does not exist yet, so there is nothing for a checkbox to\n // report on and nothing in the draft to toggle. It is left to react-select, whose Creatable turns\n // the click into the create action, exactly as in single-select.\n const isDraftRow = Boolean( props.isMulti ) && !isCreateOption( props.data );\n // Multi-select selection is driven by the in-progress draft (not react-select\'s value, which is\n // the committed selection feeding the control). Single-select keeps react-select\'s own state.\n const draft = draftValues ?? EMPTY_DRAFT;\n const optionSelected = isDraftRow\n ? ( isSelectAllRow ? Boolean( areAllSelected ) : draft.has( props.data.value ))\n : props.isSelected;\n\n const baseClassName = props.cx(\n {\n option: true,\n "option--is-disabled": props.isDisabled,\n "option--is-focused": props.isFocused,\n "option--is-selected": optionSelected\n },\n props.className\n );\n\n // Toggle the draft for multi-select (mouse path). stopPropagation keeps react-select from also\n // firing its own onChange against the committed value.\n const handleToggle = ( e: React.SyntheticEvent ) => {\n e.stopPropagation();\n if ( props.isDisabled || props.data.isFixed ) {\n return;\n }\n if ( isSelectAllRow ) {\n onSelectAll?.();\n } else {\n onToggleDraftOption?.( props.data );\n }\n };\n\n // react-select\'s own `state.isSelected` reflects the *committed* value, not the in-progress\n // multi-select draft - so it never lights up a checked-but-uncommitted row, and the inline\n // `style` from `optionStyles` can\'t respond to that anyway (nested selectors like `.dark &`\n // are dropped when applied as a plain `style` attribute). Drive the background entirely from\n // our own `optionSelected` (checked-aware for multi, same as isSelected for single) via\n // classes instead, so it\'s consistent for both select modes and both themes.\n const bgClass = optionSelected\n ? "!bg-frostBlue dark:!bg-secondary-700"\n : props.isFocused\n ? "!bg-frostBlue dark:!bg-secondary-800"\n : "!bg-transparent dark:!bg-iridium";\n\n // Show the full-text overlay only for genuinely-clipped labels. Which signal drives it depends on\n // the current input modality: the pointer path uses local `isHovered` (which clears on\n // mouseleave, so only the row actually under the cursor shows, never a stale one); the keyboard\n // path uses react-select\'s `isFocused`. Honoring `isFocused` unconditionally would leave the\n // overlay stuck on the last-focused row after the mouse moved off it (react-select keeps that\n // focus, and sets it on hover too), which is the "both overlays stay visible" bug.\n const showOverlay = isLabelTruncated &&\n ( interactionMode === "keyboard" ? props.isFocused : isHovered );\n\n return (\n <div\n style={optionStyles as React.CSSProperties}\n onMouseEnter={() => {\n onInteractionMode( "pointer" );\n setIsHovered( true );\n }}\n onMouseLeave={() => setIsHovered( false )}\n className={cx(\n baseClassName,\n "select__custom-option",\n bgClass,\n props.isMulti && "select__custom-option--is-multi"\n )}\n >\n {isDraftRow && (\n <Checkbox\n className="me-2"\n onChange={handleToggle}\n checked={optionSelected}\n disabled={props.isDisabled || props.data.isFixed}\n />\n )}\n <components.Option\n {...props}\n className={cx( "!p-0 !bg-transparent", props.isMulti && "flex-1 min-w-0" )}\n innerProps={{\n ...props.innerProps,\n ...( isDraftRow ? { onClick: handleToggle } : {})\n }}\n >\n <span ref={labelWrapRef} className={optionLabelWrapClass}>\n <span ref={labelRef} className={optionLabelClass}>{props.children}</span>\n </span>\n {showOverlay && (\n <OptionLabelOverlay anchorRef={labelWrapRef} className={optionOverlayClass}>\n {props.children}\n </OptionLabelOverlay>\n )}\n </components.Option>\n </div>\n );\n}\n\nSelectOption.displayName = "SelectOption";\n\n/**\n * Wraps a multi-select chip so its full label is surfaced in a Tooltip, but only when the chip\'s\n * label is actually clipped by react-select\'s `maxWidth` (measured against the rendered\n * `.select__multi-value__label`, whose class comes from `classNamePrefix="select"`). The Tooltip\n * always wraps the chip and is gated via its `canOpen` prop rather than being swapped in and out,\n * so the measured label node stays mounted and the ResizeObserver never loses its target. The\n * `contents` wrapper carries no box of its own, so the chip lays out exactly as it would\n * unwrapped; it exists only to scope the label lookup to this chip.\n */\nfunction TruncatedMultiValue({ label, chip }: ITruncatedMultiValueProps ): ReactElement {\n const wrapRef = React.useRef<HTMLSpanElement>( null );\n const [ isTruncated, setIsTruncated ] = React.useState( false );\n\n React.useLayoutEffect(() => {\n const labelEl = wrapRef.current?.querySelector<HTMLElement>( ".select__multi-value__label" ) ?? null;\n if ( !labelEl ) {\n return undefined;\n }\n const measure = () => setIsTruncated( labelEl.scrollWidth > labelEl.clientWidth );\n measure();\n const observer = new ResizeObserver( measure );\n observer.observe( labelEl );\n return () => observer.disconnect();\n }, [label]);\n\n return (\n <Tooltip\n placement="top"\n canOpen={isTruncated}\n title={label}\n trigger={<span ref={wrapRef} className="contents">{chip}</span>}\n />\n );\n}\n\nTruncatedMultiValue.displayName = "TruncatedMultiValue";\n\n/**\n * Builds the react-select custom components that are independent of the in-dropdown\n * search/focus machinery (kept in select.tsx) and of per-option selection state (the Option is\n * the stable {@link SelectOption} above). These are stateless, so recreating them per render is\n * harmless - react-select only remounts the focus-sensitive Menu component.\n */\nexport function createSelectComponents<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( config: ISelectComponentsConfig ) {\n const {\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n } = config;\n\n // Dropdown indicator icon\n const DropdownIndicator = ( props: DropdownIndicatorProps<IOption, IsMulti, Group> ) => {\n const {\n selectProps: { menuIsOpen }\n } = props;\n return (\n <ADPIcon size="xs" icon={menuIsOpen ? iconList.upArrow : iconList.downArrow} />\n );\n };\n\n // Custom value container to handle prefix/suffix icons and truncation\n const ValueContainer = (\n { children, ...props }: ValueContainerProps<IOption, IsMulti, Group>\n ) => {\n const values = props.getValue();\n // Split the chips (which carry `props.data`) from the search input in a single pass.\n const withData: React.ReactNode[] = [];\n const inputChild: React.ReactNode[] = [];\n React.Children.toArray( children ).forEach(( c ) => {\n const target = ( c as ReactElement ).props.data ? withData : inputChild;\n target.push( c );\n });\n return (\n <>\n {prefixIcon &&\n ( typeof prefixIcon === "string" ? (\n <ADPIcon icon={prefixIcon as TIconType} size="xs" />\n ) : (\n prefixIcon\n ))}\n <components.ValueContainer {...props}>\n {withData}\n {values.length > maxVisibleValues && (\n <div\n className={cx(\n "text-secondary-400 dark:text-secondary-300",\n "select__truncated-multi-value",\n disabled && "select__truncated-multi-value--is-disabled"\n )}\n >\n +{values.length - maxVisibleValues}{" "}\n {maxVisibleValuesMsg ?? "More"}\n </div>\n )}\n {inputChild}\n </components.ValueContainer>\n {suffixIcon &&\n ( typeof suffixIcon === "string" ? (\n <ADPIcon icon={suffixIcon as TIconType} size="xs" />\n ) : (\n suffixIcon\n ))}\n </>\n );\n };\n\n // Hide extra MultiValue components\n const MultiValue = ( props: MultiValueProps<IOption> ) => {\n if ( props.index !== undefined && props.index >= maxVisibleValues ) {\n return null;\n }\n const chip = <components.MultiValue {...props} />;\n // Surface the full label in a Tooltip, but only when the chip\'s label is actually truncated\n // (see TruncatedMultiValue). Non-string labels have no text to show, so render the chip as-is.\n if ( typeof props.data.label !== "string" ) {\n return chip;\n }\n return <TruncatedMultiValue label={props.data.label} chip={chip} />;\n };\n\n // react-select\'s default remove control is a mouse-only `<div role="button">` with no tabIndex,\n // so a pill\'s "x" can never be reached or activated by keyboard. Make it a real tab stop\n // (per chip, regardless of truncation) that removes on Enter/Space. stopPropagation keeps the\n // key from bubbling to the control, which would otherwise treat Enter/Space as open/select.\n const MultiValueRemove = ( props: MultiValueRemoveProps<IOption, IsMulti, Group> ) => {\n const { onClick } = props.innerProps;\n return (\n <components.MultiValueRemove\n {...props}\n innerProps={{\n ...props.innerProps,\n tabIndex: disabled ? -1 : 0,\n onKeyDown: ( e: React.KeyboardEvent ) => {\n if ( e.key === keyboardKeys.enter || e.key === keyboardKeys.space ) {\n e.preventDefault();\n e.stopPropagation();\n onClick?.( e as unknown as React.MouseEvent<HTMLDivElement> );\n }\n }\n }}\n />\n );\n };\n\n return { DropdownIndicator, ValueContainer, MultiValue, MultiValueRemove };\n}\n\n/**\n * The control input, which must remain present and focusable so react-select\'s click-to-open flow\n * works (onControlMouseDown \u2192 focusInput \u2192 onInputFocus \u2192 openMenu). It is read-only and visually\n * hidden, so all actual typing happens in the dropdown search input \u2014 and with no search input on\n * screen it is where focus lives for as long as the menu is open.\n *\n * Built apart from the components above, on `maxVisibleValues` alone: react-select unmounts and\n * remounts a custom component whose identity changed, and remounting this one destroys that focus.\n * Sharing the icon props\' identity would put the focus at the mercy of a consumer passing a fresh\n * `prefixIcon` element on every render.\n */\nexport function createSelectInput<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>( maxVisibleValues: number ) {\n return function Input( props: InputProps<IOption, IsMulti, Group> ): ReactElement {\n const handleKeyDown = ( e: React.KeyboardEvent<HTMLInputElement> ) => {\n if ( e.key === keyboardKeys.backspace ) {\n const vals = props.getValue();\n if ( vals.length > maxVisibleValues ) {\n e.stopPropagation();\n e.preventDefault();\n }\n }\n };\n return (\n <components.Input\n {...props}\n readOnly\n onKeyDown={handleKeyDown}\n style={{ ...( props.style as React.CSSProperties ), opacity: 0, width: 0, position: "absolute" }}\n />\n );\n };\n}\n\n/** react-select renders a separator between the indicators; this component has none. */\nexport const NoIndicatorSeparator = (): null => null;\n'
3602
3693
  },
3603
3694
  {
3604
3695
  "name": "select.tsx",
3605
- "content": 'import * as React from "react";\nimport {\n type ComponentType,\n type ForwardedRef,\n type ReactElement,\n type RefAttributes,\n useId,\n useMemo,\n useRef,\n useState\n} from "react";\nimport ReactSelect, {\n type Props as ReactSelectProps,\n type GroupBase,\n type FilterOptionOption\n} from "react-select";\nimport CreatableSelect from "react-select/creatable";\nimport mergeRefs from "react-merge-refs";\nimport { cx } from "tailwind-variants";\n\nimport { useFilterQuery, useIgnoredPropWarning, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport {\n reactSelectCustomStyles,\n getSelectableOptions,\n areAllSelectableSelected,\n SELECT_ALL_VALUE\n} from "./utils";\nimport { selectVariants } from "./selectVariants";\nimport {\n createSelectComponents,\n SelectOption,\n SelectOptionContext\n} from "./selectComponents";\nimport { SelectMenu, SelectMenuContext } from "./selectMenu";\nimport { useSelectOptionSource } from "./useSelectOptionSource";\nimport { useSelectOutsideClose } from "./useSelectOutsideClose";\n\nimport {\n ESelectSizes,\n type IOption,\n type ISelectProps,\n type ISelectMenuContext,\n type TSelectInteractionMode\n} from "./types";\n\n// The synthetic Select-All row, hoisted so `selectOptions` keeps a stable array identity while the\n// row is shown.\nconst SELECT_ALL_OPTION: IOption = { value: SELECT_ALL_VALUE, label: "Select All" };\n\n// `filterOption` deprecation notices, hoisted so the warning hook\'s message dependency stays stable.\nconst FILTER_OPTION_DEPRECATED =\n "Select: `filterOption` is deprecated and will be removed in the next major. Use `onFilterChange` " +\n "instead: hold the options in state, filter them with your own predicate, and pass the result as " +\n "`options` (with `filterDebounceMs={0}` to stay synchronous).";\nconst FILTER_OPTION_IGNORED =\n "Select: `filterOption` is deprecated and is ignored while filtering is server-side \u2014 the options " +\n "you return for the query already are the result set.";\n\nfunction SelectComponent<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n selectProps: ISelectProps<IsMulti, Group>,\n forwardedRef: ForwardedRef<HTMLDivElement>\n): ReactElement {\n const {\n id,\n className,\n label,\n size = ESelectSizes.MD,\n options,\n value,\n helperText,\n error = false,\n disabled = false,\n creatable = false,\n maxVisibleValues = 3,\n maxVisibleValuesMsg,\n menuFooter,\n prefixIcon,\n suffixIcon,\n searchPlaceholder = "Search...",\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n filterValue,\n onFilterChange,\n filterDebounceMs = 300,\n // Intercepted \u2014 not forwarded (avoids react-select\'s own loading UI).\n isLoading = false,\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n showReloadButton = false,\n onLoadError,\n ...restProps\n } = selectProps;\n\n // Owns the async/sync mode decision and every derived option/loading/error value. Declared before\n // useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useSelectOptionSource<Group>({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n showReloadButton,\n onLoadError,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n\n // Filter query state: the raw input value plus the debounced query the option source sees.\n const {\n filterQuery,\n handleFilterInput,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter\n } = useFilterQuery({\n filterValue,\n onFilterChange: optionSource.onFilterQueryChange,\n filterDebounceMs\n });\n // We control menuIsOpen ourselves. react-select\'s built-in menu management closes\n // the menu whenever its internal input blurs, and focusing our in-dropdown search\n // input always blurs that input. Owning the open state decouples the menu lifecycle\n // from react-select\'s focus/blur logic.\n const [ menuOpen, setMenuOpen ] = useState( false );\n const containerRef = useRef<HTMLDivElement>( null );\n const searchInputRef = useRef<HTMLInputElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the search box reaches react-select\'s\n // hidden control input through it). Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n // The menu can render in a portal (menuPortalTarget), so it is not always a descendant\n // of containerRef. Track its DOM node separately for the outside-click check below.\n const menuNodeRef = useRef<HTMLDivElement | null>( null );\n // Latest input modality, shared by every option\'s full-text overlay (see SelectOptionContext).\n // State, not a ref: it decides what an option renders. Re-setting the current mode is a no-op React\n // bails out of, so this only re-renders on a genuine pointer\u2194keyboard switch.\n const [ interactionMode, setInteractionMode ] = useState<TSelectInteractionMode>( "pointer" );\n\n // Extract props we compose ourselves so the spread doesn\'t override them\n const {\n onMenuClose: externalOnMenuClose,\n onMenuOpen: externalOnMenuOpen,\n onChange: externalOnChange,\n filterOption: externalFilterOption,\n ...otherRestProps\n } = restProps;\n\n const { isMulti } = otherRestProps;\n\n // Committed multi-select value shown as chips in the control. When the consumer passes `value`\n // the component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render.\n const isControlled = value !== undefined;\n // Seed committed/draft state from defaultValue when uncontrolled, so an uncontrolled multi-select\n // starts in sync with what react-select renders rather than an empty draft that would wipe the\n // defaults on the first commit. Only read on the initial render.\n const initialMultiValue = value !== undefined ? value : ( otherRestProps.defaultValue as typeof value );\n const [ committedValue, setCommittedValue ] = useState( initialMultiValue );\n // When controlled, `multiControlValue` reads `value` directly, so `committedValue` is only ever\n // consumed in the uncontrolled path \u2014 no effect mirroring `value` into it is needed.\n const multiControlValue = isControlled ? value : committedValue;\n\n // Draft selection for multi-select. While the menu is open, option toggles update this draft\n // instead of calling onChange; the draft is committed only when the menu closes via an outside\n // click. Pressing Escape discards it. Single-select keeps its live onChange behavior.\n const [ pendingValue, setPendingValue ] = useState( initialMultiValue );\n const pendingValueRef = useRef( pendingValue );\n pendingValueRef.current = pendingValue;\n\n // Keep the draft synced with the committed value while the menu is closed, so external updates\n // are reflected on next open.\n React.useEffect(() => {\n if ( isMulti && !menuOpen ) {\n setPendingValue( multiControlValue );\n }\n }, [ isMulti, menuOpen, multiControlValue ]);\n\n const closeMenu = React.useCallback(() => {\n setMenuOpen( false );\n resetFilter();\n externalOnMenuClose?.();\n }, [ externalOnMenuClose, resetFilter ]);\n\n // Commit the multi-select draft, then close. Used by the outside-click handler. Updates the\n // internal committed value (so uncontrolled chips render) and notifies the consumer.\n const commitAndClose = React.useCallback(() => {\n if ( isMulti ) {\n setCommittedValue( pendingValueRef.current );\n ( externalOnChange as ( ...args: unknown[]) => void )?.(\n pendingValueRef.current,\n { action: "set-value" }\n );\n }\n closeMenu();\n }, [ isMulti, externalOnChange, closeMenu ]);\n\n const openMenu = React.useCallback(() => {\n // No need to seed the draft here: the effect above keeps pendingValue synced to the committed\n // value the whole time the menu is closed, so it is already current at open.\n setMenuOpen( true );\n externalOnMenuOpen?.();\n }, [externalOnMenuOpen]);\n\n // Multi-select draft mutators. The control is fed the committed `value` (so chips only appear\n // once the selection is committed), while these update the in-progress draft that drives the\n // menu\'s checkboxes and Select All. Selection is committed to onChange on outside-click close.\n const toggleDraftOption = React.useCallback(( option: IOption ) => {\n setPendingValue(( prev ) => {\n const arr = ( prev as IOption[] | undefined ) ?? [];\n const exists = arr.some(( o ) => o.value === option.value );\n const next = exists ? arr.filter(( o ) => o.value !== option.value ) : [ ...arr, option ];\n return next as typeof pendingValue;\n });\n requestAnimationFrame(() => searchInputRef.current?.focus());\n }, []);\n\n const setDraft = React.useCallback(( vals: IOption[]) => {\n setPendingValue( vals as typeof pendingValue );\n requestAnimationFrame(() => searchInputRef.current?.focus());\n }, []);\n\n // Async mode, or the presence of onFilterChange, is the client/server mode switch.\n const { isServerFiltered } = optionSource;\n\n // react-select derives the candidate it hands `filterOption` from `getOptionLabel`/`getOptionValue`,\n // so mirror that construction for the Select-All path, where there is no react-select candidate to\n // pass through. Reading them off the spread rather than destructuring keeps them flowing to\n // react-select untouched.\n const { getOptionLabel: externalGetOptionLabel, getOptionValue: externalGetOptionValue } = otherRestProps;\n const toCandidate = React.useCallback(\n ( option: IOption ): FilterOptionOption<IOption> => ({\n // react-select types the candidate label as a string but passes whatever getOptionLabel returns,\n // so an unresolved ReactNode label reaches a consumer predicate here exactly as it does there.\n label: externalGetOptionLabel ? externalGetOptionLabel( option ) : ( option.label as string ),\n value: externalGetOptionValue ? externalGetOptionValue( option ) : option.value,\n data: option\n }),\n [ externalGetOptionLabel, externalGetOptionValue ]\n );\n\n // Deprecated: a second filtering axis alongside `onFilterChange`, which already covers it \u2014 that hands\n // the consumer the query and treats `options` as the answer, so a custom predicate belongs in their own\n // memo rather than in a react-select callback. Still honoured client-side until the next major, since\n // it reached react-select through the prop spread before filtering was owned here. Server-filtered mode\n // ignores it outright: a local predicate there could only hide rows the server deliberately returned,\n // and it cannot see the fields the server matched on.\n useIgnoredPropWarning(\n externalFilterOption !== undefined,\n isServerFiltered ? FILTER_OPTION_IGNORED : FILTER_OPTION_DEPRECATED\n );\n\n // The predicate react-select filters rows with, resolved once so the menu and Select All can never\n // disagree about what is visible. Precedence, highest first: server-filtered mode and\n // `filterOption={null}` (react-select\'s documented opt-out) both do no local pass at all; a consumer\n // `filterOption` then decides; otherwise the library default applies. Keyed on the prop\'s identity, so\n // a predicate that changes behaviour re-narrows the visible set instead of leaving Select All acting on\n // a stale one. The candidate argument is react-select\'s own on the path that has one, so the consumer\n // sees exactly what react-select built there and the Select-All path constructs one only when a\n // predicate is actually going to read it.\n const isOptionVisible = React.useCallback(\n ( option: IOption, input: string, candidate?: FilterOptionOption<IOption> ): boolean => {\n if ( isServerFiltered || externalFilterOption === null ) {\n return true;\n }\n return typeof externalFilterOption === "function"\n ? externalFilterOption( candidate ?? toCandidate( option ), input )\n : matchesQuery( option, input );\n },\n [ externalFilterOption, isServerFiltered, toCandidate ]\n );\n\n // The enabled options in the pool, groups flattened. Kept apart from the narrowing below so a\n // keystroke re-runs only the query pass, not the flatten.\n const selectableOptions = React.useMemo(\n () => getSelectableOptions( optionSource.options ),\n [optionSource.options]\n );\n\n // What Select All acts on: the enabled options currently ON SCREEN, so it can never reach an option\n // the query has hidden. Both no-op modes (server-filtered, `filterOption={null}`) are folded into the\n // predicate itself, so there is one pass here regardless of mode.\n const visibleSelectable = React.useMemo(\n () => selectableOptions.filter(( o ) => isOptionVisible( o, filterQuery )),\n [ selectableOptions, isOptionVisible, filterQuery ]\n );\n\n // Read through a ref so handleSelectAllDraft survives every keystroke with its identity intact \u2014\n // see useSelectOptionSource\'s note on what a churning callback costs the whole option context.\n const visibleSelectableRef = useRef( visibleSelectable );\n visibleSelectableRef.current = visibleSelectable;\n\n // Single source of truth for the "Select All" toggle, shared by the mouse path (Option\n // component) and the keyboard path (react-select onChange). If every visible option is already\n // in the draft it deselects down to the fixed ones; otherwise it selects them all. Both\n // directions leave options hidden by the query untouched, so a selection made under one query\n // survives the next.\n const handleSelectAllDraft = React.useCallback(() => {\n const selectable = visibleSelectableRef.current;\n const selectableValues = new Set( selectable.map(( o ) => o.value ));\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n const draftKeys = new Set( draft.map(( o ) => o.value ));\n const next = areAllSelectableSelected( selectable, draftKeys )\n // Deselect: drop selectable, non-fixed options; keep fixed and disabled ones untouched.\n ? draft.filter(( o ) => o.isFixed || !selectableValues.has( o.value ))\n // Select: add every selectable (enabled) option not already present.\n : [ ...draft, ...selectable.filter(( o ) => !draftKeys.has( o.value )) ];\n setDraft( next );\n }, [setDraft]);\n\n useSelectOutsideClose({ menuOpen, menuNodeRef, commitAndClose });\n\n // Prefetch the baseline on first OPEN by default, not on mount: a form with six server-filtered\n // Selects would otherwise fire six requests on paint for menus the user may never open.\n // `prefetch="mount"` opts into the baseline at render, for a Select that would otherwise sit\n // visibly empty.\n usePrefetchBaseline({\n prefetch: prefetch ?? "open",\n isOpen: menuOpen,\n optionsKey,\n ensureDefaults: optionSource.ensureDefaults\n });\n\n // Route an optionsKey CHANGE into the clear path (resetFilter \u2192 onFilterChange("")), which drops the\n // search view and lets ensureDefaults lazily repopulate. Skipped on mount: resetFilter notifies the\n // consumer whenever the query is non-empty, and a seeded `filterValue` must not fire that on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n const {\n DropdownIndicator,\n ValueContainer,\n MultiValue,\n MultiValueRemove,\n Input\n } = createSelectComponents<IsMulti, Group>({\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n });\n\n const {\n base,\n label: labelClass,\n helperText: helperTextClass,\n menuSearchContainer,\n menuSearchInput,\n menuLoader,\n menuError,\n optionLabelWrap,\n optionLabel,\n optionOverlay\n } = selectVariants({ error });\n\n const searchContainerClass = menuSearchContainer();\n const searchInputClass = menuSearchInput();\n const loaderClass = menuLoader();\n const errorClass = menuError();\n const optionLabelWrapClass = optionLabelWrap();\n const optionLabelClass = optionLabel();\n const optionOverlayClass = optionOverlay();\n\n // Live option config for the stable SelectOption (see selectComponents.tsx). Rebuilt whenever the\n // draft changes so checkbox / Select-All state tracks it; the component identity stays stable.\n const draftValues = React.useMemo(\n () => ( isMulti ? new Set((( pendingValue as IOption[] | undefined ) ?? []).map(( o ) => o.value )) : undefined ),\n [ isMulti, pendingValue ]\n );\n // Computed here, where the visible set lives, rather than in SelectOption from react-select\'s\n // unfiltered `props.options` \u2014 which would leave the row unchecked even with every visible option\n // ticked. A boolean in the context also keeps its identity stable across keystrokes.\n const areAllSelected = React.useMemo(\n () => draftValues !== undefined && areAllSelectableSelected( visibleSelectable, draftValues ),\n [ visibleSelectable, draftValues ]\n );\n const optionContextValue = React.useMemo(\n () => ({\n draftValues,\n areAllSelected,\n onToggleDraftOption: toggleDraftOption,\n onSelectAll: handleSelectAllDraft,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode: setInteractionMode\n }),\n [ draftValues, areAllSelected, toggleDraftOption, handleSelectAllDraft, optionLabelWrapClass,\n optionLabelClass, optionOverlayClass, interactionMode ]\n );\n\n // Live values the stable, module-level SelectMenu reads via context. SelectMenu must keep a\n // stable identity (react-select remounts custom components on reference change, which would\n // destroy the search input\'s focus/caret and the MenuList scroll on every keystroke), so it\n // cannot close over these directly \u2014 context lets it re-render with current values instead.\n const menuContextValue = React.useMemo<ISelectMenuContext>(\n () => ({\n filterQuery,\n onFilterInput: handleFilterInput,\n onFilterKeyDown: handleFilterKeyDown,\n onFilterKeyUp: handleFilterKeyUp,\n onFilterBlur: handleFilterBlur,\n searchPlaceholder,\n menuFooter,\n closeMenu,\n commitAndClose,\n searchContainerClass,\n searchInputClass,\n loaderClass,\n isLoading: optionSource.isLoading,\n loadError: optionSource.loadError,\n errorClass,\n searchInputRef,\n menuNodeRef,\n containerRef,\n onReload: optionSource.onReload,\n isReloading: optionSource.isReloading,\n reloadTooltip,\n onInteractionMode: setInteractionMode\n }),\n [ filterQuery, handleFilterInput, handleFilterKeyDown, handleFilterKeyUp, handleFilterBlur,\n searchPlaceholder, menuFooter, closeMenu, commitAndClose, searchContainerClass, searchInputClass,\n loaderClass, errorClass, optionSource.isLoading, optionSource.loadError, optionSource.onReload,\n optionSource.isReloading, reloadTooltip ]\n );\n\n // The synthetic Select-All row is prepended to the option set so it keyboard-navigates like any\n // other row. Keyed on the boolean rather than on `visibleSelectable` itself: react-select rebuilds\n // its whole focusable-option index whenever this array\'s identity changes, so it must churn only\n // when the row genuinely appears or disappears \u2014 not on every keystroke.\n const showSelectAll = Boolean( isMulti ) && visibleSelectable.length >= 2;\n const selectOptions = React.useMemo(\n () => ( showSelectAll\n ? [SELECT_ALL_OPTION].concat( optionSource.options as IOption[])\n : optionSource.options ),\n [ showSelectAll, optionSource.options ]\n );\n\n const customComponents = {\n IndicatorSeparator: () => null,\n DropdownIndicator,\n Option: SelectOption,\n ValueContainer,\n MultiValue,\n MultiValueRemove,\n Input,\n Menu: SelectMenu\n };\n\n // The Select-All row is an affordance over the result set, not a member of it, so it is never\n // query-matched \u2014 whether it renders at all is decided by `showSelectAll` above. Every other row goes\n // through the resolved predicate, handed react-select\'s own candidate so a consumer predicate sees the\n // label react-select built rather than a second-hand reconstruction of it.\n const filterOption = ( candidate: FilterOptionOption<IOption>, input: string ): boolean =>\n ( candidate.data.value === SELECT_ALL_VALUE || isOptionVisible( candidate.data, input, candidate ));\n\n const inputId = useId();\n // unify component type for creatable and default select\n type TRSComponent = ComponentType<ReactSelectProps<IOption, IsMulti, Group>>;\n const SelectType: TRSComponent = creatable\n ? ( CreatableSelect as TRSComponent )\n : ( ReactSelect as TRSComponent );\n\n return (\n <div className={base({ class: className })} ref={rootRef}>\n {label !== undefined && (\n <label\n htmlFor={id || inputId}\n className={labelClass()}\n >\n {label}\n </label>\n )}\n <SelectMenuContext.Provider value={menuContextValue}>\n <SelectOptionContext.Provider value={optionContextValue}>\n <SelectType\n classNamePrefix="select"\n inputId={id || inputId}\n options={selectOptions}\n value={isMulti ? multiControlValue : value}\n hideSelectedOptions={false}\n menuPlacement="auto"\n components={customComponents}\n className={cx( "select", `select-${size}` )}\n styles={\n reactSelectCustomStyles<IsMulti, Group>(\n error,\n size,\n otherRestProps.isMulti as boolean\n )\n }\n isDisabled={disabled}\n {...otherRestProps}\n // Controlled props are applied AFTER the spread so a consumer cannot accidentally\n // override the menu/search mechanism this component owns.\n // A consumer `filterOption` is resolved into this wrapper (see `isOptionVisible`) rather\n // than forwarded, so their predicate still decides every real row while the Select-All row\n // stays exempt from it.\n filterOption={filterOption}\n // Empty when closed \u2014 react-select blanks placeholder/value for a non-empty inputValue.\n inputValue={menuOpen ? filterQuery : ""}\n menuIsOpen={menuOpen}\n onMenuOpen={openMenu}\n /*\n * No-op: react-select calls onMenuClose from its input-blur handler, which\n * fires every time focus moves to the dropdown search input. Honoring it\n * would close the menu immediately. We close explicitly instead \u2014 via\n * outside-click, Escape, and single-select onChange.\n */\n onMenuClose={() => {}}\n onChange={( newValue: unknown, actionMeta: unknown ) => {\n if ( isMulti ) {\n // The control is fed the committed value, so option toggles must route into the draft\n // rather than onChange. Mouse clicks are handled directly in SelectOption; this path\n // only fires for keyboard selection (Enter forwarded to react-select\'s input), which we\n // translate into a draft toggle. The draft is committed when the menu closes via an\n // outside click.\n const meta = actionMeta as { action: string; option?: IOption; removedValue?: IOption };\n // Control-level actions act on the committed value (chips), not the in-menu draft:\n // clearing all, removing a single pill via its X, or popping the last value with\n // Backspace. These commit immediately and notify the consumer; otherwise the change\n // would only land on the next outside-click close (and never reach a controlled\n // `value`). Keyboard option toggles (Enter forwarded to react-select\'s input) are the\n // only path that should buffer into the draft.\n if ( meta.action === "clear" || meta.action === "remove-value" || meta.action === "pop-value" ) {\n setPendingValue( newValue as typeof pendingValue );\n setCommittedValue( newValue as typeof committedValue );\n ( externalOnChange as ( ...args: unknown[]) => void )?.( newValue, actionMeta );\n } else if ( meta.option ) {\n // The injected Select-All row has no dedicated onChange semantics in react-select,\n // so keyboard selection reports it like any option. Route it through the shared\n // handler instead of buffering the synthetic row into the draft.\n if ( meta.option.value === SELECT_ALL_VALUE ) {\n handleSelectAllDraft();\n } else {\n toggleDraftOption( meta.option );\n }\n }\n } else {\n // Close the menu and commit immediately after a single-value selection.\n closeMenu();\n ( externalOnChange as ( ...args: unknown[]) => void )?.( newValue, actionMeta );\n }\n }}\n closeMenuOnSelect={!isMulti}\n />\n </SelectOptionContext.Provider>\n </SelectMenuContext.Provider>\n {helperText && (\n <div className={helperTextClass()}>\n {helperText}\n </div>\n )}\n </div>\n );\n}\n\nconst SelectWithRef = React.forwardRef( SelectComponent );\nSelectWithRef.displayName = "Select";\n\n/**\n * Select component for single or multi selection. The forwarded ref lands on the wrapper `<div>`; the\n * cast is what stops `forwardRef` \u2014 whose own signature is not generic \u2014 from collapsing `IsMulti` /\n * `Group` to their defaults.\n */\nexport const Select = SelectWithRef as unknown as <\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n props: ISelectProps<IsMulti, Group> & RefAttributes<HTMLDivElement>\n) => ReactElement;\n'
3696
+ "content": 'import * as React from "react";\nimport {\n type ComponentType,\n type ForwardedRef,\n type ReactElement,\n type RefAttributes,\n useId,\n useMemo,\n useRef,\n useState\n} from "react";\nimport ReactSelect, {\n type Props as ReactSelectProps,\n type GroupBase,\n type FilterOptionOption\n} from "react-select";\nimport CreatableSelect from "react-select/creatable";\nimport mergeRefs from "react-merge-refs";\nimport { cx } from "tailwind-variants";\n\nimport { useFilterQuery, useIgnoredPropWarning, useOnValueChange, usePrefetchBaseline } from "@hooks";\nimport { matchesQuery } from "@utils";\nimport {\n reactSelectCustomStyles,\n getSelectableOptions,\n getPooledValues,\n areAllSelectableSelected,\n isCreateOption,\n toPoolOption,\n SELECT_ALL_VALUE\n} from "./utils";\nimport { selectVariants } from "./selectVariants";\nimport {\n createSelectComponents,\n createSelectInput,\n NoIndicatorSeparator,\n SelectOption,\n SelectOptionContext\n} from "./selectComponents";\nimport { SelectMenu, SelectMenuContext } from "./selectMenu";\nimport { focusMenuInput, handleMenuKey } from "./selectKeyboard";\nimport { useSelectOptionSource } from "./useSelectOptionSource";\nimport { useSelectOutsideClose } from "./useSelectOutsideClose";\n\nimport {\n ESelectSizes,\n type IOption,\n type ISelectProps,\n type ISelectMenuContext,\n type TSelectInteractionMode\n} from "./types";\n\n// Stable empty identity for the created-option pool, so an untouched creatable Select never rebuilds\n// the list it hands react-select.\nconst EMPTY_CREATED: readonly IOption[] = [];\n\n// The synthetic Select-All row, hoisted so `selectOptions` keeps a stable array identity while the\n// row is shown.\nconst SELECT_ALL_OPTION: IOption = { value: SELECT_ALL_VALUE, label: "Select All" };\n\n// `filterOption` deprecation notices, hoisted so the warning hook\'s message dependency stays stable.\nconst FILTER_OPTION_DEPRECATED =\n "Select: `filterOption` is deprecated and will be removed in the next major. Use `onFilterChange` " +\n "instead: hold the options in state, filter them with your own predicate, and pass the result as " +\n "`options` (with `filterDebounceMs={0}` to stay synchronous).";\nconst FILTER_OPTION_IGNORED =\n "Select: `filterOption` is deprecated and is ignored while filtering is server-side \u2014 the options " +\n "you return for the query already are the result set.";\nconst SEARCHABLE_FILTER_IGNORED =\n "Select: `onFilterChange` / `filterValue` have nothing to drive while `searchable={false}` \u2014 with no " +\n "search input the query can never change, and a seeded `filterValue` hides rows the user has no way " +\n "to bring back. Filter the `options` you pass instead, or keep the search input.";\n\nfunction SelectComponent<\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n selectProps: ISelectProps<IsMulti, Group>,\n forwardedRef: ForwardedRef<HTMLDivElement>\n): ReactElement {\n const {\n id,\n className,\n label,\n size = ESelectSizes.MD,\n options,\n value,\n helperText,\n error = false,\n disabled = false,\n creatable = false,\n maxVisibleValues = 3,\n maxVisibleValuesMsg,\n menuFooter,\n prefixIcon,\n suffixIcon,\n searchable = true,\n searchPlaceholder = "Search...",\n reloadTooltip = "Reload",\n onReload,\n isReloading,\n filterValue,\n onFilterChange,\n filterDebounceMs = 300,\n // Intercepted \u2014 not forwarded (avoids react-select\'s own loading UI).\n isLoading = false,\n loadOptions,\n initialOptions,\n // Left undefined here, not defaulted: sync mode warns on a `prefetch` the consumer actually passed,\n // which an eager default would erase. Resolved at the one place that reads it as a trigger.\n prefetch,\n refetchOnClear = false,\n optionsKey,\n loadErrorMessage,\n showReloadButton = false,\n onLoadError,\n ...restProps\n } = selectProps;\n\n // Owns the async/sync mode decision and every derived option/loading/error value. Declared before\n // useFilterQuery because it supplies that hook\'s handler.\n const optionSource = useSelectOptionSource<Group>({\n options,\n loadOptions,\n initialOptions,\n prefetch,\n refetchOnClear,\n optionsKey,\n loadErrorMessage,\n showReloadButton,\n onLoadError,\n isLoading,\n onReload,\n isReloading,\n onFilterChange\n });\n\n // Filter query state: the raw input value plus the debounced query the option source sees.\n const {\n filterQuery,\n handleFilterInput,\n handleFilterKeyDown,\n handleFilterKeyUp,\n handleFilterBlur,\n resetFilter\n } = useFilterQuery({\n filterValue,\n onFilterChange: optionSource.onFilterQueryChange,\n filterDebounceMs\n });\n // We control menuIsOpen ourselves. react-select\'s built-in menu management closes\n // the menu whenever its internal input blurs, and focusing our in-dropdown search\n // input always blurs that input. Owning the open state decouples the menu lifecycle\n // from react-select\'s focus/blur logic.\n const [ menuOpen, setMenuOpen ] = useState( false );\n const containerRef = useRef<HTMLDivElement>( null );\n const searchInputRef = useRef<HTMLInputElement>( null );\n // The wrapper is both the consumer\'s ref target and ours (the search box reaches react-select\'s\n // hidden control input through it). Memoised so React does not re-attach it every render.\n const rootRef = useMemo(() => mergeRefs([ forwardedRef, containerRef ]), [forwardedRef]);\n // The menu can render in a portal (menuPortalTarget), so it is not always a descendant\n // of containerRef. Track its DOM node separately for the outside-click check below.\n const menuNodeRef = useRef<HTMLDivElement | null>( null );\n // Latest input modality, shared by every option\'s full-text overlay (see SelectOptionContext).\n // State, not a ref: it decides what an option renders. Re-setting the current mode is a no-op React\n // bails out of, so this only re-renders on a genuine pointer\u2194keyboard switch.\n const [ interactionMode, setInteractionMode ] = useState<TSelectInteractionMode>( "pointer" );\n\n // Extract props we compose ourselves so the spread doesn\'t override them\n const {\n onMenuClose: externalOnMenuClose,\n onMenuOpen: externalOnMenuOpen,\n onChange: externalOnChange,\n onKeyDown: externalOnKeyDown,\n filterOption: externalFilterOption,\n ...otherRestProps\n } = restProps;\n\n const { isMulti } = otherRestProps;\n\n // Committed multi-select value shown as chips in the control. When the consumer passes `value`\n // the component is controlled and this tracks it; otherwise (uncontrolled) we own it internally\n // and update it on commit so chips still render.\n const isControlled = value !== undefined;\n // Seed committed/draft state from defaultValue when uncontrolled, so an uncontrolled multi-select\n // starts in sync with what react-select renders rather than an empty draft that would wipe the\n // defaults on the first commit. Only read on the initial render.\n const initialMultiValue = value !== undefined ? value : ( otherRestProps.defaultValue as typeof value );\n const [ committedValue, setCommittedValue ] = useState( initialMultiValue );\n // When controlled, `multiControlValue` reads `value` directly, so `committedValue` is only ever\n // consumed in the uncontrolled path \u2014 no effect mirroring `value` into it is needed.\n const multiControlValue = isControlled ? value : committedValue;\n\n // Draft selection for multi-select. While the menu is open, option toggles update this draft\n // instead of calling onChange; the draft is committed only when the menu closes via an outside\n // click. Pressing Escape discards it. Single-select keeps its live onChange behavior.\n const [ pendingValue, setPendingValue ] = useState( initialMultiValue );\n const pendingValueRef = useRef( pendingValue );\n pendingValueRef.current = pendingValue;\n\n // Keep the draft synced with the committed value while the menu is closed, so external updates\n // are reflected on next open.\n React.useEffect(() => {\n if ( isMulti && !menuOpen ) {\n setPendingValue( multiControlValue );\n }\n }, [ isMulti, menuOpen, multiControlValue ]);\n\n const closeMenu = React.useCallback(() => {\n setMenuOpen( false );\n resetFilter();\n externalOnMenuClose?.();\n }, [ externalOnMenuClose, resetFilter ]);\n\n // Focus returns to whichever input the menu is currently driven from. Deferred a frame because the\n // re-render these callers trigger can rebuild the node focus sits on.\n const refocusMenuInput = React.useCallback(() => {\n requestAnimationFrame(() => focusMenuInput({ searchInputRef, containerRef }));\n }, []);\n\n // The single definition of committing: the draft becomes the value the control renders (so\n // uncontrolled chips appear) and the consumer hears about it once. Every caller differs only in\n // what it commits and what it does afterwards.\n const commitSelection = React.useCallback(( next: typeof pendingValue, actionMeta: unknown ) => {\n setPendingValue( next );\n setCommittedValue( next as typeof committedValue );\n ( externalOnChange as ( ...args: unknown[]) => void )?.( next, actionMeta );\n }, [externalOnChange]);\n\n // Commit the multi-select draft, then close \u2014 what both ways of leaving the menu with the selection\n // intact do: an outside click and Tab.\n const commitAndClose = React.useCallback(() => {\n if ( isMulti ) {\n commitSelection( pendingValueRef.current, { action: "set-value" });\n }\n closeMenu();\n }, [ isMulti, commitSelection, closeMenu ]);\n\n const openMenu = React.useCallback(() => {\n // No need to seed the draft here: the effect above keeps pendingValue synced to the committed\n // value the whole time the menu is closed, so it is already current at open.\n setMenuOpen( true );\n externalOnMenuOpen?.();\n }, [externalOnMenuOpen]);\n\n // Multi-select draft mutators. The control is fed the committed `value` (so chips only appear\n // once the selection is committed), while these update the in-progress draft that drives the\n // menu\'s checkboxes and Select All. Selection is committed to onChange on outside-click close.\n const toggleDraftOption = React.useCallback(( option: IOption ) => {\n setPendingValue(( prev ) => {\n const arr = ( prev as IOption[] | undefined ) ?? [];\n const exists = arr.some(( o ) => o.value === option.value );\n const next = exists ? arr.filter(( o ) => o.value !== option.value ) : [ ...arr, option ];\n return next as typeof pendingValue;\n });\n refocusMenuInput();\n }, [refocusMenuInput]);\n\n // Creating commits on the spot rather than buffering into the draft: the consumer often has to act on\n // a new value at once \u2014 persisting the entity it stands for \u2014 and react-select reports the create as a\n // value-level action for that reason. It is appended to the draft first, so ticks made since the menu\n // opened travel with it instead of being overwritten by a value built from the committed one.\n const commitCreatedOption = React.useCallback(( option: IOption, actionMeta: unknown ) => {\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n // The Create row is only offered for text the selection does not already hold, so a repeat of the\n // same text is the user asking for it again, not asking to take it back.\n const next = draft.some(( o ) => o.value === option.value ) ? draft : [ ...draft, option ];\n commitSelection( next as typeof pendingValue, actionMeta );\n refocusMenuInput();\n }, [ commitSelection, refocusMenuInput ]);\n\n // Removing a chip acts on what the user can see \u2014 the committed chips \u2014 but it must not undo the\n // ticks the menu has collected since it opened. react-select builds its replacement value from the\n // control\'s value, which knows nothing about the draft, so the removal is replayed against the draft\n // instead. With the menu closed the two are in sync, so this lands on the value react-select computed.\n const commitRemovedOption = React.useCallback(( removed: IOption, actionMeta: unknown ) => {\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n commitSelection( draft.filter(( o ) => o.value !== removed.value ) as typeof pendingValue, actionMeta );\n }, [commitSelection]);\n\n const setDraft = React.useCallback(( vals: IOption[]) => {\n setPendingValue( vals as typeof pendingValue );\n refocusMenuInput();\n }, [refocusMenuInput]);\n\n // Async mode, or the presence of onFilterChange, is the client/server mode switch.\n const { isServerFiltered } = optionSource;\n\n // react-select derives the candidate it hands `filterOption` from `getOptionLabel`/`getOptionValue`,\n // so mirror that construction for the Select-All path, where there is no react-select candidate to\n // pass through. Reading them off the spread rather than destructuring keeps them flowing to\n // react-select untouched.\n const { getOptionLabel: externalGetOptionLabel, getOptionValue: externalGetOptionValue } = otherRestProps;\n const toCandidate = React.useCallback(\n ( option: IOption ): FilterOptionOption<IOption> => ({\n // react-select types the candidate label as a string but passes whatever getOptionLabel returns,\n // so an unresolved ReactNode label reaches a consumer predicate here exactly as it does there.\n label: externalGetOptionLabel ? externalGetOptionLabel( option ) : ( option.label as string ),\n value: externalGetOptionValue ? externalGetOptionValue( option ) : option.value,\n data: option\n }),\n [ externalGetOptionLabel, externalGetOptionValue ]\n );\n\n // Options the user has made with the Create row. react-select only ever puts the new value in the\n // selection \u2014 keeping them here is what gives each one an ordinary row in the list, so it can be\n // unticked and ticked again, counts towards "Select All", and stops the Create row being offered for\n // the same text twice. They last as long as the component: a row the user made does not disappear\n // because they cleared it.\n const [ createdOptions, setCreatedOptions ] = useState<readonly IOption[]>( EMPTY_CREATED );\n // Takes the option in the form the consumer is handed, so the row in the list and the value they hold\n // are the same thing \u2014 there is one `toPoolOption` per create, at the callback that reports it.\n const rememberCreatedOption = React.useCallback(( option: IOption ) => {\n setCreatedOptions(( prev ) => (\n prev.some(( o ) => o.value === option.value ) ? prev : [ ...prev, option ]\n ));\n }, []);\n\n // The created options still standing in for a value nothing upstream knows about. A consumer who\n // persists the new entity and passes it back in `options` takes ownership of it from that point: it\n // keeps their row, their grouping and their filtering, and drops out of everything below.\n const unclaimedCreated = React.useMemo(() => {\n if ( createdOptions.length === 0 ) {\n return EMPTY_CREATED;\n }\n const known = getPooledValues( optionSource.options );\n return createdOptions.filter(( o ) => !known.has( o.value ));\n }, [ optionSource.options, createdOptions ]);\n\n // The list react-select is given: the consumer\'s own options, then the created ones they do not\n // already account for.\n const pooledOptions = React.useMemo(\n () => ( unclaimedCreated.length === 0\n ? optionSource.options\n : [ ...optionSource.options, ...unclaimedCreated ]),\n [ optionSource.options, unclaimedCreated ]\n );\n\n const createdValues = React.useMemo(\n () => new Set( unclaimedCreated.map(( o ) => o.value )),\n [unclaimedCreated]\n );\n\n // Deprecated: a second filtering axis alongside `onFilterChange`, which already covers it \u2014 that hands\n // the consumer the query and treats `options` as the answer, so a custom predicate belongs in their own\n // memo rather than in a react-select callback. Still honoured client-side until the next major, since\n // it reached react-select through the prop spread before filtering was owned here. Server-filtered mode\n // ignores it outright: a local predicate there could only hide rows the server deliberately returned,\n // and it cannot see the fields the server matched on.\n useIgnoredPropWarning(\n externalFilterOption !== undefined,\n isServerFiltered ? FILTER_OPTION_IGNORED : FILTER_OPTION_DEPRECATED\n );\n\n // No search input means no query: a seeded `filterValue` narrows the list behind the user\'s back, and\n // `onFilterChange` can only ever fire the one reset on close.\n useIgnoredPropWarning(\n !searchable && ( typeof onFilterChange === "function" || ( filterValue !== undefined && filterValue !== "" )),\n SEARCHABLE_FILTER_IGNORED\n );\n\n // The predicate react-select filters rows with, resolved once so the menu and Select All can never\n // disagree about what is visible. Precedence, highest first: server-filtered mode and\n // `filterOption={null}` (react-select\'s documented opt-out) both do no local pass at all; a consumer\n // `filterOption` then decides; otherwise the library default applies. Keyed on the prop\'s identity, so\n // a predicate that changes behaviour re-narrows the visible set instead of leaving Select All acting on\n // a stale one. The candidate argument is react-select\'s own on the path that has one, so the consumer\n // sees exactly what react-select built there and the Select-All path constructs one only when a\n // predicate is actually going to read it.\n const isOptionVisible = React.useCallback(\n ( option: IOption, input: string, candidate?: FilterOptionOption<IOption> ): boolean => {\n // A created row is the library\'s own, built out of typed text. Every mode that hands narrowing to\n // someone else hands it to someone who has never seen these rows \u2014 the server did not return them,\n // and a consumer predicate is written for the consumer\'s data \u2014 so they are matched here in all of\n // them, or a created row would sit under every unrelated query.\n if ( createdValues.has( option.value )) {\n return matchesQuery( option, input );\n }\n if ( isServerFiltered || externalFilterOption === null ) {\n return true;\n }\n return typeof externalFilterOption === "function"\n ? externalFilterOption( candidate ?? toCandidate( option ), input )\n : matchesQuery( option, input );\n },\n [ externalFilterOption, isServerFiltered, toCandidate, createdValues ]\n );\n\n // The enabled options in the pool, groups flattened. Kept apart from the narrowing below so a\n // keystroke re-runs only the query pass, not the flatten.\n const selectableOptions = React.useMemo(\n () => getSelectableOptions( pooledOptions ),\n [pooledOptions]\n );\n\n // What Select All acts on: the enabled options currently ON SCREEN, so it can never reach an option\n // the query has hidden. Both no-op modes (server-filtered, `filterOption={null}`) are folded into the\n // predicate itself, so there is one pass here regardless of mode.\n const visibleSelectable = React.useMemo(\n () => selectableOptions.filter(( o ) => isOptionVisible( o, filterQuery )),\n [ selectableOptions, isOptionVisible, filterQuery ]\n );\n\n // Read through a ref so handleSelectAllDraft survives every keystroke with its identity intact \u2014\n // see useSelectOptionSource\'s note on what a churning callback costs the whole option context.\n const visibleSelectableRef = useRef( visibleSelectable );\n visibleSelectableRef.current = visibleSelectable;\n\n // Single source of truth for the "Select All" toggle, shared by the mouse path (Option\n // component) and the keyboard path (react-select onChange). If every visible option is already\n // in the draft it deselects down to the fixed ones; otherwise it selects them all. Both\n // directions leave options hidden by the query untouched, so a selection made under one query\n // survives the next.\n const handleSelectAllDraft = React.useCallback(() => {\n const selectable = visibleSelectableRef.current;\n const selectableValues = new Set( selectable.map(( o ) => o.value ));\n const draft = ( pendingValueRef.current as IOption[] | undefined ) ?? [];\n const draftKeys = new Set( draft.map(( o ) => o.value ));\n const next = areAllSelectableSelected( selectable, draftKeys )\n // Deselect: drop selectable, non-fixed options; keep fixed and disabled ones untouched.\n ? draft.filter(( o ) => o.isFixed || !selectableValues.has( o.value ))\n // Select: add every selectable (enabled) option not already present.\n : [ ...draft, ...selectable.filter(( o ) => !draftKeys.has( o.value )) ];\n setDraft( next );\n }, [setDraft]);\n\n useSelectOutsideClose({ menuOpen, menuNodeRef, commitAndClose });\n\n // Prefetch the baseline on first OPEN by default, not on mount: a form with six server-filtered\n // Selects would otherwise fire six requests on paint for menus the user may never open.\n // `prefetch="mount"` opts into the baseline at render, for a Select that would otherwise sit\n // visibly empty.\n usePrefetchBaseline({\n prefetch: prefetch ?? "open",\n isOpen: menuOpen,\n optionsKey,\n ensureDefaults: optionSource.ensureDefaults\n });\n\n // Route an optionsKey CHANGE into the clear path (resetFilter \u2192 onFilterChange("")), which drops the\n // search view and lets ensureDefaults lazily repopulate. Skipped on mount: resetFilter notifies the\n // consumer whenever the query is non-empty, and a seeded `filterValue` must not fire that on paint.\n useOnValueChange( optionsKey, resetFilter );\n\n const {\n base,\n label: labelClass,\n helperText: helperTextClass,\n menuSearchContainer,\n menuSearchInput,\n menuLoader,\n menuError,\n optionLabelWrap,\n optionLabel,\n optionOverlay\n } = selectVariants({ error, searchable });\n\n const searchContainerClass = menuSearchContainer();\n const searchInputClass = menuSearchInput();\n const loaderClass = menuLoader();\n const errorClass = menuError();\n const optionLabelWrapClass = optionLabelWrap();\n const optionLabelClass = optionLabel();\n const optionOverlayClass = optionOverlay();\n\n // Live option config for the stable SelectOption (see selectComponents.tsx). Rebuilt whenever the\n // draft changes so checkbox / Select-All state tracks it; the component identity stays stable.\n const draftValues = React.useMemo(\n () => ( isMulti ? new Set((( pendingValue as IOption[] | undefined ) ?? []).map(( o ) => o.value )) : undefined ),\n [ isMulti, pendingValue ]\n );\n // Computed here, where the visible set lives, rather than in SelectOption from react-select\'s\n // unfiltered `props.options` \u2014 which would leave the row unchecked even with every visible option\n // ticked. A boolean in the context also keeps its identity stable across keystrokes.\n const areAllSelected = React.useMemo(\n () => draftValues !== undefined && areAllSelectableSelected( visibleSelectable, draftValues ),\n [ visibleSelectable, draftValues ]\n );\n const optionContextValue = React.useMemo(\n () => ({\n draftValues,\n areAllSelected,\n onToggleDraftOption: toggleDraftOption,\n onSelectAll: handleSelectAllDraft,\n optionLabelWrapClass,\n optionLabelClass,\n optionOverlayClass,\n interactionMode,\n onInteractionMode: setInteractionMode\n }),\n [ draftValues, areAllSelected, toggleDraftOption, handleSelectAllDraft, optionLabelWrapClass,\n optionLabelClass, optionOverlayClass, interactionMode ]\n );\n\n // Live values the stable, module-level SelectMenu reads via context. SelectMenu must keep a\n // stable identity (react-select remounts custom components on reference change, which would\n // destroy the search input\'s focus/caret and the MenuList scroll on every keystroke), so it\n // cannot close over these directly \u2014 context lets it re-render with current values instead.\n const menuContextValue = React.useMemo<ISelectMenuContext>(\n () => ({\n searchable,\n filterQuery,\n onFilterInput: handleFilterInput,\n onFilterKeyDown: handleFilterKeyDown,\n onFilterKeyUp: handleFilterKeyUp,\n onFilterBlur: handleFilterBlur,\n searchPlaceholder,\n menuFooter,\n closeMenu,\n commitAndClose,\n searchContainerClass,\n searchInputClass,\n loaderClass,\n isLoading: optionSource.isLoading,\n loadError: optionSource.loadError,\n errorClass,\n searchInputRef,\n menuNodeRef,\n containerRef,\n onReload: optionSource.onReload,\n isReloading: optionSource.isReloading,\n reloadTooltip,\n onInteractionMode: setInteractionMode\n }),\n [ searchable, filterQuery, handleFilterInput, handleFilterKeyDown, handleFilterKeyUp, handleFilterBlur,\n searchPlaceholder, menuFooter, closeMenu, commitAndClose, searchContainerClass, searchInputClass,\n loaderClass, errorClass, optionSource.isLoading, optionSource.loadError, optionSource.onReload,\n optionSource.isReloading, reloadTooltip ]\n );\n\n // Without a search box the control carries the menu\'s keyboard model, so the shared handler runs from\n // react-select\'s own container listener instead of from the search input. A consumer handler goes\n // first and can opt out of the built-ins by preventing default \u2014 the contract react-select itself\n // applies to this prop. Tab through a CLOSED multi-select must stay inert, hence the menuOpen guard.\n const handleControlKeyDown = ( e: React.KeyboardEvent<HTMLDivElement> ) => {\n externalOnKeyDown?.( e );\n if ( e.defaultPrevented || searchable || !menuOpen ) {\n return;\n }\n // Nothing to relay here: the control input is where react-select listens, so a key the handler\n // leaves alone reaches it by bubbling.\n handleMenuKey( e, menuContextValue );\n };\n\n // The synthetic Select-All row is prepended to the option set so it keyboard-navigates like any\n // other row. Keyed on the boolean rather than on `visibleSelectable` itself: react-select rebuilds\n // its whole focusable-option index whenever this array\'s identity changes, so it must churn only\n // when the row genuinely appears or disappears \u2014 not on every keystroke.\n const showSelectAll = Boolean( isMulti ) && visibleSelectable.length >= 2;\n const selectOptions = React.useMemo(\n () => ( showSelectAll\n ? [SELECT_ALL_OPTION].concat( pooledOptions as IOption[])\n : pooledOptions ),\n [ showSelectAll, pooledOptions ]\n );\n\n // `Input` holds the DOM focus for as long as a search-less menu is open, and react-select remounts\n // any custom component whose identity changed \u2014 so it is memoised on its own narrow input rather\n // than alongside components that rebuild whenever a consumer passes a fresh icon element.\n const Input = useMemo(() => createSelectInput<IsMulti, Group>( maxVisibleValues ), [maxVisibleValues]);\n\n const customComponents = useMemo(\n () => ({\n ...createSelectComponents<IsMulti, Group>({\n prefixIcon,\n suffixIcon,\n maxVisibleValues,\n maxVisibleValuesMsg,\n disabled\n }),\n IndicatorSeparator: NoIndicatorSeparator,\n Option: SelectOption,\n Input,\n Menu: SelectMenu\n }),\n [ prefixIcon, suffixIcon, maxVisibleValues, maxVisibleValuesMsg, disabled, Input ]\n );\n\n // Select-All and Create are affordances over the result set, not members of it, so neither is ever\n // query-matched \u2014 whether they render at all is decided by `showSelectAll` above and by react-select\'s\n // own `isValidNewOption`. Every real row goes through the resolved predicate, handed react-select\'s own\n // candidate so a consumer predicate sees the label react-select built rather than a reconstruction of it.\n const filterOption = ( candidate: FilterOptionOption<IOption>, input: string ): boolean =>\n ( candidate.data.value === SELECT_ALL_VALUE ||\n isCreateOption( candidate.data ) ||\n isOptionVisible( candidate.data, input, candidate ));\n\n const inputId = useId();\n // unify component type for creatable and default select\n type TRSComponent = ComponentType<ReactSelectProps<IOption, IsMulti, Group>>;\n const SelectType: TRSComponent = creatable\n ? ( CreatableSelect as TRSComponent )\n : ( ReactSelect as TRSComponent );\n\n return (\n <div className={base({ class: className })} ref={rootRef}>\n {label !== undefined && (\n <label\n htmlFor={id || inputId}\n className={labelClass()}\n >\n {label}\n </label>\n )}\n <SelectMenuContext.Provider value={menuContextValue}>\n <SelectOptionContext.Provider value={optionContextValue}>\n <SelectType\n classNamePrefix="select"\n inputId={id || inputId}\n options={selectOptions}\n value={isMulti ? multiControlValue : value}\n hideSelectedOptions={false}\n menuPlacement="auto"\n components={customComponents}\n className={cx( "select", `select-${size}` )}\n styles={\n reactSelectCustomStyles<IsMulti, Group>(\n error,\n size,\n otherRestProps.isMulti as boolean\n )\n }\n isDisabled={disabled}\n {...otherRestProps}\n // Controlled props are applied AFTER the spread so a consumer cannot accidentally\n // override the menu/search mechanism this component owns.\n // A consumer `filterOption` is resolved into this wrapper (see `isOptionVisible`) rather\n // than forwarded, so their predicate still decides every real row while the Select-All row\n // stays exempt from it.\n filterOption={filterOption}\n onKeyDown={handleControlKeyDown}\n // Tab commits the multi-select draft and leaves; letting react-select select the focused\n // option on the way out would toggle a value the user never chose.\n tabSelectsValue={false}\n // Empty when closed \u2014 react-select blanks placeholder/value for a non-empty inputValue.\n inputValue={menuOpen ? filterQuery : ""}\n menuIsOpen={menuOpen}\n onMenuOpen={openMenu}\n /*\n * No-op: react-select calls onMenuClose from its input-blur handler, which\n * fires every time focus moves to the dropdown search input. Honoring it\n * would close the menu immediately. We close explicitly instead \u2014 via\n * outside-click, Escape, and single-select onChange.\n */\n onMenuClose={() => {}}\n onChange={( newValue: unknown, actionMeta: unknown ) => {\n if ( isMulti ) {\n // The control is fed the committed value, so option toggles must route into the draft\n // rather than onChange. Mouse clicks are handled directly in SelectOption; this path\n // only fires for keyboard selection (Enter forwarded to react-select\'s input), which we\n // translate into a draft toggle. The draft is committed when the menu closes via an\n // outside click.\n const meta = actionMeta as { action: string; option?: IOption; removedValue?: IOption };\n // Control-level actions are aimed at the chips rather than at the menu: clearing all,\n // removing a single pill via its X, or popping the last one with Backspace. These\n // commit immediately and notify the consumer; otherwise the change would only land on\n // the next outside-click close (and never reach a controlled `value`). Keyboard option\n // toggles (Enter forwarded to react-select\'s input) are the only path that buffers.\n if ( meta.action === "clear" ) {\n commitSelection( newValue as typeof pendingValue, actionMeta );\n } else if (( meta.action === "remove-value" || meta.action === "pop-value" ) && meta.removedValue ) {\n commitRemovedOption( meta.removedValue, actionMeta );\n } else if ( meta.action === "create-option" && meta.option ) {\n // react-select hands over the finished option \u2014 labelled with the text the user typed,\n // not with the "Create ..." prompt. Clearing the query retires the row that produced it\n // and brings the full list back, the same consumption of the search text a single-select\n // create performs on its way closed.\n const created = toPoolOption( meta.option );\n rememberCreatedOption( created );\n commitCreatedOption( created, { ...meta, option: created });\n resetFilter();\n } else if ( meta.option ) {\n // The injected Select-All row has no dedicated onChange semantics in react-select,\n // so keyboard selection reports it like any option. Route it through the shared\n // handler instead of buffering the synthetic row into the draft.\n if ( meta.option.value === SELECT_ALL_VALUE ) {\n handleSelectAllDraft();\n } else {\n toggleDraftOption( meta.option );\n }\n }\n } else {\n // Single-select reports a create through the same callback as any other pick, so the new\n // row is recorded here rather than on a branch of its own.\n const meta = actionMeta as { action: string; option?: IOption };\n const created = meta.action === "create-option" && meta.option\n ? toPoolOption( meta.option )\n : undefined;\n if ( created ) {\n rememberCreatedOption( created );\n }\n // Close the menu and commit immediately after a single-value selection.\n closeMenu();\n ( externalOnChange as ( ...args: unknown[]) => void )?.(\n created ?? newValue,\n created ? { ...meta, option: created } : actionMeta\n );\n }\n }}\n closeMenuOnSelect={!isMulti}\n />\n </SelectOptionContext.Provider>\n </SelectMenuContext.Provider>\n {helperText && (\n <div className={helperTextClass()}>\n {helperText}\n </div>\n )}\n </div>\n );\n}\n\nconst SelectWithRef = React.forwardRef( SelectComponent );\nSelectWithRef.displayName = "Select";\n\n/**\n * Select component for single or multi selection. The forwarded ref lands on the wrapper `<div>`; the\n * cast is what stops `forwardRef` \u2014 whose own signature is not generic \u2014 from collapsing `IsMulti` /\n * `Group` to their defaults.\n */\nexport const Select = SelectWithRef as unknown as <\n IsMulti extends boolean = false,\n Group extends GroupBase<IOption> = GroupBase<IOption>\n>(\n props: ISelectProps<IsMulti, Group> & RefAttributes<HTMLDivElement>\n) => ReactElement;\n'
3606
3697
  },
3607
3698
  {
3608
3699
  "name": "index.ts",
@@ -3610,7 +3701,7 @@ SelectMenu.displayName = "SelectMenu";
3610
3701
  },
3611
3702
  {
3612
3703
  "name": "README.md",
3613
- "content": '# Select Component\n\n## Component Overview\n\nThe Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality, custom rendering, and keyboard navigation.\n\n**When to use:**\n- Form fields requiring single selection from options\n- Filtering interfaces\n- Settings and preferences selection\n- Any scenario requiring choice from predefined list\n\n**Component Architecture:**\n- Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation\n- Styled with Tailwind CSS and `tailwind-variants` (`tv()`)\n- Search input lives inside the dropdown; filtering is client-side by default, or delegated to the\n parent via `onFilterChange` (see [Filtering](#filtering))\n- Accessible with proper ARIA attributes\n\n## Basic Usage\n\n```tsx\nimport { Select } from "@components";\n\nexport function Example() {\n const options = [\n { label: "Option 1", value: "1" },\n { label: "Option 2", value: "2" },\n { label: "Option 3", value: "3" }\n ];\n \n return (\n <Select \n label="Choose Option"\n options={options}\n onChange={(value) => console.log(value)}\n />\n );\n}\n```\n\n**Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/select` or `@components/select`.\n\n## Component Props\n\n| Prop | Type | Default | Required | Description |\n|------|------|---------|----------|-------------|\n| `options` | `IOption[] \\| GroupBase<IOption>[]` | `[]` | No | Array of selectable options or option groups |\n| `value` | `IOption \\| IOption[] \\| null` | `undefined` | No | Controlled value (single option or array for multi-select) |\n| `onChange` | `(value: any) => void` | - | No | Callback when selection changes |\n| `label` | `React.ReactNode` | `undefined` | No | Label displayed above the select |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Select size variant |\n| `helperText` | `React.ReactNode` | `undefined` | No | Helper text displayed below the select |\n| `error` | `boolean` | `false` | No | Display error styling |\n| `disabled` | `boolean` | `false` | No | Disable the select |\n| `creatable` | `boolean` | `false` | No | Enable creatable select (allows creating new options) |\n| `touched` | `boolean` | `undefined` | No | Field touched state (useful for form validation) |\n| `maxVisibleValues` | `number` | `3` | No | Max number of visible values in multi-select before truncating |\n| `maxVisibleValuesMsg` | `string` | `undefined` | No | Label for truncated values (e.g., "+2 more") |\n| `menuFooter` | `React.ReactNode` | `undefined` | No | Custom footer content in the dropdown menu |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the search input inside the dropdown |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown\'s search input and re-syncs it whenever this value changes (not fully controlled \u2014 see [Filtering](#filtering)) |\n| `onFilterChange` | `(query: string) => void` | - | No | Server-side filter handler. When provided, client-side filtering is skipped |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously |\n| `isLoading` | `boolean` | `false` | No | Replaces the option list with a loader while a fetch is in flight |\n| `loadOptions` | `(query: string, meta: ILoadOptionsMeta) => Promise<IOption[] \\| IOptionPage<IOption>>` | - | No | Async option source. Switches the component into [async mode](#filtering--async-loading): it owns the option list, the request lifecycle and the loading state |\n| `initialOptions` | `readonly IOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered baseline. `"open"` on first menu open; `"mount"` at render, before any interaction; `"never"` only once the user types. Async mode only |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. Costs one request per menu close |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set, for dependent selects. A change drops cached results and repopulates. Does **not** clear the selection |\n| `loadErrorMessage` | `React.ReactNode` | `"Couldn\'t load options."` | No | Shown in the menu when `loadOptions` rejects |\n| `showReloadButton` | `boolean` | `false` | No | Shows the menu\'s reload button in async mode, wired to re-run the current query |\n| `onLoadError` | `(error: unknown) => void` | - | No | Notified when a load rejects (the component renders `loadErrorMessage` and swallows it) |\n| `onReload` | `() => void` | - | No | Shows a reload button in the dropdown header; fired on click |\n| `isReloading` | `boolean` | `undefined` | No | Spins and disables the reload button |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip / aria-label for the reload button |\n| `prefixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the start of the select control |\n| `suffixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the end of the select control |\n| `id` | `string` | `undefined` | No | Unique id for the select input |\n| `placeholder` | `string` | `"Select..."` | No | Placeholder text |\n| `isClearable` | `boolean` | `false` | No | Show clear button |\n| `isMulti` | `boolean` | `false` | No | Enable multi-select mode |\n| `className` | `string` | `undefined` | No | Additional CSS classes for wrapper |\n| `ref` | `Ref<HTMLDivElement>` | `undefined` | No | Forwarded to the wrapper `<div>` \u2014 for programmatic focus/scroll and form libraries that bind by ref |\n\n### Option Object (IOption)\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `ReactNode` | Yes | Display content for the option (plain text or custom JSX) |\n| `value` | `any` | Yes | Value of the option |\n| `searchValue` | `string` | No | Plain text used for search matching. Set this when `label` is custom JSX, otherwise the option can\'t be found by typing its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Whether option is disabled |\n\n## Filtering & async loading\n\nThree modes, picked by which props you pass:\n\n| Mode | Pass | Who filters | Who fetches |\n|---|---|---|---|\n| **Client-side** (default) | nothing | Select, via `matchesQuery` | \u2014 |\n| **You own the list** | `onFilterChange` + `options` | you | you (if any) |\n| **Async** | `loadOptions` | your server | Select |\n\n- **Client-side** \u2014 the search box filters `options` locally. Matching checks an option\'s `searchValue`\n first, then a string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom\n JSX so they stay findable by their visible text.\n- **`onFilterChange`** \u2014 Select stops filtering and hands you the (debounced) query; whatever you pass\n as `options` is taken as the answer for it. Use it to fetch from a server, **and equally for a\n local list whose matching rules are your own** (fuzzy, scoped to a field, ranked) \u2014 pair it with\n `filterDebounceMs={0}` and no fetch. Pass `isLoading` while a fetch is in flight.\n- **`loadOptions`** \u2014 for a server-backed list you don\'t want to hold in state: Select owns the option\n list, the request lifecycle and the loading state. `options` is ignored (dev warning) and\n `onFilterChange`, if still passed, becomes notification-only. See [Async mode](#async-mode-loadoptions).\n\n```tsx\nfunction ServerSideSelect() {\n const [options, setOptions] = useState<IOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n const handleFilterChange = async (query: string) => {\n setIsLoading(true);\n setOptions(await fetchOptions(query));\n setIsLoading(false);\n };\n\n return (\n <Select\n label="User"\n placeholder="Select a user..."\n options={options}\n onFilterChange={handleFilterChange}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\nBehaviour worth knowing:\n\n- **The query is cleared when the dropdown closes, and `onFilterChange("")` fires** (only if the\n query was non-empty), so your `options` never stay filtered by a query the user can no longer see.\n Any pending debounced query is dropped first, so the reset always wins.\n- A pending debounce is also cancelled on unmount and whenever `filterValue` changes.\n- **Backspace/Delete holds defer the debounce.** The OS key-repeat gap (~500ms) is longer than the\n default `filterDebounceMs` (300), so debouncing each mid-hold change would fire `onFilterChange`\n with a half-cleared query before the key is released. While either key is held the input still\n updates live, but the debounce only starts on keyup (or blur if focus leaves mid-hold).\n- **`filterValue` is a seed plus an external sync, not a fully controlled value.** The search box\n owns its own text: it updates as the user types and when the component clears it on close. Passing\n a *new* `filterValue` overwrites it; re-passing the same one does not pull it back. Wiring\n `onFilterChange` back into the state you pass as `filterValue` keeps the two in step.\n- **`isLoading` replaces the option list with a loader**, keeping the search input and `menuFooter` in\n place. The rows underneath belong to the previous query, so leaving them clickable would let the\n user pick an option the incoming result set no longer contains. It also means an empty-and-loading\n dropdown shows the loader alone rather than "No options". Arrow/Enter are ignored for the same\n reason while the loader is up \u2014 otherwise the keyboard could still reach a row that is off screen.\n- `isLoading` is **not forwarded to react-select**, so its own control indicator and "Loading..."\n message never appear and `loadingMessage` has no effect.\n- **"Select All"** (multi-select) covers the options the active search leaves **visible** \u2014 in server\n mode, every option the server returned for the current query. It is not "all server-side matches".\n The row itself is never query-matched, so it stays put while you type; it is hidden only when\n fewer than two selectable options are on screen, where it would duplicate a single row\'s own\n checkbox or have nothing to act on. Toggling it off removes only those visible options, so a\n selection made under an earlier query survives. **Grouped options are included**: groups are\n flattened, so a list that mixes loose options and groups is covered in render order.\n- With `creatable`, the Create row is no longer auto-suppressed while loading (react-select gates\n that on the `isLoading` it never receives). Gate it with `isValidNewOption` if you need that. In\n server mode the Create row is also matched against the *loaded* options, which lag the query by\n `filterDebounceMs`, so it can flash mid-typing.\n- Never pass `noOptionsMessage={() => null}` \u2014 react-select bails out of rendering the menu entirely\n and the dropdown, search input included, disappears.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above is a two-part contract: the component debounces the query, you own the\nresults. But **debouncing limits how often a request starts, not how many are in flight** \u2014 type\n`sal`, pause past the debounce, type `es`, and if the first response arrives last it overwrites the\nsecond. Every server-filtered call site therefore has to hand-write the same monotonic-ticket guard,\nand the one that forgets ships a bug that is invisible on a fast connection.\n\n`loadOptions` moves that, the results state and the `isLoading` bookkeeping into the component:\n\n```tsx\n<Select\n label="Dataset"\n isMulti\n loadOptions={async (query, { signal }) => {\n const res = await fetchDatasets({ filterExpression: `DatasetName:*${query}*`, signal });\n return res.datasets\n .filter(isWriteAccessible) // domain rules stay yours\n .map((d) => ({ value: d.DatasetId, label: `${d.Domain} : ${d.DisplayName}`, name: d.DatasetName }));\n }}\n/>\n```\n\n`loadOptions` **fetches and maps**. Response envelopes, pagination shapes and domain filtering are all\nthe consumer\'s business \u2014 the component never sees the raw payload. A fresh inline arrow costs nothing:\nthe loader is read through a ref, so it never re-triggers a fetch or invalidates a memo.\n\n`meta` carries `{ signal, cursor, page, reason }`. Return either a bare `IOption[]` or a page envelope\n`{ options, cursor?, hasMore?, total? }`.\n\nBehaviour worth knowing:\n\n1. **Ordering is guaranteed.** A response is accepted only if it is still the newest request for its\n slot. Honouring `meta.signal` is **optional** \u2014 it only saves you paying for a response nobody\n wants; correctness comes from the internal guard either way.\n2. **Clearing the search restores the cached baseline, with no request.** The empty-query result and\n the current-query result live in separate buckets, so a menu close (which fires\n `onFilterChange("")`) restores rather than destroys. Pass `refetchOnClear` to *also* revalidate;\n the stale rows stay on screen while that request runs, so the list never blanks.\n3. **`filterValue` does not trigger fetches in async mode.** The shared filter hook deliberately\n cancels the debounce *without* notifying when `filterValue` changes, so a programmatic query change\n updates the search box only. Changing that would alter `MultiSelectTransfer`\'s behaviour too. If you\n need to force a reload, use `optionsKey`.\n4. **`optionsKey` does not clear the committed selection.** Whether a stale child value is invalid is a\n domain rule, and clearing a controlled `value` from inside the component means firing an `onChange`\n the consumer never asked for \u2014 unblockable in Formik or React Hook Form. **Watch for this:** options\n pass through opaquely, so a stale selection renders its own label perfectly and fails silently at\n submit. Clear it yourself in the parent when your domain says it is invalid.\n5. **Page one only.** `cursor` / `hasMore` / `total` in the resolved page are ignored, and a page\n reporting `hasMore: true` raises a one-time dev warning \u2014 there is no infinite-scroll surface in\n react-select\'s menu. Use `MultiSelectTransfer` for a paged source.\n6. **Option groups are unsupported in async mode.** The loader returns `readonly IOption[]`; groups are\n a sync-mode-only shape.\n7. **"Select All"** (multi-select) still covers only what is currently loaded and visible \u2014 every\n option the server returned for the current query, not "all server-side matches".\n8. A rejection replaces the rows with `loadErrorMessage` in `role="alert"`, blocks Arrow/Enter for the\n same reason the loader does, and auto-shows the reload button as the retry affordance. `onLoadError`\n receives the raw cause for logging.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame, so there is no loader to sit through, and they stay\non screen while the baseline fetch revalidates over them. This is the one thing `prefetch` cannot do:\n`prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<Select\n label="Dataset"\n initialOptions={ssrDatasets} // painted immediately\n loadOptions={fetchDatasets} // still runs, and replaces them when it lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a heavy\nsource you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<Select initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty menu.\n\nA *search* replaces seed rows, because they are not results for a query; clearing the search brings them\nback until a fetched baseline lands. And seed rows only mean something to the async source \u2014 passing\n`initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong in\n`options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Practical Examples\n\n### Form Field\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FormWithSelect() {\n const [country, setCountry] = useState("");\n \n const countries = [\n { label: "United States", value: "us" },\n { label: "Canada", value: "ca" },\n { label: "United Kingdom", value: "uk" },\n { label: "Germany", value: "de" }\n ];\n \n return (\n <form>\n <Select\n label="Country"\n options={countries}\n value={country}\n onChange={setCountry}\n required\n searchable\n />\n </form>\n );\n}\n```\n\n### Filter with Clear\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FilterSelect() {\n const [status, setStatus] = useState("");\n \n const statusOptions = [\n { label: "Active", value: "active" },\n { label: "Inactive", value: "inactive" },\n { label: "Pending", value: "pending" }\n ];\n \n return (\n <Select\n label="Filter by Status"\n options={statusOptions}\n value={status}\n onChange={setStatus}\n clearable\n placeholder="All statuses"\n />\n );\n}\n```\n\n### Disabled State\n\n```tsx\n<Select\n label="Disabled Select"\n options={options}\n disabled\n value="option1"\n/>\n```\n\n## Technical Details\n\n### State Management\n\n- Supports both controlled and uncontrolled modes\n- Use `value` + `onChange` for controlled\n- Use `defaultValue` for uncontrolled\n- The search query is owned internally and seeded from `filterValue`; a *change* to `filterValue`\n overwrites it and cancels any in-flight debounced `onFilterChange`\n\n### Filtering\n\n- Without `onFilterChange`, options are filtered locally via the shared `matchesQuery` helper, which\n is also used by `TransferList` and `MultiSelectTransfer`.\n- With `onFilterChange`, filtering is delegated to the parent and the query is debounced\n (`filterDebounceMs`). A pending debounce is cancelled on unmount, on an external `filterValue`\n reset, and when the dropdown closes \u2014 where `onFilterChange("")` fires instead so the parent\'s\n result set matches the now-empty search box. While Backspace/Delete is held the debounce is\n deferred until keyup (or blur), so a long-press cannot fire mid-hold. This lives in the shared\n `useFilterQuery` hook, which `MultiSelectTransfer` also uses, so its identically-named filter\n props behave identically.\n- `isLoading` renders the loader in place of react-select\'s menu list, which also keeps it out of the\n list\'s `role="listbox"` subtree (that role only accepts option children). Suppressing the "No\n options" notice this way is deliberate: returning `null` from react-select\'s `noOptionsMessage`\n makes it skip rendering the menu altogether, taking the search input with it.\n- `MultiSelectTransfer` behaves the same for a search fetch, but keeps appending the loader below the\n rows for a load-more it triggered itself, so pagination doesn\'t lose the scroll position.\n\n## Accessibility\n\n**Implemented:**\n- ARIA attributes for screen readers\n- Keyboard navigation (Arrow keys, Enter, ESC)\n- Focus management\n- Proper labeling\n\n**Best Practices:**\n- Always provide a label\n- Use descriptive option labels\n- Mark required fields\n- Provide error messages\n'
3704
+ "content": '# Select Component\n\n## Component Overview\n\nThe Select component provides a dropdown selection interface for choosing one option from a list. It includes search functionality (hidden with `searchable={false}`), custom rendering, and keyboard navigation.\n\n**When to use:**\n- Form fields requiring single selection from options\n- Filtering interfaces\n- Settings and preferences selection\n- Any scenario requiring choice from predefined list\n\n**Component Architecture:**\n- Built on `react-select`, which handles positioning (`menuPlacement="auto"`) and keyboard navigation\n- Styled with Tailwind CSS and `tailwind-variants` (`tv()`)\n- Search input lives inside the dropdown unless `searchable={false}` hides it; filtering is\n client-side by default, or delegated to the parent via `onFilterChange` (see [Filtering](#filtering))\n- Accessible with proper ARIA attributes\n\n## Basic Usage\n\n```tsx\nimport { Select } from "@components";\n\nexport function Example() {\n const options = [\n { label: "Option 1", value: "1" },\n { label: "Option 2", value: "2" },\n { label: "Option 3", value: "3" }\n ];\n \n return (\n <Select \n label="Choose Option"\n options={options}\n onChange={(value) => console.log(value)}\n />\n );\n}\n```\n\n**Note:** Update the import path based on your project structure. If you used the Astral UI CLI, the typical import path would be `@components/ui/select` or `@components/select`.\n\n## Component Props\n\n| Prop | Type | Default | Required | Description |\n|------|------|---------|----------|-------------|\n| `options` | `IOption[] \\| GroupBase<IOption>[]` | `[]` | No | Array of selectable options or option groups |\n| `value` | `IOption \\| IOption[] \\| null` | `undefined` | No | Controlled value (single option or array for multi-select) |\n| `onChange` | `(value: any) => void` | - | No | Callback when selection changes |\n| `label` | `React.ReactNode` | `undefined` | No | Label displayed above the select |\n| `size` | `\'md\' \\| \'lg\'` | `\'md\'` | No | Select size variant |\n| `helperText` | `React.ReactNode` | `undefined` | No | Helper text displayed below the select |\n| `error` | `boolean` | `false` | No | Display error styling |\n| `disabled` | `boolean` | `false` | No | Disable the select |\n| `creatable` | `boolean` | `false` | No | Enable creatable select (allows creating new options) |\n| `touched` | `boolean` | `undefined` | No | Field touched state (useful for form validation) |\n| `maxVisibleValues` | `number` | `3` | No | Max number of visible values in multi-select before truncating |\n| `maxVisibleValuesMsg` | `string` | `undefined` | No | Label for truncated values (e.g., "+2 more") |\n| `menuFooter` | `React.ReactNode` | `undefined` | No | Custom footer content in the dropdown menu |\n| `searchable` | `boolean` | `true` | No | Renders the search input inside the dropdown. `false` hides it and nothing else \u2014 the reload button, `menuFooter`, "Select All" and the whole keyboard model stay, with focus sitting on the control\'s own input. Suits lists short enough to scan; with no query, `onFilterChange` can never fire (dev warning) |\n| `searchPlaceholder` | `string` | `"Search..."` | No | Placeholder for the search input inside the dropdown. Ignored when `searchable={false}` |\n| `filterValue` | `string` | `undefined` | No | Seeds the dropdown\'s search input and re-syncs it whenever this value changes (not fully controlled \u2014 see [Filtering](#filtering)) |\n| `onFilterChange` | `(query: string) => void` | - | No | Server-side filter handler. When provided, client-side filtering is skipped |\n| `filterDebounceMs` | `number` | `300` | No | Debounce delay (ms) for `onFilterChange`. Set to `0` to fire synchronously |\n| `isLoading` | `boolean` | `false` | No | Replaces the option list with a loader while a fetch is in flight |\n| `loadOptions` | `(query: string, meta: ILoadOptionsMeta) => Promise<IOption[] \\| IOptionPage<IOption>>` | - | No | Async option source. Switches the component into [async mode](#filtering--async-loading): it owns the option list, the request lifecycle and the loading state |\n| `initialOptions` | `readonly IOption[]` | `undefined` | No | Seed rows for a list you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the baseline fetch revalidates over them \u2014 see [Seeding with `initialOptions`](#seeding-with-initialoptions). Async mode only |\n| `prefetch` | `"mount" \\| "open" \\| "never"` | `"open"` | No | When to fetch the unfiltered baseline. `"open"` on first menu open; `"mount"` at render, before any interaction; `"never"` only once the user types. Async mode only |\n| `refetchOnClear` | `boolean` | `false` | No | Clearing the search revalidates the cached baseline instead of only restoring it. Costs one request per menu close |\n| `optionsKey` | `string \\| number` | `undefined` | No | Identity of the option set, for dependent selects. A change drops cached results and repopulates. Does **not** clear the selection |\n| `loadErrorMessage` | `React.ReactNode` | `"Couldn\'t load options."` | No | Shown in the menu when `loadOptions` rejects |\n| `showReloadButton` | `boolean` | `false` | No | Shows the menu\'s reload button in async mode, wired to re-run the current query |\n| `onLoadError` | `(error: unknown) => void` | - | No | Notified when a load rejects (the component renders `loadErrorMessage` and swallows it) |\n| `onReload` | `() => void` | - | No | Shows a reload button in the dropdown header; fired on click |\n| `isReloading` | `boolean` | `undefined` | No | Spins and disables the reload button |\n| `reloadTooltip` | `string` | `"Reload"` | No | Tooltip / aria-label for the reload button |\n| `prefixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the start of the select control |\n| `suffixIcon` | `IconType \\| React.ReactNode` | `undefined` | No | Icon displayed at the end of the select control |\n| `id` | `string` | `undefined` | No | Unique id for the select input |\n| `placeholder` | `string` | `"Select..."` | No | Placeholder text |\n| `isClearable` | `boolean` | `false` | No | Show clear button |\n| `isMulti` | `boolean` | `false` | No | Enable multi-select mode |\n| `className` | `string` | `undefined` | No | Additional CSS classes for wrapper |\n| `ref` | `Ref<HTMLDivElement>` | `undefined` | No | Forwarded to the wrapper `<div>` \u2014 for programmatic focus/scroll and form libraries that bind by ref |\n\n### Option Object (IOption)\n\n| Property | Type | Required | Description |\n|----------|------|----------|-------------|\n| `label` | `ReactNode` | Yes | Display content for the option (plain text or custom JSX) |\n| `value` | `any` | Yes | Value of the option |\n| `searchValue` | `string` | No | Plain text used for search matching. Set this when `label` is custom JSX, otherwise the option can\'t be found by typing its visible text. Takes precedence over `label`/`value`. |\n| `isDisabled` | `boolean` | No | Whether option is disabled |\n\n## Filtering & async loading\n\nThree modes, picked by which props you pass:\n\n| Mode | Pass | Who filters | Who fetches |\n|---|---|---|---|\n| **Client-side** (default) | nothing | Select, via `matchesQuery` | \u2014 |\n| **You own the list** | `onFilterChange` + `options` | you | you (if any) |\n| **Async** | `loadOptions` | your server | Select |\n\n- **Client-side** \u2014 the search box filters `options` locally. Matching checks an option\'s `searchValue`\n first, then a string `label`, then its `value` \u2014 set `searchValue` on options whose `label` is custom\n JSX so they stay findable by their visible text.\n- **`onFilterChange`** \u2014 Select stops filtering and hands you the (debounced) query; whatever you pass\n as `options` is taken as the answer for it. Use it to fetch from a server, **and equally for a\n local list whose matching rules are your own** (fuzzy, scoped to a field, ranked) \u2014 pair it with\n `filterDebounceMs={0}` and no fetch. Pass `isLoading` while a fetch is in flight.\n- **`loadOptions`** \u2014 for a server-backed list you don\'t want to hold in state: Select owns the option\n list, the request lifecycle and the loading state. `options` is ignored (dev warning) and\n `onFilterChange`, if still passed, becomes notification-only. See [Async mode](#async-mode-loadoptions).\n- **No search at all** \u2014 `searchable={false}` removes the search box, and that is the only change: the\n reload button, `menuFooter`, "Select All" and Arrow/Enter/Escape/Tab all behave as before, because\n react-select\'s control input \u2014 not the in-dropdown box \u2014 is what owns focus and option navigation\n while the menu is open. Space and Home/End join them there: with no field to type into, Space\n activates the focused row and Home/End jump to the ends of the list. With no box there is no query, so `filterValue`, `filterDebounceMs` and\n `onFilterChange` have nothing to act on; passing them alongside it raises a dev warning.\n\n```tsx\nfunction ServerSideSelect() {\n const [options, setOptions] = useState<IOption[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n\n const handleFilterChange = async (query: string) => {\n setIsLoading(true);\n setOptions(await fetchOptions(query));\n setIsLoading(false);\n };\n\n return (\n <Select\n label="User"\n placeholder="Select a user..."\n options={options}\n onFilterChange={handleFilterChange}\n filterDebounceMs={300}\n isLoading={isLoading}\n />\n );\n}\n```\n\nBehaviour worth knowing:\n\n- **The query is cleared when the dropdown closes, and `onFilterChange("")` fires** (only if the\n query was non-empty), so your `options` never stay filtered by a query the user can no longer see.\n Any pending debounced query is dropped first, so the reset always wins.\n- A pending debounce is also cancelled on unmount and whenever `filterValue` changes.\n- **Backspace/Delete holds defer the debounce.** The OS key-repeat gap (~500ms) is longer than the\n default `filterDebounceMs` (300), so debouncing each mid-hold change would fire `onFilterChange`\n with a half-cleared query before the key is released. While either key is held the input still\n updates live, but the debounce only starts on keyup (or blur if focus leaves mid-hold).\n- **`filterValue` is a seed plus an external sync, not a fully controlled value.** The search box\n owns its own text: it updates as the user types and when the component clears it on close. Passing\n a *new* `filterValue` overwrites it; re-passing the same one does not pull it back. Wiring\n `onFilterChange` back into the state you pass as `filterValue` keeps the two in step.\n- **`isLoading` replaces the option list with a loader**, keeping the search input (where shown) and\n `menuFooter` in place. The rows underneath belong to the previous query, so leaving them clickable would let the\n user pick an option the incoming result set no longer contains. It also means an empty-and-loading\n dropdown shows the loader alone rather than "No options". Arrow/Enter are ignored for the same\n reason while the loader is up \u2014 otherwise the keyboard could still reach a row that is off screen.\n- `isLoading` is **not forwarded to react-select**, so its own control indicator and "Loading..."\n message never appear and `loadingMessage` has no effect.\n- **"Select All"** (multi-select) covers the options the active search leaves **visible** \u2014 in server\n mode, every option the server returned for the current query. It is not "all server-side matches".\n The row itself is never query-matched, so it stays put while you type; it is hidden only when\n fewer than two selectable options are on screen, where it would duplicate a single row\'s own\n checkbox or have nothing to act on. Toggling it off removes only those visible options, so a\n selection made under an earlier query survives. **Grouped options are included**: groups are\n flattened, so a list that mixes loose options and groups is covered in render order.\n- With `creatable`, the Create row is no longer auto-suppressed while loading (react-select gates\n that on the `isLoading` it never receives). Gate it with `isValidNewOption` if you need that. In\n server mode the Create row is also matched against the *loaded* options, which lag the query by\n `filterDebounceMs`, so it can flash mid-typing.\n- **The Create row is an action, not an option**, in multi-select as much as in single-select: it\n stands for a value that does not exist yet, so it carries no checkbox and nothing in the draft\n answers for it. Picking it reports the created option straight away \u2014 `onChange( [...selection,\n created], { action: "create-option" } )`, with the option labelled by what was typed rather than by\n the prompt \u2014 instead of waiting for the menu to close, and clears the search text that produced it.\n Ticks made since the menu opened commit along with it. The option you are handed is a plain\n `{ label, value }`: react-select\'s `__isNew__` marker is stripped, because here that flag means "this\n row is the Create affordance" and would turn the option into one. `action: "create-option"` is the\n signal that it is new.\n- **What a create produces then joins the list**, in both modes. react-select leaves the new value in\n the selection alone and expects you to put it back into `options` yourself (its docs\' Advanced\n example does exactly that from `onCreateOption`); Select owns the option list already, so it keeps\n created options for you. Each one becomes an ordinary row: it has a checkbox in multi-select, can be\n unticked and picked again, counts towards "Select All", is matched by the search, and stops the\n Create row being offered a second time for the same text. They last as long as the component \u2014\n clearing the selection does not take the row away. Supplying the same value in `options` later (say\n after persisting it) takes ownership of it, leaving one row rather than two. Passing your own\n `onCreateOption` opts out of all of this: react-select hands the text to you and nothing is created\n or recorded here.\n- Never pass `noOptionsMessage={() => null}` \u2014 react-select bails out of rendering the menu entirely\n and the dropdown, search input included, disappears. That is unrelated to `searchable`, which hides\n the search box and leaves the menu in place.\n\n## Async mode (`loadOptions`)\n\nServer-side filtering above is a two-part contract: the component debounces the query, you own the\nresults. But **debouncing limits how often a request starts, not how many are in flight** \u2014 type\n`sal`, pause past the debounce, type `es`, and if the first response arrives last it overwrites the\nsecond. Every server-filtered call site therefore has to hand-write the same monotonic-ticket guard,\nand the one that forgets ships a bug that is invisible on a fast connection.\n\n`loadOptions` moves that, the results state and the `isLoading` bookkeeping into the component:\n\n```tsx\n<Select\n label="Dataset"\n isMulti\n loadOptions={async (query, { signal }) => {\n const res = await fetchDatasets({ filterExpression: `DatasetName:*${query}*`, signal });\n return res.datasets\n .filter(isWriteAccessible) // domain rules stay yours\n .map((d) => ({ value: d.DatasetId, label: `${d.Domain} : ${d.DisplayName}`, name: d.DatasetName }));\n }}\n/>\n```\n\n`loadOptions` **fetches and maps**. Response envelopes, pagination shapes and domain filtering are all\nthe consumer\'s business \u2014 the component never sees the raw payload. A fresh inline arrow costs nothing:\nthe loader is read through a ref, so it never re-triggers a fetch or invalidates a memo.\n\n`meta` carries `{ signal, cursor, page, reason }`. Return either a bare `IOption[]` or a page envelope\n`{ options, cursor?, hasMore?, total? }`.\n\nBehaviour worth knowing:\n\n1. **Ordering is guaranteed.** A response is accepted only if it is still the newest request for its\n slot. Honouring `meta.signal` is **optional** \u2014 it only saves you paying for a response nobody\n wants; correctness comes from the internal guard either way.\n2. **Clearing the search restores the cached baseline, with no request.** The empty-query result and\n the current-query result live in separate buckets, so a menu close (which fires\n `onFilterChange("")`) restores rather than destroys. Pass `refetchOnClear` to *also* revalidate;\n the stale rows stay on screen while that request runs, so the list never blanks.\n3. **`filterValue` does not trigger fetches in async mode.** The shared filter hook deliberately\n cancels the debounce *without* notifying when `filterValue` changes, so a programmatic query change\n updates the search box only. Changing that would alter `MultiSelectTransfer`\'s behaviour too. If you\n need to force a reload, use `optionsKey`.\n4. **`optionsKey` does not clear the committed selection.** Whether a stale child value is invalid is a\n domain rule, and clearing a controlled `value` from inside the component means firing an `onChange`\n the consumer never asked for \u2014 unblockable in Formik or React Hook Form. **Watch for this:** options\n pass through opaquely, so a stale selection renders its own label perfectly and fails silently at\n submit. Clear it yourself in the parent when your domain says it is invalid.\n5. **Page one only.** `cursor` / `hasMore` / `total` in the resolved page are ignored, and a page\n reporting `hasMore: true` raises a one-time dev warning \u2014 there is no infinite-scroll surface in\n react-select\'s menu. Use `MultiSelectTransfer` for a paged source.\n6. **Option groups are unsupported in async mode.** The loader returns `readonly IOption[]`; groups are\n a sync-mode-only shape.\n7. **"Select All"** (multi-select) still covers only what is currently loaded and visible \u2014 every\n option the server returned for the current query, not "all server-side matches".\n8. A rejection replaces the rows with `loadErrorMessage` in `role="alert"`, blocks Arrow/Enter for the\n same reason the loader does, and auto-shows the reload button as the retry affordance. `onLoadError`\n receives the raw cause for logging.\n\n### Seeding with `initialOptions`\n\n`initialOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route loader, a\nwarm query cache. They are painted on the first frame, so there is no loader to sit through, and they stay\non screen while the baseline fetch revalidates over them. This is the one thing `prefetch` cannot do:\n`prefetch="mount"` still costs a round trip before anything appears.\n\n```tsx\n<Select\n label="Dataset"\n initialOptions={ssrDatasets} // painted immediately\n loadOptions={fetchDatasets} // still runs, and replaces them when it lands\n/>\n```\n\nIt does **not** suppress the baseline fetch. If the seed *is* the whole list until the user types \u2014 a heavy\nsource you do not want to hit on open \u2014 pair it with `prefetch="never"`:\n\n```tsx\n<Select initialOptions={recentlyUsed} prefetch="never" loadOptions={searchEverything} />\n```\n\nWithout `initialOptions`, that combination opens to an empty menu.\n\nA *search* replaces seed rows, because they are not results for a query; clearing the search brings them\nback until a fetched baseline lands. And seed rows only mean something to the async source \u2014 passing\n`initialOptions` without `loadOptions` is ignored with a dev warning, because those rows belong in\n`options`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadOptions` there is no fetch to schedule. Passing it there is ignored with a dev warning.\n\n## Practical Examples\n\n### Form Field\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FormWithSelect() {\n const [country, setCountry] = useState("");\n \n const countries = [\n { label: "United States", value: "us" },\n { label: "Canada", value: "ca" },\n { label: "United Kingdom", value: "uk" },\n { label: "Germany", value: "de" }\n ];\n \n return (\n <form>\n <Select\n label="Country"\n options={countries}\n value={country}\n onChange={setCountry}\n />\n </form>\n );\n}\n```\n\n### Filter with Clear\n\n```tsx\nimport { Select } from "@components";\nimport { useState } from "react";\n\nfunction FilterSelect() {\n const [status, setStatus] = useState("");\n \n const statusOptions = [\n { label: "Active", value: "active" },\n { label: "Inactive", value: "inactive" },\n { label: "Pending", value: "pending" }\n ];\n \n return (\n <Select\n label="Filter by Status"\n options={statusOptions}\n value={status}\n onChange={setStatus}\n clearable\n placeholder="All statuses"\n />\n );\n}\n```\n\n### Disabled State\n\n```tsx\n<Select\n label="Disabled Select"\n options={options}\n disabled\n value="option1"\n/>\n```\n\n## Technical Details\n\n### State Management\n\n- Supports both controlled and uncontrolled modes\n- Use `value` + `onChange` for controlled\n- Use `defaultValue` for uncontrolled\n- The search query is owned internally and seeded from `filterValue`; a *change* to `filterValue`\n overwrites it and cancels any in-flight debounced `onFilterChange`\n\n### Filtering\n\n- Without `onFilterChange`, options are filtered locally via the shared `matchesQuery` helper, which\n is also used by `TransferList` and `MultiSelectTransfer`.\n- With `onFilterChange`, filtering is delegated to the parent and the query is debounced\n (`filterDebounceMs`). A pending debounce is cancelled on unmount, on an external `filterValue`\n reset, and when the dropdown closes \u2014 where `onFilterChange("")` fires instead so the parent\'s\n result set matches the now-empty search box. While Backspace/Delete is held the debounce is\n deferred until keyup (or blur), so a long-press cannot fire mid-hold. This lives in the shared\n `useFilterQuery` hook, which `MultiSelectTransfer` also uses, so its identically-named filter\n props behave identically.\n- `isLoading` renders the loader in place of react-select\'s menu list, which also keeps it out of the\n list\'s `role="listbox"` subtree (that role only accepts option children). Suppressing the "No\n options" notice this way is deliberate: returning `null` from react-select\'s `noOptionsMessage`\n makes it skip rendering the menu altogether, taking the search input with it.\n- `MultiSelectTransfer` behaves the same for a search fetch, but keeps appending the loader below the\n rows for a load-more it triggered itself, so pagination doesn\'t lose the scroll position.\n- `searchable={false}` removes the only source of a query, so the whole filtering axis goes quiet:\n client-side matching runs against an empty query (every option visible), the debounce never starts,\n and the close-time `onFilterChange("")` has nothing to reset. Focus and option navigation are\n unaffected \u2014 they belong to react-select\'s control input, which the in-dropdown box only ever\n forwards keys to.\n\n## Accessibility\n\n**Implemented:**\n- ARIA attributes for screen readers\n- Keyboard navigation (Arrow keys, Enter, ESC)\n- Focus management\n- Proper labeling\n- With `searchable={false}` the dropdown contains no text field of its own. Focus stays on the\n control\'s input, where react-select already keeps the listbox link and the active-option cursor, so\n Arrow/Enter/Escape/Tab are unchanged, and Space/Home/End become available because no text field is\n claiming them\n\n**Best Practices:**\n- Always provide a label\n- Use descriptive option labels\n- Mark required fields\n- Provide error messages\n- Keep the search on for anything longer than a screenful \u2014 without it the arrow keys are the only way\n to reach the bottom of the list\n'
3614
3705
  }
3615
3706
  ],
3616
3707
  "directories": []
@@ -3901,6 +3992,7 @@ import { useTransferList } from "./useTransferList";
3901
3992
  import { useTransferListSource } from "./useTransferListSource";
3902
3993
  import { transferListVariants } from "./transferListVariants";
3903
3994
  import { matchesQuery } from "@utils";
3995
+ import { useIgnoredPropWarning } from "@hooks";
3904
3996
  import type { ITransferListProps, TTransferListValue, TTransferPanel } from "./types";
3905
3997
 
3906
3998
  /**
@@ -3985,6 +4077,14 @@ export const TransferList = React.forwardRef<HTMLDivElement, ITransferListProps>
3985
4077
  onAvailableSearchChange: onAvailableSearch
3986
4078
  } = availableSource;
3987
4079
 
4080
+ // No search input on either panel means nothing can produce a query, so a controlled-search pair has
4081
+ // no input to drive and no keystroke to report.
4082
+ useIgnoredPropWarning(
4083
+ !searchable && ( onAvailableSearchChange !== undefined || onSelectedSearchChange !== undefined ),
4084
+ "TransferList: the controlled-search props are ignored when \`searchable={false}\` \u2014 " +
4085
+ "there are no search inputs to drive."
4086
+ );
4087
+
3988
4088
  const {
3989
4089
  isChecked,
3990
4090
  toggleCheck,
@@ -4276,7 +4376,7 @@ TransferList.displayName = "TransferList";
4276
4376
  },
4277
4377
  {
4278
4378
  "name": "README.md",
4279
- "content": '# TransferList Component\n\n## Component Overview\n\nThe TransferList is a fully-controlled two-panel widget for moving items between an\n**Available** list and a **Selected** list. Each panel has a **"Select all" checkbox**\nabove its list and a **move button** below it that transfers the currently-checked items\nto the other panel \u2014 "Add to select" on Available, "Remove from selected" on Selected.\nItems can also be moved by native HTML5 drag-and-drop. It is intentionally decoupled\nfrom any surrounding chrome \u2014 render it inside a `Modal`, a `Card`, or a page section\nand own the surrounding layout yourself. `MultiSelectTransfer` composes it inside a modal.\n\n**When to use:**\n- Assigning a subset of items (permissions, columns, members) from a larger pool\n- Building an ordered selection where position matters (enable `reorderable`)\n- Any "pick from a long, possibly paginated list" workflow\n\n**Component Architecture:**\n- Fully controlled: `availableItems`, `selectedItems`, and `onChange` are owned by the consumer\n- Styled with `tailwind-variants` (`tv()`) slots\n- Native drag-and-drop (no extra dependency) for cross-panel transfer and reorder\n- Infinite scroll on the Available panel via an `IntersectionObserver` sentinel\n- Responsive: panels sit side-by-side on `sm`+ and stack vertically on small screens\n- Reuses `Checkbox`, `Button`, `Scrollbar`, `Loader`, and `ADPIcon`\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport { TransferList, type ITransferListItem } from "@cloudwick/astral-ui";\n\nexport function Example() {\n const [available, setAvailable] = useState<ITransferListItem[]>([\n { value: "apple", label: "Apple" },\n { value: "banana", label: "Banana" }\n ]);\n const [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n return (\n <TransferList\n availableItems={available}\n selectedItems={selected}\n onChange={( nextAvailable, nextSelected ) => {\n setAvailable( nextAvailable );\n setSelected( nextSelected );\n }}\n />\n );\n}\n```\n\n## Props\n\n| Prop | Type | Default | Description |\n|---|---|---|---|\n| `availableItems` | `ITransferListItem[]` | \u2014 | Items in the left panel. Controlled. Optional and **ignored** (dev warning) when `loadAvailableOptions` is set. |\n| `selectedItems` | `ITransferListItem[]` | \u2014 | Items in the right panel. Controlled. |\n| `onChange` | `( availableItems, selectedItems ) => void` | \u2014 | Fired on every move/reorder. |\n| `availablePanelTitle` / `selectedPanelTitle` | `ReactNode` | `"Available Items"` / `"Selected Items"` | Panel headings. |\n| `searchable` | `boolean` | `true` | Show the per-panel search inputs. |\n| `availableSearchTerm` / `onAvailableSearchChange` | `string` / `fn` | \u2014 | Controlled search for the available panel (parent owns filtering). |\n| `selectedSearchTerm` / `onSelectedSearchChange` | `string` / `fn` | \u2014 | Controlled search for the selected panel. |\n| `searchPlaceholder` | `string` | `"Search here"` | Placeholder for both inputs. |\n| `availablePanelHeaderSlot` / `selectedPanelHeaderSlot` | `ReactNode` | \u2014 | Custom content under each search input. |\n| `moveToSelectedLabel` | `string` | `"Add to select"` | Label for the available panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `moveToAvailableLabel` | `string` | `"Remove from selected"` | Label for the selected panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `reorderable` | `boolean` | `false` | Enable drag handles, position badges and up/down arrows on the selected panel. |\n| `showReload` / `onReload` / `isReloading` | `boolean` / `fn` / `boolean` | \u2014 | Reload button on the available panel header. |\n| `hasMoreAvailable` / `onLoadMoreAvailable` / `isLoadingMoreAvailable` | `boolean` / `fn` / `boolean` | \u2014 | Infinite scroll for the available panel. The loader **appends** below the rows. While `hasMoreAvailable` is true the panel never shows its empty state: with no rows left it keeps the sentinel and the append loader, so moving the whole loaded page across pulls the next one instead of dead-ending. |\n| `isLoadingAvailable` | `boolean` | `false` | Loader **replaces** the available rows (a search/refresh fetch, not a page append). |\n| `availableLoadError` | `ReactNode` | \u2014 | Replaces the available rows: that panel\'s source failed to load. |\n| `availableLoadMoreError` | `ReactNode` | \u2014 | Shown under the loaded rows when a page append failed; renders a retry button. |\n| `onRetryLoadMoreAvailable` | `fn` | \u2014 | Fired by that retry button. |\n| `retryLabel` | `string` | `"Retry"` | Label for the retry button. |\n| `availableTotalCount` | `number` | \u2014 | Server-side total; the available panel\'s header count becomes `(loaded of total)`. |\n| `loadAvailableOptions` | `(query, meta) => Promise<ITransferListItem[] \\| IOptionPage<...>>` | \u2014 | Async, paged source for the available panel. See [Async available panel](#async-available-panel). |\n| `initialAvailableOptions` | `readonly ITransferListItem[]` | \u2014 | Seed rows for a pool you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the mount fetch revalidates over them \u2014 see [Seeding the pool](#seeding-the-pool). Async mode only. |\n| `prefetch` | `"mount" \\| "never"` | `"mount"` | When to fetch the unfiltered available list. `"mount"` at render \u2014 the panel has no open/close, so mount is the only trigger it has; `"never"` only once the user searches. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | Clearing the available search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | \u2014 | Identity of the available option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `availableFilterDebounceMs` | `number` | `300` | Debounce for the available panel\'s search when it is server-driven. |\n| `loadErrorMessage` / `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load options."` / `"Couldn\'t load more."` | Async-mode copy for the two failure states above. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | Notified when a load rejects. |\n| `disabled` | `boolean` | `false` | Disable all interaction. |\n| `availableEmptyText` / `selectedEmptyText` | `ReactNode` | `"No Data Found!"` | Empty-state copy. |\n| `className` | `string` | \u2014 | Extra classes on the root. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | Forwarded to the root \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n\n## Selecting and moving items\n\n- **Per-row checkboxes:** check individual rows in either panel.\n- **Select all:** the checkbox above each list checks/clears the non-disabled items the\n active search leaves **visible** \u2014 its label counts exactly that scope, and it reflects\n an indeterminate state when only some of them are checked. Items hidden by the filter are\n left as they are in both directions, so checks made under an earlier query survive. The\n row is shown only when there are at least two visible items to act on; below that it would\n duplicate a single row\'s own checkbox or have nothing to check.\n- **Move button:** the button below each list moves **every** currently-checked item to the\n other panel (skipping disabled items) and clears the checkboxes \u2014 including items the\n active filter is hiding, so its count stays an honest tally of the selection. It is\n disabled when nothing is checked. To move everything, clear the search, click "Select all",\n then the move button.\n\n## Drag-and-drop\n\n- **Cross-panel transfer:** drag any row onto the opposite panel to move it (honoring\n `isDisabled`). Same effect as checking the row and clicking the move button. While a drag is in progress, every\n panel that is a valid, position-irrelevant drop target shows a sticky "Drop Here"\n overlay across its whole content area, for the entire drag \u2014 not just while hovering\n it. This is consistent on both panels: dragging a Selected row always shows the\n overlay on Available, and dragging an Available row shows it on Selected whenever\n `reorderable` is not set (the drop always appends, regardless of which row is\n hovered).\n- **Reorder within Selected:** only when `reorderable` \u2014 drop a selected row (or an\n incoming available row) at a new position, tracked with a precise per-row insertion\n line instead of the overlay, or use the up/down arrows. Without `reorderable`,\n dragging a selected row within Selected is a no-op and shows neither the overlay nor\n an indicator.\n- The **Available panel is never sortable**: Available rows are draggable solely to enable\n transfer to Selected; dropping an Available row within Available is a no-op and shows\n no overlay or indicator.\n\n## Loading and error states on the available panel\n\nThese are plain prop additions, usable by any controlled consumer without touching async mode:\n\n- **`isLoadingAvailable`** shows a centred loader *instead of* the rows. Use it for a search or refresh\n fetch \u2014 the rows on screen belong to the previous query, so leaving them navigable would let the user\n act on something the incoming result set no longer contains. Arrow/Enter/Space are swallowed and\n `aria-activedescendant` is dropped while it is up. `isLoadingMoreAvailable` is the opposite: the\n loader *appends* below the rows, because a page fetch adds to what is already there.\n- **`availableLoadError`** replaces the rows with `role="alert"` copy. The drop targets stay live \u2014 an\n error in Available must not break dragging items back out of Selected.\n- **`availableLoadMoreError`** + **`onRetryLoadMoreAvailable`** render below the loaded rows, replacing\n the append loader. This is the affordance that makes a failed page recoverable; because only this\n button retries, a sentinel that never left the viewport cannot hammer a failing endpoint.\n- **`availableTotalCount`** turns the header count into `(loaded of total)` when it exceeds what is\n loaded. A paged panel reporting `(20)` when the server holds 4,000 matches is lying.\n\n## Async available panel\n\n`loadAvailableOptions` makes the component own the Available pool \u2014 its paging, request ordering and\nloading/error state \u2014 instead of every consumer hand-writing a monotonic-ticket guard and a page\naccumulator:\n\n```tsx\nconst [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n loadAvailableOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return { options: res.rows, cursor: res.nextToken, total: res.totalCount };\n }}\n/>\n```\n\n- It fetches on **mount**, not on open: the panel has no open/close, so its list is always visible.\n That is why `prefetch` here is `"mount" | "never"` rather than the `"mount" | "open" | "never"` that\n `Select` and `MultiSelectTransfer` accept \u2014 there is no open event to hang a fetch on.\n `prefetch="never"` defers everything until the user searches.\n- The panel\'s search becomes **debounced and server-driven** (`availableFilterDebounceMs`); the local\n matcher stands down, since over a paged pool it could only search the pages that happen to be loaded.\n- Available is **derived** as the loaded pool minus `selectedItems`, so moving an item across needs no\n refetch. An item that was in `selectedItems` but never in the pool still returns to Available when\n moved back \u2014 the component remembers every item it has seen on the selected side. Those remembered\n items are matched locally against the active query, so one cannot surface as a result for a search it\n does not match, and they are forgotten on an `optionsKey` change along with the pool itself.\n- **`availableItems` becomes optional and is ignored** (with a dev warning), which sits a little\n awkwardly with the component\'s fully-controlled identity. `selectedItems` stays controlled \u2014 the\n consumer owns the selection, which is the whole point of the component \u2014 and `onChange` still fires\n with both arrays, so no existing call site breaks.\n- The paging, dedupe, failed-page/Retry and `optionsKey` semantics are identical to\n `MultiSelectTransfer`\'s; see its README for the full list.\n\n### Seeding the pool\n\n`initialAvailableOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route\nloader, a warm query cache. They are painted on the first frame, so the panel is never briefly empty,\nand they stay on screen while the mount fetch revalidates over them. They go through the same\npool-minus-`selectedItems` projection as fetched rows, so an already-selected seed row correctly starts\non the right-hand side.\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n initialAvailableOptions={ssrRows} // painted immediately\n loadAvailableOptions={fetchRows} // still runs at mount, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress that fetch. If the seed *is* the whole pool until the user searches \u2014 a heavy\nsource you do not want to hit on render \u2014 pair it with `prefetch="never"`, which otherwise leaves the\npanel empty:\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={...}\n initialAvailableOptions={recentlyUsed}\n prefetch="never"\n loadAvailableOptions={searchEverything}\n/>\n```\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query. And seed rows\nonly mean something to the async source \u2014 passing `initialAvailableOptions` without\n`loadAvailableOptions` is ignored with a dev warning, because those rows belong in `availableItems`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadAvailableOptions` there is no fetch to schedule. Passing it there is ignored with a dev\nwarning.\n\n## Notes\n\n- With a paged source, "the full list" that Select-all and the move buttons operate on is what has\n been **loaded**, not what the server holds.\n- Search is both controlled and uncontrolled per panel. When a search-change handler is\n provided the parent owns filtering; otherwise items are filtered client-side.\n- Client-side search matches an item\'s `searchValue` first, then a string `label`, then its\n `value`. Set `searchValue` on items whose `label` is custom JSX so they remain findable by\n their visible text (a ReactNode `label` is otherwise matched only against `value`).\n- Because the component is controlled, "pending until confirm" semantics (e.g. a modal\n with Cancel/Done) are owned by the parent \u2014 see `MultiSelectTransfer`.\n'
4379
+ "content": '# TransferList Component\n\n## Component Overview\n\nThe TransferList is a fully-controlled two-panel widget for moving items between an\n**Available** list and a **Selected** list. Each panel has a **"Select all" checkbox**\nabove its list and a **move button** below it that transfers the currently-checked items\nto the other panel \u2014 "Add to select" on Available, "Remove from selected" on Selected.\nItems can also be moved by native HTML5 drag-and-drop. It is intentionally decoupled\nfrom any surrounding chrome \u2014 render it inside a `Modal`, a `Card`, or a page section\nand own the surrounding layout yourself. `MultiSelectTransfer` composes it inside a modal.\n\n**When to use:**\n- Assigning a subset of items (permissions, columns, members) from a larger pool\n- Building an ordered selection where position matters (enable `reorderable`)\n- Any "pick from a long, possibly paginated list" workflow\n\n**Component Architecture:**\n- Fully controlled: `availableItems`, `selectedItems`, and `onChange` are owned by the consumer\n- Styled with `tailwind-variants` (`tv()`) slots\n- Native drag-and-drop (no extra dependency) for cross-panel transfer and reorder\n- Infinite scroll on the Available panel via an `IntersectionObserver` sentinel\n- Responsive: panels sit side-by-side on `sm`+ and stack vertically on small screens\n- Reuses `Checkbox`, `Button`, `Scrollbar`, `Loader`, and `ADPIcon`\n\n## Basic Usage\n\n```tsx\nimport { useState } from "react";\nimport { TransferList, type ITransferListItem } from "@cloudwick/astral-ui";\n\nexport function Example() {\n const [available, setAvailable] = useState<ITransferListItem[]>([\n { value: "apple", label: "Apple" },\n { value: "banana", label: "Banana" }\n ]);\n const [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n return (\n <TransferList\n availableItems={available}\n selectedItems={selected}\n onChange={( nextAvailable, nextSelected ) => {\n setAvailable( nextAvailable );\n setSelected( nextSelected );\n }}\n />\n );\n}\n```\n\n## Props\n\n| Prop | Type | Default | Description |\n|---|---|---|---|\n| `availableItems` | `ITransferListItem[]` | \u2014 | Items in the left panel. Controlled. Optional and **ignored** (dev warning) when `loadAvailableOptions` is set. |\n| `selectedItems` | `ITransferListItem[]` | \u2014 | Items in the right panel. Controlled. |\n| `onChange` | `( availableItems, selectedItems ) => void` | \u2014 | Fired on every move/reorder. |\n| `availablePanelTitle` / `selectedPanelTitle` | `ReactNode` | `"Available Items"` / `"Selected Items"` | Panel headings. |\n| `searchable` | `boolean` | `true` | Show the per-panel search inputs. `false` hides both; each panel\'s listbox owns focus either way, so keyboard navigation, drag-and-drop, "Select all" and the move buttons are untouched \u2014 only narrowing a panel is lost. `MultiSelectTransfer` forwards its own `searchable` here. |\n| `availableSearchTerm` / `onAvailableSearchChange` | `string` / `fn` | \u2014 | Controlled search for the available panel (parent owns filtering). |\n| `selectedSearchTerm` / `onSelectedSearchChange` | `string` / `fn` | \u2014 | Controlled search for the selected panel. |\n| `searchPlaceholder` | `string` | `"Search here"` | Placeholder for both inputs. |\n| `availablePanelHeaderSlot` / `selectedPanelHeaderSlot` | `ReactNode` | \u2014 | Custom content under each search input. |\n| `moveToSelectedLabel` | `string` | `"Add to select"` | Label for the available panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `moveToAvailableLabel` | `string` | `"Remove from selected"` | Label for the selected panel\'s move button. A `(count)` suffix is appended when items are checked. |\n| `reorderable` | `boolean` | `false` | Enable drag handles, position badges and up/down arrows on the selected panel. |\n| `showReload` / `onReload` / `isReloading` | `boolean` / `fn` / `boolean` | \u2014 | Reload button on the available panel header. |\n| `hasMoreAvailable` / `onLoadMoreAvailable` / `isLoadingMoreAvailable` | `boolean` / `fn` / `boolean` | \u2014 | Infinite scroll for the available panel. The loader **appends** below the rows. While `hasMoreAvailable` is true the panel never shows its empty state: with no rows left it keeps the sentinel and the append loader, so moving the whole loaded page across pulls the next one instead of dead-ending. |\n| `isLoadingAvailable` | `boolean` | `false` | Loader **replaces** the available rows (a search/refresh fetch, not a page append). |\n| `availableLoadError` | `ReactNode` | \u2014 | Replaces the available rows: that panel\'s source failed to load. |\n| `availableLoadMoreError` | `ReactNode` | \u2014 | Shown under the loaded rows when a page append failed; renders a retry button. |\n| `onRetryLoadMoreAvailable` | `fn` | \u2014 | Fired by that retry button. |\n| `retryLabel` | `string` | `"Retry"` | Label for the retry button. |\n| `availableTotalCount` | `number` | \u2014 | Server-side total; the available panel\'s header count becomes `(loaded of total)`. |\n| `loadAvailableOptions` | `(query, meta) => Promise<ITransferListItem[] \\| IOptionPage<...>>` | \u2014 | Async, paged source for the available panel. See [Async available panel](#async-available-panel). |\n| `initialAvailableOptions` | `readonly ITransferListItem[]` | \u2014 | Seed rows for a pool you already have (SSR payload, route loader, warm cache). Painted on the first frame and kept on screen while the mount fetch revalidates over them \u2014 see [Seeding the pool](#seeding-the-pool). Async mode only. |\n| `prefetch` | `"mount" \\| "never"` | `"mount"` | When to fetch the unfiltered available list. `"mount"` at render \u2014 the panel has no open/close, so mount is the only trigger it has; `"never"` only once the user searches. Async mode only. |\n| `refetchOnClear` | `boolean` | `false` | Clearing the available search revalidates the cached baseline instead of only restoring it. |\n| `optionsKey` | `string \\| number` | \u2014 | Identity of the available option set. A change drops cached pages and repopulates. Does **not** clear the selection. |\n| `availableFilterDebounceMs` | `number` | `300` | Debounce for the available panel\'s search when it is server-driven. |\n| `loadErrorMessage` / `loadMoreErrorMessage` | `ReactNode` | `"Couldn\'t load options."` / `"Couldn\'t load more."` | Async-mode copy for the two failure states above. |\n| `onLoadError` | `(error: unknown) => void` | \u2014 | Notified when a load rejects. |\n| `disabled` | `boolean` | `false` | Disable all interaction. |\n| `availableEmptyText` / `selectedEmptyText` | `ReactNode` | `"No Data Found!"` | Empty-state copy. |\n| `className` | `string` | \u2014 | Extra classes on the root. |\n| `ref` | `Ref<HTMLDivElement>` | \u2014 | Forwarded to the root \u2014 for programmatic focus/scroll and form libraries that bind by ref. |\n\n## Selecting and moving items\n\n- **Per-row checkboxes:** check individual rows in either panel.\n- **Select all:** the checkbox above each list checks/clears the non-disabled items the\n active search leaves **visible** \u2014 its label counts exactly that scope, and it reflects\n an indeterminate state when only some of them are checked. Items hidden by the filter are\n left as they are in both directions, so checks made under an earlier query survive. The\n row is shown only when there are at least two visible items to act on; below that it would\n duplicate a single row\'s own checkbox or have nothing to check.\n- **Move button:** the button below each list moves **every** currently-checked item to the\n other panel (skipping disabled items) and clears the checkboxes \u2014 including items the\n active filter is hiding, so its count stays an honest tally of the selection. It is\n disabled when nothing is checked. To move everything, clear the search, click "Select all",\n then the move button.\n\n## Drag-and-drop\n\n- **Cross-panel transfer:** drag any row onto the opposite panel to move it (honoring\n `isDisabled`). Same effect as checking the row and clicking the move button. While a drag is in progress, every\n panel that is a valid, position-irrelevant drop target shows a sticky "Drop Here"\n overlay across its whole content area, for the entire drag \u2014 not just while hovering\n it. This is consistent on both panels: dragging a Selected row always shows the\n overlay on Available, and dragging an Available row shows it on Selected whenever\n `reorderable` is not set (the drop always appends, regardless of which row is\n hovered).\n- **Reorder within Selected:** only when `reorderable` \u2014 drop a selected row (or an\n incoming available row) at a new position, tracked with a precise per-row insertion\n line instead of the overlay, or use the up/down arrows. Without `reorderable`,\n dragging a selected row within Selected is a no-op and shows neither the overlay nor\n an indicator.\n- The **Available panel is never sortable**: Available rows are draggable solely to enable\n transfer to Selected; dropping an Available row within Available is a no-op and shows\n no overlay or indicator.\n\n## Loading and error states on the available panel\n\nThese are plain prop additions, usable by any controlled consumer without touching async mode:\n\n- **`isLoadingAvailable`** shows a centred loader *instead of* the rows. Use it for a search or refresh\n fetch \u2014 the rows on screen belong to the previous query, so leaving them navigable would let the user\n act on something the incoming result set no longer contains. Arrow/Enter/Space are swallowed and\n `aria-activedescendant` is dropped while it is up. `isLoadingMoreAvailable` is the opposite: the\n loader *appends* below the rows, because a page fetch adds to what is already there.\n- **`availableLoadError`** replaces the rows with `role="alert"` copy. The drop targets stay live \u2014 an\n error in Available must not break dragging items back out of Selected.\n- **`availableLoadMoreError`** + **`onRetryLoadMoreAvailable`** render below the loaded rows, replacing\n the append loader. This is the affordance that makes a failed page recoverable; because only this\n button retries, a sentinel that never left the viewport cannot hammer a failing endpoint.\n- **`availableTotalCount`** turns the header count into `(loaded of total)` when it exceeds what is\n loaded. A paged panel reporting `(20)` when the server holds 4,000 matches is lying.\n\n## Async available panel\n\n`loadAvailableOptions` makes the component own the Available pool \u2014 its paging, request ordering and\nloading/error state \u2014 instead of every consumer hand-writing a monotonic-ticket guard and a page\naccumulator:\n\n```tsx\nconst [selected, setSelected] = useState<ITransferListItem[]>([]);\n\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n loadAvailableOptions={async (query, { cursor, signal }) => {\n const res = await fetchRows({ query, cursor, signal });\n return { options: res.rows, cursor: res.nextToken, total: res.totalCount };\n }}\n/>\n```\n\n- It fetches on **mount**, not on open: the panel has no open/close, so its list is always visible.\n That is why `prefetch` here is `"mount" | "never"` rather than the `"mount" | "open" | "never"` that\n `Select` and `MultiSelectTransfer` accept \u2014 there is no open event to hang a fetch on.\n `prefetch="never"` defers everything until the user searches.\n- The panel\'s search becomes **debounced and server-driven** (`availableFilterDebounceMs`); the local\n matcher stands down, since over a paged pool it could only search the pages that happen to be loaded.\n- Available is **derived** as the loaded pool minus `selectedItems`, so moving an item across needs no\n refetch. An item that was in `selectedItems` but never in the pool still returns to Available when\n moved back \u2014 the component remembers every item it has seen on the selected side. Those remembered\n items are matched locally against the active query, so one cannot surface as a result for a search it\n does not match, and they are forgotten on an `optionsKey` change along with the pool itself.\n- **`availableItems` becomes optional and is ignored** (with a dev warning), which sits a little\n awkwardly with the component\'s fully-controlled identity. `selectedItems` stays controlled \u2014 the\n consumer owns the selection, which is the whole point of the component \u2014 and `onChange` still fires\n with both arrays, so no existing call site breaks.\n- The paging, dedupe, failed-page/Retry and `optionsKey` semantics are identical to\n `MultiSelectTransfer`\'s; see its README for the full list.\n\n### Seeding the pool\n\n`initialAvailableOptions` is for the case where **you already have the rows** \u2014 an SSR payload, a route\nloader, a warm query cache. They are painted on the first frame, so the panel is never briefly empty,\nand they stay on screen while the mount fetch revalidates over them. They go through the same\npool-minus-`selectedItems` projection as fetched rows, so an already-selected seed row correctly starts\non the right-hand side.\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={(_available, nextSelected) => setSelected(nextSelected)}\n initialAvailableOptions={ssrRows} // painted immediately\n loadAvailableOptions={fetchRows} // still runs at mount, and replaces them when page one lands\n/>\n```\n\nIt does **not** suppress that fetch. If the seed *is* the whole pool until the user searches \u2014 a heavy\nsource you do not want to hit on render \u2014 pair it with `prefetch="never"`, which otherwise leaves the\npanel empty:\n\n```tsx\n<TransferList\n selectedItems={selected}\n onChange={...}\n initialAvailableOptions={recentlyUsed}\n prefetch="never"\n loadAvailableOptions={searchEverything}\n/>\n```\n\nSeed rows carry no cursor, so the infinite-scroll sentinel stays disarmed until a real page lands \u2014 a\nseed is not page one. A *search* replaces them, because they are not results for a query. And seed rows\nonly mean something to the async source \u2014 passing `initialAvailableOptions` without\n`loadAvailableOptions` is ignored with a dev warning, because those rows belong in `availableItems`.\n\n`prefetch` is async-only for the same reason: it schedules the baseline fetch and nothing else, so\nwithout `loadAvailableOptions` there is no fetch to schedule. Passing it there is ignored with a dev\nwarning.\n\n## Notes\n\n- With a paged source, "the full list" that Select-all and the move buttons operate on is what has\n been **loaded**, not what the server holds.\n- Search is both controlled and uncontrolled per panel. When a search-change handler is\n provided the parent owns filtering; otherwise items are filtered client-side.\n- With `searchable={false}` there are no search inputs to drive, so the controlled-search props\n (`availableSearchTerm` / `onAvailableSearchChange` and the selected-panel pair) have no effect and\n are dev-warned; an async Available panel then only ever sees an empty query \u2014 it still pages, it\n just cannot be searched.\n- Client-side search matches an item\'s `searchValue` first, then a string `label`, then its\n `value`. Set `searchValue` on items whose `label` is custom JSX so they remain findable by\n their visible text (a ReactNode `label` is otherwise matched only against `value`).\n- Because the component is controlled, "pending until confirm" semantics (e.g. a modal\n with Cancel/Done) are owned by the parent \u2014 see `MultiSelectTransfer`.\n'
4280
4380
  }
4281
4381
  ],
4282
4382
  "directories": []