Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectContentSearchDialog.tsx

321 lines11.9 KB

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