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