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