@narumitw/pi-ticker 0.1.0 → 0.1.2

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/render.ts CHANGED
@@ -3,161 +3,154 @@ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works
3
3
  import type { Quote } from "./quotes.js";
4
4
 
5
5
  export interface TickerItem {
6
- symbol: string;
7
- quote?: Quote;
8
- error?: string;
9
- stale?: boolean;
6
+ symbol: string;
7
+ quote?: Quote;
8
+ error?: string;
9
+ stale?: boolean;
10
10
  }
11
11
 
12
12
  export interface TickerView {
13
- items: TickerItem[];
14
- loading: boolean;
15
- updatedAt?: number;
13
+ items: TickerItem[];
14
+ loading: boolean;
15
+ updatedAt?: number;
16
16
  }
17
17
 
18
18
  export function renderTickerWidget(view: TickerView, theme: Theme, width: number): string[] {
19
- const renderWidth = Math.max(0, width);
20
- if (renderWidth === 0) return [""];
21
- const heading = renderHeading(view, theme);
22
- const separator = theme.fg("dim", " │ ");
23
- const quotes = packItems(
24
- view.items.map((item) => renderItem(item, theme)),
25
- separator,
26
- renderWidth,
27
- );
28
- return [
29
- theme.fg("borderMuted", "─".repeat(renderWidth)),
30
- ...fitLines(heading, renderWidth),
31
- ...quotes,
32
- ];
19
+ const renderWidth = Math.max(0, width);
20
+ if (renderWidth === 0) return [""];
21
+ const heading = renderHeading(view, theme);
22
+ const separator = theme.fg("dim", " │ ");
23
+ const quotes = packItems(
24
+ view.items.map((item) => renderItem(item, theme)),
25
+ separator,
26
+ renderWidth,
27
+ );
28
+ return [theme.fg("borderMuted", "─".repeat(renderWidth)), ...fitLines(heading, renderWidth), ...quotes];
33
29
  }
34
30
 
35
31
  export function formatTickerPlain(view: TickerView): string[] {
36
- const status = view.loading
37
- ? "Stocks · updating"
38
- : view.updatedAt
39
- ? `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`
40
- : "Stocks";
41
- return [status, ...view.items.map(formatItemPlain)];
32
+ const status = view.loading
33
+ ? "Stocks · updating"
34
+ : view.updatedAt
35
+ ? `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`
36
+ : "Stocks";
37
+ return [status, ...view.items.map(formatItemPlain)];
42
38
  }
43
39
 
44
40
  export function mergeQuoteResults(
45
- current: readonly TickerItem[],
46
- results: ReadonlyArray<{ symbol: string; quote?: Quote; error?: string }>,
41
+ current: readonly TickerItem[],
42
+ results: ReadonlyArray<{ symbol: string; quote?: Quote; error?: string }>,
47
43
  ): TickerItem[] {
48
- const previous = new Map(current.map((item) => [item.symbol, item]));
49
- return results.map((result) => {
50
- if (result.quote) return { symbol: result.symbol, quote: result.quote };
51
- const existing = previous.get(result.symbol);
52
- return existing?.quote
53
- ? { symbol: result.symbol, quote: existing.quote, error: result.error, stale: true }
54
- : { symbol: result.symbol, error: result.error };
55
- });
44
+ const previous = new Map(current.map((item) => [item.symbol, item]));
45
+ return results.map((result) => {
46
+ if (result.quote) return { symbol: result.symbol, quote: result.quote };
47
+ const existing = previous.get(result.symbol);
48
+ return existing?.quote
49
+ ? { symbol: result.symbol, quote: existing.quote, error: result.error, stale: true }
50
+ : { symbol: result.symbol, error: result.error };
51
+ });
56
52
  }
57
53
 
