@narumitw/pi-notes 0.1.0 → 0.2.1
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/package.json +5 -5
- package/src/menu.ts +132 -29
- package/src/note-picker.ts +712 -0
- package/src/storage.ts +26 -0
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
- Discovers notes and user-managed templates dynamically under Pi's configured agent directory.
|
|
11
11
|
- Creates a blank or templated note immediately under a collision-safe temporary name without asking for a filename.
|
|
12
12
|
- Lets the embedded agent proactively rename the current note when its purpose becomes clear.
|
|
13
|
-
- Opens notes directly
|
|
13
|
+
- Opens notes directly, deletes a highlighted note after confirmation, or inserts its canonical absolute path into the parent editor without replacing the draft.
|
|
14
14
|
- Edits existing templates with cancellation and stale-write protection.
|
|
15
15
|
- Shows a fullscreen split Chat/Preview workspace on wide terminals and fullscreen tabs on narrow terminals.
|
|
16
16
|
- Gives the embedded agent only tools scoped to the currently open note.
|
|
@@ -49,7 +49,7 @@ Run Pi in TUI mode, then open the manager:
|
|
|
49
49
|
/notes
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **Manage templates…**. Existing note names appear only after opening the dedicated note list. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension opens the note immediately as `untitled.md`, an available numbered variant, or a generated fallback, then the embedded agent renames it when the note's purpose is clear. The extension does not seed templates.
|
|
52
|
+
Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **Manage templates…**. Existing note names appear only after opening the dedicated note list. In that list, Enter opens the highlighted note and the configured `app.session.delete` binding (`Ctrl+D` by default) asks to delete it. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension opens the note immediately as `untitled.md`, an available numbered variant, or a generated fallback, then the embedded agent renames it when the note's purpose is clear. The extension does not seed templates.
|
|
53
53
|
|
|
54
54
|
## 🧭 How it works
|
|
55
55
|
|
|
@@ -57,6 +57,7 @@ Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **
|
|
|
57
57
|
flowchart LR
|
|
58
58
|
P[Parent Pi session] -->|/notes| M[Notes manager]
|
|
59
59
|
M --> W[Temporary notes workspace]
|
|
60
|
+
M --> D[Confirm and delete note]
|
|
60
61
|
M --> I[Paste canonical path into parent draft]
|
|
61
62
|
M --> E[Edit existing template]
|
|
62
63
|
W --> C[Isolated child AgentSession]
|
|
@@ -85,7 +86,9 @@ New managed directories use mode `0700` and newly created notes use `0600` where
|
|
|
85
86
|
|
|
86
87
|
`/notes` opens the browse/create manager and accepts no arguments. It requires Pi TUI mode and rejects RPC, print, and JSON modes.
|
|
87
88
|
|
|
88
|
-
The manager rescans notes and templates when each screen opens. Its first level contains actions only; **Open a note…** shows the current note list on a separate screen.
|
|
89
|
+
The manager rescans notes and templates when each screen opens. Its first level contains actions only; **Open a note…** shows the current note list on a separate screen. Enter opens the highlighted note. The effective `app.session.delete` binding (`Ctrl+D` by default) shows the exact relative path in quoted, terminal-safe escaped form and its byte size before deletion. Cancelling leaves the note unchanged. A confirmed deletion succeeds only while the selected file still has the reviewed revision, then refreshes the list and highlights a neighboring note. It removes the Markdown file but preserves its path-keyed child conversation under `pi-notes/sessions/`.
|
|
90
|
+
|
|
91
|
+
**Paste a note path…** resolves the selected regular file again, closes the manager, and inserts its canonical absolute path at the parent editor's current cursor without replacing the existing draft. Paths containing terminal or display-direction controls are rejected because Pi's paste handling cannot preserve them safely.
|
|
89
92
|
|
|
90
93
|
**Manage templates…** opens an existing template in a Pi-style multiline editor. The editor preserves leading and trailing whitespace and hides terminal controls as spaces without changing their raw values. It rejects pasted text containing an ambiguous bracketed-paste terminator rather than silently reordering it. Because terminal paste framing cannot represent a literal terminator unambiguously, the first save after a paste asks you to review the content and press save again. Cancelling or submitting unchanged content returns to the manager without writing. A changed template is published atomically only if its revision is still current; if another process changed it, Pi Notes preserves that external content, reports the conflict, and refreshes the manager.
|
|
91
94
|
|
|
@@ -110,9 +113,9 @@ The content tools accept no path, and the rename tool accepts no source path. A
|
|
|
110
113
|
- Model and credential configuration is read from Pi's configured agent directory. A provider registered only in another extension's in-memory runtime is not inherited.
|
|
111
114
|
- Child history remains on disk under `pi-notes/sessions/` until the user removes it.
|
|
112
115
|
- Note and template operations reject absolute paths, traversal, special files, and symlinked managed paths. Rename refuses an existing destination and paths deeper than the discovery limit so renamed notes remain available in menus. Same-directory temporary files and atomic publication preserve the previous content when a managed write fails.
|
|
113
|
-
- Revision checks detect stale writes and
|
|
116
|
+
- Revision checks detect stale writes, renames, and deletions, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
|
|
114
117
|
- Note paths and content are treated as untrusted terminal text and sanitized only for display; raw Markdown content and valid raw file identities remain unchanged on disk.
|
|
115
|
-
-
|
|
118
|
+
- Deleting a note does not delete its child-session history. Removing or disabling the package leaves all data under `getAgentDir()/pi-notes/` untouched.
|
|
116
119
|
|
|
117
120
|
## 🚧 Limitations
|
|
118
121
|
|
|
@@ -121,7 +124,7 @@ The content tools accept no path, and the rename tool accepts no source path. A
|
|
|
121
124
|
- Each note path supports at most 100 saved child-session files. The visible transcript is bounded to the latest 200 messages and 50,000 characters.
|
|
122
125
|
- A rename keeps the currently open child conversation, but reopening the renamed note starts a separate child conversation unless the new path already has history. Renaming a note outside the extension has the same path-associated behavior.
|
|
123
126
|
- Parent-only dynamic providers and runtime-only provider state are unavailable to the child; use a provider reconstructable from Pi's normal model and credential files.
|
|
124
|
-
- There is no manual rename UI,
|
|
127
|
+
- There is no manual rename UI, child-history deletion UI, tags, backlinks, full-text index, direct `/notes <path>` route, template language, settings, or bundled skill.
|
|
125
128
|
- Template management edits existing files only; create, rename, delete, agent-assisted template work, and Pi's external-editor shortcut are not supported.
|
|
126
129
|
- Cross-process locking, large notes, rich-text editing, attachments, synchronization, and collaborative editing are not supported.
|
|
127
130
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-notes",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Pi extension for managing global Markdown notes with an isolated embedded agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"typecheck": "tsc --noEmit"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@narumitw/pi-tui-kit": "^0.
|
|
32
|
+
"@narumitw/pi-tui-kit": "^0.66.0"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
35
35
|
"@earendil-works/pi-ai": "*",
|
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
"@earendil-works/pi-tui": "*"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@earendil-works/pi-ai": "
|
|
41
|
-
"@earendil-works/pi-coding-agent": "
|
|
42
|
-
"@earendil-works/pi-tui": "
|
|
40
|
+
"@earendil-works/pi-ai": "1.3.0",
|
|
41
|
+
"@earendil-works/pi-coding-agent": "1.3.0",
|
|
42
|
+
"@earendil-works/pi-tui": "1.3.0",
|
|
43
43
|
"typescript": "7.0.2"
|
|
44
44
|
},
|
|
45
45
|
"repository": {
|
package/src/menu.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { type MenuDefinition, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
3
|
-
import
|
|
2
|
+
import { type MenuDefinition, runCustomInteraction, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
|
|
3
|
+
import { NotePicker, type NotePickerResult } from "./note-picker.js";
|
|
4
|
+
import type { DiscoveryResult, MarkdownEntry, NoteSnapshot, NotesStorage } from "./storage.js";
|
|
4
5
|
|
|
5
6
|
interface NotesMenuState {
|
|
6
7
|
notes: DiscoveryResult;
|
|
7
8
|
templates: DiscoveryResult;
|
|
8
9
|
}
|
|
9
10
|
|
|
10
|
-
type NotesScreen = "notes" | "
|
|
11
|
-
type NotesAction = "chooseRoute" | "
|
|
11
|
+
type NotesScreen = "notes" | "templates" | "pastePath" | "manageTemplates";
|
|
12
|
+
type NotesAction = "chooseRoute" | "chooseTemplate" | "pastePath" | "editTemplate";
|
|
12
13
|
|
|
13
14
|
export type NotesManagerResult =
|
|
14
15
|
| { kind: "open"; notePath: string }
|
|
@@ -16,7 +17,7 @@ export type NotesManagerResult =
|
|
|
16
17
|
| { kind: "editTemplate"; templatePath: string }
|
|
17
18
|
| { kind: "closed" };
|
|
18
19
|
|
|
19
|
-
export function createNotesMenu(storage: NotesStorage) {
|
|
20
|
+
export function createNotesMenu(storage: NotesStorage, ownership: { isCurrent?: () => boolean } = {}) {
|
|
20
21
|
let result: Exclude<NotesManagerResult, { kind: "closed" }> | undefined;
|
|
21
22
|
|
|
22
23
|
const getState = async ({ signal }: { signal: AbortSignal }): Promise<NotesMenuState> => {
|
|
@@ -64,21 +65,6 @@ export function createNotesMenu(storage: NotesStorage) {
|
|
|
64
65
|
viewportSize: 12,
|
|
65
66
|
hint: "close",
|
|
66
67
|
}),
|
|
67
|
-
openNote: ({ state }) => ({
|
|
68
|
-
kind: "choice",
|
|
69
|
-
title: "Open a note",
|
|
70
|
-
lines: discoveryLines(state.notes, "note"),
|
|
71
|
-
items: state.notes.entries.map((note, index) => ({
|
|
72
|
-
id: `note:${index}`,
|
|
73
|
-
label: note.displayPath,
|
|
74
|
-
description: `${note.size} bytes`,
|
|
75
|
-
searchText: note.displayPath,
|
|
76
|
-
})),
|
|
77
|
-
action: "chooseNote",
|
|
78
|
-
enableSearch: state.notes.entries.length > 8,
|
|
79
|
-
viewportSize: 12,
|
|
80
|
-
hint: "back",
|
|
81
|
-
}),
|
|
82
68
|
templates: ({ state }) => ({
|
|
83
69
|
kind: "choice",
|
|
84
70
|
title: "Choose initial content",
|
|
@@ -133,19 +119,20 @@ export function createNotesMenu(storage: NotesStorage) {
|
|
|
133
119
|
}),
|
|
134
120
|
},
|
|
135
121
|
actions: {
|
|
136
|
-
chooseRoute: ({ itemId }) => {
|
|
137
|
-
if (itemId === "open")
|
|
122
|
+
chooseRoute: async ({ ctx, itemId, signal }) => {
|
|
123
|
+
if (itemId === "open") {
|
|
124
|
+
const selected = await chooseOpenNote(ctx, storage, signal, ownership);
|
|
125
|
+
if (selected.kind === "open") {
|
|
126
|
+
result = selected;
|
|
127
|
+
return { kind: "close" };
|
|
128
|
+
}
|
|
129
|
+
return { kind: selected.kind === "close" ? "close" : "stay" };
|
|
130
|
+
}
|
|
138
131
|
if (itemId === "create") return { kind: "to", screen: "templates" };
|
|
139
132
|
if (itemId === "paste-path") return { kind: "to", screen: "pastePath" };
|
|
140
133
|
if (itemId === "manage-templates") return { kind: "to", screen: "manageTemplates" };
|
|
141
134
|
return { kind: "rejected", error: new Error("The selected notes action is no longer available") };
|
|
142
135
|
},
|
|
143
|
-
chooseNote: ({ state, itemId }) => {
|
|
144
|
-
const note = indexedEntry(state.notes.entries, itemId, "note:");
|
|
145
|
-
if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
|
|
146
|
-
result = { kind: "open", notePath: note.relativePath };
|
|
147
|
-
return { kind: "close" };
|
|
148
|
-
},
|
|
149
136
|
chooseTemplate: async ({ state, itemId, signal }) => {
|
|
150
137
|
const templatePath =
|
|
151
138
|
itemId === "blank" ? undefined : indexedEntry(state.templates.entries, itemId, "template:")?.relativePath;
|
|
@@ -186,7 +173,7 @@ export async function showNotesManager(
|
|
|
186
173
|
storage: NotesStorage,
|
|
187
174
|
ownership: { signal: AbortSignal; isCurrent(): boolean },
|
|
188
175
|
): Promise<NotesManagerResult> {
|
|
189
|
-
const controller = createNotesMenu(storage);
|
|
176
|
+
const controller = createNotesMenu(storage, ownership);
|
|
190
177
|
const result = await runMenu(ctx, controller.menu, {
|
|
191
178
|
getState: controller.getState,
|
|
192
179
|
signal: ownership.signal,
|
|
@@ -202,6 +189,122 @@ export async function showNotesManager(
|
|
|
202
189
|
return selected && ownership.isCurrent() && !ownership.signal.aborted ? selected : { kind: "closed" };
|
|
203
190
|
}
|
|
204
191
|
|
|
192
|
+
async function chooseOpenNote(
|
|
193
|
+
ctx: ExtensionCommandContext,
|
|
194
|
+
storage: NotesStorage,
|
|
195
|
+
signal: AbortSignal,
|
|
196
|
+
ownership: { isCurrent?: () => boolean },
|
|
197
|
+
): Promise<{ kind: "open"; notePath: string } | { kind: "back" | "close" }> {
|
|
198
|
+
let selectedPath: string | undefined;
|
|
199
|
+
let query = "";
|
|
200
|
+
const isCurrent = () => ownership.isCurrent?.() ?? true;
|
|
201
|
+
|
|
202
|
+
while (!signal.aborted && isCurrent()) {
|
|
203
|
+
const notes = await storage.discoverNotes(signal);
|
|
204
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
205
|
+
const interaction = await runCustomInteraction<NotePickerResult>(ctx, {
|
|
206
|
+
signal,
|
|
207
|
+
isCurrent,
|
|
208
|
+
onError: (currentCtx, error) => {
|
|
209
|
+
if (!signal.aborted && isCurrent()) {
|
|
210
|
+
safeNotify(currentCtx, `Pi Notes picker failed: ${safeErrorMessage(error)}`, "error");
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
create: ({ tui, theme, keybindings, complete }) =>
|
|
214
|
+
new NotePicker({
|
|
215
|
+
tui,
|
|
216
|
+
theme,
|
|
217
|
+
keybindings,
|
|
218
|
+
notes: notes.entries,
|
|
219
|
+
lines: discoveryLines(notes, "note"),
|
|
220
|
+
initialSelectedPath: selectedPath,
|
|
221
|
+
initialQuery: query,
|
|
222
|
+
complete,
|
|
223
|
+
}),
|
|
224
|
+
});
|
|
225
|
+
if (signal.aborted || !isCurrent() || interaction.kind === "stale") return { kind: "close" };
|
|
226
|
+
if (interaction.kind !== "completed") return { kind: "close" };
|
|
227
|
+
|
|
228
|
+
const choice = interaction.value;
|
|
229
|
+
if ("query" in choice && choice.query !== undefined) query = choice.query;
|
|
230
|
+
if ("selectedPath" in choice) selectedPath = choice.selectedPath;
|
|
231
|
+
if (choice.kind === "back" || choice.kind === "close") return { kind: choice.kind };
|
|
232
|
+
if (choice.kind === "open") return { kind: "open", notePath: choice.notePath };
|
|
233
|
+
|
|
234
|
+
selectedPath = choice.nextSelectedPath;
|
|
235
|
+
const selected = notes.entries.find(({ relativePath }) => relativePath === choice.notePath);
|
|
236
|
+
if (!selected) {
|
|
237
|
+
safeNotify(ctx, "The selected note is no longer available; refreshed the note list.", "warning");
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let snapshot: NoteSnapshot;
|
|
242
|
+
try {
|
|
243
|
+
snapshot = await storage.readNote(selected.relativePath, signal);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
246
|
+
safeNotify(ctx, `Pi Notes failed to read the selected note: ${safeErrorMessage(error)}`, "error");
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
250
|
+
|
|
251
|
+
let confirmed: boolean;
|
|
252
|
+
try {
|
|
253
|
+
confirmed = await ctx.ui.confirm("Delete note?", deleteConfirmationMessage(selected, snapshot.size), {
|
|
254
|
+
signal,
|
|
255
|
+
});
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
261
|
+
if (!confirmed) {
|
|
262
|
+
selectedPath = selected.relativePath;
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
await storage.deleteNote(snapshot.relativePath, snapshot.revision, signal);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
270
|
+
safeNotify(ctx, `Pi Notes failed to delete the selected note: ${safeErrorMessage(error)}`, "error");
|
|
271
|
+
selectedPath = selected.relativePath;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (signal.aborted || !isCurrent()) return { kind: "close" };
|
|
275
|
+
safeNotify(ctx, `Deleted note: ${displayNotePath(selected)}`, "info");
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return { kind: "close" };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function deleteConfirmationMessage(note: MarkdownEntry, size: number): string {
|
|
282
|
+
return [
|
|
283
|
+
`Note: ${displayNotePath(note)}`,
|
|
284
|
+
`Size: ${size} bytes`,
|
|
285
|
+
"",
|
|
286
|
+
"Delete this Markdown note? This cannot be undone.",
|
|
287
|
+
"Its saved child conversation will remain under pi-notes/sessions/.",
|
|
288
|
+
].join("\n");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function displayNotePath(note: MarkdownEntry): string {
|
|
292
|
+
let display = '"';
|
|
293
|
+
for (const character of note.relativePath) {
|
|
294
|
+
if (character === '"' || character === "\\") {
|
|
295
|
+
display += `\\${character}`;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (sanitizeTerminalText(character) !== character) {
|
|
299
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
300
|
+
display += codePoint <= 0xff ? `\\x${codePoint.toString(16).padStart(2, "0")}` : `\\u{${codePoint.toString(16)}}`;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
display += character;
|
|
304
|
+
}
|
|
305
|
+
return `${display}"`;
|
|
306
|
+
}
|
|
307
|
+
|
|
205
308
|
function indexedEntry(entries: readonly MarkdownEntry[], itemId: string, prefix: string): MarkdownEntry | undefined {
|
|
206
309
|
if (!itemId.startsWith(prefix)) return undefined;
|
|
207
310
|
const index = Number.parseInt(itemId.slice(prefix.length), 10);
|
|
@@ -0,0 +1,712 @@
|
|
|
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 {
|
|
20
|
+
canonicalizeConfiguredKey,
|
|
21
|
+
formatInteractionHints,
|
|
22
|
+
HorizontalRule,
|
|
23
|
+
renderBoundedFrame,
|
|
24
|
+
sanitizeTerminalText,
|
|
25
|
+
} from "@narumitw/pi-tui-kit";
|
|
26
|
+
import type { MarkdownEntry } from "./storage.js";
|
|
27
|
+
|
|
28
|
+
const BRACKETED_PASTE_START = "\u001b[200~";
|
|
29
|
+
const BRACKETED_PASTE_END = "\u001b[201~";
|
|
30
|
+
const INPUT_PREFIX_TIMEOUT_MS = 10;
|
|
31
|
+
const MAX_SEARCH_QUERY_LENGTH = 256;
|
|
32
|
+
const MAX_VISIBLE_NOTES = 12;
|
|
33
|
+
|
|
34
|
+
type KeyboardProtocolTerminal = TUI["terminal"] & {
|
|
35
|
+
readonly modifyOtherKeysActive?: boolean;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
interface NotePickerHintKeys {
|
|
39
|
+
navigation: readonly KeyId[];
|
|
40
|
+
confirm: readonly KeyId[];
|
|
41
|
+
back: readonly KeyId[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const PICKER_BINDINGS = [
|
|
45
|
+
"tui.select.up",
|
|
46
|
+
"tui.select.down",
|
|
47
|
+
"tui.select.pageUp",
|
|
48
|
+
"tui.select.pageDown",
|
|
49
|
+
"tui.select.confirm",
|
|
50
|
+
"tui.select.cancel",
|
|
51
|
+
] as const;
|
|
52
|
+
// These are the configurable actions Pi Input consumes before printable insertion.
|
|
53
|
+
const SEARCH_INPUT_BINDINGS = [
|
|
54
|
+
"tui.editor.undo",
|
|
55
|
+
"tui.input.submit",
|
|
56
|
+
"tui.editor.deleteCharBackward",
|
|
57
|
+
"tui.editor.deleteCharForward",
|
|
58
|
+
"tui.editor.deleteWordBackward",
|
|
59
|
+
"tui.editor.deleteWordForward",
|
|
60
|
+
"tui.editor.deleteToLineStart",
|
|
61
|
+
"tui.editor.deleteToLineEnd",
|
|
62
|
+
"tui.editor.yank",
|
|
63
|
+
"tui.editor.yankPop",
|
|
64
|
+
"tui.editor.cursorLeft",
|
|
65
|
+
"tui.editor.cursorRight",
|
|
66
|
+
"tui.editor.cursorLineStart",
|
|
67
|
+
"tui.editor.cursorLineEnd",
|
|
68
|
+
"tui.editor.cursorWordLeft",
|
|
69
|
+
"tui.editor.cursorWordRight",
|
|
70
|
+
] as const;
|
|
71
|
+
|
|
72
|
+
const MODIFIERS = ["shift", "alt", "ctrl", "super"] as const;
|
|
73
|
+
const FUNCTION_INPUTS = ["OP", "OQ", "OR", "OS", "[15~", "[17~", "[18~", "[19~", "[20~", "[21~", "[23~", "[24~"];
|
|
74
|
+
const LEGACY_INPUTS = [
|
|
75
|
+
...Array.from({ length: 128 }, (_, code) => String.fromCharCode(code)),
|
|
76
|
+
...Array.from({ length: 128 }, (_, code) => `\u001b${String.fromCharCode(code)}`),
|
|
77
|
+
"\u001b[Z",
|
|
78
|
+
"\u001bOM",
|
|
79
|
+
"\u001b[E",
|
|
80
|
+
"\u001b[e",
|
|
81
|
+
"\u001bOe",
|
|
82
|
+
...FUNCTION_INPUTS.map((suffix) => `\u001b${suffix}`),
|
|
83
|
+
];
|
|
84
|
+
const SPECIAL_CODEPOINTS: Record<string, number> = {
|
|
85
|
+
escape: 27,
|
|
86
|
+
tab: 9,
|
|
87
|
+
enter: 13,
|
|
88
|
+
space: 32,
|
|
89
|
+
backspace: 127,
|
|
90
|
+
insert: 57425,
|
|
91
|
+
delete: 57426,
|
|
92
|
+
home: 57423,
|
|
93
|
+
end: 57424,
|
|
94
|
+
pageup: 57421,
|
|
95
|
+
pagedown: 57422,
|
|
96
|
+
left: 57417,
|
|
97
|
+
right: 57418,
|
|
98
|
+
up: 57419,
|
|
99
|
+
down: 57420,
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export type NotePickerResult =
|
|
103
|
+
| { kind: "open"; notePath: string; query?: string }
|
|
104
|
+
| { kind: "delete"; notePath: string; nextSelectedPath?: string; query?: string }
|
|
105
|
+
| { kind: "back"; selectedPath?: string; query?: string }
|
|
106
|
+
| { kind: "close"; selectedPath?: string; query?: string };
|
|
107
|
+
|
|
108
|
+
interface NotePickerOptions {
|
|
109
|
+
tui: TUI;
|
|
110
|
+
theme: Theme;
|
|
111
|
+
keybindings: KeybindingsManager;
|
|
112
|
+
notes: readonly MarkdownEntry[];
|
|
113
|
+
lines?: readonly string[];
|
|
114
|
+
initialSelectedPath?: string;
|
|
115
|
+
initialQuery?: string;
|
|
116
|
+
complete(result: NotePickerResult): void;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface MouseLayout {
|
|
120
|
+
width: number;
|
|
121
|
+
inputFrameRow?: number;
|
|
122
|
+
noteByFrameRow: ReadonlyMap<number, number>;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export class NotePicker implements Component, Focusable {
|
|
126
|
+
private readonly searchInput = new Input();
|
|
127
|
+
private readonly searchEnabled: boolean;
|
|
128
|
+
private filteredNotes: MarkdownEntry[];
|
|
129
|
+
private selectedPath: string | undefined;
|
|
130
|
+
private restoreSelectedPath: string | undefined;
|
|
131
|
+
private scrollOffset = 0;
|
|
132
|
+
private pasteStartBuffer = "";
|
|
133
|
+
private pasteBuffer: string | undefined;
|
|
134
|
+
private pasteStartTimer: ReturnType<typeof setTimeout> | undefined;
|
|
135
|
+
private mousePressedIndex: number | undefined;
|
|
136
|
+
private mouseLayout: MouseLayout | undefined;
|
|
137
|
+
private disposed = false;
|
|
138
|
+
private completed = false;
|
|
139
|
+
private isFocused = false;
|
|
140
|
+
|
|
141
|
+
constructor(private readonly options: NotePickerOptions) {
|
|
142
|
+
this.searchEnabled = options.notes.length > 8;
|
|
143
|
+
initializeSearchInput(this.searchInput, sanitizeTerminalText(options.initialQuery ?? ""));
|
|
144
|
+
this.searchInput.focused = false;
|
|
145
|
+
this.filteredNotes = this.filterNotes();
|
|
146
|
+
this.selectedPath = this.filteredNotes.some(({ relativePath }) => relativePath === options.initialSelectedPath)
|
|
147
|
+
? options.initialSelectedPath
|
|
148
|
+
: this.filteredNotes[0]?.relativePath;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
get focused(): boolean {
|
|
152
|
+
return this.isFocused;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
set focused(value: boolean) {
|
|
156
|
+
this.isFocused = value;
|
|
157
|
+
this.searchInput.focused = value && this.searchEnabled && !this.disposed;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
render(width: number): string[] {
|
|
161
|
+
const safeWidth = Math.max(1, Math.floor(width));
|
|
162
|
+
const viewportSize = this.viewportSize();
|
|
163
|
+
this.keepSelectionVisible(viewportSize);
|
|
164
|
+
const visible = this.filteredNotes.slice(this.scrollOffset, this.scrollOffset + viewportSize);
|
|
165
|
+
const rows = visible.map((note) => this.renderNote(note, note.relativePath === this.selectedPath, safeWidth));
|
|
166
|
+
const content: string[] = [];
|
|
167
|
+
let selectedContentIndex: number | undefined;
|
|
168
|
+
|
|
169
|
+
if (this.searchEnabled) {
|
|
170
|
+
content.push(this.renderSearch(safeWidth), "");
|
|
171
|
+
}
|
|
172
|
+
const listStart = content.length;
|
|
173
|
+
if (rows.length > 0) {
|
|
174
|
+
content.push(...rows);
|
|
175
|
+
const selectedVisibleIndex = visible.findIndex(({ relativePath }) => relativePath === this.selectedPath);
|
|
176
|
+
if (selectedVisibleIndex >= 0) selectedContentIndex = listStart + selectedVisibleIndex;
|
|
177
|
+
} else {
|
|
178
|
+
content.push(
|
|
179
|
+
this.options.theme.fg(
|
|
180
|
+
this.queryTooLong() ? "error" : "dim",
|
|
181
|
+
this.queryTooLong()
|
|
182
|
+
? ` Search query is too long (maximum ${MAX_SEARCH_QUERY_LENGTH} characters)`
|
|
183
|
+
: this.options.notes.length === 0
|
|
184
|
+
? " No notes found."
|
|
185
|
+
: " No matching notes.",
|
|
186
|
+
),
|
|
187
|
+
);
|
|
188
|
+
selectedContentIndex = content.length - 1;
|
|
189
|
+
}
|
|
190
|
+
if (this.filteredNotes.length > viewportSize) {
|
|
191
|
+
const selectedIndex = this.selectedIndex();
|
|
192
|
+
content.push(this.options.theme.fg("dim", ` (${selectedIndex + 1}/${this.filteredNotes.length})`));
|
|
193
|
+
}
|
|
194
|
+
if (this.searchEnabled) content.push(this.options.theme.fg("dim", "Type to search"));
|
|
195
|
+
|
|
196
|
+
const hint = this.interactionHint();
|
|
197
|
+
const hintRows = wrapTextWithAnsi(this.options.theme.fg("dim", hint), safeWidth);
|
|
198
|
+
const title = this.options.theme.fg("accent", this.options.theme.bold("Open a note"));
|
|
199
|
+
const context = (this.options.lines ?? []).map((line) =>
|
|
200
|
+
this.options.theme.fg("muted", sanitizeTerminalText(line)),
|
|
201
|
+
);
|
|
202
|
+
const rule =
|
|
203
|
+
new HorizontalRule({ ruleStyle: (text) => this.options.theme.fg("border", text) }).render(safeWidth)[0] ?? "";
|
|
204
|
+
const priorities = [
|
|
205
|
+
...(this.searchEnabled ? [0] : []),
|
|
206
|
+
...(selectedContentIndex === undefined ? [] : [selectedContentIndex]),
|
|
207
|
+
];
|
|
208
|
+
const maxRows = Math.max(1, Math.floor(this.options.tui.terminal.rows) - 3);
|
|
209
|
+
const frame = renderBoundedFrame({
|
|
210
|
+
width: safeWidth,
|
|
211
|
+
maxRows,
|
|
212
|
+
rule,
|
|
213
|
+
title: [title],
|
|
214
|
+
context,
|
|
215
|
+
content,
|
|
216
|
+
hints: hintRows,
|
|
217
|
+
compactHint: truncateToWidth(this.options.theme.fg("dim", hint), safeWidth, ""),
|
|
218
|
+
priorityRows: priorities,
|
|
219
|
+
focusedRow: selectedContentIndex,
|
|
220
|
+
});
|
|
221
|
+
const fullFrameRows = context.length + content.length + hintRows.length + 4;
|
|
222
|
+
// Kit's compact frame does not expose public pointer-row metadata. Disable pointer routing there rather than
|
|
223
|
+
// risk opening a different raw note identity; keyboard navigation remains available at every height.
|
|
224
|
+
if (fullFrameRows <= maxRows) {
|
|
225
|
+
const contentFrameStart = context.length + 3;
|
|
226
|
+
this.mouseLayout = {
|
|
227
|
+
width: safeWidth,
|
|
228
|
+
...(this.searchEnabled ? { inputFrameRow: contentFrameStart } : {}),
|
|
229
|
+
noteByFrameRow: new Map(
|
|
230
|
+
visible.map((_, index) => [contentFrameStart + listStart + index, this.scrollOffset + index]),
|
|
231
|
+
),
|
|
232
|
+
};
|
|
233
|
+
} else this.mouseLayout = undefined;
|
|
234
|
+
return frame;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
handleInput(data: string): void {
|
|
238
|
+
if (this.disposed || this.completed) return;
|
|
239
|
+
this.routeInput(data);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
243
|
+
if (this.disposed || this.completed || !this.mouseLayout || event.width !== this.mouseLayout.width) {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
if (event.y === this.mouseLayout.inputFrameRow) {
|
|
247
|
+
const labelWidth = visibleWidth("Search: ");
|
|
248
|
+
const inputWidth = Math.max(1, event.width - labelWidth);
|
|
249
|
+
if (event.x < labelWidth || event.x >= labelWidth + inputWidth) return undefined;
|
|
250
|
+
return this.searchInput.handleMouse({
|
|
251
|
+
...event,
|
|
252
|
+
x: event.x - labelWidth,
|
|
253
|
+
y: 0,
|
|
254
|
+
width: inputWidth,
|
|
255
|
+
height: 1,
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
const mappedIndex = this.mouseLayout.noteByFrameRow.get(event.y);
|
|
259
|
+
if (mappedIndex === undefined) return undefined;
|
|
260
|
+
const noteIndex = event.type === "click" ? (this.mousePressedIndex ?? mappedIndex) : mappedIndex;
|
|
261
|
+
if (noteIndex < 0 || noteIndex >= this.filteredNotes.length) return undefined;
|
|
262
|
+
if (event.type === "wheel" && event.wheelDelta) {
|
|
263
|
+
const next = Math.max(
|
|
264
|
+
0,
|
|
265
|
+
Math.min(this.filteredNotes.length - 1, this.selectedIndex() + (event.wheelDelta < 0 ? -1 : 1)),
|
|
266
|
+
);
|
|
267
|
+
const changed = next !== this.selectedIndex();
|
|
268
|
+
if (changed) this.selectAt(next);
|
|
269
|
+
return { handled: true, render: changed };
|
|
270
|
+
}
|
|
271
|
+
if (event.type === "move") return { handled: true };
|
|
272
|
+
if (event.button !== "left") return undefined;
|
|
273
|
+
if (event.type === "press") {
|
|
274
|
+
this.mousePressedIndex = noteIndex;
|
|
275
|
+
const changed = this.selectedIndex() !== noteIndex;
|
|
276
|
+
if (changed) this.selectAt(noteIndex);
|
|
277
|
+
return { handled: true, focus: true, render: changed };
|
|
278
|
+
}
|
|
279
|
+
if (event.type === "click") {
|
|
280
|
+
this.mousePressedIndex = undefined;
|
|
281
|
+
if (this.selectedIndex() !== noteIndex) this.selectAt(noteIndex);
|
|
282
|
+
this.openSelected();
|
|
283
|
+
return { handled: true };
|
|
284
|
+
}
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
invalidate(): void {
|
|
289
|
+
this.mouseLayout = undefined;
|
|
290
|
+
this.searchInput.invalidate();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
dispose(): void {
|
|
294
|
+
this.disposed = true;
|
|
295
|
+
this.clearPasteStartTimer();
|
|
296
|
+
this.pasteStartBuffer = "";
|
|
297
|
+
this.pasteBuffer = undefined;
|
|
298
|
+
this.mousePressedIndex = undefined;
|
|
299
|
+
this.mouseLayout = undefined;
|
|
300
|
+
this.isFocused = false;
|
|
301
|
+
this.searchInput.focused = false;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private renderSearch(width: number): string {
|
|
305
|
+
const label = this.options.theme.fg("muted", "Search: ");
|
|
306
|
+
const inputWidth = Math.max(1, width - visibleWidth(label));
|
|
307
|
+
return truncateToWidth(`${label}${this.searchInput.render(inputWidth)[0] ?? ""}`, width, "");
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private renderNote(note: MarkdownEntry, selected: boolean, width: number): string {
|
|
311
|
+
const prefix = selected ? this.options.theme.fg("accent", "→ ") : " ";
|
|
312
|
+
const description = `${note.size} bytes`;
|
|
313
|
+
const availableLabelWidth = Math.max(1, width - visibleWidth(prefix) - visibleWidth(description) - 2);
|
|
314
|
+
const label = truncateToWidth(sanitizeTerminalText(note.displayPath), availableLabelWidth, "…");
|
|
315
|
+
const spacing = " ".repeat(
|
|
316
|
+
Math.max(1, width - visibleWidth(prefix) - visibleWidth(label) - visibleWidth(description)),
|
|
317
|
+
);
|
|
318
|
+
const line = truncateToWidth(
|
|
319
|
+
`${prefix}${label}${this.options.theme.fg("muted", `${spacing}${description}`)}`,
|
|
320
|
+
width,
|
|
321
|
+
"",
|
|
322
|
+
);
|
|
323
|
+
return selected ? this.options.theme.bold(line) : line;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private interactionHint(): string {
|
|
327
|
+
const hintKeys = resolveNotePickerHintKeys(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
328
|
+
const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
329
|
+
return formatInteractionHints(this.options.keybindings, [
|
|
330
|
+
{ keys: hintKeys.navigation, label: "navigate" },
|
|
331
|
+
{ keys: hintKeys.confirm, label: "open" },
|
|
332
|
+
...(deleteKey ? [{ keys: [deleteKey], label: "delete" }] : []),
|
|
333
|
+
{ keys: hintKeys.back, label: "back" },
|
|
334
|
+
{ keys: ["ctrl+c"], label: "close" },
|
|
335
|
+
]);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private viewportSize(): number {
|
|
339
|
+
const fixedRows = this.searchEnabled ? 9 : 6;
|
|
340
|
+
return Math.max(1, Math.min(MAX_VISIBLE_NOTES, Math.floor(this.options.tui.terminal.rows) - fixedRows));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private query(): string {
|
|
344
|
+
return this.searchEnabled ? this.searchInput.getValue() : "";
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private queryTooLong(): boolean {
|
|
348
|
+
return this.query().length > MAX_SEARCH_QUERY_LENGTH;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private filterNotes(): MarkdownEntry[] {
|
|
352
|
+
const query = this.searchInput.getValue();
|
|
353
|
+
if (!this.searchEnabled || !query.trim()) return [...this.options.notes];
|
|
354
|
+
if (query.length > MAX_SEARCH_QUERY_LENGTH) return [];
|
|
355
|
+
return fuzzyFilter([...this.options.notes], query, ({ displayPath }) => sanitizeTerminalText(displayPath));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private applySearchInput(data: string): void {
|
|
359
|
+
const previousQuery = this.searchInput.getValue();
|
|
360
|
+
this.searchInput.handleInput(data);
|
|
361
|
+
const safeQuery = sanitizeTerminalText(this.searchInput.getValue());
|
|
362
|
+
if (safeQuery !== this.searchInput.getValue()) this.searchInput.setValue(safeQuery);
|
|
363
|
+
if (safeQuery === previousQuery) return;
|
|
364
|
+
const previousSelection = this.selectedPath;
|
|
365
|
+
this.filteredNotes = this.filterNotes();
|
|
366
|
+
const restored = this.filteredNotes.find(({ relativePath }) => relativePath === this.restoreSelectedPath);
|
|
367
|
+
const retained = this.filteredNotes.find(({ relativePath }) => relativePath === previousSelection);
|
|
368
|
+
if (restored) {
|
|
369
|
+
this.selectedPath = restored.relativePath;
|
|
370
|
+
this.restoreSelectedPath = undefined;
|
|
371
|
+
} else if (retained) this.selectedPath = retained.relativePath;
|
|
372
|
+
else {
|
|
373
|
+
if (previousSelection) this.restoreSelectedPath ??= previousSelection;
|
|
374
|
+
this.selectedPath = this.filteredNotes[0]?.relativePath;
|
|
375
|
+
}
|
|
376
|
+
this.scrollOffset = 0;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private routeInput(data: string): void {
|
|
380
|
+
this.clearPasteStartTimer();
|
|
381
|
+
if (this.pasteBuffer !== undefined) {
|
|
382
|
+
this.pasteBuffer += data;
|
|
383
|
+
this.flushPasteBuffer();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const combined = this.pasteStartBuffer + data;
|
|
388
|
+
this.pasteStartBuffer = "";
|
|
389
|
+
const pasteStart = combined.indexOf(BRACKETED_PASTE_START);
|
|
390
|
+
if (pasteStart >= 0) {
|
|
391
|
+
if (pasteStart > 0) this.handleNonPasteInput(combined.slice(0, pasteStart));
|
|
392
|
+
if (this.disposed || this.completed) return;
|
|
393
|
+
this.pasteBuffer = combined.slice(pasteStart + BRACKETED_PASTE_START.length);
|
|
394
|
+
this.flushPasteBuffer();
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const prefixLength = trailingMarkerPrefixLength(combined, BRACKETED_PASTE_START);
|
|
399
|
+
const outsidePaste = combined.slice(0, combined.length - prefixLength);
|
|
400
|
+
if (outsidePaste) this.handleNonPasteInput(outsidePaste);
|
|
401
|
+
if (this.disposed || this.completed) return;
|
|
402
|
+
const prefix = combined.slice(combined.length - prefixLength);
|
|
403
|
+
if (!prefix) return;
|
|
404
|
+
this.pasteStartBuffer = prefix;
|
|
405
|
+
this.pasteStartTimer = setTimeout(() => {
|
|
406
|
+
this.pasteStartTimer = undefined;
|
|
407
|
+
const pending = this.pasteStartBuffer;
|
|
408
|
+
this.pasteStartBuffer = "";
|
|
409
|
+
if (!this.disposed && !this.completed && pending) this.handleNonPasteInput(pending);
|
|
410
|
+
}, INPUT_PREFIX_TIMEOUT_MS);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private flushPasteBuffer(): void {
|
|
414
|
+
if (this.pasteBuffer === undefined) return;
|
|
415
|
+
const pasteEnd = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
|
|
416
|
+
if (pasteEnd < 0) return;
|
|
417
|
+
const pasted = this.pasteBuffer.slice(0, pasteEnd);
|
|
418
|
+
const remaining = this.pasteBuffer.slice(pasteEnd + BRACKETED_PASTE_END.length);
|
|
419
|
+
this.pasteBuffer = undefined;
|
|
420
|
+
if (this.searchEnabled) {
|
|
421
|
+
const safePaste = sanitizePastedSearchText(pasted);
|
|
422
|
+
this.applySearchInput(`${BRACKETED_PASTE_START}${safePaste}${BRACKETED_PASTE_END}`);
|
|
423
|
+
this.options.tui.requestRender();
|
|
424
|
+
}
|
|
425
|
+
if (remaining && !this.disposed && !this.completed) this.routeInput(remaining);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private clearPasteStartTimer(): void {
|
|
429
|
+
if (!this.pasteStartTimer) return;
|
|
430
|
+
clearTimeout(this.pasteStartTimer);
|
|
431
|
+
this.pasteStartTimer = undefined;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private handleNonPasteInput(data: string): void {
|
|
435
|
+
if (this.disposed || this.completed) return;
|
|
436
|
+
this.mousePressedIndex = undefined;
|
|
437
|
+
this.mouseLayout = undefined;
|
|
438
|
+
if (matchesKey(data, Key.ctrl("c"))) {
|
|
439
|
+
this.finish({ kind: "close", ...this.pickerState() });
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (matchesKey(data, Key.escape) || this.options.keybindings.matches(data, "tui.select.cancel")) {
|
|
443
|
+
this.finish({ kind: "back", ...this.pickerState() });
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (this.options.keybindings.matches(data, "tui.select.up")) this.move(-1);
|
|
447
|
+
else if (this.options.keybindings.matches(data, "tui.select.down")) this.move(1);
|
|
448
|
+
else if (this.options.keybindings.matches(data, "tui.select.pageUp")) this.move(-this.viewportSize(), false);
|
|
449
|
+
else if (this.options.keybindings.matches(data, "tui.select.pageDown")) this.move(this.viewportSize(), false);
|
|
450
|
+
else if (!this.searchEnabled && matchesKey(data, Key.home)) this.selectAt(0);
|
|
451
|
+
else if (!this.searchEnabled && matchesKey(data, Key.end)) this.selectAt(this.filteredNotes.length - 1);
|
|
452
|
+
else if (this.options.keybindings.matches(data, "tui.select.confirm")) this.openSelected();
|
|
453
|
+
else {
|
|
454
|
+
const deleteKey = resolveNoteDeleteKey(this.options.keybindings, this.searchEnabled, this.options.tui.terminal);
|
|
455
|
+
if (deleteKey && matchesKey(data, deleteKey)) this.deleteSelected();
|
|
456
|
+
else if (this.searchEnabled) {
|
|
457
|
+
const safeInput = sanitizeInsertableSearchInput(data, this.options.keybindings);
|
|
458
|
+
if (safeInput !== undefined) this.applySearchInput(safeInput);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (!this.completed) this.options.tui.requestRender();
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private selectedIndex(): number {
|
|
465
|
+
return Math.max(
|
|
466
|
+
0,
|
|
467
|
+
this.filteredNotes.findIndex(({ relativePath }) => relativePath === this.selectedPath),
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private move(delta: number, wrap = true): void {
|
|
472
|
+
if (this.filteredNotes.length === 0) return;
|
|
473
|
+
const current = this.selectedIndex();
|
|
474
|
+
const next = wrap
|
|
475
|
+
? (current + delta + this.filteredNotes.length) % this.filteredNotes.length
|
|
476
|
+
: Math.max(0, Math.min(this.filteredNotes.length - 1, current + delta));
|
|
477
|
+
this.selectAt(next);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
private selectAt(index: number): void {
|
|
481
|
+
if (this.filteredNotes.length === 0) return;
|
|
482
|
+
const bounded = Math.max(0, Math.min(this.filteredNotes.length - 1, index));
|
|
483
|
+
this.selectedPath = this.filteredNotes[bounded]?.relativePath;
|
|
484
|
+
this.restoreSelectedPath = undefined;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
private keepSelectionVisible(height: number): void {
|
|
488
|
+
if (this.filteredNotes.length === 0) {
|
|
489
|
+
this.scrollOffset = 0;
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
const index = this.selectedIndex();
|
|
493
|
+
if (index < this.scrollOffset) this.scrollOffset = index;
|
|
494
|
+
if (index >= this.scrollOffset + height) this.scrollOffset = index - height + 1;
|
|
495
|
+
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, this.filteredNotes.length - height));
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
private openSelected(): void {
|
|
499
|
+
if (!this.selectedPath) return;
|
|
500
|
+
this.finish({ kind: "open", notePath: this.selectedPath, query: this.query() });
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private deleteSelected(): void {
|
|
504
|
+
if (!this.selectedPath) return;
|
|
505
|
+
const selectedIndex = this.selectedIndex();
|
|
506
|
+
const nextSelectedPath =
|
|
507
|
+
this.filteredNotes[selectedIndex + 1]?.relativePath ?? this.filteredNotes[selectedIndex - 1]?.relativePath;
|
|
508
|
+
this.finish({
|
|
509
|
+
kind: "delete",
|
|
510
|
+
notePath: this.selectedPath,
|
|
511
|
+
...(nextSelectedPath ? { nextSelectedPath } : {}),
|
|
512
|
+
query: this.query(),
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private pickerState(): { selectedPath?: string; query?: string } {
|
|
517
|
+
return {
|
|
518
|
+
...(this.selectedPath ? { selectedPath: this.selectedPath } : {}),
|
|
519
|
+
...(this.searchEnabled ? { query: this.query() } : {}),
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private finish(result: NotePickerResult): void {
|
|
524
|
+
if (this.completed) return;
|
|
525
|
+
this.completed = true;
|
|
526
|
+
this.clearPasteStartTimer();
|
|
527
|
+
this.pasteStartBuffer = "";
|
|
528
|
+
this.pasteBuffer = undefined;
|
|
529
|
+
this.options.complete(result);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function sanitizePastedSearchText(value: string): string {
|
|
534
|
+
const singleLine = value
|
|
535
|
+
.replace(/\r\n/gu, "")
|
|
536
|
+
.replace(/[\r\n]/gu, "")
|
|
537
|
+
.replace(/\t/gu, " ");
|
|
538
|
+
return sanitizeTerminalText(singleLine);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function sanitizeInsertableSearchInput(
|
|
542
|
+
data: string,
|
|
543
|
+
keybindings: Pick<KeybindingsManager, "matches">,
|
|
544
|
+
): string | undefined {
|
|
545
|
+
if (data === "\n" || SEARCH_INPUT_BINDINGS.some((binding) => keybindings.matches(data, binding))) return data;
|
|
546
|
+
const printable = decodeKittyPrintable(data) ?? decodeModifyOtherKeysPrintable(data);
|
|
547
|
+
if (printable !== undefined) return sanitizeTerminalText(printable) || undefined;
|
|
548
|
+
const hasControlCharacters = [...data].some((character) => {
|
|
549
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
550
|
+
return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f);
|
|
551
|
+
});
|
|
552
|
+
if (hasControlCharacters) return data;
|
|
553
|
+
return sanitizeTerminalText(data) || undefined;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function decodeModifyOtherKeysPrintable(data: string): string | undefined {
|
|
557
|
+
// Pi exposes the Kitty decoder from its root; mirror Editor's xterm modifyOtherKeys fallback.
|
|
558
|
+
const prefix = "\u001b[27;";
|
|
559
|
+
if (!data.startsWith(prefix)) return undefined;
|
|
560
|
+
const match = data.slice(prefix.length).match(/^(\d+);(\d+)~$/u);
|
|
561
|
+
if (!match) return undefined;
|
|
562
|
+
const modifier = (Number.parseInt(match[1] ?? "", 10) - 1) & ~(64 | 128);
|
|
563
|
+
const codePoint = Number.parseInt(match[2] ?? "", 10);
|
|
564
|
+
if ((modifier & ~1) !== 0 || !Number.isFinite(codePoint) || codePoint < 32) return undefined;
|
|
565
|
+
try {
|
|
566
|
+
return String.fromCodePoint(codePoint);
|
|
567
|
+
} catch {
|
|
568
|
+
return undefined;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function initializeSearchInput(input: Input, value: string): void {
|
|
573
|
+
input.setValue(value);
|
|
574
|
+
// Input.setValue() preserves its cursor, so use its public mouse contract to place a fresh cursor at the end.
|
|
575
|
+
const x = visibleWidth(value) + 2;
|
|
576
|
+
input.handleMouse({
|
|
577
|
+
type: "press",
|
|
578
|
+
button: "left",
|
|
579
|
+
x,
|
|
580
|
+
y: 0,
|
|
581
|
+
screenX: x,
|
|
582
|
+
screenY: 0,
|
|
583
|
+
width: x + 1,
|
|
584
|
+
height: 1,
|
|
585
|
+
shift: false,
|
|
586
|
+
alt: false,
|
|
587
|
+
ctrl: false,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function resolveNotePickerHintKeys(
|
|
592
|
+
keybindings: Pick<KeybindingsManager, "getKeys">,
|
|
593
|
+
searchEnabled: boolean,
|
|
594
|
+
terminal?: KeyboardProtocolTerminal,
|
|
595
|
+
): NotePickerHintKeys {
|
|
596
|
+
const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
|
|
597
|
+
const claimed = ["ctrl+c"];
|
|
598
|
+
const claim = (candidates: readonly unknown[]): KeyId[] => {
|
|
599
|
+
const available: KeyId[] = [];
|
|
600
|
+
for (const candidate of candidates) {
|
|
601
|
+
const normalized = normalizeKey(candidate);
|
|
602
|
+
if (!normalized || !keyRoutesAsSingleInput(normalized, disambiguatedKeyProtocol)) continue;
|
|
603
|
+
if (claimed.some((other) => keysOverlap(normalized, other, disambiguatedKeyProtocol))) continue;
|
|
604
|
+
claimed.push(normalized);
|
|
605
|
+
available.push(normalized as KeyId);
|
|
606
|
+
}
|
|
607
|
+
return available;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
// Match handleNonPasteInput() branch order so every displayed key reaches its labeled action.
|
|
611
|
+
const back = claim([...keybindings.getKeys("tui.select.cancel"), "escape"]);
|
|
612
|
+
const up = claim(keybindings.getKeys("tui.select.up"));
|
|
613
|
+
const down = claim(keybindings.getKeys("tui.select.down"));
|
|
614
|
+
claim(keybindings.getKeys("tui.select.pageUp"));
|
|
615
|
+
claim(keybindings.getKeys("tui.select.pageDown"));
|
|
616
|
+
if (!searchEnabled) {
|
|
617
|
+
claim(["home"]);
|
|
618
|
+
claim(["end"]);
|
|
619
|
+
}
|
|
620
|
+
const confirm = claim(keybindings.getKeys("tui.select.confirm"));
|
|
621
|
+
return { navigation: [...up, ...down], confirm, back };
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Resolve the first effective delete binding that remains reachable in this picker. */
|
|
625
|
+
export function resolveNoteDeleteKey(
|
|
626
|
+
keybindings: Pick<KeybindingsManager, "getKeys">,
|
|
627
|
+
searchEnabled: boolean,
|
|
628
|
+
terminal?: KeyboardProtocolTerminal,
|
|
629
|
+
): KeyId | undefined {
|
|
630
|
+
const activeBindings = [...PICKER_BINDINGS, ...(searchEnabled ? SEARCH_INPUT_BINDINGS : [])];
|
|
631
|
+
const disambiguatedKeyProtocol = usesDisambiguatedKeyProtocol(terminal);
|
|
632
|
+
const reserved = [
|
|
633
|
+
"ctrl+c",
|
|
634
|
+
"escape",
|
|
635
|
+
...(!searchEnabled ? ["home", "end"] : []),
|
|
636
|
+
...(searchEnabled && !disambiguatedKeyProtocol ? ["ctrl+j"] : []),
|
|
637
|
+
...activeBindings.flatMap((binding) => {
|
|
638
|
+
if (binding === "tui.editor.deleteCharForward") {
|
|
639
|
+
return keybindings.getKeys(binding).filter((key) => normalizeKey(key) !== "ctrl+d");
|
|
640
|
+
}
|
|
641
|
+
return keybindings.getKeys(binding);
|
|
642
|
+
}),
|
|
643
|
+
];
|
|
644
|
+
for (const candidate of keybindings.getKeys("app.session.delete")) {
|
|
645
|
+
const normalized = normalizeKey(candidate);
|
|
646
|
+
if (!normalized || (searchEnabled && isTextKey(normalized))) continue;
|
|
647
|
+
if (disambiguatedKeyProtocol) {
|
|
648
|
+
if (reserved.some((other) => normalizeKey(other) === normalized)) continue;
|
|
649
|
+
return normalized as KeyId;
|
|
650
|
+
}
|
|
651
|
+
const inputs = inputsFor(normalized);
|
|
652
|
+
if (inputs.length === 0 || inputs.some((input) => !routesAsSingleNonPasteInput(input))) continue;
|
|
653
|
+
if (reserved.some((other) => inputs.some((input) => matchesKey(input, other as KeyId)))) continue;
|
|
654
|
+
return normalized as KeyId;
|
|
655
|
+
}
|
|
656
|
+
return undefined;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function normalizeKey(value: unknown): string | undefined {
|
|
660
|
+
// Retain the picker's existing admission and protocol-lookup spelling. Kit
|
|
661
|
+
// also accepts literal '+', which this picker has never admitted.
|
|
662
|
+
if (typeof value !== "string" || value.length > 80 || value.endsWith("+")) return undefined;
|
|
663
|
+
const canonical = canonicalizeConfiguredKey(value);
|
|
664
|
+
if (!canonical) return undefined;
|
|
665
|
+
const parts = canonical.toLowerCase().split("+");
|
|
666
|
+
const base = parts.pop();
|
|
667
|
+
return [...MODIFIERS.filter((modifier) => parts.includes(modifier)), base].join("+");
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function inputsFor(key: string): string[] {
|
|
671
|
+
const parts = key.split("+");
|
|
672
|
+
const base = parts.pop() ?? "";
|
|
673
|
+
const modifier = MODIFIERS.reduce((mask, part, bit) => mask | (parts.includes(part) ? 1 << bit : 0), 0);
|
|
674
|
+
const code = SPECIAL_CODEPOINTS[base] ?? (base.length === 1 ? base.charCodeAt(0) : undefined);
|
|
675
|
+
const inputs = code === undefined ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\u001b[${code};${modifier + 1}u`];
|
|
676
|
+
return inputs.filter((input) => matchesKey(input, key as KeyId));
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function usesDisambiguatedKeyProtocol(terminal?: KeyboardProtocolTerminal): boolean {
|
|
680
|
+
return isKittyProtocolActive() || terminal?.kittyProtocolActive === true || terminal?.modifyOtherKeysActive === true;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function keysOverlap(first: string, second: string, disambiguatedKeyProtocol: boolean): boolean {
|
|
684
|
+
if (disambiguatedKeyProtocol) return first === second;
|
|
685
|
+
return inputsFor(first).some((input) => matchesKey(input, second as KeyId));
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function keyRoutesAsSingleInput(key: string, disambiguatedKeyProtocol: boolean): boolean {
|
|
689
|
+
if (disambiguatedKeyProtocol) return true;
|
|
690
|
+
const inputs = inputsFor(key);
|
|
691
|
+
return inputs.length > 0 && inputs.every(routesAsSingleNonPasteInput);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function routesAsSingleNonPasteInput(input: string): boolean {
|
|
695
|
+
if (input.includes(BRACKETED_PASTE_START)) return false;
|
|
696
|
+
const prefixLength = trailingMarkerPrefixLength(input, BRACKETED_PASTE_START);
|
|
697
|
+
return prefixLength === 0 || prefixLength === input.length;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function trailingMarkerPrefixLength(value: string, marker: string): number {
|
|
701
|
+
const maximum = Math.min(value.length, marker.length - 1);
|
|
702
|
+
for (let length = maximum; length > 0; length -= 1) {
|
|
703
|
+
if (value.endsWith(marker.slice(0, length))) return length;
|
|
704
|
+
}
|
|
705
|
+
return 0;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function isTextKey(key: string): boolean {
|
|
709
|
+
const parts = key.split("+");
|
|
710
|
+
const base = parts.at(-1) ?? "";
|
|
711
|
+
return (base.length === 1 || base === "space") && !parts.some((part) => ["ctrl", "alt", "super"].includes(part));
|
|
712
|
+
}
|
package/src/storage.ts
CHANGED
|
@@ -104,6 +104,32 @@ export class NotesStorage {
|
|
|
104
104
|
return (await resolveExistingMarkdown(this.paths.notes, relativePath, "Note", signal)).absolutePath;
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
async deleteNote(relativePath: string, expectedRevision: string, signal?: AbortSignal): Promise<void> {
|
|
108
|
+
const normalized = normalizeExistingMarkdownPath(relativePath);
|
|
109
|
+
const root = await canonicalDirectory(this.paths.notes, signal);
|
|
110
|
+
const target = resolve(root, ...normalized.split("/"));
|
|
111
|
+
assertContained(root, target);
|
|
112
|
+
await withFileMutationQueue(root, async () => {
|
|
113
|
+
throwIfAborted(signal);
|
|
114
|
+
const resolved = await resolveExistingMarkdown(root, normalized, "Note", signal);
|
|
115
|
+
const current = await readBoundedMarkdown(resolved.absolutePath, "Note", signal);
|
|
116
|
+
if (revisionFor(current) !== expectedRevision) {
|
|
117
|
+
throw new Error("Note revision is stale; read the current note before deleting it");
|
|
118
|
+
}
|
|
119
|
+
throwIfAborted(signal);
|
|
120
|
+
const latest = await resolveExistingMarkdown(root, normalized, "Note", signal);
|
|
121
|
+
if (latest.absolutePath !== resolved.absolutePath) {
|
|
122
|
+
throw new Error("Note path changed before deletion; read it again");
|
|
123
|
+
}
|
|
124
|
+
const latestContent = await readBoundedMarkdown(latest.absolutePath, "Note", signal);
|
|
125
|
+
if (revisionFor(latestContent) !== expectedRevision) {
|
|
126
|
+
throw new Error("Note changed before deletion; read it again");
|
|
127
|
+
}
|
|
128
|
+
throwIfAborted(signal);
|
|
129
|
+
await unlink(latest.absolutePath);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
107
133
|
async readTemplate(relativePath: string, signal?: AbortSignal): Promise<TemplateSnapshot> {
|
|
108
134
|
const resolved = await resolveExistingMarkdown(this.paths.templates, relativePath, "Template", signal);
|
|
109
135
|
const content = await readBoundedMarkdown(resolved.absolutePath, "Template", signal);
|