@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.
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Text helpers for the picker: labels, ages, one-line snippets, and the
3
+ * wrapped, highlighted preview. Styling comes in as functions so tests can
4
+ * check the output without a theme.
5
+ */
6
+
7
+ import {
8
+ stripTerminalSequences,
9
+ truncateToWidth,
10
+ visibleWidth,
11
+ wrapTextWithAnsi,
12
+ } from "@earendil-works/pi-tui";
13
+
14
+ import type { SearchHit } from "./hits.ts";
15
+ import { findTermRanges, bestMatchIndex, type TextRange } from "./query.ts";
16
+
17
+ /** Short label for the kind of a hit, such as "user" or "call bash". */
18
+ export function kindLabel(hit: Pick<SearchHit, "kind" | "toolName">): string {
19
+ switch (hit.kind) {
20
+ case "user":
21
+ return "user";
22
+ case "assistant":
23
+ return "assistant";
24
+ case "shell":
25
+ return "shell";
26
+ case "toolCall":
27
+ return hit.toolName === undefined ? "call" : `call ${shortToolName(hit.toolName)}`;
28
+ case "toolResult":
29
+ return hit.toolName === undefined ? "result" : `result ${shortToolName(hit.toolName)}`;
30
+ default:
31
+ return hit.kind satisfies never;
32
+ }
33
+ }
34
+
35
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
36
+
37
+ /** Splits text into user-perceived characters, so emoji sequences stay whole. */
38
+ function graphemes(text: string): string[] {
39
+ return Array.from(graphemeSegmenter.segment(text), (each) => each.segment);
40
+ }
41
+
42
+ /** Drops namespaces such as "mcp__server__" so labels stay short. */
43
+ function shortToolName(name: string): string {
44
+ const separator = name.lastIndexOf("__");
45
+ return separator >= 0 ? name.slice(separator + 2) : name;
46
+ }
47
+
48
+ /** Compact age such as "now", "5m", "3h", "2d", "7mo", or "1y". */
49
+ export function relativeAge(timestamp: number, now: number): string {
50
+ if (timestamp <= 0) {
51
+ return "";
52
+ }
53
+ const seconds = Math.max(0, Math.round((now - timestamp) / 1000));
54
+ if (seconds < 60) {
55
+ return "now";
56
+ }
57
+ const minutes = Math.floor(seconds / 60);
58
+ if (minutes < 60) {
59
+ return `${minutes}m`;
60
+ }
61
+ const hours = Math.floor(minutes / 60);
62
+ if (hours < 24) {
63
+ return `${hours}h`;
64
+ }
65
+ const days = Math.floor(hours / 24);
66
+ if (days < 30) {
67
+ return `${days}d`;
68
+ }
69
+ if (days < 365) {
70
+ return `${Math.floor(days / 30)}mo`;
71
+ }
72
+ return `${Math.floor(days / 365)}y`;
73
+ }
74
+
75
+ /** Session name, or its working directory with the home folder shortened to "~". */
76
+ export function sessionLabel(
77
+ hit: Pick<SearchHit, "sessionName" | "cwd">,
78
+ homeDirectory: string,
79
+ ): string {
80
+ if (hit.sessionName !== undefined && hit.sessionName.trim() !== "") {
81
+ return hit.sessionName.trim();
82
+ }
83
+ if (
84
+ homeDirectory !== "" &&
85
+ (hit.cwd === homeDirectory || hit.cwd.startsWith(`${homeDirectory}/`))
86
+ ) {
87
+ return `~${hit.cwd.slice(homeDirectory.length)}`;
88
+ }
89
+ return hit.cwd;
90
+ }
91
+
92
+ /** Truncates from the left, keeping the end of a path visible. */
93
+ export function truncateStart(text: string, width: number): string {
94
+ if (width <= 0) {
95
+ return "";
96
+ }
97
+ if (visibleWidth(text) <= width) {
98
+ return text;
99
+ }
100
+ let kept = "";
101
+ const characters = graphemes(text);
102
+ for (let index = characters.length - 1; index >= 0; index -= 1) {
103
+ const next = `${characters[index]}${kept}`;
104
+ if (visibleWidth(next) > width - 1) {
105
+ break;
106
+ }
107
+ kept = next;
108
+ }
109
+ return `…${kept}`;
110
+ }
111
+
112
+ /**
113
+ * Removes terminal escapes and control characters that would break the
114
+ * picker's layout. Tabs become spaces. Newlines stay.
115
+ */
116
+ export function cleanForDisplay(text: string): string {
117
+ return (
118
+ stripTerminalSequences(text)
119
+ .replace(/\r\n?/gu, "\n")
120
+ .replace(/\t/gu, " ")
121
+ // oxlint-disable-next-line no-control-regex -- removing control characters is the point.
122
+ .replace(/[\u0000-\u0009\u000b-\u001f\u007f]/gu, "")
123
+ );
124
+ }
125
+
126
+ /** Wraps each range with `style`. Ranges must be sorted and must not overlap. */
127
+ export function applyRanges(
128
+ text: string,
129
+ ranges: readonly TextRange[],
130
+ style: (part: string) => string,
131
+ ): string {
132
+ if (ranges.length === 0) {
133
+ return text;
134
+ }
135
+ let output = "";
136
+ let cursor = 0;
137
+ for (const range of ranges) {
138
+ const start = Math.max(range.start, cursor);
139
+ const end = Math.min(range.end, text.length);
140
+ if (end <= start) {
141
+ continue;
142
+ }
143
+ output += text.slice(cursor, start) + style(text.slice(start, end));
144
+ cursor = end;
145
+ }
146
+ return output + text.slice(cursor);
147
+ }
148
+
149
+ /** Most columns of context shown before the first match in a one-line snippet. */
150
+ const SNIPPET_LEAD_COLUMNS = 24;
151
+
152
+ /** Collapses runs of whitespace, including newlines, to single spaces. */
153
+ function collapseWhitespace(text: string): string {
154
+ return text.replace(/\s+/gu, " ");
155
+ }
156
+
157
+ /**
158
+ * Columns of context to keep before the match: at most a third of the width,
159
+ * and never so many that the match and the closing "…" stop fitting.
160
+ */
161
+ export function snippetLeadColumns(width: number, matchColumns = 0): number {
162
+ const roomBesideMatch = width - matchColumns - 1;
163
+ return Math.max(0, Math.min(SNIPPET_LEAD_COLUMNS, Math.floor(width / 3), roomBesideMatch));
164
+ }
165
+
166
+ /**
167
+ * One line of text around the first match, whitespace collapsed, highlighted,
168
+ * and cut to `width` columns. The context before the match is budgeted in
169
+ * display columns, "…" included, so the match stays visible at any width.
170
+ */
171
+ export function snippetLine(
172
+ text: string,
173
+ patterns: RegExp[],
174
+ width: number,
175
+ highlight: (part: string) => string,
176
+ ): string {
177
+ if (width <= 0) {
178
+ return "";
179
+ }
180
+ const cleaned = cleanForDisplay(text);
181
+ const matchAt = bestMatchIndex(cleaned, patterns);
182
+ // Collapse each side on its own so the match position stays known.
183
+ const before = collapseWhitespace(cleaned.slice(0, matchAt)).trimStart();
184
+ const after = collapseWhitespace(cleaned.slice(matchAt, matchAt + width * 4 + 64));
185
+
186
+ const firstRange = findTermRanges(after, patterns, 64)[0];
187
+ const matchColumns =
188
+ firstRange !== undefined && firstRange.start === 0
189
+ ? visibleWidth(after.slice(0, firstRange.end))
190
+ : 0;
191
+ // When the text after the match is short, spend the spare width on the lead,
192
+ // so a line that fits is shown whole.
193
+ const budget = Math.max(
194
+ snippetLeadColumns(width, matchColumns),
195
+ width - visibleWidth(after.trimEnd()),
196
+ );
197
+ const beforeCharacters = graphemes(before);
198
+ let start = beforeCharacters.length;
199
+ let used = 0;
200
+ while (start > 0) {
201
+ const next = visibleWidth(beforeCharacters[start - 1] as string);
202
+ // When text is cut off in front, "…" takes one column of the budget.
203
+ const ellipsis = start - 1 > 0 ? 1 : 0;
204
+ if (used + next + ellipsis > budget) {
205
+ break;
206
+ }
207
+ used += next;
208
+ start -= 1;
209
+ }
210
+ let lead = beforeCharacters.slice(start).join("");
211
+ if (start > 0) {
212
+ // Begin at a word boundary so the snippet does not open mid-word.
213
+ const space = lead.indexOf(" ");
214
+ if (space >= 0) {
215
+ lead = lead.slice(space + 1);
216
+ }
217
+ lead = `…${lead}`;
218
+ }
219
+ const flattened = lead === "" ? after.trimStart() : `${lead}${after}`;
220
+ const ranges = findTermRanges(flattened, patterns, 64);
221
+ return truncateToWidth(applyRanges(flattened, ranges, highlight), width, "…");
222
+ }
223
+
224
+ export interface PreviewLines {
225
+ lines: string[];
226
+ /** Index in `lines` of the first row that shows a match. */
227
+ firstMatchRow: number;
228
+ }
229
+
230
+ /** Most wrapped rows a preview builds; enough for any terminal height. */
231
+ const MAX_PREVIEW_ROWS = 2000;
232
+
233
+ /** Stand-ins for a matched character while finding its wrapped row; they never break or join words. */
234
+ const NARROW_MARKER = "\u{F0000}";
235
+ const WIDE_MARKER = "\u3007";
236
+
237
+ /**
238
+ * The wrapped row, counted from 0, on which the character at `index` of
239
+ * `line` lands, when `line` is styled with `ranges` and wrapped to `width`.
240
+ * Wraps a copy where that character is swapped for a marker of the same
241
+ * width, so the breaks are unchanged, then finds the marker.
242
+ */
243
+ function wrappedRowOf(
244
+ line: string,
245
+ index: number,
246
+ ranges: readonly TextRange[],
247
+ width: number,
248
+ highlight: (part: string) => string,
249
+ ): number {
250
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
251
+ let character = "";
252
+ let at = index;
253
+ for (const { segment, index: segmentIndex } of segmenter.segment(line.slice(index))) {
254
+ if (!/\s/u.test(segment)) {
255
+ character = segment;
256
+ at = index + segmentIndex;
257
+ break;
258
+ }
259
+ }
260
+ if (character === "") {
261
+ return 0;
262
+ }
263
+ const marker = visibleWidth(character) >= 2 ? WIDE_MARKER : NARROW_MARKER;
264
+ const markersBefore = line.slice(0, at).split(marker).length - 1;
265
+ const marked = `${line.slice(0, at)}${marker}${line.slice(at + character.length)}`;
266
+ // The swap changes lengths only when the grapheme and marker differ in UTF-16 length; shift later ranges to match.
267
+ const shift = marker.length - character.length;
268
+ const shifted = ranges.map((range) => ({
269
+ start: range.start > at ? range.start + shift : range.start,
270
+ end: range.end > at ? range.end + shift : range.end,
271
+ }));
272
+ const wrapped = wrapTextWithAnsi(applyRanges(marked, shifted, highlight), Math.max(1, width));
273
+ let seen = 0;
274
+ for (let row = 0; row < wrapped.length; row += 1) {
275
+ const count = (wrapped[row] as string).split(marker).length - 1;
276
+ if (seen + count > markersBefore) {
277
+ return row;
278
+ }
279
+ seen += count;
280
+ }
281
+ return 0;
282
+ }
283
+
284
+ /**
285
+ * Wraps the hit text to `width` with matches highlighted, and reports where the
286
+ * first match landed so the preview can open there.
287
+ */
288
+ export function previewLines(
289
+ hit: Pick<SearchHit, "text" | "clippedStart" | "clippedEnd">,
290
+ patterns: RegExp[],
291
+ width: number,
292
+ highlight: (part: string) => string,
293
+ ): PreviewLines {
294
+ const cleaned = cleanForDisplay(hit.text);
295
+ const ranges = findTermRanges(cleaned, patterns);
296
+ const lines: string[] = [];
297
+ if (hit.clippedStart) {
298
+ lines.push("…");
299
+ }
300
+ let firstMatchRow = -1;
301
+ let lineStart = 0;
302
+ let rangeIndex = 0;
303
+
304
+ for (const logicalLine of cleaned.split("\n")) {
305
+ const lineEnd = lineStart + logicalLine.length;
306
+ const lineRanges: TextRange[] = [];
307
+ while (rangeIndex < ranges.length && (ranges[rangeIndex] as TextRange).end <= lineStart) {
308
+ rangeIndex += 1;
309
+ }
310
+ for (let index = rangeIndex; index < ranges.length; index += 1) {
311
+ const range = ranges[index] as TextRange;
312
+ if (range.start >= lineEnd) {
313
+ break;
314
+ }
315
+ lineRanges.push({
316
+ start: Math.max(0, range.start - lineStart),
317
+ end: Math.min(logicalLine.length, range.end - lineStart),
318
+ });
319
+ }
320
+ const styled = applyRanges(logicalLine, lineRanges, highlight);
321
+ const wrapped = styled === "" ? [""] : wrapTextWithAnsi(styled, Math.max(1, width));
322
+ const firstRange = lineRanges[0];
323
+ if (firstRange !== undefined && firstMatchRow < 0) {
324
+ firstMatchRow =
325
+ lines.length + wrappedRowOf(logicalLine, firstRange.start, lineRanges, width, highlight);
326
+ }
327
+ lines.push(...wrapped);
328
+ if (lines.length >= MAX_PREVIEW_ROWS) {
329
+ lines.length = MAX_PREVIEW_ROWS;
330
+ lines.push("…");
331
+ break;
332
+ }
333
+ lineStart = lineEnd + 1;
334
+ }
335
+ if (hit.clippedEnd && lines[lines.length - 1] !== "…") {
336
+ lines.push("…");
337
+ }
338
+ return { lines, firstMatchRow: Math.max(0, Math.min(firstMatchRow, lines.length - 1)) };
339
+ }
340
+
341
+ /** What a session header in the /find-all list shows. */
342
+ export interface SessionGroupHeader {
343
+ /** Session name, or working directory; see sessionLabel(). */
344
+ label: string;
345
+ /** Hits listed in the group. */
346
+ hitCount: number;
347
+ /** True when the session had more matches than the per-session cap. */
348
+ capped: boolean;
349
+ /** Timestamp of the group's newest hit, 0 when unknown. */
350
+ newestTimestamp: number;
351
+ /** True for the session open in pi. */
352
+ isCurrentSession: boolean;
353
+ }
354
+
355
+ /** Hit count of a session header: "1 match", "7 matches", or "20+ matches" when capped. */
356
+ export function groupCountText(hitCount: number, capped: boolean): string {
357
+ if (capped) {
358
+ return `${hitCount}+ matches`;
359
+ }
360
+ return `${hitCount} ${hitCount === 1 ? "match" : "matches"}`;
361
+ }
362
+
363
+ /**
364
+ * One header row for a session group, at most `width` columns, such as
365
+ * "~/work/app · this session · 20+ matches · 3h". The label is cut from the
366
+ * left so the end of a path stays visible; the details are kept whole when
367
+ * they fit.
368
+ */
369
+ export function sessionGroupHeaderText(
370
+ header: SessionGroupHeader,
371
+ width: number,
372
+ now: number,
373
+ ): string {
374
+ if (width <= 0) {
375
+ return "";
376
+ }
377
+ const details: string[] = [];
378
+ if (header.isCurrentSession) {
379
+ details.push("this session");
380
+ }
381
+ details.push(groupCountText(header.hitCount, header.capped));
382
+ const age = relativeAge(header.newestTimestamp, now);
383
+ if (age !== "") {
384
+ details.push(age);
385
+ }
386
+ const separator = " · ";
387
+ const suffix = `${separator}${details.join(separator)}`;
388
+ const label = cleanForDisplay(header.label).replace(/\s+/gu, " ");
389
+ const labelWidth = Math.max(8, width - visibleWidth(suffix));
390
+ return truncateToWidth(`${truncateStart(label, labelWidth)}${suffix}`, width, "…");
391
+ }