@foundrykit/components 1.0.9 → 1.0.12

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.
@@ -0,0 +1,739 @@
1
+ 'use client';
2
+
3
+ import * as React from 'react';
4
+ import { Slot } from '@radix-ui/react-slot';
5
+ import { cva, VariantProps } from 'class-variance-authority';
6
+ import { Search, X, ChevronDown } from 'lucide-react';
7
+
8
+ import { cn } from '@foundrykit/utils';
9
+ import {
10
+ useAdvancedSearch,
11
+ SearchContext,
12
+ type EmptyStateBehavior,
13
+ } from '@foundrykit/hooks';
14
+ import { Input } from '@foundrykit/primitives';
15
+ import { Button } from '@foundrykit/primitives';
16
+ import { Separator } from '@foundrykit/primitives';
17
+ import { Badge } from '@foundrykit/primitives';
18
+ import { Card, CardContent } from '@foundrykit/primitives';
19
+ import {
20
+ Popover,
21
+ PopoverContent,
22
+ PopoverTrigger,
23
+ } from '@foundrykit/primitives';
24
+
25
+ // Re-export types from hooks package
26
+ import type {
27
+ SearchResult,
28
+ SearchSection as SearchSectionType,
29
+ } from '@foundrykit/types';
30
+
31
+ // Provider Component
32
+ export interface AdvancedSearchProviderProps {
33
+ children: React.ReactNode;
34
+ onSearch?: (query: string) => Promise<SearchResult[]> | SearchResult[];
35
+ onResultSelect?: (result: SearchResult) => void;
36
+ debounceMs?: number;
37
+ minQueryLength?: number;
38
+ emptyStateBehavior?: EmptyStateBehavior;
39
+ initialResults?: SearchResult[]; // For showing all results initially
40
+ }
41
+
42
+ export function AdvancedSearchProvider({
43
+ children,
44
+ onSearch,
45
+ onResultSelect,
46
+ debounceMs = 300,
47
+ minQueryLength = 1,
48
+ emptyStateBehavior = 'show-empty-message',
49
+ initialResults = [],
50
+ }: AdvancedSearchProviderProps) {
51
+ const [query, setQuery] = React.useState('');
52
+ const [isOpen, setIsOpen] = React.useState(false);
53
+ const [results, setResults] = React.useState<SearchResult[]>(initialResults);
54
+ const [isLoading, setIsLoading] = React.useState(false);
55
+
56
+ const debouncedSearch = React.useCallback(
57
+ (searchQuery: string) => {
58
+ const timeoutId = setTimeout(async () => {
59
+ if (searchQuery.length >= minQueryLength && onSearch) {
60
+ setIsLoading(true);
61
+ try {
62
+ const searchResults = await onSearch(searchQuery);
63
+ setResults(searchResults);
64
+ } catch (error) {
65
+ console.error('Search error:', error);
66
+ setResults([]);
67
+ } finally {
68
+ setIsLoading(false);
69
+ }
70
+ } else {
71
+ // Handle different empty state behaviors
72
+ if (
73
+ emptyStateBehavior === 'show-all-results' &&
74
+ searchQuery.length === 0
75
+ ) {
76
+ // Show initial results when query is empty
77
+ setResults(initialResults);
78
+ } else if (
79
+ emptyStateBehavior === 'show-all-results' &&
80
+ searchQuery.length > 0 &&
81
+ searchQuery.length < minQueryLength
82
+ ) {
83
+ // Show initial results when query is too short
84
+ setResults(initialResults);
85
+ } else {
86
+ // Default behavior: show empty results
87
+ setResults([]);
88
+ }
89
+ }
90
+ }, debounceMs);
91
+
92
+ return () => clearTimeout(timeoutId);
93
+ },
94
+ [onSearch, debounceMs, minQueryLength, emptyStateBehavior, initialResults]
95
+ );
96
+
97
+ const handleSearch = React.useCallback(
98
+ (searchQuery: string) => {
99
+ setQuery(searchQuery);
100
+ debouncedSearch(searchQuery);
101
+ },
102
+ [debouncedSearch]
103
+ );
104
+
105
+ const handleResultSelect = React.useCallback(
106
+ (result: SearchResult) => {
107
+ onResultSelect?.(result);
108
+ setIsOpen(false);
109
+ },
110
+ [onResultSelect]
111
+ );
112
+
113
+ const value = React.useMemo(
114
+ () => ({
115
+ query,
116
+ setQuery,
117
+ isOpen,
118
+ setIsOpen,
119
+ results,
120
+ setResults,
121
+ isLoading,
122
+ setIsLoading,
123
+ onSearch: handleSearch,
124
+ onResultSelect: handleResultSelect,
125
+ emptyStateBehavior,
126
+ minQueryLength,
127
+ }),
128
+ [
129
+ query,
130
+ isOpen,
131
+ results,
132
+ isLoading,
133
+ handleSearch,
134
+ handleResultSelect,
135
+ emptyStateBehavior,
136
+ minQueryLength,
137
+ ]
138
+ );
139
+
140
+ return (
141
+ <SearchContext.Provider value={value}>{children}</SearchContext.Provider>
142
+ );
143
+ }
144
+
145
+ // Search Input Wrapper Variants
146
+ const searchInputWrapperVariants = cva('relative flex items-center w-full', {
147
+ variants: {
148
+ size: {
149
+ sm: 'h-8',
150
+ md: 'h-10',
151
+ lg: 'h-12',
152
+ xl: 'h-14',
153
+ },
154
+ variant: {
155
+ default: 'border border-input bg-background',
156
+ ghost: 'bg-transparent',
157
+ filled: 'bg-muted',
158
+ },
159
+ },
160
+ defaultVariants: {
161
+ size: 'md',
162
+ variant: 'default',
163
+ },
164
+ });
165
+
166
+ // Search Results Variants
167
+ const searchResultsVariants = cva('w-full', {
168
+ variants: {
169
+ size: {
170
+ sm: 'max-w-sm',
171
+ md: 'max-w-md',
172
+ lg: 'max-w-lg',
173
+ xl: 'max-w-xl',
174
+ '2xl': 'max-w-2xl',
175
+ full: 'max-w-full',
176
+ },
177
+ },
178
+ defaultVariants: {
179
+ size: 'lg',
180
+ },
181
+ });
182
+
183
+ // Search Input Component
184
+ export interface SearchInputProps
185
+ extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'>,
186
+ VariantProps<typeof searchInputWrapperVariants> {
187
+ placeholder?: string;
188
+ showSearchIcon?: boolean;
189
+ showClearButton?: boolean;
190
+ onClear?: () => void;
191
+ asChild?: boolean;
192
+ }
193
+
194
+ export const SearchInput = React.forwardRef<HTMLInputElement, SearchInputProps>(
195
+ (
196
+ {
197
+ className,
198
+ size,
199
+ variant,
200
+ placeholder = 'Search...',
201
+ showSearchIcon = true,
202
+ showClearButton = true,
203
+ onClear,
204
+ asChild = false,
205
+ ...props
206
+ },
207
+ ref
208
+ ) => {
209
+ const {
210
+ query,
211
+ setQuery,
212
+ onSearch,
213
+ setIsOpen,
214
+ emptyStateBehavior,
215
+ minQueryLength,
216
+ } = useAdvancedSearch();
217
+ const Comp = asChild ? Slot : 'div';
218
+
219
+ const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
220
+ const value = e.target.value;
221
+ setQuery(value);
222
+ onSearch(value);
223
+
224
+ // Handle popover opening based on empty state behavior
225
+ if (emptyStateBehavior === 'hide-until-min-chars') {
226
+ setIsOpen(value.length >= minQueryLength);
227
+ } else {
228
+ setIsOpen(true); // Open popover when typing for other behaviors
229
+ }
230
+
231
+ props.onChange?.(e);
232
+ };
233
+
234
+ const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
235
+ // Handle popover opening based on empty state behavior
236
+ if (emptyStateBehavior === 'hide-until-min-chars') {
237
+ setIsOpen(query.length >= minQueryLength);
238
+ } else {
239
+ setIsOpen(true); // Open popover when focused for other behaviors
240
+ }
241
+
242
+ props.onFocus?.(e);
243
+ };
244
+
245
+ const handleClear = () => {
246
+ setQuery('');
247
+ onSearch('');
248
+ onClear?.();
249
+ };
250
+
251
+ return (
252
+ <Comp
253
+ className={cn(
254
+ searchInputWrapperVariants({ size, variant }),
255
+ 'rounded-md',
256
+ className
257
+ )}
258
+ >
259
+ {showSearchIcon && (
260
+ <Search className='text-muted-foreground absolute left-3 h-4 w-4' />
261
+ )}
262
+ <Input
263
+ ref={ref}
264
+ type='search'
265
+ placeholder={placeholder}
266
+ value={query}
267
+ onChange={handleChange}
268
+ onFocus={handleFocus}
269
+ className={cn(
270
+ 'border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0',
271
+ showSearchIcon && 'pl-10',
272
+ showClearButton && query && 'pr-10'
273
+ )}
274
+ size={undefined}
275
+ {...props}
276
+ />
277
+ {showClearButton && query && (
278
+ <Button
279
+ variant='ghost'
280
+ size='sm'
281
+ className='absolute right-1 h-6 w-6 p-0'
282
+ onClick={handleClear}
283
+ >
284
+ <X className='h-3 w-3' />
285
+ </Button>
286
+ )}
287
+ </Comp>
288
+ );
289
+ }
290
+ );
291
+ SearchInput.displayName = 'SearchInput';
292
+
293
+ // Search Trigger Component
294
+ export interface SearchTriggerProps
295
+ extends React.ButtonHTMLAttributes<HTMLButtonElement> {
296
+ asChild?: boolean;
297
+ }
298
+
299
+ export const SearchTrigger = React.forwardRef<
300
+ HTMLButtonElement,
301
+ SearchTriggerProps
302
+ >(({ className, asChild = false, children, ...props }, ref) => {
303
+ const { isOpen, setIsOpen } = useAdvancedSearch();
304
+ const Comp = asChild ? Slot : Button;
305
+
306
+ return (
307
+ <Comp
308
+ ref={ref}
309
+ className={cn(className)}
310
+ onClick={() => setIsOpen(!isOpen)}
311
+ {...props}
312
+ >
313
+ {children}
314
+ </Comp>
315
+ );
316
+ });
317
+ SearchTrigger.displayName = 'SearchTrigger';
318
+
319
+ // Search Results Component
320
+ export interface SearchResultsProps
321
+ extends React.HTMLAttributes<HTMLDivElement>,
322
+ VariantProps<typeof searchResultsVariants> {
323
+ sections?: SearchSectionType[];
324
+ showEmptyState?: boolean;
325
+ emptyStateMessage?: string;
326
+ showLoadingState?: boolean;
327
+ loadingMessage?: string;
328
+ }
329
+
330
+ export const SearchResults = React.forwardRef<
331
+ HTMLDivElement,
332
+ SearchResultsProps
333
+ >(
334
+ (
335
+ {
336
+ className,
337
+ size,
338
+ sections,
339
+ showEmptyState = true,
340
+ emptyStateMessage = 'No results found',
341
+ showLoadingState = true,
342
+ loadingMessage = 'Searching...',
343
+ ...props
344
+ },
345
+ ref
346
+ ) => {
347
+ const {
348
+ results,
349
+ isLoading,
350
+ query,
351
+ onResultSelect,
352
+ emptyStateBehavior,
353
+ minQueryLength,
354
+ } = useAdvancedSearch();
355
+
356
+ if (isLoading && showLoadingState) {
357
+ return (
358
+ <div
359
+ ref={ref}
360
+ className={cn(
361
+ searchResultsVariants({ size }),
362
+ 'text-muted-foreground p-4 text-center',
363
+ className
364
+ )}
365
+ {...props}
366
+ >
367
+ {loadingMessage}
368
+ </div>
369
+ );
370
+ }
371
+
372
+ // Handle different empty state behaviors
373
+ if (!query || results.length === 0) {
374
+ if (!showEmptyState) return null;
375
+
376
+ // For hide-until-min-chars behavior, don't show anything if query is too short
377
+ if (
378
+ emptyStateBehavior === 'hide-until-min-chars' &&
379
+ query.length > 0 &&
380
+ query.length < minQueryLength
381
+ ) {
382
+ return null;
383
+ }
384
+
385
+ return (
386
+ <div
387
+ ref={ref}
388
+ className={cn(
389
+ searchResultsVariants({ size }),
390
+ 'text-muted-foreground p-4 text-center',
391
+ className
392
+ )}
393
+ {...props}
394
+ >
395
+ {emptyStateMessage}
396
+ </div>
397
+ );
398
+ }
399
+
400
+ // Use sections if provided, otherwise use default results
401
+ const displaySections = sections || [
402
+ {
403
+ id: 'results',
404
+ title: 'Results',
405
+ results: results,
406
+ },
407
+ ];
408
+
409
+ return (
410
+ <div
411
+ ref={ref}
412
+ className={cn(
413
+ searchResultsVariants({ size }),
414
+ 'max-h-96 overflow-hidden',
415
+ className
416
+ )}
417
+ {...props}
418
+ >
419
+ <div className='h-full overflow-auto'>
420
+ <div className='space-y-4 p-4'>
421
+ {displaySections.map((section, index) => (
422
+ <div key={section.id}>
423
+ {index > 0 && <Separator className='my-4' />}
424
+ <div className='space-y-2'>
425
+ <h3 className='text-muted-foreground text-sm font-semibold uppercase tracking-wide'>
426
+ {section.title}
427
+ </h3>
428
+ <div className='space-y-1'>
429
+ {section.results.map((result: SearchResult) => (
430
+ <SearchResultItem
431
+ key={result.id}
432
+ result={result}
433
+ onClick={() => onResultSelect(result)}
434
+ />
435
+ ))}
436
+ {section.showMore && section.onShowMore && (
437
+ <Button
438
+ variant='ghost'
439
+ size='sm'
440
+ className='text-muted-foreground w-full justify-start'
441
+ onClick={section.onShowMore}
442
+ >
443
+ Show more
444
+ <ChevronDown className='ml-2 h-3 w-3' />
445
+ </Button>
446
+ )}
447
+ </div>
448
+ </div>
449
+ </div>
450
+ ))}
451
+ </div>
452
+ </div>
453
+ </div>
454
+ );
455
+ }
456
+ );
457
+ SearchResults.displayName = 'SearchResults';
458
+
459
+ // Search Result Item Component
460
+ interface SearchResultItemProps {
461
+ result: SearchResult;
462
+ onClick: () => void;
463
+ }
464
+
465
+ const SearchResultItem = ({ result, onClick }: SearchResultItemProps) => {
466
+ if (result.type === 'category') {
467
+ return (
468
+ <div className='text-muted-foreground p-2 text-sm font-medium'>
469
+ {result.title}
470
+ </div>
471
+ );
472
+ }
473
+
474
+ if (result.type === 'suggestion') {
475
+ return (
476
+ <Button
477
+ variant='ghost'
478
+ size='sm'
479
+ className='h-auto w-full justify-start p-2'
480
+ onClick={onClick}
481
+ >
482
+ <span className='text-sm'>{result.title}</span>
483
+ </Button>
484
+ );
485
+ }
486
+
487
+ // Complex result with image, description, etc.
488
+ return (
489
+ <Card
490
+ className='hover:bg-muted/50 cursor-pointer transition-colors'
491
+ onClick={onClick}
492
+ >
493
+ <CardContent className='p-3'>
494
+ <div className='flex gap-3'>
495
+ {result.image && (
496
+ <div className='flex-shrink-0'>
497
+ <img
498
+ src={result.image}
499
+ alt={result.title}
500
+ className='h-12 w-12 rounded-md object-cover'
501
+ />
502
+ </div>
503
+ )}
504
+ <div className='min-w-0 flex-1'>
505
+ <div className='flex items-start justify-between gap-2'>
506
+ <h4 className='truncate text-sm font-semibold'>{result.title}</h4>
507
+ {result.badge && (
508
+ <Badge variant='secondary' className='text-xs'>
509
+ {result.badge}
510
+ </Badge>
511
+ )}
512
+ </div>
513
+ {result.description && (
514
+ <p className='text-muted-foreground mt-1 line-clamp-2 text-xs'>
515
+ {result.description}
516
+ </p>
517
+ )}
518
+ </div>
519
+ </div>
520
+ </CardContent>
521
+ </Card>
522
+ );
523
+ };
524
+
525
+ // Main Advanced Search Bar Component (Compound Pattern)
526
+ export interface AdvancedSearchBarProps
527
+ extends React.HTMLAttributes<HTMLDivElement> {
528
+ open?: boolean;
529
+ onOpenChange?: (open: boolean) => void;
530
+ }
531
+
532
+ export const AdvancedSearchBar = React.forwardRef<
533
+ HTMLDivElement,
534
+ AdvancedSearchBarProps
535
+ >(({ className, children, open, onOpenChange, ...props }, ref) => {
536
+ const { isOpen, setIsOpen } = useAdvancedSearch();
537
+
538
+ const handleOpenChange = (newOpen: boolean) => {
539
+ if (open !== undefined) {
540
+ onOpenChange?.(newOpen);
541
+ } else {
542
+ setIsOpen(newOpen);
543
+ }
544
+ };
545
+
546
+ const isControlled = open !== undefined;
547
+ const isOpenState = isControlled ? open : isOpen;
548
+
549
+ // Find Input and Results components in children
550
+ const childrenArray = React.Children.toArray(children);
551
+ const inputChild = childrenArray.find(
552
+ child => React.isValidElement(child) && child.type === SearchInput
553
+ );
554
+ const resultsChild = childrenArray.find(
555
+ child => React.isValidElement(child) && child.type === SearchResults
556
+ );
557
+
558
+ // If no Input found, create a default one
559
+ const triggerElement = inputChild || <SearchInput />;
560
+
561
+ return (
562
+ <div ref={ref} className={cn('relative', className)} {...props}>
563
+ <Popover open={isOpenState} onOpenChange={handleOpenChange}>
564
+ <PopoverTrigger asChild>{triggerElement}</PopoverTrigger>
565
+ <PopoverContent className='p-0' align='start'>
566
+ {resultsChild || <SearchResults />}
567
+ </PopoverContent>
568
+ </Popover>
569
+ </div>
570
+ );
571
+ });
572
+ AdvancedSearchBar.displayName = 'AdvancedSearchBar';
573
+
574
+ // Compound Pattern Components
575
+
576
+ // Search Section Component (for compound pattern)
577
+ export interface SearchSectionProps
578
+ extends React.HTMLAttributes<HTMLDivElement> {
579
+ title?: string;
580
+ maxResults?: number;
581
+ showMore?: boolean;
582
+ onShowMore?: () => void;
583
+ }
584
+
585
+ export const SearchSection = React.forwardRef<
586
+ HTMLDivElement,
587
+ SearchSectionProps
588
+ >(({ className, title, showMore, onShowMore, children, ...props }, ref) => {
589
+ return (
590
+ <div ref={ref} className={cn('space-y-2', className)} {...props}>
591
+ {title && (
592
+ <h3 className='text-muted-foreground text-sm font-semibold uppercase tracking-wide'>
593
+ {title}
594
+ </h3>
595
+ )}
596
+ <div className='space-y-1'>
597
+ {children}
598
+ {showMore && onShowMore && (
599
+ <Button
600
+ variant='ghost'
601
+ size='sm'
602
+ className='text-muted-foreground w-full justify-start'
603
+ onClick={onShowMore}
604
+ >
605
+ Show more
606
+ <ChevronDown className='ml-2 h-3 w-3' />
607
+ </Button>
608
+ )}
609
+ </div>
610
+ </div>
611
+ );
612
+ });
613
+ SearchSection.displayName = 'SearchSection ';
614
+
615
+ // Search Item Component (for compound pattern)
616
+ export interface SearchItemProps extends React.HTMLAttributes<HTMLDivElement> {
617
+ result?: SearchResult;
618
+ onClick?: () => void;
619
+ }
620
+
621
+ export const SearchItem = React.forwardRef<HTMLDivElement, SearchItemProps>(
622
+ ({ className, result, onClick, children, ...props }, ref) => {
623
+ const { onResultSelect } = useAdvancedSearch();
624
+
625
+ const handleClick = () => {
626
+ if (result) {
627
+ onResultSelect(result);
628
+ }
629
+ onClick?.();
630
+ };
631
+
632
+ // If children are provided, render them directly
633
+ if (children) {
634
+ return (
635
+ <div
636
+ ref={ref}
637
+ className={cn('cursor-pointer', className)}
638
+ onClick={handleClick}
639
+ {...props}
640
+ >
641
+ {children}
642
+ </div>
643
+ );
644
+ }
645
+
646
+ // Otherwise render based on result type
647
+ if (!result) return null;
648
+
649
+ if (result.type === 'category') {
650
+ return (
651
+ <div
652
+ ref={ref}
653
+ className={cn(
654
+ 'text-muted-foreground p-2 text-sm font-medium',
655
+ className
656
+ )}
657
+ {...props}
658
+ >
659
+ {result.title}
660
+ </div>
661
+ );
662
+ }
663
+
664
+ if (result.type === 'suggestion') {
665
+ return (
666
+ <Button
667
+ ref={ref as unknown as React.RefObject<HTMLButtonElement>}
668
+ variant='ghost'
669
+ size='sm'
670
+ className={cn('h-auto w-full justify-start p-2', className)}
671
+ onClick={handleClick}
672
+ {...(props as React.ButtonHTMLAttributes<HTMLButtonElement>)}
673
+ >
674
+ <span className='text-sm'>{result.title}</span>
675
+ </Button>
676
+ );
677
+ }
678
+
679
+ // Complex result with image, description, etc.
680
+ return (
681
+ <Card
682
+ ref={ref as unknown as React.RefObject<HTMLDivElement>}
683
+ className={cn(
684
+ 'hover:bg-muted/50 cursor-pointer transition-colors',
685
+ className
686
+ )}
687
+ onClick={handleClick}
688
+ {...(props as React.HTMLAttributes<HTMLDivElement>)}
689
+ >
690
+ <CardContent className='p-3'>
691
+ <div className='flex gap-3'>
692
+ {result.image && (
693
+ <div className='flex-shrink-0'>
694
+ <img
695
+ src={result.image}
696
+ alt={result.title}
697
+ className='h-12 w-12 rounded-md object-cover'
698
+ />
699
+ </div>
700
+ )}
701
+ <div className='min-w-0 flex-1'>
702
+ <div className='flex items-start justify-between gap-2'>
703
+ <h4 className='truncate text-sm font-semibold'>
704
+ {result.title}
705
+ </h4>
706
+ {result.badge && (
707
+ <Badge variant='secondary' className='text-xs'>
708
+ {result.badge}
709
+ </Badge>
710
+ )}
711
+ </div>
712
+ {result.description && (
713
+ <p className='text-muted-foreground mt-1 line-clamp-2 text-xs'>
714
+ {result.description}
715
+ </p>
716
+ )}
717
+ </div>
718
+ </div>
719
+ </CardContent>
720
+ </Card>
721
+ );
722
+ }
723
+ );
724
+ SearchItem.displayName = 'SearchItem';
725
+
726
+ // Export all components with compound pattern
727
+ export {
728
+ AdvancedSearchBar as Root,
729
+ SearchInput as Input,
730
+ SearchTrigger as Trigger,
731
+ SearchResults as Results,
732
+ SearchSection as Section,
733
+ SearchItem as Item,
734
+ searchInputWrapperVariants,
735
+ searchResultsVariants,
736
+ };
737
+
738
+ // Export Provider separately to avoid conflicts
739
+ export { AdvancedSearchProvider as Provider };