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

ProjectContentSearchDialog.tsx

330 lines12.0 KB

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