@brightlocal/ui-components 2.0.0 → 2.1.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}
@@ -341,7 +491,8 @@ function ComboboxContent({
341
491
  avoidCollisions,
342
492
  hideList = false,
343
493
  }: ComboboxContentProps) {
344
- const { open, shouldFilter, itemToStringValue } = useComboboxContext();
494
+ const { open, shouldFilter, filterFn, itemToStringValue } =
495
+ useComboboxContext();
345
496
 
346
497
  // TODO: This is a workaround for floating-ui re-flipping on content resize.
347
498
  // The root cause is that Radix Popper's autoUpdate watches elementResize and
@@ -439,11 +590,10 @@ function ComboboxContent({
439
590
  return undefined;
440
591
  }, [open]);
441
592
 
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]);
593
+ // Use the shared filterFn from context. When itemToStringValue is set it
594
+ // wraps defaultFilter; otherwise it IS defaultFilter — passing undefined
595
+ // tells cmdk to use its own built-in default (same function).
596
+ const cmdkFilter = itemToStringValue ? filterFn : undefined;
447
597
 
448
598
  return (
449
599
  <PopoverContent
@@ -455,6 +605,7 @@ function ComboboxContent({
455
605
  "flex max-h-[var(--radix-popover-content-available-height)] w-[var(--radix-popover-trigger-width)] flex-col overflow-hidden p-0",
456
606
  className
457
607
  )}
608
+ collisionPadding={4}
458
609
  data-slot="combobox-popover"
459
610
  side={lockedSide ?? side}
460
611
  sideOffset={sideOffset}
@@ -467,7 +618,7 @@ function ComboboxContent({
467
618
  )}
468
619
  data-slot="combobox-command"
469
620
  dataHook={dataHook || "combobox-command"}
470
- filter={filter}
621
+ filter={cmdkFilter}
471
622
  shouldFilter={shouldFilter}
472
623
  >
473
624
  {children}
@@ -487,13 +638,76 @@ export interface ComboboxInputProps extends React.ComponentProps<
487
638
  value?: string;
488
639
  /** Called when input value changes. Use to trigger async search requests. */
489
640
  onValueChange?: (value: string) => void;
641
+ /**
642
+ * Debounce delay in milliseconds for the `onValueChange` callback.
643
+ * The input display updates immediately; only the callback is debounced.
644
+ * Useful for async search to avoid firing API calls on every keystroke.
645
+ * @example 300
646
+ */
647
+ debounceMs?: number;
490
648
  }
491
649
 
492
650
  const ComboboxInput = React.forwardRef<
493
651
  React.ComponentRef<typeof CommandInput>,
494
652
  ComboboxInputProps
495
- >((props, ref) => {
496
- return <CommandInput ref={ref} data-slot="combobox-input" {...props} />;
653
+ >(({ debounceMs, onValueChange, ...props }, ref) => {
654
+ const { setSearchValue, shouldFilter, activeDescendantId } =
655
+ useComboboxContext();
656
+ const timerRef = React.useRef<ReturnType<typeof setTimeout> | undefined>(
657
+ undefined
658
+ );
659
+
660
+ useDevWarning(
661
+ () => !!(debounceMs && debounceMs > 0 && shouldFilter),
662
+ "debounceMs is set on <ComboboxInput> but shouldFilter is true (default).\n" +
663
+ "Debounce is designed for async/server-driven search where the consumer " +
664
+ "controls the items list.\n" +
665
+ "Set shouldFilter={false} on <Combobox> for async search, or remove " +
666
+ "debounceMs for client-side filtering.",
667
+ [debounceMs, shouldFilter]
668
+ );
669
+
670
+ useDevWarning(
671
+ () => !!(debounceMs && debounceMs > 0 && props.value !== undefined),
672
+ "debounceMs is set on <ComboboxInput> together with a controlled `value` prop.\n" +
673
+ "The debounced onValueChange callback cannot update the controlled value " +
674
+ "synchronously, so the input will appear to lag behind typing.\n" +
675
+ "Remove `value` to let the input manage its own display, or remove " +
676
+ "debounceMs if you need a controlled input.",
677
+ [debounceMs, props.value]
678
+ );
679
+
680
+ React.useEffect(() => {
681
+ return () => {
682
+ if (timerRef.current) clearTimeout(timerRef.current);
683
+ };
684
+ }, []);
685
+
686
+ const handleValueChange = React.useCallback(
687
+ (newValue: string) => {
688
+ setSearchValue(newValue);
689
+
690
+ if (debounceMs && debounceMs > 0) {
691
+ clearTimeout(timerRef.current);
692
+ timerRef.current = setTimeout(() => {
693
+ onValueChange?.(newValue);
694
+ }, debounceMs);
695
+ } else {
696
+ onValueChange?.(newValue);
697
+ }
698
+ },
699
+ [debounceMs, onValueChange, setSearchValue]
700
+ );
701
+
702
+ return (
703
+ <CommandInput
704
+ ref={ref}
705
+ aria-activedescendant={activeDescendantId}
706
+ data-slot="combobox-input"
707
+ onValueChange={handleValueChange}
708
+ {...props}
709
+ />
710
+ );
497
711
  });
498
712
  ComboboxInput.displayName = "ComboboxInput";
499
713
 
@@ -518,6 +732,304 @@ const ComboboxList = React.forwardRef<
518
732
  });
