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

ProjectContentSearchDialog.tsx

323 lines11.8 KB

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