-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathindex.js
More file actions
514 lines (462 loc) · 17.8 KB
/
index.js
File metadata and controls
514 lines (462 loc) · 17.8 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
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
IconSearch,
IconX,
IconFolder,
IconBox,
IconFileText,
IconBook
} from '@tabler/icons';
import { flattenItems, isItemARequest, isItemAFolder, findParentItemInCollection } from 'utils/collections';
import { addTab, focusTab } from 'providers/ReduxStore/slices/tabs';
import { toggleCollectionItem, toggleCollection } from 'providers/ReduxStore/slices/collections';
import { mountCollection } from 'providers/ReduxStore/slices/collections/actions';
import { getDefaultRequestPaneTab } from 'utils/collections';
import { normalizeQuery, isValidQuery, highlightText, sortResults, getTypeLabel, getItemPath } from './utils/searchUtils';
import { SEARCH_TYPES, MATCH_TYPES, SEARCH_CONFIG, DOCUMENTATION_RESULT } from './constants';
import StyledWrapper from './StyledWrapper';
const GlobalSearchModal = ({ isOpen, onClose }) => {
const [query, setQuery] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
const [results, setResults] = useState([]);
const inputRef = useRef(null);
const resultsRef = useRef(null);
const debounceTimeoutRef = useRef(null);
const dispatch = useDispatch();
const collections = useSelector((state) => state.collections.collections);
const tabs = useSelector((state) => state.tabs.tabs);
const createCollectionResults = () => {
const collectionResults = collections.map((collection) => ({
type: SEARCH_TYPES.COLLECTION,
item: collection,
name: collection.name,
path: collection.name,
matchType: MATCH_TYPES.COLLECTION,
collectionUid: collection.uid
}));
collectionResults.sort((a, b) => a.name.localeCompare(b.name));
return [DOCUMENTATION_RESULT, ...collectionResults];
};
const searchInCollections = (searchTerms, enablePathMatch) => {
const results = [];
// Check for documentation match
const queryLower = searchTerms.join(' ');
if (['documentation', 'docs', 'bruno docs'].some((term) => term.includes(queryLower))) {
results.push(DOCUMENTATION_RESULT);
}
collections.forEach((collection) => {
// Search collection name
if (searchTerms.every((term) => collection.name.toLowerCase().includes(term))) {
results.push({
type: SEARCH_TYPES.COLLECTION,
item: collection,
name: collection.name,
path: collection.name,
matchType: MATCH_TYPES.COLLECTION,
collectionUid: collection.uid
});
}
// Search collection items
const flattenedItems = flattenItems(collection.items);
flattenedItems.forEach((item) => {
const itemPath = getItemPath(item, collection, findParentItemInCollection);
const itemPathLower = itemPath.toLowerCase();
if (isItemARequest(item)) {
// add an optional check for the item name to prevent a crash if it doesn’t exist.
const nameMatch = searchTerms.every((term) => (item.name || '').toLowerCase().includes(term));
const urlMatch = searchTerms.every((term) => (item.request?.url || '').toLowerCase().includes(term));
const pathMatch = enablePathMatch && searchTerms.every((term) => itemPathLower.includes(term));
if (nameMatch || urlMatch || pathMatch) {
// Check if this is a gRPC request and get the method type
const isGrpcRequest = item.request?.type === 'grpc';
let method = item.request?.method || '';
if (isGrpcRequest) {
// For gRPC requests, use the methodType
const methodType = item.request?.methodType || 'UNARY';
method = methodType.toLowerCase().replace(/[_]/g, '-');
}
results.push({
type: SEARCH_TYPES.REQUEST,
item,
name: item.name,
path: itemPath,
matchType: nameMatch ? MATCH_TYPES.REQUEST : urlMatch ? MATCH_TYPES.URL : MATCH_TYPES.PATH,
method,
collectionUid: collection.uid
});
}
} else if (isItemAFolder(item)) {
const nameMatch = searchTerms.every((term) => item.name.toLowerCase().includes(term));
const pathMatch = enablePathMatch && searchTerms.every((term) => itemPathLower.includes(term));
if (nameMatch || pathMatch) {
results.push({
type: SEARCH_TYPES.FOLDER,
item,
name: item.name,
path: itemPath,
matchType: nameMatch ? MATCH_TYPES.FOLDER : MATCH_TYPES.PATH,
collectionUid: collection.uid
});
}
}
});
});
return results;
};
const performSearch = (searchQuery) => {
const normalizedQuery = normalizeQuery(searchQuery);
if (!normalizedQuery) {
setResults(createCollectionResults());
return;
}
if (!isValidQuery(normalizedQuery)) {
setResults([]);
return;
}
const searchTerms = normalizedQuery.toLowerCase().split(/[\s\/]+/).filter(Boolean);
if (!searchTerms.length) {
setResults([]);
return;
}
const enablePathMatch = normalizedQuery.includes('/');
const searchResults = searchInCollections(searchTerms, enablePathMatch);
const sortedResults = sortResults(searchResults);
setResults(sortedResults);
setSelectedIndex(0);
};
const debouncedSearch = useCallback((searchQuery) => {
// Clear existing timeout
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
// Set new timeout
debounceTimeoutRef.current = setTimeout(() => {
performSearch(searchQuery);
}, SEARCH_CONFIG.DEBOUNCE_DELAY);
}, [collections]); // Depend on collections to recreate when they change
const expandItemPath = (result) => {
const collection = collections.find((c) => c.uid === result.collectionUid);
if (!collection) return;
ensureCollectionIsMounted(collection);
if (collection.collapsed) {
dispatch(toggleCollection(collection.uid));
}
let currentItem = result.type === SEARCH_TYPES.FOLDER
? result.item
: findParentItemInCollection(collection, result.item.uid);
while (currentItem?.type === 'folder') {
if (currentItem.collapsed) {
dispatch(toggleCollectionItem({ collectionUid: collection.uid, itemUid: currentItem.uid }));
}
currentItem = findParentItemInCollection(collection, currentItem.uid);
}
};
const ensureCollectionIsMounted = (collection) => {
if (!collection || collection.mountStatus === 'mounted') return;
dispatch(mountCollection({
collectionUid: collection.uid,
collectionPathname: collection.pathname,
brunoConfig: collection.brunoConfig
}));
};
const handleKeyNavigation = (e) => {
const handlers = {
ArrowDown: () => {
e.preventDefault();
setSelectedIndex((prev) => prev < results.length - 1 ? prev + 1 : 0);
},
ArrowUp: () => {
e.preventDefault();
setSelectedIndex((prev) => prev > 0 ? prev - 1 : results.length - 1);
},
Enter: () => {
e.preventDefault();
if (results[selectedIndex]) {
handleResultSelection(results[selectedIndex]);
}
},
Escape: () => {
e.preventDefault();
onClose();
},
PageDown: () => {
e.preventDefault();
setSelectedIndex((prev) => Math.min(prev + 5, results.length - 1));
},
PageUp: () => {
e.preventDefault();
setSelectedIndex((prev) => Math.max(prev - 5, 0));
},
Home: () => {
e.preventDefault();
setSelectedIndex(0);
},
End: () => {
e.preventDefault();
setSelectedIndex(results.length - 1);
}
};
const handler = handlers[e.key];
if (handler) handler();
};
const handleResultSelection = (result) => {
const targetCollection = collections.find((c) => c.uid === result.collectionUid);
ensureCollectionIsMounted(targetCollection);
if (result.type === SEARCH_TYPES.DOCUMENTATION) {
window.open('https://docs.usebruno.com/', '_blank');
onClose();
return;
}
expandItemPath(result);
if (result.type === SEARCH_TYPES.REQUEST) {
const existingTab = tabs.find((tab) => tab.uid === result.item.uid);
if (existingTab) {
dispatch(focusTab({ uid: result.item.uid }));
} else {
dispatch(addTab({
uid: result.item.uid,
collectionUid: result.collectionUid,
requestPaneTab: getDefaultRequestPaneTab(result.item),
type: result.item.type,
pathname: result.item.pathname
}));
}
} else if (result.type === SEARCH_TYPES.FOLDER) {
dispatch(addTab({
uid: result.item.uid,
collectionUid: result.collectionUid,
type: 'folder-settings',
pathname: result.item.pathname
}));
} else if (result.type === SEARCH_TYPES.COLLECTION) {
dispatch(addTab({
uid: result.item.uid,
collectionUid: result.collectionUid,
type: 'collection-settings'
}));
}
onClose();
};
const handleQueryChange = (e) => {
const newQuery = e.target.value;
setQuery(newQuery);
if (newQuery.trim()) {
debouncedSearch(newQuery);
} else {
// For empty queries, search immediately to show collections
performSearch(newQuery);
}
};
const clearSearch = () => {
// Clear any pending debounced search
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
setQuery('');
setResults([]);
};
// Initialize modal when opened
useEffect(() => {
if (isOpen) {
const timeoutId = setTimeout(() => inputRef.current?.focus(), SEARCH_CONFIG.FOCUS_DELAY);
setQuery('');
performSearch('');
setSelectedIndex(0);
return () => clearTimeout(timeoutId);
} else {
// Clear any pending debounced search when modal closes
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
}
}, [isOpen]);
// Auto-scroll selected item into view
useEffect(() => {
if (resultsRef.current && results.length > 0) {
const selectedElement = resultsRef.current.children[selectedIndex];
selectedElement?.scrollIntoView({
behavior: SEARCH_CONFIG.SCROLL_BEHAVIOR,
block: SEARCH_CONFIG.SCROLL_BLOCK
});
}
}, [selectedIndex, results]);
// Cleanup debounce timeout on unmount or modal close
useEffect(() => {
return () => {
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
}
};
}, []);
const getResultIcon = (type) => {
const iconMap = {
[SEARCH_TYPES.DOCUMENTATION]: IconBook,
[SEARCH_TYPES.COLLECTION]: IconBox,
[SEARCH_TYPES.FOLDER]: IconFolder,
[SEARCH_TYPES.REQUEST]: IconFileText
};
const IconComponent = iconMap[type] || IconFileText;
return <IconComponent size={18} stroke={1.5} />;
};
if (!isOpen) return null;
return (
<StyledWrapper>
<div
className="command-k-overlay"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-labelledby="search-modal-title"
aria-describedby="search-modal-description"
>
<div className="command-k-modal" onClick={(e) => e.stopPropagation()}>
<h1 id="search-modal-title" className="sr-only">Global Search</h1>
<p id="search-modal-description" className="sr-only">
Search through collections, requests, folders, and documentation. Use arrow keys to navigate results and Enter to select.
</p>
<div aria-live="polite" aria-atomic="true" className="sr-only">
{results.length > 0 && query
? `${results.length} result${results.length === 1 ? '' : 's'} found`
: query && results.length === 0
? 'No results found'
: ''}
</div>
<div className="command-k-header">
<div className="search-input-container">
<IconSearch size={20} className="search-icon" aria-hidden="true" />
<input
ref={inputRef}
type="text"
placeholder="Search collections, requests, or documentation..."
value={query}
onChange={handleQueryChange}
onKeyDown={handleKeyNavigation}
className="search-input"
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
aria-label="Search collections, requests, or documentation"
aria-expanded={results.length > 0}
aria-controls="search-results"
aria-activedescendant={results.length > 0 ? `search-result-${selectedIndex}` : undefined}
role="combobox"
aria-autocomplete="list"
/>
{query && (
<button
onClick={clearSearch}
className="clear-button"
aria-label="Clear search query"
type="button"
>
<IconX size={16} aria-hidden="true" />
</button>
)}
</div>
</div>
<div
className="command-k-results"
ref={resultsRef}
id="search-results"
role="listbox"
aria-label="Search results"
>
{results.length === 0 && query ? (
<div className="no-results">
<p>
No results found for "{query}".
<br />
<span className="block mt-2">
The item might not exist yet, or its collection isn’t mounted. Press <strong>Enter</strong> here (or open it from the sidebar) to mount the collection automatically.
</span>
</p>
</div>
) : results.length === 0 ? (
<div className="empty-state">
<p>
No collections are currently mounted or visible.
<br />
<span className="block mt-2">
Mount a collection via the sidebar or this search modal, then try again.
</span>
</p>
</div>
) : (
results.map((result, index) => {
const isSelected = index === selectedIndex;
const typeLabel = getTypeLabel(result.type);
return (
<div
key={`${result.type}-${result.item.id || result.item.uid}-${index}`}
id={`search-result-${index}`}
className={`result-item ${isSelected ? 'selected' : ''}`}
onClick={() => handleResultSelection(result)}
data-selected={isSelected}
data-type={result.type}
role="option"
aria-selected={isSelected}
aria-label={`${result.name}, ${typeLabel || result.type}${result.method ? `, ${result.method}` : ''}`}
tabIndex={-1}
>
<div className="result-icon">
{getResultIcon(result.type)}
</div>
<div className="result-content">
<div className="result-info">
<div className="result-name">
{highlightText(result.name, query)}
</div>
<div className="result-path">
{result.type === SEARCH_TYPES.DOCUMENTATION
? result.description
: result.type === SEARCH_TYPES.REQUEST
? highlightText(result.item.request?.url || '', query)
: highlightText(result.path, query)}
</div>
</div>
<div className="result-badges">
{result.type === SEARCH_TYPES.REQUEST && result.method && (
<span
className={`method-badge ${result.method.toLowerCase()}`}
aria-label={`HTTP method ${result.method.toUpperCase().replace(/-/g, ' ')}`}
>
{result.method.toUpperCase().replace(/-/g, ' ')}
</span>
)}
{typeLabel && (
<div className="result-type" aria-label={`Item type ${typeLabel}`}>
{typeLabel}
</div>
)}
</div>
</div>
</div>
);
})
)}
</div>
<div className="command-k-footer">
<div className="keyboard-hints" role="region" aria-label="Keyboard shortcuts">
<span aria-label="Use up and down arrows to navigate">
<span className="keycap" aria-hidden="true">↑</span>
<span className="keycap" aria-hidden="true">↓</span>
<span className="hint-label">to navigate</span>
</span>
<span aria-label="Press Enter to select">
<span className="keycap" aria-hidden="true">↵</span>
<span className="hint-label">to select</span>
</span>
<span aria-label="Press Escape to close">
<span className="keycap" aria-hidden="true">esc</span>
<span className="hint-label">to close</span>
</span>
</div>
</div>
</div>
</div>
</StyledWrapper>
);
};
export default GlobalSearchModal;