@narumitw/pi-ticker 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,499 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { fuzzyFilter, Input, Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import type { TickerMenuOptions } from "./menu.js";
4
+ import { parseSymbols } from "./settings.js";
5
+
6
+ type TuiMenuResult = "add" | "close";
7
+ type TickerRow = { kind: "ticker"; id: string; symbol: string };
8
+ type ActionRow = {
9
+ kind: "action";
10
+ id: "add" | "widget" | "refresh";
11
+ label: string;
12
+ description: string;
13
+ };
14
+ type Row = TickerRow | ActionRow;
15
+
16
+ const PASTE_START = "\u001b[200~";
17
+ const PASTE_END = "\u001b[201~";
18
+ // Keep these aligned with Input.handleInput so configured editing actions beat additive reorder.
19
+ const RESERVED_INPUT_BINDINGS = [
20
+ "tui.select.up",
21
+ "tui.select.down",
22
+ "tui.select.pageUp",
23
+ "tui.select.pageDown",
24
+ "tui.select.confirm",
25
+ "tui.select.cancel",
26
+ "tui.editor.undo",
27
+ "tui.input.submit",
28
+ "tui.editor.deleteCharBackward",
29
+ "tui.editor.deleteCharForward",
30
+ "tui.editor.deleteWordBackward",
31
+ "tui.editor.deleteWordForward",
32
+ "tui.editor.deleteToLineStart",
33
+ "tui.editor.deleteToLineEnd",
34
+ "tui.editor.yank",
35
+ "tui.editor.yankPop",
36
+ "tui.editor.cursorLeft",
37
+ "tui.editor.cursorRight",
38
+ "tui.editor.cursorLineStart",
39
+ "tui.editor.cursorLineEnd",
40
+ "tui.editor.cursorWordLeft",
41
+ "tui.editor.cursorWordRight",
42
+ ] as const;
43
+
44
+ // Pi TUI Kit multi-select screens do not expose in-place row-reorder shortcuts.
45
+ // This specialized TUI keeps the same search, toggle, action, binding, and cancellation behavior
46
+ // while RPC mode continues to use the Kit's declarative adapter in menu.ts.
47
+ export async function showTickerTuiMenu(
48
+ ctx: ExtensionCommandContext,
49
+ options: TickerMenuOptions,
50
+ ): Promise<void> {
51
+ const { formatInteractionHints, HorizontalRule, runCustomInteraction, sanitizeTerminalText } =
52
+ await import("@narumitw/pi-tui-kit");
53
+
54
+ while (!options.signal.aborted && options.isCurrent()) {
55
+ const result = await runCustomInteraction<TuiMenuResult>(ctx, {
56
+ signal: options.signal,
57
+ isCurrent: options.isCurrent,
58
+ onError: (errorCtx, error) => {
59
+ if (!errorCtx.hasUI) return;
60
+ const message = error instanceof Error ? error.message : String(error);
61
+ errorCtx.ui.notify(sanitizeTerminalText(message), "error");
62
+ },
63
+ create: ({ tui, theme, keybindings, complete }) => {
64
+ let symbols = [...options.getSymbols()];
65
+ let widgetEnabled = options.getWidgetEnabled();
66
+ const rawSearchInput = new Input();
67
+ const searchInput = new Input();
68
+ let selectedIndex = 0;
69
+ let rows: Row[] = [];
70
+ let busy = false;
71
+ let disposed = false;
72
+ let pasteActive = false;
73
+ let errorMessage: string | undefined;
74
+ let pending = Promise.resolve();
75
+ const shortcutUp = shortcutAvailable(keybindings, "shift+up");
76
+ const shortcutDown = shortcutAvailable(keybindings, "shift+down");
77
+ const activationHint = (label: string) =>
78
+ formatInteractionHints(keybindings, [
79
+ { bindings: ["tui.select.confirm"], keys: ["space"], label },
80
+ ]);
81
+ const reorderKeys = [shortcutUp, shortcutDown].filter(
82
+ (shortcut): shortcut is "shift+up" | "shift+down" => shortcut !== undefined,
83
+ );
84
+ const tickerDescription = `${[
85
+ activationHint("removes this ticker"),
86
+ ...(reorderKeys.length > 0 ? [`${reorderKeys.join("/")} changes its order`] : []),
87
+ ].join("; ")}.`;
88
+ const topRule = new HorizontalRule({
89
+ label: "Manage tickers",
90
+ labelAlignment: "left",
91
+ ruleStyle: (text) => theme.fg("borderMuted", text),
92
+ labelStyle: (text) => theme.fg("accent", text),
93
+ });
94
+ const bottomRule = new HorizontalRule({
95
+ ruleStyle: (text) => theme.fg("borderMuted", text),
96
+ });
97
+ const hint = formatInteractionHints(keybindings, [
98
+ { bindings: ["tui.select.up", "tui.select.down"], label: "select" },
99
+ ...(shortcutUp ? [{ keys: [shortcutUp], label: "move up" }] : []),
100
+ ...(shortcutDown ? [{ keys: [shortcutDown], label: "move down" }] : []),
101
+ { bindings: ["tui.select.confirm"], keys: ["space"], label: "toggle/select" },
102
+ {
103
+ bindings: ["tui.select.cancel"],
104
+ excludeKeys: ["ctrl+c"],
105
+ label: "close",
106
+ },
107
+ { keys: ["ctrl+c"], label: "close" },
108
+ ]);
109
+
110
+ const actionRows = (directSymbol?: string): ActionRow[] => [
111
+ {
112
+ kind: "action",
113
+ id: "add",
114
+ label: directSymbol
115
+ ? `Add ${sanitizeTerminalText(directSymbol)}`
116
+ : "Add custom ticker…",
117
+ description: directSymbol
118
+ ? `${activationHint(`adds ${sanitizeTerminalText(directSymbol)} directly`)}.`
119
+ : "Add and select one Yahoo Finance symbol.",
120
+ },
121
+ {
122
+ kind: "action",
123
+ id: "widget",
124
+ label: `Widget: ${widgetEnabled ? "On" : "Off"}`,
125
+ description: "Show or hide the editor widget and persist this setting.",
126
+ },
127
+ {
128
+ kind: "action",
129
+ id: "refresh",
130
+ label: "Refresh now",
131
+ description: widgetEnabled
132
+ ? "Fetch the selected symbols immediately."
133
+ : "Enable the widget before refreshing.",
134
+ },
135
+ ];
136
+ const buildRows = (): Row[] => {
137
+ const tickerRows = symbols.map(
138
+ (symbol): TickerRow => ({ kind: "ticker", id: symbol, symbol }),
139
+ );
140
+ const query = searchInput.getValue().toLowerCase();
141
+ const filtered = fuzzyFilter(tickerRows, query, (row) =>
142
+ sanitizeTerminalText(row.symbol.replaceAll("-", " ")).toLowerCase(),
143
+ );
144
+ const directSymbol =
145
+ filtered.length === 0 ? tryDirectSymbol(rawSearchInput.getValue()) : undefined;
146
+ return [...filtered, ...actionRows(directSymbol)];
147
+ };
148
+ const selectedRow = () => rows[selectedIndex];
149
+ const rebuild = (preferredId?: string, fallbackIndex = selectedIndex) => {
150
+ rows = buildRows();
151
+ const preferredIndex = preferredId ? rows.findIndex((row) => row.id === preferredId) : -1;
152
+ selectedIndex =
153
+ preferredIndex >= 0
154
+ ? preferredIndex
155
+ : Math.max(0, Math.min(fallbackIndex, rows.length - 1));
156
+ tui.requestRender();
157
+ };
158
+ rebuild();
159
+
160
+ const select = (index: number, wrap: boolean) => {
161
+ if (rows.length === 0) return;
162
+ selectedIndex = wrap
163
+ ? (index + rows.length) % rows.length
164
+ : Math.max(0, Math.min(index, rows.length - 1));
165
+ tui.requestRender();
166
+ };
167
+ const persist = (
168
+ nextSymbols: readonly string[],
169
+ previousSymbols: readonly string[],
170
+ preferredId: string | undefined,
171
+ previousIndex: number,
172
+ clearSearchOnSuccess = false,
173
+ ) => {
174
+ busy = true;
175
+ errorMessage = undefined;
176
+ symbols = [...nextSymbols];
177
+ rebuild(preferredId, previousIndex);
178
+ pending = (async () => {
179
+ try {
180
+ await options.applySymbols(symbols, options.signal);
181
+ if (options.signal.aborted || !options.isCurrent()) return;
182
+ symbols = [...options.getSymbols()];
183
+ if (clearSearchOnSuccess) {
184
+ rawSearchInput.setValue("");
185
+ searchInput.setValue("");
186
+ }
187
+ } catch (error) {
188
+ if (options.signal.aborted || !options.isCurrent()) return;
189
+ symbols = [...previousSymbols];
190
+ errorMessage = sanitizeTerminalText(
191
+ error instanceof Error ? error.message : String(error),
192
+ );
193
+ ctx.ui.notify(`Ticker settings were not saved: ${errorMessage}`, "error");
194
+ } finally {
195
+ busy = false;
196
+ if (!disposed && !options.signal.aborted && options.isCurrent()) {
197
+ rebuild(preferredId, previousIndex);
198
+ }
199
+ }
200
+ })();
201
+ };
202
+ const persistWidgetEnabled = (nextWidgetEnabled: boolean) => {
203
+ const previousWidgetEnabled = widgetEnabled;
204
+ widgetEnabled = nextWidgetEnabled;
205
+ busy = true;
206
+ errorMessage = undefined;
207
+ rebuild("widget");
208
+ pending = (async () => {
209
+ try {
210
+ await options.applyWidgetEnabled(nextWidgetEnabled, options.signal);
211
+ if (options.signal.aborted || !options.isCurrent()) return;
212
+ widgetEnabled = options.getWidgetEnabled();
213
+ } catch (error) {
214
+ if (options.signal.aborted || !options.isCurrent()) return;
215
+ widgetEnabled = previousWidgetEnabled;
216
+ errorMessage = sanitizeTerminalText(
217
+ error instanceof Error ? error.message : String(error),
218
+ );
219
+ ctx.ui.notify(`Ticker settings were not saved: ${errorMessage}`, "error");
220
+ } finally {
221
+ busy = false;
222
+ if (!disposed && !options.signal.aborted && options.isCurrent()) rebuild("widget");
223
+ }
224
+ })();
225
+ };
226
+ const toggle = () => {
227
+ if (busy || disposed) return;
228
+ const row = selectedRow();
229
+ if (row?.kind !== "ticker") return;
230
+ const previous = [...symbols];
231
+ const next = symbols.filter((symbol) => symbol !== row.symbol);
232
+ persist(next, previous, undefined, selectedIndex);
233
+ };
234
+ const moveTicker = (direction: -1 | 1) => {
235
+ if (
236
+ busy ||
237
+ disposed ||
238
+ rawSearchInput.getValue() ||
239
+ options.signal.aborted ||
240
+ !options.isCurrent()
241
+ ) {
242
+ return;
243
+ }
244
+ const row = selectedRow();
245
+ if (row?.kind !== "ticker") return;
246
+ const from = symbols.indexOf(row.symbol);
247
+ const to = from + direction;
248
+ if (from < 0 || to < 0 || to >= symbols.length) return;
249
+ const previous = [...symbols];
250
+ const next = [...symbols];
251
+ const [symbol] = next.splice(from, 1);
252
+ if (!symbol) return;
253
+ next.splice(to, 0, symbol);
254
+ persist(next, previous, symbol, selectedIndex);
255
+ };
256
+ const activate = () => {
257
+ if (busy || disposed) return;
258
+ const row = selectedRow();
259
+ if (!row) return;
260
+ if (row.kind === "ticker") {
261
+ toggle();
262
+ return;
263
+ }
264
+ if (row.id === "add") {
265
+ const query = rawSearchInput.getValue();
266
+ const hasTickerMatch = rows.some((candidate) => candidate.kind === "ticker");
267
+ if (query.trim() && !hasTickerMatch) {
268
+ let symbol: string;
269
+ try {
270
+ symbol = parseDirectSymbol(query);
271
+ } catch (error) {
272
+ const message = error instanceof Error ? error.message : String(error);
273
+ errorMessage = sanitizeTerminalText(message);
274
+ ctx.ui.notify(errorMessage, "error");
275
+ tui.requestRender();
276
+ return;
277
+ }
278
+ if (symbols.includes(symbol)) {
279
+ ctx.ui.notify(`${symbol} is already selected.`, "info");
280
+ return;
281
+ }
282
+ persist([...symbols, symbol], [...symbols], symbol, selectedIndex, true);
283
+ return;
284
+ }
285
+ complete("add");
286
+ } else if (row.id === "widget") persistWidgetEnabled(!widgetEnabled);
287
+ else options.refresh();
288
+ };
289
+ const handleSearch = (data: string) => {
290
+ const previousId = selectedRow()?.id;
291
+ errorMessage = undefined;
292
+ rawSearchInput.handleInput(data);
293
+ searchInput.handleInput(data);
294
+ searchInput.setValue(sanitizeTerminalText(rawSearchInput.getValue()));
295
+ rebuild(previousId, 0);
296
+ };
297
+
298
+ return {
299
+ render(width: number) {
300
+ const safeWidth = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
301
+ if (safeWidth === 0) return [""];
302
+ const viewportSize = availableRows(tui.terminal.rows, rows.length);
303
+ const viewportStart = Math.max(
304
+ 0,
305
+ Math.min(selectedIndex - Math.floor(viewportSize / 2), rows.length - viewportSize),
306
+ );
307
+ const visibleRows = rows.slice(viewportStart, viewportStart + viewportSize);
308
+ const content = visibleRows.map((row, offset) => {
309
+ const index = viewportStart + offset;
310
+ const focused = index === selectedIndex;
311
+ const label =
312
+ row.kind === "ticker"
313
+ ? `${focused ? "›" : " "} [x] ${sanitizeTerminalText(row.symbol)}`
314
+ : `${focused ? "›" : " "} ${row.label}`;
315
+ const bounded = truncateToWidth(label, safeWidth, safeWidth > 1 ? "…" : "");
316
+ return focused ? theme.fg("accent", bounded) : bounded;
317
+ });
318
+ if (viewportSize < rows.length) {
319
+ content.push(
320
+ theme.fg(
321
+ "dim",
322
+ truncateToWidth(` (${selectedIndex + 1}/${rows.length})`, safeWidth, ""),
323
+ ),
324
+ );
325
+ }
326
+ const row = selectedRow();
327
+ const description =
328
+ row?.kind === "ticker"
329
+ ? rawSearchInput.getValue()
330
+ ? "Clear search before reordering."
331
+ : tickerDescription
332
+ : row?.description;
333
+ const status = errorMessage
334
+ ? theme.fg("error", errorMessage)
335
+ : busy
336
+ ? theme.fg("muted", "Saving changes…")
337
+ : undefined;
338
+ return [
339
+ ...topRule.render(safeWidth),
340
+ theme.fg(
341
+ "muted",
342
+ truncateToWidth(
343
+ `${symbols.length} selected · changes save immediately`,
344
+ safeWidth,
345
+ "",
346
+ ),
347
+ ),
348
+ ...searchInput.render(safeWidth).map((line) => truncateToWidth(line, safeWidth, "")),
349
+ ...content,
350
+ ...(description
351
+ ? [theme.fg("dim", truncateToWidth(` ${description}`, safeWidth, ""))]
352
+ : []),
353
+ ...(status ? [truncateToWidth(status, safeWidth, "")] : []),
354
+ ...bottomRule.render(safeWidth),
355
+ theme.fg("dim", truncateToWidth(hint, safeWidth, "")),
356
+ ];
357
+ },
358
+ invalidate() {
359
+ searchInput.invalidate();
360
+ },
361
+ handleInput(data: string) {
362
+ if (pasteActive || data.includes(PASTE_START)) {
363
+ pasteActive = !data.includes(PASTE_END);
364
+ handleSearch(data);
365
+ return;
366
+ }
367
+ if (matchesKey(data, Key.ctrl("c"))) {
368
+ complete("close");
369
+ return;
370
+ }
371
+ if (keybindings.matches(data, "tui.select.cancel")) {
372
+ complete("close");
373
+ return;
374
+ }
375
+ if (keybindings.matches(data, "tui.select.up")) {
376
+ select(selectedIndex - 1, true);
377
+ return;
378
+ }
379
+ if (keybindings.matches(data, "tui.select.down")) {
380
+ select(selectedIndex + 1, true);
381
+ return;
382
+ }
383
+ if (keybindings.matches(data, "tui.select.pageUp")) {
384
+ select(selectedIndex - availableRows(tui.terminal.rows, rows.length), false);
385
+ return;
386
+ }
387
+ if (keybindings.matches(data, "tui.select.pageDown")) {
388
+ select(selectedIndex + availableRows(tui.terminal.rows, rows.length), false);
389
+ return;
390
+ }
391
+ if (keybindings.matches(data, "tui.select.confirm") || data === " ") {
392
+ activate();
393
+ return;
394
+ }
395
+ if (shortcutUp && matchesKey(data, shortcutUp)) {
396
+ moveTicker(-1);
397
+ return;
398
+ }
399
+ if (shortcutDown && matchesKey(data, shortcutDown)) {
400
+ moveTicker(1);
401
+ return;
402
+ }
403
+ handleSearch(data);
404
+ },
405
+ async waitForPending() {
406
+ await pending;
407
+ },
408
+ dispose() {
409
+ disposed = true;
410
+ },
411
+ get focused() {
412
+ return searchInput.focused;
413
+ },
414
+ set focused(value: boolean) {
415
+ searchInput.focused = value;
416
+ },
417
+ };
418
+ },
419
+ });
420
+
421
+ if (result.kind !== "completed" || result.value === "close") return;
422
+ const entered = await ctx.ui.input(
423
+ "Add custom ticker",
424
+ "Yahoo symbol, for example MSFT or SOL-USD",
425
+ { signal: options.signal },
426
+ );
427
+ if (options.signal.aborted || !options.isCurrent()) return;
428
+ if (!entered?.trim()) continue;
429
+ try {
430
+ const parsed = parseSymbols([entered]);
431
+ if (parsed.length !== 1) throw new Error("Enter exactly one Yahoo Finance symbol.");
432
+ const symbol = parsed[0];
433
+ if (!symbol) continue;
434
+ const current = options.getSymbols();
435
+ if (current.includes(symbol)) {
436
+ ctx.ui.notify(`${symbol} is already selected.`, "info");
437
+ continue;
438
+ }
439
+ await options.applySymbols([...current, symbol], options.signal);
440
+ if (options.signal.aborted || !options.isCurrent()) return;
441
+ } catch (error) {
442
+ if (options.signal.aborted || !options.isCurrent()) return;
443
+ const message = error instanceof Error ? error.message : String(error);
444
+ ctx.ui.notify(sanitizeTerminalText(message), "error");
445
+ }
446
+ }
447
+ }
448
+
449
+ function parseDirectSymbol(value: string): string {
450
+ const parsed = parseSymbols([value]);
451
+ if (parsed.length !== 1) throw new Error("Enter exactly one Yahoo Finance symbol.");
452
+ const symbol = parsed[0];
453
+ if (!symbol) throw new Error("Enter one Yahoo Finance symbol.");
454
+ return symbol;
455
+ }
456
+
457
+ function tryDirectSymbol(value: string): string | undefined {
458
+ if (!value.trim()) return undefined;
459
+ try {
460
+ return parseDirectSymbol(value);
461
+ } catch {
462
+ return undefined;
463
+ }
464
+ }
465
+
466
+ function availableRows(terminalRows: number, rowCount: number): number {
467
+ const boundedRows = Number.isFinite(terminalRows)
468
+ ? Math.max(1, Math.floor(terminalRows) - 9)
469
+ : 10;
470
+ return Math.max(1, Math.min(rowCount, boundedRows, 12));
471
+ }
472
+
473
+ function shortcutAvailable(
474
+ keybindings: {
475
+ getKeys(binding: string): readonly string[];
476
+ },
477
+ shortcut: "shift+up" | "shift+down",
478
+ ): typeof shortcut | undefined {
479
+ const unavailable = new Set(
480
+ [
481
+ "ctrl+c",
482
+ "home",
483
+ "end",
484
+ "space",
485
+ ...RESERVED_INPUT_BINDINGS.flatMap((binding) => keybindings.getKeys(binding)),
486
+ ].map(canonicalKey),
487
+ );
488
+ return unavailable.has(canonicalKey(shortcut)) ? undefined : shortcut;
489
+ }
490
+
491
+ function canonicalKey(value: string): string {
492
+ const parts = value.toLowerCase().split("+");
493
+ const base = parts.at(-1) ?? "";
494
+ const canonicalBase = base === "escape" ? "esc" : base === "return" ? "enter" : base;
495
+ const modifiers = ["ctrl", "shift", "alt", "super"].filter((modifier) =>
496
+ parts.includes(modifier),
497
+ );
498
+ return [...modifiers, canonicalBase].join("+");
499
+ }