519
733
  ComboboxList.displayName = "ComboboxList";
520
734
 
735
+ /* -------------------------------------------------------------------------------------------------
736
+ * Combobox Virtual List
737
+ * -----------------------------------------------------------------------------------------------*/
738
+
739
+ export interface ComboboxVirtualListProps<T> {
740
+ /** Array of items to virtualise */
741
+ items: T[];
742
+ /** Extract the string value for each item (used for selection and keyboard navigation) */
743
+ getItemValue: (item: T) => string;
744
+ /**
745
+ * Extract a display label for filtering. Defaults to `getItemValue`.
746
+ * Only used when `shouldFilter` is true on the parent Combobox.
747
+ */
748
+ getItemLabel?: (item: T) => string;
749
+ /** Estimated item height in pixels. @default 36 */
750
+ estimateSize?: number;
751
+ /** Number of items to render above and below the visible area. @default 5 */
752
+ overscan?: number;
753
+ /** Render function for each item */
754
+ children: (item: T, index: number) => React.ReactNode;
755
+ /** Content to render when no items match the filter */
756
+ renderEmpty?: React.ReactNode;
757
+ /** Custom className for the scrollable container */
758
+ className?: string;
759
+ /** Data hook for automated testing */
760
+ dataHook?: string;
761
+ }
762
+
763
+ /**
764
+ * Virtualised list for Combobox with 50+ items.
765
+ * Drop-in replacement for `ComboboxList` + `ComboboxGroup` + manual `.map()`.
766
+ * Uses `@tanstack/react-virtual` to render only visible items.
767
+ *
768
+ * @example
769
+ * ```tsx
770
+ * <ComboboxVirtualList items={items} getItemValue={(i) => i.value} estimateSize={36}>
771
+ * {(item) => <ComboboxItem value={item.value}>{item.label}</ComboboxItem>}
772
+ * </ComboboxVirtualList>
773
+ * ```
774
+ */
775
+ function ComboboxVirtualListInner<T>(
776
+ {
777
+ items,
778
+ getItemValue,
779
+ getItemLabel,
780
+ estimateSize = 36,
781
+ overscan = 5,
782
+ children,
783
+ renderEmpty,
784
+ className,
785
+ dataHook,
786
+ }: ComboboxVirtualListProps<T>,
787
+ ref: React.ForwardedRef<HTMLDivElement>
788
+ ) {
789
+ const parentRef = React.useRef<HTMLDivElement>(null);
790
+ const {
791
+ value,
792
+ onValueChange,
793
+ setOpen,
794
+ shouldFilter,
795
+ searchValue,
796
+ filterFn,
797
+ setActiveDescendantId,
798
+ } = useComboboxContext();
799
+ const [activeIndex, setActiveIndex] = React.useState(0);
800
+ const idPrefix = React.useId();
801
+
802
+ // Merge forwarded ref with internal ref
803
+ React.useImperativeHandle(ref, () => parentRef.current!, []);
804
+
805
+ // Filter AND rank items by score — same behaviour as cmdk's scoring system.
806
+ // Items with higher match scores appear first, so ordering is consistent
807
+ // between the virtual list and cmdk's normal list path.
808
+ const filteredItems = React.useMemo(() => {
809
+ if (!shouldFilter || !searchValue.trim()) return items;
810
+
811
+ const scored: { item: T; score: number }[] = [];
812
+ for (const item of items) {
813
+ // getItemLabel is a virtual-list-specific override; otherwise delegate
814
+ // to the shared filterFn which already respects itemToStringValue.
815
+ const score = getItemLabel
816
+ ? defaultFilter(getItemLabel(item), searchValue)
817
+ : filterFn(getItemValue(item), searchValue);
818
+ if (score > 0) scored.push({ item, score });
819
+ }
820
+
821
+ // Sort descending by score (best match first) — matches cmdk behaviour
822
+ scored.sort((a, b) => b.score - a.score);
823
+ return scored.map((s) => s.item);
824
+ }, [items, shouldFilter, searchValue, getItemValue, getItemLabel, filterFn]);
825
+
826
+ // eslint-disable-next-line react-hooks/incompatible-library -- compiler already skips this component; virtualizer is not passed to memoized consumers
827
+ const virtualizer = useVirtualizer({
828
+ count: filteredItems.length,
829
+ getScrollElement: () => parentRef.current,
830
+ estimateSize: () => estimateSize,
831
+ overscan,
832
+ });
833
+
834
+ // Derive active value for context
835
+ const activeValue =
836
+ activeIndex >= 0 && activeIndex < filteredItems.length
837
+ ? getItemValue(filteredItems[activeIndex]!)
838
+ : null;
839
+
840
+ // Reset active index when search or items change
841
+ React.useEffect(() => {
842
+ setActiveIndex(0);
843
+ }, [searchValue, filteredItems.length]);
844
+
845
+ // Scroll to selected value once it becomes available (when popover opens).
846
+ // Runs when value/filteredItems change but only fires once via guard ref,
847
+ // so async-loaded items that arrive after mount are still handled.
848
+ const initialScrollDone = React.useRef(false);
849
+ React.useEffect(() => {
850
+ if (initialScrollDone.current || !value) return;
851
+
852
+ const idx = filteredItems.findIndex((item) => getItemValue(item) === value);
853
+ if (idx >= 0) {
854
+ setActiveIndex(idx);
855
+ virtualizer.scrollToIndex(idx, { align: "center" });
856
+ initialScrollDone.current = true;
857
+ }
858
+ }, [value, filteredItems, getItemValue, virtualizer]);
859
+
860
+ // Only auto-scroll when the active index changed from keyboard navigation,
861
+ // not from pointer hover (the user's mouse is already at the item they see).
862
+ const scrollOnNextIndexChange = React.useRef(false);
863
+
864
+ React.useEffect(() => {
865
+ if (
866
+ scrollOnNextIndexChange.current &&
867
+ activeIndex >= 0 &&
868
+ activeIndex < filteredItems.length
869
+ ) {
870
+ virtualizer.scrollToIndex(activeIndex, { align: "auto" });
871
+ }
872
+ scrollOnNextIndexChange.current = false;
873
+ }, [activeIndex, filteredItems.length, virtualizer]);
874
+
875
+ // Keyboard navigation (intercept before cmdk)
876
+ React.useEffect(() => {
877
+ const el = parentRef.current?.closest(
878
+ '[data-slot="combobox-command"]'
879
+ ) as HTMLElement | null;
880
+ if (!el) return;
881
+
882
+ const handleKeyDown = (e: KeyboardEvent) => {
883
+ switch (e.key) {
884
+ case "ArrowDown":
885
+ e.preventDefault();
886
+ e.stopPropagation();
887
+ scrollOnNextIndexChange.current = true;
888
+ setActiveIndex((prev) =>
889
+ prev < filteredItems.length - 1 ? prev + 1 : prev
890
+ );
891
+ break;
892
+ case "ArrowUp":
893
+ e.preventDefault();
894
+ e.stopPropagation();
895
+ scrollOnNextIndexChange.current = true;
896
+ setActiveIndex((prev) => (prev > 0 ? prev - 1 : prev));
897
+ break;
898
+ case "Enter":
899
+ e.preventDefault();
900
+ e.stopPropagation();
901
+ if (activeIndex >= 0 && activeIndex < filteredItems.length) {
902
+ const itemValue = getItemValue(filteredItems[activeIndex]!);
903
+ const newValue = itemValue === value ? "" : itemValue;
904
+ onValueChange(newValue);
905
+ setOpen(false);
906
+ }
907
+ break;
908
+ case "Home":
909
+ e.preventDefault();
910
+ e.stopPropagation();
911
+ scrollOnNextIndexChange.current = true;
912
+ setActiveIndex(0);
913
+ break;
914
+ case "End":
915
+ e.preventDefault();
916
+ e.stopPropagation();
917
+ scrollOnNextIndexChange.current = true;
918
+ setActiveIndex(filteredItems.length - 1);
919
+ break;
920
+ }
921
+ };
922
+
923
+ el.addEventListener("keydown", handleKeyDown, { capture: true });
924
+ return () =>
925
+ el.removeEventListener("keydown", handleKeyDown, { capture: true });
926
+ }, [filteredItems, activeIndex, value, onValueChange, setOpen, getItemValue]);
927
+
928
+ // Value → 0-based index map for O(1) lookups (pointer move + aria-posinset)
929
+ const itemIndexMap = React.useMemo(() => {
930
+ const map = new Map<string, number>();
931
+ filteredItems.forEach((item, i) => {
932
+ map.set(getItemValue(item), i);
933
+ });
934
+ return map;
935
+ }, [filteredItems, getItemValue]);
936
+
937
+ // Pointer move only updates the highlight — no scrolling (O(1) via index map)
938
+ const onItemPointerMove = React.useCallback(
939
+ (itemValue: string) => {
940
+ const index = itemIndexMap.get(itemValue);
941
+ if (index !== undefined) setActiveIndex(index);
942
+ },
943
+ [itemIndexMap]
944
+ );
945
+
946
+ // aria-posinset is 1-based
947
+ const getItemPosition = React.useCallback(
948
+ (itemValue: string) => (itemIndexMap.get(itemValue) ?? 0) + 1,
949
+ [itemIndexMap]
950
+ );
951
+
952
+ const filteredCount = filteredItems.length;
953
+
954
+ const contextValue = React.useMemo<ComboboxVirtualListContextValue>(
955
+ () => ({
956
+ activeValue,
957
+ onItemPointerMove,
958
+ idPrefix,
959
+ filteredCount,
960
+ getItemPosition,
961
+ }),
962
+ [activeValue, onItemPointerMove, idPrefix, filteredCount, getItemPosition]
963
+ );
964
+
965
+ // Push the active item ID into the Combobox context so ComboboxInput
966
+ // (the focused element) can set aria-activedescendant.
967
+ const activeItemId =
968
+ activeValue != null ? `${idPrefix}item-${activeValue}` : undefined;
969
+
970
+ React.useEffect(() => {
971
+ setActiveDescendantId(activeItemId);
972
+ return () => setActiveDescendantId(undefined);
973
+ }, [activeItemId, setActiveDescendantId]);
974
+
975
+ // Always render the listbox container so empty state stays within the
976
+ // correct ARIA structure (role="listbox" wraps renderEmpty).
977
+ if (filteredItems.length === 0) {
978
+ return (
979
+ <div
980
+ ref={parentRef}
981
+ className={cn(
982
+ "max-h-[300px] min-h-0 flex-1 scroll-py-1 overflow-x-hidden overflow-y-auto py-1",
983
+ className
984
+ )}
985
+ data-hook={dataHook}
986
+ data-slot="combobox-virtual-list"
987
+ role="listbox"
988
+ >
989
+ {renderEmpty}
990
+ </div>
991
+ );
992
+ }
993
+
994
+ return (
995
+ <ComboboxVirtualListContext.Provider value={contextValue}>
996
+ <div
997
+ ref={parentRef}
998
+ className={cn(
999
+ "max-h-[300px] min-h-0 flex-1 scroll-py-1 overflow-x-hidden overflow-y-auto py-1",
1000
+ className
1001
+ )}
1002
+ data-hook={dataHook}
1003
+ data-slot="combobox-virtual-list"
1004
+ role="listbox"
1005
+ >
1006
+ <div
1007
+ className="relative w-full"
1008
+ style={{ height: `${virtualizer.getTotalSize()}px` }}
1009
+ >
1010
+ {virtualizer.getVirtualItems().map((virtualItem) => (
1011
+ <div
1012
+ key={virtualItem.key}
1013
+ ref={virtualizer.measureElement}
1014
+ className="absolute top-0 left-0 w-full px-2"
1015
+ data-index={virtualItem.index}
1016
+ style={{
1017
+ transform: `translateY(${virtualItem.start}px)`,
1018
+ }}
1019
+ >
1020
+ {children(filteredItems[virtualItem.index]!, virtualItem.index)}
1021
+ </div>
1022
+ ))}
1023
+ </div>
1024
+ </div>
1025
+ </ComboboxVirtualListContext.Provider>
1026
+ );
1027
+ }
1028
+
1029
+ const ComboboxVirtualList = React.forwardRef(ComboboxVirtualListInner) as <T>(
1030
+ props: ComboboxVirtualListProps<T> & { ref?: React.Ref<HTMLDivElement> }
1031
+ ) => React.ReactElement | null;
1032
+
521
1033
  /* -------------------------------------------------------------------------------------------------
522
1034
  * Combobox Empty
523
1035
  * -----------------------------------------------------------------------------------------------*/
