Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectContentSearchDialog.tsx

346 lines12.6 KB

1import { Spinner } from "~/components/ui/spinner";
2import { AuthFilesystemReadScope, type ProjectContentMatch } from "@t3tools/contracts";
3​
4import { T, useGT, useMessages } from "gt-react";
5import { useState, type ReactNode } from "react";
6​
7import { useActiveProjectTarget, type ActiveProjectTarget } from "~/hooks/useActiveProjectTarget";
8import { useRenderedAppearance, useTheme } from "~/hooks/useTheme";
9import { cn } from "~/lib/utils";
10import { useRightPanelStore } from "~/rightPanelStore";
11import { useProjectContentSearch } from "~/state/queries";
12import { readEnvironmentScope } from "~/state/session";
13​
14import { PierreEntryIcon } from "../chat/PierreEntryIcon";
15import { CommandPaletteContent } from "../CommandPaletteContent";
16import { ScrollArea } from "../ui/scroll-area";
17import { Toggle } from "../ui/toggle";
18import { HighlightedSearchLine } from "./HighlightedSearchLine";
19import { SharedTooltipTrigger } from "../ui/shared-tooltip";
20​
21interface ProjectContentSearchDialogProps {
22 readonly onOpenChange: (open: boolean) => void;
24​
25/** Syntax-highlighting all 500 result rows at once stalls the UI. */
26const VISIBLE_MATCH_WINDOW = 100;
27​
28interface MatchGroup {
29 readonly path: string;
30 readonly matches: ReadonlyArray<ProjectContentMatch & { readonly resultIndex: number }>;
32​
33function splitPath(path: string): { readonly name: string; readonly directory: string } {
34 const separator = path.lastIndexOf("/");
35 return separator === -1
36 ? { name: path, directory: "" }
37 : { name: path.slice(separator + 1), directory: path.slice(0, separator) };
39​
40function groupMatches(matches: ReadonlyArray<ProjectContentMatch>): MatchGroup[] {
41 const groups = new Map<string, Array<ProjectContentMatch & { readonly resultIndex: number }>>();
42 matches.forEach((match, resultIndex) => {
43 const group = groups.get(match.path);
44 const indexedMatch = { ...match, resultIndex };
45 if (group) {
46 group.push(indexedMatch);
47 } else {
48 groups.set(match.path, [indexedMatch]);
49 }
50 });
51 return [...groups].map(([path, groupedMatches]) => ({ path, matches: groupedMatches }));
53​
54function SearchOptionButton(props: {
55 readonly active: boolean;
56 readonly disabled: boolean;
57 readonly label: string;
58 readonly onClick: () => void;
59 readonly children: ReactNode;
60}) {
61 return (
62 <SharedTooltipTrigger
63 render={
64 <Toggle
65 aria-label={props.label}
66 disabled={props.disabled}
67 pressed={props.active}
68 size="segmented"
69 variant="segmented"
70 onClick={props.onClick}
71 />
72 }
73 label={props.label}
74 >
75 <span className="font-mono">{props.children}</span>
76 </SharedTooltipTrigger>
77 );
79​
80function EmptyContentSearchDialog() {
81 const gt = useGT();
82 return (
83 <CommandPaletteContent
84 aria-label={gt("Search project contents")}
85 escapeLabel={gt("Back")}
86 footerActionLabel={gt("Open file")}
87 inputProps={{ disabled: true, placeholder: gt("Search project contents…") }}
88 mode="none"
89 panelSize="fill"
90 testId="project-content-search"
91 value=""
92 >
93 <p className="m-auto px-6 text-center text-muted-foreground text-sm">
94 <T>Open a project to search its files.</T>
95 </p>
96 </CommandPaletteContent>
97 );
99​
100const scrollSelectedRowIntoView = (row: HTMLElement | null) => {
101 row?.scrollIntoView({ block: "nearest" });
102};
103​
104function OpenContentSearchDialog(props: {
105 readonly onOpenChange: (open: boolean) => void;
106 readonly target: ActiveProjectTarget;
107}) {
108 const { target } = props;
109 const gt = useGT();
110 const messages = useMessages();
111 const { resolvedTheme } = useTheme();
112 const renderedAppearance = useRenderedAppearance();
113 const [query, setQuery] = useState("");
114 const [caseSensitive, setCaseSensitive] = useState(false);
115 const [wholeWord, setWholeWord] = useState(false);
116 const [useRegex, setUseRegex] = useState(false);
117 const [selectedIndex, setSelectedIndex] = useState(0);
118​
119 const [visibleCount, setVisibleCount] = useState(VISIBLE_MATCH_WINDOW);
120​
121 const search = useProjectContentSearch(
122 {
123 environmentId: target.environmentId,
124 cwd: target.cwd,
125 query,
126 caseSensitive,
127 wholeWord,
128 useRegex,
129 },
130 messages,
131 );
132 const canOpenMatches = search.canReadFiles && !search.isPending && search.error === null;
133 const matches = search.matches;
134 const [resultsFor, setResultsFor] = useState(matches);
135 if (resultsFor !== matches) {
136 setResultsFor(matches);
137 setSelectedIndex(0);
138 setVisibleCount(VISIBLE_MATCH_WINDOW);
139 }
140 if (selectedIndex >= visibleCount) {
141 setVisibleCount(selectedIndex + VISIBLE_MATCH_WINDOW);
142 }
143 const visibleMatches = matches.slice(0, visibleCount);
144 const groups = groupMatches(visibleMatches);
145​
146 const observeLoadMoreSentinel = (sentinel: HTMLElement | null) => {
147 if (!sentinel) return;
148 const observer = new IntersectionObserver((entries) => {
149 if (entries.some((entry) => entry.isIntersecting)) {
150 setVisibleCount((current) => current + VISIBLE_MATCH_WINDOW);
151 }
152 });
153 observer.observe(sentinel);
154 return () => observer.disconnect();
155 };
156​
157 const openMatch = (match: ProjectContentMatch) => {
158 if (!canOpenMatches || !readEnvironmentScope(target.environmentId, AuthFilesystemReadScope)) {
159 return;
160 }
161 props.onOpenChange(false);
162 useRightPanelStore.getState().openFile(target.threadRef, match.path, match.lineNumber);
163 };
164 const fileCount = new Set(matches.map((match) => match.path)).size;
165 const showSearchStatus =
166 search.canReadFiles &&
167 (search.hasQuery || search.isPending || search.error !== null || search.invalidRegex);
168​
169 return (
170 <CommandPaletteContent
171 aria-label={gt("Search file contents in {project}", { project: target.projectName })}
172 escapeLabel={gt("Back")}
173 footerActionLabel={gt("Open file")}
174 inputAccessory={
175 <div className="absolute inset-e-2.5 top-1/2 flex shrink-0 -translate-y-1/2 items-center gap-0.5 rounded-lg border bg-muted/30 p-0.5">
176 <SearchOptionButton
177 active={caseSensitive}
178 disabled={!search.canReadFiles}
179 label={gt("Match case")}
180 onClick={() => setCaseSensitive((current) => !current)}
181 >
182 {/* oxlint-disable-next-line t3code/no-untranslated-copy -- match-case glyph; the label carries the meaning */}
183 {"Aa"}
184 </SearchOptionButton>
185 <SearchOptionButton
186 active={wholeWord}
187 disabled={!search.canReadFiles}
188 label={gt("Match whole word")}
189 onClick={() => setWholeWord((current) => !current)}
190 >
191 <span className="underline decoration-2 underline-offset-2">ab</span>
192 </SearchOptionButton>
193 <SearchOptionButton
194 active={useRegex}
195 disabled={!search.canReadFiles}
196 label={gt("Use regular expression")}
197 onClick={() => setUseRegex((current) => !current)}
198 >
199 .*
200 </SearchOptionButton>
201 </div>
202 }
203 inputProps={{
204 className: "pe-30",
205 disabled: !search.canReadFiles,
206 placeholder: gt("Search in {project}", { project: target.projectName }),
207 onKeyDown: (event) => {
208 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
209 if (event.key === "ArrowDown" && matches.length > 0) {
210 event.preventDefault();
211 setSelectedIndex((current) => (current + 1) % matches.length);
212 } else if (event.key === "ArrowUp" && matches.length > 0) {
213 event.preventDefault();
214 setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);
215 } else if (event.key === "Enter") {
216 if (!canOpenMatches) {
217 event.preventDefault();
218 return;
219 }
220 const match = matches[selectedIndex];
221 if (match) {
222 event.preventDefault();
223 openMatch(match);
224 }
225 }
226 },
227 }}
228 mode="none"
229 onValueChange={setQuery}
230 panelSize="fill"
231 testId="project-content-search"
232 value={query}
233 >
234 {showSearchStatus ? (
235 <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">
236 {search.isPending ? (
237 <span className="flex items-center gap-2">
238 <Spinner size="sm" /> <T>Searching…</T>
239 </span>
240 ) : search.error ? (
241 <span className="text-destructive">{search.error}</span>
242 ) : search.invalidRegex ? (
243 <span className="text-destructive">
244 <T>Invalid regular expression</T>
245 </span>
246 ) : search.truncated ? (
247 gt("{results}+ results in {files} files", {
248 results: matches.length.toLocaleString(),
249 files: fileCount.toLocaleString(),
250 })
251 ) : (
252 gt("{results} results in {files} files", {
253 results: matches.length.toLocaleString(),
254 files: fileCount.toLocaleString(),
255 })
256 )}
257 </div>
258 ) : null}
259​
260 {matches.length === 0 ? (
261 <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
262 {search.isCheckingAccess
263 ? gt("Checking file access…")
264 : !search.canReadFiles
265 ? search.error
266 : search.hasQuery && !search.isPending && !search.error
267 ? gt("No results found.")
268 : gt("Type to search across your project.")}
269 </div>
270 ) : (
271 <ScrollArea className="min-h-0 flex-1" scrollFade>
272 <div className="py-2">
273 {groups.map((group) => {
274 const path = splitPath(group.path);
275 return (
276 <section className="pb-2" key={group.path}>
277 <div className="sticky top-0 z-10 flex h-8 items-center gap-2 bg-popover/95 px-3 text-xs backdrop-blur-sm">
278 <PierreEntryIcon
279 pathValue={group.path}
280 kind="file"
281 theme={resolvedTheme}
282 className="size-3.5"
283 />
284 <span className="font-medium text-foreground">{path.name}</span>
285 {path.directory ? (
286 <span className="min-w-0 truncate text-muted-foreground">
287 {path.directory}
288 </span>
289 ) : null}
290 <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 tabular-nums text-3xs text-muted-foreground">
291 {group.matches.length}
292 </span>
293 </div>
294 {group.matches.map((match) => (
295 <button
296 type="button"
297 key={`${match.path}:${match.lineNumber}:${match.resultIndex}`}
298 ref={
299 match.resultIndex === selectedIndex ? scrollSelectedRowIntoView : undefined
300 }
301 className={cn(
302 "flex h-7 w-full min-w-0 items-center gap-3 px-3 text-left font-mono text-xs hover:bg-accent/60 disabled:pointer-events-none",
303 match.resultIndex === selectedIndex && "bg-accent text-accent-foreground",
304 )}
305 disabled={!canOpenMatches}
306 onMouseEnter={() => setSelectedIndex(match.resultIndex)}
307 onClick={() => openMatch(match)}
308 >
309 <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground/70">
310 {match.lineNumber}
311 </span>
312 <span className="min-w-0 flex-1 truncate whitespace-pre">
313 <HighlightedSearchLine
314 match={match}
315 path={group.path}
316 theme={renderedAppearance}
317 />
318 </span>
319 </button>
320 ))}
321 </section>
322 );
323 })}
324 {matches.length > visibleCount ? (
325 <div ref={observeLoadMoreSentinel} className="h-8" aria-hidden="true" />
326 ) : null}
327 </div>
328 </ScrollArea>
329 )}
330 </CommandPaletteContent>
331 );
333​
334export function ProjectContentSearchDialog(props: ProjectContentSearchDialogProps) {
335 const target = useActiveProjectTarget();
336​
337 return target ? (
338 <OpenContentSearchDialog
339 key={`${target.environmentId}:${target.cwd}`}
340 onOpenChange={props.onOpenChange}
341 target={target}
342 />
343 ) : (
344 <EmptyContentSearchDialog />
345 );