Open History to see the last commit
1import type { ProjectContentMatch } from "@t3tools/contracts";
2import { LoaderCircle } from "lucide-react";
3import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
4
5import { useActiveProjectTarget, type ActiveProjectTarget } from "~/hooks/useActiveProjectTarget";
6import { useTheme } from "~/hooks/useTheme";
7import { cn } from "~/lib/utils";
8import { useRightPanelStore } from "~/rightPanelStore";
9import { useProjectContentSearch } from "~/state/queries";
10
11import { PierreEntryIcon } from "../chat/PierreEntryIcon";
12import { CommandPaletteContent } from "../CommandPaletteContent";
13import { ScrollArea } from "../ui/scroll-area";
14import { HighlightedSearchLine } from "./HighlightedSearchLine";
15
16interface ProjectContentSearchDialogProps {
17 readonly onOpenChange: (open: boolean) => void;
18}
19
20/**
21 * Result rows are syntax highlighted, so mounting all 500 possible rows at
22 * once stalls the UI. Rows render in windows that grow as the sentinel at the
23 * bottom of the list scrolls into view (or keyboard navigation moves past
24 * the rendered window).
25 */
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 label: string;
57 readonly onClick: () => void;
58 readonly children: ReactNode;
59}) {
60 return (
61 <button
62 type="button"
63 aria-label={props.label}
64 aria-pressed={props.active}
65 title={props.label}
66 className={cn(
67 "flex size-8 shrink-0 items-center justify-center rounded-[5px] font-mono text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",
68 props.active && "bg-accent text-foreground shadow-sm",
69 )}
70 onClick={props.onClick}
71 >
72 {props.children}
73 </button>
74 );
75}
76
77function EmptyContentSearchDialog() {
78 return (
79 <CommandPaletteContent
80 aria-label="Search project contents"
81 escapeLabel="Back"
82 footerActionLabel="Open file"
83 inputProps={{ disabled: true, placeholder: "Search project contents…" }}
84 mode="none"
85 panelClassName="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground"
86 testId="project-content-search"
87 value=""
88 >
89 Open a project to search its files.
90 </CommandPaletteContent>
91 );
92}
93
94function OpenContentSearchDialog(props: {
95 readonly onOpenChange: (open: boolean) => void;
96 readonly target: ActiveProjectTarget;
97}) {
98 const { target } = props;
99 const { resolvedTheme } = useTheme();
100 const [query, setQuery] = useState("");
101 const [caseSensitive, setCaseSensitive] = useState(false);
102 const [wholeWord, setWholeWord] = useState(false);
103 const [useRegex, setUseRegex] = useState(false);
104 const [selectedIndex, setSelectedIndex] = useState(0);
105
106 const [visibleCount, setVisibleCount] = useState(VISIBLE_MATCH_WINDOW);
107
108 const search = useProjectContentSearch({
109 environmentId: target.environmentId,
110 cwd: target.cwd,
111 query,
112 caseSensitive,
113 wholeWord,
114 useRegex,
115 });
116 const canOpenMatches = !search.isPending;
117 const matches = search.matches;
118 const visibleMatches = useMemo(() => matches.slice(0, visibleCount), [matches, visibleCount]);
119 const groups = useMemo(() => groupMatches(visibleMatches), [visibleMatches]);
120
121 useEffect(() => {
122 setSelectedIndex(0);
123 setVisibleCount(VISIBLE_MATCH_WINDOW);
124 }, [matches]);
125
126 useEffect(() => {
127 if (selectedIndex >= visibleCount) {
128 setVisibleCount(selectedIndex + VISIBLE_MATCH_WINDOW);
129 return;
130 }
131 document
132 .querySelector<HTMLElement>(`[data-content-search-result="${selectedIndex}"]`)
133 ?.scrollIntoView({ block: "nearest" });
134 }, [selectedIndex, visibleCount]);
135
136 const observeLoadMoreSentinel = useCallback((sentinel: HTMLElement | null) => {
137 if (!sentinel) return;
138 const observer = new IntersectionObserver((entries) => {
139 if (entries.some((entry) => entry.isIntersecting)) {
140 setVisibleCount((current) => current + VISIBLE_MATCH_WINDOW);
141 }
142 });
143 observer.observe(sentinel);
144 return () => observer.disconnect();
145 }, []);
146
147 const openMatch = (match: ProjectContentMatch) => {
148 if (!canOpenMatches) return;
149 props.onOpenChange(false);
150 useRightPanelStore.getState().openFile(target.threadRef, match.path, match.lineNumber);
151 };
152 const fileCount = useMemo(() => new Set(matches.map((match) => match.path)).size, [matches]);
153 const showSearchStatus =
154 search.hasQuery || search.isPending || search.error !== null || search.invalidRegex;
155
156 return (
157 <CommandPaletteContent
158 aria-label={`Search file contents in ${target.projectName}`}
159 escapeLabel="Back"
160 footerActionLabel="Open file"
161 inputAccessory={
162 <div className="absolute inset-e-2.5 top-1/2 flex shrink-0 -translate-y-1/2 items-center gap-0.5 rounded-md border bg-muted/30 p-0.5">
163 <SearchOptionButton
164 active={caseSensitive}
165 label="Match case"
166 onClick={() => setCaseSensitive((current) => !current)}
167 >
168 Aa
169 </SearchOptionButton>
170 <SearchOptionButton
171 active={wholeWord}
172 label="Match whole word"
173 onClick={() => setWholeWord((current) => !current)}
174 >
175 <span className="underline decoration-2 underline-offset-2">ab</span>
176 </SearchOptionButton>
177 <SearchOptionButton
178 active={useRegex}
179 label="Use regular expression"
180 onClick={() => setUseRegex((current) => !current)}
181 >
182 .*
183 </SearchOptionButton>
184 </div>
185 }
186 inputProps={{
187 className: "pe-30",
188 placeholder: `Search in ${target.projectName}`,
189 onKeyDown: (event) => {
190 if (event.key === "ArrowDown" && matches.length > 0) {
191 event.preventDefault();
192 setSelectedIndex((current) => (current + 1) % matches.length);
193 } else if (event.key === "ArrowUp" && matches.length > 0) {
194 event.preventDefault();
195 setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);
196 } else if (event.key === "Enter") {
197 // While a newer query is debouncing or in flight, the visible
198 // matches belong to the previous query; opening one would jump
199 // to a result the user did not ask for.
200 if (!canOpenMatches) {
201 event.preventDefault();
202 return;
203 }
204 const match = matches[selectedIndex];
205 if (match) {
206 event.preventDefault();
207 openMatch(match);
208 }
209 }
210 },
211 }}
212 mode="none"
213 onValueChange={setQuery}
214 panelClassName="flex min-h-0 flex-1 flex-col"
215 testId="project-content-search"
216 value={query}
217 >
218 {showSearchStatus ? (
219 <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">
220 {search.isPending ? (
221 <span className="flex items-center gap-2">
222 <LoaderCircle className="size-3.5 animate-spin" /> Searching…
223 </span>
224 ) : search.error ? (
225 <span className="text-destructive">{search.error}</span>
226 ) : search.invalidRegex ? (
227 <span className="text-destructive">Invalid regular expression</span>
228 ) : (
229 `${matches.length.toLocaleString()}${search.truncated ? "+" : ""} results in ${fileCount.toLocaleString()} files`
230 )}
231 </div>
232 ) : null}
233
234 {matches.length === 0 ? (
235 <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
236 {search.hasQuery && !search.isPending && !search.error
237 ? "No results found."
238 : "Type to search across your project."}
239 </div>
240 ) : (
241 <ScrollArea className="min-h-0 flex-1" scrollFade>
242 <div className="py-2">
243 {groups.map((group) => {
244 const path = splitPath(group.path);
245 return (
246 <section className="pb-2" key={group.path}>
247 <div className="sticky top-0 z-10 flex h-8 items-center gap-2 bg-popover/95 px-3 text-xs backdrop-blur-sm">
248 <PierreEntryIcon
249 pathValue={group.path}
250 kind="file"
251 theme={resolvedTheme}
252 className="size-3.5"
253 />
254 <span className="font-medium text-foreground">{path.name}</span>
255 {path.directory ? (
256 <span className="min-w-0 truncate text-muted-foreground">
257 {path.directory}
258 </span>
259 ) : null}
260 <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 tabular-nums text-[10px] text-muted-foreground">
261 {group.matches.length}
262 </span>
263 </div>
264 {group.matches.map((match) => (
265 <button
266 type="button"
267 key={`${match.path}:${match.lineNumber}:${match.resultIndex}`}
268 data-content-search-result={match.resultIndex}
269 className={cn(
270 "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",
271 match.resultIndex === selectedIndex && "bg-accent text-accent-foreground",
272 )}
273 disabled={!canOpenMatches}
274 onMouseEnter={() => setSelectedIndex(match.resultIndex)}
275 onClick={() => openMatch(match)}
276 >
277 <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground/70">
278 {match.lineNumber}
279 </span>
280 <span className="min-w-0 flex-1 truncate whitespace-pre">
281 <HighlightedSearchLine
282 match={match}
283 path={group.path}
284 theme={resolvedTheme}
285 />
286 </span>
287 </button>
288 ))}
289 </section>
290 );
291 })}
292 {matches.length > visibleCount ? (
293 <div ref={observeLoadMoreSentinel} className="h-8" aria-hidden="true" />
294 ) : null}
295 </div>
296 </ScrollArea>
297 )}
298 </CommandPaletteContent>
299 );
300}
301
302export function ProjectContentSearchDialog(props: ProjectContentSearchDialogProps) {
303 const target = useActiveProjectTarget();
304
305 return target ? (
306 <OpenContentSearchDialog
307 // Reset the query and options whenever the workspace changes.
308 key={`${target.environmentId}:${target.cwd}`}
309 onOpenChange={props.onOpenChange}
310 target={target}
311 />
312 ) : (
313 <EmptyContentSearchDialog />
314 );
315}