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

ProjectContentSearchDialog.tsx

329 lines11.9 KB

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;
23​
24/** Syntax-highlighting all 500 result rows at once stalls the UI. */
25const VISIBLE_MATCH_WINDOW = 100;
26​
27interface MatchGroup {
28 readonly path: string;
29 readonly matches: ReadonlyArray<ProjectContentMatch & { readonly resultIndex: number }>;
31​
32function splitPath(path: string): { readonly name: string; readonly directory: string } {
33 const separator = path.lastIndexOf("/");
34 return separator === -1
35 ? { name: path, directory: "" }
36 : { name: path.slice(separator + 1), directory: path.slice(0, separator) };
38​
39function groupMatches(matches: ReadonlyArray<ProjectContentMatch>): MatchGroup[] {
40 const groups = new Map<string, Array<ProjectContentMatch & { readonly resultIndex: number }>>();
41 matches.forEach((match, resultIndex) => {
42 const group = groups.get(match.path);
43 const indexedMatch = { ...match, resultIndex };
44 if (group) {
45 group.push(indexedMatch);
46 } else {
47 groups.set(match.path, [indexedMatch]);
48 }
49 });
50 return [...groups].map(([path, groupedMatches]) => ({ path, matches: groupedMatches }));
52​
53function SearchOptionButton(props: {
54 readonly active: boolean;
55 readonly disabled: boolean;
56 readonly label: string;
57 readonly onClick: () => void;
58 readonly children: ReactNode;
59}) {
60 return (
61 <Tooltip>
62 <TooltipTrigger
63 render={
64 <Toggle
65 aria-label={props.label}
66 disabled={props.disabled}
67 pressed={props.active}
68 size="segmented"
69 variant="segmented"
70 onClick={props.onClick}
71 />
72 }
73 >
74 <span className="font-mono">{props.children}</span>
75 </TooltipTrigger>
76 <TooltipPopup side="top">{props.label}</TooltipPopup>
77 </Tooltip>
78 );
80​
81function EmptyContentSearchDialog() {
82 return (
83 <CommandPaletteContent
84 aria-label="Search project contents"
85 escapeLabel="Back"
86 footerActionLabel="Open file"
87 inputProps={{ disabled: true, placeholder: "Search project contents…" }}
88 mode="none"
89 panelSize="fill"
90 testId="project-content-search"
91 value=""
92 >
93 <p className="m-auto px-6 text-center text-muted-foreground text-sm">
94 Open a project to search its files.
95 </p>
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 renderedAppearance = useRenderedAppearance();
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.canReadFiles && !search.isPending && search.error === null;
124 const matches = search.matches;
125 const [resultsFor, setResultsFor] = useState(matches);
126 if (resultsFor !== matches) {
127 setResultsFor(matches);
128 setSelectedIndex(0);
129 setVisibleCount(VISIBLE_MATCH_WINDOW);
130 }
131 if (selectedIndex >= visibleCount) {
132 setVisibleCount(selectedIndex + VISIBLE_MATCH_WINDOW);
133 }
134 const visibleMatches = matches.slice(0, visibleCount);
135 const groups = groupMatches(visibleMatches);
136​
137 useEffect(() => {
138 document
139 .querySelector<HTMLElement>(`[data-content-search-result="${selectedIndex}"]`)
140 ?.scrollIntoView({ block: "nearest" });
141 }, [selectedIndex]);
142​
143 const observeLoadMoreSentinel = (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 || !readEnvironmentScope(target.environmentId, AuthFilesystemReadScope)) {
156 return;
157 }
158 props.onOpenChange(false);
159 useRightPanelStore.getState().openFile(target.threadRef, match.path, match.lineNumber);
160 };
161 const fileCount = new Set(matches.map((match) => match.path)).size;
162 const showSearchStatus =
163 search.canReadFiles &&
164 (search.hasQuery || search.isPending || search.error !== null || search.invalidRegex);
165​
166 return (
167 <CommandPaletteContent
168 aria-label={`Search file contents in ${target.projectName}`}
169 escapeLabel="Back"
170 footerActionLabel="Open file"
171 inputAccessory={
172 <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">
173 <SearchOptionButton
174 active={caseSensitive}
175 disabled={!search.canReadFiles}
176 label="Match case"
177 onClick={() => setCaseSensitive((current) => !current)}
178 >
179 Aa
180 </SearchOptionButton>
181 <SearchOptionButton
182 active={wholeWord}
183 disabled={!search.canReadFiles}
184 label="Match whole word"
185 onClick={() => setWholeWord((current) => !current)}
186 >
187 <span className="underline decoration-2 underline-offset-2">ab</span>
188 </SearchOptionButton>
189 <SearchOptionButton
190 active={useRegex}
191 disabled={!search.canReadFiles}
192 label="Use regular expression"
193 onClick={() => setUseRegex((current) => !current)}
194 >
195 .*
196 </SearchOptionButton>
197 </div>
198 }
199 inputProps={{
200 className: "pe-30",
201 disabled: !search.canReadFiles,
202 placeholder: `Search in ${target.projectName}`,
203 onKeyDown: (event) => {
204 if (event.key === "ArrowDown" && matches.length > 0) {
205 event.preventDefault();
206 setSelectedIndex((current) => (current + 1) % matches.length);
207 } else if (event.key === "ArrowUp" && matches.length > 0) {
208 event.preventDefault();
209 setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);
210 } else if (event.key === "Enter") {
211 if (!canOpenMatches) {
212 event.preventDefault();
213 return;
214 }
215 const match = matches[selectedIndex];
216 if (match) {
217 event.preventDefault();
218 openMatch(match);
219 }
220 }
221 },
222 }}
223 mode="none"
224 onValueChange={setQuery}
225 panelSize="fill"
226 testId="project-content-search"
227 value={query}
228 >
229 {showSearchStatus ? (
230 <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">
231 {search.isPending ? (
232 <span className="flex items-center gap-2">
233 <Spinner size="sm" /> Searching…
234 </span>
235 ) : search.error ? (
236 <span className="text-destructive">{search.error}</span>
237 ) : search.invalidRegex ? (
238 <span className="text-destructive">Invalid regular expression</span>
239 ) : (
240 `${matches.length.toLocaleString()}${search.truncated ? "+" : ""} results in ${fileCount.toLocaleString()} files`
241 )}
242 </div>
243 ) : null}
244​
245 {matches.length === 0 ? (
246 <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
247 {search.isCheckingAccess
248 ? "Checking file access…"
249 : !search.canReadFiles
250 ? search.error
251 : search.hasQuery && !search.isPending && !search.error
252 ? "No results found."
253 : "Type to search across your project."}
254 </div>
255 ) : (
256 <ScrollArea className="min-h-0 flex-1" scrollFade>
257 <div className="py-2">
258 {groups.map((group) => {
259 const path = splitPath(group.path);
260 return (
261 <section className="pb-2" key={group.path}>
262 <div className="sticky top-0 z-10 flex h-8 items-center gap-2 bg-popover/95 px-3 text-xs backdrop-blur-sm">
263 <PierreEntryIcon
264 pathValue={group.path}
265 kind="file"
266 theme={resolvedTheme}
267 className="size-3.5"
268 />
269 <span className="font-medium text-foreground">{path.name}</span>
270 {path.directory ? (
271 <span className="min-w-0 truncate text-muted-foreground">
272 {path.directory}
273 </span>
274 ) : null}
275 <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 tabular-nums text-3xs text-muted-foreground">
276 {group.matches.length}
277 </span>
278 </div>
279 {group.matches.map((match) => (
280 <button
281 type="button"
282 key={`${match.path}:${match.lineNumber}:${match.resultIndex}`}
283 data-content-search-result={match.resultIndex}
284 className={cn(
285 "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",
286 match.resultIndex === selectedIndex && "bg-accent text-accent-foreground",
287 )}
288 disabled={!canOpenMatches}
289 onMouseEnter={() => setSelectedIndex(match.resultIndex)}
290 onClick={() => openMatch(match)}
291 >
292 <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground/70">
293 {match.lineNumber}
294 </span>
295 <span className="min-w-0 flex-1 truncate whitespace-pre">
296 <HighlightedSearchLine
297 match={match}
298 path={group.path}
299 theme={renderedAppearance}
300 />
301 </span>
302 </button>
303 ))}
304 </section>
305 );
306 })}
307 {matches.length > visibleCount ? (
308 <div ref={observeLoadMoreSentinel} className="h-8" aria-hidden="true" />
309 ) : null}
310 </div>
311 </ScrollArea>
312 )}
313 </CommandPaletteContent>
314 );
316​
317export function ProjectContentSearchDialog(props: ProjectContentSearchDialogProps) {
318 const target = useActiveProjectTarget();
319​
320 return target ? (
321 <OpenContentSearchDialog
322 key={`${target.environmentId}:${target.cwd}`}
323 onOpenChange={props.onOpenChange}
324 target={target}
325 />
326 ) : (
327 <EmptyContentSearchDialog />
328 );