Open History to see the last commit
1import { Spinner } from "~/components/ui/spinner";
2import { AuthFilesystemReadScope, type ProjectContentMatch } from "@t3tools/contracts";
3
4import { useEffect, useState, type ReactNode } from "react";
5
6import { useActiveProjectTarget, type ActiveProjectTarget } from "~/hooks/useActiveProjectTarget";
7import { useTheme } from "~/hooks/useTheme";
8import { cn } from "~/lib/utils";
9import { useRightPanelStore } from "~/rightPanelStore";
10import { useProjectContentSearch } from "~/state/queries";
11import { readEnvironmentScope } from "~/state/session";
12
13import { PierreEntryIcon } from "../chat/PierreEntryIcon";
14import { CommandPaletteContent } from "../CommandPaletteContent";
15import { ScrollArea } from "../ui/scroll-area";
16import { Toggle } from "../ui/toggle";
17import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
18import { HighlightedSearchLine } from "./HighlightedSearchLine";
19
20interface ProjectContentSearchDialogProps {
21 readonly onOpenChange: (open: boolean) => void;
22}
23
24/**
25 * Result rows are syntax highlighted, so mounting all 500 possible rows at once
26 * stalls the UI.
27 */
28const VISIBLE_MATCH_WINDOW = 100;
29
30interface MatchGroup {
31 readonly path: string;
32 readonly matches: ReadonlyArray<ProjectContentMatch & { readonly resultIndex: number }>;
33}
34
35function splitPath(path: string): { readonly name: string; readonly directory: string } {
36 const separator = path.lastIndexOf("/");
37 return separator === -1
38 ? { name: path, directory: "" }
39 : { name: path.slice(separator + 1), directory: path.slice(0, separator) };
40}
41
42function groupMatches(matches: ReadonlyArray<ProjectContentMatch>): MatchGroup[] {
43 const groups = new Map<string, Array<ProjectContentMatch & { readonly resultIndex: number }>>();
44 matches.forEach((match, resultIndex) => {
45 const group = groups.get(match.path);
46 const indexedMatch = { ...match, resultIndex };
47 if (group) {
48 group.push(indexedMatch);
49 } else {
50 groups.set(match.path, [indexedMatch]);
51 }
52 });
53 return [...groups].map(([path, groupedMatches]) => ({ path, matches: groupedMatches }));
54}
55
56function SearchOptionButton(props: {
57 readonly active: boolean;
58 readonly disabled: boolean;
59 readonly label: string;
60 readonly onClick: () => void;
61 readonly children: ReactNode;
62}) {
63 return (
64 <Tooltip>
65 <TooltipTrigger
66 render={
67 <Toggle
68 aria-label={props.label}
69 disabled={props.disabled}
70 pressed={props.active}
71 size="segmented"
72 variant="segmented"
73 onClick={props.onClick}
74 />
75 }
76 >
77 <span className="font-mono">{props.children}</span>
78 </TooltipTrigger>
79 <TooltipPopup side="top">{props.label}</TooltipPopup>
80 </Tooltip>
81 );
82}
83
84function EmptyContentSearchDialog() {
85 return (
86 <CommandPaletteContent
87 aria-label="Search project contents"
88 escapeLabel="Back"
89 footerActionLabel="Open file"
90 inputProps={{ disabled: true, placeholder: "Search project contents…" }}
91 mode="none"
92 panelSize="fill"
93 testId="project-content-search"
94 value=""
95 >
96 <p className="m-auto px-6 text-center text-muted-foreground text-sm">
97 Open a project to search its files.
98 </p>
99 </CommandPaletteContent>
100 );
101}
102
103function OpenContentSearchDialog(props: {
104 readonly onOpenChange: (open: boolean) => void;
105 readonly target: ActiveProjectTarget;
106}) {
107 const { target } = props;
108 const { resolvedTheme } = useTheme();
109 const [query, setQuery] = useState("");
110 const [caseSensitive, setCaseSensitive] = useState(false);
111 const [wholeWord, setWholeWord] = useState(false);
112 const [useRegex, setUseRegex] = useState(false);
113 const [selectedIndex, setSelectedIndex] = useState(0);
114
115 const [visibleCount, setVisibleCount] = useState(VISIBLE_MATCH_WINDOW);
116
117 const search = useProjectContentSearch({
118 environmentId: target.environmentId,
119 cwd: target.cwd,
120 query,
121 caseSensitive,
122 wholeWord,
123 useRegex,
124 });
125 const canOpenMatches = search.canReadFiles && !search.isPending && search.error === null;
126 const matches = search.matches;
127 // New results restart the selection and the rendered window.
128 const [resultsFor, setResultsFor] = useState(matches);
129 if (resultsFor !== matches) {
130 setResultsFor(matches);
131 setSelectedIndex(0);
132 setVisibleCount(VISIBLE_MATCH_WINDOW);
133 }
134 // Keyboard selection past the window grows it before the row has to scroll into view.
135 if (selectedIndex >= visibleCount) {
136 setVisibleCount(selectedIndex + VISIBLE_MATCH_WINDOW);
137 }
138 const visibleMatches = matches.slice(0, visibleCount);
139 const groups = groupMatches(visibleMatches);
140
141 useEffect(() => {
142 document
143 .querySelector<HTMLElement>(`[data-content-search-result="${selectedIndex}"]`)
144 ?.scrollIntoView({ block: "nearest" });
145 }, [selectedIndex]);
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={`Search file contents in ${target.projectName}`}
173 escapeLabel="Back"
174 footerActionLabel="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="Match case"
181 onClick={() => setCaseSensitive((current) => !current)}
182 >
183 Aa
184 </SearchOptionButton>
185 <SearchOptionButton
186 active={wholeWord}
187 disabled={!search.canReadFiles}
188 label="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="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: `Search in ${target.projectName}`,
207 onKeyDown: (event) => {
208 if (event.key === "ArrowDown" && matches.length > 0) {
209 event.preventDefault();
210 setSelectedIndex((current) => (current + 1) % matches.length);
211 } else if (event.key === "ArrowUp" && matches.length > 0) {
212 event.preventDefault();
213 setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);
214 } else if (event.key === "Enter") {
215 if (!canOpenMatches) {
216 event.preventDefault();
217 return;
218 }
219 const match = matches[selectedIndex];
220 if (match) {
221 event.preventDefault();
222 openMatch(match);
223 }
224 }
225 },
226 }}
227 mode="none"
228 onValueChange={setQuery}
229 panelSize="fill"
230 testId="project-content-search"
231 value={query}
232 >
233 {showSearchStatus ? (
234 <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">
235 {search.isPending ? (
236 <span className="flex items-center gap-2">
237 <Spinner size="sm" /> Searching…
238 </span>
239 ) : search.error ? (
240 <span className="text-destructive">{search.error}</span>
241 ) : search.invalidRegex ? (
242 <span className="text-destructive">Invalid regular expression</span>
243 ) : (
244 `${matches.length.toLocaleString()}${search.truncated ? "+" : ""} results in ${fileCount.toLocaleString()} files`
245 )}
246 </div>
247 ) : null}
248
249 {matches.length === 0 ? (
250 <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
251 {search.isCheckingAccess
252 ? "Checking file access…"
253 : !search.canReadFiles
254 ? search.error
255 : search.hasQuery && !search.isPending && !search.error
256 ? "No results found."
257 : "Type to search across your project."}
258 </div>
259 ) : (
260 <ScrollArea className="min-h-0 flex-1" scrollFade>
261 <div className="py-2">
262 {groups.map((group) => {
263 const path = splitPath(group.path);
264 return (
265 <section className="pb-2" key={group.path}>
266 <div className="sticky top-0 z-10 flex h-8 items-center gap-2 bg-popover/95 px-3 text-xs backdrop-blur-sm">
267 <PierreEntryIcon
268 pathValue={group.path}
269 kind="file"
270 theme={resolvedTheme}
271 className="size-3.5"
272 />
273 <span className="font-medium text-foreground">{path.name}</span>
274 {path.directory ? (
275 <span className="min-w-0 truncate text-muted-foreground">
276 {path.directory}
277 </span>
278 ) : null}
279 <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 tabular-nums text-3xs text-muted-foreground">
280 {group.matches.length}
281 </span>
282 </div>
283 {group.matches.map((match) => (
284 <button
285 type="button"
286 key={`${match.path}:${match.lineNumber}:${match.resultIndex}`}
287 data-content-search-result={match.resultIndex}
288 className={cn(
289 "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",
290 match.resultIndex === selectedIndex && "bg-accent text-accent-foreground",
291 )}
292 disabled={!canOpenMatches}
293 onMouseEnter={() => setSelectedIndex(match.resultIndex)}
294 onClick={() => openMatch(match)}
295 >
296 <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground/70">
297 {match.lineNumber}
298 </span>
299 <span className="min-w-0 flex-1 truncate whitespace-pre">
300 <HighlightedSearchLine
301 match={match}
302 path={group.path}
303 theme={resolvedTheme}
304 />
305 </span>
306 </button>
307 ))}
308 </section>
309 );
310 })}
311 {matches.length > visibleCount ? (
312 <div ref={observeLoadMoreSentinel} className="h-8" aria-hidden="true" />
313 ) : null}
314 </div>
315 </ScrollArea>
316 )}
317 </CommandPaletteContent>
318 );
319}
320
321export function ProjectContentSearchDialog(props: ProjectContentSearchDialogProps) {
322 const target = useActiveProjectTarget();
323
324 return target ? (
325 <OpenContentSearchDialog
326 key={`${target.environmentId}:${target.cwd}`}
327 onOpenChange={props.onOpenChange}
328 target={target}
329 />
330 ) : (
331 <EmptyContentSearchDialog />
332 );
333}