@luxass/pi-session-search 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/package.json +49 -3
- package/src/current-session-search.ts +233 -0
- package/src/display-text.ts +391 -0
- package/src/finder-overlay.ts +1075 -0
- package/src/hits.ts +77 -0
- package/src/index-client.ts +404 -0
- package/src/index-search.ts +578 -0
- package/src/index-worker.ts +102 -0
- package/src/index.ts +196 -0
- package/src/jsonl-reader.ts +100 -0
- package/src/match-text.ts +65 -0
- package/src/open-match.ts +544 -0
- package/src/query.ts +490 -0
- package/src/searchable-text.ts +176 -0
- package/src/session-index.ts +577 -0
- package/src/transcript-scroll.ts +456 -0
- package/src/worker-protocol.ts +66 -0
|
@@ -0,0 +1,1075 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The /find and /find-all picker: a query prompt, a result list, and a
|
|
3
|
+
* preview of the selected match. It searches the current session in memory
|
|
4
|
+
* and all sessions through the index worker, and never blocks on the index.
|
|
5
|
+
* In all sessions, the open session's hits come from memory, not the index.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import {
|
|
10
|
+
type Component,
|
|
11
|
+
type Focusable,
|
|
12
|
+
Input,
|
|
13
|
+
matchesKey,
|
|
14
|
+
type TUI,
|
|
15
|
+
truncateToWidth,
|
|
16
|
+
visibleWidth,
|
|
17
|
+
} from "@earendil-works/pi-tui";
|
|
18
|
+
|
|
19
|
+
import type { AllSessionsOutcome, CurrentSessionSearcher } from "./current-session-search.ts";
|
|
20
|
+
import {
|
|
21
|
+
kindLabel,
|
|
22
|
+
previewLines,
|
|
23
|
+
relativeAge,
|
|
24
|
+
sessionGroupHeaderText,
|
|
25
|
+
sessionLabel,
|
|
26
|
+
snippetLine,
|
|
27
|
+
} from "./display-text.ts";
|
|
28
|
+
import { hitKey, type SearchHit } from "./hits.ts";
|
|
29
|
+
import type { IndexSearcher, IndexUpdater } from "./index-client.ts";
|
|
30
|
+
import { copiedNoteText } from "./match-text.ts";
|
|
31
|
+
import { parseQuery, ROLE_FILTERS, type RoleFilter, termPatterns } from "./query.ts";
|
|
32
|
+
import type { SyncProgress } from "./session-index.ts";
|
|
33
|
+
|
|
34
|
+
export type FinderScope = "current" | "all";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* How the picker closed on a hit: `open` jumps to it (Enter), `insert` puts
|
|
38
|
+
* its text into the prompt editor (Alt-Enter).
|
|
39
|
+
*/
|
|
40
|
+
export interface FinderResult {
|
|
41
|
+
action: "open" | "insert";
|
|
42
|
+
hit: SearchHit;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface FinderOptions {
|
|
46
|
+
tui: TUI;
|
|
47
|
+
theme: Theme;
|
|
48
|
+
keybindings: KeybindingsManager;
|
|
49
|
+
/** Called once when the picker closes: with the chosen action, or undefined when cancelled. */
|
|
50
|
+
done: (result: FinderResult | undefined) => void;
|
|
51
|
+
/** The full, cleaned text of a hit; see readMatchText(). Rejects when it cannot be read. */
|
|
52
|
+
readMatchText: (hit: SearchHit) => Promise<string>;
|
|
53
|
+
/** Puts text on the system clipboard. Pi's copyToClipboard() in the extension. */
|
|
54
|
+
copyToClipboard: (text: string) => Promise<void>;
|
|
55
|
+
scope: FinderScope;
|
|
56
|
+
initialQuery: string;
|
|
57
|
+
current: CurrentSessionSearcher;
|
|
58
|
+
/** Index access for the all-sessions scope. Undefined when the index cannot run. */
|
|
59
|
+
index: { searcher: IndexSearcher; updater: IndexUpdater } | undefined;
|
|
60
|
+
homeDirectory: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Results requested from the index per search. */
|
|
64
|
+
const INDEX_RESULT_LIMIT = 200;
|
|
65
|
+
/** Most index results per session, so one long session cannot fill the list. */
|
|
66
|
+
const INDEX_PER_SESSION_LIMIT = 20;
|
|
67
|
+
/** Most current-session results listed; the status line shows the full count. */
|
|
68
|
+
const CURRENT_RESULT_LIMIT = 500;
|
|
69
|
+
/** Wait after a keystroke before searching, so fast typing sends one search. */
|
|
70
|
+
const CURRENT_DEBOUNCE_MS = 30;
|
|
71
|
+
const INDEX_DEBOUNCE_MS = 120;
|
|
72
|
+
/** Least time between result refreshes while the index is being updated. */
|
|
73
|
+
const INDEX_REFRESH_MS = 1200;
|
|
74
|
+
/** Rows of context kept above the first match when a preview opens. */
|
|
75
|
+
const PREVIEW_CONTEXT_ROWS = 2;
|
|
76
|
+
|
|
77
|
+
const ROLE_FILTER_LABELS: Record<RoleFilter, string> = {
|
|
78
|
+
all: "all",
|
|
79
|
+
user: "user",
|
|
80
|
+
assistant: "assistant",
|
|
81
|
+
tools: "tools",
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** The inputs of one search. Results are only acted on while they match what is on screen. */
|
|
85
|
+
interface SearchRequest {
|
|
86
|
+
queryText: string;
|
|
87
|
+
roleFilter: RoleFilter;
|
|
88
|
+
scope: FinderScope;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The hits of one session in the grouped all-sessions list. */
|
|
92
|
+
export interface SessionGroup {
|
|
93
|
+
/** Session file, or session id for an unsaved session. */
|
|
94
|
+
key: string;
|
|
95
|
+
/** A hit of the group, for its session name, cwd, and file. */
|
|
96
|
+
firstHit: SearchHit;
|
|
97
|
+
hitCount: number;
|
|
98
|
+
/** True when the search skipped further matches of this session. */
|
|
99
|
+
capped: boolean;
|
|
100
|
+
newestTimestamp: number;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface GroupedHits {
|
|
104
|
+
/** The hits reordered group by group; hit order is kept inside a group. */
|
|
105
|
+
hits: SearchHit[];
|
|
106
|
+
/** Groups in list order: the group with the newest hit first. */
|
|
107
|
+
groups: SessionGroup[];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** One row of the result list: a session header, or a hit by its index in the hit list. */
|
|
111
|
+
type ListRow = { kind: "header"; group: SessionGroup } | { kind: "hit"; hitIndex: number };
|
|
112
|
+
|
|
113
|
+
function groupKey(hit: SearchHit): string {
|
|
114
|
+
return hit.sessionFile ?? hit.sessionId;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Groups hits by session. Groups are ordered by their newest hit, ties kept in
|
|
119
|
+
* order of first appearance. `sessionsWithMore` holds the group keys of the
|
|
120
|
+
* capped sessions: the session file, or the session id when there is no file.
|
|
121
|
+
*/
|
|
122
|
+
export function groupHitsBySession(
|
|
123
|
+
hits: readonly SearchHit[],
|
|
124
|
+
sessionsWithMore: readonly string[],
|
|
125
|
+
): GroupedHits {
|
|
126
|
+
const capped = new Set(sessionsWithMore);
|
|
127
|
+
const members = new Map<string, SearchHit[]>();
|
|
128
|
+
for (const hit of hits) {
|
|
129
|
+
const key = groupKey(hit);
|
|
130
|
+
const list = members.get(key);
|
|
131
|
+
if (list === undefined) {
|
|
132
|
+
members.set(key, [hit]);
|
|
133
|
+
} else {
|
|
134
|
+
list.push(hit);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const groups: Array<SessionGroup & { members: SearchHit[] }> = [];
|
|
138
|
+
for (const [key, list] of members) {
|
|
139
|
+
const first = list[0] as SearchHit;
|
|
140
|
+
groups.push({
|
|
141
|
+
key,
|
|
142
|
+
firstHit: first,
|
|
143
|
+
hitCount: list.length,
|
|
144
|
+
capped: capped.has(key),
|
|
145
|
+
newestTimestamp: Math.max(...list.map((hit) => hit.timestamp)),
|
|
146
|
+
members: list,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
// Array.prototype.sort is stable, so equal ages keep their first-appearance order.
|
|
150
|
+
groups.sort((left, right) => right.newestTimestamp - left.newestTimestamp);
|
|
151
|
+
return {
|
|
152
|
+
hits: groups.flatMap((group) => group.members),
|
|
153
|
+
groups: groups.map(({ members: _members, ...group }) => group),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The all-sessions results after the current session's hits replace the index's. */
|
|
158
|
+
export interface MergedHits {
|
|
159
|
+
/** Newest first. */
|
|
160
|
+
hits: SearchHit[];
|
|
161
|
+
/** Group keys of the sessions with more matches than listed. */
|
|
162
|
+
sessionsWithMore: string[];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Replaces the index's hits of the open session with `current`, searched in
|
|
167
|
+
* memory, so its newest messages show before the index has them and nothing
|
|
168
|
+
* is listed twice. Both lists are newest first, and so is the merged list.
|
|
169
|
+
*/
|
|
170
|
+
export function mergeCurrentSessionHits(
|
|
171
|
+
indexHits: readonly SearchHit[],
|
|
172
|
+
indexSessionsWithMore: readonly string[],
|
|
173
|
+
current: Pick<CurrentSessionSearcher, "sessionKey" | "isSameSession">,
|
|
174
|
+
currentOutcome: AllSessionsOutcome,
|
|
175
|
+
): MergedHits {
|
|
176
|
+
const otherHits = indexHits.filter((hit) => !current.isSameSession(hit));
|
|
177
|
+
const hits: SearchHit[] = [];
|
|
178
|
+
let otherIndex = 0;
|
|
179
|
+
for (const currentHit of currentOutcome.hits) {
|
|
180
|
+
let other = otherHits[otherIndex];
|
|
181
|
+
while (other !== undefined && other.timestamp >= currentHit.timestamp) {
|
|
182
|
+
hits.push(other);
|
|
183
|
+
otherIndex += 1;
|
|
184
|
+
other = otherHits[otherIndex];
|
|
185
|
+
}
|
|
186
|
+
hits.push(currentHit);
|
|
187
|
+
}
|
|
188
|
+
hits.push(...otherHits.slice(otherIndex));
|
|
189
|
+
|
|
190
|
+
const sessionsWithMore = indexSessionsWithMore.filter((key) => key !== current.sessionKey);
|
|
191
|
+
if (currentOutcome.hasMore) {
|
|
192
|
+
sessionsWithMore.push(current.sessionKey);
|
|
193
|
+
}
|
|
194
|
+
return { hits, sessionsWithMore };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function sameRequest(left: SearchRequest | undefined, right: SearchRequest): boolean {
|
|
198
|
+
return (
|
|
199
|
+
left !== undefined &&
|
|
200
|
+
left.queryText === right.queryText &&
|
|
201
|
+
left.roleFilter === right.roleFilter &&
|
|
202
|
+
left.scope === right.scope
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export class FinderOverlay implements Component, Focusable {
|
|
207
|
+
private readonly options: FinderOptions;
|
|
208
|
+
private readonly input: Input;
|
|
209
|
+
private scope: FinderScope;
|
|
210
|
+
private roleFilter: RoleFilter = "all";
|
|
211
|
+
private hits: SearchHit[] = [];
|
|
212
|
+
/** What the list shows: hits, and session headers when the results are grouped. */
|
|
213
|
+
private rows: ListRow[] = [];
|
|
214
|
+
/** Row of each hit in `rows`, by hit index. */
|
|
215
|
+
private rowOfHit: number[] = [];
|
|
216
|
+
/** Session groups of the listed all-sessions results; empty for a flat list. */
|
|
217
|
+
private groups: SessionGroup[] = [];
|
|
218
|
+
/** The search that produced `hits`. Undefined until the first results arrive. */
|
|
219
|
+
private resultsRequest: SearchRequest | undefined;
|
|
220
|
+
/** The all-sessions search waiting for its reply. */
|
|
221
|
+
private pendingRequest: SearchRequest | undefined;
|
|
222
|
+
/** Increases with every search; replies from older searches are dropped. */
|
|
223
|
+
private searchGeneration = 0;
|
|
224
|
+
/** The query of the hit chosen with Enter, for finding it in the transcript. */
|
|
225
|
+
private acceptedQueryText: string | undefined;
|
|
226
|
+
/** True from the moment this picker starts or joins an index update until it ends. */
|
|
227
|
+
private followingIndexUpdate = false;
|
|
228
|
+
/** Shown once when Enter is pressed before the all-sessions results are current. */
|
|
229
|
+
private enterNote: string | undefined;
|
|
230
|
+
/** Outcome of the last copy, shown until the next key. */
|
|
231
|
+
private copyNote: { text: string; failed: boolean } | undefined;
|
|
232
|
+
/** Increases with every copy, so only the newest copy shows its outcome. */
|
|
233
|
+
private copyGeneration = 0;
|
|
234
|
+
private total = 0;
|
|
235
|
+
private truncated = false;
|
|
236
|
+
private fuzzy = false;
|
|
237
|
+
private searching = false;
|
|
238
|
+
private errorMessage: string | undefined;
|
|
239
|
+
/** Index in `hits` of the selected hit. Headers are never selected. */
|
|
240
|
+
private selected = 0;
|
|
241
|
+
/** First visible row, as an index in `rows`. */
|
|
242
|
+
private listTop = 0;
|
|
243
|
+
private previewTop: number | undefined;
|
|
244
|
+
private previewCache:
|
|
245
|
+
| { key: string; width: number; lines: string[]; firstMatchRow: number }
|
|
246
|
+
| undefined;
|
|
247
|
+
private indexProgress: SyncProgress | undefined;
|
|
248
|
+
private indexNote: string | undefined;
|
|
249
|
+
private searchTimer: ReturnType<typeof setTimeout> | undefined;
|
|
250
|
+
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
|
|
251
|
+
private lastIndexRefresh = 0;
|
|
252
|
+
private stopListening: (() => void) | undefined;
|
|
253
|
+
private closed = false;
|
|
254
|
+
private listHeight = 5;
|
|
255
|
+
private previewHeight = 5;
|
|
256
|
+
private isFocused = false;
|
|
257
|
+
|
|
258
|
+
constructor(options: FinderOptions) {
|
|
259
|
+
this.options = options;
|
|
260
|
+
this.scope = options.index === undefined ? "current" : options.scope;
|
|
261
|
+
this.input = new Input({ prompt: "> " });
|
|
262
|
+
typeInitialQuery(this.input, options.initialQuery);
|
|
263
|
+
if (this.scope === "all") {
|
|
264
|
+
this.startIndexUpdate();
|
|
265
|
+
}
|
|
266
|
+
this.runSearch();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The query that produced the chosen hit, used to find the message in the
|
|
271
|
+
* transcript after Enter. Before a hit is chosen: the query of the results
|
|
272
|
+
* on screen, else the typed text.
|
|
273
|
+
*/
|
|
274
|
+
get queryText(): string {
|
|
275
|
+
return this.acceptedQueryText ?? this.resultsRequest?.queryText ?? this.input.getValue();
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
get focused(): boolean {
|
|
279
|
+
return this.isFocused;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
set focused(value: boolean) {
|
|
283
|
+
this.isFocused = value;
|
|
284
|
+
this.input.focused = value;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
// Searching
|
|
289
|
+
|
|
290
|
+
private scheduleSearch(): void {
|
|
291
|
+
if (this.searchTimer !== undefined) {
|
|
292
|
+
clearTimeout(this.searchTimer);
|
|
293
|
+
}
|
|
294
|
+
const delay = this.scope === "current" ? CURRENT_DEBOUNCE_MS : INDEX_DEBOUNCE_MS;
|
|
295
|
+
this.searchTimer = setTimeout(() => {
|
|
296
|
+
this.searchTimer = undefined;
|
|
297
|
+
this.runSearch();
|
|
298
|
+
}, delay);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** What a search started now would use. */
|
|
302
|
+
private currentRequest(): SearchRequest {
|
|
303
|
+
return { queryText: this.input.getValue(), roleFilter: this.roleFilter, scope: this.scope };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* True when the listed results belong to the query, role filter, and scope
|
|
308
|
+
* on screen, and no search for newer input is due. A refresh of the same
|
|
309
|
+
* query while the index grows does not make them outdated.
|
|
310
|
+
*/
|
|
311
|
+
private resultsAreCurrent(): boolean {
|
|
312
|
+
return (
|
|
313
|
+
this.searchTimer === undefined && sameRequest(this.resultsRequest, this.currentRequest())
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Runs a debounced search now instead of waiting for its timer. */
|
|
318
|
+
private flushScheduledSearch(): void {
|
|
319
|
+
if (this.searchTimer !== undefined) {
|
|
320
|
+
clearTimeout(this.searchTimer);
|
|
321
|
+
this.searchTimer = undefined;
|
|
322
|
+
this.runSearch();
|
|
323
|
+
} else {
|
|
324
|
+
const request = this.currentRequest();
|
|
325
|
+
if (
|
|
326
|
+
!sameRequest(this.resultsRequest, request) &&
|
|
327
|
+
!(this.searching && sameRequest(this.pendingRequest, request))
|
|
328
|
+
) {
|
|
329
|
+
this.runSearch();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private runSearch(): void {
|
|
335
|
+
if (this.closed) {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
this.searchGeneration += 1;
|
|
339
|
+
const generation = this.searchGeneration;
|
|
340
|
+
const request = this.currentRequest();
|
|
341
|
+
this.errorMessage = undefined;
|
|
342
|
+
this.enterNote = undefined;
|
|
343
|
+
if (request.scope === "current") {
|
|
344
|
+
const outcome = this.options.current.search(
|
|
345
|
+
request.queryText,
|
|
346
|
+
request.roleFilter,
|
|
347
|
+
CURRENT_RESULT_LIMIT,
|
|
348
|
+
Date.now(),
|
|
349
|
+
);
|
|
350
|
+
this.searching = false;
|
|
351
|
+
this.showResults(request, outcome.hits, outcome.total, false, outcome.fuzzy);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const index = this.options.index;
|
|
356
|
+
if (index === undefined) {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
this.searching = true;
|
|
360
|
+
this.pendingRequest = request;
|
|
361
|
+
this.requestRender();
|
|
362
|
+
// Only the newest search may change the list, whether it succeeds or fails.
|
|
363
|
+
const isLatest = (): boolean => !this.closed && generation === this.searchGeneration;
|
|
364
|
+
// One clock reading for both sources, so since: and until: agree between them.
|
|
365
|
+
const now = Date.now();
|
|
366
|
+
index.searcher
|
|
367
|
+
.search(
|
|
368
|
+
request.queryText,
|
|
369
|
+
request.roleFilter,
|
|
370
|
+
INDEX_RESULT_LIMIT,
|
|
371
|
+
INDEX_PER_SESSION_LIMIT,
|
|
372
|
+
now,
|
|
373
|
+
)
|
|
374
|
+
.then(
|
|
375
|
+
(reply) => {
|
|
376
|
+
// undefined means a newer search replaced this one inside the searcher.
|
|
377
|
+
if (reply === undefined || !isLatest()) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
this.searching = false;
|
|
381
|
+
// Searched now, not when the index replied, so the open session is as fresh as possible.
|
|
382
|
+
const currentOutcome = this.options.current.searchForAllSessions(
|
|
383
|
+
request.queryText,
|
|
384
|
+
request.roleFilter,
|
|
385
|
+
INDEX_PER_SESSION_LIMIT,
|
|
386
|
+
now,
|
|
387
|
+
);
|
|
388
|
+
const merged = mergeCurrentSessionHits(
|
|
389
|
+
reply.hits,
|
|
390
|
+
reply.sessionsWithMore,
|
|
391
|
+
this.options.current,
|
|
392
|
+
currentOutcome,
|
|
393
|
+
);
|
|
394
|
+
this.showResults(
|
|
395
|
+
request,
|
|
396
|
+
merged.hits,
|
|
397
|
+
merged.hits.length,
|
|
398
|
+
reply.truncated,
|
|
399
|
+
false,
|
|
400
|
+
merged.sessionsWithMore,
|
|
401
|
+
);
|
|
402
|
+
},
|
|
403
|
+
(error: unknown) => {
|
|
404
|
+
if (!isLatest()) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
this.searching = false;
|
|
408
|
+
this.errorMessage = `Index search failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
409
|
+
this.showResults(request, [], 0, false, false);
|
|
410
|
+
},
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private showResults(
|
|
415
|
+
request: SearchRequest,
|
|
416
|
+
hits: SearchHit[],
|
|
417
|
+
total: number,
|
|
418
|
+
truncated: boolean,
|
|
419
|
+
fuzzy: boolean,
|
|
420
|
+
sessionsWithMore: readonly string[] = [],
|
|
421
|
+
): void {
|
|
422
|
+
const previous = this.hits[this.selected];
|
|
423
|
+
this.resultsRequest = request;
|
|
424
|
+
this.enterNote = undefined;
|
|
425
|
+
this.setHits(hits, request.scope === "all", sessionsWithMore);
|
|
426
|
+
this.total = total;
|
|
427
|
+
this.truncated = truncated;
|
|
428
|
+
this.fuzzy = fuzzy;
|
|
429
|
+
let nextSelected = 0;
|
|
430
|
+
if (previous !== undefined) {
|
|
431
|
+
const key = hitKey(previous);
|
|
432
|
+
const kept = this.hits.findIndex((hit) => hitKey(hit) === key);
|
|
433
|
+
nextSelected = kept >= 0 ? kept : 0;
|
|
434
|
+
}
|
|
435
|
+
this.select(nextSelected);
|
|
436
|
+
this.requestRender();
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Lists `hits`: grouped by session with a header row per group for the
|
|
441
|
+
* all-sessions scope, flat otherwise.
|
|
442
|
+
*/
|
|
443
|
+
private setHits(hits: SearchHit[], grouped: boolean, sessionsWithMore: readonly string[]): void {
|
|
444
|
+
this.rows = [];
|
|
445
|
+
this.rowOfHit = [];
|
|
446
|
+
if (!grouped) {
|
|
447
|
+
this.hits = hits;
|
|
448
|
+
this.groups = [];
|
|
449
|
+
for (let hitIndex = 0; hitIndex < hits.length; hitIndex += 1) {
|
|
450
|
+
this.rowOfHit.push(this.rows.length);
|
|
451
|
+
this.rows.push({ kind: "hit", hitIndex });
|
|
452
|
+
}
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const grouping = groupHitsBySession(hits, sessionsWithMore);
|
|
456
|
+
this.hits = grouping.hits;
|
|
457
|
+
this.groups = grouping.groups;
|
|
458
|
+
let hitIndex = 0;
|
|
459
|
+
for (const group of grouping.groups) {
|
|
460
|
+
this.rows.push({ kind: "header", group });
|
|
461
|
+
for (let member = 0; member < group.hitCount; member += 1) {
|
|
462
|
+
this.rowOfHit.push(this.rows.length);
|
|
463
|
+
this.rows.push({ kind: "hit", hitIndex });
|
|
464
|
+
hitIndex += 1;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Starts an index update, or joins the one already running (for example the
|
|
471
|
+
* startup update), so progress shows and results refresh when it ends.
|
|
472
|
+
*/
|
|
473
|
+
private startIndexUpdate(): void {
|
|
474
|
+
const index = this.options.index;
|
|
475
|
+
if (index === undefined || this.followingIndexUpdate) {
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
this.followingIndexUpdate = true;
|
|
479
|
+
if (this.stopListening === undefined) {
|
|
480
|
+
this.stopListening = index.updater.onProgress((progress) => {
|
|
481
|
+
this.indexProgress = progress;
|
|
482
|
+
if (progress.changed) {
|
|
483
|
+
this.scheduleIndexRefresh();
|
|
484
|
+
}
|
|
485
|
+
this.requestRender();
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
this.indexProgress = index.updater.progress;
|
|
489
|
+
this.indexNote = undefined;
|
|
490
|
+
index.updater.update().then(
|
|
491
|
+
(summary) => {
|
|
492
|
+
this.followingIndexUpdate = false;
|
|
493
|
+
this.indexProgress = undefined;
|
|
494
|
+
if (summary.failed > 0) {
|
|
495
|
+
this.indexNote = `${summary.failed} file(s) could not be indexed`;
|
|
496
|
+
}
|
|
497
|
+
if (summary.updated > 0 || summary.removed > 0) {
|
|
498
|
+
this.scheduleIndexRefresh(true);
|
|
499
|
+
}
|
|
500
|
+
this.requestRender();
|
|
501
|
+
},
|
|
502
|
+
(error: unknown) => {
|
|
503
|
+
this.followingIndexUpdate = false;
|
|
504
|
+
this.indexProgress = undefined;
|
|
505
|
+
this.indexNote = `index update failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
506
|
+
this.requestRender();
|
|
507
|
+
},
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Refreshes all-sessions results as new index data lands, at most every INDEX_REFRESH_MS. */
|
|
512
|
+
private scheduleIndexRefresh(immediate = false): void {
|
|
513
|
+
if (this.scope !== "all" || this.closed || this.refreshTimer !== undefined) {
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
const wait = immediate ? 0 : Math.max(0, this.lastIndexRefresh + INDEX_REFRESH_MS - Date.now());
|
|
517
|
+
this.refreshTimer = setTimeout(() => {
|
|
518
|
+
this.refreshTimer = undefined;
|
|
519
|
+
this.lastIndexRefresh = Date.now();
|
|
520
|
+
if (this.searchTimer === undefined) {
|
|
521
|
+
this.runSearch();
|
|
522
|
+
}
|
|
523
|
+
}, wait);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// ---------------------------------------------------------------------------
|
|
527
|
+
// Input
|
|
528
|
+
|
|
529
|
+
handleInput(data: string): void {
|
|
530
|
+
const { keybindings } = this.options;
|
|
531
|
+
this.copyNote = undefined;
|
|
532
|
+
if (
|
|
533
|
+
matchesKey(data, "escape") ||
|
|
534
|
+
matchesKey(data, "ctrl+c") ||
|
|
535
|
+
keybindings.matches(data, "tui.select.cancel")
|
|
536
|
+
) {
|
|
537
|
+
this.close(undefined);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
// Before Enter, so Alt-Enter never counts as a plain Enter.
|
|
541
|
+
if (matchesKey(data, "alt+enter")) {
|
|
542
|
+
this.accept("insert");
|
|
543
|
+
this.requestRender();
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (matchesKey(data, "enter") || keybindings.matches(data, "tui.select.confirm")) {
|
|
547
|
+
this.accept("open");
|
|
548
|
+
this.requestRender();
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
// Pi's copy key, the one /tree uses to copy the selected message (Ctrl-X by default).
|
|
552
|
+
if (matchesKey(data, "ctrl+x") || keybindings.matches(data, "app.message.copy")) {
|
|
553
|
+
this.copySelected();
|
|
554
|
+
this.requestRender();
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
if (
|
|
558
|
+
matchesKey(data, "up") ||
|
|
559
|
+
matchesKey(data, "ctrl+p") ||
|
|
560
|
+
matchesKey(data, "ctrl+k") ||
|
|
561
|
+
keybindings.matches(data, "tui.select.up")
|
|
562
|
+
) {
|
|
563
|
+
this.select(this.selected - 1);
|
|
564
|
+
} else if (
|
|
565
|
+
matchesKey(data, "down") ||
|
|
566
|
+
matchesKey(data, "ctrl+n") ||
|
|
567
|
+
matchesKey(data, "ctrl+j") ||
|
|
568
|
+
keybindings.matches(data, "tui.select.down")
|
|
569
|
+
) {
|
|
570
|
+
this.select(this.selected + 1);
|
|
571
|
+
} else if (matchesKey(data, "pageUp") || keybindings.matches(data, "tui.select.pageUp")) {
|
|
572
|
+
this.selectPage(-1);
|
|
573
|
+
} else if (matchesKey(data, "pageDown") || keybindings.matches(data, "tui.select.pageDown")) {
|
|
574
|
+
this.selectPage(1);
|
|
575
|
+
} else if (matchesKey(data, "ctrl+u")) {
|
|
576
|
+
this.scrollPreview(-Math.max(1, Math.floor(this.previewHeight / 2)));
|
|
577
|
+
} else if (matchesKey(data, "ctrl+d")) {
|
|
578
|
+
this.scrollPreview(Math.max(1, Math.floor(this.previewHeight / 2)));
|
|
579
|
+
} else if (matchesKey(data, "shift+tab")) {
|
|
580
|
+
this.cycleRoleFilter(-1);
|
|
581
|
+
} else if (matchesKey(data, "tab")) {
|
|
582
|
+
this.cycleRoleFilter(1);
|
|
583
|
+
} else if (matchesKey(data, "ctrl+s")) {
|
|
584
|
+
this.toggleScope();
|
|
585
|
+
} else {
|
|
586
|
+
const before = this.input.getValue();
|
|
587
|
+
this.input.handleInput(data);
|
|
588
|
+
if (this.input.getValue() !== before) {
|
|
589
|
+
this.scheduleSearch();
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
this.requestRender();
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Closes on the selected row with `action`, but never on one from outdated
|
|
597
|
+
* results. A search the debounce still holds runs first. The current session
|
|
598
|
+
* searches at once, so its fresh selection is used; an all-sessions search
|
|
599
|
+
* answers later, so the key waits for it and must be pressed again.
|
|
600
|
+
*/
|
|
601
|
+
private accept(action: FinderResult["action"]): void {
|
|
602
|
+
if (!this.resultsAreCurrent()) {
|
|
603
|
+
this.flushScheduledSearch();
|
|
604
|
+
if (!this.resultsAreCurrent()) {
|
|
605
|
+
this.enterNote =
|
|
606
|
+
action === "open"
|
|
607
|
+
? "results are updating; press Enter again"
|
|
608
|
+
: "results are updating; press Alt-Enter again";
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const hit = this.hits[this.selected];
|
|
613
|
+
if (hit !== undefined) {
|
|
614
|
+
this.acceptedQueryText = this.resultsRequest?.queryText;
|
|
615
|
+
this.close({ action, hit });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Copies the full text of the selected match and keeps the picker open. The
|
|
621
|
+
* status line then says how much was copied, or why copying failed.
|
|
622
|
+
*/
|
|
623
|
+
private copySelected(): void {
|
|
624
|
+
const hit = this.hits[this.selected];
|
|
625
|
+
if (hit === undefined) {
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
this.copyGeneration += 1;
|
|
629
|
+
const generation = this.copyGeneration;
|
|
630
|
+
const show = (note: { text: string; failed: boolean }): void => {
|
|
631
|
+
if (!this.closed && generation === this.copyGeneration) {
|
|
632
|
+
this.copyNote = note;
|
|
633
|
+
this.requestRender();
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
this.options
|
|
637
|
+
.readMatchText(hit)
|
|
638
|
+
.then(async (text) => {
|
|
639
|
+
await this.options.copyToClipboard(text);
|
|
640
|
+
return text;
|
|
641
|
+
})
|
|
642
|
+
.then(
|
|
643
|
+
(text) => show({ text: copiedNoteText(text), failed: false }),
|
|
644
|
+
(error: unknown) =>
|
|
645
|
+
show({
|
|
646
|
+
text: `Copy failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
647
|
+
failed: true,
|
|
648
|
+
}),
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Selects the hit with index `index` in `hits`, clamped to the list, and
|
|
654
|
+
* scrolls so its row stays visible. The group's header is kept in view too
|
|
655
|
+
* while it fits on screen with the selected row.
|
|
656
|
+
*/
|
|
657
|
+
private select(index: number): void {
|
|
658
|
+
const last = this.hits.length - 1;
|
|
659
|
+
const next = last < 0 ? 0 : Math.max(0, Math.min(last, index));
|
|
660
|
+
if (next !== this.selected) {
|
|
661
|
+
this.previewTop = undefined;
|
|
662
|
+
}
|
|
663
|
+
this.selected = next;
|
|
664
|
+
const row = this.rowOfHit[next] ?? 0;
|
|
665
|
+
if (row < this.listTop) {
|
|
666
|
+
this.listTop = row;
|
|
667
|
+
} else if (row >= this.listTop + this.listHeight) {
|
|
668
|
+
this.listTop = row - this.listHeight + 1;
|
|
669
|
+
}
|
|
670
|
+
const headerRow = this.headerRowAbove(row);
|
|
671
|
+
if (headerRow !== undefined && headerRow < this.listTop && row - headerRow < this.listHeight) {
|
|
672
|
+
this.listTop = headerRow;
|
|
673
|
+
}
|
|
674
|
+
this.listTop = Math.max(
|
|
675
|
+
0,
|
|
676
|
+
Math.min(this.listTop, Math.max(0, this.rows.length - this.listHeight)),
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Row of the header of the group that holds `row`. Undefined in a flat list. */
|
|
681
|
+
private headerRowAbove(row: number): number | undefined {
|
|
682
|
+
for (let index = row; index >= 0; index -= 1) {
|
|
683
|
+
if (this.rows[index]?.kind === "header") {
|
|
684
|
+
return index;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return undefined;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Moves the selection one page of rows up or down. Landing on a header
|
|
692
|
+
* selects the first hit below it, so headers are never selected.
|
|
693
|
+
*/
|
|
694
|
+
private selectPage(direction: 1 | -1): void {
|
|
695
|
+
if (this.rows.length === 0) {
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const currentRow = this.rowOfHit[this.selected] ?? 0;
|
|
699
|
+
let target = Math.max(
|
|
700
|
+
0,
|
|
701
|
+
Math.min(this.rows.length - 1, currentRow + direction * this.listHeight),
|
|
702
|
+
);
|
|
703
|
+
let row = this.rows[target];
|
|
704
|
+
while (row !== undefined && row.kind === "header") {
|
|
705
|
+
target += 1;
|
|
706
|
+
row = this.rows[target];
|
|
707
|
+
}
|
|
708
|
+
if (row !== undefined) {
|
|
709
|
+
this.select(row.hitIndex);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
private scrollPreview(rows: number): void {
|
|
714
|
+
const preview = this.previewCache;
|
|
715
|
+
if (preview === undefined) {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
const current = this.previewTop ?? this.initialPreviewTop(preview.firstMatchRow);
|
|
719
|
+
const maxTop = Math.max(0, preview.lines.length - this.previewHeight);
|
|
720
|
+
this.previewTop = Math.max(0, Math.min(maxTop, current + rows));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
private cycleRoleFilter(step: number): void {
|
|
724
|
+
const position = ROLE_FILTERS.indexOf(this.roleFilter);
|
|
725
|
+
const next = (position + step + ROLE_FILTERS.length) % ROLE_FILTERS.length;
|
|
726
|
+
this.roleFilter = ROLE_FILTERS[next] ?? "all";
|
|
727
|
+
this.runSearch();
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
private toggleScope(): void {
|
|
731
|
+
if (this.options.index === undefined) {
|
|
732
|
+
this.errorMessage = "The all-sessions index is not available.";
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
this.scope = this.scope === "current" ? "all" : "current";
|
|
736
|
+
this.setHits([], false, []);
|
|
737
|
+
this.total = 0;
|
|
738
|
+
this.truncated = false;
|
|
739
|
+
this.resultsRequest = undefined;
|
|
740
|
+
this.selected = 0;
|
|
741
|
+
this.listTop = 0;
|
|
742
|
+
this.previewTop = undefined;
|
|
743
|
+
if (this.searchTimer !== undefined) {
|
|
744
|
+
clearTimeout(this.searchTimer);
|
|
745
|
+
this.searchTimer = undefined;
|
|
746
|
+
}
|
|
747
|
+
if (this.scope === "all") {
|
|
748
|
+
// Joins an update that is already running, such as the startup one.
|
|
749
|
+
this.startIndexUpdate();
|
|
750
|
+
}
|
|
751
|
+
this.runSearch();
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
private close(result: FinderResult | undefined): void {
|
|
755
|
+
if (this.closed) {
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
this.closed = true;
|
|
759
|
+
this.dispose();
|
|
760
|
+
this.options.done(result);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
dispose(): void {
|
|
764
|
+
if (this.searchTimer !== undefined) {
|
|
765
|
+
clearTimeout(this.searchTimer);
|
|
766
|
+
this.searchTimer = undefined;
|
|
767
|
+
}
|
|
768
|
+
if (this.refreshTimer !== undefined) {
|
|
769
|
+
clearTimeout(this.refreshTimer);
|
|
770
|
+
this.refreshTimer = undefined;
|
|
771
|
+
}
|
|
772
|
+
this.stopListening?.();
|
|
773
|
+
this.stopListening = undefined;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
private requestRender(): void {
|
|
777
|
+
if (!this.closed) {
|
|
778
|
+
this.options.tui.requestRender();
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// ---------------------------------------------------------------------------
|
|
783
|
+
// Rendering
|
|
784
|
+
|
|
785
|
+
invalidate(): void {
|
|
786
|
+
this.previewCache = undefined;
|
|
787
|
+
this.input.invalidate();
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
render(width: number): string[] {
|
|
791
|
+
const { theme } = this.options;
|
|
792
|
+
const inner = Math.max(10, width - 4);
|
|
793
|
+
const totalHeight = Math.max(12, Math.floor(this.options.tui.terminal.rows * 0.8));
|
|
794
|
+
// Rows used by borders, the prompt, separators, and the hint line.
|
|
795
|
+
const fixedRows = 7;
|
|
796
|
+
const flexible = Math.max(6, totalHeight - fixedRows);
|
|
797
|
+
this.listHeight = Math.max(3, Math.floor(flexible * 0.45));
|
|
798
|
+
this.previewHeight = Math.max(3, flexible - this.listHeight);
|
|
799
|
+
this.select(this.selected);
|
|
800
|
+
|
|
801
|
+
const border = (text: string): string => theme.fg("border", text);
|
|
802
|
+
const row = (content: string): string => {
|
|
803
|
+
const fitted = truncateToWidth(content, inner);
|
|
804
|
+
const padding = " ".repeat(Math.max(0, inner - visibleWidth(fitted)));
|
|
805
|
+
return `${border("│")} ${fitted}${padding} ${border("│")}`;
|
|
806
|
+
};
|
|
807
|
+
const rule = (label: string): string => {
|
|
808
|
+
const title = label === "" ? "" : ` ${label} `;
|
|
809
|
+
const fitted = truncateToWidth(title, inner);
|
|
810
|
+
return border(`├─${fitted}${"─".repeat(Math.max(0, inner - visibleWidth(fitted)))}─┤`);
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
const lines: string[] = [];
|
|
814
|
+
const title = truncateToWidth(` ${this.titleText()} `, inner);
|
|
815
|
+
lines.push(border(`╭─${title}${"─".repeat(Math.max(0, inner - visibleWidth(title)))}─╮`));
|
|
816
|
+
lines.push(row(this.input.render(inner)[0] ?? ""));
|
|
817
|
+
lines.push(rule(this.statusText()));
|
|
818
|
+
lines.push(...this.renderList(inner).map(row));
|
|
819
|
+
lines.push(rule(this.previewTitle()));
|
|
820
|
+
lines.push(...this.renderPreview(inner).map(row));
|
|
821
|
+
lines.push(rule(""));
|
|
822
|
+
lines.push(row(theme.fg("dim", this.hintText())));
|
|
823
|
+
lines.push(border(`╰${"─".repeat(inner + 2)}╯`));
|
|
824
|
+
return lines;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
private titleText(): string {
|
|
828
|
+
const { theme } = this.options;
|
|
829
|
+
const scope = this.scope === "current" ? "Find in this session" : "Find in all sessions";
|
|
830
|
+
const role =
|
|
831
|
+
this.roleFilter === "all"
|
|
832
|
+
? ""
|
|
833
|
+
: theme.fg("warning", ` [${ROLE_FILTER_LABELS[this.roleFilter]}]`);
|
|
834
|
+
return `${theme.fg("accent", theme.bold(scope))}${role}`;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
private statusText(): string {
|
|
838
|
+
const { theme } = this.options;
|
|
839
|
+
const parts: string[] = [];
|
|
840
|
+
if (this.errorMessage !== undefined) {
|
|
841
|
+
parts.push(theme.fg("error", this.errorMessage));
|
|
842
|
+
} else if (this.searching && this.hits.length === 0) {
|
|
843
|
+
parts.push("searching…");
|
|
844
|
+
} else {
|
|
845
|
+
parts.push(
|
|
846
|
+
matchCountText(
|
|
847
|
+
this.hits.length,
|
|
848
|
+
this.total,
|
|
849
|
+
this.truncated,
|
|
850
|
+
this.groups.length > 0 ? this.groups.length : undefined,
|
|
851
|
+
),
|
|
852
|
+
);
|
|
853
|
+
if (this.fuzzy) {
|
|
854
|
+
parts.push(theme.fg("warning", "fuzzy"));
|
|
855
|
+
}
|
|
856
|
+
if (this.searching) {
|
|
857
|
+
parts.push("searching…");
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
if (this.enterNote !== undefined) {
|
|
861
|
+
parts.push(theme.fg("warning", this.enterNote));
|
|
862
|
+
}
|
|
863
|
+
if (this.copyNote !== undefined) {
|
|
864
|
+
parts.push(theme.fg(this.copyNote.failed ? "error" : "success", this.copyNote.text));
|
|
865
|
+
}
|
|
866
|
+
const typedQuery = parseQuery(this.input.getValue());
|
|
867
|
+
// An unreadable since: or until: is ignored; say so instead of matching nothing.
|
|
868
|
+
for (const note of typedQuery.invalidFilterNotes ?? []) {
|
|
869
|
+
parts.push(theme.fg("warning", note));
|
|
870
|
+
}
|
|
871
|
+
if (this.scope === "current" && typedQuery.cwd !== undefined) {
|
|
872
|
+
parts.push(theme.fg("warning", "cwd: applies only to all sessions (^s)"));
|
|
873
|
+
}
|
|
874
|
+
if (this.scope === "all") {
|
|
875
|
+
if (this.indexProgress !== undefined) {
|
|
876
|
+
parts.push(`indexing ${this.indexProgress.done}/${this.indexProgress.total}`);
|
|
877
|
+
} else if (this.indexNote !== undefined) {
|
|
878
|
+
parts.push(this.indexNote);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return theme.fg("muted", parts.join(" · "));
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
private hintText(): string {
|
|
885
|
+
return "↑↓ move · tab role · ^s scope · ^u/^d preview · enter open · alt+enter insert · ^x copy · esc close";
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
private highlight = (part: string): string => {
|
|
889
|
+
const { theme } = this.options;
|
|
890
|
+
return theme.fg("warning", theme.bold(part));
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
private renderList(width: number): string[] {
|
|
894
|
+
const { theme } = this.options;
|
|
895
|
+
const rows: string[] = [];
|
|
896
|
+
const patterns = this.highlightPatterns();
|
|
897
|
+
const now = Date.now();
|
|
898
|
+
const roleWidth = 13;
|
|
899
|
+
|
|
900
|
+
for (let offset = 0; offset < this.listHeight; offset += 1) {
|
|
901
|
+
const listRow = this.rows[this.listTop + offset];
|
|
902
|
+
if (listRow?.kind === "header") {
|
|
903
|
+
rows.push(this.renderGroupHeader(listRow.group, width, now));
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
const index = listRow?.hitIndex ?? -1;
|
|
907
|
+
const hit = this.hits[index];
|
|
908
|
+
if (hit === undefined) {
|
|
909
|
+
rows.push(
|
|
910
|
+
offset === 0 && this.hits.length === 0 && !this.searching
|
|
911
|
+
? theme.fg("dim", " no matches")
|
|
912
|
+
: "",
|
|
913
|
+
);
|
|
914
|
+
continue;
|
|
915
|
+
}
|
|
916
|
+
const isSelected = index === this.selected;
|
|
917
|
+
const marker = isSelected ? theme.fg("accent", "▸ ") : " ";
|
|
918
|
+
const role = truncateToWidth(kindLabel(hit), roleWidth, "…", true);
|
|
919
|
+
|
|
920
|
+
const metaParts: string[] = [];
|
|
921
|
+
if (!hit.onActiveBranch) {
|
|
922
|
+
metaParts.push("branch");
|
|
923
|
+
}
|
|
924
|
+
// The session label is in the group header, so the snippet gets its width.
|
|
925
|
+
metaParts.push(relativeAge(hit.timestamp, now).padStart(3));
|
|
926
|
+
const meta = metaParts.join(" ");
|
|
927
|
+
|
|
928
|
+
const snippetWidth = Math.max(4, width - 2 - roleWidth - 1 - visibleWidth(meta) - 2);
|
|
929
|
+
const snippet = snippetLine(hit.text, patterns, snippetWidth, this.highlight);
|
|
930
|
+
const gap = " ".repeat(Math.max(1, snippetWidth - visibleWidth(snippet) + 1));
|
|
931
|
+
const roleColored = theme.fg(roleColor(hit.kind), role);
|
|
932
|
+
let line = `${marker}${roleColored} ${snippet}${gap}${theme.fg("dim", meta)}`;
|
|
933
|
+
line = truncateToWidth(line, width);
|
|
934
|
+
if (isSelected) {
|
|
935
|
+
line = selectedRow(theme, line + " ".repeat(Math.max(0, width - visibleWidth(line))));
|
|
936
|
+
}
|
|
937
|
+
rows.push(line);
|
|
938
|
+
}
|
|
939
|
+
return rows;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/** A session header row; never selected. */
|
|
943
|
+
private renderGroupHeader(group: SessionGroup, width: number, now: number): string {
|
|
944
|
+
const { theme } = this.options;
|
|
945
|
+
const hit = group.firstHit;
|
|
946
|
+
const isCurrentSession = this.options.current.isSameSession(hit);
|
|
947
|
+
const text = sessionGroupHeaderText(
|
|
948
|
+
{
|
|
949
|
+
label: sessionLabel(hit, this.options.homeDirectory),
|
|
950
|
+
hitCount: group.hitCount,
|
|
951
|
+
capped: group.capped,
|
|
952
|
+
newestTimestamp: group.newestTimestamp,
|
|
953
|
+
isCurrentSession,
|
|
954
|
+
},
|
|
955
|
+
width,
|
|
956
|
+
now,
|
|
957
|
+
);
|
|
958
|
+
return theme.bold(theme.fg(isCurrentSession ? "accent" : "muted", text));
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** The query of the listed results; highlights follow it, not text typed since. */
|
|
962
|
+
private resultsQueryText(): string {
|
|
963
|
+
return this.resultsRequest?.queryText ?? this.input.getValue();
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
private highlightPatterns(): RegExp[] {
|
|
967
|
+
return termPatterns(parseQuery(this.resultsQueryText()));
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
private previewTitle(): string {
|
|
971
|
+
const { theme } = this.options;
|
|
972
|
+
const hit = this.hits[this.selected];
|
|
973
|
+
if (hit === undefined) {
|
|
974
|
+
return "";
|
|
975
|
+
}
|
|
976
|
+
const parts = [kindLabel(hit)];
|
|
977
|
+
if (hit.timestamp > 0) {
|
|
978
|
+
parts.push(new Date(hit.timestamp).toLocaleString());
|
|
979
|
+
}
|
|
980
|
+
if (this.scope === "all") {
|
|
981
|
+
parts.push(sessionLabel(hit, this.options.homeDirectory));
|
|
982
|
+
}
|
|
983
|
+
if (!hit.onActiveBranch) {
|
|
984
|
+
parts.push("on another branch");
|
|
985
|
+
}
|
|
986
|
+
return theme.fg("muted", parts.join(" · "));
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
private renderPreview(width: number): string[] {
|
|
990
|
+
const hit = this.hits[this.selected];
|
|
991
|
+
if (hit === undefined) {
|
|
992
|
+
return Array.from({ length: this.previewHeight }, () => "");
|
|
993
|
+
}
|
|
994
|
+
const key = `${hitKey(hit)}|${this.resultsQueryText()}`;
|
|
995
|
+
if (
|
|
996
|
+
this.previewCache === undefined ||
|
|
997
|
+
this.previewCache.key !== key ||
|
|
998
|
+
this.previewCache.width !== width
|
|
999
|
+
) {
|
|
1000
|
+
const patterns = this.highlightPatterns();
|
|
1001
|
+
const built = previewLines(hit, patterns, width, this.highlight);
|
|
1002
|
+
this.previewCache = { key, width, lines: built.lines, firstMatchRow: built.firstMatchRow };
|
|
1003
|
+
}
|
|
1004
|
+
const preview = this.previewCache;
|
|
1005
|
+
const maxTop = Math.max(0, preview.lines.length - this.previewHeight);
|
|
1006
|
+
const top = Math.min(maxTop, this.previewTop ?? this.initialPreviewTop(preview.firstMatchRow));
|
|
1007
|
+
const rows = preview.lines.slice(top, top + this.previewHeight);
|
|
1008
|
+
while (rows.length < this.previewHeight) {
|
|
1009
|
+
rows.push("");
|
|
1010
|
+
}
|
|
1011
|
+
return rows;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
private initialPreviewTop(firstMatchRow: number): number {
|
|
1015
|
+
return Math.max(0, firstMatchRow - PREVIEW_CONTEXT_ROWS);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/**
|
|
1020
|
+
* Types the query from the command line one character at a time, so the
|
|
1021
|
+
* cursor ends up after it, as if the user had typed it. Input.setValue()
|
|
1022
|
+
* would leave the cursor at the start. Control characters become spaces.
|
|
1023
|
+
*/
|
|
1024
|
+
function typeInitialQuery(input: Input, query: string): void {
|
|
1025
|
+
// oxlint-disable-next-line no-control-regex -- replacing control characters is the point.
|
|
1026
|
+
const printable = query.replace(/[\u0000-\u001f\u007f]/gu, " ");
|
|
1027
|
+
for (const character of printable) {
|
|
1028
|
+
input.handleInput(character);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* Status text for the result count: "3 matches", "200+ matches" when the
|
|
1034
|
+
* index stopped early, or "showing 500 of 812 matches" when the list is capped.
|
|
1035
|
+
* With `sessions`, the grouped list adds where they are: "86 matches in 7 sessions".
|
|
1036
|
+
*/
|
|
1037
|
+
export function matchCountText(
|
|
1038
|
+
listed: number,
|
|
1039
|
+
total: number,
|
|
1040
|
+
truncated: boolean,
|
|
1041
|
+
sessions?: number,
|
|
1042
|
+
): string {
|
|
1043
|
+
const where =
|
|
1044
|
+
sessions === undefined ? "" : ` in ${sessions} ${sessions === 1 ? "session" : "sessions"}`;
|
|
1045
|
+
if (truncated) {
|
|
1046
|
+
return `${listed}+ matches${where}`;
|
|
1047
|
+
}
|
|
1048
|
+
const noun = total === 1 ? "match" : "matches";
|
|
1049
|
+
if (listed < total) {
|
|
1050
|
+
return `showing ${listed} of ${total} ${noun}${where}`;
|
|
1051
|
+
}
|
|
1052
|
+
return `${total} ${noun}${where}`;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/**
|
|
1056
|
+
* Paints the selected row. Truncation inserts full style resets, which would
|
|
1057
|
+
* end the background early, so the background is applied again after each one.
|
|
1058
|
+
*/
|
|
1059
|
+
function selectedRow(theme: Theme, line: string): string {
|
|
1060
|
+
const background = theme.getBgAnsi("selectedBg");
|
|
1061
|
+
return theme.bg("selectedBg", line.replaceAll("\u001b[0m", `\u001b[0m${background}`));
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function roleColor(kind: SearchHit["kind"]): "accent" | "success" | "muted" | "warning" {
|
|
1065
|
+
switch (kind) {
|
|
1066
|
+
case "user":
|
|
1067
|
+
return "accent";
|
|
1068
|
+
case "assistant":
|
|
1069
|
+
return "success";
|
|
1070
|
+
case "shell":
|
|
1071
|
+
return "warning";
|
|
1072
|
+
default:
|
|
1073
|
+
return "muted";
|
|
1074
|
+
}
|
|
1075
|
+
}
|