58
54
  function renderHeading(view: TickerView, theme: Theme): string {
59
- if (view.loading) return theme.fg("muted", "Stocks · updating…");
60
- if (view.updatedAt) {
61
- return theme.fg("muted", `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`);
62
- }
63
- return theme.fg("muted", "Stocks");
55
+ if (view.loading) return theme.fg("muted", "Stocks · updating…");
56
+ if (view.updatedAt) {
57
+ return theme.fg("muted", `Stocks · updated ${new Date(view.updatedAt).toLocaleTimeString()}`);
58
+ }
59
+ return theme.fg("muted", "Stocks");
64
60
  }
65
61
 
66
62
  function renderItem(item: TickerItem, theme: Theme): string {
67
- const symbol = theme.fg("accent", theme.bold(item.symbol));
68
- if (!item.quote) return `${symbol} ${theme.fg("error", "unavailable")}`;
69
- const changeRole = item.quote.change >= 0 ? "success" : "error";
70
- const content = `${symbol} ${theme.fg("text", formatPrice(item.quote))} ${theme.fg(
71
- changeRole,
72
- formatChange(item.quote),
73
- )}`;
74
- return item.stale ? `${content} ${theme.fg("warning", "stale")}` : content;
63
+ const symbol = theme.fg("accent", theme.bold(item.symbol));
64
+ if (!item.quote) return `${symbol} ${theme.fg("error", "unavailable")}`;
65
+ const changeRole = item.quote.change >= 0 ? "success" : "error";
66
+ const content = `${symbol} ${theme.fg("text", formatPrice(item.quote))} ${theme.fg(
67
+ changeRole,
68
+ formatChange(item.quote),
69
+ )}`;
70
+ return item.stale ? `${content} ${theme.fg("warning", "stale")}` : content;
75
71
  }
76
72
 
77
73
  function formatItemPlain(item: TickerItem): string {
78
- if (!item.quote) return `${item.symbol} unavailable`;
79
- const content = `${item.symbol} ${formatPrice(item.quote)} ${formatChange(item.quote)}`;
80
- return item.stale ? `${content} stale` : content;
74
+ if (!item.quote) return `${item.symbol} unavailable`;
75
+ const content = `${item.symbol} ${formatPrice(item.quote)} ${formatChange(item.quote)}`;
76
+ return item.stale ? `${content} stale` : content;
81
77
  }
82
78
 
83
79
  function formatPrice(quote: Quote): string {
84
- const value = formatMarketNumber(quote.price);
85
- if (quote.currency === "GBp") return `${value}p`;
86
- return `${currencyPrefix(quote.currency)}${value}`;
80
+ const value = formatMarketNumber(quote.price);
81
+ if (quote.currency === "GBp") return `${value}p`;
82
+ return `${currencyPrefix(quote.currency)}${value}`;
87
83
  }
88
84
 
89
85
  function formatChange(quote: Quote): string {
90
- const sign = quote.change >= 0 ? "+" : "";
91
- return `${sign}${formatMarketNumber(quote.change)} (${sign}${quote.changePercent.toFixed(2)}%)`;
86
+ const sign = quote.change >= 0 ? "+" : "";
87
+ return `${sign}${formatMarketNumber(quote.change)} (${sign}${quote.changePercent.toFixed(2)}%)`;
92
88
  }
93
89
 
94
90
  function formatMarketNumber(value: number): string {
95
- const absolute = Math.abs(value);
96
- if (absolute === 0) return "0.00";
97
- const magnitude = Math.floor(Math.log10(absolute));
98
- const significantDecimals = 6 - magnitude - 1;
99
- const formatted =
100
- significantDecimals > 8
101
- ? value.toPrecision(6)
102
- : value.toFixed(Math.max(2, significantDecimals));
103
- return trimNumericZeros(formatted);
91
+ const absolute = Math.abs(value);
92
+ if (absolute === 0) return "0.00";
93
+ const magnitude = Math.floor(Math.log10(absolute));
94
+ const significantDecimals = 6 - magnitude - 1;
95
+ const formatted = significantDecimals > 8 ? value.toPrecision(6) : value.toFixed(Math.max(2, significantDecimals));
96
+ return trimNumericZeros(formatted);
104
97
  }
105
98
 