@@ -541,8 +1053,36 @@ export type ComboboxGroupProps = React.ComponentProps<typeof CommandGroup>;
541
1053
  const ComboboxGroup = React.forwardRef<
542
1054
  React.ComponentRef<typeof CommandGroup>,
543
1055
  ComboboxGroupProps
544
- >((props, ref) => {
545
- return <CommandGroup ref={ref} data-slot="combobox-group" {...props} />;
1056
+ >(({ children, ...props }, ref) => {
1057
+ const groupRef = React.useRef<HTMLDivElement>(null);
1058
+
1059
+ useDevWarning(
1060
+ () => {
1061
+ if (!groupRef.current) return false;
1062
+ return (
1063
+ groupRef.current.querySelectorAll('[data-slot="combobox-item"]')
1064
+ .length >= 100
1065
+ );
1066
+ },
1067
+ "ComboboxGroup contains 100+ items. Use <ComboboxVirtualList> for large " +
1068
+ "datasets to avoid DOM bloat and slow renders.\n" +
1069
+ 'Import: import { ComboboxVirtualList } from "@brightlocal/ui-components/combobox"',
1070
+ [children]
1071
+ );
1072
+
1073
+ return (
1074
+ <CommandGroup
1075
+ ref={(node) => {
1076
+ groupRef.current = node;
1077
+ if (typeof ref === "function") ref(node);
1078
+ else if (ref) ref.current = node;
1079
+ }}
1080
+ data-slot="combobox-group"
1081
+ {...props}
1082
+ >
1083
+ {children}
1084
+ </CommandGroup>
1085
+ );
546
1086
  });
547
1087
  ComboboxGroup.displayName = "ComboboxGroup";
548
1088
 
@@ -619,8 +1159,9 @@ const ComboboxItem = React.forwardRef<
619
1159
  },
620
1160
  ref
621
1161
  ) => {
622
- const { value, onValueChange, setOpen, registerItem } =
1162
+ const { value, onValueChange, setOpen, registerItem, unregisterItem } =
623
1163
  useComboboxContext();
1164
+ const virtualCtx = React.useContext(ComboboxVirtualListContext);
624
1165
  const isSelected = value === itemValue;
625
1166
 
626
1167
  // Extract text content from children for label registration
@@ -631,15 +1172,19 @@ const ComboboxItem = React.forwardRef<
631
1172
  return itemValue;
632
1173
  }, [label, children, itemValue]);
