-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathfileSearchCommandDialog.tsx
More file actions
269 lines (248 loc) · 10 KB
/
fileSearchCommandDialog.tsx
File metadata and controls
269 lines (248 loc) · 10 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
'use client';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { useState, useRef, useMemo, useEffect, useCallback } from "react";
import { useHotkeys } from "react-hotkeys-hook";
import { useQuery } from "@tanstack/react-query";
import { unwrapServiceError } from "@/lib/utils";
import { FileTreeItem, getFiles } from "@/features/fileTree/actions";
import { useDomain } from "@/hooks/useDomain";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { useBrowseNavigation } from "../hooks/useBrowseNavigation";
import { useBrowseState } from "../hooks/useBrowseState";
import { useBrowseParams } from "../hooks/useBrowseParams";
import { FileTreeItemIcon } from "@/features/fileTree/components/fileTreeItemIcon";
import { useLocalStorage } from "usehooks-ts";
import { Skeleton } from "@/components/ui/skeleton";
const MAX_RESULTS = 100;
type SearchResult = {
file: FileTreeItem;
match?: {
from: number;
to: number;
};
}
export const FileSearchCommandDialog = () => {
const { repoName, revisionName } = useBrowseParams();
const domain = useDomain();
const { state: { isFileSearchOpen }, updateBrowseState } = useBrowseState();
const commandListRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [searchQuery, setSearchQuery] = useState('');
const { navigateToPath } = useBrowseNavigation();
const [recentlyOpened, setRecentlyOpened] = useLocalStorage<FileTreeItem[]>(`recentlyOpenedFiles-${repoName}`, []);
useHotkeys("mod+p", (event) => {
event.preventDefault();
updateBrowseState({
isFileSearchOpen: !isFileSearchOpen,
});
}, {
enableOnFormTags: true,
enableOnContentEditable: true,
description: "Open File Search",
});
// Whenever we open the dialog, clear the search query
useEffect(() => {
if (isFileSearchOpen) {
setSearchQuery('');
}
}, [isFileSearchOpen]);
const { data: files, isLoading, isError } = useQuery({
queryKey: ['files', repoName, revisionName, domain],
queryFn: () => unwrapServiceError(getFiles({ repoName, revisionName: revisionName ?? 'HEAD' }, domain)),
enabled: isFileSearchOpen,
});
const { filteredFiles, maxResultsHit } = useMemo((): { filteredFiles: SearchResult[]; maxResultsHit: boolean } => {
if (!files || isLoading) {
return {
filteredFiles: [],
maxResultsHit: false,
};
}
const matches = files
.map((file) => {
return {
file,
matchIndex: file.path.toLowerCase().indexOf(searchQuery.toLowerCase()),
}
})
.filter(({ matchIndex }) => {
return matchIndex !== -1;
});
return {
filteredFiles: matches
.slice(0, MAX_RESULTS)
.map(({ file, matchIndex }) => {
return {
file,
match: {
from: matchIndex,
to: matchIndex + searchQuery.length - 1,
},
}
}),
maxResultsHit: matches.length > MAX_RESULTS,
}
}, [searchQuery, files, isLoading]);
// Scroll to the top of the list whenever the search query changes
useEffect(() => {
commandListRef.current?.scrollTo({
top: 0,
})
}, [searchQuery]);
const onSelect = useCallback((file: FileTreeItem) => {
setRecentlyOpened((prev) => {
const filtered = prev.filter(f => f.path !== file.path);
return [file, ...filtered];
});
navigateToPath({
repoName,
revisionName,
path: file.path,
pathType: 'blob',
});
updateBrowseState({
isFileSearchOpen: false,
});
}, [navigateToPath, repoName, revisionName, setRecentlyOpened, updateBrowseState]);
// @note: We were hitting issues when the user types into the input field while the files are still
// loading. The workaround was to set `disabled` when loading and then focus the input field when
// the files are loaded, hence the `useEffect` below.
useEffect(() => {
if (!isLoading) {
inputRef.current?.focus();
}
}, [isLoading]);
return (
<Dialog
open={isFileSearchOpen}
onOpenChange={(isOpen) => {
updateBrowseState({
isFileSearchOpen: isOpen,
});
}}
modal={true}
>
<DialogContent
className="overflow-hidden p-0 shadow-lg max-w-[90vw] sm:max-w-2xl top-[20%] translate-y-0"
>
<DialogTitle className="sr-only">Search for files</DialogTitle>
<DialogDescription className="sr-only">{`Search for files in the repository ${repoName}.`}</DialogDescription>
<Command
shouldFilter={false}
>
<CommandInput
placeholder={`Search for files in ${repoName}...`}
onValueChange={setSearchQuery}
disabled={isLoading}
ref={inputRef}
/>
{
isLoading ? (
<ResultsSkeleton />
) : isError ? (
<p>Error loading files.</p>
) : (
<CommandList ref={commandListRef}>
{searchQuery.length === 0 ? (
<CommandGroup
heading="Recently opened"
>
<CommandEmpty className="text-muted-foreground text-center text-sm py-6">No recently opened files.</CommandEmpty>
{recentlyOpened.map((file) => {
return (
<SearchResultComponent
key={file.path}
file={file}
onSelect={() => onSelect(file)}
/>
);
})}
</CommandGroup>
) : (
<>
<CommandEmpty className="text-muted-foreground text-center text-sm py-6">No results found.</CommandEmpty>
{filteredFiles.map(({ file, match }) => {
return (
<SearchResultComponent
key={file.path}
file={file}
match={match}
onSelect={() => onSelect(file)}
/>
);
})}
{maxResultsHit && (
<div className="text-muted-foreground text-center text-sm py-4">
Maximum results hit. Please refine your search.
</div>
)}
</>
)}
</CommandList>
)
}
</Command>
</DialogContent>
</Dialog>
)
}
interface SearchResultComponentProps {
file: FileTreeItem;
match?: {
from: number;
to: number;
};
onSelect: () => void;
}
const SearchResultComponent = ({
file,
match,
onSelect,
}: SearchResultComponentProps) => {
return (
<CommandItem
key={file.path}
onSelect={onSelect}
>
<div className="flex flex-row gap-2 w-full cursor-pointer relative">
<FileTreeItemIcon item={file} className="mt-1" />
<div className="flex flex-col w-full">
<span className="text-sm font-medium">
{file.name}
</span>
<span className="text-xs text-muted-foreground">
{match ? (
<Highlight text={file.path} range={match} />
) : (
file.path
)}
</span>
</div>
</div>
</CommandItem>
);
}
const Highlight = ({ text, range }: { text: string, range: { from: number; to: number } }) => {
return (
<span>
{text.slice(0, range.from)}
<span className="searchMatch-selected">{text.slice(range.from, range.to + 1)}</span>
{text.slice(range.to + 1)}
</span>
)
}
const ResultsSkeleton = () => {
return (
<div className="p-2">
{Array.from({ length: 6 }).map((_, index) => (
<div key={index} className="flex flex-row gap-2 p-2 mb-1">
<Skeleton className="w-4 h-4" />
<div className="flex flex-col w-full gap-1">
<Skeleton className="h-4 w-1/4" />
<Skeleton className="h-3 w-1/2" />
</div>
</div>
))}
</div>
);
};