106
99
  function trimNumericZeros(value: string): string {
107
- const [coefficient, exponent] = value.split("e");
108
- const [integer = value, fraction = ""] = coefficient?.split(".") ?? [value, ""];
109
- let trimmedFraction = fraction;
110
- const minimumFractionDigits = exponent === undefined ? 2 : 0;
111
- while (trimmedFraction.length > minimumFractionDigits && trimmedFraction.endsWith("0")) {
112
- trimmedFraction = trimmedFraction.slice(0, -1);
113
- }
114
- const trimmed = trimmedFraction ? `${integer}.${trimmedFraction}` : integer;
115
- return exponent === undefined ? trimmed : `${trimmed}e${exponent}`;
100
+ const [coefficient, exponent] = value.split("e");
101
+ const [integer = value, fraction = ""] = coefficient?.split(".") ?? [value, ""];
102
+ let trimmedFraction = fraction;
103
+ const minimumFractionDigits = exponent === undefined ? 2 : 0;
104
+ while (trimmedFraction.length > minimumFractionDigits && trimmedFraction.endsWith("0")) {
105
+ trimmedFraction = trimmedFraction.slice(0, -1);
106
+ }
107
+ const trimmed = trimmedFraction ? `${integer}.${trimmedFraction}` : integer;
108
+ return exponent === undefined ? trimmed : `${trimmed}e${exponent}`;
116
109
  }
117
110
 
118
111
  function currencyPrefix(currency: string | undefined): string {
119
- switch (currency) {
120
- case "USD":
121
- return "$";
122
- case "EUR":
123
- return "€";
124
- case "GBP":
125
- return "£";
126
- case "JPY":
127
- return "¥";
128
- case "CAD":
129
- return "C$";
130
- case "HKD":
131
- return "HK$";
132
- case "TWD":
133
- return "NT$";
134
- default:
135
- return currency ? `${currency} ` : "";
136
- }
112
+ switch (currency) {
113
+ case "USD":
114
+ return "$";
115
+ case "EUR":
116
+ return "€";
117
+ case "GBP":
118
+ return "£";
119
+ case "JPY":
120
+ return "¥";
121
+ case "CAD":
122
+ return "C$";
123
+ case "HKD":
124
+ return "HK$";
125
+ case "TWD":
126
+ return "NT$";
127
+ default:
128
+ return currency ? `${currency} ` : "";
129
+ }
137
130
  }
138
131
 
139
132
  function packItems(items: readonly string[], separator: string, width: number): string[] {
140
- const rows: string[] = [];
141
- let current = "";
142
- for (const item of items) {
143
- if (visibleWidth(item) > width) {
144
- if (current) rows.push(current);
145
- rows.push(...fitLines(item, width));
146
- current = "";
147
- continue;
148
- }
149
- const candidate = current ? `${current}${separator}${item}` : item;
150
- if (visibleWidth(candidate) <= width) {
151
- current = candidate;
152
- continue;
153
- }
154
- rows.push(current);
155
- current = item;
156
- }
157
- if (current) rows.push(current);
158
- return rows;
133
+ const rows: string[] = [];
134
+ let current = "";
135
+ for (const item of items) {
136
+ if (visibleWidth(item) > width) {
137
+ if (current) rows.push(current);
138
+ rows.push(...fitLines(item, width));
139
+ current = "";
140
+ continue;
141
+ }
142
+ const candidate = current ? `${current}${separator}${item}` : item;
143
+ if (visibleWidth(candidate) <= width) {
144
+ current = candidate;
145
+ continue;
146
+ }
147
+ rows.push(current);
148
+ current = item;
149
+ }
150
+ if (current) rows.push(current);
151
+ return rows;
159
152
  }
160
153
 
161
154
  function fitLines(content: string, width: number): string[] {
162
- return wrapTextWithAnsi(content, width).map((line) => truncateToWidth(line, width, ""));
155
+ return wrapTextWithAnsi(content, width).map((line) => truncateToWidth(line, width, ""));
163
156
  }
