-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFilterBar.tsx
More file actions
815 lines (777 loc) · 29.9 KB
/
FilterBar.tsx
File metadata and controls
815 lines (777 loc) · 29.9 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import ListItemText from '@mui/material/ListItemText';
import Typography from '@mui/material/Typography';
import InputBase from '@mui/material/InputBase';
import Divider from '@mui/material/Divider';
import Tooltip from '@mui/material/Tooltip';
import CloseIcon from '@mui/icons-material/Close';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import type { FilterCategory, ActiveFilters, FilterCounts } from '../types';
import { FILTER_LABELS, FILTER_TOOLTIPS, FILTER_CATEGORIES } from '../types';
import type { ImageSize } from '../constants';
import { getAvailableValues, getAvailableValuesForGroup, getSearchResults, type SearchResult } from '../utils';
import { ToolbarActions } from './ToolbarActions';
interface FilterBarProps {
activeFilters: ActiveFilters;
filterCounts: FilterCounts | null; // Contextual counts (for AND additions)
orCounts: Record<string, number>[]; // Per-group counts for OR additions
specTitles: Record<string, string>; // Mapping spec_id -> title for search/tooltips
currentTotal: number; // Total number of filtered images
displayedCount: number; // Currently displayed images
randomAnimation: { index: number; phase: 'out' | 'in'; oldLabel?: string } | null;
searchInputRef?: React.RefObject<HTMLInputElement | null>;
imageSize: ImageSize;
onImageSizeChange: (size: ImageSize) => void;
onAddFilter: (category: FilterCategory, value: string) => void;
onAddValueToGroup: (groupIndex: number, value: string) => void;
onRemoveFilter: (groupIndex: number, value: string) => void;
onRemoveGroup: (groupIndex: number) => void;
onTrackEvent: (event: string, props?: Record<string, string>) => void;
}
export function FilterBar({
activeFilters,
filterCounts,
orCounts,
specTitles,
currentTotal,
displayedCount,
randomAnimation,
searchInputRef,
imageSize,
onImageSizeChange,
onAddFilter,
onAddValueToGroup,
onRemoveFilter,
onRemoveGroup,
onTrackEvent,
}: FilterBarProps) {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
// Scroll percentage and sticky detection
const [scrollPercent, setScrollPercent] = useState(0);
const [isSticky, setIsSticky] = useState(false);
const filterBarRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const calculatePercent = () => {
const scrollY = window.scrollY;
const docHeight = document.documentElement.scrollHeight;
const windowHeight = window.innerHeight;
// Estimate total height based on ratio of loaded vs total plots
const loadRatio = displayedCount > 0 && currentTotal > 0
? currentTotal / displayedCount
: 1;
const estimatedTotalHeight = (docHeight - windowHeight) * loadRatio;
const percent = Math.round((scrollY / estimatedTotalHeight) * 100);
setScrollPercent(Math.min(100, Math.max(0, percent || 0)));
// Detect if bar is in sticky mode (scrolled past threshold)
// The bar becomes sticky when scrollY > ~200px (header height)
setIsSticky(scrollY > 200);
};
calculatePercent();
window.addEventListener('scroll', calculatePercent);
const resizeObserver = new ResizeObserver(calculatePercent);
resizeObserver.observe(document.body);
return () => {
window.removeEventListener('scroll', calculatePercent);
resizeObserver.disconnect();
};
}, [displayedCount, currentTotal]);
// Search/dropdown state
const [searchQuery, setSearchQuery] = useState('');
const [dropdownAnchor, setDropdownAnchor] = useState<HTMLElement | null>(null);
const [selectedCategory, setSelectedCategory] = useState<FilterCategory | null>(null);
const [isSearchManuallyExpanded, setIsSearchManuallyExpanded] = useState(false);
const searchContainerRef = useRef<HTMLDivElement>(null);
const localInputRef = useRef<HTMLInputElement>(null);
const inputRef = searchInputRef || localInputRef;
// Search is expanded when: no filters OR manually expanded
const isSearchExpanded = activeFilters.length === 0 || isSearchManuallyExpanded;
// Chip menu state
const [chipMenuAnchor, setChipMenuAnchor] = useState<HTMLElement | null>(null);
const [activeGroupIndex, setActiveGroupIndex] = useState<number | null>(null);
// Dropdown keyboard navigation
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
// Expand and open dropdown
const handleSearchExpand = useCallback(() => {
setIsSearchManuallyExpanded(true);
setDropdownAnchor(searchContainerRef.current);
setTimeout(() => inputRef.current?.focus(), 0);
}, [inputRef]);
// Collapse when empty and loses focus (only if there are filters)
const handleSearchBlur = useCallback(() => {
// Delay to allow click events on dropdown to fire first
setTimeout(() => {
if (!searchQuery && !selectedCategory && !dropdownAnchor && activeFilters.length > 0) {
setIsSearchManuallyExpanded(false);
}
}, 200);
}, [searchQuery, selectedCategory, dropdownAnchor, activeFilters.length]);
// Close dropdown and collapse if empty
const handleDropdownClose = useCallback(() => {
setDropdownAnchor(null);
setSelectedCategory(null);
setSearchQuery('');
setHighlightedIndex(-1);
setIsSearchManuallyExpanded(false);
}, []);
// Select category from dropdown
const handleCategorySelect = useCallback((category: FilterCategory) => {
setSelectedCategory(category);
setSearchQuery('');
setHighlightedIndex(-1);
setTimeout(() => inputRef.current?.focus(), 50);
}, [inputRef]);
// Select value (add new filter group)
const handleValueSelect = useCallback(
(category: FilterCategory, value: string) => {
onAddFilter(category, value);
// Track search if query was used (filter changes tracked via pageview)
if (searchQuery.trim()) {
onTrackEvent('search', { query: searchQuery.trim(), category });
}
setSelectedCategory(null);
setSearchQuery('');
setHighlightedIndex(-1);
// Keep expanded and focused for next filter
setIsSearchManuallyExpanded(true);
setTimeout(() => {
setDropdownAnchor(searchContainerRef.current);
inputRef.current?.focus();
}, 50);
},
[onAddFilter, onTrackEvent, searchQuery, inputRef]
);
// Chip click - open chip menu
const handleChipClick = useCallback(
(event: React.MouseEvent<HTMLElement>, groupIndex: number) => {
setChipMenuAnchor(event.currentTarget);
setActiveGroupIndex(groupIndex);
},
[]
);
// Remove single value from group
const handleRemoveValue = useCallback(
(value: string) => {
if (activeGroupIndex !== null) {
onRemoveFilter(activeGroupIndex, value);
}
setChipMenuAnchor(null);
setActiveGroupIndex(null);
},
[activeGroupIndex, onRemoveFilter]
);
// Remove entire group
const handleRemoveGroup = useCallback(() => {
if (activeGroupIndex !== null) {
onRemoveGroup(activeGroupIndex);
}
setChipMenuAnchor(null);
setActiveGroupIndex(null);
}, [activeGroupIndex, onRemoveGroup]);
// Add value to existing group (OR)
const handleAddValueToExistingGroup = useCallback(
(value: string) => {
if (activeGroupIndex !== null) {
onAddValueToGroup(activeGroupIndex, value);
}
setChipMenuAnchor(null);
setActiveGroupIndex(null);
},
[activeGroupIndex, onAddValueToGroup]
);
// Memoize search results to avoid recalculating on every render
const searchResults = useMemo(
() => getSearchResults(filterCounts, activeFilters, searchQuery, selectedCategory, specTitles),
[filterCounts, activeFilters, searchQuery, selectedCategory, specTitles]
);
// Track searches with no results (debounced, to discover missing specs)
const lastTrackedQueryRef = useRef<string>('');
useEffect(() => {
const query = searchQuery.trim();
// Only track if: query >= 2 chars, no results, not already tracked this query
if (query.length >= 2 && searchResults.length === 0 && query !== lastTrackedQueryRef.current) {
const timer = setTimeout(() => {
onTrackEvent('search_no_results', { query });
lastTrackedQueryRef.current = query;
}, 200);
return () => clearTimeout(timer);
}
}, [searchQuery, searchResults.length, onTrackEvent]);
// Reset tracked query when dropdown closes
useEffect(() => {
if (!dropdownAnchor) {
lastTrackedQueryRef.current = '';
}
}, [dropdownAnchor]);
// Only open if anchor is valid and in document
const isDropdownOpen = Boolean(dropdownAnchor) && document.body.contains(dropdownAnchor);
const hasQuery = searchQuery.trim().length > 0;
const maxFiltersReached = activeFilters.length >= 5;
// Get dropdown items for keyboard navigation
const getDropdownItems = useCallback(() => {
if (!selectedCategory && !hasQuery) {
// Categories list
return FILTER_CATEGORIES
.filter((cat) => {
const available = getAvailableValues(filterCounts, activeFilters, cat);
return available.length > 0;
})
.map((cat) => ({ type: 'category' as const, category: cat }));
} else if (selectedCategory && !hasQuery) {
// Category selected but no query - show all available values for this category
const available = getAvailableValues(filterCounts, activeFilters, selectedCategory);
return available.map(([value, count]) => ({
type: 'value' as const,
category: selectedCategory,
value,
count,
matchType: 'exact' as const,
}));
} else {
// Search results (with query)
return searchResults.map((r) => ({ type: 'value' as const, ...r }));
}
}, [selectedCategory, hasQuery, filterCounts, activeFilters, searchResults]);
const dropdownItems = getDropdownItems();
// Handle keyboard navigation
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (event.key === 'ArrowDown') {
event.preventDefault();
setHighlightedIndex((prev) => Math.min(prev + 1, dropdownItems.length - 1));
} else if (event.key === 'ArrowUp') {
event.preventDefault();
setHighlightedIndex((prev) => Math.max(prev - 1, -1));
} else if (event.key === 'Enter') {
event.preventDefault();
const item = dropdownItems[highlightedIndex] || dropdownItems[0];
if (item) {
if (item.type === 'category') {
handleCategorySelect(item.category);
setHighlightedIndex(-1);
} else {
handleValueSelect(item.category, item.value);
}
}
} else if (event.key === 'Escape') {
handleDropdownClose();
inputRef.current?.blur();
}
},
[dropdownItems, highlightedIndex, handleCategorySelect, handleValueSelect, handleDropdownClose, inputRef]
);
// Get active group for chip menu
const activeGroup = activeGroupIndex !== null ? activeFilters[activeGroupIndex] : null;
const availableValuesForActiveGroup = activeGroupIndex !== null
? getAvailableValuesForGroup(activeGroupIndex, activeFilters, orCounts, currentTotal)
: [];
return (
<Box
ref={filterBarRef}
sx={{
mb: 4,
position: 'sticky',
top: 0,
zIndex: 100,
py: 1,
transition: 'background-color 0.2s, border-color 0.2s, margin 0.2s, padding 0.2s',
// Only apply full-width styling when sticky
...(isSticky
? {
mx: { xs: -2, sm: -4, md: -8, lg: -12 },
px: { xs: 2, sm: 4, md: 8, lg: 12 },
bgcolor: '#f3f4f6',
borderBottom: '1px solid #e5e7eb',
}
: {
px: 2,
bgcolor: 'transparent',
borderBottom: '1px solid transparent',
}),
}}
>
{/* Filter chips row */}
<Box
sx={{
display: 'flex',
flexWrap: 'wrap',
gap: 1,
justifyContent: 'center',
alignItems: 'center',
position: { xs: 'static', md: 'relative' },
}}
>
{/* Progress counter - absolute left (desktop only) */}
{!isMobile && currentTotal > 0 && (
<Typography
sx={{
position: 'absolute',
left: 0,
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.75rem',
color: '#9ca3af',
whiteSpace: 'nowrap',
}}
>
{scrollPercent}% · {currentTotal}
</Typography>
)}
{/* Toolbar actions - absolute right (desktop only) */}
{!isMobile && (
<Box sx={{ position: 'absolute', right: 0 }}>
<ToolbarActions
imageSize={imageSize}
onImageSizeChange={onImageSizeChange}
onTrackEvent={onTrackEvent}
/>
</Box>
)}
{/* Active filter chips */}
{activeFilters.map((group, index) => {
const isAnimating = randomAnimation?.index === index;
const animationClass = isAnimating ? `chip-blur-${randomAnimation.phase}` : undefined;
// Show old label during 'out' phase, new label during 'in' phase
const displayLabel = isAnimating && randomAnimation.phase === 'out' && randomAnimation.oldLabel
? randomAnimation.oldLabel
: `${group.category}:${group.values.join(',')}`;
return (
<Chip
key={`${group.category}-${index}`}
label={displayLabel}
onClick={(e) => handleChipClick(e, index)}
onDelete={() => onRemoveGroup(index)}
deleteIcon={<CloseIcon sx={{ fontSize: '1rem !important' }} />}
sx={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.85rem',
height: 32,
bgcolor: '#f3f4f6',
border: '1px solid #3776AB',
color: '#374151',
cursor: 'pointer',
'&:hover': { bgcolor: '#e5e7eb' },
'& .MuiChip-deleteIcon': {
color: '#9ca3af',
'&:hover': { color: '#3776AB' },
},
...(animationClass === 'chip-blur-out' && {
animation: 'chip-roll-out 0.5s ease-in forwards',
}),
...(animationClass === 'chip-blur-in' && {
animation: 'chip-roll-in 0.5s ease-out forwards',
}),
'@keyframes chip-roll-out': {
'0%': { transform: 'perspective(200px) rotateX(0deg)' },
'100%': { transform: 'perspective(200px) rotateX(180deg)' },
},
'@keyframes chip-roll-in': {
'0%': { transform: 'perspective(200px) rotateX(180deg)' },
'100%': { transform: 'perspective(200px) rotateX(360deg)' },
},
}}
/>
);
})}
{/* Search input - collapsed icon or expanded input */}
{!maxFiltersReached && (
<Box
ref={searchContainerRef}
role={isSearchExpanded ? undefined : 'button'}
tabIndex={isSearchExpanded ? undefined : 0}
aria-label={isSearchExpanded ? undefined : 'Open filter search'}
onClick={handleSearchExpand}
onKeyDown={(e) => {
if (!isSearchExpanded && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
handleSearchExpand();
}
}}
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 0.5,
px: isSearchExpanded ? 1.5 : 0,
height: 32,
width: isSearchExpanded ? { xs: 80, sm: 160, md: 'auto' } : 32,
minWidth: isSearchExpanded ? { xs: 80, sm: 160, md: 120 } : 32,
border: isSearchExpanded ? '1px dashed #9ca3af' : 'none',
borderRadius: '16px',
bgcolor: isDropdownOpen ? '#f9fafb' : 'transparent',
cursor: 'pointer',
transition: 'all 0.2s ease',
'&:hover': {
borderColor: isSearchExpanded ? '#3776AB' : undefined,
bgcolor: isSearchExpanded ? '#f9fafb' : undefined,
},
'&:hover .search-icon': {
color: '#3776AB',
},
'&:focus': isSearchExpanded ? {} : { outline: '2px solid #3776AB', outlineOffset: 2 },
}}
>
<Tooltip title={isSearchExpanded ? '' : 'search'}>
<SearchIcon
className="search-icon"
sx={{
color: '#9ca3af',
fontSize: isSearchExpanded ? '1rem' : '1.25rem',
transition: 'all 0.2s ease',
flexShrink: 0,
}}
/>
</Tooltip>
<InputBase
inputRef={inputRef}
id="filter-search"
name="filter-search"
aria-label={selectedCategory ? `Search ${FILTER_LABELS[selectedCategory]}` : 'Search filters'}
placeholder={selectedCategory ? FILTER_LABELS[selectedCategory] : ''}
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setHighlightedIndex(-1);
if (!dropdownAnchor) {
setDropdownAnchor(searchContainerRef.current);
}
}}
onFocus={() => {
if (!isSearchManuallyExpanded && activeFilters.length > 0) {
setIsSearchManuallyExpanded(true);
}
setDropdownAnchor(searchContainerRef.current);
setHighlightedIndex(-1);
}}
onBlur={handleSearchBlur}
onKeyDown={handleKeyDown}
sx={{
flex: isSearchExpanded ? 1 : 0,
width: isSearchExpanded ? 'auto' : 0,
opacity: isSearchExpanded ? 1 : 0,
transition: 'all 0.2s ease',
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.85rem',
'& input': {
padding: 0,
'&::placeholder': {
color: '#9ca3af',
opacity: 1,
},
},
}}
/>
{isSearchExpanded && (searchQuery || selectedCategory) && (
<CloseIcon
onClick={(e) => {
e.stopPropagation();
setSearchQuery('');
setSelectedCategory(null);
}}
sx={{
color: '#9ca3af',
fontSize: '0.9rem',
cursor: 'pointer',
'&:hover': { color: '#6b7280' },
}}
/>
)}
</Box>
)}
</Box>
{/* Counter and toggle row (mobile only) */}
{isMobile && (
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
mt: 1,
}}
>
{currentTotal > 0 ? (
<Typography
sx={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.75rem',
color: '#9ca3af',
whiteSpace: 'nowrap',
}}
>
{scrollPercent}% · {currentTotal}
</Typography>
) : (
<Box />
)}
<ToolbarActions
imageSize={imageSize}
onImageSizeChange={onImageSizeChange}
onTrackEvent={onTrackEvent}
/>
</Box>
)}
{/* Dropdown menu */}
<Menu
anchorEl={dropdownAnchor}
open={isDropdownOpen}
onClose={handleDropdownClose}
autoFocus={false}
disableAutoFocus
disableRestoreFocus
disableEnforceFocus
PaperProps={{
sx: {
maxHeight: 350,
minWidth: 240,
mt: 0.5,
},
}}
slotProps={{
root: {
slotProps: {
backdrop: {
invisible: true,
},
},
},
}}
>
{!selectedCategory && !hasQuery
? // Show categories
FILTER_CATEGORIES.map((category) => {
const availableVals = getAvailableValues(filterCounts, activeFilters, category);
if (availableVals.length === 0) return null;
// Calculate actual index among visible items
const visibleIdx = dropdownItems.findIndex((item) => item.type === 'category' && item.category === category);
return (
<Tooltip
key={category}
title={FILTER_TOOLTIPS[category]}
placement="right"
arrow
>
<MenuItem
onClick={() => handleCategorySelect(category)}
selected={visibleIdx === highlightedIndex}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace' }}
>
<ListItemText
primary={FILTER_LABELS[category]}
secondary={`${availableVals.length} options`}
primaryTypographyProps={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.9rem',
}}
secondaryTypographyProps={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.75rem',
color: '#9ca3af',
}}
/>
</MenuItem>
</Tooltip>
);
})
: // Show search results or category values
[
...(selectedCategory
? [
<MenuItem
key="back"
onClick={() => {
setSelectedCategory(null);
setSearchQuery('');
}}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace', color: '#6b7280' }}
>
← {FILTER_LABELS[selectedCategory]}
</MenuItem>,
<Divider key="divider" />,
]
: []),
...((() => {
// Use searchResults if query exists, otherwise show all available values for selected category
const resultsToShow: SearchResult[] = hasQuery
? searchResults
: selectedCategory
? getAvailableValues(filterCounts, activeFilters, selectedCategory).map(([value, count]) => ({
category: selectedCategory,
value,
count,
matchType: 'exact' as const,
}))
: [];
if (resultsToShow.length > 0) {
// Split results into exact and fuzzy matches
const exactResults = resultsToShow.filter((r) => r.matchType === 'exact');
const fuzzyResults = resultsToShow.filter((r) => r.matchType === 'fuzzy');
const renderMenuItem = (result: SearchResult, idx: number) => {
const { category, value, count } = result;
const specTitle = category === 'spec' ? specTitles[value] : undefined;
const menuItem = (
<MenuItem
key={`${category}-${value}`}
onClick={() => handleValueSelect(category, value)}
selected={idx === highlightedIndex}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace' }}
>
<ListItemText
primary={value}
secondary={!selectedCategory ? FILTER_LABELS[category] : undefined}
primaryTypographyProps={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.85rem',
}}
secondaryTypographyProps={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.7rem',
color: '#9ca3af',
}}
/>
<Typography
sx={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.75rem',
color: '#9ca3af',
ml: 2,
}}
>
({count})
</Typography>
</MenuItem>
);
return specTitle ? (
<Tooltip key={`${category}-${value}`} title={specTitle} placement="right" arrow>
<span>{menuItem}</span>
</Tooltip>
) : (
menuItem
);
};
const items: React.ReactNode[] = [];
// Add exact matches
exactResults.forEach((result, i) => {
items.push(renderMenuItem(result, i));
});
// Add fuzzy label/divider if there are fuzzy results
if (fuzzyResults.length > 0) {
items.push(
<Divider key="exact-fuzzy-divider" sx={{ my: 0.5 }}>
<Typography
sx={{
fontSize: '0.65rem',
color: '#9ca3af',
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
px: 1,
}}
>
fuzzy
</Typography>
</Divider>
);
}
// Add fuzzy matches
fuzzyResults.forEach((result, i) => {
items.push(renderMenuItem(result, exactResults.length + i));
});
return items;
} else {
return [
<MenuItem key="no-results" disabled>
<Typography
sx={{
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
fontSize: '0.85rem',
color: '#9ca3af',
}}
>
no matches
</Typography>
</MenuItem>,
];
}
})()),
]}
</Menu>
{/* Chip action menu */}
<Menu
anchorEl={chipMenuAnchor}
open={Boolean(chipMenuAnchor)}
onClose={() => {
setChipMenuAnchor(null);
setActiveGroupIndex(null);
}}
PaperProps={{
sx: {
minWidth: 180,
maxHeight: 350,
},
}}
>
{activeGroup && [
// Add value (OR) - submenu with available values
...(availableValuesForActiveGroup.length > 0
? [
<Typography
key="add-or-header"
sx={{
px: 2,
py: 0.5,
fontSize: '0.7rem',
color: '#9ca3af',
fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace',
textTransform: 'uppercase',
}}
>
add (or)
</Typography>,
...availableValuesForActiveGroup.map(([value, count]) => (
<MenuItem
key={`add-${value}`}
onClick={() => handleAddValueToExistingGroup(value)}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace', py: 0.5 }}
>
<AddIcon fontSize="small" sx={{ mr: 1, color: '#22c55e', fontSize: '1rem' }} />
<Typography sx={{ fontSize: '0.85rem', flex: 1 }}>{value}</Typography>
<Typography sx={{ fontSize: '0.75rem', color: '#9ca3af' }}>({count})</Typography>
</MenuItem>
)),
<Divider key="divider-add" />,
]
: []),
// Remove individual values
...activeGroup.values.map((value) => (
<MenuItem
key={`remove-${value}`}
onClick={() => handleRemoveValue(value)}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace' }}
>
<CloseIcon fontSize="small" sx={{ mr: 1, color: '#ef4444' }} />
{value}
</MenuItem>
)),
// Remove all (only if more than 1 value)
...(activeGroup.values.length > 1
? [
<Divider key="divider-remove" />,
<MenuItem
key="remove-all"
onClick={handleRemoveGroup}
sx={{ fontFamily: '"MonoLisa", "MonoLisa Fallback", monospace', color: '#ef4444' }}
>
<CloseIcon fontSize="small" sx={{ mr: 1 }} />
remove all
</MenuItem>,
]
: []),
]}
</Menu>
</Box>
);
}