Open History to see the last commit
1import type { OrchestrationV2FileSearchResult } from "@t3tools/contracts";
2import { groupFileSearchResults } from "@t3tools/client-runtime/work-log/item-detail";
3import { splitSearchText, type SearchRange } from "@t3tools/shared/paletteSearch";
4import { useGT, plural, part as gtPart } from "gt-react";
5
6import { formatWorkspaceRelativePath } from "../../filePathDisplay";
7import { cn } from "../../lib/utils";
8
9const MAX_HIGHLIGHTS_PER_LINE = 20;
10const MAX_HIGHLIGHTED_LINE_CHARS = 1_000;
11
12// JavaScript backtracks where ripgrep runs in linear time, and the work multiplies with every
13// quantifier and alternation. One quantifier (not on a group) and three `|` keep a match within
14// about 8·n² steps; other patterns could hang rendering, so they go unhighlighted.
15function backtracksSafely(pattern: string) {
16 const unescaped = pattern.replace(/\\./g, "");
17 return (
18 (unescaped.match(/[*+?{]/g) ?? []).length <= 1 &&
19 (unescaped.match(/\|/g) ?? []).length <= 3 &&
20 !/\)[*+{]/.test(unescaped)
21 );
22}
23
24// Provider patterns are ripgrep regexes; JavaScript reads most of them the same way. Every
25// matched line is known to match, so when the case-sensitive form misses one the search
26// was case-insensitive. A pattern JavaScript can't parse just goes unhighlighted.
27function patternMatchers(pattern: string | undefined): ReadonlyArray<RegExp> {
28 if (!pattern?.trim() || !backtracksSafely(pattern)) return [];
29 try {
30 return [new RegExp(pattern, "g"), new RegExp(pattern, "gi")];
31 } catch {
32 return [];
33 }
34}
35
36function matchRanges(text: string, matchers: ReadonlyArray<RegExp>): ReadonlyArray<SearchRange> {
37 if (text.length > MAX_HIGHLIGHTED_LINE_CHARS) return [];
38 for (const matcher of matchers) {
39 const ranges: SearchRange[] = [];
40 for (const match of text.matchAll(matcher)) {
41 if (match[0].length === 0) continue;
42 ranges.push({ start: match.index, end: match.index + match[0].length });
43 if (ranges.length === MAX_HIGHLIGHTS_PER_LINE) break;
44 }
45 if (ranges.length > 0) return ranges;
46 }
47 return [];
48}
49
50function MatchedLine(props: { readonly text: string; readonly matchers: ReadonlyArray<RegExp> }) {
51 const ranges = matchRanges(props.text, props.matchers);
52 if (ranges.length === 0) return props.text;
53 return splitSearchText(props.text, ranges).map((part) =>
54 part.highlighted ? (
55 <mark key={part.start} className="rounded-xs bg-warning/20 text-foreground">
56 {part.text}
57 </mark>
58 ) : (
59 part.text
60 ),
61 );
62}
63
64function FilePath(props: { readonly path: string; readonly className?: string }) {
65 const slash = props.path.lastIndexOf("/");
66 return (
67 <span className={props.className}>
68 {slash >= 0 ? (
69 <span className="text-muted-foreground/70">{props.path.slice(0, slash + 1)}</span>
70 ) : null}
71 <span className="text-foreground/90">{props.path.slice(slash + 1)}</span>
72 </span>
73 );
74}
75
76const resultsClassName =
77 "max-h-96 overflow-y-auto font-mono text-(length:--font-size-code,var(--text-2xs)) leading-relaxed select-text";
78
79export function FileSearchResults(props: {
80 readonly pattern: string | undefined;
81 readonly results: ReadonlyArray<OrchestrationV2FileSearchResult>;
82 readonly workspaceRoot: string | undefined;
83}) {
84 const gt = useGT();
85 const groups = groupFileSearchResults(props.results);
86 if (props.results.every((result) => result.line === undefined && !result.preview?.trim())) {
87 return (
88 <ul className={cn("list-none", resultsClassName)}>
89 {groups.map(({ fileName }) => (
90 <li key={fileName} className="wrap-anywhere">
91 <FilePath path={formatWorkspaceRelativePath(fileName, props.workspaceRoot)} />
92 </li>
93 ))}
94 </ul>
95 );
96 }
97
98 const matchers = patternMatchers(props.pattern);
99 return (
100 <div
101 className={cn(
102 "divide-y divide-border/60 rounded-md border border-border/70 bg-muted/45",
103 resultsClassName,
104 )}
105 >
106 {groups.map((group) => {
107 const lines = group.results.filter((result) => result.line !== undefined);
108 const notes = group.results.flatMap((result) =>
109 result.line === undefined && result.preview?.trim() ? [result.preview.trimEnd()] : [],
110 );
111 const [firstNote] = notes;
112 const inlineNote =
113 lines.length === 0 &&
114 notes.length === 1 &&
115 firstNote !== undefined &&
116 !firstNote.includes("\n");
117 return (
118 <section key={group.fileName} className="min-w-0 px-2.5 py-1.5">
119 <div className="flex min-w-0 items-baseline gap-2">
120 <FilePath
121 path={formatWorkspaceRelativePath(group.fileName, props.workspaceRoot)}
122 className="min-w-0 truncate"
123 />
124 {lines.length > 1 ? (
125 <span className="shrink-0 text-muted-foreground/60 tabular-nums">
126 {gt`${plural(
127 { count: lines.length },
128 {
129 one: gtPart`${{ count: lines.length }} match`,
130 other: gtPart`${{ count: lines.length }} matches`,
131 },
132 )}`}
133 </span>
134 ) : null}
135 {inlineNote ? (
136 <span className="shrink-0 text-muted-foreground/70">{firstNote}</span>
137 ) : null}
138 </div>
139 {lines.length > 0 ? (
140 <div className="mt-0.5 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3">
141 {lines.map((result) => (
142 <div key={`${result.line}:${result.column ?? ""}`} className="contents">
143 <span className="text-right text-muted-foreground/45 tabular-nums select-none">
144 {result.line}
145 </span>
146 <span className="line-clamp-3 break-words whitespace-pre-wrap text-muted-foreground">
147 <MatchedLine text={result.preview?.trim() ?? ""} matchers={matchers} />
148 </span>
149 </div>
150 ))}
151 </div>
152 ) : null}
153 {!inlineNote && notes.length > 0 ? (
154 <pre className="mt-0.5 break-words whitespace-pre-wrap text-muted-foreground">
155 {notes.join("\n")}
156 </pre>
157 ) : null}
158 </section>
159 );
160 })}
161 </div>
162 );
163}