proper-base 0.2.8 → 0.4.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/README.md +2 -2
- package/index.ts +129 -9
- package/package.json +3 -3
- package/src/autocomplete-details.ts +21 -5
- package/src/clipboard-guard.ts +181 -0
- package/src/fast-mode.ts +210 -0
- package/src/image-preview.ts +15 -4
- package/src/osc8-link-ids.ts +90 -0
- package/src/prompt-jump.ts +29 -4
- package/src/recorder.ts +6 -0
- package/src/selection-dismiss.ts +110 -0
- package/src/session-list.ts +497 -0
- package/src/transcript-cleanup.ts +29 -3
- package/src/wheel-scroll.ts +46 -0
package/src/fast-mode.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
const CONFIG_FILE_NAME = "cliproxyapi.json";
|
|
5
|
+
const MODELS_CACHE_FILE_NAME = "cliproxyapi-models.json";
|
|
6
|
+
const DEFAULT_PROVIDER_ID = "cliproxyapi";
|
|
7
|
+
const PRIORITY_TIER = "priority";
|
|
8
|
+
const FAST_COMMAND = "/fast";
|
|
9
|
+
|
|
10
|
+
type JsonObject = Record<string, unknown>;
|
|
11
|
+
|
|
12
|
+
/** The request-model fields this module reads. */
|
|
13
|
+
export type FastModel = { provider: string; id: string };
|
|
14
|
+
|
|
15
|
+
export type FastNotice = { message: string; level: "info" | "warning" };
|
|
16
|
+
|
|
17
|
+
function readJsonObject(path: string): JsonObject | undefined {
|
|
18
|
+
try {
|
|
19
|
+
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
20
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
21
|
+
? (parsed as JsonObject)
|
|
22
|
+
: undefined;
|
|
23
|
+
} catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Mirror of the provider's boolean-setting grammar for `CLIPROXYAPI_FAST`. */
|
|
29
|
+
function parseBooleanSetting(value: string): boolean | undefined {
|
|
30
|
+
switch (value.trim().toLowerCase()) {
|
|
31
|
+
case "1":
|
|
32
|
+
case "true":
|
|
33
|
+
case "yes":
|
|
34
|
+
case "on":
|
|
35
|
+
return true;
|
|
36
|
+
case "0":
|
|
37
|
+
case "false":
|
|
38
|
+
case "no":
|
|
39
|
+
case "off":
|
|
40
|
+
return false;
|
|
41
|
+
default:
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Whether submitted editor text is exactly the `/fast` toggle. */
|
|
47
|
+
export function isFastToggle(text: string): boolean {
|
|
48
|
+
return text.trim() === FAST_COMMAND;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Session and global Fast preferences layered over the CLIProxyAPI provider.
|
|
53
|
+
*
|
|
54
|
+
* The provider's own `/fast` persists one flag and refreshes it only at
|
|
55
|
+
* extension load, so it is neither session-scoped nor live across sessions.
|
|
56
|
+
* This overlay owns the final `service_tier` decision instead: the session
|
|
57
|
+
* flag lives in memory and dies with the session, while the global flag is
|
|
58
|
+
* the provider's persisted `fast` key, re-read on every request so a toggle
|
|
59
|
+
* in one session reaches every running session's next request.
|
|
60
|
+
*/
|
|
61
|
+
export class FastOverlay {
|
|
62
|
+
private sessionEnabled = false;
|
|
63
|
+
private modelsCache: { mtimeMs: number; ids: Set<string> } | undefined;
|
|
64
|
+
private readonly agentDir: string;
|
|
65
|
+
private readonly env: Record<string, string | undefined>;
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
agentDir: string,
|
|
69
|
+
env: Record<string, string | undefined> = process.env,
|
|
70
|
+
) {
|
|
71
|
+
this.agentDir = agentDir;
|
|
72
|
+
this.env = env;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private configPath(): string {
|
|
76
|
+
return join(this.agentDir, CONFIG_FILE_NAME);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Session Fast is never persisted; a new session always starts off. */
|
|
80
|
+
resetSession(): void {
|
|
81
|
+
this.sessionEnabled = false;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
isSessionEnabled(): boolean {
|
|
85
|
+
return this.sessionEnabled;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
toggleSession(): boolean {
|
|
89
|
+
this.sessionEnabled = !this.sessionEnabled;
|
|
90
|
+
return this.sessionEnabled;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The provider's Fast default: `CLIPROXYAPI_FAST` when set, else the
|
|
95
|
+
* persisted `fast` key. Re-read per call so other sessions' writes count.
|
|
96
|
+
*/
|
|
97
|
+
isGlobalEnabled(): boolean {
|
|
98
|
+
const envValue = this.env.CLIPROXYAPI_FAST;
|
|
99
|
+
if (envValue !== undefined) {
|
|
100
|
+
const parsed = parseBooleanSetting(envValue);
|
|
101
|
+
if (parsed !== undefined) return parsed;
|
|
102
|
+
}
|
|
103
|
+
return readJsonObject(this.configPath())?.fast === true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Flip the persisted global flag, preserving every other config key and
|
|
108
|
+
* the provider's own file format. Write failures propagate to the caller.
|
|
109
|
+
*/
|
|
110
|
+
toggleGlobal(): boolean {
|
|
111
|
+
const existing = readJsonObject(this.configPath()) ?? {};
|
|
112
|
+
const next = !this.isGlobalEnabled();
|
|
113
|
+
writeFileSync(
|
|
114
|
+
this.configPath(),
|
|
115
|
+
`${JSON.stringify({ ...existing, fast: next }, null, 2)}\n`,
|
|
116
|
+
"utf8",
|
|
117
|
+
);
|
|
118
|
+
return next;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The configured provider id the overlay scopes itself to. */
|
|
122
|
+
providerId(): string {
|
|
123
|
+
const envId = this.env.CLIPROXYAPI_PROVIDER_ID?.trim();
|
|
124
|
+
if (envId) return envId;
|
|
125
|
+
const fileId = readJsonObject(this.configPath())?.providerId;
|
|
126
|
+
return typeof fileId === "string" && fileId.trim()
|
|
127
|
+
? fileId.trim()
|
|
128
|
+
: DEFAULT_PROVIDER_ID;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Whether the provider's cached catalog marks this model Fast-capable. */
|
|
132
|
+
supportsModel(model: FastModel | undefined): boolean {
|
|
133
|
+
if (!model || model.provider !== this.providerId()) return false;
|
|
134
|
+
const path = join(this.agentDir, MODELS_CACHE_FILE_NAME);
|
|
135
|
+
let mtimeMs: number;
|
|
136
|
+
try {
|
|
137
|
+
mtimeMs = statSync(path).mtimeMs;
|
|
138
|
+
} catch {
|
|
139
|
+
this.modelsCache = undefined;
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
if (this.modelsCache?.mtimeMs !== mtimeMs) {
|
|
143
|
+
const ids = readJsonObject(path)?.fastModelIds;
|
|
144
|
+
this.modelsCache = {
|
|
145
|
+
mtimeMs,
|
|
146
|
+
ids: new Set(
|
|
147
|
+
Array.isArray(ids)
|
|
148
|
+
? ids.filter((id): id is string => typeof id === "string")
|
|
149
|
+
: [],
|
|
150
|
+
),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return this.modelsCache.ids.has(model.id);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The replacement payload for pi's `before_provider_request`, or
|
|
158
|
+
* `undefined` to keep it. Adds `service_tier` when Fast is on for a
|
|
159
|
+
* capable model of this provider, and strips a priority tier the
|
|
160
|
+
* provider's stale in-memory flag injected when Fast is off, so a global
|
|
161
|
+
* toggle takes effect on every running session's next request.
|
|
162
|
+
*/
|
|
163
|
+
rewritePayload(payload: unknown, model: FastModel | undefined): unknown {
|
|
164
|
+
if (!model || model.provider !== this.providerId()) return undefined;
|
|
165
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const record = payload as JsonObject;
|
|
169
|
+
const effective = this.sessionEnabled || this.isGlobalEnabled();
|
|
170
|
+
if (effective && this.supportsModel(model)) {
|
|
171
|
+
if (record.service_tier === PRIORITY_TIER) return undefined;
|
|
172
|
+
return { ...record, service_tier: PRIORITY_TIER };
|
|
173
|
+
}
|
|
174
|
+
if (!effective && record.service_tier === PRIORITY_TIER) {
|
|
175
|
+
const { service_tier: _dropped, ...rest } = record;
|
|
176
|
+
return rest;
|
|
177
|
+
}
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** User-facing toggle feedback shared by `/fast` and `/fast-global`. */
|
|
183
|
+
export function fastToggleNotice(options: {
|
|
184
|
+
scope: "session" | "global";
|
|
185
|
+
enabled: boolean;
|
|
186
|
+
otherEnabled: boolean;
|
|
187
|
+
modelSupported: boolean;
|
|
188
|
+
}): FastNotice {
|
|
189
|
+
const { scope, enabled, otherEnabled, modelSupported } = options;
|
|
190
|
+
const where =
|
|
191
|
+
scope === "session" ? "for this session" : "globally for all sessions";
|
|
192
|
+
if (!enabled) {
|
|
193
|
+
const residual = otherEnabled
|
|
194
|
+
? scope === "session"
|
|
195
|
+
? " Global Fast mode is still on."
|
|
196
|
+
: " This session's Fast mode is still on."
|
|
197
|
+
: "";
|
|
198
|
+
return {
|
|
199
|
+
message: `Fast mode disabled ${where}.${residual}`,
|
|
200
|
+
level: "info",
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
if (!modelSupported) {
|
|
204
|
+
return {
|
|
205
|
+
message: `Fast mode enabled ${where}, but the current model does not support it.`,
|
|
206
|
+
level: "warning",
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return { message: `Fast mode enabled ${where}.`, level: "info" };
|
|
210
|
+
}
|
package/src/image-preview.ts
CHANGED
|
@@ -119,11 +119,18 @@ function installFocusRefresh(tui: TUI, refresh: () => void): () => void {
|
|
|
119
119
|
return () => controller.restore();
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Pi's terminal allowlist does not know Scribe, so detection leaves Kitty
|
|
124
|
+
* images and OSC 8 hyperlinks off. Scribe supports both. Hyperlinks matter
|
|
125
|
+
* because Pi reopens the OSC 8 sequence on every wrapped physical row, so
|
|
126
|
+
* the terminal's ctrl+click opens the full URL instead of one row's
|
|
127
|
+
* fragment of a hard-wrapped link.
|
|
128
|
+
*/
|
|
129
|
+
export function enableScribeCapabilities(): void {
|
|
123
130
|
if (process.env.TERM_PROGRAM?.toLowerCase() !== "scribe") return;
|
|
124
131
|
const capabilities = getCapabilities();
|
|
125
|
-
if (capabilities.images !== "kitty") {
|
|
126
|
-
setCapabilities({ ...capabilities, images: "kitty" });
|
|
132
|
+
if (capabilities.images !== "kitty" || !capabilities.hyperlinks) {
|
|
133
|
+
setCapabilities({ ...capabilities, images: "kitty", hyperlinks: true });
|
|
127
134
|
}
|
|
128
135
|
}
|
|
129
136
|
|
|
@@ -502,7 +509,11 @@ export function installImagePreview(
|
|
|
502
509
|
target.render = (width: number) => {
|
|
503
510
|
const lines = render.call(target, width);
|
|
504
511
|
sync(target.getText?.() ?? "");
|
|
505
|
-
|
|
512
|
+
// rowsBelow re-renders every component below the editor, so frames
|
|
513
|
+
// without a visible preview skip the measurement entirely.
|
|
514
|
+
if (isVisible()) {
|
|
515
|
+
margin.bottom = lines.length + rowsBelow(tui, target, width);
|
|
516
|
+
}
|
|
506
517
|
return lines;
|
|
507
518
|
};
|
|
508
519
|
target[INSTALLED] = controller;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { TUI } from "@earendil-works/pi-tui";
|
|
2
|
+
|
|
3
|
+
const INSTALLED = Symbol.for("pi-proper-base.osc8-link-ids");
|
|
4
|
+
const OSC8_OPEN = "\x1b]8;;";
|
|
5
|
+
const ESC = "\x1b";
|
|
6
|
+
const BEL = "\x07";
|
|
7
|
+
|
|
8
|
+
type TerminalWriter = {
|
|
9
|
+
write(data: string): void;
|
|
10
|
+
[INSTALLED]?: () => void;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
type TerminalTui = TUI & { terminal?: TerminalWriter };
|
|
14
|
+
|
|
15
|
+
/** FNV-1a of the URI in base36. */
|
|
16
|
+
function linkId(uri: string): string {
|
|
17
|
+
let hash = 0x811c9dc5;
|
|
18
|
+
for (let index = 0; index < uri.length; index++) {
|
|
19
|
+
hash ^= uri.charCodeAt(index);
|
|
20
|
+
hash = Math.imul(hash, 0x01000193);
|
|
21
|
+
}
|
|
22
|
+
return (hash >>> 0).toString(36);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** End of the URI starting at `uriStart`: the position of its BEL or ST
|
|
26
|
+
* terminator, or -1 when the sequence is unterminated or malformed. */
|
|
27
|
+
function uriEndAt(data: string, uriStart: number): number {
|
|
28
|
+
const belAt = data.indexOf(BEL, uriStart);
|
|
29
|
+
const escAt = data.indexOf(ESC, uriStart);
|
|
30
|
+
if (belAt !== -1 && (escAt === -1 || belAt < escAt)) return belAt;
|
|
31
|
+
if (escAt !== -1 && data.startsWith("\\", escAt + 1)) return escAt;
|
|
32
|
+
return -1;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Give anonymous OSC 8 opens a stable URI-derived id. Pi reopens a wrapped
|
|
37
|
+
* hyperlink on every physical row without an id, so terminals assign each
|
|
38
|
+
* row its own link identity and hover-highlight one row at a time. A shared
|
|
39
|
+
* id lets id-aware terminals treat all rows of one link as a unit. Closes
|
|
40
|
+
* (empty URI), opens that already carry params, and malformed or split
|
|
41
|
+
* sequences stay untouched, and data without an anonymous open passes
|
|
42
|
+
* through by reference.
|
|
43
|
+
*/
|
|
44
|
+
export function tagAnonymousOsc8Links(data: string): string {
|
|
45
|
+
let openAt = data.indexOf(OSC8_OPEN);
|
|
46
|
+
if (openAt === -1) return data;
|
|
47
|
+
let result = "";
|
|
48
|
+
let copied = 0;
|
|
49
|
+
while (openAt !== -1) {
|
|
50
|
+
const uriStart = openAt + OSC8_OPEN.length;
|
|
51
|
+
const uriEnd = uriEndAt(data, uriStart);
|
|
52
|
+
if (uriEnd > uriStart) {
|
|
53
|
+
const uri = data.slice(uriStart, uriEnd);
|
|
54
|
+
result += `${data.slice(copied, openAt)}${ESC}]8;id=${linkId(uri)};${uri}`;
|
|
55
|
+
copied = uriEnd;
|
|
56
|
+
}
|
|
57
|
+
openAt = data.indexOf(OSC8_OPEN, uriStart);
|
|
58
|
+
}
|
|
59
|
+
if (copied === 0) return data;
|
|
60
|
+
return result + data.slice(copied);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Rewrite TUI terminal writes so wrapped links share one hyperlink id.
|
|
65
|
+
* Unknown terminal shapes install nothing and keep Pi's native output.
|
|
66
|
+
*/
|
|
67
|
+
export function installOsc8LinkIds(tui: TUI): (() => void) | undefined {
|
|
68
|
+
const terminal = (tui as TerminalTui).terminal;
|
|
69
|
+
if (!terminal || typeof terminal.write !== "function") return undefined;
|
|
70
|
+
if (terminal[INSTALLED]) return terminal[INSTALLED];
|
|
71
|
+
|
|
72
|
+
const hadOwnMethod = Object.hasOwn(terminal, "write");
|
|
73
|
+
const original = terminal.write;
|
|
74
|
+
const wrapped = function (this: TerminalWriter, data: string) {
|
|
75
|
+
return original.call(
|
|
76
|
+
this,
|
|
77
|
+
typeof data === "string" ? tagAnonymousOsc8Links(data) : data,
|
|
78
|
+
);
|
|
79
|
+
};
|
|
80
|
+
terminal.write = wrapped;
|
|
81
|
+
|
|
82
|
+
const dispose = () => {
|
|
83
|
+
if (terminal.write !== wrapped) return;
|
|
84
|
+
if (hadOwnMethod) terminal.write = original;
|
|
85
|
+
else delete (terminal as { write?: unknown }).write;
|
|
86
|
+
delete terminal[INSTALLED];
|
|
87
|
+
};
|
|
88
|
+
terminal[INSTALLED] = dispose;
|
|
89
|
+
return dispose;
|
|
90
|
+
}
|
package/src/prompt-jump.ts
CHANGED
|
@@ -136,9 +136,10 @@ function isPromptRow(line: string): boolean {
|
|
|
136
136
|
* above the first prompt reports position zero, so one down click always
|
|
137
137
|
* advances the reading by one.
|
|
138
138
|
*/
|
|
139
|
-
function promptCount(
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
function promptCount(
|
|
140
|
+
lines: readonly string[],
|
|
141
|
+
top: number,
|
|
142
|
+
): string | undefined {
|
|
142
143
|
let current = 0;
|
|
143
144
|
let total = 0;
|
|
144
145
|
for (let row = 0; row < lines.length; row++) {
|
|
@@ -194,6 +195,14 @@ export function installPromptJump(
|
|
|
194
195
|
target[INSTALLED]?.();
|
|
195
196
|
|
|
196
197
|
let hit: Hit | undefined;
|
|
198
|
+
// The prompt scan walks every transcript line and runs once per frame
|
|
199
|
+
// while the viewport is scrolled up, so it is cached on the pair that
|
|
200
|
+
// changes when the reading can change.
|
|
201
|
+
// ponytail: keyed on (line count, scroll top) — an in-place rewrite that
|
|
202
|
+
// keeps the length can show a stale reading until either key moves.
|
|
203
|
+
let countCache:
|
|
204
|
+
| { length: number; top: number; value: string | undefined }
|
|
205
|
+
| undefined;
|
|
197
206
|
const chipWidth = visibleWidth(UP) + visibleWidth(DOWN);
|
|
198
207
|
const hadOwnMethod = Object.hasOwn(view, "compositeFlashes");
|
|
199
208
|
const flashes = view.compositeFlashes;
|
|
@@ -218,7 +227,23 @@ export function installPromptJump(
|
|
|
218
227
|
);
|
|
219
228
|
// The reading only answers "where am I", so it stays out of the way while
|
|
220
229
|
// the viewport is already following the newest output.
|
|
221
|
-
|
|
230
|
+
let count: string | undefined;
|
|
231
|
+
if (!view.isFollowingOutput) {
|
|
232
|
+
const lines = contentLines(view) ?? [];
|
|
233
|
+
const top = view.viewportTop;
|
|
234
|
+
if (
|
|
235
|
+
!countCache ||
|
|
236
|
+
countCache.length !== lines.length ||
|
|
237
|
+
countCache.top !== top
|
|
238
|
+
) {
|
|
239
|
+
countCache = {
|
|
240
|
+
length: lines.length,
|
|
241
|
+
top,
|
|
242
|
+
value: promptCount(lines, top),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
count = countCache.value;
|
|
246
|
+
}
|
|
222
247
|
if (count) {
|
|
223
248
|
const countWidth = visibleWidth(count);
|
|
224
249
|
// Centred on the chips rather than the screen edge: the chips carry a
|
package/src/recorder.ts
CHANGED
|
@@ -25,11 +25,16 @@ const INSTALLED = Symbol.for("pi-proper-history.recorder");
|
|
|
25
25
|
* pi's submit path cannot cost a history entry. Returns false if the editor
|
|
26
26
|
* already has a recorder, which keeps repeated `session_start` passes from
|
|
27
27
|
* stacking them.
|
|
28
|
+
*
|
|
29
|
+
* `consume` runs first and may swallow a submission entirely: pi checks
|
|
30
|
+
* extension commands before the `input` event, so this is the only place an
|
|
31
|
+
* extension can take over a command name another extension registered.
|
|
28
32
|
*/
|
|
29
33
|
export function installRecorder(
|
|
30
34
|
editor: SubmittableEditor,
|
|
31
35
|
record: (text: string, sourceText: string) => void,
|
|
32
36
|
prepare: (text: string) => string = (text) => text,
|
|
37
|
+
consume?: (text: string) => boolean,
|
|
33
38
|
): boolean {
|
|
34
39
|
const marked = editor as SubmittableEditor & { [INSTALLED]?: boolean };
|
|
35
40
|
if (marked[INSTALLED]) return false;
|
|
@@ -37,6 +42,7 @@ export function installRecorder(
|
|
|
37
42
|
let handler = editor.onSubmit;
|
|
38
43
|
const wrap =
|
|
39
44
|
(next: ((text: string) => void) | undefined) => (text: string) => {
|
|
45
|
+
if (consume?.(text)) return;
|
|
40
46
|
const prepared = prepare(text);
|
|
41
47
|
record(prepared, text);
|
|
42
48
|
next?.(prepared);
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isKeyRelease,
|
|
3
|
+
parseKey,
|
|
4
|
+
type TUI,
|
|
5
|
+
type TuiInputListener,
|
|
6
|
+
} from "@earendil-works/pi-tui";
|
|
7
|
+
|
|
8
|
+
const INSTALLED = Symbol.for("pi-proper-base.selection-dismiss");
|
|
9
|
+
const PASTE_START = "\x1b[200~";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Alternate-screen renderer surface holding the mouse-selection state. Every
|
|
13
|
+
* field is TypeScript-private upstream, so the shape is duck-typed here and a
|
|
14
|
+
* rename disables the dismissal rather than breaking selection itself.
|
|
15
|
+
*/
|
|
16
|
+
type SelectionHost = TUI & {
|
|
17
|
+
getSelectionBounds?(): unknown;
|
|
18
|
+
stopSelectionAutoScroll?(): void;
|
|
19
|
+
selectionPressActive?: boolean;
|
|
20
|
+
selectionDragged?: boolean;
|
|
21
|
+
selectionAnchor?: unknown;
|
|
22
|
+
selectionFocus?: unknown;
|
|
23
|
+
selectionGranularity?: string;
|
|
24
|
+
selectionInitialRange?: unknown;
|
|
25
|
+
[INSTALLED]?: () => void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Whether terminal input is a keystroke or paste headed for the focused
|
|
30
|
+
* component, as opposed to a terminal report such as a cell-size response.
|
|
31
|
+
* Mouse, wheel, viewport-key, and focus input never reaches the listener at
|
|
32
|
+
* all: the renderer's own earlier listener consumes it.
|
|
33
|
+
*/
|
|
34
|
+
export function isTypingInput(data: string): boolean {
|
|
35
|
+
if (data.length === 0) return false;
|
|
36
|
+
// Printable text, Enter, Backspace, control chars, non-ASCII graphemes,
|
|
37
|
+
// and multi-character bursts all arrive without an escape prefix.
|
|
38
|
+
if (!data.startsWith("\x1b")) return true;
|
|
39
|
+
if (data.startsWith(PASTE_START)) return true;
|
|
40
|
+
// Kitty release events repeat the press encoding and must not re-dismiss.
|
|
41
|
+
if (isKeyRelease(data)) return false;
|
|
42
|
+
return parseKey(data) !== undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Dismiss the fullscreen mouse selection when typing reaches the editor.
|
|
47
|
+
*
|
|
48
|
+
* Pi's alternate-screen renderer clears its selection on focus loss and on
|
|
49
|
+
* the next mouse press, but never on keyboard input, so a highlight survives
|
|
50
|
+
* typing and keeps painting whatever new content lands on its rows. The copy
|
|
51
|
+
* already happened on mouse release, so dropping the highlight loses nothing.
|
|
52
|
+
*
|
|
53
|
+
* The listener registers after the renderer's own constructor-installed
|
|
54
|
+
* listener, so it only sees input the viewport declined: scroll keys and
|
|
55
|
+
* mouse gestures keep the selection, matching terminal convention. Keys the
|
|
56
|
+
* caller marks preserved also keep it: Pi 0.84.4's `app.message.copy` action
|
|
57
|
+
* (Ctrl+X) copies the active selection when `fullscreenCopyOnSelect` is
|
|
58
|
+
* disabled, and it runs at the editor after this listener, so dismissing on
|
|
59
|
+
* that keystroke would clear the selection before the copy reads it. It resets
|
|
60
|
+
* the same private fields the renderer's focus-loss branch resets and never
|
|
61
|
+
* consumes the input, so the keystroke still reaches the editor.
|
|
62
|
+
*
|
|
63
|
+
* Renderers without the selection surface, including regular mode, install
|
|
64
|
+
* nothing. The renderer outlives an extension reload, so installation takes
|
|
65
|
+
* over a previous instance's listener and disposal is identity-guarded.
|
|
66
|
+
*
|
|
67
|
+
* @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Selection dismissal]]
|
|
68
|
+
*/
|
|
69
|
+
export function installSelectionDismiss(
|
|
70
|
+
tui: TUI,
|
|
71
|
+
isPreservedInput?: (data: string) => boolean,
|
|
72
|
+
): (() => void) | undefined {
|
|
73
|
+
const host = tui as SelectionHost;
|
|
74
|
+
if (
|
|
75
|
+
typeof host.getSelectionBounds !== "function" ||
|
|
76
|
+
typeof host.stopSelectionAutoScroll !== "function"
|
|
77
|
+
) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
// A reload runs the new instance's editor factory before the outgoing
|
|
81
|
+
// instance shuts down, so take over any listener it left on the renderer.
|
|
82
|
+
host[INSTALLED]?.();
|
|
83
|
+
|
|
84
|
+
const listener: TuiInputListener = (data) => {
|
|
85
|
+
// A drag in progress owns the selection it is building.
|
|
86
|
+
if (host.selectionPressActive) return undefined;
|
|
87
|
+
if (host.getSelectionBounds?.() === undefined) return undefined;
|
|
88
|
+
if (!isTypingInput(data)) return undefined;
|
|
89
|
+
if (isPreservedInput?.(data)) return undefined;
|
|
90
|
+
host.stopSelectionAutoScroll?.();
|
|
91
|
+
host.selectionAnchor = undefined;
|
|
92
|
+
host.selectionFocus = undefined;
|
|
93
|
+
host.selectionGranularity = "character";
|
|
94
|
+
host.selectionInitialRange = undefined;
|
|
95
|
+
host.selectionDragged = false;
|
|
96
|
+
host.requestRender();
|
|
97
|
+
return undefined;
|
|
98
|
+
};
|
|
99
|
+
const unsubscribe = tui.addInputListener(listener);
|
|
100
|
+
|
|
101
|
+
// A disposer left over from a previous extension instance must not remove
|
|
102
|
+
// the listener that replaced it.
|
|
103
|
+
const dispose = () => {
|
|
104
|
+
if (host[INSTALLED] !== dispose) return;
|
|
105
|
+
unsubscribe();
|
|
106
|
+
delete host[INSTALLED];
|
|
107
|
+
};
|
|
108
|
+
host[INSTALLED] = dispose;
|
|
109
|
+
return dispose;
|
|
110
|
+
}
|