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,451 @@
1
+ import {
2
+ type Component,
3
+ decodeKittyPrintable,
4
+ matchesKey,
5
+ type TUI,
6
+ truncateToWidth,
7
+ visibleWidth,
8
+ } from "@earendil-works/pi-tui";
9
+
10
+ const INSTALLED = Symbol.for("pi-proper-base.editor-navigation");
11
+ const REVERSE_SEARCH_INSTALLED = Symbol.for(
12
+ "pi-proper-base.reverse-history-search",
13
+ );
14
+ const PROMPT_CLEAR_INSTALLED = Symbol.for("pi-proper-base.prompt-clear");
15
+ const CLEAR_EXIT_WINDOW_MS = 500;
16
+
17
+ type Keybindings = {
18
+ matches(data: string, action: string): boolean;
19
+ };
20
+
21
+ type PromptClearContext = {
22
+ shutdown(): void;
23
+ ui: {
24
+ theme: { fg(color: "warning", text: string): string };
25
+ };
26
+ };
27
+
28
+ type PromptClearController = {
29
+ cleanup(): void;
30
+ update(
31
+ tui: Pick<TUI, "requestRender">,
32
+ keybindings: Keybindings,
33
+ ctx: PromptClearContext,
34
+ ): void;
35
+ };
36
+
37
+ type NavigableEditor = Component & {
38
+ borderColor?(text: string): string;
39
+ handleInput?(data: string): void;
40
+ getCursor?(): { line: number; col: number };
41
+ getLines?(): string[];
42
+ getText?(): string;
43
+ isShowingAutocomplete?(): boolean;
44
+ onChange?(text: string): void;
45
+ setText?(text: string): void;
46
+ state?: {
47
+ lines: string[];
48
+ cursorLine: number;
49
+ cursorCol: number;
50
+ };
51
+ setCursorCol?(column: number): void;
52
+ lastWidth?: number;
53
+ buildVisualLineMap?(width: number): Array<{
54
+ logicalLine: number;
55
+ startCol: number;
56
+ length: number;
57
+ }>;
58
+ findCurrentVisualLine?(
59
+ visualLines: Array<{
60
+ logicalLine: number;
61
+ startCol: number;
62
+ length: number;
63
+ }>,
64
+ ): number;
65
+ [INSTALLED]?: boolean;
66
+ [REVERSE_SEARCH_INSTALLED]?: ReverseHistorySearchController;
67
+ [PROMPT_CLEAR_INSTALLED]?: PromptClearController;
68
+ };
69
+
70
+ export type ReverseHistorySearchController = {
71
+ add(text: string): void;
72
+ reset(prompts: readonly string[]): void;
73
+ };
74
+
75
+ export function installEditorNavigation(
76
+ editor: Component,
77
+ keybindings: Keybindings,
78
+ ): void {
79
+ const target = editor as NavigableEditor;
80
+ if (
81
+ target[INSTALLED] ||
82
+ !target.handleInput ||
83
+ !target.getCursor ||
84
+ !target.getLines
85
+ ) {
86
+ return;
87
+ }
88
+
89
+ const handleInput = target.handleInput.bind(target);
90
+ target.handleInput = (data: string) => {
91
+ const home = keybindings.matches(data, "tui.editor.cursorLineStart");
92
+ const end = keybindings.matches(data, "tui.editor.cursorLineEnd");
93
+ const previous =
94
+ keybindings.matches(data, "tui.editor.cursorUp") ||
95
+ keybindings.matches(data, "tui.editor.historyPrevious");
96
+ if (target.isShowingAutocomplete?.()) {
97
+ handleInput(data);
98
+ return;
99
+ }
100
+ if (previous) {
101
+ const before = target.getLines?.().join("\n");
102
+ handleInput(data);
103
+ const state = target.state;
104
+ if (state && target.getLines?.().join("\n") !== before) {
105
+ state.cursorLine = 0;
106
+ if (target.setCursorCol) target.setCursorCol(0);
107
+ else state.cursorCol = 0;
108
+ }
109
+ return;
110
+ }
111
+ if (!home && !end) {
112
+ handleInput(data);
113
+ return;
114
+ }
115
+
116
+ const lines = target.getLines?.() ?? [];
117
+ const cursor = target.getCursor?.();
118
+ const state = target.state;
119
+ if (home) {
120
+ const visualLines = target.buildVisualLineMap?.(target.lastWidth ?? 80);
121
+ const visualIndex = visualLines
122
+ ? target.findCurrentVisualLine?.(visualLines)
123
+ : undefined;
124
+ const visualLine =
125
+ visualIndex === undefined || visualIndex < 0
126
+ ? undefined
127
+ : visualLines?.[visualIndex];
128
+ if (!cursor || !state || !visualLine) {
129
+ handleInput(data);
130
+ return;
131
+ }
132
+ if (cursor.col > visualLine.startCol) {
133
+ if (target.setCursorCol) target.setCursorCol(visualLine.startCol);
134
+ else state.cursorCol = visualLine.startCol;
135
+ return;
136
+ }
137
+ if (cursor.line > 0 || cursor.col > 0) {
138
+ state.cursorLine = 0;
139
+ if (target.setCursorCol) target.setCursorCol(0);
140
+ else state.cursorCol = 0;
141
+ return;
142
+ }
143
+ handleInput(data);
144
+ return;
145
+ }
146
+
147
+ const currentLine = cursor ? lines[cursor.line] : undefined;
148
+ if (
149
+ !cursor ||
150
+ currentLine === undefined ||
151
+ cursor.col < currentLine.length
152
+ ) {
153
+ handleInput(data);
154
+ return;
155
+ }
156
+
157
+ const lastLine = lines.length - 1;
158
+ if (cursor.line >= lastLine) {
159
+ handleInput(data);
160
+ return;
161
+ }
162
+
163
+ if (state && Array.isArray(state.lines)) {
164
+ state.cursorLine = lastLine;
165
+ const column = lines[lastLine]?.length ?? 0;
166
+ if (target.setCursorCol) target.setCursorCol(column);
167
+ else state.cursorCol = column;
168
+ return;
169
+ }
170
+
171
+ // Compatibility fallback for custom editors that expose cursor reads but
172
+ // not pi-tui's state object.
173
+ for (let attempts = 0; attempts < lines.length * 4; attempts++) {
174
+ const before = target.getCursor?.();
175
+ if (!before || before.line >= lastLine) break;
176
+ handleInput("\x1b[B");
177
+ const after = target.getCursor?.();
178
+ if (!after || (after.line === before.line && after.col === before.col))
179
+ break;
180
+ }
181
+ handleInput(data);
182
+ };
183
+ target[INSTALLED] = true;
184
+ }
185
+
186
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt clearing and exit]]
187
+ export function installPromptClear(
188
+ editor: Component,
189
+ tui: Pick<TUI, "requestRender">,
190
+ keybindings: Keybindings,
191
+ ctx: PromptClearContext,
192
+ ): (() => void) | undefined {
193
+ const target = editor as NavigableEditor;
194
+ const installed = target[PROMPT_CLEAR_INSTALLED];
195
+ if (installed) {
196
+ installed.update(tui, keybindings, ctx);
197
+ return installed.cleanup;
198
+ }
199
+ if (!target.handleInput || !target.getText || !target.setText) return;
200
+
201
+ let active = { tui, keybindings, ctx };
202
+ let lastEmptyClear = 0;
203
+ let warningVisible = false;
204
+ let warningTimer: NodeJS.Timeout | undefined;
205
+ const handleInput = target.handleInput.bind(target);
206
+ const render = target.render.bind(target);
207
+ const clearWarning = (requestRender: boolean) => {
208
+ if (warningTimer) clearTimeout(warningTimer);
209
+ warningTimer = undefined;
210
+ if (!warningVisible) return;
211
+ warningVisible = false;
212
+ if (requestRender) active.tui.requestRender();
213
+ };
214
+ const showWarning = () => {
215
+ clearWarning(false);
216
+ warningVisible = true;
217
+ warningTimer = setTimeout(() => {
218
+ warningTimer = undefined;
219
+ warningVisible = false;
220
+ active.tui.requestRender();
221
+ }, CLEAR_EXIT_WINDOW_MS);
222
+ warningTimer.unref?.();
223
+ active.tui.requestRender();
224
+ };
225
+ const controller: PromptClearController = {
226
+ cleanup() {
227
+ lastEmptyClear = 0;
228
+ clearWarning(false);
229
+ },
230
+ update(nextTui, nextKeybindings, nextCtx) {
231
+ controller.cleanup();
232
+ active = {
233
+ tui: nextTui,
234
+ keybindings: nextKeybindings,
235
+ ctx: nextCtx,
236
+ };
237
+ },
238
+ };
239
+
240
+ target.handleInput = (data: string) => {
241
+ if (!active.keybindings.matches(data, "app.clear")) {
242
+ if (warningVisible) {
243
+ lastEmptyClear = 0;
244
+ clearWarning(true);
245
+ }
246
+ handleInput(data);
247
+ return;
248
+ }
249
+ if (target.getText?.()) {
250
+ lastEmptyClear = 0;
251
+ clearWarning(false);
252
+ target.setText?.("");
253
+ active.tui.requestRender();
254
+ return;
255
+ }
256
+
257
+ const now = Date.now();
258
+ if (now - lastEmptyClear < CLEAR_EXIT_WINDOW_MS) {
259
+ lastEmptyClear = 0;
260
+ clearWarning(true);
261
+ active.ctx.shutdown();
262
+ return;
263
+ }
264
+ lastEmptyClear = now;
265
+ showWarning();
266
+ };
267
+ target.render = (width: number) => {
268
+ const lines = render(width);
269
+ if (!warningVisible) return lines;
270
+ const warning = truncateToWidth(" Press Ctrl+C again to exit", width, "");
271
+ return [active.ctx.ui.theme.fg("warning", warning), ...lines];
272
+ };
273
+ target[PROMPT_CLEAR_INSTALLED] = controller;
274
+ return controller.cleanup;
275
+ }
276
+
277
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Reverse history search]]
278
+ export function installReverseHistorySearch(
279
+ editor: Component,
280
+ tui: Pick<TUI, "requestRender">,
281
+ keybindings: Keybindings,
282
+ prompts: readonly string[],
283
+ limit: number,
284
+ ): ReverseHistorySearchController | undefined {
285
+ const target = editor as NavigableEditor;
286
+ const installed = target[REVERSE_SEARCH_INSTALLED];
287
+ if (installed) {
288
+ installed.reset(prompts);
289
+ return installed;
290
+ }
291
+ if (
292
+ !target.handleInput ||
293
+ !target.getText ||
294
+ (!target.state && !target.setText)
295
+ )
296
+ return undefined;
297
+
298
+ let entries: string[] = [];
299
+ let search:
300
+ | {
301
+ draft: string;
302
+ cursor: { line: number; col: number } | undefined;
303
+ query: string;
304
+ index: number;
305
+ failed: boolean;
306
+ }
307
+ | undefined;
308
+ const handleInput = target.handleInput.bind(target);
309
+ const render = target.render.bind(target);
310
+
311
+ const replaceText = (
312
+ text: string,
313
+ cursor?: { line: number; col: number },
314
+ ) => {
315
+ const state = target.state;
316
+ if (!state) {
317
+ target.setText?.(text);
318
+ return;
319
+ }
320
+ state.lines = text.split("\n");
321
+ state.cursorLine = Math.max(
322
+ 0,
323
+ Math.min(cursor?.line ?? state.lines.length - 1, state.lines.length - 1),
324
+ );
325
+ const line = state.lines[state.cursorLine] ?? "";
326
+ state.cursorCol = Math.max(
327
+ 0,
328
+ Math.min(cursor?.col ?? line.length, line.length),
329
+ );
330
+ target.onChange?.(text);
331
+ };
332
+ const findMatch = (startExclusive: number) => {
333
+ if (!search) return;
334
+ for (
335
+ let index = Math.min(startExclusive, entries.length) - 1;
336
+ index >= 0;
337
+ index--
338
+ ) {
339
+ const entry = entries[index];
340
+ if (entry?.includes(search.query)) {
341
+ search.index = index;
342
+ search.failed = false;
343
+ replaceText(entry);
344
+ tui.requestRender();
345
+ return;
346
+ }
347
+ }
348
+ search.failed = true;
349
+ tui.requestRender();
350
+ };
351
+ const finish = (restoreDraft: boolean) => {
352
+ const active = search;
353
+ search = undefined;
354
+ if (restoreDraft && active) replaceText(active.draft, active.cursor);
355
+ tui.requestRender();
356
+ };
357
+ const start = () => {
358
+ const draft = target.getText?.();
359
+ if (draft === undefined) return;
360
+ if (target.isShowingAutocomplete?.()) handleInput("\x1b");
361
+ const cursor = target.getCursor?.();
362
+ // Exit Pi's native Up/Down history mode without adding an undo entry.
363
+ target.setText?.(draft);
364
+ search = {
365
+ draft,
366
+ cursor,
367
+ query: "",
368
+ index: -1,
369
+ failed: false,
370
+ };
371
+ findMatch(entries.length);
372
+ };
373
+ const normalize = (values: readonly string[]) => {
374
+ const next: string[] = [];
375
+ for (const value of values) {
376
+ const prompt = value.trim();
377
+ if (prompt && next.at(-1) !== prompt) next.push(prompt);
378
+ }
379
+ return next.slice(-limit);
380
+ };
381
+
382
+ const controller: ReverseHistorySearchController = {
383
+ add(text) {
384
+ const prompt = text.trim();
385
+ if (!prompt || entries.at(-1) === prompt) return;
386
+ entries.push(prompt);
387
+ if (entries.length > limit) entries.shift();
388
+ },
389
+ reset(next) {
390
+ finish(true);
391
+ entries = normalize(next);
392
+ },
393
+ };
394
+
395
+ target.handleInput = (data: string) => {
396
+ if (matchesKey(data, "ctrl+r")) {
397
+ if (!search) start();
398
+ else findMatch(search.index < 0 ? entries.length : search.index);
399
+ return;
400
+ }
401
+ if (!search) {
402
+ handleInput(data);
403
+ return;
404
+ }
405
+ if (matchesKey(data, "ctrl+g")) {
406
+ finish(true);
407
+ return;
408
+ }
409
+ if (
410
+ keybindings.matches(data, "tui.editor.deleteCharBackward") ||
411
+ matchesKey(data, "shift+backspace")
412
+ ) {
413
+ search.query = [...search.query].slice(0, -1).join("");
414
+ findMatch(search.index < 0 ? entries.length : search.index + 1);
415
+ return;
416
+ }
417
+ if (keybindings.matches(data, "tui.input.submit")) {
418
+ finish(false);
419
+ handleInput(data);
420
+ return;
421
+ }
422
+ if (matchesKey(data, "escape")) {
423
+ finish(false);
424
+ return;
425
+ }
426
+
427
+ const printable =
428
+ decodeKittyPrintable(data) ??
429
+ (/^[^\p{Cc}]+$/u.test(data) ? data : undefined);
430
+ if (printable !== undefined) {
431
+ search.query += printable;
432
+ findMatch(search.index < 0 ? entries.length : search.index + 1);
433
+ return;
434
+ }
435
+
436
+ finish(false);
437
+ handleInput(data);
438
+ };
439
+ target.render = (width: number) => {
440
+ const lines = [...render(width)];
441
+ if (!search || lines.length === 0) return lines;
442
+ const label = `(${search.failed ? "failing " : ""}reverse-i-search)\`${search.query}':`;
443
+ const clipped = truncateToWidth(label, width, "");
444
+ const border = `${clipped}${"─".repeat(Math.max(0, width - visibleWidth(clipped)))}`;
445
+ lines[lines.length - 1] = target.borderColor?.(border) ?? border;
446
+ return lines;
447
+ };
448
+ target[REVERSE_SEARCH_INSTALLED] = controller;
449
+ controller.reset(prompts);
450
+ return controller;
451
+ }