forked from guacsec/trustify-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSearchMenu.tsx
More file actions
342 lines (305 loc) · 9.6 KB
/
SearchMenu.tsx
File metadata and controls
342 lines (305 loc) · 9.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
import React from "react";
import { Link } from "react-router-dom";
import {
Label,
Menu,
MenuContent,
MenuItem,
MenuList,
Popper,
SearchInput,
Spinner,
} from "@patternfly/react-core";
import { useDebounceValue } from "usehooks-ts";
import { FILTER_TEXT_CATEGORY_KEY } from "@app/Constants";
import type { HubRequestParams } from "@app/api/models";
import { SbomSearchContext } from "@app/pages/sbom-list/sbom-context";
import { useFetchAdvisories } from "@app/queries/advisories";
import { useFetchPackages } from "@app/queries/packages";
import { useFetchSBOMs } from "@app/queries/sboms";
import { useFetchVulnerabilities } from "@app/queries/vulnerabilities";
export interface IEntity {
id: string;
title: string | null;
description?: string | null;
navLink: string;
type: string;
typeColor:
| "blue"
| "teal"
| "green"
| "orange"
| "purple"
| "red"
| "orangered"
| "grey"
| "yellow"
| undefined;
}
const entityToMenu = (option: IEntity) => {
return (
<Link
key={option.id}
to={option.navLink}
style={{ textDecoration: "none" }}
>
<MenuItem itemId={option.id} description={option.description}>
{option.title} <Label color={option.typeColor}>{option.type}</Label>
</MenuItem>
</Link>
);
};
function useAllEntities(filterText: string, disableSearch: boolean) {
const params: HubRequestParams = {
filters: [
{ field: FILTER_TEXT_CATEGORY_KEY, operator: "~", value: filterText },
],
page: { pageNumber: 1, itemsPerPage: 5 },
};
const {
isFetching: isFetchingAdvisories,
result: { data: advisories },
} = useFetchAdvisories({ ...params }, disableSearch);
const {
isFetching: isFetchingPackages,
result: { data: packages },
} = useFetchPackages({ ...params }, disableSearch);
const {
isFetching: isFetchingSBOMs,
result: { data: sboms },
} = useFetchSBOMs({ ...params }, disableSearch);
const {
isFetching: isFetchingVulnerabilities,
result: { data: vulnerabilities },
} = useFetchVulnerabilities({ ...params }, disableSearch);
const transformedAdvisories: IEntity[] = advisories.map((item) => ({
id: `advisory-${item.uuid}`,
title: item.document_id,
description: item.title?.substring(0, 75),
navLink: `/advisories/${item.uuid}`,
type: "Advisory",
typeColor: "blue",
}));
const transformedPackages: IEntity[] = packages.map((item) => ({
id: `package-${item.uuid}`,
title: item.purl,
navLink: `/packages/${item.uuid}`,
type: "Package",
typeColor: "teal",
}));
const transformedSboms: IEntity[] = sboms.map((item) => ({
id: `sbom-${item.id}`,
title: item.name,
description: item.suppliers.join(", "),
navLink: `/sboms/${item.id}`,
type: "SBOM",
typeColor: "purple",
}));
const transformedVulnerabilities: IEntity[] = vulnerabilities.map((item) => ({
id: `vulnerability-${item.identifier}`,
title: item.identifier,
description: item.description?.substring(0, 75),
navLink: `/vulnerabilities/${item.identifier}`,
type: "Vulnerability",
typeColor: "orange",
}));
const filterTextLowerCase = filterText.toLowerCase();
const list = [
...transformedVulnerabilities,
...transformedSboms,
...transformedAdvisories,
...transformedPackages,
].sort((a, b) => {
if (a.title?.includes(filterTextLowerCase)) {
return -1;
}
if (b.title?.includes(filterTextLowerCase)) {
return 1;
}
const aIndex = (a.description || "")
.toLowerCase()
.indexOf(filterTextLowerCase);
const bIndex = (b.description || "")
.toLowerCase()
.indexOf(filterTextLowerCase);
return aIndex - bIndex;
});
return {
isFetching:
isFetchingAdvisories ||
isFetchingPackages ||
isFetchingSBOMs ||
isFetchingVulnerabilities,
list,
};
}
export interface ISearchMenu {
filterFunction?: (
list: IEntity[],
searchString: string,
) => React.JSX.Element[];
onChangeSearch: (searchValue: string | undefined) => void;
}
export const SearchMenu: React.FC<ISearchMenu> = ({ onChangeSearch }) => {
// Search value initial value
const { tableControls: sbomTableControls } =
React.useContext(SbomSearchContext);
// Search value
const [searchValue, setSearchValue] = React.useState("");
const [isSearchValueDirty, setIsSearchValueDirty] = React.useState(false);
React.useEffect(() => {
const searchValueFromTableControls =
sbomTableControls.filterState.filterValues[FILTER_TEXT_CATEGORY_KEY]?.[0];
setSearchValue(searchValueFromTableControls ?? "");
}, [sbomTableControls.filterState]);
// Debounce Search value
const [debouncedSearchValue, setDebouncedSearchValue] = useDebounceValue(
searchValue,
500,
);
React.useEffect(() => {
setDebouncedSearchValue(searchValue);
}, [setDebouncedSearchValue, searchValue]);
// Fetch all entities
const { isFetching, list: entityList } = useAllEntities(
debouncedSearchValue,
!isSearchValueDirty,
);
const [isAutocompleteOpen, setIsAutocompleteOpen] =
React.useState<boolean>(false);
const searchInputRef: React.RefObject<HTMLInputElement> = React.useRef(null);
const autocompleteRef: React.RefObject<HTMLInputElement> = React.useRef(null);
const onChangeSearchValue = (newValue: string) => {
if (
newValue !== "" &&
searchInputRef &&
searchInputRef.current &&
searchInputRef.current.contains(document.activeElement)
) {
setIsAutocompleteOpen(true);
} else {
setIsAutocompleteOpen(false);
}
setSearchValue(newValue);
setIsSearchValueDirty(true);
};
const onClearSearchValue = () => {
setSearchValue("");
};
const onSubmitInput = () => {
onChangeSearch(searchValue);
};
React.useEffect(() => {
const handleMenuKeys = (event: KeyboardEvent) => {
if (
isAutocompleteOpen &&
searchInputRef.current &&
searchInputRef.current === event.target
) {
// the escape key closes the autocomplete menu and keeps the focus on the search input.
if (event.key === "Escape") {
setIsAutocompleteOpen(false);
searchInputRef.current.focus();
// the up and down arrow keys move browser focus into the autocomplete menu
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
const firstElement = autocompleteRef.current?.querySelector(
"li > button:not(:disabled)",
);
firstElement && (firstElement as HTMLElement)?.focus();
event.preventDefault(); // by default, the up and down arrow keys scroll the window
// the tab, enter, and space keys will close the menu, and the tab key will move browser
// focus forward one element (by default)
} else if (
event.key === "Tab" ||
event.key === "Enter" ||
event.key === "Space"
) {
setIsAutocompleteOpen(false);
if (event.key === "Enter" || event.key === "Space") {
event.preventDefault();
}
}
// If the autocomplete is open and the browser focus is in the autocomplete menu
// hitting tab will close the autocomplete and but browser focus back on the search input.
} else if (
isAutocompleteOpen &&
autocompleteRef.current?.contains(event.target as Node) &&
event.key === "Tab"
) {
event.preventDefault();
setIsAutocompleteOpen(false);
searchInputRef.current?.focus();
}
};
// The autocomplete menu should close if the user clicks outside the menu.
const handleClickOutside = (event: { target: EventTarget | null }) => {
if (
isAutocompleteOpen &&
autocompleteRef &&
autocompleteRef.current &&
!autocompleteRef.current.contains(event.target as Node)
) {
setIsAutocompleteOpen(false);
}
};
window.addEventListener("keydown", handleMenuKeys);
window.addEventListener("click", handleClickOutside);
return () => {
window.removeEventListener("keydown", handleMenuKeys);
window.removeEventListener("click", handleClickOutside);
};
}, [isAutocompleteOpen]);
const autocomplete = (
<Menu
ref={autocompleteRef}
style={{
width: "450px",
maxHeight: "450px",
overflow: "scroll",
overflowX: "hidden",
overflowY: "auto",
}}
>
<MenuContent>
<MenuList>
{isFetching ? (
<MenuItem itemId="loading">
<Spinner size="sm" />
</MenuItem>
) : (
entityList.map(entityToMenu)
)}
</MenuList>
</MenuContent>
</Menu>
);
const searchInput = (
<SearchInput
placeholder="Search for an SBOM, Package, Advisory, or Vulnerability"
value={searchValue}
onChange={(_event, value) => onChangeSearchValue(value)}
onClear={onClearSearchValue}
onSearch={onSubmitInput}
onKeyDown={(event: React.KeyboardEvent) => {
if (event.key && event.key !== "Enter") return;
}}
ref={searchInputRef}
id="autocomplete-search"
style={{ width: 500 }}
/>
);
return (
<Popper
trigger={searchInput}
triggerRef={searchInputRef}
popper={autocomplete}
popperRef={autocompleteRef}
isVisible={(isAutocompleteOpen && entityList.length > 0) || isFetching}
enableFlip={false}
// append the autocomplete menu to the search input in the DOM for the sake of the keyboard navigation experience
appendTo={() =>
document.querySelector("#autocomplete-search") as HTMLElement
}
/>
);
};