package/src/settings.ts CHANGED
@@ -5,168 +5,162 @@ export const MAX_SYMBOLS = 10;
5
5
  export const DEFAULT_WIDGET_ENABLED = true;
6
6
 
7
7
  export interface StockTickerSettings {
8
- symbols: string[];
9
- widgetEnabled: boolean;
8
+ symbols: string[];
9
+ widgetEnabled: boolean;
10
10
  }
11
11
 
12
12
  export interface LoadedSettings {
13
- settings: StockTickerSettings;
14
- warning?: string;
13
+ settings: StockTickerSettings;
14
+ warning?: string;
15
15
  }
16
16
 
17
17
  export interface SettingsWriter {
18
- save(path: string, symbols: readonly string[]): Promise<void>;
19
- saveWidgetEnabled(path: string, widgetEnabled: boolean): Promise<void>;
20
- flush(): Promise<void>;
18
+ save(path: string, symbols: readonly string[]): Promise<void>;
19
+ saveWidgetEnabled(path: string, widgetEnabled: boolean): Promise<void>;
20
+ flush(): Promise<void>;
21
21
  }
22
22
 
23
23
  const SYMBOL_PATTERN = /^[A-Z0-9.^=-]{1,15}$/;
24
24
 
25
25
  export function parseSymbols(values: Iterable<string>): string[] {
26
- return normalizeSymbols(values, false);
26
+ return normalizeSymbols(values, false);
27
27
  }
28
28
 
29
29
  export function normalizeSymbols(values: Iterable<string>, allowEmpty: boolean): string[] {
30
- const symbols = [...values]
31
- .flatMap((value) => value.split(/[\s,]+/))
32
- .map((value) => value.trim().toUpperCase())
33
- .filter(Boolean);
34
- const unique = [...new Set(symbols)];
35
- if (!allowEmpty && unique.length === 0) throw new Error("Provide at least one stock symbol.");
36
- if (unique.length > MAX_SYMBOLS) {
37
- throw new Error(`At most ${MAX_SYMBOLS} stock symbols are supported.`);
38
- }
39
- const invalid = unique.find((symbol) => !SYMBOL_PATTERN.test(symbol));
40
- if (invalid) throw new Error(`Invalid stock symbol: ${invalid}`);
41
- return unique;
30
+ const symbols = [...values]
31
+ .flatMap((value) => value.split(/[\s,]+/))
32
+ .map((value) => value.trim().toUpperCase())
33
+ .filter(Boolean);
34
+ const unique = [...new Set(symbols)];
35
+ if (!allowEmpty && unique.length === 0) throw new Error("Provide at least one stock symbol.");
36
+ if (unique.length > MAX_SYMBOLS) {
37
+ throw new Error(`At most ${MAX_SYMBOLS} stock symbols are supported.`);
38
+ }
39
+ const invalid = unique.find((symbol) => !SYMBOL_PATTERN.test(symbol));
40
+ if (invalid) throw new Error(`Invalid stock symbol: ${invalid}`);
41
+ return unique;
42
42
  }
43
43
 
