The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 348 lines 12.7 KB
Raw
1 import { Spinner } from "~/components/ui/spinner";
2 import { AuthFilesystemReadScope, type ProjectContentMatch } from "@t3tools/contracts";
3
4 import { T, useGT, useMessages } from "gt-react";
5 import { useState, type ReactNode } from "react";
6
7 import { useActiveProjectTarget, type ActiveProjectTarget } from "~/hooks/useActiveProjectTarget";
8 import { useRenderedAppearance, useTheme } from "~/hooks/useTheme";
9 import { cn } from "~/lib/utils";
10 import { useRightPanelStore } from "~/rightPanelStore";
11 import { useProjectContentSearch } from "~/state/queries";
12 import { readEnvironmentScope } from "~/state/session";
13
14 import { PierreEntryIcon } from "../chat/PierreEntryIcon";
15 import { CommandPaletteContent } from "../CommandPaletteContent";
16 import { ScrollArea } from "../ui/scroll-area";
17 import { Toggle } from "../ui/toggle";
18 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
19 import { HighlightedSearchLine } from "./HighlightedSearchLine";
20
21 interface ProjectContentSearchDialogProps {
22 readonly onOpenChange: (open: boolean) => void;
23 }
24
25 /** Syntax-highlighting all 500 result rows at once stalls the UI. */
26 const VISIBLE_MATCH_WINDOW = 100;
27
28 interface MatchGroup {
29 readonly path: string;
30 readonly matches: ReadonlyArray<ProjectContentMatch & { readonly resultIndex: number }>;
31 }
32
33 function splitPath(path: string): { readonly name: string; readonly directory: string } {
34 const separator = path.lastIndexOf("/");
35 return separator === -1
36 ? { name: path, directory: "" }
37 : { name: path.slice(separator + 1), directory: path.slice(0, separator) };
38 }
39
40 function groupMatches(matches: ReadonlyArray<ProjectContentMatch>): MatchGroup[] {
41 const groups = new Map<string, Array<ProjectContentMatch & { readonly resultIndex: number }>>();
42 matches.forEach((match, resultIndex) => {
43 const group = groups.get(match.path);
44 const indexedMatch = { ...match, resultIndex };
45 if (group) {
46 group.push(indexedMatch);
47 } else {
48 groups.set(match.path, [indexedMatch]);
49 }
50 });
51 return [...groups].map(([path, groupedMatches]) => ({ path, matches: groupedMatches }));
52 }
53
54 function SearchOptionButton(props: {
55 readonly active: boolean;
56 readonly disabled: boolean;
57 readonly label: string;
58 readonly onClick: () => void;
59 readonly children: ReactNode;
60 }) {
61 return (
62 <Tooltip>
63 <TooltipTrigger
64 render={
65 <Toggle
66 aria-label={props.label}
67 disabled={props.disabled}
68 pressed={props.active}
69 size="segmented"
70 variant="segmented"
71 onClick={props.onClick}
72 />
73 }
74 >
75 <span className="font-mono">{props.children}</span>
76 </TooltipTrigger>
77 <TooltipPopup side="top">{props.label}</TooltipPopup>
78 </Tooltip>
79 );
80 }
81
82 function EmptyContentSearchDialog() {
83 const gt = useGT();
84 return (
85 <CommandPaletteContent
86 aria-label={gt("Search project contents")}
87 escapeLabel={gt("Back")}
88 footerActionLabel={gt("Open file")}
89 inputProps={{ disabled: true, placeholder: gt("Search project contents…") }}
90 mode="none"
91 panelSize="fill"
92 testId="project-content-search"
93 value=""
94 >
95 <p className="m-auto px-6 text-center text-muted-foreground text-sm">
96 <T>Open a project to search its files.</T>
97 </p>
98 </CommandPaletteContent>
99 );
100 }
101
102 const scrollSelectedRowIntoView = (row: HTMLElement | null) => {
103 row?.scrollIntoView({ block: "nearest" });
104 };
105
106 function OpenContentSearchDialog(props: {
107 readonly onOpenChange: (open: boolean) => void;
108 readonly target: ActiveProjectTarget;
109 }) {
110 const { target } = props;
111 const gt = useGT();
112 const messages = useMessages();
113 const { resolvedTheme } = useTheme();
114 const renderedAppearance = useRenderedAppearance();
115 const [query, setQuery] = useState("");
116 const [caseSensitive, setCaseSensitive] = useState(false);
117 const [wholeWord, setWholeWord] = useState(false);
118 const [useRegex, setUseRegex] = useState(false);
119 const [selectedIndex, setSelectedIndex] = useState(0);
120
121 const [visibleCount, setVisibleCount] = useState(VISIBLE_MATCH_WINDOW);
122
123 const search = useProjectContentSearch(
124 {
125 environmentId: target.environmentId,
126 cwd: target.cwd,
127 query,
128 caseSensitive,
129 wholeWord,
130 useRegex,
131 },
132 messages,
133 );
134 const canOpenMatches = search.canReadFiles && !search.isPending && search.error === null;
135 const matches = search.matches;
136 const [resultsFor, setResultsFor] = useState(matches);
137 if (resultsFor !== matches) {
138 setResultsFor(matches);
139 setSelectedIndex(0);
140 setVisibleCount(VISIBLE_MATCH_WINDOW);
141 }
142 if (selectedIndex >= visibleCount) {
143 setVisibleCount(selectedIndex + VISIBLE_MATCH_WINDOW);
144 }
145 const visibleMatches = matches.slice(0, visibleCount);
146 const groups = groupMatches(visibleMatches);
147
148 const observeLoadMoreSentinel = (sentinel: HTMLElement | null) => {
149 if (!sentinel) return;
150 const observer = new IntersectionObserver((entries) => {
151 if (entries.some((entry) => entry.isIntersecting)) {
152 setVisibleCount((current) => current + VISIBLE_MATCH_WINDOW);
153 }
154 });
155 observer.observe(sentinel);
156 return () => observer.disconnect();
157 };
158
159 const openMatch = (match: ProjectContentMatch) => {
160 if (!canOpenMatches || !readEnvironmentScope(target.environmentId, AuthFilesystemReadScope)) {
161 return;
162 }
163 props.onOpenChange(false);
164 useRightPanelStore.getState().openFile(target.threadRef, match.path, match.lineNumber);
165 };
166 const fileCount = new Set(matches.map((match) => match.path)).size;
167 const showSearchStatus =
168 search.canReadFiles &&
169 (search.hasQuery || search.isPending || search.error !== null || search.invalidRegex);
170
171 return (
172 <CommandPaletteContent
173 aria-label={gt("Search file contents in {project}", { project: target.projectName })}
174 escapeLabel={gt("Back")}
175 footerActionLabel={gt("Open file")}
176 inputAccessory={
177 <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">
178 <SearchOptionButton
179 active={caseSensitive}
180 disabled={!search.canReadFiles}
181 label={gt("Match case")}
182 onClick={() => setCaseSensitive((current) => !current)}
183 >
184 {/* oxlint-disable-next-line t3code/no-untranslated-copy -- match-case glyph; the label carries the meaning */}
185 {"Aa"}
186 </SearchOptionButton>
187 <SearchOptionButton
188 active={wholeWord}
189 disabled={!search.canReadFiles}
190 label={gt("Match whole word")}
191 onClick={() => setWholeWord((current) => !current)}
192 >
193 <span className="underline decoration-2 underline-offset-2">ab</span>
194 </SearchOptionButton>
195 <SearchOptionButton
196 active={useRegex}
197 disabled={!search.canReadFiles}
198 label={gt("Use regular expression")}
199 onClick={() => setUseRegex((current) => !current)}
200 >
201 .*
202 </SearchOptionButton>
203 </div>
204 }
205 inputProps={{
206 className: "pe-30",
207 disabled: !search.canReadFiles,
208 placeholder: gt("Search in {project}", { project: target.projectName }),
209 onKeyDown: (event) => {
210 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
211 if (event.key === "ArrowDown" && matches.length > 0) {
212 event.preventDefault();
213 setSelectedIndex((current) => (current + 1) % matches.length);
214 } else if (event.key === "ArrowUp" && matches.length > 0) {
215 event.preventDefault();
216 setSelectedIndex((current) => (current - 1 + matches.length) % matches.length);
217 } else if (event.key === "Enter") {
218 if (!canOpenMatches) {
219 event.preventDefault();
220 return;
221 }
222 const match = matches[selectedIndex];
223 if (match) {
224 event.preventDefault();
225 openMatch(match);
226 }
227 }
228 },
229 }}
230 mode="none"
231 onValueChange={setQuery}
232 panelSize="fill"
233 testId="project-content-search"
234 value={query}
235 >
236 {showSearchStatus ? (
237 <div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">
238 {search.isPending ? (
239 <span className="flex items-center gap-2">
240 <Spinner size="sm" /> <T>Searching…</T>
241 </span>
242 ) : search.error ? (
243 <span className="text-destructive">{search.error}</span>
244 ) : search.invalidRegex ? (
245 <span className="text-destructive">
246 <T>Invalid regular expression</T>
247 </span>
248 ) : search.truncated ? (
249 gt("{results}+ results in {files} files", {
250 results: matches.length.toLocaleString(),
251 files: fileCount.toLocaleString(),
252 })
253 ) : (
254 gt("{results} results in {files} files", {
255 results: matches.length.toLocaleString(),
256 files: fileCount.toLocaleString(),
257 })
258 )}
259 </div>
260 ) : null}
261
262 {matches.length === 0 ? (
263 <div className="flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">
264 {search.isCheckingAccess
265 ? gt("Checking file access…")
266 : !search.canReadFiles
267 ? search.error
268 : search.hasQuery && !search.isPending && !search.error
269 ? gt("No results found.")
270 : gt("Type to search across your project.")}
271 </div>
272 ) : (
273 <ScrollArea className="min-h-0 flex-1" scrollFade>
274 <div className="py-2">
275 {groups.map((group) => {
276 const path = splitPath(group.path);
277 return (
278 <section className="pb-2" key={group.path}>
279 <div className="sticky top-0 z-10 flex h-8 items-center gap-2 bg-popover/95 px-3 text-xs backdrop-blur-sm">
280 <PierreEntryIcon
281 pathValue={group.path}
282 kind="file"
283 theme={resolvedTheme}
284 className="size-3.5"
285 />
286 <span className="font-medium text-foreground">{path.name}</span>
287 {path.directory ? (
288 <span className="min-w-0 truncate text-muted-foreground">
289 {path.directory}
290 </span>
291 ) : null}
292 <span className="ml-auto rounded-full bg-muted px-1.5 py-0.5 tabular-nums text-3xs text-muted-foreground">
293 {group.matches.length}
294 </span>
295 </div>
296 {group.matches.map((match) => (
297 <button
298 type="button"
299 key={`${match.path}:${match.lineNumber}:${match.resultIndex}`}
300 ref={
301 match.resultIndex === selectedIndex ? scrollSelectedRowIntoView : undefined
302 }
303 className={cn(
304 "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",
305 match.resultIndex === selectedIndex && "bg-accent text-accent-foreground",
306 )}
307 disabled={!canOpenMatches}
308 onMouseEnter={() => setSelectedIndex(match.resultIndex)}
309 onClick={() => openMatch(match)}
310 >
311 <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground/70">
312 {match.lineNumber}
313 </span>
314 <span className="min-w-0 flex-1 truncate whitespace-pre">
315 <HighlightedSearchLine
316 match={match}
317 path={group.path}
318 theme={renderedAppearance}
319 />
320 </span>
321 </button>
322 ))}
323 </section>
324 );
325 })}
326 {matches.length > visibleCount ? (
327 <div ref={observeLoadMoreSentinel} className="h-8" aria-hidden="true" />
328 ) : null}
329 </div>
330 </ScrollArea>
331 )}
332 </CommandPaletteContent>
333 );
334 }
335
336 export function ProjectContentSearchDialog(props: ProjectContentSearchDialogProps) {
337 const target = useActiveProjectTarget();
338
339 return target ? (
340 <OpenContentSearchDialog
341 key={`${target.environmentId}:${target.cwd}`}
342 onOpenChange={props.onOpenChange}
343 target={target}
344 />
345 ) : (
346 <EmptyContentSearchDialog />
347 );
348 }