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