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