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