@brightlocal/ui-components 2.0.1 → 2.2.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.
@@ -2,10 +2,12 @@
2
2
 
3
3
  import * as React from "react";
4
4
  import { ChevronsUpDown, Check } from "@brightlocal/icons";
5
+ import { useVirtualizer } from "@tanstack/react-virtual";
5
6
  import { cva } from "class-variance-authority";
6
7
  import { defaultFilter } from "cmdk";
7
8
 
8
9
  import { cn } from "@brightlocal/ui-components/lib/utils";
10
+ import { useDevWarning } from "@brightlocal/ui-components/lib/use-dev-warning";
9
11
  import {
10
12
  Popover,
11
13
  PopoverContent,
@@ -35,11 +37,49 @@ interface ComboboxContextValue {
35
37
  /** Map of value -> label for displaying selected value */
36
38
  itemLabels: Map<string, string>;
37
39
  registerItem: (value: string, label: string) => void;
40
+ /** Remove an item from the label map (called on unmount to prevent stale entries) */
41
+ unregisterItem: (value: string) => void;
38
42
  /** Maps item value to a searchable string for filtering */
39
43
  itemToStringValue?: (value: string) => string;
44
+ /**
45
+ * Shared filter function used by both cmdk (normal list) and virtual list.
46
+ * Signature matches cmdk's filter: `(value, search, keywords?) => number`.
47
+ * A score > 0 means the item matches. Both paths use this so filtering
48
+ * behaviour is always consistent.
49
+ */
50
+ filterFn: (value: string, search: string, keywords?: string[]) => number;
51
+ /** Current search input value (for virtual list filtering) */
52
+ searchValue: string;
53
+ /** Update the search input value */
54
+ setSearchValue: (value: string) => void;
55
+ /** Active descendant element ID (set by virtual list for the input) */
56
+ activeDescendantId: string | undefined;
57
+ /** Update the active descendant ID */
58
+ setActiveDescendantId: React.Dispatch<
59
+ React.SetStateAction<string | undefined>
60
+ >;
61
+ }
62
+
63
+ /* -------------------------------------------------------------------------------------------------
64
+ * Virtual List Context
65
+ * -----------------------------------------------------------------------------------------------*/
66
+
67
+ interface ComboboxVirtualListContextValue {
68
+ /** Value of the currently keyboard-highlighted item */
69
+ activeValue: string | null;
70
+ /** Callback when pointer moves over an item */
71
+ onItemPointerMove: (value: string) => void;
72
+ /** Stable ID prefix for generating item element IDs (for aria-activedescendant) */
73
+ idPrefix: string;
74
+ /** Total number of filtered items (for aria-setsize) */
75
+ filteredCount: number;
76
+ /** Look up 1-based position of an item by value (for aria-posinset) */
77
+ getItemPosition: (value: string) => number;
40
78
  }
41
79
 
42
80
  const ComboboxContext = React.createContext<ComboboxContextValue | null>(null);
81
+ const ComboboxVirtualListContext =
82
+ React.createContext<ComboboxVirtualListContextValue | null>(null);
43
83
 
44
84
  function useComboboxContext() {
45
85
  const context = React.useContext(ComboboxContext);
@@ -53,6 +93,40 @@ function useComboboxContext() {
53
93
  * Combobox Root
54
94
  * -----------------------------------------------------------------------------------------------*/
55
95
 
96
+ /**
97
+ * Composable combobox supporting three usage modes:
98
+ *
99
+ * **1. Client-filtered (default)** — small/medium datasets with instant search.
100
+ * ```tsx
101
+ * <Combobox>
102
+ * <ComboboxInput />
103
+ * <ComboboxList>
104
+ * <ComboboxGroup><ComboboxItem value="a">A</ComboboxItem></ComboboxGroup>
105
+ * </ComboboxList>
106
+ * </Combobox>
107
+ * ```
108
+ *
109
+ * **2. Async / server-driven** — results fetched from an API.
110
+ * ```tsx
111
+ * <Combobox shouldFilter={false}>
112
+ * <ComboboxInput debounceMs={300} onValueChange={fetchResults} />
113
+ * <ComboboxList>
114
+ * {results.map(r => <ComboboxItem key={r.id} value={r.id}>{r.name}</ComboboxItem>)}
115
+ * </ComboboxList>
116
+ * </Combobox>
117
+ * ```
118
+ *
119
+ * **3. Virtualised large list** — 100+ items rendered efficiently.
120
+ * Client-side filtering is on by default (`shouldFilter` omitted).
121
+ * ```tsx
122
+ * <Combobox>
123
+ * <ComboboxInput />
124
+ * <ComboboxVirtualList items={items} getItemValue={i => i.id} estimateSize={36}>
125
+ * {(item) => <ComboboxItem value={item.id}>{item.name}</ComboboxItem>}
126
+ * </ComboboxVirtualList>
127
+ * </Combobox>
128
+ * ```
129
+ */
56
130
  export interface ComboboxProps {
57
131
  /** Controlled selected value */
58
132
  value?: string;
@@ -62,7 +136,12 @@ export interface ComboboxProps {
62
136
  open?: boolean;
63
137
  /** Callback when open state changes */
64
138
  onOpenChange?: (open: boolean) => void;
65
- /** Whether to use cmdk's built-in filtering. Set to false for async search. */
139
+ /**
140
+ * Whether to use built-in client-side filtering. Defaults to `true`.
141
+ * Both `ComboboxList` (cmdk) and `ComboboxVirtualList` respect this flag.
142
+ * Set to `false` only for async/server-driven search where the consumer
143
+ * controls the items list.
144
+ */
66
145
  shouldFilter?: boolean;
67
146
  /** Disabled state */
68
147
  disabled?: boolean;
@@ -87,6 +166,10 @@ function Combobox({
87
166
  const [itemLabels, setItemLabels] = React.useState<Map<string, string>>(
88
167
  () => new Map()
89
168
  );
169
+ const [searchValue, setSearchValue] = React.useState("");
170
+ const [activeDescendantId, setActiveDescendantId] = React.useState<
171
+ string | undefined
172
+ >(undefined);
90
173
 
91
174
  const isValueControlled = controlledValue !== undefined;
92
175
  const isOpenControlled = controlledOpen !== undefined;
@@ -96,6 +179,7 @@ function Combobox({
96
179
 
97
180
  const setOpen = React.useCallback(
98
181
  (newOpen: boolean) => {
182
+ if (!newOpen) setSearchValue("");
99
183
  if (!isOpenControlled) {
100
184
  setUncontrolledOpen(newOpen);
101
185
  }
@@ -114,15 +198,70 @@ function Combobox({
114
198
  [isValueControlled, controlledOnValueChange]
115
199
  );
116
200
 
117
- const registerItem = React.useCallback((itemValue: string, label: string) => {
118
- setItemLabels((prev) => {
119
- if (prev.get(itemValue) === label) return prev;
120
- const next = new Map(prev);
121
- next.set(itemValue, label);
122
- return next;
123
- });
201
+ // Batch item registrations via microtask to avoid per-item state updates
202
+ const itemLabelsRef = React.useRef<Map<string, string>>(new Map());
203
+ const pendingFlushRef = React.useRef(false);
204
+ const isMountedRef = React.useRef(true);
205
+
206
+ React.useEffect(() => {
207
+ return () => {
208
+ isMountedRef.current = false;
209
+ };
210
+ }, []);
211
+
212
+ const scheduleMicrotaskFlush = React.useCallback(() => {
213
+ if (!pendingFlushRef.current) {
214
+ pendingFlushRef.current = true;
215
+ queueMicrotask(() => {
216
+ pendingFlushRef.current = false;
217
+ if (!isMountedRef.current) return;
218
+ setItemLabels(new Map(itemLabelsRef.current));
219
+ });
220
+ }
124
221
  }, []);
125
222
 
223
+ const registerItem = React.useCallback(
224
+ (itemValue: string, label: string) => {
225
+ if (itemLabelsRef.current.get(itemValue) === label) return;
226
+ itemLabelsRef.current.set(itemValue, label);
227
+ scheduleMicrotaskFlush();
228
+ },
229
+ [scheduleMicrotaskFlush]
230
+ );
231
+
232
+ // Track the current value in a ref so unregisterItem can read it without
233
+ // adding `value` as a dependency (which would break callback identity).
234
+ // useLayoutEffect runs before passive-effect cleanups, so the ref is
235
+ // up-to-date when unmounting items call unregisterItem.
236
+ const valueRef = React.useRef(value);
237
+ React.useLayoutEffect(() => {
238
+ valueRef.current = value;
239
+ }, [value]);
240
+
241
+ const unregisterItem = React.useCallback(
242
+ (itemValue: string) => {
243
+ // Preserve the label for the currently selected value — ComboboxValue
244
+ // needs it after the popover closes and items unmount.
245
+ if (itemValue === valueRef.current) return;
246
+ if (!itemLabelsRef.current.has(itemValue)) return;
247
+ itemLabelsRef.current.delete(itemValue);
248
+ scheduleMicrotaskFlush();
249
+ },
250
+ [scheduleMicrotaskFlush]
251
+ );
252
+
253
+ // Single filter function shared by both cmdk (normal list) and virtual list.
254
+ // When itemToStringValue is provided it maps the raw value to a searchable
255
+ // string first; otherwise falls through to cmdk's defaultFilter directly.
256
+ const filterFn = React.useMemo(
257
+ () =>
258
+ itemToStringValue
259
+ ? (value: string, search: string, keywords?: string[]) =>
260
+ defaultFilter(itemToStringValue(value), search, keywords)
261
+ : defaultFilter,
262
+ [itemToStringValue]
263
+ );
264
+
126
265
  const contextValue = React.useMemo<ComboboxContextValue>(
127
266
  () => ({
128
267
  open,
@@ -133,7 +272,13 @@ function Combobox({
133
272
  disabled,
134
273
  itemLabels,
135
274
  registerItem,
275
+ unregisterItem,
136
276
  itemToStringValue,
277
+ filterFn,
278
+ searchValue,
279
+ setSearchValue,
280
+ activeDescendantId,
281
+ setActiveDescendantId,
137
282
  }),
138
283
  [
139
284
  open,
@@ -144,7 +289,12 @@ function Combobox({
144
289
  disabled,
145
290
  itemLabels,
146
291
  registerItem,
292
+ unregisterItem,
147
293
  itemToStringValue,
294
+ filterFn,
295
+ searchValue,
296
+ activeDescendantId,
297
+ setActiveDescendantId,
148
298
  ]
149
299
  );
150
300
 
@@ -246,7 +396,7 @@ const ComboboxTrigger = React.forwardRef<
246
396
  className={cn(
247
397
  comboboxTriggerVariants(),
248
398
  hasError &&
249
- "border-destructive-40 focus-visible:border-destructive-40 dark:focus-visible:border-destructive-40 focus-visible:shadow-destructive data-[state=open]:border-destructive-40 dark:data-[state=open]:border-destructive-40 data-[state=open]:shadow-destructive",
399
+ "border-destructive-40 dark:border-destructive-40 focus-visible:border-destructive-40 dark:focus-visible:border-destructive-40 focus-visible:shadow-destructive data-[state=open]:border-destructive-40 dark:data-[state=open]:border-destructive-40 data-[state=open]:shadow-destructive",
250
400
  className
251
401
  )}
252
402
  data-hook={dataHook}
@@ -281,11 +431,31 @@ export interface ComboboxValueProps {
281
431
  placeholder?: string;
282
432
  /** Custom className */
283
433
  className?: string;
434
+ /**
435
+ * Resolve a display label for the selected value. Called when the internal
436
+ * label registry doesn't have a match (e.g. before the popover opens for
437
+ * the first time with a pre-selected value).
438
+ *
439
+ * @example
440
+ * ```tsx
441
+ * <ComboboxValue
442
+ * placeholder="Select country..."
443
+ * displayValue={(v) => countriesMap.get(v)?.name}
444
+ * />
445
+ * ```
446
+ */
447
+ displayValue?: (value: string) => string | undefined;
284
448
  }
285
449
 
286
- function ComboboxValue({ placeholder, className }: ComboboxValueProps) {
450
+ function ComboboxValue({
451
+ placeholder,
452
+ className,
453
+ displayValue,
454
+ }: ComboboxValueProps) {
287
455
  const { value, itemLabels } = useComboboxContext();
288
- const displayText = value ? itemLabels.get(value) || value : placeholder;
456
+ const displayText = value
457
+ ? itemLabels.get(value) || displayValue?.(value) || value
458
+ : placeholder;
289
459
 
290
460
  return (
291
461
  <span
@@ -341,7 +511,8 @@ function ComboboxContent({
341
511
  avoidCollisions,
342
512
  hideList = false,
343
513
  }: ComboboxContentProps) {
344
- const { open, shouldFilter, itemToStringValue } = useComboboxContext();
514
+ const { open, shouldFilter, filterFn, itemToStringValue } =
515
+ useComboboxContext();
345
516
 
346
517
  // TODO: This is a workaround for floating-ui re-flipping on content resize.
347
518
  // The root cause is that Radix Popper's autoUpdate watches elementResize and
@@ -439,11 +610,10 @@ function ComboboxContent({
439
610
  return undefined;
440
611
  }, [open]);
441
612
 
442
- const filter = React.useMemo(() => {
443
- if (!itemToStringValue) return undefined;
444
- return (value: string, search: string, keywords?: string[]) =>
445
- defaultFilter(itemToStringValue(value), search, keywords);
446
- }, [itemToStringValue]);
613
+ // Use the shared filterFn from context. When itemToStringValue is set it
614
+ // wraps defaultFilter; otherwise it IS defaultFilter — passing undefined
615
+ // tells cmdk to use its own built-in default (same function).
616
+ const cmdkFilter = itemToStringValue ? filterFn : undefined;
447
617
 
448
618
  return (
449
619
  <PopoverContent
@@ -455,6 +625,7 @@ function ComboboxContent({
455
625
  "flex max-h-[var(--radix-popover-content-available-height)] w-[var(--radix-popover-trigger-width)] flex-col overflow-hidden p-0",
456
626
  className
457
627
  )}
628
+ collisionPadding={4}
458
629
  data-slot="combobox-popover"
459
630
  side={lockedSide ?? side}
460
631
  sideOffset={sideOffset}
@@ -467,7 +638,7 @@ function ComboboxContent({
467
638
  )}
468
639
  data-slot="combobox-command"
469
640
  dataHook={dataHook || "combobox-command"}
470
- filter={filter}
641
+ filter={cmdkFilter}
471
642
  shouldFilter={shouldFilter}
472
643
  >
473
644
  {children}
@@ -487,13 +658,76 @@ export interface ComboboxInputProps extends React.ComponentProps<
487
658
  value?: string;
488
659
  /** Called when input value changes. Use to trigger async search requests. */
489
660
  onValueChange?: (value: string) => void;
661
+ /**
662
+ * Debounce delay in milliseconds for the `onValueChange` callback.
663
+ * The input display updates immediately; only the callback is debounced.
664
+ * Useful for async search to avoid firing API calls on every keystroke.
665
+ * @example 300
666
+ */
667
+ debounceMs?: number;
490
668
  }
491
669
 
492
670
  const ComboboxInput = React.forwardRef<
493
671
  React.ComponentRef<typeof CommandInput>,
494
672
  ComboboxInputProps
495
- >((props, ref) => {
496
- return <CommandInput ref={ref} data-slot="combobox-input" {...props} />;
673
+ >(({ debounceMs, onValueChange, ...props }, ref) => {
674
+ const { setSearchValue, shouldFilter, activeDescendantId } =
675
+ useComboboxContext();
676
+ const timerRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(
677
+ undefined
678
+ );
679
+
680
+ useDevWarning(
681
+ () => !!(debounceMs && debounceMs > 0 && shouldFilter),
682
+ "debounceMs is set on <ComboboxInput> but shouldFilter is true (default).\n" +
683
+ "Debounce is designed for async/server-driven search where the consumer " +
684
+ "controls the items list.\n" +
685
+ "Set shouldFilter={false} on <Combobox> for async search, or remove " +
686
+ "debounceMs for client-side filtering.",
687
+ [debounceMs, shouldFilter]
688
+ );
689
+
690
+ useDevWarning(
691
+ () => !!(debounceMs && debounceMs > 0 && props.value !== undefined),
692
+ "debounceMs is set on <ComboboxInput> together with a controlled `value` prop.\n" +
693
+ "The debounced onValueChange callback cannot update the controlled value " +
694
+ "synchronously, so the input will appear to lag behind typing.\n" +
695
+ "Remove `value` to let the input manage its own display, or remove " +
696
+ "debounceMs if you need a controlled input.",
697
+ [debounceMs, props.value]
698
+ );
699
+
700
+ React.useEffect(() => {
701
+ return () => {
702
+ if (timerRef.current) clearTimeout(timerRef.current);
703
+ };
704
+ }, []);
705
+
706
+ const handleValueChange = React.useCallback(
707
+ (newValue: string) => {
708
+ setSearchValue(newValue);
709
+
710
+ if (debounceMs && debounceMs > 0) {
711
+ clearTimeout(timerRef.current);
712
+ timerRef.current = setTimeout(() => {
713
+ onValueChange?.(newValue);
714
+ }, debounceMs);
715
+ } else {
716
+ onValueChange?.(newValue);
717
+ }
718
+ },
719
+ [debounceMs, onValueChange, setSearchValue]
720
+ );
721
+
722
+ return (
723
+ <CommandInput
724
+ ref={ref}
725
+ aria-activedescendant={activeDescendantId}
726
+ data-slot="combobox-input"
727
+ onValueChange={handleValueChange}
728
+ {...props}
729
+ />
730
+ );
497
731
  });
498
732
  ComboboxInput.displayName = "ComboboxInput";
499
733
 
@@ -518,6 +752,352 @@ const ComboboxList = React.forwardRef<
518
752
  });
519
753
  ComboboxList.displayName = "ComboboxList";
520
754
 
755
+ /* -------------------------------------------------------------------------------------------------
756
+ * Combobox Virtual List
757
+ * -----------------------------------------------------------------------------------------------*/
758
+
759
+ export interface ComboboxVirtualListProps<T> {
760
+ /** Array of items to virtualise. Memoize with useMemo to avoid re-registering labels on every render. */
761
+ items: T[];
762
+ /** Extract the string value for each item (used for selection and keyboard navigation) */
763
+ getItemValue: (item: T) => string;
764
+ /**
765
+ * Extract a display label for filtering and trigger display. Defaults to `getItemValue`.
766
+ * Only used when `shouldFilter` is true on the parent Combobox.
767
+ */
768
+ getItemLabel?: (item: T) => string;
769
+ /**
770
+ * Extract additional keywords to match against when filtering.
771
+ * The item label is always included automatically — these are extras
772
+ * (e.g. ISO codes, abbreviations) that should be searchable without
773
+ * appearing in the trigger display.
774
+ */
775
+ getItemKeywords?: (item: T) => string[];
776
+ /** Estimated item height in pixels. @default 36 */
777
+ estimateSize?: number;
778
+ /** Number of items to render above and below the visible area. @default 5 */
779
+ overscan?: number;
780
+ /** Render function for each item. The third argument is the current search query, useful for highlighting matching text. */
781
+ children: (item: T, index: number, searchValue: string) => React.ReactNode;
782
+ /** Content to render when no items match the filter */
783
+ renderEmpty?: React.ReactNode;
784
+ /** Custom className for the scrollable container */
785
+ className?: string;
786
+ /** Data hook for automated testing */
787
+ dataHook?: string;
788
+ }
789
+
790
+ /**
791
+ * Virtualised list for Combobox with 50+ items.
792
+ * Drop-in replacement for `ComboboxList` + `ComboboxGroup` + manual `.map()`.
793
+ * Uses `@tanstack/react-virtual` to render only visible items.
794
+ *
795
+ * @example
796
+ * ```tsx
797
+ * <ComboboxVirtualList items={items} getItemValue={(i) => i.value} estimateSize={36}>
798
+ * {(item) => <ComboboxItem value={item.value}>{item.label}</ComboboxItem>}
799
+ * </ComboboxVirtualList>
800
+ * ```
801
+ */
802
+ function ComboboxVirtualListInner<T>(
803
+ {
804
+ items,
805
+ getItemValue,
806
+ getItemLabel,
807
+ getItemKeywords,
808
+ estimateSize = 36,
809
+ overscan = 5,
810
+ children,
811
+ renderEmpty,
812
+ className,
813
+ dataHook,
814
+ }: ComboboxVirtualListProps<T>,
815
+ ref: React.ForwardedRef<HTMLDivElement>
816
+ ) {
817
+ const parentRef = React.useRef<HTMLDivElement>(null);
818
+ const {
819
+ value,
820
+ onValueChange,
821
+ setOpen,
822
+ shouldFilter,
823
+ searchValue,
824
+ filterFn,
825
+ setActiveDescendantId,
826
+ registerItem,
827
+ unregisterItem,
828
+ } = useComboboxContext();
829
+ const [activeIndex, setActiveIndex] = React.useState(0);
830
+ const idPrefix = React.useId();
831
+
832
+ // Merge forwarded ref with internal ref
833
+ React.useImperativeHandle(ref, () => parentRef.current!, []);
834
+
835
+ // Bulk-register all item labels upfront so ComboboxValue can always resolve
836
+ // the display label — even for items outside the virtualised viewport.
837
+ // Cleanup unregisters stale labels when `items` changes (e.g. server-driven
838
+ // filtering/pagination). The selected value's label survives because
839
+ // unregisterItem has a guard that preserves the currently selected value.
840
+ React.useEffect(() => {
841
+ const resolveLabel = getItemLabel ?? getItemValue;
842
+ for (const item of items) {
843
+ registerItem(getItemValue(item), resolveLabel(item));
844
+ }
845
+ return () => {
846
+ for (const item of items) {
847
+ unregisterItem(getItemValue(item));
848
+ }
849
+ };
850
+ }, [items, getItemValue, getItemLabel, registerItem, unregisterItem]);
851
+
852
+ // Filter AND rank items by score — same behaviour as cmdk's scoring system.
853
+ // Items with higher match scores appear first, so ordering is consistent
854
+ // between the virtual list and cmdk's normal list path.
855
+ const filteredItems = React.useMemo(() => {
856
+ if (!shouldFilter || !searchValue.trim()) return items;
857
+
858
+ const scored: { item: T; score: number }[] = [];
859
+ for (const item of items) {
860
+ // getItemLabel is a virtual-list-specific override; otherwise delegate
861
+ // to the shared filterFn which already respects itemToStringValue.
862
+ let score = getItemLabel
863
+ ? defaultFilter(getItemLabel(item), searchValue)
864
+ : filterFn(getItemValue(item), searchValue);
865
+
866
+ // Check additional keywords — take the best score across label + keywords,
867
+ // mirroring how cmdk's keywords prop works on regular ComboboxItem.
868
+ if (getItemKeywords) {
869
+ for (const kw of getItemKeywords(item)) {
870
+ score = Math.max(score, defaultFilter(kw, searchValue));
871
+ }
872
+ }
873
+
874
+ if (score > 0) scored.push({ item, score });
875
+ }
876
+
877
+ // Sort descending by score (best match first) — matches cmdk behaviour
878
+ scored.sort((a, b) => b.score - a.score);
879
+ return scored.map((s) => s.item);
880
+ }, [
881
+ items,
882
+ shouldFilter,
883
+ searchValue,
884
+ getItemValue,
885
+ getItemLabel,
886
+ getItemKeywords,
887
+ filterFn,
888
+ ]);
889
+
890
+ // eslint-disable-next-line react-hooks/incompatible-library -- compiler already skips this component; virtualizer is not passed to memoized consumers
891
+ const virtualizer = useVirtualizer({
892
+ count: filteredItems.length,
893
+ getScrollElement: () => parentRef.current,
894
+ estimateSize: () => estimateSize,
895
+ overscan,
896
+ });
897
+
898
+ // Derive active value for context
899
+ const activeValue =
900
+ activeIndex >= 0 && activeIndex < filteredItems.length
901
+ ? getItemValue(filteredItems[activeIndex]!)
902
+ : null;
903
+
904
+ // Reset active index when search or items change
905
+ React.useEffect(() => {
906
+ setActiveIndex(0);
907
+ }, [searchValue, filteredItems.length]);
908
+
909
+ // Scroll to selected value once it becomes available (when popover opens).
910
+ // Runs when value/filteredItems change but only fires once via guard ref,
911
+ // so async-loaded items that arrive after mount are still handled.
912
+ const initialScrollDone = React.useRef(false);
913
+ React.useEffect(() => {
914
+ if (initialScrollDone.current || !value) return;
915
+
916
+ const idx = filteredItems.findIndex((item) => getItemValue(item) === value);
917
+ if (idx >= 0) {
918
+ setActiveIndex(idx);
919
+ virtualizer.scrollToIndex(idx, { align: "center" });
920
+ initialScrollDone.current = true;
921
+ }
922
+ }, [value, filteredItems, getItemValue, virtualizer]);
923
+
924
+ // Only auto-scroll when the active index changed from keyboard navigation,
925
+ // not from pointer hover (the user's mouse is already at the item they see).
926
+ const scrollOnNextIndexChange = React.useRef(false);
927
+
928
+ React.useEffect(() => {
929
+ if (
930
+ scrollOnNextIndexChange.current &&
931
+ activeIndex >= 0 &&
932
+ activeIndex < filteredItems.length
933
+ ) {
934
+ virtualizer.scrollToIndex(activeIndex, { align: "auto" });
935
+ }
936
+ scrollOnNextIndexChange.current = false;
937
+ }, [activeIndex, filteredItems.length, virtualizer]);
938
+
939
+ // Keyboard navigation (intercept before cmdk)
940
+ React.useEffect(() => {
941
+ const el = parentRef.current?.closest(
942
+ '[data-slot="combobox-command"]'
943
+ ) as HTMLElement | null;
944
+ if (!el) return;
945
+
946
+ const handleKeyDown = (e: KeyboardEvent) => {
947
+ switch (e.key) {
948
+ case "ArrowDown":
949
+ e.preventDefault();
950
+ e.stopPropagation();
951
+ scrollOnNextIndexChange.current = true;
952
+ setActiveIndex((prev) =>
953
+ prev < filteredItems.length - 1 ? prev + 1 : prev
954
+ );
955
+ break;
956
+ case "ArrowUp":
957
+ e.preventDefault();
958
+ e.stopPropagation();
959
+ scrollOnNextIndexChange.current = true;
960
+ setActiveIndex((prev) => (prev > 0 ? prev - 1 : prev));
961
+ break;
962
+ case "Enter":
963
+ e.preventDefault();
964
+ e.stopPropagation();
965
+ if (activeIndex >= 0 && activeIndex < filteredItems.length) {
966
+ const itemValue = getItemValue(filteredItems[activeIndex]!);
967
+ const newValue = itemValue === value ? "" : itemValue;
968
+ onValueChange(newValue);
969
+ setOpen(false);
970
+ }
971
+ break;
972
+ case "Home":
973
+ e.preventDefault();
974
+ e.stopPropagation();
975
+ scrollOnNextIndexChange.current = true;
976
+ setActiveIndex(0);
977
+ break;
978
+ case "End":
979
+ e.preventDefault();
980
+ e.stopPropagation();
981
+ scrollOnNextIndexChange.current = true;
982
+ setActiveIndex(filteredItems.length - 1);
983
+ break;
984
+ }
985
+ };
986
+
987
+ el.addEventListener("keydown", handleKeyDown, { capture: true });
988
+ return () =>
989
+ el.removeEventListener("keydown", handleKeyDown, { capture: true });
990
+ }, [filteredItems, activeIndex, value, onValueChange, setOpen, getItemValue]);
991
+
992
+ // Value → 0-based index map for O(1) lookups (pointer move + aria-posinset)
993
+ const itemIndexMap = React.useMemo(() => {
994
+ const map = new Map<string, number>();
995
+ filteredItems.forEach((item, i) => {
996
+ map.set(getItemValue(item), i);
997
+ });
998
+ return map;
999
+ }, [filteredItems, getItemValue]);
1000
+
1001
+ // Pointer move only updates the highlight — no scrolling (O(1) via index map)
1002
+ const onItemPointerMove = React.useCallback(
1003
+ (itemValue: string) => {
1004
+ const index = itemIndexMap.get(itemValue);
1005
+ if (index !== undefined) setActiveIndex(index);
1006
+ },
1007
+ [itemIndexMap]
1008
+ );
1009
+
1010
+ // aria-posinset is 1-based
1011
+ const getItemPosition = React.useCallback(
1012
+ (itemValue: string) => (itemIndexMap.get(itemValue) ?? 0) + 1,
1013
+ [itemIndexMap]
1014
+ );
1015
+
1016
+ const filteredCount = filteredItems.length;
1017
+
1018
+ const contextValue = React.useMemo<ComboboxVirtualListContextValue>(
1019
+ () => ({
1020
+ activeValue,
1021
+ onItemPointerMove,
1022
+ idPrefix,
1023
+ filteredCount,
1024
+ getItemPosition,
1025
+ }),
1026
+ [activeValue, onItemPointerMove, idPrefix, filteredCount, getItemPosition]
1027
+ );
1028
+
1029
+ // Push the active item ID into the Combobox context so ComboboxInput
1030
+ // (the focused element) can set aria-activedescendant.
1031
+ const activeItemId =
1032
+ activeValue != null ? `${idPrefix}item-${activeValue}` : undefined;
1033
+
1034
+ React.useEffect(() => {
1035
+ setActiveDescendantId(activeItemId);
1036
+ return () => setActiveDescendantId(undefined);
1037
+ }, [activeItemId, setActiveDescendantId]);
1038
+
1039
+ // Always render the listbox container so empty state stays within the
1040
+ // correct ARIA structure (role="listbox" wraps renderEmpty).
1041
+ if (filteredItems.length === 0) {
1042
+ return (
1043
+ <div
1044
+ ref={parentRef}
1045
+ className={cn(
1046
+ "max-h-[300px] min-h-0 flex-1 scroll-py-1 overflow-x-hidden overflow-y-auto py-1",
1047
+ className
1048
+ )}
1049
+ data-hook={dataHook}
1050
+ data-slot="combobox-virtual-list"
1051
+ role="listbox"
1052
+ >
1053
+ {renderEmpty}
1054
+ </div>
1055
+ );
1056
+ }
1057
+
1058
+ return (
1059
+ <ComboboxVirtualListContext.Provider value={contextValue}>
1060
+ <div
1061
+ ref={parentRef}
1062
+ className={cn(
1063
+ "max-h-[300px] min-h-0 flex-1 scroll-py-1 overflow-x-hidden overflow-y-auto py-1",
1064
+ className
1065
+ )}
1066
+ data-hook={dataHook}
1067
+ data-slot="combobox-virtual-list"
1068
+ role="listbox"
1069
+ >
1070
+ <div
1071
+ className="relative w-full"
1072
+ style={{ height: `${virtualizer.getTotalSize()}px` }}
1073
+ >
1074
+ {virtualizer.getVirtualItems().map((virtualItem) => (
1075
+ <div
1076
+ key={virtualItem.key}
1077
+ ref={virtualizer.measureElement}
1078
+ className="absolute top-0 left-0 w-full px-2"
1079
+ data-index={virtualItem.index}
1080
+ style={{
1081
+ transform: `translateY(${virtualItem.start}px)`,
1082
+ }}
1083
+ >
1084
+ {children(
1085
+ filteredItems[virtualItem.index]!,
1086
+ virtualItem.index,
1087
+ searchValue
1088
+ )}
1089
+ </div>
1090
+ ))}
1091
+ </div>
1092
+ </div>
1093
+ </ComboboxVirtualListContext.Provider>
1094
+ );
1095
+ }
1096
+
1097
+ const ComboboxVirtualList = React.forwardRef(ComboboxVirtualListInner) as <T>(
1098
+ props: ComboboxVirtualListProps<T> & { ref?: React.Ref<HTMLDivElement> }
1099
+ ) => React.ReactElement | null;
1100
+
521
1101
  /* -------------------------------------------------------------------------------------------------
522
1102
  * Combobox Empty
523
1103
  * -----------------------------------------------------------------------------------------------*/
@@ -541,8 +1121,36 @@ export type ComboboxGroupProps = React.ComponentProps<typeof CommandGroup>;
541
1121
  const ComboboxGroup = React.forwardRef<
542
1122
  React.ComponentRef<typeof CommandGroup>,
543
1123
  ComboboxGroupProps
544
- >((props, ref) => {
545
- return <CommandGroup ref={ref} data-slot="combobox-group" {...props} />;
1124
+ >(({ children, ...props }, ref) => {
1125
+ const groupRef = React.useRef<HTMLDivElement>(null);
1126
+
1127
+ useDevWarning(
1128
+ () => {
1129
+ if (!groupRef.current) return false;
1130
+ return (
1131
+ groupRef.current.querySelectorAll('[data-slot="combobox-item"]')
1132
+ .length >= 100
1133
+ );
1134
+ },
1135
+ "ComboboxGroup contains 100+ items. Use <ComboboxVirtualList> for large " +
1136
+ "datasets to avoid DOM bloat and slow renders.\n" +
1137
+ 'Import: import { ComboboxVirtualList } from "@brightlocal/ui-components/combobox"',
1138
+ [children]
1139
+ );
1140
+
1141
+ return (
1142
+ <CommandGroup
1143
+ ref={(node) => {
1144
+ groupRef.current = node;
1145
+ if (typeof ref === "function") ref(node);
1146
+ else if (ref) ref.current = node;
1147
+ }}
1148
+ data-slot="combobox-group"
1149
+ {...props}
1150
+ >
1151
+ {children}
1152
+ </CommandGroup>
1153
+ );
546
1154
  });
547
1155
  ComboboxGroup.displayName = "ComboboxGroup";
548
1156
 
@@ -619,8 +1227,9 @@ const ComboboxItem = React.forwardRef<
619
1227
  },
620
1228
  ref
621
1229
  ) => {
622
- const { value, onValueChange, setOpen, registerItem } =
1230
+ const { value, onValueChange, setOpen, registerItem, unregisterItem } =
623
1231
  useComboboxContext();
1232
+ const virtualCtx = React.useContext(ComboboxVirtualListContext);
624
1233
  const isSelected = value === itemValue;
625
1234
 
626
1235
  // Extract text content from children for label registration
@@ -631,16 +1240,23 @@ const ComboboxItem = React.forwardRef<
631
1240
  return itemValue;
632
1241
  }, [label, children, itemValue]);
633
1242
 
634
- // Keep latest registerItem in a ref to avoid effect dependency churn
1243
+ // Keep latest callbacks in refs to avoid effect dependency churn
635
1244
  const registerItemRef = React.useRef(registerItem);
1245
+ const unregisterItemRef = React.useRef(unregisterItem);
636
1246
  React.useEffect(() => {
637
1247
  registerItemRef.current = registerItem;
638
- }, [registerItem]);
1248
+ unregisterItemRef.current = unregisterItem;
1249
+ }, [registerItem, unregisterItem]);
639
1250
 
640
- // Register item label for ComboboxValue display
1251
+ // Register item label for ComboboxValue display; clean up on unmount
1252
+ // to prevent stale labels in async/pagination/dynamic datasets.
1253
+ // Skip when inside a VirtualList — VirtualList bulk-registers all labels.
1254
+ const isVirtual = !!virtualCtx;
641
1255
  React.useEffect(() => {
1256
+ if (isVirtual) return;
642
1257
  registerItemRef.current(itemValue, childText);
643
- }, [itemValue, childText]);
1258
+ return () => unregisterItemRef.current(itemValue);
1259
+ }, [itemValue, childText, isVirtual]);
644
1260
 
645
1261
  const handleSelect = () => {
646
1262
  const newValue = itemValue === value ? "" : itemValue;
@@ -660,6 +1276,55 @@ const ComboboxItem = React.forwardRef<
660
1276
  return children;
661
1277
  };
662
1278
 
1279
+ // Inside a virtual list: render as a plain div (bypasses cmdk registration)
1280
+ if (virtualCtx) {
1281
+ const isHighlighted = virtualCtx.activeValue === itemValue;
1282
+ const isDisabled = !!props.disabled;
1283
+
1284
+ return (
1285
+ <div
1286
+ ref={ref as React.Ref<HTMLDivElement>}
1287
+ aria-disabled={isDisabled || undefined}
1288
+ aria-posinset={virtualCtx.getItemPosition(itemValue)}
1289
+ aria-selected={isSelected}
1290
+ aria-setsize={virtualCtx.filteredCount}
1291
+ className={cn(
1292
+ "data-[highlighted=true]:bg-accent data-[highlighted=true]:text-accent-foreground relative flex cursor-default items-center justify-between gap-2 rounded-sm px-2 py-3 text-sm outline-hidden select-none",
1293
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0",
1294
+ isDisabled && "pointer-events-none opacity-50",
1295
+ className
1296
+ )}
1297
+ data-highlighted={isHighlighted || undefined}
1298
+ data-hook={dataHook}
1299
+ data-slot="combobox-item"
1300
+ id={`${virtualCtx.idPrefix}item-${itemValue}`}
1301
+ role="option"
1302
+ tabIndex={-1}
1303
+ onClick={isDisabled ? undefined : handleSelect}
1304
+ onKeyDown={
1305
+ isDisabled
1306
+ ? undefined
1307
+ : (e) => {
1308
+ if (e.key === "Enter" || e.key === " ") handleSelect();
1309
+ }
1310
+ }
1311
+ onPointerMove={
1312
+ isDisabled
1313
+ ? undefined
1314
+ : () => virtualCtx.onItemPointerMove(itemValue)
1315
+ }
1316
+ >
1317
+ {renderContent()}
1318
+ {isSelected && (
1319
+ <Check
1320
+ aria-hidden="true"
1321
+ className="text-muted-foreground shrink-0"
1322
+ />
1323
+ )}
1324
+ </div>
1325
+ );
1326
+ }
1327
+
663
1328
  return (
664
1329
  <CommandItem
665
1330
  ref={ref}
@@ -716,14 +1381,13 @@ export interface ComboboxLoadingProps {
716
1381
  function ComboboxLoading({ className, children }: ComboboxLoadingProps) {
717
1382
  return (
718
1383
  <div
719
- aria-disabled="true"
720
- aria-selected="false"
1384
+ aria-live="polite"
721
1385
  className={cn(
722
1386
  "text-muted-foreground flex items-center justify-center gap-2 py-6 text-sm",
723
1387
  className
724
1388
  )}
725
1389
  data-slot="combobox-loading"
726
- role="option"
1390
+ role="status"
727
1391
  >
728
1392
  {children || (
729
1393
  <>
@@ -749,6 +1413,7 @@ export {
749
1413
  ComboboxContent,
750
1414
  ComboboxInput,
751
1415
  ComboboxList,
1416
+ ComboboxVirtualList,
752
1417
  ComboboxEmpty,
753
1418
  ComboboxGroup,
754
1419
  ComboboxItem,