@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/src/menu.ts CHANGED
@@ -1,28 +1,30 @@
1
1
  import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
- import { type MenuDefinition, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
3
- import type { DiscoveryResult, MarkdownEntry, NotesStorage } from "./storage.js";
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" | "templates" | "path";
11
- type NotesAction = "chooseNote" | "chooseTemplate" | "createNote";
11
+ type NotesScreen = "notes" | "templates" | "pastePath" | "manageTemplates";
12
+ type NotesAction = "chooseRoute" | "chooseTemplate" | "pastePath" | "editTemplate";
12
13
 
13
- export interface NotesManagerResult {
14
- kind: "open" | "closed";
15
- notePath?: string;
16
- }
14
+ export type NotesManagerResult =
15
+ | { kind: "open"; notePath: string }
16
+ | { kind: "pastePath"; notePath: string }
17
+ | { kind: "editTemplate"; templatePath: string }
18
+ | { kind: "closed" };
17
19
 
18
- export function createNotesMenu(storage: NotesStorage) {
19
- let selectedTemplate: string | undefined;
20
- let selectedNote: string | undefined;
20
+ export function createNotesMenu(storage: NotesStorage, ownership: { isCurrent?: () => boolean } = {}) {
21
+ let result: Exclude<NotesManagerResult, { kind: "closed" }> | undefined;
21
22
 
22
23
  const getState = async ({ signal }: { signal: AbortSignal }): Promise<NotesMenuState> => {
23
24
  const notes = await storage.discoverNotes(signal);
24
25
  if (signal.aborted) throw signal.reason;
25
26
  const templates = await storage.discoverTemplates(signal);
27
+ if (signal.aborted) throw signal.reason;
26
28
  return { notes, templates };
27
29
  };
28
30
 
@@ -34,21 +36,32 @@ export function createNotesMenu(storage: NotesStorage) {
34
36
  title: `Pi Notes · ${state.notes.entries.length} note${state.notes.entries.length === 1 ? "" : "s"}`,
35
37
  lines: discoveryLines(state.notes, "note"),
36
38
  items: [
39
+ {
40
+ id: "open",
41
+ label: "Open a note…",
42
+ description: "Choose an existing Markdown note.",
43
+ searchText: "open browse existing note",
44
+ },
37
45
  {
38
46
  id: "create",
39
47
  label: "Create a note…",
40
- description: "Start blank or copy a user template.",
41
- searchText: "new create blank template",
48
+ description: "Open an automatically named blank note or user template.",
49
+ searchText: "new create blank template automatic filename",
50
+ },
51
+ {
52
+ id: "paste-path",
53
+ label: "Paste a note path…",
54
+ description: "Insert a note's absolute path into the parent editor.",
55
+ searchText: "paste insert absolute path",
56
+ },
57
+ {
58
+ id: "manage-templates",
59
+ label: "Manage templates…",
60
+ description: "Edit existing Markdown templates.",
61
+ searchText: "manage edit templates",
42
62
  },
43
- ...state.notes.entries.map((note, index) => ({
44
- id: `note:${index}`,
45
- label: note.displayPath,
46
- description: `${note.size} bytes`,
47
- searchText: note.displayPath,
48
- })),
49
63
  ],
50
- action: "chooseNote",
51
- enableSearch: state.notes.entries.length > 8,
64
+ action: "chooseRoute",
52
65
  viewportSize: 12,
53
66
  hint: "close",
54
67
  }),
@@ -74,43 +87,75 @@ export function createNotesMenu(storage: NotesStorage) {
74
87
  viewportSize: 12,
75
88
  hint: "back",
76
89
  }),
77
- path: () => ({
78
- kind: "input",
79
- title: "New note path",
80
- lines: [
81
- "Enter a relative Markdown path below pi-notes/notes.",
82
- selectedTemplate ? `Template: ${sanitizeTerminalText(selectedTemplate)}` : "Template: Blank",
83
- ],
84
- placeholder: "topic.md or folder/topic.md",
85
- action: "createNote",
90
+ pastePath: ({ state }) => ({
91
+ kind: "choice",
92
+ title: "Paste a note path",
93
+ lines: discoveryLines(state.notes, "note"),
94
+ items: state.notes.entries.map((note, index) => ({
95
+ id: `paste:${index}`,
96
+ label: note.displayPath,
97
+ description: `${note.size} bytes`,
98
+ searchText: note.displayPath,
99
+ })),
100
+ action: "pastePath",
101
+ enableSearch: state.notes.entries.length > 8,
102
+ viewportSize: 12,
103
+ hint: "back",
104
+ }),
105
+ manageTemplates: ({ state }) => ({
106
+ kind: "choice",
107
+ title: "Manage templates",
108
+ lines: discoveryLines(state.templates, "template"),
109
+ items: state.templates.entries.map((template, index) => ({
110
+ id: `manage-template:${index}`,
111
+ label: template.displayPath,
112
+ description: `${template.size} bytes`,
113
+ searchText: template.displayPath,
114
+ })),
115
+ action: "editTemplate",
116
+ enableSearch: state.templates.entries.length > 8,
117
+ viewportSize: 12,
86
118
  hint: "back",
87
119
  }),
88
120
  },
89
121
  actions: {
90
- chooseNote: ({ state, itemId }) => {
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
+ }
91
131
  if (itemId === "create") return { kind: "to", screen: "templates" };
92
- const note = indexedEntry(state.notes.entries, itemId, "note:");
132
+ if (itemId === "paste-path") return { kind: "to", screen: "pastePath" };
133
+ if (itemId === "manage-templates") return { kind: "to", screen: "manageTemplates" };
134
+ return { kind: "rejected", error: new Error("The selected notes action is no longer available") };
135
+ },
136
+ chooseTemplate: async ({ state, itemId, signal }) => {
137
+ const templatePath =
138
+ itemId === "blank" ? undefined : indexedEntry(state.templates.entries, itemId, "template:")?.relativePath;
139
+ if (itemId !== "blank" && !templatePath) {
140
+ return { kind: "rejected", error: new Error("The selected template is no longer available") };
141
+ }
142
+ const note = await storage.createAutomaticNote({ ...(templatePath ? { templatePath } : {}), signal });
143
+ if (signal.aborted) return { kind: "close" };
144
+ result = { kind: "open", notePath: note.relativePath };
145
+ return { kind: "close" };
146
+ },
147
+ pastePath: ({ state, itemId }) => {
148
+ const note = indexedEntry(state.notes.entries, itemId, "paste:");
93
149
  if (!note) return { kind: "rejected", error: new Error("The selected note is no longer available") };
94
- selectedNote = note.relativePath;
150
+ result = { kind: "pastePath", notePath: note.relativePath };
95
151
  return { kind: "close" };
96
152
  },
97
- chooseTemplate: ({ state, itemId }) => {
98
- if (itemId === "blank") {
99
- selectedTemplate = undefined;
100
- return { kind: "to", screen: "path" };
101
- }
102
- const template = indexedEntry(state.templates.entries, itemId, "template:");
153
+ editTemplate: ({ state, itemId }) => {
154
+ const template = indexedEntry(state.templates.entries, itemId, "manage-template:");
103
155
  if (!template) {
104
156
  return { kind: "rejected", error: new Error("The selected template is no longer available") };
105
157
  }
106
- selectedTemplate = template.relativePath;
107
- return { kind: "to", screen: "path" };
108
- },
109
- createNote: async ({ value, signal }) => {
110
- if (typeof value !== "string") return { kind: "rejected", error: new Error("Note path is required") };
111
- const note = await storage.createNote(value, { templatePath: selectedTemplate, signal });
112
- if (signal.aborted) return { kind: "close" };
113
- selectedNote = note.relativePath;
158
+ result = { kind: "editTemplate", templatePath: template.relativePath };
114
159
  return { kind: "close" };
115
160
  },
116
161
  },
@@ -119,7 +164,7 @@ export function createNotesMenu(storage: NotesStorage) {
119
164
  return {
120
165
  menu,
121
166
  getState,
122
- getSelectedNote: () => selectedNote,
167
+ getResult: () => result,
123
168
  };
124
169
  }
125
170
 
@@ -128,7 +173,7 @@ export async function showNotesManager(
128
173
  storage: NotesStorage,
129
174
  ownership: { signal: AbortSignal; isCurrent(): boolean },
130
175
  ): Promise<NotesManagerResult> {
131
- const controller = createNotesMenu(storage);
176
+ const controller = createNotesMenu(storage, ownership);
132
177
  const result = await runMenu(ctx, controller.menu, {
133
178
  getState: controller.getState,
134
179
  signal: ownership.signal,
@@ -140,10 +185,124 @@ export async function showNotesManager(
140
185
  },
141
186
  });
142
187
  if (result.kind === "error") throw result.error;
143
- const selected = controller.getSelectedNote();
144
- return selected && ownership.isCurrent() && !ownership.signal.aborted
145
- ? { kind: "open", notePath: selected }
146
- : { kind: "closed" };
188
+ const selected = controller.getResult();
189
+ return selected && ownership.isCurrent() && !ownership.signal.aborted ? selected : { kind: "closed" };
190
+ }
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}"`;
147
306
  }
148
307
 
149
308
  function indexedEntry(entries: readonly MarkdownEntry[], itemId: string, prefix: string): MarkdownEntry | undefined {