@each1024/pi-mini-mode 2.0.9 → 2.0.10
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 +9 -6
- package/README.zh-CN.md +6 -8
- package/extensions/footer-status.ts +46 -1189
- package/lib/agent-render.ts +203 -0
- package/lib/agent-state.ts +199 -0
- package/lib/agent-view.ts +5 -519
- package/lib/agent-widgets.ts +129 -0
- package/lib/footer-line.ts +206 -0
- package/lib/input-editor-paths.ts +79 -0
- package/lib/input-editor.ts +184 -0
- package/lib/input-enhancements-types.ts +49 -0
- package/lib/input-enhancements.ts +15 -797
- package/lib/input-hover-preview.ts +122 -0
- package/lib/input-image-graphics.ts +34 -0
- package/lib/input-image-paths.ts +120 -0
- package/lib/input-inline-images.ts +114 -0
- package/lib/input-skill-completion.ts +132 -0
- package/lib/minimal-output.ts +379 -0
- package/lib/minimal-turns.ts +203 -0
- package/lib/settings-web.ts +9 -2
- package/lib/settings.html +5 -4
- package/lib/settings.ts +153 -0
- package/lib/thinking-preview.ts +30 -19
- package/lib/thinking-stream.ts +89 -0
- package/lib/transcript-adapter.ts +15 -501
- package/lib/transcript-cards.ts +67 -0
- package/lib/transcript-notice-render.ts +211 -0
- package/lib/transcript-notices.ts +238 -0
- package/lib/usage.ts +137 -0
- package/package.json +4 -2
|
@@ -11,538 +11,25 @@
|
|
|
11
11
|
* and call cleanup.refresh() when the setting changes; call cleanup from
|
|
12
12
|
* `session_shutdown`.
|
|
13
13
|
*/
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} from "
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
14
|
+
import type { ExtensionAPI, ExtensionContext, InputEvent, InputEventResult } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { deleteKittyImage } from "@earendil-works/pi-tui";
|
|
16
|
+
import type { Enhancements, InputEnhancementsCleanup } from "./input-enhancements-types.ts";
|
|
17
|
+
import { installEditor, liveUI } from "./input-editor.ts";
|
|
18
|
+
import { handleTerminalInput, requestPreview, setPointer } from "./input-hover-preview.ts";
|
|
19
|
+
import { clearInlineGraphics, syncInlineImages } from "./input-inline-images.ts";
|
|
20
|
+
import { createSkillAutocompleteProvider, handleInput, readSkillCommands } from "./input-skill-completion.ts";
|
|
21
|
+
|
|
22
|
+
export { MAX_PREVIEW_BYTES, imagePathsInLine, imagePathAtCursor, imageDirectoryUrl, readPreview } from "./input-image-paths.ts";
|
|
23
|
+
export type { ImagePathMatch, PreviewImage, PreviewNote, Preview } from "./input-image-paths.ts";
|
|
24
|
+
export { readSkillCommands, skillBlock, skillTokensIn, expandSkillTokens, createSkillAutocompleteProvider } from "./input-skill-completion.ts";
|
|
25
|
+
export type { SkillEntry, SkillToken } from "./input-skill-completion.ts";
|
|
26
|
+
export { previewLines } from "./input-image-graphics.ts";
|
|
27
|
+
export { inlinePreviewLines } from "./input-inline-images.ts";
|
|
28
|
+
export type { PreviewState, InputEnhancementsCleanup } from "./input-enhancements-types.ts";
|
|
25
29
|
|
|
26
30
|
export const INPUT_ENHANCEMENTS_SETTING = "pi-mini-mode-input-enhancements";
|
|
27
|
-
export const MAX_PREVIEW_BYTES = 20 * 1024 * 1024;
|
|
28
|
-
const MAX_PREVIEW_ENCODED_BYTES = 1024 * 1024;
|
|
29
|
-
const MAX_PREVIEW_WIDTH_PX = 1200;
|
|
30
|
-
const MAX_PREVIEW_HEIGHT_PX = 800;
|
|
31
|
-
|
|
32
|
-
const IMAGE_MIME: Record<string, string> = {
|
|
33
|
-
".png": "image/png",
|
|
34
|
-
".jpg": "image/jpeg",
|
|
35
|
-
".jpeg": "image/jpeg",
|
|
36
|
-
".gif": "image/gif",
|
|
37
|
-
".webp": "image/webp",
|
|
38
|
-
};
|
|
39
|
-
const SKILL_TOKEN = /(?:^|\s)(\/skill:[^\s/]+)/g;
|
|
40
|
-
const SKILL_PREFIX = /(?:^|[ \t])(\/(?:skill:)?[^/\s]*)$/;
|
|
41
|
-
|
|
42
|
-
export interface ImagePathMatch {
|
|
43
|
-
path: string;
|
|
44
|
-
/** Source indices in the line (after terminal sequences are stripped). */
|
|
45
|
-
start: number;
|
|
46
|
-
end: number;
|
|
47
|
-
/** Visible columns, for rendered lines. */
|
|
48
|
-
startCol: number;
|
|
49
|
-
endCol: number;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function absolutePath(path: string, cwd: string): string {
|
|
53
|
-
if (path === "~") return homedir();
|
|
54
|
-
if (path.startsWith("~/")) return join(homedir(), path.slice(2));
|
|
55
|
-
return isAbsolute(path) ? path : resolve(cwd, path);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Image paths in one line, with source indices and visible columns. */
|
|
59
|
-
export function imagePathsInLine(line: string): ImagePathMatch[] {
|
|
60
|
-
const plain = stripTerminalSequences(line);
|
|
61
|
-
const matches: ImagePathMatch[] = [];
|
|
62
|
-
// ponytail: accept existing absolute clipboard paths with spaces; extend to cwd-aware relative paths if needed.
|
|
63
|
-
const spaced = [...plain.matchAll(/(?:^|[\s"'`])((?:\/|~\/|\.\.?\/)[^\n"'`<>()[\]{},。;!?]+?\.(?:png|jpe?g|gif|webp))(?=$|[\s"'`<>()[\]{},。;!?])/gi)]
|
|
64
|
-
.map(match => ({ path: match[1], start: match.index + match[0].length - match[1].length, end: match.index + match[0].length }))
|
|
65
|
-
.filter(match => isAbsolute(match.path) && match.path.includes(" ") && existsSync(match.path));
|
|
66
|
-
for (const { path, start, end } of [...spaced, ...filePaths(plain).filter(match => !spaced.some(full => match.start >= full.start && match.start < full.end))]) {
|
|
67
|
-
if (!IMAGE_MIME[extname(path).toLowerCase()]) continue;
|
|
68
|
-
matches.push({ path, start, end, startCol: visibleWidth(plain.slice(0, start)), endCol: visibleWidth(plain.slice(0, end)) });
|
|
69
|
-
}
|
|
70
|
-
return matches;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Image path token the cursor sits in, if any. */
|
|
74
|
-
export function imagePathAtCursor(text: string, line: number, col: number): string | undefined {
|
|
75
|
-
const current = text.split("\n")[line];
|
|
76
|
-
if (current === undefined) return undefined;
|
|
77
|
-
return imagePathsInLine(current).find((match) => col >= match.start && col <= match.end)?.path;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** OSC 8 target for an image path: the `file://` URL of its directory. */
|
|
81
|
-
export function imageDirectoryUrl(path: string, cwd: string): string {
|
|
82
|
-
return pathToFileURL(dirname(absolutePath(path, cwd))).href;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export interface PreviewImage {
|
|
86
|
-
kind: "image";
|
|
87
|
-
path: string;
|
|
88
|
-
mimeType: string;
|
|
89
|
-
base64: string;
|
|
90
|
-
widthPx: number;
|
|
91
|
-
heightPx: number;
|
|
92
|
-
}
|
|
93
|
-
export interface PreviewNote {
|
|
94
|
-
kind: "note";
|
|
95
|
-
path: string;
|
|
96
|
-
note: string;
|
|
97
|
-
}
|
|
98
|
-
export type Preview = PreviewImage | PreviewNote;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Read a preview for an image path. Returns undefined when there is nothing to show
|
|
102
|
-
* (unknown extension, missing file, directory) so typing never raises a hint.
|
|
103
|
-
*/
|
|
104
|
-
export async function readPreview(path: string, cwd: string, bounds = { widthPx: MAX_PREVIEW_WIDTH_PX, heightPx: MAX_PREVIEW_HEIGHT_PX }): Promise<Preview | undefined> {
|
|
105
|
-
const absolute = absolutePath(path, cwd);
|
|
106
|
-
const mimeType = IMAGE_MIME[extname(absolute).toLowerCase()];
|
|
107
|
-
if (!mimeType) return undefined;
|
|
108
|
-
const file = await open(absolute, "r").catch(() => undefined);
|
|
109
|
-
if (!file) return undefined;
|
|
110
|
-
try {
|
|
111
|
-
const info = await file.stat();
|
|
112
|
-
if (!info.isFile()) return undefined;
|
|
113
|
-
if (info.size > MAX_PREVIEW_BYTES) return { kind: "note", path, note: `超过 ${MAX_PREVIEW_BYTES / 1024 / 1024}MB` };
|
|
114
|
-
const bytes = Buffer.alloc(info.size);
|
|
115
|
-
let offset = 0;
|
|
116
|
-
while (offset < bytes.length) {
|
|
117
|
-
const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
|
|
118
|
-
if (!bytesRead) break;
|
|
119
|
-
offset += bytesRead;
|
|
120
|
-
}
|
|
121
|
-
const data = bytes.subarray(0, offset);
|
|
122
|
-
const base64 = data.toString("base64");
|
|
123
|
-
const dimensions = getImageDimensions(base64, mimeType);
|
|
124
|
-
if (!dimensions) return { kind: "note", path, note: "无法解析图片尺寸" };
|
|
125
|
-
const maxWidth = Math.max(1, Math.min(MAX_PREVIEW_WIDTH_PX, Math.floor(bounds.widthPx)));
|
|
126
|
-
const maxHeight = Math.max(1, Math.min(MAX_PREVIEW_HEIGHT_PX, Math.floor(bounds.heightPx)));
|
|
127
|
-
// renderImage controls cell placement, not pixels; its Kitty f=100 payload must be PNG.
|
|
128
|
-
const resized = dimensions.widthPx <= maxWidth && dimensions.heightPx <= maxHeight && base64.length < MAX_PREVIEW_ENCODED_BYTES
|
|
129
|
-
? { data: base64, mimeType } : await resizeImage(data, mimeType, { maxWidth, maxHeight, maxBytes: MAX_PREVIEW_ENCODED_BYTES });
|
|
130
|
-
if (!resized) return { kind: "note", path, note: "无法缩小图片预览" };
|
|
131
|
-
const png = resized.mimeType === "image/png" ? resized
|
|
132
|
-
: await (await import("@earendil-works/pi-coding-agent")).convertToPng(resized.data, resized.mimeType);
|
|
133
|
-
if (!png) return { kind: "note", path, note: "无法转换图片预览" };
|
|
134
|
-
if (png.data.length > MAX_PREVIEW_ENCODED_BYTES) return { kind: "note", path, note: "图片预览过大" };
|
|
135
|
-
return { kind: "image", path, mimeType: png.mimeType, base64: png.data, widthPx: dimensions.widthPx, heightPx: dimensions.heightPx };
|
|
136
|
-
} catch {
|
|
137
|
-
return { kind: "note", path, note: "读取失败" };
|
|
138
|
-
} finally { await file.close(); }
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export interface SkillEntry {
|
|
142
|
-
/** Registry command name, e.g. `skill:release`. */
|
|
143
|
-
command: string;
|
|
144
|
-
name: string;
|
|
145
|
-
path: string;
|
|
146
|
-
baseDir: string;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** Skills registered for this session, keyed by command name (`skill:<name>`). */
|
|
150
|
-
export function readSkillCommands(pi: Pick<ExtensionAPI, "getCommands">): Map<string, SkillEntry> {
|
|
151
|
-
const skills = new Map<string, SkillEntry>();
|
|
152
|
-
for (const command of pi.getCommands()) {
|
|
153
|
-
const path = command.sourceInfo?.path;
|
|
154
|
-
if (command.source !== "skill" || !path) continue;
|
|
155
|
-
skills.set(command.name, { command: command.name, name: command.name.replace(/^skill:/, ""), path, baseDir: command.sourceInfo.baseDir ?? dirname(path) });
|
|
156
|
-
}
|
|
157
|
-
return skills;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Same wrapper the core `_expandSkillCommand` uses. */
|
|
161
|
-
export function skillBlock(skill: SkillEntry, body: string): string {
|
|
162
|
-
return `<skill name="${skill.name}" location="${skill.path}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
export interface SkillToken {
|
|
166
|
-
token: string;
|
|
167
|
-
start: number;
|
|
168
|
-
end: number;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/** `/skill:name` tokens at whitespace boundaries. */
|
|
172
|
-
export function skillTokensIn(text: string): SkillToken[] {
|
|
173
|
-
const tokens: SkillToken[] = [];
|
|
174
|
-
for (const match of text.matchAll(SKILL_TOKEN)) {
|
|
175
|
-
const token = match[1];
|
|
176
|
-
const start = match.index + match[0].length - token.length;
|
|
177
|
-
tokens.push({ token, start, end: start + token.length });
|
|
178
|
-
}
|
|
179
|
-
return tokens;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Expand registered `/skill:name` tokens that the core would not expand itself.
|
|
184
|
-
* Leave single leading skills to the core; expand multiple skills in place.
|
|
185
|
-
*/
|
|
186
|
-
export async function expandSkillTokens(
|
|
187
|
-
text: string,
|
|
188
|
-
skills: Map<string, SkillEntry>,
|
|
189
|
-
readSkill: (path: string) => Promise<string>,
|
|
190
|
-
onError: (skill: SkillEntry, error: unknown) => void,
|
|
191
|
-
): Promise<string | undefined> {
|
|
192
|
-
const tokens = skillTokensIn(text).filter((token) => skills.has(token.token.slice(1)));
|
|
193
|
-
if (tokens.length === 0 || (tokens.length === 1 && tokens[0].start === 0)) return undefined;
|
|
194
|
-
const parts: string[] = [];
|
|
195
|
-
let cursor = 0;
|
|
196
|
-
for (const token of tokens) {
|
|
197
|
-
const skill = skills.get(token.token.slice(1));
|
|
198
|
-
if (!skill) continue;
|
|
199
|
-
let body: string;
|
|
200
|
-
try {
|
|
201
|
-
body = stripFrontmatter(await readSkill(skill.path)).trim();
|
|
202
|
-
} catch (error) {
|
|
203
|
-
onError(skill, error);
|
|
204
|
-
continue; // Keep the token verbatim and let the rest of the text survive.
|
|
205
|
-
}
|
|
206
|
-
parts.push(text.slice(cursor, token.start), skillBlock(skill, body));
|
|
207
|
-
cursor = token.end;
|
|
208
|
-
}
|
|
209
|
-
if (parts.length === 0) return undefined;
|
|
210
|
-
parts.push(text.slice(cursor));
|
|
211
|
-
return parts.join("");
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** Skill completion layered on the built-in provider. */
|
|
215
|
-
export function createSkillAutocompleteProvider(current: AutocompleteProvider, listSkills: () => Map<string, SkillEntry>, enabled: () => boolean = () => true): AutocompleteProvider {
|
|
216
|
-
return {
|
|
217
|
-
triggerCharacters: ["/"],
|
|
218
|
-
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
219
|
-
if (!enabled()) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
220
|
-
const before = (lines[cursorLine] ?? "").slice(0, cursorCol);
|
|
221
|
-
const match = SKILL_PREFIX.exec(before);
|
|
222
|
-
if (!match) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
223
|
-
const prefix = match[1];
|
|
224
|
-
const typed = prefix.slice(1).replace(/^skill:/, "");
|
|
225
|
-
const ours: AutocompleteItem[] = [];
|
|
226
|
-
for (const skill of listSkills().values()) {
|
|
227
|
-
if (skill.command.startsWith(`skill:${typed}`) || skill.name.startsWith(typed)) ours.push({ value: `/${skill.command}`, label: skill.command });
|
|
228
|
-
}
|
|
229
|
-
// Mid-line only skills: the built-in provider would offer file paths there.
|
|
230
|
-
if (cursorLine !== 0 || prefix.length !== before.length) return ours.length > 0 ? { items: ours, prefix } : current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
231
|
-
const builtin = await current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
232
|
-
const items = (builtin?.items ?? []).filter((item) => !ours.some((skill) => skill.value.slice(1) === item.value.replace(/^\//, "")));
|
|
233
|
-
if (items.length === 0 && ours.length === 0) return null;
|
|
234
|
-
return { items: [...items, ...ours], prefix };
|
|
235
|
-
},
|
|
236
|
-
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
237
|
-
if (!item.value.startsWith("/skill:")) return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
238
|
-
// The built-in provider special-cases line-start slash commands; replace our own fragment.
|
|
239
|
-
const line = lines[cursorLine] ?? "";
|
|
240
|
-
const start = Math.max(0, cursorCol - prefix.length);
|
|
241
|
-
const rest = line.slice(cursorCol);
|
|
242
|
-
const text = `${item.value}${/^[ \t]/.test(rest) ? "" : " "}`;
|
|
243
|
-
const next = [...lines];
|
|
244
|
-
next[cursorLine] = `${line.slice(0, start)}${text}${rest}`;
|
|
245
|
-
return { lines: next, cursorLine, cursorCol: start + text.length };
|
|
246
|
-
},
|
|
247
|
-
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
248
|
-
return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
|
|
249
|
-
},
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
export interface PreviewState {
|
|
254
|
-
path?: string;
|
|
255
|
-
note?: string;
|
|
256
|
-
graphic?: NonNullable<ReturnType<typeof renderImage>>;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function positionedGraphic(sequence: string, up: number, right: number): string {
|
|
260
|
-
// Pi <=0.87's ANSI slicer needs an SGR terminator after relative motion.
|
|
261
|
-
// Otty places Kitty graphics against the last committed cursor while DEC 2026
|
|
262
|
-
// buffers text/cursor updates. Commit the target before the APC, then resume
|
|
263
|
-
// Pi's synchronized frame. Other terminals retain their atomic rendering.
|
|
264
|
-
const flush = process.env.TERM_PROGRAM?.toLowerCase() === "otty"
|
|
265
|
-
&& !process.env.TMUX && !process.env.STY && !/^(tmux|screen)/i.test(process.env.TERM ?? "")
|
|
266
|
-
&& sequence.startsWith("\x1b_G");
|
|
267
|
-
return `\x1b[s\x1b[${up}A\x1b[${right}C\x1b[0m${flush ? "\x1b[?2026l\x1b[0m" : ""}${sequence}\x1b[u${flush ? "\x1b[?2026h" : ""}\x1b[0m`;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
function imageLayoutKey(): string {
|
|
271
|
-
const cells = getCellDimensions();
|
|
272
|
-
return `${getCapabilities().images}:${cells.widthPx}:${cells.heightPx}`;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/** A tightly sized image frame. Draw after clearing its interior, never a path-only tooltip. */
|
|
276
|
-
export function previewLines(preview: PreviewState, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
277
|
-
if (!preview.path) return [];
|
|
278
|
-
const graphic = preview.graphic;
|
|
279
|
-
const innerWidth = Math.max(1, Math.min(width - 2, graphic?.columns ?? 26));
|
|
280
|
-
const border = (text: string) => theme.fg("border", text);
|
|
281
|
-
const lines = [border(`╭${"─".repeat(innerWidth)}╮`)];
|
|
282
|
-
if (graphic) {
|
|
283
|
-
for (let row = 0; row < graphic.rows; row++) lines.push(border("│") + " ".repeat(innerWidth) + border("│"));
|
|
284
|
-
} else lines.push(border("│") + truncateToWidth(preview.note ?? "无法预览图片", innerWidth, "", true) + border("│"));
|
|
285
|
-
const draw = graphic ? positionedGraphic(graphic.sequence, graphic.rows, 1) : "";
|
|
286
|
-
lines.push(draw + border(`╰${"─".repeat(innerWidth)}╯`));
|
|
287
|
-
return lines;
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
type EditorFactoryFunction = NonNullable<Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0]>;
|
|
291
|
-
type CursorEditor = EditorComponent & { getCursor?(): { line: number; col: number } };
|
|
292
|
-
|
|
293
|
-
export interface InputEnhancementsCleanup {
|
|
294
|
-
(): void;
|
|
295
|
-
refresh(): void;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
interface Enhancements {
|
|
299
|
-
pi: ExtensionAPI;
|
|
300
|
-
enabled: () => boolean;
|
|
301
|
-
ctx?: ExtensionContext;
|
|
302
|
-
cwd?: string;
|
|
303
|
-
theme?: ExtensionContext["ui"]["theme"];
|
|
304
|
-
generation?: unknown;
|
|
305
|
-
preview: PreviewState;
|
|
306
|
-
previewSource?: Preview;
|
|
307
|
-
previewLayout?: string;
|
|
308
|
-
previewToken: number;
|
|
309
|
-
overlayReady: boolean;
|
|
310
|
-
previewTui?: { requestRender(): void };
|
|
311
|
-
previewHandle?: OverlayHandle;
|
|
312
|
-
tui?: TUI;
|
|
313
|
-
requestedPath?: string;
|
|
314
|
-
pointer?: boolean;
|
|
315
|
-
previewAnchor?: { x: number; y: number };
|
|
316
|
-
hoverLink?: { row: number; start: number; end: number; path: string };
|
|
317
|
-
previewOptions?: OverlayOptions;
|
|
318
|
-
previewMode: () => "hover" | "inline";
|
|
319
|
-
inlineImages: Map<string, Preview | undefined>;
|
|
320
|
-
inlinePending: Map<string, Promise<Preview | undefined>>;
|
|
321
|
-
inlineGraphics: Map<string, { layout: string } & NonNullable<ReturnType<typeof renderImage>>>;
|
|
322
|
-
baseFactory?: EditorFactoryFunction;
|
|
323
|
-
editor?: EditorComponent;
|
|
324
|
-
editorFactory?: EditorFactoryFunction;
|
|
325
|
-
unsubscribeInput?: () => void;
|
|
326
|
-
restoreViewportInput?: () => void;
|
|
327
|
-
cleanup: InputEnhancementsCleanup;
|
|
328
|
-
}
|
|
329
31
|
|
|
330
32
|
let installed: Enhancements | undefined;
|
|
331
|
-
let viewportHook: { restore(): void } | undefined;
|
|
332
|
-
|
|
333
|
-
/** TUI survives /new; detach any previous instance's mouse hook before wrapping again. */
|
|
334
|
-
function unhookViewportInput(): void {
|
|
335
|
-
viewportHook?.restore();
|
|
336
|
-
viewportHook = undefined;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
function hookViewportInput(tui: TUI, onInput: (data: string) => void): () => void {
|
|
340
|
-
unhookViewportInput();
|
|
341
|
-
const viewport = tui as TUI & { handleViewportInput?(data: string): { consume?: boolean } | undefined };
|
|
342
|
-
const original = viewport.handleViewportInput;
|
|
343
|
-
if (!original) return () => {};
|
|
344
|
-
const observe = (data: string) => {
|
|
345
|
-
onInput(data);
|
|
346
|
-
return original.call(tui, data);
|
|
347
|
-
};
|
|
348
|
-
viewport.handleViewportInput = observe;
|
|
349
|
-
const hook = {
|
|
350
|
-
restore() {
|
|
351
|
-
if (viewport.handleViewportInput === observe) viewport.handleViewportInput = original;
|
|
352
|
-
},
|
|
353
|
-
};
|
|
354
|
-
viewportHook = hook;
|
|
355
|
-
return () => {
|
|
356
|
-
if (viewportHook !== hook) return;
|
|
357
|
-
unhookViewportInput();
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
function liveUI(ctx?: ExtensionContext): ExtensionContext["ui"] | undefined {
|
|
362
|
-
if (!ctx) return undefined;
|
|
363
|
-
try {
|
|
364
|
-
return ctx.ui;
|
|
365
|
-
} catch {
|
|
366
|
-
return undefined;
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/** Compact image attachments without losing their paths on submit, reload, or external editing. */
|
|
371
|
-
function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolean, isInline: () => boolean, theme: ExtensionContext["ui"]["theme"], inlineState: Enhancements, onCursor: () => void, onHoverEditor: (editor: EditorComponent, event: TuiMouseEvent) => void, onEditorRender: () => void = () => {}): EditorComponent {
|
|
372
|
-
const attachments = new Map<string, string>();
|
|
373
|
-
const sources = new Map<string, string>();
|
|
374
|
-
const expand = (text: string) => text.replace(/\[img\d+\]/g, (label, index) => {
|
|
375
|
-
const path = sources.get(label) ?? attachments.get(label);
|
|
376
|
-
const next = /^\[img\d+\]/.exec(text.slice(index + label.length));
|
|
377
|
-
return path === undefined ? label : path + (next && attachments.has(next[0]) ? " " : "");
|
|
378
|
-
});
|
|
379
|
-
const compact = (text: string) => {
|
|
380
|
-
if (!isEnabled()) return text;
|
|
381
|
-
const replacements = imagePathsInLine(text).map(match => {
|
|
382
|
-
const source = text.slice(match.start, match.end);
|
|
383
|
-
let label = [...attachments].find(([label, path]) => path === match.path && (sources.get(label) ?? path) === source)?.[0];
|
|
384
|
-
if (!label) {
|
|
385
|
-
label = `[img${attachments.size + 1}]`;
|
|
386
|
-
attachments.set(label, match.path);
|
|
387
|
-
sources.set(label, source);
|
|
388
|
-
}
|
|
389
|
-
return { ...match, label };
|
|
390
|
-
});
|
|
391
|
-
for (const match of replacements.reverse()) text = text.slice(0, match.start) + match.label + text.slice(match.end);
|
|
392
|
-
return text;
|
|
393
|
-
};
|
|
394
|
-
// ponytail: Pi 0.87 image paste calls the private inserter, bypassing the public proxy; replace with a public attachment API when available.
|
|
395
|
-
const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; insertTextAtCursorInternal?(text: string): void; setTextInternal?(text: string, placement?: "start" | "end"): void; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string>; state?: { lines: string[] } };
|
|
396
|
-
core.imageAttachments = attachments;
|
|
397
|
-
// Rendering reads the stored lines directly, so the submit expansion must not put the temp path back on screen.
|
|
398
|
-
if (core.state) core.state.lines = compact(core.state.lines.join("\n")).split("\n");
|
|
399
|
-
if (core.expandPasteMarkers) { const original = core.expandPasteMarkers.bind(core); core.expandPasteMarkers = text => expand(original(text)); }
|
|
400
|
-
if (core.insertTextAtCursorInternal) { const insert = core.insertTextAtCursorInternal.bind(core); core.insertTextAtCursorInternal = text => insert(compact(text)); }
|
|
401
|
-
// Native history navigation bypasses setText; compact the restored draft before its onChange/render.
|
|
402
|
-
if (core.setTextInternal) { const restore = core.setTextInternal.bind(core); core.setTextInternal = (text, placement) => restore(compact(text), placement); }
|
|
403
|
-
const pasteEditor = inner as EditorComponent & { handlePaste?(text: string): void };
|
|
404
|
-
if (pasteEditor.handlePaste) { const paste = pasteEditor.handlePaste.bind(inner); pasteEditor.handlePaste = text => paste(compact(text)); }
|
|
405
|
-
if (core.segment) {
|
|
406
|
-
const original = core.segment.bind(core);
|
|
407
|
-
core.segment = (text, mode) => {
|
|
408
|
-
const spans = [...text.matchAll(/\[img\d+\]/g)].filter(match => attachments.has(match[0]));
|
|
409
|
-
return [...original(text, mode)].flatMap(segment => {
|
|
410
|
-
const span = spans.find(match => segment.index >= match.index && segment.index < match.index + match[0].length);
|
|
411
|
-
return !span ? [segment] : segment.index === span.index ? [{ segment: span[0], index: span.index, input: text }] : [];
|
|
412
|
-
});
|
|
413
|
-
};
|
|
414
|
-
}
|
|
415
|
-
let onChange: ((text: string) => void) | undefined;
|
|
416
|
-
return new Proxy(inner, {
|
|
417
|
-
get(target, property, receiver) {
|
|
418
|
-
if (property === "getText") return () => expand(target.getText());
|
|
419
|
-
if (property === "setText" || property === "insertTextAtCursor" || property === "insertTextAtCursorInternal") return (text: string) => { const insert = (target as EditorComponent & { insertTextAtCursorInternal?(value: string): void })[property] as ((value: string) => void) | undefined; insert?.call(target, compact(text)); onEditorRender(); };
|
|
420
|
-
if (property === "render") {
|
|
421
|
-
return (width: number) => {
|
|
422
|
-
const lines = target.render(width);
|
|
423
|
-
onEditorRender();
|
|
424
|
-
const linked = isEnabled() ? linkImagePaths(lines, target, cwd, width) : lines;
|
|
425
|
-
if (!isInline()) return linked;
|
|
426
|
-
const cards = inlinePreviewLines(inlineState, theme, width);
|
|
427
|
-
if (!cards.length) return linked;
|
|
428
|
-
// ponytail: Pi's editor has no rich image nodes; keep its cursor/text layout and mask owned tokens only in render. Replace with native attachment nodes when available.
|
|
429
|
-
const labels = new Set(attachments.keys());
|
|
430
|
-
const body = linked.map((line, row) => row > 0 && row <= ((target as EditorComponent & { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0) ? hideImageLabels(line, labels, theme, lines[row]) : line);
|
|
431
|
-
return [...cards, ...body];
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
if (property === "handleMouse") {
|
|
435
|
-
return (event: TuiMouseEvent) => {
|
|
436
|
-
const offset = isInline() ? inlinePreviewLines(inlineState, theme, event.width).length : 0;
|
|
437
|
-
const adjusted = offset ? { ...event, y: event.y - offset } : event;
|
|
438
|
-
const result = !offset || event.y >= offset ? target.handleMouse?.(adjusted) : undefined;
|
|
439
|
-
if (event.type === "move") onHoverEditor(target, adjusted);
|
|
440
|
-
else if (event.type === "click") void requestPreview(inlineState, undefined);
|
|
441
|
-
return result;
|
|
442
|
-
};
|
|
443
|
-
}
|
|
444
|
-
if (property === "handleInput") {
|
|
445
|
-
return (data: string) => {
|
|
446
|
-
if (isEnabled() && matchesKey(data, "super+v")) { (target as CustomEditor).onPasteImage?.(); return; }
|
|
447
|
-
target.handleInput(data);
|
|
448
|
-
// Pi explicitly excludes '/' from provider triggerCharacters; request inline completions ourselves.
|
|
449
|
-
const native = target as CursorEditor & { tryTriggerAutocomplete?(): void };
|
|
450
|
-
const cursor = native.getCursor?.();
|
|
451
|
-
if (isEnabled() && cursor && data.length === 1 && /[\w/:-]/.test(data)
|
|
452
|
-
&& SKILL_PREFIX.test((target.getText().split("\n")[cursor.line] ?? "").slice(0, cursor.col))) native.tryTriggerAutocomplete?.();
|
|
453
|
-
onCursor();
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
return Reflect.get(target, property, receiver);
|
|
457
|
-
},
|
|
458
|
-
set(target, property, value) {
|
|
459
|
-
if (property === "onChange") {
|
|
460
|
-
onChange = value as ((text: string) => void) | undefined;
|
|
461
|
-
return Reflect.set(target, property, (text: string) => {
|
|
462
|
-
onChange?.(expand(text));
|
|
463
|
-
onEditorRender();
|
|
464
|
-
onCursor();
|
|
465
|
-
});
|
|
466
|
-
}
|
|
467
|
-
return Reflect.set(target, property, value);
|
|
468
|
-
},
|
|
469
|
-
}) as EditorComponent;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
// ponytail: Pi 0.85 editor layout mapping; unknown editors use visible-line matching.
|
|
473
|
-
function editorImagePaths(editor: EditorComponent, text: string): ImagePathMatch[] {
|
|
474
|
-
const attachments = (editor as EditorComponent & { imageAttachments?: Map<string, string> }).imageAttachments;
|
|
475
|
-
const paths = imagePathsInLine(text);
|
|
476
|
-
for (const match of text.matchAll(/\[img\d+\]/g)) {
|
|
477
|
-
const path = attachments?.get(match[0]);
|
|
478
|
-
if (path) paths.push({ path, start: match.index, end: match.index + match[0].length, startCol: visibleWidth(text.slice(0, match.index)), endCol: visibleWidth(text.slice(0, match.index + match[0].length)) });
|
|
479
|
-
}
|
|
480
|
-
return paths.sort((a, b) => a.start - b.start);
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
function editorPaths(editor: EditorComponent, row: number, width: number, includeWeb = false, compactImages = false) {
|
|
484
|
-
const core = editor as EditorComponent & { lastWidth?: number; scrollOffset?: number; renderedVisibleLineCount?: number; getPaddingX?(): number; buildVisualLineMap?(width: number): Array<{ logicalLine: number; startCol: number; length: number }> };
|
|
485
|
-
if (!core.buildVisualLineMap || !core.lastWidth) return imagePathsInLine(editor.render(width)[row] ?? "");
|
|
486
|
-
if (row < 1 || row > (core.renderedVisibleLineCount ?? 0)) return [];
|
|
487
|
-
const chunk = core.buildVisualLineMap(core.lastWidth)[(core.scrollOffset ?? 0) + row - 1];
|
|
488
|
-
if (!chunk) return [];
|
|
489
|
-
const source = editor.getText().split("\n")[chunk.logicalLine] ?? "";
|
|
490
|
-
const padding = Math.min(core.getPaddingX?.() ?? 0, Math.max(0, Math.floor((width - 1) / 2)));
|
|
491
|
-
return [...editorImagePaths(editor, source), ...(includeWeb ? webPaths(source) : [])].filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
|
|
492
|
-
...match,
|
|
493
|
-
startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start)))
|
|
494
|
-
+ (compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end)) ? 1 : 0),
|
|
495
|
-
endCol: padding + visibleWidth(source.slice(chunk.startCol, Math.min(chunk.startCol + chunk.length, compactImages && /^\[img\d+\]$/.test(source.slice(match.start, match.end))
|
|
496
|
-
? match.start + 1 + visibleWidth(` #${source.slice(match.start + 4, match.end - 1)}`) : match.end))),
|
|
497
|
-
}));
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
function hideImageLabels(line: string, labels: Set<string>, theme: ExtensionContext["ui"]["theme"], original: string): string {
|
|
501
|
-
const markerIndex = original.indexOf(CURSOR_MARKER);
|
|
502
|
-
const cursorCol = markerIndex < 0 ? -1 : visibleWidth(original.slice(0, markerIndex));
|
|
503
|
-
const plain = stripTerminalSequences(line);
|
|
504
|
-
const clean = line.replaceAll(CURSOR_MARKER, "").replaceAll("\x1b[7m", "");
|
|
505
|
-
const reset = "\x1b]8;;\x07\x1b[0m";
|
|
506
|
-
const caret = (cell: string) => reset + CURSOR_MARKER + `\x1b[7m${cell}\x1b[27m`;
|
|
507
|
-
const textSlice = (start: number, length: number) => {
|
|
508
|
-
const part = sliceByColumn(clean, start, length, true);
|
|
509
|
-
if (getOsc8LinkAtColumn(clean, start)) return part;
|
|
510
|
-
return part.replace(/^(?:\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]_][^\x07\x1b]*(?:\x07|\x1b\\))*/,
|
|
511
|
-
leading => leading.replace(/\x1b\]8;[^\x07\x1b]*(?:\x07|\x1b\\)/g, ""));
|
|
512
|
-
};
|
|
513
|
-
const textSpan = (start: number, end: number) => {
|
|
514
|
-
if (cursorCol < start || cursorCol >= end) return textSlice(start, end - start);
|
|
515
|
-
const cell = stripTerminalSequences(sliceByColumn(clean, cursorCol, 1));
|
|
516
|
-
return textSlice(start, cursorCol - start) + caret(cell)
|
|
517
|
-
+ textSlice(cursorCol + visibleWidth(cell), end - cursorCol - visibleWidth(cell));
|
|
518
|
-
};
|
|
519
|
-
const parts: string[] = [];
|
|
520
|
-
let previous = 0;
|
|
521
|
-
for (const match of plain.matchAll(/\[img\d+\]/g)) {
|
|
522
|
-
if (!labels.has(match[0])) continue;
|
|
523
|
-
const start = visibleWidth(plain.slice(0, match.index));
|
|
524
|
-
const end = start + visibleWidth(match[0]);
|
|
525
|
-
const icon = theme.fg("accent", ` #${match[0].slice(4, -1)}`);
|
|
526
|
-
const url = getOsc8LinkAtColumn(line, start);
|
|
527
|
-
const chip = url ? `\x1b]8;;${url}\x07${icon}\x1b]8;;\x07` : icon;
|
|
528
|
-
// [imgN] fits exactly one insertion cell plus the visible chip; no hidden padding.
|
|
529
|
-
// Emit the caret before styling the chip: slicing styled output replays stale ANSI resets.
|
|
530
|
-
parts.push(textSpan(previous, start), reset, cursorCol === start ? caret(" ") : " ", chip);
|
|
531
|
-
previous = end;
|
|
532
|
-
}
|
|
533
|
-
parts.push(textSpan(previous, visibleWidth(plain)), reset);
|
|
534
|
-
return parts.join("");
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, width: number): string[] {
|
|
538
|
-
if (!inputCapabilities().hyperlinks) return lines;
|
|
539
|
-
return lines.map((line, row) => {
|
|
540
|
-
for (const match of editorPaths(editor, row, width, true).reverse()) line = linkRenderedPath(line, match.startCol, match.endCol, /^https?:\/\//i.test(match.path) ? match.path : localPath(match.path, cwd));
|
|
541
|
-
// Isolate editor rows from inherited terminal link/color state.
|
|
542
|
-
const reset = "\x1b]8;;\x07\x1b[0m";
|
|
543
|
-
return reset + line + reset;
|
|
544
|
-
});
|
|
545
|
-
}
|
|
546
33
|
|
|
547
34
|
export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean), previewMode: () => "hover" | "inline" = () => "hover"): InputEnhancementsCleanup {
|
|
548
35
|
const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
|
|
@@ -631,272 +118,3 @@ function createEnhancements(pi: ExtensionAPI): Enhancements {
|
|
|
631
118
|
|
|
632
119
|
return state;
|
|
633
120
|
}
|
|
634
|
-
|
|
635
|
-
async function handleInput(state: Enhancements, event: InputEvent, ctx: ExtensionContext): Promise<InputEventResult | undefined> {
|
|
636
|
-
if (!state.enabled() || event.source !== "interactive" || !event.text.includes("/skill:")) return undefined;
|
|
637
|
-
const skills = readSkillCommands(state.pi);
|
|
638
|
-
const text = await expandSkillTokens(
|
|
639
|
-
event.text,
|
|
640
|
-
skills,
|
|
641
|
-
(path) => readFile(path, "utf8"),
|
|
642
|
-
(skill) => ctx.ui.notify(`无法读取技能文件:${skill.path}`, "warning"),
|
|
643
|
-
);
|
|
644
|
-
return text === undefined ? undefined : { action: "transform", text };
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/** Wrap the current editor factory (or the default editor) so enhancements ride on top of it. */
|
|
648
|
-
function installEditor(ctx: ExtensionContext, state: Enhancements, base?: EditorFactoryFunction): void {
|
|
649
|
-
const create: EditorFactoryFunction = base ?? ((tui, theme, keybindings) => new CustomEditor(tui, theme, keybindings, { embedWorkingStatus: true }));
|
|
650
|
-
const factory: EditorFactoryFunction = (tui, theme, keybindings) => {
|
|
651
|
-
state.tui = tui;
|
|
652
|
-
state.previewTui = tui;
|
|
653
|
-
// ponytail: fullscreen's first input listener consumes mouse events before extension listeners.
|
|
654
|
-
// Observe its entry point until Pi exposes a pre-dispatch mouse subscription.
|
|
655
|
-
state.restoreViewportInput = hookViewportInput(tui, (data) => handleTerminalInput(state, data));
|
|
656
|
-
const inner: CursorEditor = create(tui, theme, keybindings);
|
|
657
|
-
const editor = wrapEditor(inner, state.cwd ?? process.cwd(), () => state.enabled(), () => state.enabled() && state.previewMode() === "inline", state.theme!, state, () => {
|
|
658
|
-
const cursor = inner.getCursor?.();
|
|
659
|
-
const path = cursor ? editorImagePaths(inner, inner.getText().split("\n")[cursor.line] ?? "").find(match => cursor.col >= match.start && cursor.col <= match.end)?.path : undefined;
|
|
660
|
-
if (state.previewMode() === "hover") void requestPreview(state, state.enabled() ? path : undefined);
|
|
661
|
-
}, (target, event) => {
|
|
662
|
-
const match = state.enabled() && event.y >= 1 ? editorPaths(target, event.y, event.width, false, state.previewMode() === "inline").find(path => event.x >= path.startCol && event.x < path.endCol) : undefined;
|
|
663
|
-
const screenStart = match ? event.screenX - event.x + match.startCol : 0;
|
|
664
|
-
const screenEnd = match ? event.screenX - event.x + match.endCol : 0;
|
|
665
|
-
if (match && (match.path !== state.requestedPath || state.previewAnchor?.y !== event.screenY
|
|
666
|
-
|| state.previewAnchor.x < screenStart || state.previewAnchor.x >= screenEnd)) {
|
|
667
|
-
state.previewAnchor = { x: event.screenX, y: event.screenY };
|
|
668
|
-
if (match.path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
|
|
669
|
-
}
|
|
670
|
-
setPointer(state, !!match);
|
|
671
|
-
void requestPreview(state, match?.path);
|
|
672
|
-
}, () => syncInlineImages(state));
|
|
673
|
-
state.editor = editor;
|
|
674
|
-
return editor;
|
|
675
|
-
};
|
|
676
|
-
state.baseFactory = base;
|
|
677
|
-
state.editorFactory = factory;
|
|
678
|
-
ctx.ui.setEditorComponent(factory);
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
function draftImagePaths(editor: EditorComponent): string[] {
|
|
682
|
-
const source = (editor as EditorComponent & { state?: { lines: string[] } }).state?.lines ?? editor.getText().split("\n");
|
|
683
|
-
return source.flatMap(line => editorImagePaths(editor, line).map(match => match.path));
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
function clearInlineGraphics(state: Pick<Enhancements, "inlineGraphics" | "tui">): void {
|
|
687
|
-
for (const graphic of state.inlineGraphics.values()) {
|
|
688
|
-
if (graphic.imageId) state.tui?.terminal.write(deleteKittyImage(graphic.imageId));
|
|
689
|
-
}
|
|
690
|
-
state.inlineGraphics.clear();
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
/** Only the editing draft is shown here; history hover remains the separate mode. */
|
|
694
|
-
function syncInlineImages(state: Enhancements): void {
|
|
695
|
-
const paths = state.editor && state.enabled() && state.previewMode() === "inline"
|
|
696
|
-
? [...new Set(draftImagePaths(state.editor))].slice(0, 15) : [];
|
|
697
|
-
if (!paths.length) clearInlineGraphics(state);
|
|
698
|
-
for (const path of state.inlineImages.keys()) if (!paths.includes(path)) { state.inlineImages.delete(path); clearInlineGraphics(state); }
|
|
699
|
-
for (const path of state.inlinePending.keys()) if (!paths.includes(path)) state.inlinePending.delete(path);
|
|
700
|
-
for (const path of paths) {
|
|
701
|
-
if (state.inlineImages.has(path) || state.inlinePending.has(path)) continue;
|
|
702
|
-
const cwd = state.cwd ?? process.cwd();
|
|
703
|
-
// Cell placement scales the image; keep a bounded copy independent of startup cell metrics.
|
|
704
|
-
const pending = readPreview(path, cwd).catch(() => undefined);
|
|
705
|
-
state.inlinePending.set(path, pending);
|
|
706
|
-
void pending.then(preview => {
|
|
707
|
-
if (state.inlinePending.get(path) !== pending) return;
|
|
708
|
-
state.inlinePending.delete(path);
|
|
709
|
-
if (!state.editor || !state.enabled() || state.previewMode() !== "inline" || !draftImagePaths(state.editor).includes(path)) return;
|
|
710
|
-
state.inlineImages.set(path, preview);
|
|
711
|
-
state.tui?.requestRender();
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
export function inlinePreviewLines(state: Pick<Enhancements, "editor" | "enabled" | "previewMode" | "inlineImages" | "inlinePending" | "inlineGraphics" | "tui">, theme: ExtensionContext["ui"]["theme"], width: number): string[] {
|
|
717
|
-
const paths = state.editor && state.enabled() && state.previewMode() === "inline" && width >= 12 ? draftImagePaths(state.editor) : [];
|
|
718
|
-
if (!paths.length) { clearInlineGraphics(state); return []; }
|
|
719
|
-
const cardWidth = Math.min(14, width);
|
|
720
|
-
// ponytail: cards are capped at one row; beyond viewport width show compact numbered tags, upgrade to a gallery when scrolling is supported.
|
|
721
|
-
const count = Math.max(1, Math.floor((width + 2) / (cardWidth + 2)));
|
|
722
|
-
const protocol = getCapabilities().images;
|
|
723
|
-
const layout = `${cardWidth}:${imageLayoutKey()}`;
|
|
724
|
-
const keys = paths.slice(0, count).map((path, index) => `${index}:${path}`);
|
|
725
|
-
if ([...state.inlineGraphics].some(([key, graphic]) => graphic.layout !== layout || !keys.includes(key))) clearInlineGraphics(state);
|
|
726
|
-
const rows: string[] = [];
|
|
727
|
-
const color = (index: number, text: string) => theme.fg((["warning", "accent", "success", "error"] as const)[index % 4], text);
|
|
728
|
-
{
|
|
729
|
-
const cards = paths.slice(0, count).map((path, index) => {
|
|
730
|
-
const key = `${index}:${path}`;
|
|
731
|
-
const preview = state.inlineImages.get(path);
|
|
732
|
-
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
733
|
-
let graphic = state.inlineGraphics.get(key);
|
|
734
|
-
if (preview?.kind === "image" && dimensions && protocol && !graphic) {
|
|
735
|
-
const cells = getCellDimensions();
|
|
736
|
-
const scale = Math.min((cardWidth - 2) * cells.widthPx / dimensions.widthPx, 4 * cells.heightPx / dimensions.heightPx);
|
|
737
|
-
const columns = Math.min(cardWidth - 2, Math.ceil(dimensions.widthPx * scale / cells.widthPx));
|
|
738
|
-
const rows = Math.min(4, Math.ceil(dimensions.heightPx * scale / cells.heightPx));
|
|
739
|
-
const imageId = protocol === "kitty" ? allocateImageId() : undefined;
|
|
740
|
-
// ponytail: bottom-row placement must not register top-row crop metadata; use Pi's encoder until its layout API supports positioned graphics.
|
|
741
|
-
const rendered = protocol === "kitty"
|
|
742
|
-
? { sequence: encodeKitty(preview.base64, { imageId, columns, rows, moveCursor: false }), imageId, rows, columns }
|
|
743
|
-
: renderImage(preview.base64, dimensions, { maxWidthCells: cardWidth - 2, maxHeightCells: 4, moveCursor: false });
|
|
744
|
-
if (rendered) { graphic = { layout, ...rendered }; state.inlineGraphics.set(key, graphic); }
|
|
745
|
-
}
|
|
746
|
-
const frame = (text: string) => color(index, text);
|
|
747
|
-
const rim = (text: string, top: boolean) => {
|
|
748
|
-
const caption = truncateToWidth(text, cardWidth - 4, "…");
|
|
749
|
-
const fill = cardWidth - 4 - visibleWidth(caption);
|
|
750
|
-
return frame(`${top ? "╭" : "╰"}${"─".repeat(Math.floor(fill / 2))} ${caption} ${"─".repeat(Math.ceil(fill / 2))}${top ? "╮" : "╯"}`);
|
|
751
|
-
};
|
|
752
|
-
const top = rim(` #${index + 1}`, true);
|
|
753
|
-
const size = preview?.kind === "image" ? `${preview.widthPx}x${preview.heightPx}` : state.inlinePending.has(path) ? "加载中" : "无法预览";
|
|
754
|
-
return { graphic, preview, top, size, rim, frame };
|
|
755
|
-
});
|
|
756
|
-
// OMP's 12x4 inner grid; never grow a tall empty box for a wide image.
|
|
757
|
-
const bodyHeight = 4;
|
|
758
|
-
rows.push(cards.map(card => card.top).join(" "));
|
|
759
|
-
for (let row = 0; row < bodyHeight; row++) rows.push(cards.map(card => {
|
|
760
|
-
const content = row === 0 && !card.graphic ? truncateToWidth(card.preview?.kind === "note" ? card.preview.note : card.size === "加载中" ? "加载中" : "无法预览", cardWidth - 4, "…") : "";
|
|
761
|
-
const left = card.graphic ? Math.floor((cardWidth - 2 - card.graphic.columns) / 2) : 0;
|
|
762
|
-
return card.frame("│") + " ".repeat(left) + " ".repeat(cardWidth - 2 - left - visibleWidth(content)) + content + card.frame("│");
|
|
763
|
-
}).join(" "));
|
|
764
|
-
const bottom = cards.map(card => card.rim(card.size, false)).join(" ");
|
|
765
|
-
// Draw the cleared card first, then place images over its interior from the final row.
|
|
766
|
-
const drawings = cards.map((card, index) => {
|
|
767
|
-
if (!card.graphic) return "";
|
|
768
|
-
const topPad = Math.floor((bodyHeight - card.graphic.rows) / 2);
|
|
769
|
-
const leftPad = Math.floor((cardWidth - 2 - card.graphic.columns) / 2);
|
|
770
|
-
const up = bodyHeight - topPad;
|
|
771
|
-
const right = index * (cardWidth + 2) + leftPad + 1;
|
|
772
|
-
return positionedGraphic(card.graphic.sequence, up, right);
|
|
773
|
-
}).join("");
|
|
774
|
-
rows.push(drawings + bottom);
|
|
775
|
-
}
|
|
776
|
-
if (paths.length > count) {
|
|
777
|
-
rows.push("");
|
|
778
|
-
let line = "";
|
|
779
|
-
for (let index = count; index < paths.length; index++) {
|
|
780
|
-
const tag = color(index, ` #${index + 1}`);
|
|
781
|
-
if (visibleWidth(line) + visibleWidth(tag) + 2 > width) { rows.push(line); line = ""; }
|
|
782
|
-
line += (line ? " " : "") + tag;
|
|
783
|
-
}
|
|
784
|
-
if (line) rows.push(line);
|
|
785
|
-
}
|
|
786
|
-
return rows;
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
function setPointer(state: Enhancements, pointer: boolean): void {
|
|
790
|
-
if (state.pointer === pointer) return;
|
|
791
|
-
if (pointer || state.pointer) state.tui?.terminal.write(`\x1b]22;${pointer ? "pointer" : "default"}\x07`);
|
|
792
|
-
state.pointer = pointer;
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
function handleTerminalInput(state: Enhancements, data: string): { consume?: boolean } | undefined {
|
|
796
|
-
if (data === "\x1b[O") { setPointer(state, false); void requestPreview(state, undefined); }
|
|
797
|
-
const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
|
|
798
|
-
if (mouse) {
|
|
799
|
-
const x = Number(mouse[2]) - 1, y = Number(mouse[3]) - 1;
|
|
800
|
-
// ponytail: Pi 0.85 has no public screen hit-test API; inspect its last rendered OSC 8 cells.
|
|
801
|
-
const screen = (state.tui as TUI & { previousScreen?: string[] } | undefined)?.previousScreen;
|
|
802
|
-
const moving = !!(Number(mouse[1]) & 32) && mouse[4] === "M";
|
|
803
|
-
if (!moving) { setPointer(state, false); void requestPreview(state, undefined); return undefined; }
|
|
804
|
-
const cached = state.hoverLink;
|
|
805
|
-
const sameTarget = cached?.row === y && x >= cached.start && x < cached.end;
|
|
806
|
-
const url = state.enabled()
|
|
807
|
-
? sameTarget ? pathToFileURL(cached.path).href : getOsc8LinkAtColumn(screen?.[y] ?? "", x)
|
|
808
|
-
: undefined;
|
|
809
|
-
let path: string | undefined;
|
|
810
|
-
if (url?.startsWith("file:")) {
|
|
811
|
-
try { const file = fileURLToPath(url); if (IMAGE_MIME[extname(file).toLowerCase()]) path = file; } catch { /* Reject malformed or remote file URLs. */ }
|
|
812
|
-
}
|
|
813
|
-
if (path && (path !== state.requestedPath || !sameTarget)) {
|
|
814
|
-
state.previewAnchor = { x, y };
|
|
815
|
-
if (path === state.requestedPath && state.preview.path) { positionPreview(state); state.previewTui?.requestRender(); }
|
|
816
|
-
let start = x, end = x + 1;
|
|
817
|
-
const line = screen?.[y] ?? "";
|
|
818
|
-
while (start > 0 && getOsc8LinkAtColumn(line, start - 1) === url) start--;
|
|
819
|
-
while (end < visibleWidth(line) && getOsc8LinkAtColumn(line, end) === url) end++;
|
|
820
|
-
state.hoverLink = { row: y, start, end, path };
|
|
821
|
-
} else if (!path) state.hoverLink = undefined;
|
|
822
|
-
setPointer(state, !!path);
|
|
823
|
-
void requestPreview(state, path);
|
|
824
|
-
}
|
|
825
|
-
if (!state.preview.path || !matchesKey(data, "escape")) return undefined;
|
|
826
|
-
void requestPreview(state, undefined);
|
|
827
|
-
return { consume: true };
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
async function requestPreview(state: Enhancements, path: string | undefined): Promise<void> {
|
|
831
|
-
if (path && state.enabled() && path === state.requestedPath) return;
|
|
832
|
-
if (!path || !state.enabled()) state.hoverLink = undefined;
|
|
833
|
-
if (!path && !state.requestedPath && !state.preview.path) return;
|
|
834
|
-
state.requestedPath = state.enabled() ? path : undefined;
|
|
835
|
-
const token = ++state.previewToken;
|
|
836
|
-
if (!path || !state.enabled()) {
|
|
837
|
-
setPreview(state, undefined);
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
const cells = getCellDimensions();
|
|
841
|
-
const preview = await readPreview(path, state.cwd ?? process.cwd(), {
|
|
842
|
-
widthPx: Math.max(1, (state.tui?.terminal.columns ?? 80) - 2) * cells.widthPx,
|
|
843
|
-
heightPx: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2) * cells.heightPx,
|
|
844
|
-
});
|
|
845
|
-
if (token !== state.previewToken || !state.enabled()) return;
|
|
846
|
-
setPreview(state, preview);
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
function setPreview(state: Enhancements, preview: Preview | undefined): void {
|
|
850
|
-
// Overlay visibility only erases text; explicitly free the image owned by this preview.
|
|
851
|
-
if (state.preview.graphic?.imageId) state.tui?.terminal.write(deleteKittyImage(state.preview.graphic.imageId));
|
|
852
|
-
state.previewSource = preview;
|
|
853
|
-
state.previewLayout = imageLayoutKey();
|
|
854
|
-
const dimensions = preview?.kind === "image" ? getImageDimensions(preview.base64, preview.mimeType) : undefined;
|
|
855
|
-
const bandWidth = state.previewMode() === "inline" && state.editor && state.theme
|
|
856
|
-
? visibleWidth(inlinePreviewLines(state, state.theme, state.tui?.terminal.columns ?? 80)[0] ?? "") : 0;
|
|
857
|
-
const available = (state.tui?.terminal.columns ?? 80) - (bandWidth ? bandWidth + 4 : 2);
|
|
858
|
-
const graphic = preview?.kind === "image" && dimensions ? renderImage(preview.base64, dimensions, {
|
|
859
|
-
maxWidthCells: Math.max(1, Math.min(Math.floor(dimensions.widthPx / getCellDimensions().widthPx), available)),
|
|
860
|
-
maxHeightCells: Math.max(1, (state.tui?.terminal.rows ?? 24) - 2),
|
|
861
|
-
imageId: allocateImageId(), moveCursor: false,
|
|
862
|
-
}) ?? undefined : undefined;
|
|
863
|
-
state.preview = {
|
|
864
|
-
path: preview?.path, graphic,
|
|
865
|
-
note: preview?.kind === "note" ? preview.note : graphic ? undefined : "终端未能生成图片预览",
|
|
866
|
-
};
|
|
867
|
-
if (state.preview.path && !state.overlayReady) showOverlay(state);
|
|
868
|
-
positionPreview(state);
|
|
869
|
-
state.previewTui?.requestRender();
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
function showOverlay(state: Enhancements): void {
|
|
873
|
-
if (!state.tui || !state.theme) return;
|
|
874
|
-
state.overlayReady = true;
|
|
875
|
-
state.previewOptions = { width: 60, maxHeight: "100%", nonCapturing: true, visible: () => state.enabled() && state.preview.path !== undefined };
|
|
876
|
-
state.previewHandle = state.tui.showOverlay({
|
|
877
|
-
render: width => {
|
|
878
|
-
if (state.previewLayout !== imageLayoutKey()) setPreview(state, state.previewSource);
|
|
879
|
-
return previewLines(state.preview, state.theme!, width);
|
|
880
|
-
},
|
|
881
|
-
invalidate: () => {},
|
|
882
|
-
}, state.previewOptions);
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
function positionPreview(state: Enhancements): void {
|
|
886
|
-
if (!state.previewOptions || !state.tui || !state.theme) return;
|
|
887
|
-
const { rows, columns } = state.tui.terminal;
|
|
888
|
-
const width = Math.max(3, Math.min((state.preview.graphic?.columns ?? 26) + 2, columns || 80));
|
|
889
|
-
const height = Math.min(rows, previewLines(state.preview, state.theme, width).length);
|
|
890
|
-
const { x, y } = state.previewAnchor ?? { x: 0, y: rows - 2 };
|
|
891
|
-
const previewRow = y + 1 + height <= rows ? y + 1 : Math.max(0, y - height);
|
|
892
|
-
// Keep hover previews out of the draft attachment band. If there is no safe
|
|
893
|
-
// vertical gap, move to the side rather than painting over the thumbnail.
|
|
894
|
-
const band = state.previewMode() === "inline" && state.editor && state.theme
|
|
895
|
-
? inlinePreviewLines(state, state.theme, columns).length : 0;
|
|
896
|
-
const overlapsBand = band > 0 && previewRow < y && previewRow + height > y - band - 1;
|
|
897
|
-
const bandWidth = band && state.theme && state.editor ? visibleWidth(inlinePreviewLines(state, state.theme, columns)[0] ?? "") : 0;
|
|
898
|
-
const side = Math.min(columns - width, bandWidth + 2);
|
|
899
|
-
const beside = overlapsBand && side >= bandWidth + 2;
|
|
900
|
-
Object.assign(state.previewOptions, { width, col: beside ? side : Math.max(0, Math.min(x, columns - width)),
|
|
901
|
-
row: beside ? Math.max(0, Math.min(y + 1, rows - height)) : previewRow });
|
|
902
|
-
}
|