44
44
  export async function loadSettings(path: string): Promise<LoadedSettings> {
45
- let text: string;
46
- try {
47
- text = await readFile(path, "utf8");
48
- } catch (error) {
49
- if (isMissingFile(error)) return { settings: defaultSettings() };
50
- return {
51
- settings: defaultSettings(),
52
- warning: `Could not read ${path}; using default ticker settings.`,
53
- };
54
- }
55
-
56
- try {
57
- const document = parseDocument(text);
58
- const symbols = document.symbols === undefined ? [] : parseSymbolSetting(document.symbols);
59
- const widgetEnabled =
60
- document.widgetEnabled === undefined
61
- ? DEFAULT_WIDGET_ENABLED
62
- : parseWidgetEnabled(document.widgetEnabled);
63
- return { settings: { symbols, widgetEnabled } };
64
- } catch (error) {
65
- return {
66
- settings: defaultSettings(),
67
- warning: `${errorMessage(error)} Using default ticker settings without changing ${path}.`,
68
- };
69
- }
45
+ let text: string;
46
+ try {
47
+ text = await readFile(path, "utf8");
48
+ } catch (error) {
49
+ if (isMissingFile(error)) return { settings: defaultSettings() };
50
+ return {
51
+ settings: defaultSettings(),
52
+ warning: `Could not read ${path}; using default ticker settings.`,
53
+ };
54
+ }
55
+
56
+ try {
57
+ const document = parseDocument(text);
58
+ const symbols = document.symbols === undefined ? [] : parseSymbolSetting(document.symbols);
59
+ const widgetEnabled =
60
+ document.widgetEnabled === undefined ? DEFAULT_WIDGET_ENABLED : parseWidgetEnabled(document.widgetEnabled);
61
+ return { settings: { symbols, widgetEnabled } };
62
+ } catch (error) {
63
+ return {
64
+ settings: defaultSettings(),
65
+ warning: `${errorMessage(error)} Using default ticker settings without changing ${path}.`,
66
+ };
67
+ }
70
68
  }
71
69
 
72
70
  export async function saveSymbols(path: string, symbols: readonly string[]): Promise<void> {
73
- await saveSettingsPatch(path, { symbols: normalizeSymbols(symbols, true) });
71
+ await saveSettingsPatch(path, { symbols: normalizeSymbols(symbols, true) });
74
72
  }
75
73
 
76
74
  export async function saveWidgetEnabled(path: string, widgetEnabled: boolean): Promise<void> {
77
- await saveSettingsPatch(path, { widgetEnabled: parseWidgetEnabled(widgetEnabled) });
75
+ await saveSettingsPatch(path, { widgetEnabled: parseWidgetEnabled(widgetEnabled) });
78
76
  }
79
77
 
80
78
  export function createSettingsWriter(): SettingsWriter {
81
- let queue = Promise.resolve();
82
- const enqueue = (operation: () => Promise<void>) => {
83
- const running = queue.catch(() => undefined).then(operation);
84
- queue = running.then(
85
- () => undefined,
86
- () => undefined,
87
- );
88
- return running;
89
- };
90
- return {
91
- save: (path, symbols) => enqueue(() => saveSymbols(path, symbols)),
92
- saveWidgetEnabled: (path, widgetEnabled) =>
93
- enqueue(() => saveWidgetEnabled(path, widgetEnabled)),
94
- flush: () => queue,
95
- };
79
+ let queue = Promise.resolve();
80
+ const enqueue = (operation: () => Promise<void>) => {
81
+ const running = queue.catch(() => undefined).then(operation);
82
+ queue = running.then(
83
+ () => undefined,
84
+ () => undefined,
85
+ );
86
+ return running;
87
+ };
88
+ return {
89
+ save: (path, symbols) => enqueue(() => saveSymbols(path, symbols)),
90
+ saveWidgetEnabled: (path, widgetEnabled) => enqueue(() => saveWidgetEnabled(path, widgetEnabled)),
91
+ flush: () => queue,
92
+ };
96
93
  }
97
94
 