633
1174
 
634
- // Keep latest registerItem in a ref to avoid effect dependency churn
1175
+ // Keep latest callbacks in refs to avoid effect dependency churn
635
1176
  const registerItemRef = React.useRef(registerItem);
1177
+ const unregisterItemRef = React.useRef(unregisterItem);
636
1178
  React.useEffect(() => {
637
1179
  registerItemRef.current = registerItem;
638
- }, [registerItem]);
1180
+ unregisterItemRef.current = unregisterItem;
1181
+ }, [registerItem, unregisterItem]);
639
1182
 
640
- // Register item label for ComboboxValue display
1183
+ // Register item label for ComboboxValue display; clean up on unmount
1184
+ // to prevent stale labels in async/pagination/dynamic datasets.
641
1185
  React.useEffect(() => {
642
1186
  registerItemRef.current(itemValue, childText);
1187
+ return () => unregisterItemRef.current(itemValue);
643
1188
  }, [itemValue, childText]);
644
1189
 
645
1190
  const handleSelect = () => {
@@ -660,6 +1205,55 @@ const ComboboxItem = React.forwardRef<
660
1205
  return children;
661
1206
  };
662
1207
 
1208
+ // Inside a virtual list: render as a plain div (bypasses cmdk registration)
1209
+ if (virtualCtx) {
1210
+ const isHighlighted = virtualCtx.activeValue === itemValue;
1211
+ const isDisabled = !!props.disabled;
1212
+
1213
+ return (
1214
+ <div
1215
+ ref={ref as React.Ref<HTMLDivElement>}
1216
+ aria-disabled={isDisabled || undefined}
1217
+ aria-posinset={virtualCtx.getItemPosition(itemValue)}
1218
+ aria-selected={isSelected}
1219
+ aria-setsize={virtualCtx.filteredCount}
1220
+ className={cn(
1221
+ "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",
1222
+ "[&_svg]:pointer-events-none [&_svg]:shrink-0",
1223
+ isDisabled && "pointer-events-none opacity-50",
1224
+ className
1225
+ )}
1226
+ data-highlighted={isHighlighted || undefined}
1227
+ data-hook={dataHook}
1228
+ data-slot="combobox-item"
1229
+ id={`${virtualCtx.idPrefix}item-${itemValue}`}
1230
+ role="option"
1231
+ tabIndex={-1}
1232
+ onClick={isDisabled ? undefined : handleSelect}
1233
+ onKeyDown={
1234
+ isDisabled
1235
+ ? undefined
1236
+ : (e) => {
1237
+ if (e.key === "Enter" || e.key === " ") handleSelect();
1238
+ }
1239
+ }
1240
+ onPointerMove={
1241
+ isDisabled
1242
+ ? undefined
1243
+ : () => virtualCtx.onItemPointerMove(itemValue)
1244
+ }
1245
+ >
1246
+ {renderContent()}
1247
+ {isSelected && (
1248
+ <Check
1249
+ aria-hidden="true"
1250
+ className="text-muted-foreground shrink-0"
1251
+ />
1252
+ )}
1253
+ </div>
1254
+ );
1255
+ }
1256
+
663
1257
  return (
664
1258
  <CommandItem
665
1259
  ref={ref}
@@ -716,14 +1310,13 @@ export interface ComboboxLoadingProps {
716
1310
  function ComboboxLoading({ className, children }: ComboboxLoadingProps) {
717
1311
  return (
718
1312
  <div
719
- aria-disabled="true"
720
- aria-selected="false"
1313
+ aria-live="polite"
721
1314
  className={cn(
722
1315
  "text-muted-foreground flex items-center justify-center gap-2 py-6 text-sm",
723
1316
  className
724
1317
  )}
725
1318
  data-slot="combobox-loading"
726
- role="option"
1319
+ role="status"
727
1320
  >
728
1321
  {children || (
729
1322
  <>
@@ -749,6 +1342,7 @@ export {
749
1342
  ComboboxContent,
750
1343
  ComboboxInput,
751
1344
  ComboboxList,
1345
+ ComboboxVirtualList,
752
1346
  ComboboxEmpty,
753
1347
  ComboboxGroup,
754
1348
  ComboboxItem,