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