98
95
  async function saveSettingsPatch(path: string, patch: Partial<StockTickerSettings>): Promise<void> {
99
- let document: Record<string, unknown> = {};
100
- try {
101
- const text = await readFile(path, "utf8");
102
- document = parseDocument(text);
103
- validateKnownSettings(document);
104
- } catch (error) {
105
- if (!isMissingFile(error)) throw error;
106
- }
107
-
108
- const next = `${JSON.stringify({ ...document, ...patch }, null, 2)}\n`;
109
- const directory = dirname(path);
110
- await mkdir(directory, { recursive: true });
111
- const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
112
- try {
113
- await writeFile(temporaryPath, next, { encoding: "utf8", flag: "wx", mode: 0o600 });
114
- await rename(temporaryPath, path);
115
- } catch (error) {
116
- await unlink(temporaryPath).catch(() => undefined);
117
- throw error;
118
- }
96
+ let document: Record<string, unknown> = {};
97
+ try {
98
+ const text = await readFile(path, "utf8");
99
+ document = parseDocument(text);
100
+ validateKnownSettings(document);
101
+ } catch (error) {
102
+ if (!isMissingFile(error)) throw error;
103
+ }
104
+
105
+ const next = `${JSON.stringify({ ...document, ...patch }, null, 2)}\n`;
106
+ const directory = dirname(path);
107
+ await mkdir(directory, { recursive: true });
108
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${Date.now()}.tmp`);
109
+ try {
110
+ await writeFile(temporaryPath, next, { encoding: "utf8", flag: "wx", mode: 0o600 });
111
+ await rename(temporaryPath, path);
112
+ } catch (error) {
113
+ await unlink(temporaryPath).catch(() => undefined);
114
+ throw error;
115
+ }
119
116
  }
120
117
 
121
118
  function defaultSettings(): StockTickerSettings {
122
- return { symbols: [], widgetEnabled: DEFAULT_WIDGET_ENABLED };
119
+ return { symbols: [], widgetEnabled: DEFAULT_WIDGET_ENABLED };
123
120
  }
124
121
 
125
122
  function parseDocument(text: string): Record<string, unknown> {
126
- let value: unknown;
127
- try {
128
- value = JSON.parse(text);
129
- } catch {
130
- throw new Error("Stock ticker settings must contain valid JSON.");
131
- }
132
- if (!value || typeof value !== "object" || Array.isArray(value)) {
133
- throw new Error("Stock ticker settings must be a JSON object.");
134
- }
135
- return value as Record<string, unknown>;
123
+ let value: unknown;
124
+ try {
125
+ value = JSON.parse(text);
126
+ } catch {
127
+ throw new Error("Stock ticker settings must contain valid JSON.");
128
+ }
129
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
130
+ throw new Error("Stock ticker settings must be a JSON object.");
131
+ }
132
+ return value as Record<string, unknown>;
136
133
  }
137
134
 
138
135
  function validateKnownSettings(document: Record<string, unknown>): void {
139
- if (document.symbols !== undefined) parseSymbolSetting(document.symbols);
140
- if (document.widgetEnabled !== undefined) parseWidgetEnabled(document.widgetEnabled);
136
+ if (document.symbols !== undefined) parseSymbolSetting(document.symbols);
137
+ if (document.widgetEnabled !== undefined) parseWidgetEnabled(document.widgetEnabled);
141
138
  }
142
139
 
143
140
  function parseSymbolSetting(value: unknown): string[] {
144
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
145
- throw new Error("The stock ticker symbols setting must be an array of strings.");
146
- }
147
- return normalizeSymbols(value as string[], true);
141
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
142
+ throw new Error("The stock ticker symbols setting must be an array of strings.");
143
+ }
144
+ return normalizeSymbols(value as string[], true);
148
145
  }
149
146
 
150
147
  function parseWidgetEnabled(value: unknown): boolean {
151
- if (typeof value !== "boolean") {
152
- throw new Error("The stock ticker widgetEnabled setting must be a boolean.");
153
- }
154
- return value;
148
+ if (typeof value !== "boolean") {
149
+ throw new Error("The stock ticker widgetEnabled setting must be a boolean.");
150
+ }
151
+ return value;
155
152
  }
156
153
 
157
154
  function isMissingFile(error: unknown): boolean {
158
- return hasErrorCode(error, "ENOENT");
155
+ return hasErrorCode(error, "ENOENT");
159
156
  }
160
157
 
161
158
  function hasErrorCode(error: unknown, code: string): boolean {
162
- return (
163
- typeof error === "object" &&
164
- error !== null &&
165
- "code" in error &&
166
- (error as NodeJS.ErrnoException).code === code
167
- );
159
+ return (
160
+ typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === code
161
+ );
168
162
  }
169
163
 
170
164
  function errorMessage(error: unknown): string {
171
- return error instanceof Error ? error.message : String(error);
165
+ return error instanceof Error ? error.message : String(error);
172
166
  }