Repository navigation
Expand file tree
/
Copy pathCustomSelect.tsx
More file actions
516 lines (475 loc) · 17.6 KB
/
Copy pathCustomSelect.tsx
File metadata and controls
516 lines (475 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
"use client";
import { Icon as UiIcon } from "@repo/ui/icons";
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";
import { inputVariants } from "./input";
const MENU_OFFSET = 8;
const MENU_MAX_HEIGHT = 320;
const VIEWPORT_PADDING = 12;
const SEARCH_AUTO_THRESHOLD = 8;
interface Option<T extends string> {
value: T;
label: string;
icon?: React.ReactNode;
/** Optional dimmed second line under the label (domain, host, hint …). */
description?: string;
}
interface CustomSelectFooterAction {
label: string;
icon?: React.ReactNode;
onClick: () => void;
}
interface DropdownPosition {
top?: number;
bottom?: number;
left: number;
width: number;
maxHeight: number;
zIndex: number;
}
export interface CustomSelectProps<T extends string> {
id?: string;
"aria-label"?: string;
value: T;
options: Option<T>[];
onChange: (value: T) => void;
placeholder?: string;
className?: string;
triggerClassName?: string;
/** Keep domain-specific rows identical in the trigger and searchable menu. */
renderOption?: (option: Option<T>, selected: boolean) => React.ReactNode;
/** Input and filled use the shared Input appearance, with descriptions only in the menu. */
variant?: "default" | "input" | "filled";
footerAction?: CustomSelectFooterAction;
/** Fired once each time the menu opens — use to lazily load options. */
onOpen?: () => void;
disabled?: boolean;
onLoadMore?: () => void;
hasMore?: boolean;
isLoadingMore?: boolean;
searchable?: boolean;
searchPlaceholder?: string;
emptySearchMessage?: (query: string) => string;
emptyMessage?: string;
loadingMessage?: string;
loadMoreMessage?: string;
}
export function CustomSelect<T extends string>({
id,
"aria-label": ariaLabel,
value,
options,
onChange,
placeholder = "Select",
className = "",
triggerClassName,
renderOption,
variant = "default",
footerAction,
onOpen,
disabled = false,
onLoadMore,
hasMore = false,
isLoadingMore = false,
searchable,
searchPlaceholder,
emptySearchMessage,
emptyMessage = "No matches",
loadingMessage = "Loading...",
loadMoreMessage = "Load more",
}: CustomSelectProps<T>) {
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState("");
const [highlightedValue, setHighlightedValue] = useState<T>();
const listId = useId();
const containerRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const didInitialScroll = useRef(false);
const [menuPosition, setMenuPosition] = useState<DropdownPosition | null>(null);
const selectedOption = options.find((opt) => opt.value === value);
const showSearch =
searchable ?? (Boolean(searchPlaceholder) || options.length >= SEARCH_AUTO_THRESHOLD);
const filteredOptions = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return options;
return options.filter((opt) =>
`${opt.label} ${opt.value} ${opt.description ?? ""}`.toLocaleLowerCase().includes(q),
);
}, [options, query]);
// Loading another page can reorder options; keep keyboard focus on the same value.
const highlight = Math.max(
0,
filteredOptions.findIndex((option) => option.value === highlightedValue),
);
const updateMenuPosition = useCallback(() => {
if (!triggerRef.current || typeof window === "undefined") return;
const rect = triggerRef.current.getBoundingClientRect();
const width = Math.min(Math.max(rect.width, 220), window.innerWidth - VIEWPORT_PADDING * 2);
const left = Math.min(
Math.max(VIEWPORT_PADDING, rect.left),
Math.max(VIEWPORT_PADDING, window.innerWidth - width - VIEWPORT_PADDING),
);
const spaceBelow = window.innerHeight - rect.bottom - VIEWPORT_PADDING;
const spaceAbove = rect.top - VIEWPORT_PADDING;
const openAbove = spaceBelow < 220 && spaceAbove > spaceBelow;
const availableHeight = Math.max(120, (openAbove ? spaceAbove : spaceBelow) - MENU_OFFSET);
// Menus are portaled to body, so they must inherit the owning modal's
// layer explicitly. A nested modal sits above the default menu layer.
const modalLayer = Number(
triggerRef.current.closest("[data-modal-layer]")?.getAttribute("data-modal-layer") ?? 0,
);
const zIndex = Math.max(10050, modalLayer + 50);
setMenuPosition(
openAbove
? {
bottom: window.innerHeight - rect.top + MENU_OFFSET,
left,
width,
maxHeight: Math.min(MENU_MAX_HEIGHT, availableHeight),
zIndex,
}
: {
top: rect.bottom + MENU_OFFSET,
left,
width,
maxHeight: Math.min(MENU_MAX_HEIGHT, availableHeight),
zIndex,
},
);
}, []);
useEffect(() => {
const isInside = (target: EventTarget | null) =>
target instanceof Node &&
(!!containerRef.current?.contains(target) || !!menuRef.current?.contains(target));
const handleClickOutside = (event: MouseEvent) => {
if (!isInside(event.target)) {
setIsOpen(false);
}
};
const handleEscape = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setIsOpen(false);
triggerRef.current?.focus();
}
};
if (isOpen) {
document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("keydown", handleEscape);
}
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleEscape);
};
}, [isOpen]);
useEffect(() => {
if (!isOpen) {
setMenuPosition(null);
setQuery("");
return;
}
updateMenuPosition();
const handlePositionChange = () => updateMenuPosition();
window.addEventListener("resize", handlePositionChange);
window.addEventListener("scroll", handlePositionChange, true);
return () => {
window.removeEventListener("resize", handlePositionChange);
window.removeEventListener("scroll", handlePositionChange, true);
};
}, [isOpen, updateMenuPosition]);
useEffect(() => {
if (!isOpen) {
didInitialScroll.current = false;
return;
}
if (didInitialScroll.current || !listRef.current) return;
didInitialScroll.current = true;
const selectedIndex = filteredOptions.findIndex((opt) => opt.value === value);
const start = selectedIndex >= 0 ? selectedIndex : 0;
setHighlightedValue(filteredOptions[start]?.value);
listRef.current.querySelector(`[data-index="${start}"]`)?.scrollIntoView({ block: "nearest" });
if (showSearch) inputRef.current?.focus();
else listRef.current.focus();
}, [filteredOptions, isOpen, menuPosition, showSearch, value]);
// A filtered first page can be empty and therefore cannot trigger scrolling.
// Keep looking through later pages until the menu has matches or reaches the end.
useEffect(() => {
if (
isOpen &&
query.trim() &&
filteredOptions.length < SEARCH_AUTO_THRESHOLD &&
hasMore &&
!isLoadingMore
) {
onLoadMore?.();
}
}, [isOpen, query, filteredOptions.length, hasMore, isLoadingMore, onLoadMore]);
const handleSearch = (nextQuery: string) => {
setQuery(nextQuery);
setHighlightedValue(undefined);
listRef.current?.scrollTo({ top: 0 });
};
const handleSelect = (optionValue: T) => {
onChange(optionValue);
setIsOpen(false);
triggerRef.current?.focus();
};
const handleFooterAction = () => {
setIsOpen(false);
// A dialog opened by the action must restore focus to the surviving trigger.
triggerRef.current?.focus();
footerAction?.onClick();
};
const moveHighlight = (delta: number) => {
if (filteredOptions.length === 0) return;
const next = Math.min(Math.max(highlight + delta, 0), filteredOptions.length - 1);
setHighlightedValue(filteredOptions[next].value);
listRef.current?.querySelector(`[data-index="${next}"]`)?.scrollIntoView({ block: "nearest" });
};
const handleMenuKeyDown = (event: React.KeyboardEvent) => {
// Buttons (including the footer action) retain their native Enter behavior.
if (
event.key === "Enter" &&
event.target !== inputRef.current &&
event.target !== listRef.current
)
return;
if (event.key === "ArrowDown") {
event.preventDefault();
moveHighlight(1);
} else if (event.key === "ArrowUp") {
event.preventDefault();
moveHighlight(-1);
} else if (event.key === "Enter") {
event.preventDefault();
const option = filteredOptions[highlight];
if (option) handleSelect(option.value);
}
};
const handleListScroll = (event: React.UIEvent<HTMLDivElement>) => {
if (!onLoadMore || !hasMore || isLoadingMore) return;
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (scrollHeight - scrollTop - clientHeight <= 64) onLoadMore();
};
const dropdownMenu =
isOpen && menuPosition && typeof document !== "undefined"
? createPortal(
<div
ref={menuRef}
onKeyDown={handleMenuKeyDown}
className="fixed flex flex-col overflow-hidden rounded-2xl border border-border/50 bg-popover shadow-[var(--th-dropdown-shadow)]"
style={{
left: menuPosition.left,
width: menuPosition.width,
maxHeight: menuPosition.maxHeight,
zIndex: menuPosition.zIndex,
...(menuPosition.top !== undefined
? { top: menuPosition.top }
: { bottom: menuPosition.bottom }),
}}
>
{showSearch && (
<div className="flex-none border-b border-border/50 px-3 py-2">
<div className="flex items-center gap-2">
<UiIcon
name="search"
className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0"
/>
<input
ref={inputRef}
type="text"
role="combobox"
aria-expanded={true}
aria-controls={listId}
aria-activedescendant={
filteredOptions[highlight] ? `${listId}-${highlight}` : undefined
}
value={query}
onChange={(e) => handleSearch(e.target.value)}
placeholder={searchPlaceholder ?? "Search..."}
aria-label={searchPlaceholder ?? "Search..."}
className="w-full bg-transparent text-sm text-foreground placeholder:text-muted-foreground focus:outline-none"
/>
</div>
</div>
)}
<div
ref={listRef}
id={listId}
role="listbox"
aria-label={ariaLabel ?? placeholder}
tabIndex={-1}
onScroll={handleListScroll}
className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-1.5 touch-pan-y"
>
{filteredOptions.length === 0 && !isLoadingMore ? (
<div className="px-4 py-3 text-sm text-muted-foreground">
{emptySearchMessage?.(query) ?? emptyMessage}
</div>
) : (
filteredOptions.map((option, index) => {
const isSelected = option.value === value;
const isHighlighted = index === highlight;
return (
<button
key={option.value}
id={`${listId}-${index}`}
data-index={index}
role="option"
aria-selected={isSelected}
onClick={() => handleSelect(option.value)}
onMouseEnter={() => setHighlightedValue(option.value)}
className={`
w-full px-4 py-2.5 text-start flex items-center justify-between gap-2
text-sm transition-all duration-150
${
isSelected
? "bg-accent text-accent-foreground font-medium"
: isHighlighted
? "text-foreground bg-accent/50"
: "text-muted-foreground hover:text-foreground hover:bg-accent/50"
}
`}
type="button"
>
<span className="flex min-w-0 items-center gap-2">
{renderOption ? (
renderOption(option, isSelected)
) : (
<>
{option.icon}
<span className="flex min-w-0 flex-col">
<span className="truncate">{option.label}</span>
{option.description && (
<span className="truncate text-xs text-muted-foreground/70">
{option.description}
</span>
)}
</span>
</>
)}
</span>
{isSelected && (
<UiIcon
name="check"
className="w-3.5 h-3.5 text-muted-foreground flex-shrink-0"
/>
)}
</button>
);
})
)}
</div>
{hasMore && onLoadMore && !isLoadingMore && (
<button
type="button"
onClick={onLoadMore}
className="flex-none border-t border-border/50 px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
>
{loadMoreMessage}
</button>
)}
{isLoadingMore && (
<div
role="status"
className="flex flex-none items-center justify-center gap-2 border-t border-border/50 px-4 py-2 text-xs text-muted-foreground"
>
<UiIcon name="spinner" className="h-3.5 w-3.5 animate-spin" />
{loadingMessage}
</div>
)}
{footerAction && (
<div className="flex-none border-t border-border/50 p-1.5">
<button
type="button"
onClick={handleFooterAction}
className="flex w-full items-center gap-2 rounded-xl px-3 py-2.5 text-start text-sm font-medium text-foreground transition-colors hover:bg-accent/50"
>
{footerAction.icon}
{footerAction.label}
</button>
</div>
)}
</div>,
document.body,
)
: null;
return (
<div ref={containerRef} className={`relative ${className}`}>
{/* Select Button */}
<button
ref={triggerRef}
id={id}
onClick={() => {
if (disabled) return;
if (!isOpen) onOpen?.();
setIsOpen((prev) => !prev);
}}
disabled={disabled}
aria-expanded={isOpen}
aria-haspopup="listbox"
aria-label={ariaLabel}
aria-controls={isOpen ? listId : undefined}
aria-describedby={ariaLabel && selectedOption ? `${listId}-value` : undefined}
className={cn(
variant !== "default"
? inputVariants({ variant: variant === "filled" ? "filled" : "default" })
: `
w-full px-4 py-3 rounded-2xl text-sm font-medium
transition-all duration-200 flex items-center justify-between gap-2
border border-border/50
${
disabled
? "bg-muted/30 opacity-60 cursor-not-allowed"
: isOpen
? "bg-muted/80 border-border"
: "bg-muted/40 hover:bg-muted/60 hover:border-border"
}
`,
"items-center justify-between gap-2",
triggerClassName,
)}
type="button"
>
<span
className={cn(
"flex min-w-0 flex-1 items-center gap-2",
variant !== "default" ? "text-foreground" : "text-foreground/70",
)}
>
{selectedOption && renderOption ? (
<span id={`${listId}-value`} className="flex min-w-0 flex-1 items-center gap-3">
{renderOption(selectedOption, true)}
</span>
) : selectedOption ? (
<>
{selectedOption.icon}
<span className="flex min-w-0 flex-col text-start">
<span id={`${listId}-value`} className="truncate">
{selectedOption.label}
</span>
{variant === "default" && selectedOption.description && (
<span className="truncate text-xs font-normal text-muted-foreground/70">
{selectedOption.description}
</span>
)}
</span>
</>
) : (
<span className="text-muted-foreground">{placeholder}</span>
)}
</span>
<UiIcon
name="chevron-down"
className={`w-4 h-4 text-muted-foreground transition-transform duration-200 flex-shrink-0 ${
isOpen ? "rotate-180" : ""
}`}
/>
</button>
{dropdownMenu}
</div>
);
}