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

ProjectContentSearchDialog.tsx

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