proper-base 0.2.7 → 0.3.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,307 @@
1
+ import type { TUI, TuiInputListener } from "@earendil-works/pi-tui";
2
+ import {
3
+ compositeTuiLine,
4
+ sliceByColumn,
5
+ visibleWidth,
6
+ } from "@earendil-works/pi-tui";
7
+
8
+ import { prioritize } from "./jump-to-bottom.ts";
9
+
10
+ const INSTALLED = Symbol.for("pi-proper-base.prompt-jump");
11
+ // Plain arrows rather than arrowheads or chevrons: U+2303/U+2304 and the
12
+ // box-drawing carets are missing from common monospace fonts and render as a
13
+ // blank cell there.
14
+ const UP = " ↑ ";
15
+ const DOWN = " ↓ ";
16
+ /** Columns kept clear to the right of the chips, sparing the scrollbar. */
17
+ const RIGHT_GAP = 1;
18
+ // ESC prefix is matched separately: biome bans control characters in
19
+ // regexes, and string literals carry it fine.
20
+ const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
21
+ const LEFT_BUTTON = "0";
22
+ // The ESC is matched separately for the same reason as the mouse sequence
23
+ // above: biome bans control characters in regexes, whichever escape spells
24
+ // them, while string literals carry them fine.
25
+ const ESC = "\x1b";
26
+ const SGR_TAIL = /^\[[0-9;]*m/;
27
+ // OSC 133 zone markers open both user and assistant transcript blocks. A user
28
+ // block opens with its background-padded box row, an assistant block with an
29
+ // empty spacer row, so trailing content after the markers identifies a prompt.
30
+ const ZONE_START = "\x1b]133;A\x07";
31
+ const ZONE_MARK = "\x1b]133;";
32
+
33
+ /** Alternate-screen renderer surface used for the chips. */
34
+ type Scroller = TUI & {
35
+ readonly viewportTop: number;
36
+ readonly isFollowingOutput: boolean;
37
+ scrollBy(lines: number): void;
38
+ scrollToBottom(): void;
39
+ compositeFlashes(screen: string[], width: number, height: number): string[];
40
+ currentLayout?: LayoutFrame;
41
+ };
42
+ type LayoutBox = {
43
+ scrollView?: unknown;
44
+ scrollContentLines?: readonly string[];
45
+ children?: LayoutBox[];
46
+ };
47
+ type LayoutFrame = { root: LayoutBox; primaryScrollView?: unknown };
48
+ type Installed = Scroller & { [INSTALLED]?: () => void };
49
+ /** Screen columns of the rendered chips, in 0-based terminal cells. */
50
+ type Hit = { start: number; middle: number; end: number };
51
+ export type PromptJumpOptions = {
52
+ color(value: string): string;
53
+ /** Weaker than `color`, so the reading recedes behind the chips. */
54
+ subtle(value: string): string;
55
+ };
56
+
57
+ function scroller(tui: TUI): Scroller | undefined {
58
+ const candidate = tui as Partial<Scroller>;
59
+ return typeof candidate.scrollBy === "function" &&
60
+ typeof candidate.scrollToBottom === "function" &&
61
+ typeof candidate.compositeFlashes === "function" &&
62
+ typeof candidate.isFollowingOutput === "boolean" &&
63
+ typeof candidate.viewportTop === "number"
64
+ ? (candidate as Scroller)
65
+ : undefined;
66
+ }
67
+
68
+ function contentLines(view: Scroller): readonly string[] | undefined {
69
+ const layout = view.currentLayout;
70
+ const scrollView = layout?.primaryScrollView;
71
+ if (!layout || !scrollView) return undefined;
72
+ const visit = (box: LayoutBox): readonly string[] | undefined => {
73
+ if (box.scrollView === scrollView) return box.scrollContentLines;
74
+ for (const child of box.children ?? []) {
75
+ const found = visit(child);
76
+ if (found) return found;
77
+ }
78
+ return undefined;
79
+ };
80
+ return visit(layout.root);
81
+ }
82
+
83
+ /**
84
+ * Leading SGR sequences of a slice, which carry the colors already active at
85
+ * that column. Replaying them under the glyphs keeps the transcript's own
86
+ * background intact, because compositing otherwise resets the covered cells to
87
+ * the terminal default and cuts a hole in the row.
88
+ *
89
+ * Each step consumes a whole matched sequence, so the walk always advances and
90
+ * a truncated escape ends it. That matters because this runs inside the
91
+ * renderer's frame, where a loop that fails to terminate freezes the whole
92
+ * application rather than degrading one row.
93
+ */
94
+ function activeStyle(slice: string): string {
95
+ let index = 0;
96
+ for (;;) {
97
+ if (slice[index] !== ESC) break;
98
+ const tail = SGR_TAIL.exec(slice.slice(index + 1));
99
+ if (!tail) break;
100
+ index += 1 + tail[0].length;
101
+ }
102
+ return slice.slice(0, index);
103
+ }
104
+
105
+ /** Composite content onto one screen row at a column, keeping its colors. */
106
+ function paintRow(
107
+ screen: string[],
108
+ row: number,
109
+ content: string,
110
+ contentWidth: number,
111
+ start: number,
112
+ width: number,
113
+ ): void {
114
+ if (start < 0 || row >= screen.length) return;
115
+ const line = screen[row] ?? "";
116
+ const beneath = activeStyle(sliceByColumn(line, start, contentWidth, true));
117
+ screen[row] = compositeTuiLine(
118
+ line,
119
+ `${beneath}${content}`,
120
+ start,
121
+ contentWidth,
122
+ width,
123
+ );
124
+ }
125
+
126
+ function isPromptRow(line: string): boolean {
127
+ if (!line.startsWith(ZONE_START)) return false;
128
+ let index = 0;
129
+ while (line.startsWith(ZONE_MARK, index)) index += ZONE_START.length;
130
+ return index < line.length;
131
+ }
132
+
133
+ /**
134
+ * Position of the prompt the viewport currently sits in, counted from the top
135
+ * of the transcript, alongside the session's total prompt count. Scrolling
136
+ * above the first prompt reports position zero, so one down click always
137
+ * advances the reading by one.
138
+ */
139
+ function promptCount(
140
+ lines: readonly string[],
141
+ top: number,
142
+ ): string | undefined {
143
+ let current = 0;
144
+ let total = 0;
145
+ for (let row = 0; row < lines.length; row++) {
146
+ if (!isPromptRow(lines[row] ?? "")) continue;
147
+ total += 1;
148
+ if (row <= top) current = total;
149
+ }
150
+ return total > 0 ? `${current}/${total}` : undefined;
151
+ }
152
+
153
+ /**
154
+ * Scroll to the neighbouring user prompt, or to the transcript end when the
155
+ * last prompt is already above the viewport.
156
+ */
157
+ function jump(view: Scroller, direction: 1 | -1): void {
158
+ const lines = contentLines(view) ?? [];
159
+ const from = view.viewportTop;
160
+ for (
161
+ let row = from + direction;
162
+ row >= 0 && row < lines.length;
163
+ row += direction
164
+ ) {
165
+ if (!isPromptRow(lines[row] ?? "")) continue;
166
+ view.scrollBy(row - from);
167
+ return;
168
+ }
169
+ if (direction === 1) view.scrollToBottom();
170
+ }
171
+
172
+ /**
173
+ * Render clickable previous/next prompt chips in the top-right corner of the
174
+ * transcript viewport.
175
+ *
176
+ * The chips composite into the finished screen rather than an overlay: any
177
+ * visible overlay disables Pi's scrollbar hit testing, which is a gesture
178
+ * users reach for in the same scrolled-up state. They carry no background of
179
+ * their own and replay the covered row's colors, so the transcript reads
180
+ * through as two quiet arrows instead of a punched-out block.
181
+ *
182
+ * Regular-mode terminals scroll themselves, so nothing is installed there.
183
+ *
184
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt jump chips]]
185
+ */
186
+ export function installPromptJump(
187
+ tui: TUI,
188
+ options: PromptJumpOptions,
189
+ ): (() => void) | undefined {
190
+ const view = scroller(tui);
191
+ if (!view) return undefined;
192
+ const target = view as Installed;
193
+ // A reload runs the new instance's editor factory before the outgoing
194
+ // instance shuts down, so take over any wrapper it left on the renderer.
195
+ target[INSTALLED]?.();
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;
206
+ const chipWidth = visibleWidth(UP) + visibleWidth(DOWN);
207
+ const hadOwnMethod = Object.hasOwn(view, "compositeFlashes");
208
+ const flashes = view.compositeFlashes;
209
+
210
+ const decorate = (screen: string[], width: number): string[] => {
211
+ const start = width - RIGHT_GAP - chipWidth;
212
+ if (start < 0) {
213
+ hit = undefined;
214
+ return screen;
215
+ }
216
+ hit = { start, middle: start + visibleWidth(UP), end: start + chipWidth };
217
+ const painted = [...screen];
218
+ // Colored per frame rather than once at install, so a theme that rejects
219
+ // the request fails inside the guard instead of out of the editor factory.
220
+ paintRow(
221
+ painted,
222
+ 0,
223
+ options.color(`${UP}${DOWN}`),
224
+ chipWidth,
225
+ start,
226
+ width,
227
+ );
228
+ // The reading only answers "where am I", so it stays out of the way while
229
+ // the viewport is already following the newest output.
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
+ }
247
+ if (count) {
248
+ const countWidth = visibleWidth(count);
249
+ // Centred on the chips rather than the screen edge: the chips carry a
250
+ // padding column each, so sharing the right margin would sit the
251
+ // reading off to one side of the arrows.
252
+ const centred = Math.min(
253
+ start + Math.round((chipWidth - countWidth) / 2),
254
+ width - RIGHT_GAP - countWidth,
255
+ );
256
+ paintRow(painted, 1, options.subtle(count), countWidth, centred, width);
257
+ }
258
+ return painted;
259
+ };
260
+
261
+ const wrapped = (screen: string[], width: number, height: number) => {
262
+ // This runs inside the renderer's own frame, where anything thrown leaves
263
+ // the process with no handler and takes the session down. A decoration is
264
+ // never worth that, so a failure drops the chips for the frame instead.
265
+ let painted = screen;
266
+ try {
267
+ painted = decorate(screen, width);
268
+ } catch {
269
+ hit = undefined;
270
+ }
271
+ // Flashes composite last, so a transient message still wins the row.
272
+ return flashes.call(view, painted, width, height);
273
+ };
274
+ view.compositeFlashes = wrapped;
275
+
276
+ const listener: TuiInputListener = (data) => {
277
+ const button = hit;
278
+ if (!button) return undefined;
279
+ if (!data.startsWith("\x1b")) return undefined;
280
+ const match = SGR_MOUSE_TAIL.exec(data.slice(1));
281
+ if (!match || match[1] !== LEFT_BUTTON) return undefined;
282
+ const column = Number.parseInt(match[2] ?? "", 10) - 1;
283
+ const row = Number.parseInt(match[3] ?? "", 10) - 1;
284
+ if (row !== 0 || column < button.start || column >= button.end) {
285
+ return undefined;
286
+ }
287
+ // Consume the release too, so the renderer never sees a half press and
288
+ // starts a text selection at the chips.
289
+ if (match[4] === "M") jump(view, column < button.middle ? -1 : 1);
290
+ return { consume: true };
291
+ };
292
+ const unsubscribe = tui.addInputListener(listener);
293
+ prioritize(tui, listener);
294
+
295
+ // A disposer left over from a previous extension instance must not unwrap
296
+ // the installation that replaced it.
297
+ const dispose = () => {
298
+ if (view.compositeFlashes !== wrapped) return;
299
+ unsubscribe();
300
+ if (hadOwnMethod) view.compositeFlashes = flashes;
301
+ else delete (view as Partial<Scroller>).compositeFlashes;
302
+ hit = undefined;
303
+ delete target[INSTALLED];
304
+ };
305
+ target[INSTALLED] = dispose;
306
+ return dispose;
307
+ }
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,102 @@
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. It resets
56
+ * the same private fields the renderer's focus-loss branch resets and never
57
+ * consumes the input, so the keystroke still reaches the editor.
58
+ *
59
+ * Renderers without the selection surface, including regular mode, install
60
+ * nothing. The renderer outlives an extension reload, so installation takes
61
+ * over a previous instance's listener and disposal is identity-guarded.
62
+ *
63
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Selection dismissal]]
64
+ */
65
+ export function installSelectionDismiss(tui: TUI): (() => void) | undefined {
66
+ const host = tui as SelectionHost;
67
+ if (
68
+ typeof host.getSelectionBounds !== "function" ||
69
+ typeof host.stopSelectionAutoScroll !== "function"
70
+ ) {
71
+ return undefined;
72
+ }
73
+ // A reload runs the new instance's editor factory before the outgoing
74
+ // instance shuts down, so take over any listener it left on the renderer.
75
+ host[INSTALLED]?.();
76
+
77
+ const listener: TuiInputListener = (data) => {
78
+ // A drag in progress owns the selection it is building.
79
+ if (host.selectionPressActive) return undefined;
80
+ if (host.getSelectionBounds?.() === undefined) return undefined;
81
+ if (!isTypingInput(data)) return undefined;
82
+ host.stopSelectionAutoScroll?.();
83
+ host.selectionAnchor = undefined;
84
+ host.selectionFocus = undefined;
85
+ host.selectionGranularity = "character";
86
+ host.selectionInitialRange = undefined;
87
+ host.selectionDragged = false;
88
+ host.requestRender();
89
+ return undefined;
90
+ };
91
+ const unsubscribe = tui.addInputListener(listener);
92
+
93
+ // A disposer left over from a previous extension instance must not remove
94
+ // the listener that replaced it.
95
+ const dispose = () => {
96
+ if (host[INSTALLED] !== dispose) return;
97
+ unsubscribe();
98
+ delete host[INSTALLED];
99
+ };
100
+ host[INSTALLED] = dispose;
101
+ return dispose;
102
+ }