-
Notifications
You must be signed in to change notification settings - Fork 529
/
PlayersSearchBox.tsx
256 lines (236 loc) · 11 KB
/
PlayersSearchBox.tsx
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
import { throttle } from "throttle-debounce";
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { ChevronsUpDownIcon, FilterXIcon, XIcon, ChevronDownIcon } from 'lucide-react';
import { Input } from '@/components/ui/input';
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator, DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import InlineCode from '@/components/InlineCode';
import { PlayersTableFiltersType, PlayersTableSearchType } from "@shared/playerApiTypes";
import { useEventListener } from "usehooks-ts";
/**
* Helpers
*/
const availableSearchTypes = [
{
value: 'playerName',
label: 'Name',
placeholder: 'Enter a player name',
description: 'Search players by their last display name.'
},
{
value: 'playerNotes',
label: 'Notes',
placeholder: 'Enter part of the note to search for',
description: 'Search players by their profile notes contents.'
},
{
value: 'playerIds',
label: 'Identifiers',
placeholder: 'License, Discord, Steam, etc.',
description: 'Search players by their IDs separated by a comma.'
},
] as const;
const availableFilters = [
{ label: 'Is Admin', value: 'isAdmin' },
{ label: 'Is Online', value: 'isOnline' },
// { label: 'Is Banned', value: 'isBanned' },
// { label: 'Has Previous Ban', value: 'hasPreviousBan' },
{ label: 'Has Whitelisted ID', value: 'isWhitelisted' },
{ label: 'Has Profile Notes', value: 'hasNote' },
] as const;
//FIXME: this doesn't require exporting, but HMR doesn't work without it
// eslint-disable-next-line @typescript-eslint/no-explicit-any, react-refresh/only-export-components
export const throttleFunc = throttle(1250, (func: any) => {
func();
}, { noLeading: true });
/**
* Component
*/
export type PlayersSearchBoxReturnStateType = {
search: PlayersTableSearchType;
filters: PlayersTableFiltersType;
}
type PlayerSearchBoxProps = {
doSearch: (search: PlayersTableSearchType, filters: PlayersTableFiltersType) => void;
initialState: PlayersSearchBoxReturnStateType;
};
export function PlayerSearchBox({ doSearch, initialState }: PlayerSearchBoxProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [isSearchTypeDropdownOpen, setSearchTypeDropdownOpen] = useState(false);
const [isFilterDropdownOpen, setFilterDropdownOpen] = useState(false);
const [currSearchType, setCurrSearchType] = useState<string>(initialState.search?.type || 'playerName');
const [selectedFilters, setSelectedFilters] = useState<string[]>(initialState.filters);
const [hasSearchText, setHasSearchText] = useState(!!initialState.search?.value);
const updateSearch = () => {
if (!inputRef.current) return;
const searchValue = inputRef.current.value.trim();
if (searchValue.length) {
doSearch({ value: searchValue, type: currSearchType }, selectedFilters);
} else {
doSearch(null, selectedFilters);
}
}
//Call onSearch when params change
useEffect(() => {
updateSearch();
}, [currSearchType, selectedFilters]);
//Input handlers
const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
throttleFunc.cancel({ upcomingOnly: true });
updateSearch();
} else if (e.key === 'Escape') {
inputRef.current!.value = '';
throttleFunc(updateSearch);
setHasSearchText(false);
} else {
throttleFunc(updateSearch);
setHasSearchText(true);
}
};
const clearSearchBtn = () => {
inputRef.current!.value = '';
throttleFunc.cancel({ upcomingOnly: true });
updateSearch();
setHasSearchText(false);
};
const filterSelectChange = (filter: string, checked: boolean) => {
if (checked) {
setSelectedFilters((prev) => [...prev, filter]);
} else {
setSelectedFilters((prev) => prev.filter((f) => f !== filter));
}
}
//Search hotkey
useEventListener('keydown', (e: KeyboardEvent) => {
if (e.code === 'KeyF' && (e.ctrlKey || e.metaKey)) {
inputRef.current?.focus();
e.preventDefault();
}
});
//It's render time! 🎉
const selectedSearchType = availableSearchTypes.find((type) => type.value === currSearchType);
if (!selectedSearchType) throw new Error(`Invalid search type: ${currSearchType}`);
const filterBtnMessage = selectedFilters.length ? `${selectedFilters.length} Filters` : 'No filters';
return (
<div className="p-4 mb-2 md:mb-4 md:rounded-xl border border-border bg-card text-card-foreground shadow-sm">
<div className="flex flex-wrap-reverse gap-2">
<div className='relative min-w-44 grow'>
<Input
type="text"
autoFocus
autoCapitalize='off'
autoCorrect='off'
ref={inputRef}
placeholder={selectedSearchType.placeholder}
onKeyDown={handleInputKeyDown}
/>
{hasSearchText ? (
<button
className="absolute right-2 inset-y-0 text-zinc-500 dark:text-zinc-400 ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-lg"
onClick={clearSearchBtn}
>
<XIcon />
</button>
) : (
<div className="absolute right-2 inset-y-0 flex items-center text-zinc-500 dark:text-zinc-400 select-none pointer-events-none">
<InlineCode className="text-xs tracking-wide">ctrl+f</InlineCode>
</div>
)}
</div>
<div className="grow flex justify-between">
<div className='space-x-2 flex-nowrap'>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={isSearchTypeDropdownOpen}
onClick={() => setSearchTypeDropdownOpen(!isSearchTypeDropdownOpen)}
className="grow xs:w-36 justify-between border-input bg-black/5 dark:bg-black/30 hover:dark:bg-primary"
>
{selectedSearchType.label}
<ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-36'>
<DropdownMenuLabel>Search Type</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuRadioGroup value={currSearchType} onValueChange={setCurrSearchType}>
{availableSearchTypes.map((searchType) => (
<DropdownMenuRadioItem
key={searchType.value}
value={searchType.value}
className='cursor-pointer'
>
{searchType.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={isFilterDropdownOpen}
onClick={() => setFilterDropdownOpen(!isFilterDropdownOpen)}
className="grow xs:w-44 justify-between border-input bg-black/5 dark:bg-black/30 hover:dark:bg-primary"
>
{filterBtnMessage}
<ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-44'>
<DropdownMenuLabel>Search Filters</DropdownMenuLabel>
<DropdownMenuSeparator />
{availableFilters.map((filter) => (
<DropdownMenuCheckboxItem
key={filter.value}
checked={selectedFilters.includes(filter.value)}
className="cursor-pointer"
onCheckedChange={(checked) => {
filterSelectChange(filter.value, checked);
}}
>
{filter.label}
</DropdownMenuCheckboxItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
className="cursor-pointer"
onClick={() => setSelectedFilters([])}
>
<FilterXIcon className="mr-2 h-4 w-4" />
Clear Filters
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div>
<Button
variant="outline"
className="flex-grow"
>
More
<ChevronDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</div>
</div>
</div>
<div className="text-xs text-muted-foreground mt-1 px-1">
{selectedSearchType.description}
</div>
</div>
)
}