pi-stereo-view 0.1.18 → 0.1.19
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/CHANGELOG.md +7 -0
- package/package.json +5 -3
- package/src/content.ts +132 -63
- package/src/layout.ts +77 -38
- package/src/native.ts +371 -46
- package/src/render-cache.ts +19 -5
- package/src/surface.ts +875 -0
- package/src/timestamps.ts +41 -5
- package/src/tool-streaming.ts +31 -13
package/src/surface.ts
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Container, CURSOR_MARKER, getOsc8LinkAtColumn, ScrollView, sliceByColumn, stripTerminalSequences, truncateToWidth, visibleWidth,
|
|
3
|
+
type Component, type TUI, type TuiMouseEvent, type TuiMouseEventResult,
|
|
4
|
+
} from "@earendil-works/pi-tui";
|
|
5
|
+
|
|
6
|
+
// Pi exports stacks and scroll views but not its layout engine. Stacks describe themselves through this symbol.
|
|
7
|
+
const LAYOUT_NODE = Symbol.for("@earendil-works/pi-tui/layout-node");
|
|
8
|
+
const RESET = "\x1b[0m\x1b]8;;\x07";
|
|
9
|
+
const OSC133_ZONE_PREFIX = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
|
|
10
|
+
const ANSI = /\x1b(?:\[[0-9;:?<>=]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|_[^\x07\x1b]*(?:\x07|\x1b\\)|P[^\x07\x1b]*(?:\x07|\x1b\\))/y;
|
|
11
|
+
const DOUBLE_CLICK_INTERVAL_MS = 500;
|
|
12
|
+
const WORD_JOINERS = new Set(["/", "-", "+", "\\", "~", "_", "."]);
|
|
13
|
+
const words = new Intl.Segmenter(undefined, { granularity: "word" });
|
|
14
|
+
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
15
|
+
const WIDTH_CACHE_LIMIT = 50_000;
|
|
16
|
+
|
|
17
|
+
interface Rect { x: number; y: number; width: number; height: number }
|
|
18
|
+
interface Viewport { width: number; height: number }
|
|
19
|
+
interface Entry {
|
|
20
|
+
component: Component; basis?: number | "auto"; grow?: number; shrink?: number; minSize?: number; maxSize?: number;
|
|
21
|
+
visible?: (viewport: Viewport) => boolean;
|
|
22
|
+
}
|
|
23
|
+
type LayoutNode =
|
|
24
|
+
| { type: "vstack" | "hstack"; entries: Entry[]; gap: number; align: "stretch" | "start" | "center" | "end" }
|
|
25
|
+
| { type: "scroll"; component: Component; state: ScrollView };
|
|
26
|
+
interface Box {
|
|
27
|
+
component: Component; rect: Rect; clip: Rect; children: Box[];
|
|
28
|
+
lines?: string[]; lineOffset?: number; scrollView?: ScrollView; scrollContentLines?: string[];
|
|
29
|
+
}
|
|
30
|
+
interface Context { viewport: Viewport; cache: Map<Component, Map<number, string[]>>; requestRender: () => void; scrolls: Map<ScrollView, Box> }
|
|
31
|
+
interface Segment { x: number; width: number; line: string; raw?: boolean; background?: boolean }
|
|
32
|
+
interface Geometry { column: number; trackTop: number; trackHeight: number; thumbTop: number; thumbHeight: number; maxScrollTop: number }
|
|
33
|
+
interface Frame { width: number; height: number; root: Box; lines: string[]; scrolls: Map<ScrollView, Box>; indicator?: { row: number; column: number; width: number } }
|
|
34
|
+
interface Point { row: number; col: number; view: ScrollView; boundary?: boolean }
|
|
35
|
+
interface Range { start: Point; end: Point }
|
|
36
|
+
type Dispatched = TuiMouseEventResult & { handled: true; target: { component: Component; originX: number; originY: number; width: number; height: number }; focusTarget?: Component };
|
|
37
|
+
/** Read-only and opaque scroll-follow hooks offered by projected documents. */
|
|
38
|
+
interface ScrollContent { takeScrollShift?(): number }
|
|
39
|
+
|
|
40
|
+
function layoutNode(component: Component): LayoutNode | undefined {
|
|
41
|
+
const describe = (component as unknown as Record<symbol, unknown>)[LAYOUT_NODE];
|
|
42
|
+
return typeof describe === "function" ? describe.call(component) as LayoutNode : undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function intersect(a: Rect, b: Rect): Rect {
|
|
46
|
+
const x = Math.max(a.x, b.x);
|
|
47
|
+
const y = Math.max(a.y, b.y);
|
|
48
|
+
return { x, y, width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x), height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function contains(rect: Rect, x: number, y: number): boolean {
|
|
52
|
+
return x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function rendered(context: Context, component: Component, width: number): string[] {
|
|
56
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
57
|
+
let widths = context.cache.get(component);
|
|
58
|
+
if (!widths) { widths = new Map(); context.cache.set(component, widths); }
|
|
59
|
+
let lines = widths.get(safeWidth);
|
|
60
|
+
if (!lines) { lines = component.render(safeWidth); widths.set(safeWidth, lines); }
|
|
61
|
+
return lines;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function clampSize(size: number, entry: Entry): number {
|
|
65
|
+
const min = Math.max(0, Math.floor(entry.minSize ?? 0));
|
|
66
|
+
const max = Math.max(min, Math.floor(entry.maxSize ?? Number.MAX_SAFE_INTEGER));
|
|
67
|
+
return Math.max(min, Math.min(max, Math.max(0, Math.floor(size))));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function distribute(sizes: number[], entries: Entry[], amount: number, mode: "grow" | "shrink"): void {
|
|
71
|
+
let remaining = amount;
|
|
72
|
+
while (remaining > 0) {
|
|
73
|
+
const candidates = entries.map((entry, index) => ({ entry, index })).filter(({ entry, index }) => mode === "grow" ?
|
|
74
|
+
(entry.grow ?? 0) > 0 && sizes[index] < (entry.maxSize ?? Number.MAX_SAFE_INTEGER) :
|
|
75
|
+
(entry.shrink ?? 1) > 0 && sizes[index] > (entry.minSize ?? 0));
|
|
76
|
+
if (!candidates.length) return;
|
|
77
|
+
const weight = (entry: Entry, index: number): number => mode === "grow" ? entry.grow ?? 0 : (entry.shrink ?? 1) * Math.max(1, sizes[index]);
|
|
78
|
+
const total = candidates.reduce((sum, { entry, index }) => sum + weight(entry, index), 0);
|
|
79
|
+
let distributed = 0;
|
|
80
|
+
for (const { entry, index } of candidates) {
|
|
81
|
+
if (remaining <= 0) break;
|
|
82
|
+
const proposed = Math.max(1, Math.floor(remaining * weight(entry, index) / total));
|
|
83
|
+
const capacity = mode === "grow" ? (entry.maxSize ?? Number.MAX_SAFE_INTEGER) - sizes[index] : sizes[index] - (entry.minSize ?? 0);
|
|
84
|
+
const delta = Math.min(remaining, proposed, capacity);
|
|
85
|
+
if (delta <= 0) continue;
|
|
86
|
+
sizes[index] += mode === "grow" ? delta : -delta;
|
|
87
|
+
remaining -= delta;
|
|
88
|
+
distributed += delta;
|
|
89
|
+
}
|
|
90
|
+
if (!distributed) return;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Same allocation as Pi's stacks, so the split keeps its native sizing rules. */
|
|
95
|
+
function allocate(entries: Entry[], intrinsic: number[], available: number | undefined, gap: number): number[] {
|
|
96
|
+
const sizes = entries.map((entry, index) => clampSize(entry.basis === undefined || entry.basis === "auto" ? intrinsic[index] ?? 0 : entry.basis, entry));
|
|
97
|
+
if (available === undefined) return sizes;
|
|
98
|
+
const content = Math.max(0, Math.floor(available) - Math.max(0, entries.length - 1) * gap);
|
|
99
|
+
const total = sizes.reduce((sum, size) => sum + size, 0);
|
|
100
|
+
if (total < content) distribute(sizes, entries, content - total, "grow");
|
|
101
|
+
else if (total > content) distribute(sizes, entries, total - content, "shrink");
|
|
102
|
+
return sizes;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function translate(box: Box, delta: number): void {
|
|
106
|
+
box.rect.y += delta;
|
|
107
|
+
for (const child of box.children) translate(child, delta);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function updateClips(box: Box, parent: Rect): void {
|
|
111
|
+
box.clip = intersect(parent, box.rect);
|
|
112
|
+
for (const child of box.children) updateClips(child, box.clip);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Set a pane's scroll position without the transient scrollbar a user scroll shows. */
|
|
116
|
+
function restoreScrollTop(view: ScrollView, top: number): void {
|
|
117
|
+
const max = Math.max(0, (Reflect.get(view, "contentHeight") as number ?? 0) - view.viewportHeight);
|
|
118
|
+
const next = Math.max(0, Math.min(max, Math.trunc(top)));
|
|
119
|
+
if (typeof Reflect.get(view, "currentScrollTop") === "number") Reflect.set(view, "currentScrollTop", next);
|
|
120
|
+
else view.scrollTo(next, { disableFollow: true });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Port of Pi's layout pass. It runs inside one full-width component, so Pi paints the split without compositing. */
|
|
124
|
+
function layout(context: Context, component: Component, x: number, y: number, width: number, height: number | undefined, clip: Rect): Box {
|
|
125
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
126
|
+
const node = layoutNode(component);
|
|
127
|
+
if (!node) {
|
|
128
|
+
const lines = rendered(context, component, safeWidth);
|
|
129
|
+
const allocated = height === undefined ? lines.length : Math.max(0, Math.floor(height));
|
|
130
|
+
let lineOffset = 0;
|
|
131
|
+
if (lines.length > allocated && allocated > 0) {
|
|
132
|
+
const cursor = lines.findIndex(line => line.includes(CURSOR_MARKER));
|
|
133
|
+
if (cursor >= allocated) lineOffset = cursor - allocated + 1;
|
|
134
|
+
}
|
|
135
|
+
const rect = { x, y, width: safeWidth, height: allocated };
|
|
136
|
+
return { component, rect, clip: intersect(clip, rect), children: [], lines, lineOffset };
|
|
137
|
+
}
|
|
138
|
+
if (node.type === "scroll") {
|
|
139
|
+
const state = node.state;
|
|
140
|
+
const previous = state.scrollTop;
|
|
141
|
+
const contentWidth = state.getContentWidth(safeWidth);
|
|
142
|
+
const child = layout(context, node.component, x, y - previous, contentWidth, undefined, clip);
|
|
143
|
+
const contentHeight = child.rect.height;
|
|
144
|
+
const viewport = height === undefined ? contentHeight : Math.max(0, Math.floor(height));
|
|
145
|
+
state.updateLayout(contentHeight, viewport, context.requestRender);
|
|
146
|
+
const shift = (node.component as Component & ScrollContent).takeScrollShift?.() ?? 0;
|
|
147
|
+
if (shift && !state.isFollowingEnd) restoreScrollTop(state, state.scrollTop + shift);
|
|
148
|
+
translate(child, previous - state.scrollTop);
|
|
149
|
+
const rect = { x, y, width: safeWidth, height: viewport };
|
|
150
|
+
const box: Box = { component, rect, clip: intersect(clip, rect), children: [child], scrollView: state,
|
|
151
|
+
scrollContentLines: rendered(context, node.component, contentWidth) };
|
|
152
|
+
updateClips(child, box.clip);
|
|
153
|
+
context.scrolls.set(state, box);
|
|
154
|
+
return box;
|
|
155
|
+
}
|
|
156
|
+
const entries = node.entries.filter(entry => entry.visible?.(context.viewport) ?? true);
|
|
157
|
+
const gaps = Math.max(0, entries.length - 1) * node.gap;
|
|
158
|
+
if (node.type === "vstack") {
|
|
159
|
+
const intrinsic = entries.map(entry => typeof entry.basis === "number" ? entry.basis : rendered(context, entry.component, safeWidth).length);
|
|
160
|
+
const sizes = allocate(entries, intrinsic, height, node.gap);
|
|
161
|
+
const allocated = height === undefined ? sizes.reduce((sum, size) => sum + size, 0) + gaps : Math.max(0, Math.floor(height));
|
|
162
|
+
const rect = { x, y, width: safeWidth, height: allocated };
|
|
163
|
+
const box: Box = { component, rect, clip: intersect(clip, rect), children: [] };
|
|
164
|
+
let childY = y;
|
|
165
|
+
for (let index = 0; index < entries.length; index++) {
|
|
166
|
+
box.children.push(layout(context, entries[index].component, x, childY, safeWidth, sizes[index], box.clip));
|
|
167
|
+
childY += sizes[index] + node.gap;
|
|
168
|
+
}
|
|
169
|
+
return box;
|
|
170
|
+
}
|
|
171
|
+
const intrinsicWidths = entries.map(entry => typeof entry.basis === "number" ? entry.basis :
|
|
172
|
+
rendered(context, entry.component, safeWidth).reduce((max, line) => Math.max(max, visibleWidth(line)), 0));
|
|
173
|
+
const widths = allocate(entries, intrinsicWidths, safeWidth, node.gap);
|
|
174
|
+
const heights = entries.map((entry, index) => rendered(context, entry.component, Math.max(1, widths[index])).length);
|
|
175
|
+
const allocated = height === undefined ? heights.reduce((max, value) => Math.max(max, value), 0) : Math.max(0, height);
|
|
176
|
+
const rect = { x, y, width: safeWidth, height: allocated };
|
|
177
|
+
const box: Box = { component, rect, clip: intersect(clip, rect), children: [] };
|
|
178
|
+
let childX = x;
|
|
179
|
+
for (let index = 0; index < entries.length; index++) {
|
|
180
|
+
const childHeight = node.align === "stretch" ? allocated : Math.min(allocated, heights[index]);
|
|
181
|
+
let childY = y;
|
|
182
|
+
if (node.align === "center") childY += Math.floor((allocated - childHeight) / 2);
|
|
183
|
+
else if (node.align === "end") childY += allocated - childHeight;
|
|
184
|
+
if (widths[index] === 0) {
|
|
185
|
+
box.children.push({ component: entries[index].component, rect: { x: childX, y: childY, width: 0, height: childHeight },
|
|
186
|
+
clip: { x: childX, y: childY, width: 0, height: 0 }, children: [] });
|
|
187
|
+
} else box.children.push(layout(context, entries[index].component, childX, childY, widths[index], childHeight, box.clip));
|
|
188
|
+
childX += widths[index] + node.gap;
|
|
189
|
+
}
|
|
190
|
+
return box;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function scrollbarGeometry(box: Box, includeHiddenAuto = false): Geometry | undefined {
|
|
194
|
+
const view = box.scrollView;
|
|
195
|
+
if (!view || box.rect.width <= 0 || box.rect.height <= 0) return undefined;
|
|
196
|
+
const contentHeight = box.children[0]?.rect.height ?? box.scrollContentLines?.length ?? 0;
|
|
197
|
+
const trackHeight = box.rect.height;
|
|
198
|
+
if (!view.isScrollbarVisible && !(includeHiddenAuto && view.scrollbar === "auto" && contentHeight > trackHeight)) return undefined;
|
|
199
|
+
const thumbHeight = Math.max(Math.min(2, trackHeight), Math.min(trackHeight, Math.round(trackHeight * trackHeight / contentHeight)));
|
|
200
|
+
const maxScrollTop = Math.max(0, contentHeight - trackHeight);
|
|
201
|
+
const thumbOffset = maxScrollTop === 0 ? 0 : Math.round(view.scrollTop / maxScrollTop * (trackHeight - thumbHeight));
|
|
202
|
+
const column = box.rect.x + box.rect.width - 1;
|
|
203
|
+
if (column < box.clip.x || column >= box.clip.x + box.clip.width) return undefined;
|
|
204
|
+
return { column, trackTop: box.rect.y, trackHeight, thumbTop: box.rect.y + thumbOffset, thumbHeight, maxScrollTop };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Background color active at the end of a styled prefix, so a scrollbar cell keeps its row's fill. */
|
|
208
|
+
export function activeBackground(text: string): string {
|
|
209
|
+
let background = "";
|
|
210
|
+
for (const match of text.matchAll(/\x1b\[([0-9;:]*)m/g)) {
|
|
211
|
+
const params = match[1] === "" ? [0] : match[1].split(/[;:]/).map(Number);
|
|
212
|
+
for (let index = 0; index < params.length; index++) {
|
|
213
|
+
const code = params[index];
|
|
214
|
+
if (code === 0 || code === 49) background = "";
|
|
215
|
+
else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) background = `\x1b[${code}m`;
|
|
216
|
+
else if (code === 48 && params[index + 1] === 5) { background = `\x1b[48;5;${params[index + 2]}m`; index += 2; }
|
|
217
|
+
else if (code === 48 && params[index + 1] === 2) {
|
|
218
|
+
background = `\x1b[48;2;${params[index + 2]};${params[index + 3]};${params[index + 4]}m`;
|
|
219
|
+
index += 4;
|
|
220
|
+
} else if ((code === 38 || code === 58) && params[index + 1] === 5) index += 2;
|
|
221
|
+
else if ((code === 38 || code === 58) && params[index + 1] === 2) index += 4;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return background;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Cell range of the grapheme at a column, ignoring terminal sequences. */
|
|
228
|
+
function graphemeRange(line: string, column: number): { start: number; end: number } | undefined {
|
|
229
|
+
let current = 0;
|
|
230
|
+
for (const { segment } of graphemes.segment(stripTerminalSequences(line))) {
|
|
231
|
+
const width = visibleWidth(segment);
|
|
232
|
+
if (width > 0 && column >= current && column < current + width) return { start: current, end: current + width };
|
|
233
|
+
current += width;
|
|
234
|
+
}
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function highlightSelection(text: string): string {
|
|
239
|
+
let result = "\x1b[7m";
|
|
240
|
+
let index = 0;
|
|
241
|
+
while (index < text.length) {
|
|
242
|
+
ANSI.lastIndex = index;
|
|
243
|
+
const match = ANSI.exec(text);
|
|
244
|
+
if (!match) { result += text[index++]; continue; }
|
|
245
|
+
result += match[0];
|
|
246
|
+
if (match[0].endsWith("m")) result += "\x1b[7m";
|
|
247
|
+
index += match[0].length;
|
|
248
|
+
}
|
|
249
|
+
return result + "\x1b[27m";
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** One scroll position for Pi's keyboard scrolling, prompt jumps and follow-end: the active split panel's. */
|
|
253
|
+
export class ActivePaneScrollView extends ScrollView {
|
|
254
|
+
constructor(private readonly target: () => ScrollView | undefined, lines: () => string[]) {
|
|
255
|
+
super({ render: () => lines(), invalidate() {} }, { follow: "end" });
|
|
256
|
+
Object.defineProperty(this, "primary", { value: true });
|
|
257
|
+
Object.defineProperty(this, "followEnd", { get: () => this.target()?.followEnd ?? false });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
override get scrollTop(): number { return this.target()?.scrollTop ?? 0; }
|
|
261
|
+
override get isFollowingEnd(): boolean { return this.target()?.isFollowingEnd ?? true; }
|
|
262
|
+
override get viewportHeight(): number { return this.target()?.viewportHeight ?? 0; }
|
|
263
|
+
override get isScrollbarVisible(): boolean { return false; }
|
|
264
|
+
override scrollTo(scrollTop: number, options?: Parameters<ScrollView["scrollTo"]>[1]): void { this.target()?.scrollTo(scrollTop, options); }
|
|
265
|
+
override scrollBy(lines: number): number { return this.target()?.scrollBy(lines) ?? lines; }
|
|
266
|
+
override scrollToStart(): void { this.target()?.scrollToStart(); }
|
|
267
|
+
override scrollToEnd(): void { this.target()?.scrollToEnd(); }
|
|
268
|
+
override setScrollbarActive(): void {}
|
|
269
|
+
// Pi lays this view out with no rows; the panels' own layout pass sizes the real views.
|
|
270
|
+
override updateLayout(): void {}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export interface SplitSurfaceOptions {
|
|
274
|
+
/** Current split tree, whether it fills the available rows, and its minimum height. */
|
|
275
|
+
model(): { component: Component; fill: boolean; minSize: number } | undefined;
|
|
276
|
+
/** Rows between the toolbar and the dock. */
|
|
277
|
+
height(): number;
|
|
278
|
+
/** Panel receiving keyboard scrolling and the follow-end indicator. */
|
|
279
|
+
active(): ScrollView | undefined;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
type SelectionApi = Record<"hasActiveSelection" | "copyActiveSelectionToClipboard" | "resetTextSelection", (...args: never[]) => unknown>;
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Paint the split area as one full-width component. Pi assigns full-width rows directly, while panels at a column
|
|
286
|
+
* offset would go through its per-row compositor. This component runs Pi's layout rules for the split tree itself,
|
|
287
|
+
* pads each panel row to its width and joins the rows. It also owns what Pi does only for views it lays out:
|
|
288
|
+
* scrollbars, the follow-end indicator, wheel routing, mouse dispatch and text selection inside panels.
|
|
289
|
+
*/
|
|
290
|
+
export class SplitSurface extends Container {
|
|
291
|
+
readonly proxy: ActivePaneScrollView;
|
|
292
|
+
private frame?: Frame;
|
|
293
|
+
private readonly widths = new Map<string, number>();
|
|
294
|
+
private hover?: ScrollView;
|
|
295
|
+
private lastEvent?: TuiMouseEvent;
|
|
296
|
+
private scrollbarDrag?: { view: ScrollView; grab: number };
|
|
297
|
+
private anchor?: Point;
|
|
298
|
+
private focus?: Point;
|
|
299
|
+
private granularity: "character" | "word" | "line" = "character";
|
|
300
|
+
private initial?: Range;
|
|
301
|
+
private pressing = false;
|
|
302
|
+
private dragged = false;
|
|
303
|
+
private pendingClick = false;
|
|
304
|
+
private pressedUrl?: string;
|
|
305
|
+
private lastClick?: { time: number; count: number; row: number; view: ScrollView; start: number; end: number };
|
|
306
|
+
private autoScroll?: { timer: ReturnType<typeof setInterval>; direction: number; x: number; y: number };
|
|
307
|
+
private restoreApi: (() => void)[] = [];
|
|
308
|
+
private readonly requestRender = (): void => this.tui.requestRender();
|
|
309
|
+
|
|
310
|
+
constructor(private readonly tui: TUI, private readonly options: SplitSurfaceOptions) {
|
|
311
|
+
super();
|
|
312
|
+
this.proxy = new ActivePaneScrollView(options.active, () => {
|
|
313
|
+
const view = options.active();
|
|
314
|
+
return (view && this.frame?.scrolls.get(view)?.scrollContentLines) ?? [];
|
|
315
|
+
});
|
|
316
|
+
this.installSelectionApi();
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Components owned by the split tree, so invalidation and inspection still reach them. */
|
|
320
|
+
setModels(components: Component[]): void {
|
|
321
|
+
this.children = components;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
override render(width: number): string[] {
|
|
325
|
+
const model = this.options.model();
|
|
326
|
+
this.syncHostSelection();
|
|
327
|
+
if (!model) {
|
|
328
|
+
this.frame = undefined;
|
|
329
|
+
return [];
|
|
330
|
+
}
|
|
331
|
+
const context: Context = {
|
|
332
|
+
viewport: { width, height: Math.max(1, this.tui.terminal.rows) }, cache: new Map(), requestRender: this.requestRender, scrolls: new Map(),
|
|
333
|
+
};
|
|
334
|
+
const available = Math.max(0, Math.floor(this.options.height()));
|
|
335
|
+
const natural = model.fill ? available : rendered(context, model.component, width).length;
|
|
336
|
+
const height = Math.max(model.minSize, Math.min(natural, available));
|
|
337
|
+
const clip = { x: 0, y: 0, width, height };
|
|
338
|
+
const root = layout(context, model.component, 0, 0, width, height, clip);
|
|
339
|
+
const frame: Frame = { width, height, root, lines: [], scrolls: context.scrolls };
|
|
340
|
+
frame.lines = this.paint(frame);
|
|
341
|
+
this.frame = frame;
|
|
342
|
+
return frame.lines;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private paint(frame: Frame): string[] {
|
|
346
|
+
const rows: Segment[][] = Array.from({ length: frame.height }, () => []);
|
|
347
|
+
const punches: Segment[][] = Array.from({ length: frame.height }, () => []);
|
|
348
|
+
const selection = this.selectionBounds();
|
|
349
|
+
const collect = (box: Box, selected?: Range): void => {
|
|
350
|
+
if (box.lines) {
|
|
351
|
+
const offset = box.lineOffset ?? 0;
|
|
352
|
+
const first = Math.max(box.rect.y, box.clip.y, 0);
|
|
353
|
+
const last = Math.min(box.rect.y + box.rect.height, box.clip.y + box.clip.height, frame.height);
|
|
354
|
+
for (let row = first; row < last; row++) {
|
|
355
|
+
const index = offset + row - box.rect.y;
|
|
356
|
+
let line = box.lines[index];
|
|
357
|
+
if (line === undefined) continue;
|
|
358
|
+
if (line.startsWith("\x1b]133;")) line = line.replace(OSC133_ZONE_PREFIX, "");
|
|
359
|
+
if (selected && index >= selected.start.row && index <= selected.end.row) line = this.highlight(line, index, selected, box.rect.width);
|
|
360
|
+
rows[row].push({ x: box.rect.x, width: box.rect.width, line });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
for (const child of box.children) collect(child, box.scrollView && selection?.start.view === box.scrollView ? selection : undefined);
|
|
364
|
+
if (box.scrollView) this.scrollbar(box, punches, frame.height);
|
|
365
|
+
};
|
|
366
|
+
collect(frame.root);
|
|
367
|
+
this.indicator(frame, punches);
|
|
368
|
+
return rows.map((segments, row) => {
|
|
369
|
+
for (const punch of punches[row]) this.punch(segments, punch);
|
|
370
|
+
return this.compose(segments);
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private scrollbar(box: Box, punches: Segment[][], height: number): void {
|
|
375
|
+
const geometry = scrollbarGeometry(box);
|
|
376
|
+
const view = box.scrollView;
|
|
377
|
+
if (!geometry || !view) return;
|
|
378
|
+
for (let row = geometry.trackTop; row < geometry.trackTop + geometry.trackHeight; row++) {
|
|
379
|
+
if (row < box.clip.y || row >= box.clip.y + box.clip.height || row < 0 || row >= height) continue;
|
|
380
|
+
const thumb = row >= geometry.thumbTop && row < geometry.thumbTop + geometry.thumbHeight;
|
|
381
|
+
const line = thumb ? view.scrollbarThumbStyle(view.isScrollbarActive ? "█" : "┃") : view.scrollbarTrackStyle("│");
|
|
382
|
+
punches[row].push({ x: geometry.column, width: 1, line, raw: true, background: view.scrollbar !== "always" });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
private indicator(frame: Frame, punches: Segment[][]): void {
|
|
387
|
+
const view = this.options.active();
|
|
388
|
+
const label = Reflect.get(this.tui, "scrollToEndIndicator") as (() => string) | undefined;
|
|
389
|
+
const box = view && frame.scrolls.get(view);
|
|
390
|
+
if (typeof label !== "function" || !view?.followEnd || view.isFollowingEnd || !box) return;
|
|
391
|
+
const clip = box.clip;
|
|
392
|
+
if (clip.width <= 0 || clip.height <= 0) return;
|
|
393
|
+
const row = clip.y + clip.height - 1;
|
|
394
|
+
if (row >= frame.height) return;
|
|
395
|
+
const text = truncateToWidth(label(), clip.width, "");
|
|
396
|
+
const column = clip.x + Math.floor((clip.width - visibleWidth(text)) / 2);
|
|
397
|
+
const right = scrollbarGeometry(box)?.column ?? clip.x + clip.width;
|
|
398
|
+
const shown = truncateToWidth(text, Math.max(0, right - column), "");
|
|
399
|
+
const width = visibleWidth(shown);
|
|
400
|
+
if (!width) return;
|
|
401
|
+
punches[row].push({ x: column, width, line: shown, raw: true });
|
|
402
|
+
frame.indicator = { row, column, width };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Replace cells of an underlying panel row, as Pi's scrollbar and indicator overlays do. */
|
|
406
|
+
private punch(segments: Segment[], punch: Segment): void {
|
|
407
|
+
const index = segments.findIndex(segment => !segment.raw && punch.x >= segment.x && punch.x < segment.x + segment.width);
|
|
408
|
+
if (index < 0) {
|
|
409
|
+
segments.push(punch);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
const segment = segments[index];
|
|
413
|
+
const left = punch.x - segment.x;
|
|
414
|
+
const rightStart = punch.x + punch.width;
|
|
415
|
+
const rightWidth = segment.x + segment.width - rightStart;
|
|
416
|
+
const parts: Segment[] = [];
|
|
417
|
+
if (left > 0) parts.push({ x: segment.x, width: left, line: segment.line });
|
|
418
|
+
const fill = punch.background ? activeBackground(sliceByColumn(segment.line, 0, left + 1, true)) : "";
|
|
419
|
+
parts.push({ ...punch, line: RESET + fill + punch.line });
|
|
420
|
+
if (rightWidth > 0) parts.push({ x: rightStart, width: rightWidth, line: sliceByColumn(segment.line, rightStart - segment.x, rightWidth, true) });
|
|
421
|
+
segments.splice(index, 1, ...parts);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private compose(segments: Segment[]): string {
|
|
425
|
+
if (!segments.length) return "";
|
|
426
|
+
if (segments.length > 1) segments.sort((a, b) => a.x - b.x);
|
|
427
|
+
let line = "";
|
|
428
|
+
let column = 0;
|
|
429
|
+
for (const segment of segments) {
|
|
430
|
+
if (segment.width <= 0 || segment.x < column) continue;
|
|
431
|
+
if (segment.x > column) line += " ".repeat(segment.x - column);
|
|
432
|
+
line += (segment.raw ? segment.line : this.fit(segment.line, segment.width)) + RESET;
|
|
433
|
+
column = segment.x + segment.width;
|
|
434
|
+
}
|
|
435
|
+
return line;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
private widthOf(line: string): number {
|
|
439
|
+
let width = this.widths.get(line);
|
|
440
|
+
if (width === undefined) {
|
|
441
|
+
if (this.widths.size >= WIDTH_CACHE_LIMIT) this.widths.clear();
|
|
442
|
+
width = visibleWidth(line);
|
|
443
|
+
this.widths.set(line, width);
|
|
444
|
+
}
|
|
445
|
+
return width;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
private fit(line: string, width: number): string {
|
|
449
|
+
const actual = this.widthOf(line);
|
|
450
|
+
if (actual === width) return line;
|
|
451
|
+
if (actual < width) return line + " ".repeat(width - actual);
|
|
452
|
+
const cut = sliceByColumn(line, 0, width, true);
|
|
453
|
+
const cutWidth = visibleWidth(cut);
|
|
454
|
+
return cutWidth < width ? cut + " ".repeat(width - cutWidth) : cut;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// Mouse
|
|
458
|
+
|
|
459
|
+
private boxesAt(x: number, y: number): Box[] {
|
|
460
|
+
const found: { box: Box; depth: number }[] = [];
|
|
461
|
+
const visit = (box: Box, depth: number): void => {
|
|
462
|
+
if (!contains(box.clip, x, y)) return;
|
|
463
|
+
found.push({ box, depth });
|
|
464
|
+
for (const child of box.children) visit(child, depth + 1);
|
|
465
|
+
};
|
|
466
|
+
if (this.frame) visit(this.frame.root, 0);
|
|
467
|
+
return found.sort((a, b) => b.depth - a.depth).map(entry => entry.box);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private scrollViewsAt(x: number, y: number): ScrollView[] {
|
|
471
|
+
return this.boxesAt(x, y).filter(box => box.scrollView && contains(box.rect, x, y)).map(box => box.scrollView!);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Dispatch like Pi: deepest component first, with exact targets so Pi captures drags directly. */
|
|
475
|
+
private dispatch(event: TuiMouseEvent): Dispatched | undefined {
|
|
476
|
+
const visited = new Set<Component>();
|
|
477
|
+
for (const box of this.boxesAt(event.x, event.y)) {
|
|
478
|
+
const component = box.component;
|
|
479
|
+
if (visited.has(component) || !component.handleMouse) continue;
|
|
480
|
+
if (layoutNode(component) && component.handleMouse === Container.prototype.handleMouse) continue;
|
|
481
|
+
visited.add(component);
|
|
482
|
+
const local = { ...event, x: event.x - box.rect.x, y: event.y - box.rect.y, width: box.rect.width, height: box.rect.height };
|
|
483
|
+
const result = component.handleMouse(local) as (TuiMouseEventResult & Partial<Dispatched>) | undefined;
|
|
484
|
+
if (!result) continue;
|
|
485
|
+
if (result.target) return result as Dispatched;
|
|
486
|
+
if (!result.handled && !result.capture && !result.focus) continue;
|
|
487
|
+
return {
|
|
488
|
+
...result, handled: true, ...(result.focus ? { focusTarget: component } : {}),
|
|
489
|
+
target: { component, originX: event.screenX - local.x, originY: event.screenY - local.y, width: local.width, height: local.height },
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
return undefined;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
private scrollbarAt(x: number, y: number, includeHiddenAuto: boolean): { view: ScrollView; geometry: Geometry } | undefined {
|
|
496
|
+
for (const view of this.scrollViewsAt(x, y)) {
|
|
497
|
+
const box = this.frame?.scrolls.get(view);
|
|
498
|
+
const geometry = box && scrollbarGeometry(box, includeHiddenAuto);
|
|
499
|
+
if (geometry && x === geometry.column && y >= geometry.trackTop && y < geometry.trackTop + geometry.trackHeight) return { view, geometry };
|
|
500
|
+
}
|
|
501
|
+
return undefined;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
private setHover(view: ScrollView | undefined): void {
|
|
505
|
+
if (view === this.hover) return;
|
|
506
|
+
this.hover?.setScrollbarActive(false);
|
|
507
|
+
this.hover = view;
|
|
508
|
+
view?.setScrollbarActive(true);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Pi passed an event no component handled; clear hover unless this surface just saw it. */
|
|
512
|
+
unhandled(event: TuiMouseEvent): void {
|
|
513
|
+
const seen = this.lastEvent;
|
|
514
|
+
if (seen && seen.type === event.type && seen.screenX === event.screenX && seen.screenY === event.screenY) return;
|
|
515
|
+
if (!this.scrollbarDrag && event.type !== "wheel") this.setHover(undefined);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
private scrollToPointer(view: ScrollView, geometry: Geometry, y: number, grab: number): void {
|
|
519
|
+
const maxThumb = geometry.trackHeight - geometry.thumbHeight;
|
|
520
|
+
const thumb = Math.max(0, Math.min(maxThumb, y - geometry.trackTop - grab));
|
|
521
|
+
view.scrollTo(maxThumb === 0 ? 0 : Math.round(thumb / maxThumb * geometry.maxScrollTop));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
override handleMouse(event: TuiMouseEvent): Dispatched | undefined {
|
|
525
|
+
this.lastEvent = event;
|
|
526
|
+
const result = this.mouse(event) as (TuiMouseEventResult & Partial<Dispatched>) | undefined;
|
|
527
|
+
if (!result || result.target) return result as Dispatched | undefined;
|
|
528
|
+
if (!result.handled && !result.capture && !result.focus) return undefined;
|
|
529
|
+
return { ...result, handled: true, target: { component: this, originX: event.screenX - event.x, originY: event.screenY - event.y,
|
|
530
|
+
width: event.width, height: event.height } };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
private mouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
534
|
+
if (!this.frame) return undefined;
|
|
535
|
+
if (this.scrollbarDrag) {
|
|
536
|
+
const drag = this.scrollbarDrag;
|
|
537
|
+
if (event.type === "release") this.scrollbarDrag = undefined;
|
|
538
|
+
else if (event.type === "drag") {
|
|
539
|
+
const box = this.frame.scrolls.get(drag.view);
|
|
540
|
+
const geometry = box && scrollbarGeometry(box);
|
|
541
|
+
if (geometry) this.scrollToPointer(drag.view, geometry, event.y, drag.grab);
|
|
542
|
+
}
|
|
543
|
+
return { handled: true };
|
|
544
|
+
}
|
|
545
|
+
if (this.pressing) return this.continueSelection(event);
|
|
546
|
+
if (event.type === "click") return this.pendingClick ? this.finishClick(event) : undefined;
|
|
547
|
+
if (event.type === "release") return undefined;
|
|
548
|
+
if (event.type === "press" && event.button === "left") {
|
|
549
|
+
const indicator = this.frame.indicator;
|
|
550
|
+
if (indicator && event.y === indicator.row && event.x >= indicator.column && event.x < indicator.column + indicator.width) {
|
|
551
|
+
this.options.active()?.scrollToEnd();
|
|
552
|
+
this.requestRender();
|
|
553
|
+
return { handled: true };
|
|
554
|
+
}
|
|
555
|
+
const bar = this.scrollbarAt(event.x, event.y, false);
|
|
556
|
+
if (bar) {
|
|
557
|
+
this.clearSelection();
|
|
558
|
+
this.lastClick = undefined;
|
|
559
|
+
this.setHover(bar.view);
|
|
560
|
+
const onThumb = event.y >= bar.geometry.thumbTop && event.y < bar.geometry.thumbTop + bar.geometry.thumbHeight;
|
|
561
|
+
const grab = onThumb ? event.y - bar.geometry.thumbTop : Math.floor(bar.geometry.thumbHeight / 2);
|
|
562
|
+
if (!onThumb) this.scrollToPointer(bar.view, bar.geometry, event.y, grab);
|
|
563
|
+
this.scrollbarDrag = { view: bar.view, grab };
|
|
564
|
+
return { capture: true };
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (event.type !== "wheel") this.setHover(this.scrollbarAt(event.x, event.y, true)?.view);
|
|
568
|
+
const result = this.dispatch(event);
|
|
569
|
+
if (result) {
|
|
570
|
+
if (event.type === "press") this.clearSelection();
|
|
571
|
+
return result;
|
|
572
|
+
}
|
|
573
|
+
if (event.type === "wheel") return this.routeWheel(event);
|
|
574
|
+
if (event.type === "press" && event.button === "left") return this.startSelection(event);
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
private routeWheel(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
579
|
+
const views = this.scrollViewsAt(event.x, event.y);
|
|
580
|
+
if (!views.length) return undefined;
|
|
581
|
+
let remaining = event.wheelDelta ?? 0;
|
|
582
|
+
for (const view of views) {
|
|
583
|
+
remaining = view.scrollBy(remaining);
|
|
584
|
+
if (remaining === 0 || view.overscroll === "contain") break;
|
|
585
|
+
}
|
|
586
|
+
const active = this.options.active();
|
|
587
|
+
// Pi passes leftover wheel movement to its primary view, which is the active panel here.
|
|
588
|
+
if (remaining !== 0 && active && !views.includes(active)) this.proxy.scrollBy(remaining);
|
|
589
|
+
this.setHover(this.scrollbarAt(event.x, event.y, true)?.view);
|
|
590
|
+
return { handled: true };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// Selection inside panels, matching Pi's selection in its own scroll views.
|
|
594
|
+
|
|
595
|
+
private point(view: ScrollView, x: number, y: number): Point | undefined {
|
|
596
|
+
const frame = this.frame;
|
|
597
|
+
const box = frame?.scrolls.get(view);
|
|
598
|
+
if (!frame || !box || box.rect.height <= 0 || box.clip.height <= 0) return undefined;
|
|
599
|
+
const top = Math.max(0, box.rect.y, box.clip.y);
|
|
600
|
+
const bottom = Math.min(frame.height - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
|
|
601
|
+
if (bottom < top) return undefined;
|
|
602
|
+
const pointer = Math.max(top, Math.min(bottom, y));
|
|
603
|
+
const maxRow = Math.max(0, (box.scrollContentLines?.length ?? 1) - 1);
|
|
604
|
+
return {
|
|
605
|
+
row: Math.max(0, Math.min(maxRow, view.scrollTop + pointer - box.rect.y)),
|
|
606
|
+
col: Math.max(0, Math.min(box.rect.width - 1, x - box.rect.x)), view,
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
private sourceLine(point: Point): string {
|
|
611
|
+
return this.frame?.scrolls.get(point.view)?.scrollContentLines?.[point.row] ?? "";
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
private wordAt(point: Point): Range | undefined {
|
|
615
|
+
const line = stripTerminalSequences(this.sourceLine(point));
|
|
616
|
+
const segments: { start: number; end: number; selectable: boolean; joiner: boolean }[] = [];
|
|
617
|
+
let start = 0;
|
|
618
|
+
for (const segment of words.segment(line)) {
|
|
619
|
+
const end = start + visibleWidth(segment.segment);
|
|
620
|
+
const joiner = WORD_JOINERS.has(segment.segment);
|
|
621
|
+
segments.push({ start, end, selectable: segment.isWordLike === true || joiner, joiner });
|
|
622
|
+
start = end;
|
|
623
|
+
}
|
|
624
|
+
const clicked = segments.findIndex(segment => point.col >= segment.start && point.col < segment.end);
|
|
625
|
+
if (clicked < 0) return undefined;
|
|
626
|
+
const join = (left: typeof segments[number], right: typeof segments[number]): boolean => left.selectable && right.selectable && (left.joiner || right.joiner);
|
|
627
|
+
let first = clicked;
|
|
628
|
+
while (first > 0 && join(segments[first - 1], segments[first])) first--;
|
|
629
|
+
let last = clicked;
|
|
630
|
+
while (last < segments.length - 1 && join(segments[last], segments[last + 1])) last++;
|
|
631
|
+
return { start: { ...point, col: segments[first].start }, end: { ...point, col: segments[last].end, boundary: true } };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
private lineAt(point: Point): Range {
|
|
635
|
+
return { start: { ...point, col: 0 }, end: { ...point, col: visibleWidth(this.sourceLine(point)), boundary: true } };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
private clickCount(point: Point, word: Range | undefined): number {
|
|
639
|
+
const now = Date.now();
|
|
640
|
+
const previous = this.lastClick;
|
|
641
|
+
const count = word && previous && now - previous.time <= DOUBLE_CLICK_INTERVAL_MS && previous.row === point.row &&
|
|
642
|
+
previous.view === point.view && previous.start === word.start.col && previous.end === word.end.col ? previous.count % 3 + 1 : 1;
|
|
643
|
+
this.lastClick = word ? { time: now, count, row: point.row, view: point.view, start: word.start.col, end: word.end.col } : undefined;
|
|
644
|
+
return count;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
private startSelection(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
648
|
+
const view = this.scrollViewsAt(event.x, event.y)[0];
|
|
649
|
+
const anchor = view && this.point(view, event.x, event.y);
|
|
650
|
+
if (!anchor) return undefined;
|
|
651
|
+
this.stopAutoScroll();
|
|
652
|
+
const word = this.wordAt(anchor);
|
|
653
|
+
const count = this.clickCount(anchor, word);
|
|
654
|
+
const range = count === 2 ? word : count === 3 ? this.lineAt(anchor) : undefined;
|
|
655
|
+
this.granularity = range ? count === 2 ? "word" : "line" : "character";
|
|
656
|
+
this.initial = range;
|
|
657
|
+
this.anchor = range?.start ?? anchor;
|
|
658
|
+
this.focus = range?.end ?? anchor;
|
|
659
|
+
this.dragged = false;
|
|
660
|
+
this.pendingClick = false;
|
|
661
|
+
this.pressing = true;
|
|
662
|
+
this.pressedUrl = range ? undefined : getOsc8LinkAtColumn(this.frame?.lines[event.y] ?? "", event.x);
|
|
663
|
+
return { capture: true, render: true };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
private updateFocus(point: Point | undefined): void {
|
|
667
|
+
if (!point) return;
|
|
668
|
+
if (this.granularity === "character" || !this.initial) {
|
|
669
|
+
this.focus = point;
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const range = this.granularity === "word" ? this.wordAt(point) : this.lineAt(point);
|
|
673
|
+
if (!range) return;
|
|
674
|
+
const initial = this.initial;
|
|
675
|
+
if (range.start.row < initial.start.row || (range.start.row === initial.start.row && range.start.col < initial.start.col)) {
|
|
676
|
+
this.anchor = initial.end;
|
|
677
|
+
this.focus = range.start;
|
|
678
|
+
} else {
|
|
679
|
+
this.anchor = initial.start;
|
|
680
|
+
this.focus = range.end;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
private continueSelection(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
685
|
+
const view = this.anchor?.view;
|
|
686
|
+
if (!view) {
|
|
687
|
+
this.pressing = false;
|
|
688
|
+
return { handled: true };
|
|
689
|
+
}
|
|
690
|
+
const point = this.point(view, event.x, event.y);
|
|
691
|
+
if (event.type === "drag") {
|
|
692
|
+
this.dragged = true;
|
|
693
|
+
this.lastClick = undefined;
|
|
694
|
+
this.pressedUrl = undefined;
|
|
695
|
+
this.updateFocus(point);
|
|
696
|
+
this.updateAutoScroll(event);
|
|
697
|
+
return { handled: true, render: true };
|
|
698
|
+
}
|
|
699
|
+
if (event.type !== "release") return { handled: true };
|
|
700
|
+
this.pressing = false;
|
|
701
|
+
this.stopAutoScroll();
|
|
702
|
+
const anchor = this.anchor!;
|
|
703
|
+
this.updateFocus(point);
|
|
704
|
+
const click = !this.dragged && point?.view === anchor.view && point.row === anchor.row && point.col === anchor.col;
|
|
705
|
+
const url = click ? this.pressedUrl : undefined;
|
|
706
|
+
this.pressedUrl = undefined;
|
|
707
|
+
const open = Reflect.get(this.tui, "openUrl") as ((url: string) => void) | undefined;
|
|
708
|
+
if (url && typeof open === "function") {
|
|
709
|
+
this.anchor = undefined;
|
|
710
|
+
this.focus = undefined;
|
|
711
|
+
try { open(url); } catch { /* URL activation is best-effort, as in Pi. */ }
|
|
712
|
+
return { handled: true, render: true };
|
|
713
|
+
}
|
|
714
|
+
// Pi follows an unmoved release with a click event; components may handle it.
|
|
715
|
+
if (click) this.pendingClick = true;
|
|
716
|
+
else if ((this.tui as TUI & { getCopyOnSelect?(): boolean }).getCopyOnSelect?.() ?? true) void this.copySelection();
|
|
717
|
+
return { handled: true, render: true };
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
private finishClick(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
721
|
+
this.pendingClick = false;
|
|
722
|
+
const result = this.dispatch(event);
|
|
723
|
+
if (result) {
|
|
724
|
+
this.clearSelection();
|
|
725
|
+
return result;
|
|
726
|
+
}
|
|
727
|
+
return { handled: true, render: true };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
private updateAutoScroll(event: TuiMouseEvent): void {
|
|
731
|
+
const view = this.anchor?.view;
|
|
732
|
+
const box = view && this.frame?.scrolls.get(view);
|
|
733
|
+
if (!box || box.rect.height <= 0 || box.clip.height <= 0) {
|
|
734
|
+
this.stopAutoScroll();
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
const top = Math.max(0, box.rect.y, box.clip.y);
|
|
738
|
+
const bottom = Math.min(this.frame!.height - 1, box.rect.y + box.rect.height - 1, box.clip.y + box.clip.height - 1);
|
|
739
|
+
const direction = event.y <= top ? -1 : event.y >= bottom ? 1 : 0;
|
|
740
|
+
if (!direction) {
|
|
741
|
+
this.stopAutoScroll();
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
if (this.autoScroll) {
|
|
745
|
+
Object.assign(this.autoScroll, { direction, x: event.x, y: event.y });
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
const timer = setInterval(() => this.autoScrollSelection(), 50);
|
|
749
|
+
timer.unref?.();
|
|
750
|
+
this.autoScroll = { timer, direction, x: event.x, y: event.y };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
private autoScrollSelection(): void {
|
|
754
|
+
const scroll = this.autoScroll;
|
|
755
|
+
const view = this.anchor?.view;
|
|
756
|
+
const capture = Reflect.get(this.tui, "mouseCapture") as { component?: Component } | undefined;
|
|
757
|
+
// Pi drops captured gestures when the terminal loses focus.
|
|
758
|
+
if (!scroll || !view || !this.pressing || capture?.component !== this) {
|
|
759
|
+
this.stopAutoScroll();
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (view.scrollBy(scroll.direction) === scroll.direction) {
|
|
763
|
+
this.stopAutoScroll();
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
this.updateFocus(this.point(view, scroll.x, scroll.y));
|
|
767
|
+
this.requestRender();
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
private stopAutoScroll(): void {
|
|
771
|
+
if (this.autoScroll) clearInterval(this.autoScroll.timer);
|
|
772
|
+
this.autoScroll = undefined;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
private clearSelection(): void {
|
|
776
|
+
this.stopAutoScroll();
|
|
777
|
+
this.pressing = false;
|
|
778
|
+
this.anchor = undefined;
|
|
779
|
+
this.focus = undefined;
|
|
780
|
+
this.granularity = "character";
|
|
781
|
+
this.initial = undefined;
|
|
782
|
+
this.pressedUrl = undefined;
|
|
783
|
+
this.dragged = false;
|
|
784
|
+
this.pendingClick = false;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Pi's own screen selection, or a press another component handled, replaces a panel selection. */
|
|
788
|
+
private syncHostSelection(): void {
|
|
789
|
+
if (!this.anchor) return;
|
|
790
|
+
const target = Reflect.get(this.tui, "mousePressTarget") as { component?: Component } | undefined;
|
|
791
|
+
if (Reflect.get(this.tui, "selectionAnchor") !== undefined || (target && target.component !== this)) this.clearSelection();
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
private selectionBounds(): Range | undefined {
|
|
795
|
+
const anchor = this.anchor;
|
|
796
|
+
const focus = this.focus;
|
|
797
|
+
if (!anchor || !focus || anchor.view !== focus.view || (anchor.row === focus.row && anchor.col === focus.col)) return undefined;
|
|
798
|
+
return anchor.row < focus.row || (anchor.row === focus.row && anchor.col < focus.col) ? { start: anchor, end: focus } : { start: focus, end: anchor };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
private columns(line: string, row: number, selection: Range, maxColumn: number): { start: number; end: number } {
|
|
802
|
+
const width = this.widthOf(line);
|
|
803
|
+
let start = 0;
|
|
804
|
+
let end = Math.min(width, maxColumn);
|
|
805
|
+
if (row === selection.start.row) start = graphemeRange(line, selection.start.col)?.start ?? Math.min(selection.start.col, width);
|
|
806
|
+
if (row === selection.end.row) {
|
|
807
|
+
end = selection.end.boundary ? Math.min(selection.end.col, width) :
|
|
808
|
+
graphemeRange(line, selection.end.col)?.end ?? Math.min(selection.end.col + 1, width);
|
|
809
|
+
}
|
|
810
|
+
return { start: Math.max(0, start), end: Math.min(maxColumn, end) };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
private highlight(line: string, row: number, selection: Range, maxColumn: number): string {
|
|
814
|
+
const { start, end } = this.columns(line, row, selection, maxColumn);
|
|
815
|
+
if (end <= start) return line;
|
|
816
|
+
const width = this.widthOf(line);
|
|
817
|
+
return sliceByColumn(line, 0, start, true) + highlightSelection(sliceByColumn(line, start, end - start, true)) +
|
|
818
|
+
sliceByColumn(line, end, Math.max(0, width - end), true);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
private selectedText(): string | undefined {
|
|
822
|
+
const selection = this.selectionBounds();
|
|
823
|
+
const lines = selection && this.frame?.scrolls.get(selection.start.view)?.scrollContentLines;
|
|
824
|
+
if (!selection || !lines) return undefined;
|
|
825
|
+
const text: string[] = [];
|
|
826
|
+
for (let row = selection.start.row; row <= selection.end.row; row++) {
|
|
827
|
+
const line = lines[row] ?? "";
|
|
828
|
+
const { start, end } = this.columns(line, row, selection, Number.MAX_SAFE_INTEGER);
|
|
829
|
+
text.push(stripTerminalSequences(sliceByColumn(line, start, Math.max(0, end - start), true)).trimEnd());
|
|
830
|
+
}
|
|
831
|
+
const joined = text.join("\n");
|
|
832
|
+
return joined.length ? joined : undefined;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
private async copySelection(): Promise<boolean> {
|
|
836
|
+
const text = this.selectedText();
|
|
837
|
+
const copy = Reflect.get(this.tui, "copyTextToClipboard") as ((text: string) => Promise<boolean>) | undefined;
|
|
838
|
+
if (!text || typeof copy !== "function") return false;
|
|
839
|
+
return copy.call(this.tui, text);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** Pi's selection commands (copy without copy-on-select, transcript reset) also cover panel selections. */
|
|
843
|
+
private installSelectionApi(): void {
|
|
844
|
+
const host = this.tui as unknown as Partial<SelectionApi>;
|
|
845
|
+
const wrap = <K extends keyof SelectionApi>(name: K, create: (original: SelectionApi[K]) => SelectionApi[K]): void => {
|
|
846
|
+
const original = host[name];
|
|
847
|
+
if (typeof original !== "function") return;
|
|
848
|
+
const own = Object.getOwnPropertyDescriptor(host, name);
|
|
849
|
+
const bound = original.bind(host) as SelectionApi[K];
|
|
850
|
+
const wrapper = create(bound);
|
|
851
|
+
host[name] = wrapper;
|
|
852
|
+
this.restoreApi.push(() => {
|
|
853
|
+
if (host[name] !== wrapper) return;
|
|
854
|
+
if (own) Object.defineProperty(host, name, own);
|
|
855
|
+
else Reflect.deleteProperty(host, name);
|
|
856
|
+
});
|
|
857
|
+
};
|
|
858
|
+
wrap("hasActiveSelection", original => () => this.selectedText() !== undefined || original());
|
|
859
|
+
wrap("copyActiveSelectionToClipboard", original => () => this.selectedText() !== undefined ? this.copySelection() : original());
|
|
860
|
+
wrap("resetTextSelection", original => () => {
|
|
861
|
+
this.clearSelection();
|
|
862
|
+
this.lastClick = undefined;
|
|
863
|
+
return original();
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/** Stop timers and give Pi back its own selection commands. */
|
|
868
|
+
dispose(): void {
|
|
869
|
+
this.clearSelection();
|
|
870
|
+
this.setHover(undefined);
|
|
871
|
+
this.scrollbarDrag = undefined;
|
|
872
|
+
for (const restore of this.restoreApi.splice(0)) restore();
|
|
873
|
+
this.frame = undefined;
|
|
874
|
+
}
|
|
875
|
+
}
|