@narumitw/pi-notes 0.0.0 → 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.
- package/README.md +32 -15
- package/package.json +1 -1
- package/src/child-session.ts +54 -15
- package/src/constants.ts +8 -3
- package/src/fullscreen.ts +253 -0
- package/src/menu.ts +212 -53
- package/src/note-picker.ts +735 -0
- package/src/notes-extension.ts +92 -16
- package/src/storage.ts +178 -26
- package/src/template-editor.ts +664 -0
- package/src/workspace.ts +179 -23
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import {
|
|
3
|
+
type Component,
|
|
4
|
+
decodeKittyPrintable,
|
|
5
|
+
type Focusable,
|
|
6
|
+
fuzzyFilter,
|
|
7
|
+
Input,
|
|
8
|
+
isKittyProtocolActive,
|
|
9
|
+
Key,
|
|
10
|
+
type KeyId,
|
|
11
|
+
matchesKey,
|
|
12
|
+
type TUI,
|
|
13
|
+
type TuiMouseEvent,
|
|
14
|
+
type TuiMouseEventResult,
|
|
15
|
+
truncateToWidth,
|
|
16
|
+
visibleWidth,
|
|
17
|
+
wrapTextWithAnsi,
|
|
18
|
+
} from "@earendil-works/pi-tui";
|
|
19
|
+
import { formatInteractionHints, HorizontalRule, renderBoundedFrame, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
20
|
+
import type { MarkdownEntry } from "./storage.js";
|
|
21
|
+
|
|
22
|
+
const BRACKETED_PASTE_START = "\u001b[200~";
|
|
23
|
+
const BRACKETED_PASTE_END = "\u001b[201~";
|
|
24
|
+
const INPUT_PREFIX_TIMEOUT_MS = 10;
|
|
25
|
+
const MAX_SEARCH_QUERY_LENGTH = 256;
|
|
26
|
+
const MAX_VISIBLE_NOTES = 12;
|
|
27
|
+
|
|
28
|
+
type KeyboardProtocolTerminal = TUI["terminal"] & {
|
|
29
|
+
readonly modifyOtherKeysActive?: boolean;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
interface NotePickerHintKeys {
|
|
33
|
+
navigation: readonly KeyId[];
|
|
34
|
+
confirm: readonly KeyId[];
|
|
35
|
+
back: readonly KeyId[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const PICKER_BINDINGS = [
|
|
39
|
+
"tui.select.up",
|
|
40
|
+
"tui.select.down",
|
|
41
|
+
"tui.select.pageUp",
|
|
42
|
+
"tui.select.pageDown",
|
|
43
|
+
"tui.select.confirm",
|
|
44
|
+
"tui.select.cancel",
|
|
45
|
+
] as const;
|
|
46
|
+
// These are the configurable actions Pi Input consumes before printable insertion.
|
|
47
|
+
const SEARCH_INPUT_BINDINGS = [
|
|
48
|
+
"tui.editor.undo",
|
|
49
|
+
"tui.input.submit",
|
|
50
|
+
"tui.editor.deleteCharBackward",
|
|
51
|
+
"tui.editor.deleteCharForward",
|
|
52
|
+
"tui.editor.deleteWordBackward",
|
|
53
|
+
"tui.editor.deleteWordForward",
|
|
54
|
+
"tui.editor.deleteToLineStart",
|
|
55
|
+
"tui.editor.deleteToLineEnd",
|
|
56
|
+
"tui.editor.yank",
|
|
57
|
+
"tui.editor.yankPop",
|
|
58
|
+
"tui.editor.cursorLeft",
|
|
59
|
+
"tui.editor.cursorRight",
|
|
60
|
+
"tui.editor.cursorLineStart",
|
|
61
|
+
"tui.editor.cursorLineEnd",
|
|
62
|
+
"tui.editor.cursorWordLeft",
|
|
63
|
+
"tui.editor.cursorWordRight",
|
|
64
|
+
] as const;
|
|
65
|
+
|
|
66
|
+
const MODIFIERS = ["shift", "alt", "ctrl", "super"] as const;
|
|
67
|
+
const SYMBOLS = "`-=[]\\;',./!@#$%^&*()_|~{}:<>?";
|
|
68
|
+
const SPECIAL_KEYS = new Set([
|
|
69
|
+
"escape",
|
|
70
|
+
"enter",
|
|
71
|
+
"tab",
|
|
72
|
+
"space",
|
|
73
|
+
"backspace",
|
|
74
|
+
"insert",
|
|
75
|
+
"delete",
|
|
76
|
+
"clear",
|
|
77
|
+
"home",
|
|
78
|
+
"end",
|
|
79
|
+
"pageup",
|
|
80
|
+
"pagedown",
|
|
81
|
+
"left",
|
|
82
|
+
"right",
|
|
83
|
+
"up",
|
|
84
|
+
"down",
|
|
85
|
+
]);
|
|
86
|
+
const FUNCTION_INPUTS = ["OP", "OQ", "OR", "OS", "[15~", "[17~", "[18~", "[19~", "[20~", "[21~", "[23~", "[24~"];
|
|
87
|
+
const LEGACY_INPUTS = [
|
|
88
|
+
...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),
|
|
89
|
+
...Array.from({ length: 128 }, (_, code) => `\u001b${String.fromCharCode(code)}`),
|
|
90
|
+
"\u001b[Z",
|
|
91
|
+
"\u001bOM",
|
|
92
|
+
"\u001b[E",
|
|
93
|
+
"\u001b[e",
|
|
94
|
+
"\u001bOe",
|
|
95
|
+
...FUNCTION_INPUTS.map((suffix) => `\u001b${suffix}`),
|
|
96
|
+
];
|
|
97
|
+
const SPECIAL_CODEPOINTS: Record<string, number> = {
|
|
98
|
+
escape: 27,
|
|
99
|
+
tab: 9,
|
|
100
|
+
enter: 13,
|
|
101
|
+
space: 32,
|
|
102
|
+
backspace: 127,
|
|
103
|
+
insert: 57425,
|
|
104
|
+
delete: 57426,
|
|
105
|
+
home: 57423,
|
|
106
|
+
end: 57424,
|
|
107
|
+
pageup: 57421,
|
|
108
|
+
pagedown: 57422,
|
|
109
|
+
left: 57417,
|
|
110
|
+
right: 57418,
|
|
111
|
+
up: 57419,
|
|
112
|
+
down: 57420,
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type NotePickerResult =
|
|
116
|
+
| { kind: "open"; notePath: string; query?: string }
|
|
117
|
+
| { kind: "delete"; notePath: string; nextSelectedPath?: string; query?: string }
|
|
118
|
+
| { kind: "back"; selectedPath?: string; query?: string }
|
|
119
|
+
| { kind: "close"; selectedPath?: string; query?: string };
|
|
120
|
+
|
|
121
|
+
interface NotePickerOptions {
|
|
122
|
+
tui: TUI;
|
|
123
|
+
theme: Theme;
|
|
124
|
+
keybindings: KeybindingsManager;
|
|
125
|
+
notes: readonly MarkdownEntry[];
|
|
126
|
+
lines?: readonly string[];
|
|
127
|
+
initialSelectedPath?: string;
|
|
128
|
+
initialQuery?: string;
|
|
129
|
+
complete(result: NotePickerResult): void;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
interface MouseLayout {
|
|
133
|
+
width: number;
|
|
134
|
+
inputFrameRow?: number;
|
|
135
|
+
noteByFrameRow: ReadonlyMap<number, number>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export class NotePicker implements Component, Focusable {
|
|
139
|
+
private readonly searchInput = new Input();
|
|
140
|
+
private readonly searchEnabled: boolean;
|
|
141
|
+
private filteredNotes: MarkdownEntry[];
|
|
142
|
+
private selectedPath: string | undefined;
|
|
143
|
+
private restoreSelectedPath: string | undefined;
|
|
144
|
+
private scrollOffset = 0;
|
|
145
|
+
private pasteStartBuffer = "";
|
|
146
|
+
private pasteBuffer: string | undefined;
|
|
147
|
+
private pasteStartTimer: ReturnType<typeof setTimeout> | undefined;
|
|
148
|
+
private mousePressedIndex: number | undefined;
|
|
149
|
+
private mouseLayout: MouseLayout | undefined;
|
|
150
|
+
private disposed = false;
|
|
151
|
+
private completed = false;
|
|
152
|
+
private isFocused = false;
|
|
153
|
+
|
|
154
|
+
constructor(private readonly options: NotePickerOptions) {
|
|
155
|
+
this.searchEnabled = options.notes.length > 8;
|
|
156
|
+
initializeSearchInput(this.searchInput, sanitizeTerminalText(options.initialQuery ?? ""));
|
|
157
|
+
this.searchInput.focused = false;
|
|
158
|
+
this.filteredNotes = this.filterNotes();
|
|
159
|
+
this.selectedPath = this.filteredNotes.some(({ relativePath }) => relativePath === options.initialSelectedPath)
|
|
160
|
+
? options.initialSelectedPath
|
|
161
|
+
: this.filteredNotes[0]?.relativePath;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
get focused(): boolean {
|
|
165
|
+
return this.isFocused;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
set focused(value: boolean) {
|
|
169
|
+
this.isFocused = value;
|
|
170
|
+
this.searchInput.focused = value && this.searchEnabled && !this.disposed;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
render(width: number): string[] {
|
|
174
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
175
|
+
const viewportSize = this.viewportSize();
|
|
176
|
+
this.keepSelectionVisible(viewportSize);
|
|
177
|
+
const visible = this.filteredNotes.slice(this.scrollOffset, this.scrollOffset + viewportSize);
|
|
178
|
+
const rows = visible.map((note) => this.renderNote(note, note.relativePath === this.selectedPath, safeWidth));
|
|
179
|
+
const content: string[] = [];
|
|
180
|
+
let selectedContentIndex: number | undefined;
|
|
181
|
+
|
|
182
|
+
if (this.searchEnabled) {
|
|
183
|
+
content.push(this.renderSearch(safeWidth), "");
|
|
184
|
+
}
|
|
185
|
+
const listStart = content.length;
|
|
186
|
+
if (rows.length > 0) {
|
|
187
|
+
content.push(...rows);
|
|
188
|
+
const selectedVisibleIndex = visible.findIndex(({ relativePath }) => relativePath === this.selectedPath);
|
|
189
|
+
if (selectedVisibleIndex >= 0) selectedContentIndex = listStart + selectedVisibleIndex;
|
|
190
|
+
} else {
|
|
191
|
+
content.push(
|
|
192
|
+
this.options.theme.fg(
|
|
193
|
+
this.queryTooLong() ? "error" : "dim",
|
|
194
|
+
this.queryTooLong()
|
|
195
|
+
? ` Search query is too long (maximum ${MAX_SEARCH_QUERY_LENGTH} characters)`
|
|
196
|
+
: this.options.notes.length === 0
|
|
197
|
+
? " No notes found."
|
|
198
|
+
: " No matching notes.",
|
|
199
|
+
),
|
|
200
|
+
);
|
|
201
|
+
selectedContentIndex = content.length - 1;
|
|
202
|
+
}
|
|
203
|
+
if (this.filteredNotes.length > viewportSize) {
|
|
204
|
+
const selectedIndex = this.selectedIndex();
|
|
205
|
+
content.push(this.options.theme.fg("dim", ` (${selectedIndex + 1}/${this.filteredNotes.length})`));
|
|
206
|
+
}
|
|
207
|
+
if (this.searchEnabled) content.push(this.options.theme.fg("dim", "Type to search"));
|
|
208
|
+
|
|
209
|
+
const hint = this.interactionHint();
|
|
210
|
+
const hintRows = wrapTextWithAnsi(this.options.theme.fg("dim", hint), safeWidth);
|
|
211
|
+
const title = this.options.theme.fg("accent", this.options.theme.bold("Open a note"));
|
|
212
|
+
const context = (this.options.lines ?? []).map((line) =>
|
|
213
|
+
this.options.theme.fg("muted", sanitizeTerminalText(line)),
|
|
214
|
+
);
|
|
215
|
+
const rule =
|
|
216
|
+
new HorizontalRule({ ruleStyle: (text) => this.options.theme.fg("border", text) }).render(safeWidth)[0] ?? "";
|
|
217
|
+
const priorities = [
|
|
218
|
+
...(this.searchEnabled ? [0] : []),
|
|
219
|
+
...(selectedContentIndex === undefined ? [] : [selectedContentIndex]),
|
|
220
|
+
];
|
|
221
|
+
const maxRows = Math.max(1, Math.floor(this.options.tui.terminal.rows) - 3);
|
|
222
|
+
const frame = renderBoundedFrame({
|
|
223
|
+
width: safeWidth,
|
|
224
|
+
maxRows,
|
|
225
|
+
rule,
|
|
226
|
+
title: [title],
|
|
227
|
+
context,
|
|
228
|
+
content,
|
|
229
|
+
hints: hintRows,
|
|
230
|
+
compactHint: truncateToWidth(this.options.theme.fg("dim", hint), safeWidth, ""),
|
|
231
|
+
priorityRows: priorities,
|
|
232
|
+
focusedRow: selectedContentIndex,
|
|
233
|
+
});
|
|
234
|
+
const fullFrameRows = context.length + content.length + hintRows.length + 4;
|
|
235
|
+
// Kit's compact frame does not expose public pointer-row metadata. Disable pointer routing there rather than
|
|
236
|
+
// risk opening a different raw note identity; keyboard navigation remains available at every height.
|
|
237
|
+
if (fullFrameRows <= maxRows) {
|
|
238
|
+
const contentFrameStart = context.length + 3;
|
|
239
|
+
this.mouseLayout = {
|
|
240
|
+
width: safeWidth,
|
|
241
|
+
...(this.searchEnabled ? { inputFrameRow: contentFrameStart } : {}),
|
|
242
|
+
noteByFrameRow: new Map(
|
|
243
|
+
visible.map((_, index) => [contentFrameStart + listStart + index, this.scrollOffset + index]),
|
|
244
|
+
),
|
|
245
|
+
};
|
|
246
|
+
} else this.mouseLayout = undefined;
|
|
247
|
+
return frame;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
handleInput(data: string): void {
|
|
251
|
+
if (this.disposed || this.completed) return;
|
|
252
|
+
this.routeInput(data);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
256
|
+
if (this.disposed || this.completed || !this.mouseLayout || event.width !== this.mouseLayout.width) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
if (event.y === this.mouseLayout.inputFrameRow) {
|
|
260
|
+
const labelWidth = visibleWidth("Search: ");
|
|
261
|
+
const inputWidth = Math.max(1, event.width - labelWidth);
|
|
262
|
+
if (event.x < labelWidth || event.x >= labelWidth + inputWidth) return undefined;
|
|
263
|
+
return this.searchInput.handleMouse({
|
|
264
|
+
...event,
|
|
265
|
+
x: event.x - labelWidth,
|
|
266
|
+
y: 0,
|
|
267
|
+
width: inputWidth,
|
|
268
|
+
height: 1,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
const mappedIndex = this.mouseLayout.noteByFrameRow.get(event.y);
|
|
272
|
+
if (mappedIndex === undefined) return undefined;
|
|
273
|
+
const noteIndex = event.type === "click" ? (this.mousePressedIndex ?? mappedIndex) : mappedIndex;
|
|
274
|
+
if (noteIndex < 0 || noteIndex >= this.filteredNotes.length) return undefined;
|
|
275
|
+
if (event.type === "wheel" && event.wheelDelta) {
|
|
276
|
+
const next = Math.max(
|
|
277
|
+
0,
|
|
278
|
+
Math.min(this.filteredNotes.length - 1, this.selectedIndex() + (event.wheelDelta < 0 ? -1 : 1)),
|
|
279
|
+
);
|
|
280
|
+
const changed = next !== this.selectedIndex();
|
|
281
|
+
if (changed) this.selectAt(next);
|
|
282
|
+
return { handled: true, render: changed };
|
|
283
|
+
}
|
|
284
|
+
if (event.type === "move") return { handled: true };
|
|
285
|
+
if (event.button !== "left") return undefined;
|
|
286
|
+
if (event.type === "press") {
|
|
287
|
+
this.mousePressedIndex = noteIndex;
|
|
288
|
+
const changed = this.selectedIndex() !== noteIndex;
|
|
289
|
+
if (changed) this.selectAt(noteIndex);
|
|
290
|
+
return { handled: true, focus: true, render: changed };
|
|
291
|
+
}
|
|
292
|
+
if (event.type === "click") {
|
|
293
|
+
this.mousePressedIndex = undefined;
|
|
294
|
+
if (this.selectedIndex() !== noteIndex) this.selectAt(noteIndex);
|
|
295
|
+
this.openSelected();
|
|
296
|
+
return { handled: true };
|
|
297
|
+
}
|
|
298
|
+
return undefined;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
invalidate(): void {
|
|
302
|
+
this.mouseLayout = undefined;
|
|
303
|
+
this.searchInput.invalidate();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
dispose(): void {
|
|
307
|
+
this.disposed = true;
|
|
308
|
+
this.clearPasteStartTimer();
|
|
309
|
+
this.pasteStartBuffer = "";
|
|
310
|
+
this.pasteBuffer = undefined;
|
|
311
|
+
this.mousePressedIndex = undefined;
|
|
312
|
+
this.mouseLayout = undefined;
|
|
313
|
+
this.isFocused = false;
|
|
314
|
+
this.searchInput.focused = false;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private renderSearch(width: number): string {
|
|
318
|
+
const label = this.options.theme.fg("muted", "Search: ");
|
|
319
|
+
const inputWidth = Math.max(1, width - visibleWidth(label));
|
|
320
|
+
return truncateToWidth(`${label}${this.searchInput.render(inputWidth)[0] ?? ""}`, width, "");
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
private renderNote(note: MarkdownEntry, selected: boolean, width: number): string {
|
|
324
|
+
const prefix = selected ? this.options.theme.fg("accent", "→ ") : " ";
|
|
325
|
+
const description = `${note.size} bytes`;
|
|
326
|
+
const availableLabelWidth = Math.max(1, width - visibleWidth(prefix) - visibleWidth(description) - 2);
|
|
327
|
+
const label = truncateToWidth(sanitizeTerminalText(note.displayPath), availableLabelWidth, "…");
|
|
328
|
+
const spacing = " ".repeat(
|
|
329
|
+
Math.max(1, width - visibleWidth(prefix) - visibleWidth(label) - visibleWidth(description)),
|
|
330
|
+
);
|
|
331
|
+
const line = truncateToWidth(
|
|
332
|
+
`${prefix}${label}${this.options.theme.fg("muted", `${spacing}${description}`)}`,
|
|
333
|
+
width,
|
|
334
|
+
"",
|
|
335
|
+
);
|
|
336
|
+
return selected ? this.options.theme.bold(line) : line;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private interactionHint(): string {
|
|
340
|
+
const hintKeys = resolveNotePickerHintKeys(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
341
|
+
const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
342
|
+
return formatInteractionHints(this.options.keybindings, [
|
|
343
|
+
{ keys: hintKeys.navigation, label: "navigate" },
|
|
344
|
+
{ keys: hintKeys.confirm, label: "open" },
|
|
345
|
+
...(deleteKey ? [{ keys: [deleteKey], label: "delete" }] : []),
|
|
346
|
+
{ keys: hintKeys.back, label: "back" },
|
|
347
|
+
{ keys: ["ctrl+c"], label: "close" },
|
|
348
|
+
]);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private viewportSize(): number {
|
|
352
|
+
const fixedRows = this.searchEnabled ? 9 : 6;
|
|
353
|
+
return Math.max(1, Math.min(MAX_VISIBLE_NOTES, Math.floor(this.options.tui.terminal.rows) - fixedRows));
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private query(): string {
|
|
357
|
+
return this.searchEnabled ? this.searchInput.getValue() : "";
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private queryTooLong(): boolean {
|
|
361
|
+
return this.query().length > MAX_SEARCH_QUERY_LENGTH;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private filterNotes(): MarkdownEntry[] {
|
|
365
|
+
const query = this.searchInput.getValue();
|
|
366
|
+
if (!this.searchEnabled || !query.trim()) return [...this.options.notes];
|
|
367
|
+
if (query.length > MAX_SEARCH_QUERY_LENGTH) return [];
|
|
368
|
+
return fuzzyFilter([...this.options.notes], query, ({ displayPath }) => sanitizeTerminalText(displayPath));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private applySearchInput(data: string): void {
|
|
372
|
+
const previousQuery = this.searchInput.getValue();
|
|
373
|
+
this.searchInput.handleInput(data);
|
|
374
|
+
const safeQuery = sanitizeTerminalText(this.searchInput.getValue());
|
|
375
|
+
if (safeQuery !== this.searchInput.getValue()) this.searchInput.setValue(safeQuery);
|
|
376
|
+
if (safeQuery === previousQuery) return;
|
|
377
|
+
const previousSelection = this.selectedPath;
|
|
378
|
+
this.filteredNotes = this.filterNotes();
|
|
379
|
+
const restored = this.filteredNotes.find(({ relativePath }) => relativePath === this.restoreSelectedPath);
|
|
380
|
+
const retained = this.filteredNotes.find(({ relativePath }) => relativePath === previousSelection);
|
|
381
|
+
if (restored) {
|
|
382
|
+
this.selectedPath = restored.relativePath;
|
|
383
|
+
this.restoreSelectedPath = undefined;
|
|
384
|
+
} else if (retained) this.selectedPath = retained.relativePath;
|
|
385
|
+
else {
|
|
386
|
+
if (previousSelection) this.restoreSelectedPath ??= previousSelection;
|
|
387
|
+
this.selectedPath = this.filteredNotes[0]?.relativePath;
|
|
388
|
+
}
|
|
389
|
+
this.scrollOffset = 0;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
private routeInput(data: string): void {
|
|
393
|
+
this.clearPasteStartTimer();
|
|
394
|
+
if (this.pasteBuffer !== undefined) {
|
|
395
|
+
this.pasteBuffer += data;
|
|
396
|
+
this.flushPasteBuffer();
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const combined = this.pasteStartBuffer + data;
|
|
401
|
+
this.pasteStartBuffer = "";
|
|
402
|
+
const pasteStart = combined.indexOf(BRACKETED_PASTE_START);
|
|
403
|
+
if (pasteStart >= 0) {
|
|
404
|
+
if (pasteStart > 0) this.handleNonPasteInput(combined.slice(0, pasteStart));
|
|
405
|
+
if (this.disposed || this.completed) return;
|
|
406
|
+
this.pasteBuffer = combined.slice(pasteStart + BRACKETED_PASTE_START.length);
|
|
407
|
+
this.flushPasteBuffer();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const prefixLength = trailingMarkerPrefixLength(combined, BRACKETED_PASTE_START);
|
|
412
|
+
const outsidePaste = combined.slice(0, combined.length - prefixLength);
|
|
413
|
+
if (outsidePaste) this.handleNonPasteInput(outsidePaste);
|
|
414
|
+
if (this.disposed || this.completed) return;
|
|
415
|
+
const prefix = combined.slice(combined.length - prefixLength);
|
|
416
|
+
if (!prefix) return;
|
|
417
|
+
this.pasteStartBuffer = prefix;
|
|
418
|
+
this.pasteStartTimer = setTimeout(() => {
|
|
419
|
+
this.pasteStartTimer = undefined;
|
|
420
|
+
const pending = this.pasteStartBuffer;
|
|
421
|
+
this.pasteStartBuffer = "";
|
|
422
|
+
if (!this.disposed && !this.completed && pending) this.handleNonPasteInput(pending);
|
|
423
|
+
}, INPUT_PREFIX_TIMEOUT_MS);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private flushPasteBuffer(): void {
|
|
427
|
+
if (this.pasteBuffer === undefined) return;
|
|
428
|
+
const pasteEnd = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
|
|
429
|
+
if (pasteEnd < 0) return;
|
|
430
|
+
const pasted = this.pasteBuffer.slice(0, pasteEnd);
|
|
431
|
+
const remaining = this.pasteBuffer.slice(pasteEnd + BRACKETED_PASTE_END.length);
|
|
432
|
+
this.pasteBuffer = undefined;
|
|
433
|
+
if (this.searchEnabled) {
|
|
434
|
+
const safePaste = sanitizePastedSearchText(pasted);
|
|
435
|
+
this.applySearchInput(`${BRACKETED_PASTE_START}${safePaste}${BRACKETED_PASTE_END}`);
|
|
436
|
+
this.options.tui.requestRender();
|
|
437
|
+
}
|
|
438
|
+
if (remaining && !this.disposed && !this.completed) this.routeInput(remaining);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private clearPasteStartTimer(): void {
|
|
442
|
+
if (!this.pasteStartTimer) return;
|
|
443
|
+
clearTimeout(this.pasteStartTimer);
|
|
444
|
+
this.pasteStartTimer = undefined;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private handleNonPasteInput(data: string): void {
|
|
448
|
+
if (this.disposed || this.completed) return;
|
|
449
|
+
this.mousePressedIndex = undefined;
|
|
450
|
+
this.mouseLayout = undefined;
|
|
451
|
+
if (matchesKey(data, Key.ctrl("c"))) {
|
|
452
|
+
this.finish({ kind: "close", ...this.pickerState() });
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
if (matchesKey(data, Key.escape) || this.options.keybindings.matches(data, "tui.select.cancel")) {
|
|
456
|
+
this.finish({ kind: "back", ...this.pickerState() });
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
if (this.options.keybindings.matches(data, "tui.select.up")) this.move(-1);
|
|
460
|
+
else if (this.options.keybindings.matches(data, "tui.select.down")) this.move(1);
|
|
461
|
+
else if (this.options.keybindings.matches(data, "tui.select.pageUp")) this.move(-this.viewportSize(), false);
|
|
462
|
+
else if (this.options.keybindings.matches(data, "tui.select.pageDown")) this.move(this.viewportSize(), false);
|
|
463
|
+
else if (!this.searchEnabled && matchesKey(data, Key.home)) this.selectAt(0);
|
|
464
|
+
else if (!this.searchEnabled && matchesKey(data, Key.end)) this.selectAt(this.filteredNotes.length - 1);
|
|
465
|
+
else if (this.options.keybindings.matches(data, "tui.select.confirm")) this.openSelected();
|
|
466
|
+
else {
|
|
467
|
+
const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
468
|
+
if (deleteKey && matchesKey(data, deleteKey)) this.deleteSelected();
|
|
469
|
+
else if (this.searchEnabled) {
|
|
470
|
+
const safeInput = sanitizeInsertableSearchInput(data, this.options.keybindings);
|
|
471
|
+
if (safeInput !== undefined) this.applySearchInput(safeInput);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (!this.completed) this.options.tui.requestRender();
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private selectedIndex(): number {
|
|
478
|
+
return Math.max(
|
|
479
|
+
0,
|
|
480
|
+
this.filteredNotes.findIndex(({ relativePath }) => relativePath === this.selectedPath),
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
private move(delta: number, wrap = true): void {
|
|
485
|
+
if (this.filteredNotes.length === 0) return;
|
|
486
|
+
const current = this.selectedIndex();
|
|
487
|
+
const next = wrap
|
|
488
|
+
? (current + delta + this.filteredNotes.length) % this.filteredNotes.length
|
|
489
|
+
: Math.max(0, Math.min(this.filteredNotes.length - 1, current + delta));
|
|
490
|
+
this.selectAt(next);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
private selectAt(index: number): void {
|
|
494
|
+
if (this.filteredNotes.length === 0) return;
|
|
495
|
+
const bounded = Math.max(0, Math.min(this.filteredNotes.length - 1, index));
|
|
496
|
+
this.selectedPath = this.filteredNotes[bounded]?.relativePath;
|
|
497
|
+
this.restoreSelectedPath = undefined;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private keepSelectionVisible(height: number): void {
|
|
501
|
+
if (this.filteredNotes.length === 0) {
|
|
502
|
+
this.scrollOffset = 0;
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
const index = this.selectedIndex();
|
|
506
|
+
if (index < this.scrollOffset) this.scrollOffset = index;
|
|
507
|
+
if (index >= this.scrollOffset + height) this.scrollOffset = index - height + 1;
|
|
508
|
+
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.filteredNotes.length - height));
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
private openSelected(): void {
|
|
512
|
+
if (!this.selectedPath) return;
|
|
513
|
+
this.finish({ kind: "open", notePath: this.selectedPath, query: this.query() });
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private deleteSelected(): void {
|
|
517
|
+
if (!this.selectedPath) return;
|
|
518
|
+
const selectedIndex = this.selectedIndex();
|
|
519
|
+
const nextSelectedPath =
|
|
520
|
+
this.filteredNotes[selectedIndex + 1]?.relativePath ?? this.filteredNotes[selectedIndex - 1]?.relativePath;
|
|
521
|
+
this.finish({
|
|
522
|
+
kind: "delete",
|
|
523
|
+
notePath: this.selectedPath,
|
|
524
|
+
...(nextSelectedPath ? { nextSelectedPath } : {}),
|
|
525
|
+
query: this.query(),
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private pickerState(): { selectedPath?: string; query?: string } {
|
|
530
|
+
return {
|
|
531
|
+
...(this.selectedPath ? { selectedPath: this.selectedPath } : {}),
|
|
532
|
+
...(this.searchEnabled ? { query: this.query() } : {}),
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private finish(result: NotePickerResult): void {
|
|
537
|
+
if (this.completed) return;
|
|
538
|
+
this.completed = true;
|
|
539
|
+
this.clearPasteStartTimer();
|
|
540
|
+
this.pasteStartBuffer = "";
|
|
541
|
+
this.pasteBuffer = undefined;
|
|
542
|
+
this.options.complete(result);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function sanitizePastedSearchText(value: string): string {
|
|
547
|
+
const singleLine = value
|
|
548
|
+
.replace(/\r\n/gu, "")
|
|
549
|
+
.replace(/[\r\n]/gu, "")
|
|
550
|
+
.replace(/\t/gu, " ");
|
|
551
|
+
return sanitizeTerminalText(singleLine);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function sanitizeInsertableSearchInput(
|
|
555
|
+
data: string,
|
|
556
|
+
keybindings: Pick<KeybindingsManager, "matches">,
|
|
557
|
+
): string | undefined {
|
|
558
|
+
if (data === "\n" || SEARCH_INPUT_BINDINGS.some((binding) => keybindings.matches(data, binding))) return data;
|
|
559
|
+
const printable = decodeKittyPrintable(data) ?? decodeModifyOtherKeysPrintable(data);
|
|
560
|
+
if (printable !== undefined) return sanitizeTerminalText(printable) || undefined;
|
|
561
|
+
const hasControlCharacters = [...data].some((character) => {
|
|
562
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
563
|
+
return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f);
|
|
564
|
+
});
|
|
565
|
+
if (hasControlCharacters) return data;
|
|
566
|
+
return sanitizeTerminalText(data) || undefined;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function decodeModifyOtherKeysPrintable(data: string): string | undefined {
|
|
570
|
+
// Pi exposes the Kitty decoder from its root; mirror Editor's xterm modifyOtherKeys fallback.
|
|
571
|
+
const prefix = "\u001b[27;";
|
|
572
|
+
if (!data.startsWith(prefix)) return undefined;
|
|
573
|
+
const match = data.slice(prefix.length).match(/^(\d+);(\d+)~$/u);
|
|
574
|
+
if (!match) return undefined;
|
|
575
|
+
const modifier = (Number.parseInt(match[1] ?? "", 10) - 1) & ~(64 | 128);
|
|
576
|
+
const codePoint = Number.parseInt(match[2] ?? "", 10);
|
|
577
|
+
if ((modifier & ~1) !== 0 || !Number.isFinite(codePoint) || codePoint < 32) return undefined;
|
|
578
|
+
try {
|
|
579
|
+
return String.fromCodePoint(codePoint);
|
|
580
|
+
} catch {
|
|
581
|
+
return undefined;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function initializeSearchInput(input: Input, value: string): void {
|
|
586
|
+
input.setValue(value);
|
|
587
|
+
// Input.setValue() preserves its cursor, so use its public mouse contract to place a fresh cursor at the end.
|
|
588
|
+
const x = visibleWidth(value) + 2;
|
|
589
|
+
input.handleMouse({
|
|
590
|
+
type: "press",
|
|
591
|
+
button: "left",
|
|
592
|
+
x,
|
|
593
|
+
y: 0,
|
|
594
|
+
screenX: x,
|
|
595
|
+
screenY: 0,
|
|
596
|
+
width: x + 1,
|
|
597
|
+
height: 1,
|
|
598
|
+
shift: false,
|
|
599
|
+
alt: false,
|
|
600
|
+
ctrl: false,
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function resolveNotePickerHintKeys(
|
|
605
|
+
keybindings: Pick<KeybindingsManager, "getKeys">,
|
|
606
|
+
searchEnabled: boolean,
|
|
607
|
+
terminal?: KeyboardProtocolTerminal,
|
|
608
|
+
): NotePickerHintKeys {
|
|
609
|
+
const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
|
|
610
|
+
const claimed = ["ctrl+c"];
|
|
611
|
+
const claim = (candidates: readonly unknown[]): KeyId[] => {
|
|
612
|
+
const available: KeyId[] = [];
|
|
613
|
+
for (const candidate of candidates) {
|
|
614
|
+
const normalized = normalizeKey(candidate);
|
|
615
|
+
if (!normalized || !keyRoutesAsSingleInput(normalized, disambiguatedKeyProtocol)) continue;
|
|
616
|
+
if (claimed.some((other) => keysOverlap(normalized, other, disambiguatedKeyProtocol))) continue;
|
|
617
|
+
claimed.push(normalized);
|
|
618
|
+
available.push(normalized as KeyId);
|
|
619
|
+
}
|
|
620
|
+
return available;
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
// Match handleNonPasteInput() branch order so every displayed key reaches its labeled action.
|
|
624
|
+
const back = claim([...keybindings.getKeys("tui.select.cancel"), "escape"]);
|
|
625
|
+
const up = claim(keybindings.getKeys("tui.select.up"));
|
|
626
|
+
const down = claim(keybindings.getKeys("tui.select.down"));
|
|
627
|
+
claim(keybindings.getKeys("tui.select.pageUp"));
|
|
628
|
+
claim(keybindings.getKeys("tui.select.pageDown"));
|
|
629
|
+
if (!searchEnabled) {
|
|
630
|
+
claim(["home"]);
|
|
631
|
+
claim(["end"]);
|
|
632
|
+
}
|
|
633
|
+
const confirm = claim(keybindings.getKeys("tui.select.confirm"));
|
|
634
|
+
return { navigation: [...up, ...down], confirm, back };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Resolve the first effective delete binding that remains reachable in this picker. */
|
|
638
|
+
export function resolveNoteDeleteKey(
|
|
639
|
+
keybindings: Pick<KeybindingsManager, "getKeys">,
|
|
640
|
+
searchEnabled: boolean,
|
|
641
|
+
terminal?: KeyboardProtocolTerminal,
|
|
642
|
+
): KeyId | undefined {
|
|
643
|
+
const activeBindings = [...PICKER_BINDINGS, ...(searchEnabled ? SEARCH_INPUT_BINDINGS : [])];
|
|
644
|
+
const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
|
|
645
|
+
const reserved = [
|
|
646
|
+
"ctrl+c",
|
|
647
|
+
"escape",
|
|
648
|
+
...(!searchEnabled ? ["home", "end"] : []),
|
|
649
|
+
...(searchEnabled && !disambiguatedKeyProtocol ? ["ctrl+j"] : []),
|
|
650
|
+
...activeBindings.flatMap((binding) => {
|
|
651
|
+
if (binding === "tui.editor.deleteCharForward") {
|
|
652
|
+
return keybindings.getKeys(binding).filter((key) => normalizeKey(key) !== "ctrl+d");
|
|
653
|
+
}
|
|
654
|
+
return keybindings.getKeys(binding);
|
|
655
|
+
}),
|
|
656
|
+
];
|
|
657
|
+
for (const candidate of keybindings.getKeys("app.session.delete")) {
|
|
658
|
+
const normalized = normalizeKey(candidate);
|
|
659
|
+
if (!normalized || (searchEnabled && isTextKey(normalized))) continue;
|
|
660
|
+
if (disambiguatedKeyProtocol) {
|
|
661
|
+
if (reserved.some((other) => normalizeKey(other) === normalized)) continue;
|
|
662
|
+
return normalized as KeyId;
|
|
663
|
+
}
|
|
664
|
+
const inputs = inputsFor(normalized);
|
|
665
|
+
if (inputs.length === 0 || inputs.some((input) => !routesAsSingleNonPasteInput(input))) continue;
|
|
666
|
+
if (reserved.some((other) => inputs.some((input) => matchesKey(input, other as KeyId)))) continue;
|
|
667
|
+
return normalized as KeyId;
|
|
668
|
+
}
|
|
669
|
+
return undefined;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function normalizeKey(value: unknown): string | undefined {
|
|
673
|
+
if (typeof value !== "string" || value.length > 80 || /[\s\p{Cc}]/u.test(value)) return undefined;
|
|
674
|
+
const parts = value.toLowerCase().split("+");
|
|
675
|
+
let base = parts.pop();
|
|
676
|
+
if (!base) return undefined;
|
|
677
|
+
if (base === "esc") base = "escape";
|
|
678
|
+
if (base === "return") base = "enter";
|
|
679
|
+
if (new Set(parts).size !== parts.length || parts.some((part) => !MODIFIERS.includes(part as never)))
|
|
680
|
+
return undefined;
|
|
681
|
+
if (
|
|
682
|
+
!SPECIAL_KEYS.has(base) &&
|
|
683
|
+
!/^f(?:[1-9]|1[0-2])$/u.test(base) &&
|
|
684
|
+
!(base.length === 1 && (/^[a-z0-9]$/u.test(base) || SYMBOLS.includes(base)))
|
|
685
|
+
)
|
|
686
|
+
return undefined;
|
|
687
|
+
if ((base === "escape" || /^f(?:[1-9]|1[0-2])$/u.test(base)) && parts.length > 0) return undefined;
|
|
688
|
+
if (base === "clear" && (parts.length > 1 || (parts.length === 1 && !["ctrl", "shift"].includes(parts[0] ?? ""))))
|
|
689
|
+
return undefined;
|
|
690
|
+
return [...MODIFIERS.filter((modifier) => parts.includes(modifier)), base].join("+");
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function inputsFor(key: string): string[] {
|
|
694
|
+
const parts = key.split("+");
|
|
695
|
+
const base = parts.pop() ?? "";
|
|
696
|
+
const modifier = MODIFIERS.reduce((mask, part, bit) => mask | (parts.includes(part) ? 1 << bit : 0), 0);
|
|
697
|
+
const code = SPECIAL_CODEPOINTS[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);
|
|
698
|
+
const inputs = code === undefined ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\u001b[${code};${modifier + 1}u`];
|
|
699
|
+
return inputs.filter((input) => matchesKey(input, key as KeyId));
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function usesDisambiguatedKeyProtocol(terminal?: KeyboardProtocolTerminal): boolean {
|
|
703
|
+
return isKittyProtocolActive() || terminal?.kittyProtocolActive === true || terminal?.modifyOtherKeysActive === true;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function keysOverlap(first: string, second: string, disambiguatedKeyProtocol: boolean): boolean {
|
|
707
|
+
if (disambiguatedKeyProtocol) return first === second;
|
|
708
|
+
return inputsFor(first).some((input) => matchesKey(input, second as KeyId));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function keyRoutesAsSingleInput(key: string, disambiguatedKeyProtocol: boolean): boolean {
|
|
712
|
+
if (disambiguatedKeyProtocol) return true;
|
|
713
|
+
const inputs = inputsFor(key);
|
|
714
|
+
return inputs.length > 0 && inputs.every(routesAsSingleNonPasteInput);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function routesAsSingleNonPasteInput(input: string): boolean {
|
|
718
|
+
if (input.includes(BRACKETED_PASTE_START)) return false;
|
|
719
|
+
const prefixLength = trailingMarkerPrefixLength(input, BRACKETED_PASTE_START);
|
|
720
|
+
return prefixLength === 0 || prefixLength === input.length;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function trailingMarkerPrefixLength(value: string, marker: string): number {
|
|
724
|
+
const maximum = Math.min(value.length, marker.length - 1);
|
|
725
|
+
for (let length = maximum; length > 0; length -= 1) {
|
|
726
|
+
if (value.endsWith(marker.slice(0, length))) return length;
|
|
727
|
+
}
|
|
728
|
+
return 0;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function isTextKey(key: string): boolean {
|
|
732
|
+
const parts = key.split("+");
|
|
733
|
+
const base = parts.at(-1) ?? "";
|
|
734
|
+
return (base.length === 1 || base === "space") && !parts.some((part) => ["ctrl", "alt", "super"].includes(part));
|
|
735
|
+
}
|