proper-base 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import { basename, isAbsolute } from "node:path";
3
+
4
+ import {
5
+ type Component,
6
+ type OverlayHandle,
7
+ type OverlayMargin,
8
+ type OverlayOptions,
9
+ type TUI,
10
+ wrapTextWithAnsi,
11
+ } from "@earendil-works/pi-tui";
12
+
13
+ import { isMounted, rowsBelow } from "./autocomplete-details.ts";
14
+
15
+ const INSTALLED = Symbol.for("pi-proper-base.image-preview");
16
+ const ACTIVE_OVERLAY = Symbol.for("pi-proper-base.image-preview-overlay");
17
+ const CLIPBOARD_IMAGE = /^pi-clipboard-[0-9a-f-]+\.(?:gif|jpe?g|png|webp)$/i;
18
+ const CLIPBOARD_IMAGE_PATH =
19
+ /(?:[A-Za-z]:[\\/]|\/)[^\s]*?pi-clipboard-[0-9a-f-]+\.(?:gif|jpe?g|png|webp)/gi;
20
+
21
+ type PreviewEditor = Component & {
22
+ getText?(): string;
23
+ setText?(text: string): void;
24
+ getCursor?(): { line: number; col: number };
25
+ state?: { lines?: string[]; cursorLine: number; cursorCol: number };
26
+ historyIndex?: number;
27
+ setCursorCol?(column: number): void;
28
+ onChange?: (text: string) => void;
29
+ autocompleteList?: {
30
+ getSelectedItem(): { description?: string } | null;
31
+ };
32
+ };
33
+
34
+ type Preview = {
35
+ marker: string;
36
+ path: string;
37
+ };
38
+
39
+ export type ImagePreviewController = {
40
+ prepare(text: string): string;
41
+ clear(): void;
42
+ dispose(): void;
43
+ };
44
+
45
+ type InstalledEditor = PreviewEditor & {
46
+ [INSTALLED]?: ImagePreviewController;
47
+ };
48
+ type OverlayTui = TUI & { [ACTIVE_OVERLAY]?: OverlayHandle };
49
+
50
+ function singleDeletionIndex(
51
+ before: string,
52
+ after: string,
53
+ ): number | undefined {
54
+ if (before.length !== after.length + 1) return undefined;
55
+ let index = 0;
56
+ while (index < after.length && before[index] === after[index]) index++;
57
+ return before.slice(0, index) + before.slice(index + 1) === after
58
+ ? index
59
+ : undefined;
60
+ }
61
+
62
+ export function installImagePreview(
63
+ editor: Component,
64
+ tui: TUI,
65
+ ): ImagePreviewController | undefined {
66
+ const target = editor as InstalledEditor;
67
+ const existing = target[INSTALLED];
68
+ if (existing) return existing;
69
+ if (!target.getText || !target.setText) return undefined;
70
+
71
+ let counter = 0;
72
+ let changingText = false;
73
+ let previousText = target.getText();
74
+ let activePreviews: Preview[] = [];
75
+ let handler = target.onChange;
76
+ const previews = new Map<string, Preview>();
77
+ const markersByPath = new Map<string, string>();
78
+ const render = target.render;
79
+ const host = tui as OverlayTui;
80
+ const margin: OverlayMargin = { bottom: 0 };
81
+ let overlay: OverlayHandle | undefined;
82
+
83
+ const releaseOverlay = () => {
84
+ const active = overlay;
85
+ if (!active) return;
86
+ active.hide();
87
+ overlay = undefined;
88
+ if (host[ACTIVE_OVERLAY] === active) delete host[ACTIVE_OVERLAY];
89
+ };
90
+ const hasDescription = () =>
91
+ Boolean(target.autocompleteList?.getSelectedItem()?.description);
92
+ const isVisible = () => activePreviews.length > 0 && !hasDescription();
93
+ const scheduleReleaseOverlay = () => {
94
+ const inactive = overlay;
95
+ if (!inactive) return;
96
+ queueMicrotask(() => {
97
+ if (overlay === inactive && (!isVisible() || !isMounted(tui, target))) {
98
+ releaseOverlay();
99
+ }
100
+ });
101
+ };
102
+ const component: Component = {
103
+ render(width: number) {
104
+ return activePreviews.flatMap((preview) =>
105
+ wrapTextWithAnsi(`${preview.marker} ${preview.path}`, width),
106
+ );
107
+ },
108
+ invalidate() {},
109
+ };
110
+ const options: OverlayOptions = {
111
+ anchor: "bottom-left",
112
+ margin,
113
+ nonCapturing: true,
114
+ width: "100%",
115
+ visible: () => {
116
+ const visible = isVisible() && isMounted(tui, target);
117
+ if (!visible) scheduleReleaseOverlay();
118
+ return visible;
119
+ },
120
+ };
121
+ const ensureOverlay = () => {
122
+ const active = host[ACTIVE_OVERLAY];
123
+ if (overlay && active === overlay) return;
124
+ active?.hide();
125
+ overlay = tui.showOverlay(component, options);
126
+ host[ACTIVE_OVERLAY] = overlay;
127
+ };
128
+
129
+ const sync = (text: string) => {
130
+ activePreviews = [...previews.values()].filter((preview) =>
131
+ text.includes(preview.marker),
132
+ );
133
+ if (isVisible() && isMounted(tui, target)) ensureOverlay();
134
+ else releaseOverlay();
135
+ };
136
+
137
+ const cursorOffset = (text: string): number | undefined => {
138
+ const cursor = target.getCursor?.();
139
+ if (!cursor) return undefined;
140
+ const lines = text.split("\n");
141
+ let offset = 0;
142
+ for (let line = 0; line < cursor.line; line++) {
143
+ offset += (lines[line]?.length ?? 0) + 1;
144
+ }
145
+ return offset + cursor.col;
146
+ };
147
+ const restoreCursor = (text: string, offset: number | undefined) => {
148
+ const state = target.state;
149
+ if (offset === undefined || !state) return;
150
+ const before = text.slice(0, Math.max(0, Math.min(offset, text.length)));
151
+ const lines = before.split("\n");
152
+ state.cursorLine = lines.length - 1;
153
+ const column = lines.at(-1)?.length ?? 0;
154
+ if (target.setCursorCol) target.setCursorCol(column);
155
+ else state.cursorCol = column;
156
+ };
157
+ const replaceText = (text: string, offset: number | undefined) => {
158
+ const state = target.state;
159
+ if ((target.historyIndex ?? -1) >= 0 && state?.lines) {
160
+ state.lines = text.split("\n");
161
+ restoreCursor(text, offset);
162
+ previousText = text;
163
+ sync(text);
164
+ handler?.(text);
165
+ return;
166
+ }
167
+ changingText = true;
168
+ try {
169
+ target.setText?.(text);
170
+ } finally {
171
+ changingText = false;
172
+ }
173
+ restoreCursor(text, offset);
174
+ };
175
+ const markerForPath = (path: string): string | undefined => {
176
+ const known = markersByPath.get(path);
177
+ if (known) return known;
178
+ if (!isAbsolute(path) || !CLIPBOARD_IMAGE.test(basename(path))) return;
179
+ try {
180
+ accessSync(path, constants.R_OK);
181
+ } catch {
182
+ return;
183
+ }
184
+ const marker = `[image ${++counter}]`;
185
+ previews.set(marker, { marker, path });
186
+ markersByPath.set(path, marker);
187
+ return marker;
188
+ };
189
+ const ingest = (text: string, cursor: number | undefined) => {
190
+ let mappedCursor = cursor;
191
+ let delta = 0;
192
+ const ingested = text.replace(
193
+ CLIPBOARD_IMAGE_PATH,
194
+ (path, offset: number) => {
195
+ const marker = markerForPath(path);
196
+ if (!marker) return path;
197
+ const end = offset + path.length;
198
+ const difference = marker.length - path.length;
199
+ if (cursor !== undefined) {
200
+ if (cursor >= end) mappedCursor = cursor + delta + difference;
201
+ else if (cursor > offset)
202
+ mappedCursor = offset + delta + marker.length;
203
+ }
204
+ delta += difference;
205
+ return marker;
206
+ },
207
+ );
208
+ return { text: ingested, cursor: mappedCursor };
209
+ };
210
+ const onChange = (text: string) => {
211
+ if (changingText) {
212
+ previousText = text;
213
+ sync(text);
214
+ handler?.(text);
215
+ return;
216
+ }
217
+
218
+ const deletedIndex = singleDeletionIndex(previousText, text);
219
+ if (deletedIndex !== undefined) {
220
+ for (const preview of previews.values()) {
221
+ const markerStart = previousText.indexOf(preview.marker);
222
+ if (
223
+ markerStart < 0 ||
224
+ deletedIndex < markerStart ||
225
+ deletedIndex >= markerStart + preview.marker.length
226
+ ) {
227
+ continue;
228
+ }
229
+ previews.delete(preview.marker);
230
+ markersByPath.delete(preview.path);
231
+ const cleaned =
232
+ text.slice(0, markerStart) +
233
+ text.slice(markerStart + preview.marker.length - 1);
234
+ replaceText(cleaned, markerStart);
235
+ return;
236
+ }
237
+ }
238
+
239
+ const ingested = ingest(text, cursorOffset(text));
240
+ if (ingested.text !== text) {
241
+ replaceText(ingested.text, ingested.cursor);
242
+ return;
243
+ }
244
+ previousText = text;
245
+ sync(text);
246
+ handler?.(text);
247
+ };
248
+
249
+ const controller: ImagePreviewController = {
250
+ prepare(text) {
251
+ let prepared = text;
252
+ for (const preview of previews.values()) {
253
+ prepared = prepared.replaceAll(preview.marker, preview.path);
254
+ }
255
+ activePreviews = [];
256
+ releaseOverlay();
257
+ return prepared;
258
+ },
259
+ clear() {
260
+ previews.clear();
261
+ markersByPath.clear();
262
+ activePreviews = [];
263
+ releaseOverlay();
264
+ },
265
+ dispose() {
266
+ if (target[INSTALLED] !== controller) return;
267
+ controller.clear();
268
+ target.render = render;
269
+ delete target.onChange;
270
+ if (handler) target.onChange = handler;
271
+ delete target[INSTALLED];
272
+ },
273
+ };
274
+
275
+ try {
276
+ Object.defineProperty(target, "onChange", {
277
+ configurable: true,
278
+ enumerable: true,
279
+ get: () => onChange,
280
+ set: (next: ((text: string) => void) | undefined) => {
281
+ handler = next;
282
+ },
283
+ });
284
+ } catch {
285
+ return undefined;
286
+ }
287
+ target.render = (width: number) => {
288
+ const lines = render.call(target, width);
289
+ sync(target.getText?.() ?? "");
290
+ margin.bottom = lines.length + rowsBelow(tui, target, width);
291
+ return lines;
292
+ };
293
+ target[INSTALLED] = controller;
294
+ onChange(target.getText());
295
+ return controller;
296
+ }
@@ -0,0 +1,126 @@
1
+ import type { Component, TUI, TuiInputListener } from "@earendil-works/pi-tui";
2
+ import { visibleWidth } from "@earendil-works/pi-tui";
3
+
4
+ import { rowsBelow } from "./autocomplete-details.ts";
5
+
6
+ const INSTALLED = Symbol.for("pi-proper-base.jump-to-bottom");
7
+ const LABEL = "↓ jump to bottom";
8
+ const COMPACT_LABEL = "↓";
9
+ /** Columns kept clear to the right of the button, matching the footer. */
10
+ const RIGHT_GAP = 1;
11
+ // ESC prefix is matched separately: biome bans control characters in
12
+ // regexes, and string literals carry it fine.
13
+ const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
14
+ const LEFT_BUTTON = "0";
15
+
16
+ /** Alternate-screen renderer surface used for the button. */
17
+ type ScrollableTui = TUI & {
18
+ readonly isFollowingOutput: boolean;
19
+ scrollToBottom(): void;
20
+ };
21
+ type ListenerHost = TUI & { inputListeners?: Set<TuiInputListener> };
22
+ type JumpEditor = Component & { [INSTALLED]?: () => void };
23
+ /** Screen position of the rendered button, in 0-based terminal cells. */
24
+ type Hit = { row: number; start: number; end: number };
25
+
26
+ function scrollableTui(tui: TUI): ScrollableTui | undefined {
27
+ const candidate = tui as Partial<ScrollableTui>;
28
+ return typeof candidate.scrollToBottom === "function" &&
29
+ typeof candidate.isFollowingOutput === "boolean"
30
+ ? (candidate as ScrollableTui)
31
+ : undefined;
32
+ }
33
+
34
+ /**
35
+ * Pi's alternate-screen renderer consumes every mouse event from a listener it
36
+ * registers in its own constructor, so an extension listener never sees a
37
+ * click. Moving ours to the front of the set is the only way the button can
38
+ * respond to the mouse; if that internal field ever changes shape the button
39
+ * keeps rendering and simply stops reacting.
40
+ */
41
+ function prioritize(tui: TUI, listener: TuiInputListener): void {
42
+ const listeners = (tui as ListenerHost).inputListeners;
43
+ if (!listeners?.has(listener)) return;
44
+ const rest = [...listeners].filter((entry) => entry !== listener);
45
+ listeners.clear();
46
+ listeners.add(listener);
47
+ for (const entry of rest) listeners.add(entry);
48
+ }
49
+
50
+ /**
51
+ * Render a clickable jump-to-bottom button above the prompt while the
52
+ * transcript viewport is scrolled up.
53
+ *
54
+ * The row is part of the editor's own render output rather than an overlay:
55
+ * any visible overlay disables Pi's scrollbar dragging, which is exactly the
56
+ * gesture in use while the button is on screen.
57
+ *
58
+ * Regular-mode terminals scroll themselves, so nothing is installed there.
59
+ */
60
+ export function installJumpToBottom(
61
+ editor: Component,
62
+ tui: TUI,
63
+ ): (() => void) | undefined {
64
+ const target = editor as JumpEditor;
65
+ const existing = target[INSTALLED];
66
+ if (existing) return existing;
67
+ const view = scrollableTui(tui);
68
+ if (!view) return undefined;
69
+
70
+ let hit: Hit | undefined;
71
+
72
+ const render = target.render.bind(target);
73
+ target.render = (width: number) => {
74
+ const lines = render(width);
75
+ if (view.isFollowingOutput) {
76
+ hit = undefined;
77
+ return lines;
78
+ }
79
+
80
+ const label =
81
+ width >= visibleWidth(LABEL) + 2 + RIGHT_GAP ? LABEL : COMPACT_LABEL;
82
+ const chipWidth = visibleWidth(label) + 2;
83
+ const start = width - RIGHT_GAP - chipWidth;
84
+ if (start < 0) {
85
+ hit = undefined;
86
+ return lines;
87
+ }
88
+
89
+ hit = {
90
+ row: tui.terminal.rows - lines.length - 1 - rowsBelow(tui, target, width),
91
+ start,
92
+ end: start + chipWidth,
93
+ };
94
+ return [
95
+ `${" ".repeat(start)}\x1b[7m ${label} \x1b[0m${" ".repeat(RIGHT_GAP)}`,
96
+ ...lines,
97
+ ];
98
+ };
99
+
100
+ const listener: TuiInputListener = (data) => {
101
+ const button = hit;
102
+ if (!button) return undefined;
103
+ if (!data.startsWith("\x1b")) return undefined;
104
+ const match = SGR_MOUSE_TAIL.exec(data.slice(1));
105
+ if (!match || match[1] !== LEFT_BUTTON) return undefined;
106
+ const column = Number.parseInt(match[2] ?? "", 10) - 1;
107
+ const row = Number.parseInt(match[3] ?? "", 10) - 1;
108
+ if (row !== button.row || column < button.start || column >= button.end) {
109
+ return undefined;
110
+ }
111
+ // Consume the release too, so the renderer never sees a half press and
112
+ // starts a text selection at the button.
113
+ if (match[4] === "M") view.scrollToBottom();
114
+ return { consume: true };
115
+ };
116
+ const unsubscribe = tui.addInputListener(listener);
117
+ prioritize(tui, listener);
118
+
119
+ const dispose = () => {
120
+ unsubscribe();
121
+ hit = undefined;
122
+ delete target[INSTALLED];
123
+ };
124
+ target[INSTALLED] = dispose;
125
+ return dispose;
126
+ }
@@ -0,0 +1,101 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const PROMPT_DISPLAY_ENTRY = "proper-prompt-display";
4
+
5
+ type Command = { name: string; source: string };
6
+ type Message = { content: string | Array<{ type: string; text?: string }> };
7
+ type Entry = {
8
+ type: string;
9
+ customType?: string;
10
+ data?: unknown;
11
+ };
12
+ export type PromptDisplayRecord = { hash: string; raw: string };
13
+
14
+ export type PromptDisplayController = {
15
+ captureInput(text: string, commands: Command[]): void;
16
+ captureUser(message: Message): void;
17
+ transform(markdown: string): string;
18
+ drain(): PromptDisplayRecord[];
19
+ restore(entries: Entry[]): void;
20
+ clear(): void;
21
+ };
22
+
23
+ export function createPromptDisplay(): PromptDisplayController {
24
+ const display = new Map<string, string>();
25
+ const pending = new Map<string, string>();
26
+ const inputs: Array<string | undefined> = [];
27
+
28
+ return {
29
+ captureInput(text, commands) {
30
+ const name = /^\/([^\s]+)/.exec(text)?.[1];
31
+ const prompt = name
32
+ ? commands.some(
33
+ (command) => command.name === name && command.source === "prompt",
34
+ )
35
+ : false;
36
+ inputs.push(prompt ? text : undefined);
37
+ },
38
+ captureUser(message) {
39
+ const raw = inputs.shift();
40
+ if (!raw) return;
41
+ const expanded = messageText(message);
42
+ if (!expanded) return;
43
+ const key = hash(expanded);
44
+ display.set(key, raw);
45
+ pending.set(key, raw);
46
+ },
47
+ transform(markdown) {
48
+ return display.get(hash(markdown)) ?? markdown;
49
+ },
50
+ drain() {
51
+ const records = [...pending].map(([hash, raw]) => ({ hash, raw }));
52
+ pending.clear();
53
+ return records;
54
+ },
55
+ restore(entries) {
56
+ display.clear();
57
+ pending.clear();
58
+ inputs.length = 0;
59
+ for (const entry of entries) {
60
+ if (
61
+ entry.type !== "custom" ||
62
+ entry.customType !== PROMPT_DISPLAY_ENTRY
63
+ ) {
64
+ continue;
65
+ }
66
+ const records = asRecords(entry.data);
67
+ for (const record of records) display.set(record.hash, record.raw);
68
+ }
69
+ },
70
+ clear() {
71
+ display.clear();
72
+ pending.clear();
73
+ inputs.length = 0;
74
+ },
75
+ };
76
+ }
77
+
78
+ function messageText(message: Message): string {
79
+ if (typeof message.content === "string") return message.content;
80
+ return message.content
81
+ .filter((part) => part.type === "text" && typeof part.text === "string")
82
+ .map((part) => part.text ?? "")
83
+ .join("");
84
+ }
85
+
86
+ function hash(text: string): string {
87
+ return createHash("sha256").update(text.trim()).digest("hex");
88
+ }
89
+
90
+ function asRecords(data: unknown): PromptDisplayRecord[] {
91
+ if (typeof data !== "object" || data === null) return [];
92
+ const prompts = (data as { prompts?: unknown }).prompts;
93
+ if (!Array.isArray(prompts)) return [];
94
+ return prompts.flatMap((record) => {
95
+ if (typeof record !== "object" || record === null) return [];
96
+ const { hash, raw } = record as { hash?: unknown; raw?: unknown };
97
+ return typeof hash === "string" && typeof raw === "string"
98
+ ? [{ hash, raw }]
99
+ : [];
100
+ });
101
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Submit interception for pi's editor.
3
+ *
4
+ * `onSubmit` is the only hook that sees every prompt. pi's `input` event fires
5
+ * after built-in commands return and after extension commands are dispatched,
6
+ * so `/resume` and `/piolium-help` never reach it.
7
+ */
8
+
9
+ /** The part of pi's editor this module touches. */
10
+ export interface SubmittableEditor {
11
+ onSubmit?: (text: string) => void;
12
+ }
13
+
14
+ const INSTALLED = Symbol.for("pi-proper-history.recorder");
15
+
16
+ /**
17
+ * Record every prompt submitted through this editor.
18
+ *
19
+ * pi assigns `onSubmit` as a plain property after construction, and pi-tui
20
+ * declares it as a class field. That field is an own property on every
21
+ * instance, so a prototype accessor on a subclass is shadowed and never runs.
22
+ * Redefining the property on the instance is what makes interception work.
23
+ *
24
+ * Recording happens before the prompt is handed on, so a failure further down
25
+ * pi's submit path cannot cost a history entry. Returns false if the editor
26
+ * already has a recorder, which keeps repeated `session_start` passes from
27
+ * stacking them.
28
+ */
29
+ export function installRecorder(
30
+ editor: SubmittableEditor,
31
+ record: (text: string, sourceText: string) => void,
32
+ prepare: (text: string) => string = (text) => text,
33
+ ): boolean {
34
+ const marked = editor as SubmittableEditor & { [INSTALLED]?: boolean };
35
+ if (marked[INSTALLED]) return false;
36
+
37
+ let handler = editor.onSubmit;
38
+ const wrap =
39
+ (next: ((text: string) => void) | undefined) => (text: string) => {
40
+ const prepared = prepare(text);
41
+ record(prepared, text);
42
+ next?.(prepared);
43
+ };
44
+ handler = handler ? wrap(handler) : undefined;
45
+
46
+ try {
47
+ Object.defineProperty(editor, "onSubmit", {
48
+ configurable: true,
49
+ enumerable: true,
50
+ get: () => handler,
51
+ set: (next: ((text: string) => void) | undefined) => {
52
+ handler = next ? wrap(next) : undefined;
53
+ },
54
+ });
55
+ } catch {
56
+ return false;
57
+ }
58
+
59
+ marked[INSTALLED] = true;
60
+ return true;
61
+ }