@operad-io/tui 0.0.0-stage → 0.1.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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +27 -4
  4. package/src/actions.ts +997 -0
  5. package/src/app.ts +1665 -0
  6. package/src/args.ts +198 -0
  7. package/src/autostart.ts +302 -0
  8. package/src/client.ts +478 -0
  9. package/src/discover.ts +90 -0
  10. package/src/events.ts +345 -0
  11. package/src/index.ts +11 -0
  12. package/src/layout.ts +260 -0
  13. package/src/live.ts +113 -0
  14. package/src/markdown.ts +85 -0
  15. package/src/recent.ts +40 -0
  16. package/src/sanitize.ts +18 -0
  17. package/src/state.ts +3200 -0
  18. package/src/theme.ts +525 -0
  19. package/src/themes.ts +60 -0
  20. package/src/view/index.ts +1204 -0
  21. package/src/wrap.ts +156 -0
  22. package/theme.schema.json +197 -0
  23. package/themes/LICENSE-catppuccin +21 -0
  24. package/themes/LICENSE-dracula +21 -0
  25. package/themes/LICENSE-github +21 -0
  26. package/themes/LICENSE-kanagawa +21 -0
  27. package/themes/LICENSE-nord +21 -0
  28. package/themes/LICENSE-one +20 -0
  29. package/themes/LICENSE-rose-pine +21 -0
  30. package/themes/LICENSE-solarized +20 -0
  31. package/themes/LICENSE-tokyo-night +22 -0
  32. package/themes/README.md +81 -0
  33. package/themes/catppuccin-frappe.json +19 -0
  34. package/themes/catppuccin-latte.json +19 -0
  35. package/themes/catppuccin-macchiato.json +19 -0
  36. package/themes/catppuccin-mocha.json +19 -0
  37. package/themes/dracula.json +19 -0
  38. package/themes/github-dark.json +19 -0
  39. package/themes/github-light.json +19 -0
  40. package/themes/kanagawa-dragon.json +19 -0
  41. package/themes/kanagawa-lotus.json +19 -0
  42. package/themes/kanagawa-wave.json +19 -0
  43. package/themes/nord.json +19 -0
  44. package/themes/one-dark.json +19 -0
  45. package/themes/one-light.json +19 -0
  46. package/themes/rose-pine-dawn.json +19 -0
  47. package/themes/rose-pine-main.json +19 -0
  48. package/themes/solarized-dark.json +19 -0
  49. package/themes/solarized-light.json +19 -0
  50. package/themes/tokyo-night-day.json +19 -0
  51. package/themes/tokyo-night-night.json +19 -0
  52. package/tui.schema.json +24 -0
package/src/theme.ts ADDED
@@ -0,0 +1,525 @@
1
+ /**
2
+ * The TUI's colours. Every colour the TUI draws is a token of one `TuiPalette`;
3
+ * this module is the only place that names a colour value. A colour is a string:
4
+ * a hex triplet, `ansi:<0-15>` (the terminal's own colour), or `default-fg` /
5
+ * `default-bg` (the terminal's default foreground / background).
6
+ */
7
+
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { RGBA } from "@opentui/core";
11
+ import { watchDirectory } from "@operad-io/engine/platform";
12
+ import { repeatEvery } from "@operad-io/engine";
13
+ import { SHIPPED_THEMES, THEME_FAMILIES, shippedThemeFile } from "./themes.ts";
14
+
15
+ /** The theme mode a terminal reports. */
16
+ export type TuiMode = "light" | "dark";
17
+
18
+ /** The colour tokens every theme defines. */
19
+ export interface TuiPalette {
20
+ /** Ordinary text. */
21
+ readonly text: string;
22
+ /** Secondary text, hints, rules' labels. */
23
+ readonly weak: string;
24
+ /** Rules and borders. */
25
+ readonly rule: string;
26
+ /** What needs you. */
27
+ readonly accent: string;
28
+ /** In progress. */
29
+ readonly run: string;
30
+ /** Success. */
31
+ readonly ok: string;
32
+ readonly error: string;
33
+ /** A cancelled object: a dark red, apart from error and weak. */
34
+ readonly cancelled: string;
35
+ /** An added diff line. */
36
+ readonly add: string;
37
+ /** A removed diff line. */
38
+ readonly remove: string;
39
+ /** The selection's background. */
40
+ readonly tint: string;
41
+ /** A code block's background. */
42
+ readonly code: string;
43
+ /** The fill of an overlay box (palette, note, confirmation, key list). */
44
+ readonly background: string;
45
+ }
46
+
47
+ export type TuiToken = keyof TuiPalette;
48
+
49
+ /** Every token name, in the order the docs list them. */
50
+ export const TUI_TOKENS: readonly TuiToken[] = [
51
+ "text",
52
+ "weak",
53
+ "rule",
54
+ "accent",
55
+ "run",
56
+ "ok",
57
+ "error",
58
+ "cancelled",
59
+ "add",
60
+ "remove",
61
+ "tint",
62
+ "code",
63
+ "background",
64
+ ];
65
+
66
+ const LIGHT: TuiPalette = {
67
+ text: "#17171a",
68
+ weak: "#6a6a75",
69
+ rule: "#e4e3e9",
70
+ accent: "#5b3fd0",
71
+ run: "#1f6fd1",
72
+ ok: "#1d7a4b",
73
+ error: "#c3242c",
74
+ cancelled: "#8a1c22",
75
+ add: "#1a7f37",
76
+ remove: "#cf222e",
77
+ tint: "#f1eefc",
78
+ code: "#f4f3f7",
79
+ background: "#ffffff",
80
+ };
81
+
82
+ const DARK: TuiPalette = {
83
+ text: "#ececf2",
84
+ weak: "#9696a3",
85
+ rule: "#292933",
86
+ accent: "#a793ff",
87
+ run: "#6aa9ff",
88
+ ok: "#5fcf9a",
89
+ error: "#ff7d82",
90
+ cancelled: "#b23b45",
91
+ add: "#7ee787",
92
+ remove: "#ff7b72",
93
+ tint: "#1c1830",
94
+ code: "#16161c",
95
+ background: "#0e0e12",
96
+ };
97
+
98
+ /** The terminal's own 16 colours: its scheme decides the look. */
99
+ const TERMINAL: TuiPalette = {
100
+ text: "default-fg",
101
+ weak: "ansi:8",
102
+ rule: "ansi:8",
103
+ accent: "ansi:5",
104
+ run: "ansi:4",
105
+ ok: "ansi:2",
106
+ error: "ansi:1",
107
+ cancelled: "ansi:9",
108
+ add: "ansi:2",
109
+ remove: "ansi:1",
110
+ tint: "default-bg",
111
+ code: "default-bg",
112
+ background: "default-bg",
113
+ };
114
+
115
+ /** Light and dark palettes, for code that has a mode and no theme name. */
116
+ export const TUI_PALETTE: Readonly<Record<TuiMode, TuiPalette>> = {
117
+ light: LIGHT,
118
+ dark: DARK,
119
+ };
120
+
121
+ /** The built-in themes that are a palette of their own. */
122
+ export const BUILTIN_THEMES: Readonly<Record<"light" | "dark" | "terminal", TuiPalette>> = {
123
+ light: LIGHT,
124
+ dark: DARK,
125
+ terminal: TERMINAL,
126
+ };
127
+
128
+ /**
129
+ * The theme names a person can choose. `auto` follows the terminal, and so does
130
+ * a family; the shipped themes are fixed.
131
+ */
132
+ export const THEME_NAMES: readonly string[] = [
133
+ "auto",
134
+ "light",
135
+ "dark",
136
+ "terminal",
137
+ ...Object.keys(THEME_FAMILIES),
138
+ ...SHIPPED_THEMES,
139
+ ];
140
+
141
+ export const DEFAULT_THEME = "auto";
142
+
143
+ /** The palette a theme name shows in a terminal whose mode is `mode`. */
144
+ export function resolvePalette(name: string, mode: TuiMode): TuiPalette {
145
+ if (name === "auto") return TUI_PALETTE[mode];
146
+ if (name === "light" || name === "dark" || name === "terminal") return BUILTIN_THEMES[name];
147
+ const shipped = shippedPalette(name);
148
+ if (shipped !== undefined) return shipped;
149
+ const family = THEME_FAMILIES[name];
150
+ if (family !== undefined) return resolvePalette(family[mode], mode);
151
+ throw new Error(unknownTheme(name));
152
+ }
153
+
154
+ function unknownTheme(name: string): string {
155
+ return `unknown theme "${name}"; the themes are ${THEME_NAMES.join(", ")}`;
156
+ }
157
+
158
+ /** The drawing colour of a token value. */
159
+ export function toRgba(colour: string): RGBA {
160
+ if (colour === "default-fg") return RGBA.defaultForeground();
161
+ if (colour === "default-bg") return RGBA.defaultBackground();
162
+ const index = /^ansi:(\d{1,2})$/.exec(colour);
163
+ if (index !== null) return RGBA.fromIndex(Number(index[1]));
164
+ return RGBA.fromHex(colour);
165
+ }
166
+
167
+ /** The file that holds the theme choice. */
168
+ export function tuiConfigPath(home: string): string {
169
+ return join(home, "tui.json");
170
+ }
171
+
172
+ /** The directory of the person's own theme files. */
173
+ export function themesDirectory(home: string): string {
174
+ return join(home, "themes");
175
+ }
176
+
177
+ /** A theme as the view draws it: a built-in by name, or a file theme's own palette. */
178
+ export interface ThemeSelection {
179
+ readonly name: string;
180
+ /** Set for a file theme; a built-in is resolved from its name and the mode. */
181
+ readonly palette?: TuiPalette | undefined;
182
+ }
183
+
184
+ const FILE_THEME_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
185
+ const HEX_COLOUR = /^#[0-9a-fA-F]{6}$/;
186
+
187
+ function isBuiltin(name: string): boolean {
188
+ return THEME_NAMES.includes(name);
189
+ }
190
+
191
+ function themeFile(home: string, name: string): string {
192
+ return join(themesDirectory(home), `${name}.json`);
193
+ }
194
+
195
+ function fileThemeNames(home: string): string[] {
196
+ try {
197
+ return readdirSync(themesDirectory(home))
198
+ .filter((entry) => entry.endsWith(".json"))
199
+ .map((entry) => entry.slice(0, -".json".length))
200
+ .filter((name) => FILE_THEME_NAME.test(name) && !isBuiltin(name))
201
+ .sort();
202
+ } catch {
203
+ return [];
204
+ }
205
+ }
206
+
207
+ /** The themes a person can choose: the built-in and shipped ones, then the files in `<home>/themes`. */
208
+ export function installedThemes(home: string): readonly string[] {
209
+ return [...THEME_NAMES, ...fileThemeNames(home)];
210
+ }
211
+
212
+ function unknownThemeIn(home: string, name: string): string {
213
+ const names = [...THEME_NAMES, ...fileThemeNames(home)];
214
+ return `unknown theme "${name}"; the themes are ${names.join(", ")}`;
215
+ }
216
+
217
+ function colourValue(file: string, token: string, value: unknown): string {
218
+ if (typeof value === "string" && HEX_COLOUR.test(value)) return value.toLowerCase();
219
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 15) {
220
+ return `ansi:${value}`;
221
+ }
222
+ throw new Error(
223
+ `${file}: colors.${token} is ${JSON.stringify(value)}, not a colour; use "#rrggbb" or an ANSI index from 0 to 15`,
224
+ );
225
+ }
226
+
227
+ /**
228
+ * The shipped themes already read, by name. A file is read the first time its
229
+ * theme is chosen, not when this module is imported: a missing or broken file
230
+ * fails that choice, not every TUI start.
231
+ */
232
+ const SHIPPED_PALETTES = new Map<string, TuiPalette>();
233
+
234
+ /** One shipped palette, read on first use and checked like any theme file. */
235
+ function shippedPalette(name: string): TuiPalette | undefined {
236
+ if (!SHIPPED_THEMES.includes(name)) return undefined;
237
+ const cached = SHIPPED_PALETTES.get(name);
238
+ if (cached !== undefined) return cached;
239
+ const file = shippedThemeFile(name);
240
+ const { parent, changes } = parseThemeFile(file);
241
+ if (parent !== "dark") throw new Error(`${file}: a shipped theme extends dark, not "${parent}"`);
242
+ const palette = { ...DARK, ...changes };
243
+ SHIPPED_PALETTES.set(name, palette);
244
+ return palette;
245
+ }
246
+
247
+ /** What a theme file says: the theme it extends and the tokens it changes. */
248
+ function parseThemeFile(file: string): {
249
+ readonly parent: string;
250
+ readonly changes: Partial<Record<TuiToken, string>>;
251
+ } {
252
+ let value: unknown;
253
+ try {
254
+ value = JSON.parse(readFileSync(file, "utf8"));
255
+ } catch (error) {
256
+ const reason = error instanceof Error ? error.message : String(error);
257
+ throw new Error(`${file} is not valid JSON: ${reason}`);
258
+ }
259
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
260
+ throw new Error(`${file} must be a JSON object like {"colors": {"accent": "#ff8800"}}`);
261
+ }
262
+ const record = value as Record<string, unknown>;
263
+ for (const key of Object.keys(record)) {
264
+ if (key !== "extends" && key !== "colors" && key !== "$schema" && key !== "comment") {
265
+ throw new Error(`${file}: unknown key "${key}"; only "extends", "colors" and "comment" are allowed`);
266
+ }
267
+ }
268
+ if (record["comment"] !== undefined && typeof record["comment"] !== "string") {
269
+ throw new Error(`${file}: "comment" must be a string`);
270
+ }
271
+ const parent = record["extends"] ?? "dark";
272
+ if (typeof parent !== "string") throw new Error(`${file}: "extends" must be a string`);
273
+ const colors = record["colors"] ?? {};
274
+ if (typeof colors !== "object" || colors === null || Array.isArray(colors)) {
275
+ throw new Error(`${file}: "colors" must be an object of token to colour`);
276
+ }
277
+ const changes: Partial<Record<TuiToken, string>> = {};
278
+ for (const [token, colour] of Object.entries(colors)) {
279
+ if (!(TUI_TOKENS as readonly string[]).includes(token)) {
280
+ throw new Error(
281
+ `${file}: colors.${token} is not a token; the tokens are ${TUI_TOKENS.join(", ")}`,
282
+ );
283
+ }
284
+ changes[token as TuiToken] = colourValue(file, token, colour);
285
+ }
286
+ return { parent, changes };
287
+ }
288
+
289
+ /** Reads one theme file and the themes it extends into a full palette. */
290
+ function loadFileTheme(home: string, name: string, chain: readonly string[]): TuiPalette {
291
+ const file = themeFile(home, name);
292
+ if (!existsSync(file)) {
293
+ const by = themeFile(home, chain[chain.length - 1] ?? name);
294
+ throw new Error(
295
+ `${by}: "extends" names "${name}", which is not a theme; the themes are ${[...THEME_NAMES, ...fileThemeNames(home)].join(", ")}`,
296
+ );
297
+ }
298
+ const { parent, changes } = parseThemeFile(file);
299
+ let base: TuiPalette;
300
+ const shipped = shippedPalette(parent);
301
+ if (parent === "light" || parent === "dark" || parent === "terminal") {
302
+ if (existsSync(themeFile(home, parent))) throw new Error(clash(home, parent));
303
+ base = BUILTIN_THEMES[parent];
304
+ } else if (shipped !== undefined) {
305
+ if (existsSync(themeFile(home, parent))) throw new Error(clash(home, parent));
306
+ base = shipped;
307
+ } else if (!FILE_THEME_NAME.test(parent) || isBuiltin(parent)) {
308
+ throw new Error(
309
+ `${file}: "extends" names "${parent}"; use light, dark, terminal, a shipped theme or another theme file`,
310
+ );
311
+ } else {
312
+ const chained = [...chain, name];
313
+ if (chained.includes(parent)) {
314
+ throw new Error(`${file}: "extends" makes a cycle: ${[...chained, parent].join(" -> ")}`);
315
+ }
316
+ base = loadFileTheme(home, parent, chained);
317
+ }
318
+ return { ...base, ...changes };
319
+ }
320
+
321
+ function clash(home: string, name: string): string {
322
+ return `${themeFile(home, name)} has the name of the built-in theme "${name}"; rename the file`;
323
+ }
324
+
325
+ /** The theme a name stands for; it throws an error naming the file and the key. */
326
+ export function resolveSelection(home: string, name: string): ThemeSelection {
327
+ if (isBuiltin(name)) {
328
+ if (existsSync(themeFile(home, name))) throw new Error(clash(home, name));
329
+ // A shipped theme is checked when it is chosen; a family checks both of its
330
+ // members, whichever one the terminal's mode later picks.
331
+ const family = THEME_FAMILIES[name];
332
+ if (family !== undefined) {
333
+ shippedPalette(family.light);
334
+ shippedPalette(family.dark);
335
+ } else {
336
+ shippedPalette(name);
337
+ }
338
+ return { name };
339
+ }
340
+ if (!FILE_THEME_NAME.test(name) || !existsSync(themeFile(home, name))) {
341
+ throw new Error(unknownThemeIn(home, name));
342
+ }
343
+ return { name, palette: loadFileTheme(home, name, []) };
344
+ }
345
+
346
+ /**
347
+ * The theme for this session: `flag` beats `tui.json`, which beats `auto`.
348
+ * It throws an error naming the problem when the name is unknown, a theme file
349
+ * is invalid or the config cannot be read, so the TUI never starts on a
350
+ * half-read config.
351
+ */
352
+ export function chooseSelection(options: {
353
+ readonly home: string;
354
+ readonly flag?: string | undefined;
355
+ }): ThemeSelection {
356
+ const file = tuiConfigPath(options.home);
357
+ // The file is read even when the flag wins, so a broken file is not hidden.
358
+ const fromFile = readThemeFile(file);
359
+ const name = options.flag ?? fromFile ?? DEFAULT_THEME;
360
+ try {
361
+ return resolveSelection(options.home, name);
362
+ } catch (error) {
363
+ const reason = error instanceof Error ? error.message : String(error);
364
+ if (!reason.startsWith("unknown theme")) throw error;
365
+ const where = options.flag === undefined ? ` in ${file}` : " given with --theme";
366
+ throw new Error(`${reason}${where}`);
367
+ }
368
+ }
369
+
370
+ /** The theme name for this session; see `chooseSelection`. */
371
+ export function chooseTheme(options: {
372
+ readonly home: string;
373
+ readonly flag?: string | undefined;
374
+ }): string {
375
+ return chooseSelection(options).name;
376
+ }
377
+
378
+ /** The theme in force, kept up to date by `watchThemes`. */
379
+ export interface ThemeHolder {
380
+ current: ThemeSelection;
381
+ /** A theme shown only while a person looks at it; it wins over `current` until cleared. */
382
+ preview?: ThemeSelection | undefined;
383
+ }
384
+
385
+ /** How the object page draws its next level, from `tui.json`. */
386
+ export type TuiChildLayout = "tree" | "list";
387
+
388
+ const CHILD_LAYOUTS: readonly TuiChildLayout[] = ["tree", "list"];
389
+
390
+ interface TuiConfig {
391
+ readonly theme?: string | undefined;
392
+ readonly layout?: TuiChildLayout | undefined;
393
+ }
394
+
395
+ /** The child layout in force for a session: `tui.json`'s, or the tree. */
396
+ export function chooseChildLayout(options: { readonly home: string }): TuiChildLayout {
397
+ return readTuiConfig(tuiConfigPath(options.home)).layout ?? "tree";
398
+ }
399
+
400
+ /** Writes one choice to `tui.json`, keeping every other key in the file. */
401
+ function saveTuiChoice(home: string, key: "theme" | "layout", value: string): void {
402
+ const file = tuiConfigPath(home);
403
+ // Reading checks the file first, so a broken one is never overwritten.
404
+ readTuiConfig(file);
405
+ const existing: Record<string, unknown> = existsSync(file)
406
+ ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>)
407
+ : {};
408
+ mkdirSync(home, { recursive: true });
409
+ const temporary = `${file}.${process.pid}.tmp`;
410
+ writeFileSync(temporary, `${JSON.stringify({ ...existing, [key]: value }, null, 2)}\n`);
411
+ renameSync(temporary, file);
412
+ }
413
+
414
+ /**
415
+ * Writes the theme choice to `tui.json`, keeping every other key in the file.
416
+ * It throws, and writes nothing, when the name is not a theme or the file
417
+ * cannot be read as it is.
418
+ */
419
+ export function saveThemeChoice(home: string, name: string): void {
420
+ resolveSelection(home, name);
421
+ saveTuiChoice(home, "theme", name);
422
+ }
423
+
424
+ /** Writes the child layout to `tui.json`, keeping every other key in the file. */
425
+ export function saveChildLayout(home: string, layout: TuiChildLayout): void {
426
+ if (!CHILD_LAYOUTS.includes(layout)) {
427
+ throw new Error(`unknown child layout "${layout}"; use tree or list`);
428
+ }
429
+ saveTuiChoice(home, "layout", layout);
430
+ }
431
+
432
+ /**
433
+ * Watches `tui.json` and the themes directory. After every change the watch
434
+ * reports, and on a fallback timer (an edit can slip past the watch), it chooses
435
+ * the theme again. A watch event always calls `onChange`; a timer tick calls it
436
+ * only when the theme or the problem changed. A result: a good result replaces `holder.current` and calls `onChange()`; a
437
+ * bad one keeps the last good theme and calls `onChange` with the reason.
438
+ * Returns the stop function.
439
+ */
440
+ export function watchThemes(options: {
441
+ readonly home: string;
442
+ readonly flag?: string | undefined | (() => string | undefined);
443
+ readonly holder: ThemeHolder;
444
+ readonly onChange: (problem?: string) => void;
445
+ readonly watch?: typeof watchDirectory | undefined;
446
+ /** The fallback timer; a test injects it. Defaults to a real interval. */
447
+ readonly repeat?: ((ms: number, callback: () => void) => () => void) | undefined;
448
+ readonly pollMs?: number | undefined;
449
+ }): () => void {
450
+ const watch = options.watch ?? watchDirectory;
451
+ const themes = themesDirectory(options.home);
452
+ let stopThemes: (() => void) | undefined;
453
+ let stopped = false;
454
+ let lastProblem: string | undefined;
455
+ // A directory watch is the fast path, not a promise: an edit made as the
456
+ // watch starts can produce no event. The timer re-reads and reports only a
457
+ // change in the theme or in the problem.
458
+ const refresh = (always: boolean): void => {
459
+ if (stopped) return;
460
+ // The themes directory may appear after the TUI started.
461
+ if (stopThemes === undefined && existsSync(themes)) stopThemes = watch(themes, reload);
462
+ let next: ThemeSelection;
463
+ try {
464
+ const flag = typeof options.flag === "function" ? options.flag() : options.flag;
465
+ next = chooseSelection({ home: options.home, flag });
466
+ } catch (error) {
467
+ const problem = error instanceof Error ? error.message : String(error);
468
+ const changed = problem !== lastProblem;
469
+ lastProblem = problem;
470
+ if (always || changed) options.onChange(problem);
471
+ return;
472
+ }
473
+ const changed = lastProblem !== undefined || JSON.stringify(next) !== JSON.stringify(options.holder.current);
474
+ lastProblem = undefined;
475
+ options.holder.current = next;
476
+ if (always || changed) options.onChange();
477
+ };
478
+ const reload = (): void => refresh(true);
479
+ const stopPoll = (options.repeat ?? repeatEvery)(options.pollMs ?? 500, () => refresh(false));
480
+ const stopHome = watch(options.home, (filename) => {
481
+ if (filename === null || filename === "tui.json" || filename === "themes") reload();
482
+ });
483
+ if (existsSync(themes)) stopThemes = watch(themes, reload);
484
+ return () => {
485
+ stopped = true;
486
+ stopPoll();
487
+ stopHome();
488
+ stopThemes?.();
489
+ };
490
+ }
491
+
492
+ function readTuiConfig(file: string): TuiConfig {
493
+ if (!existsSync(file)) return {};
494
+ let value: unknown;
495
+ try {
496
+ value = JSON.parse(readFileSync(file, "utf8"));
497
+ } catch (error) {
498
+ const reason = error instanceof Error ? error.message : String(error);
499
+ throw new Error(`${file} is not valid JSON: ${reason}`);
500
+ }
501
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
502
+ throw new Error(`${file} must be a JSON object like {"theme": "dark"}`);
503
+ }
504
+ for (const key of Object.keys(value)) {
505
+ if (key !== "theme" && key !== "layout" && key !== "$schema") {
506
+ throw new Error(`${file} has an unknown key "${key}"; only "theme" and "layout" are allowed`);
507
+ }
508
+ }
509
+ const theme = (value as { readonly theme?: unknown }).theme;
510
+ if (theme !== undefined && typeof theme !== "string") {
511
+ throw new Error(`${file}: "theme" must be a string`);
512
+ }
513
+ const layout = (value as { readonly layout?: unknown }).layout;
514
+ if (layout !== undefined && !CHILD_LAYOUTS.includes(layout as TuiChildLayout)) {
515
+ throw new Error(`${file}: "layout" must be "tree" or "list"`);
516
+ }
517
+ return {
518
+ ...(theme === undefined ? {} : { theme }),
519
+ ...(layout === undefined ? {} : { layout: layout as TuiChildLayout }),
520
+ };
521
+ }
522
+
523
+ function readThemeFile(file: string): string | undefined {
524
+ return readTuiConfig(file).theme;
525
+ }
package/src/themes.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The themes shipped with operad and the families that pair a light theme with
3
+ * a dark one. The colours are in `themes/<name>.json` (same format as the
4
+ * person's own theme files); this module only names them. This is the one place
5
+ * that declares a family.
6
+ */
7
+
8
+ import { join } from "node:path";
9
+
10
+ /** A family: a name that follows the terminal's light or dark mode. */
11
+ export interface ThemeFamily {
12
+ readonly light: string;
13
+ readonly dark: string;
14
+ }
15
+
16
+ /** The shipped themes, one file each in `themes/`. */
17
+ export const SHIPPED_THEMES: readonly string[] = [
18
+ "catppuccin-latte",
19
+ "catppuccin-frappe",
20
+ "catppuccin-macchiato",
21
+ "catppuccin-mocha",
22
+ "dracula",
23
+ "nord",
24
+ "solarized-light",
25
+ "solarized-dark",
26
+ "tokyo-night-day",
27
+ "tokyo-night-night",
28
+ "one-light",
29
+ "one-dark",
30
+ "rose-pine-dawn",
31
+ "rose-pine-main",
32
+ "github-light",
33
+ "github-dark",
34
+ "kanagawa-lotus",
35
+ "kanagawa-wave",
36
+ "kanagawa-dragon",
37
+ ];
38
+
39
+ /**
40
+ * `theme: "<family>"` shows the family's light member in a light terminal and
41
+ * its dark member in a dark one, and switches live like `auto`. A family name is
42
+ * never also a theme name, so every shipped theme can still be chosen on its own.
43
+ */
44
+ export const THEME_FAMILIES: Readonly<Record<string, ThemeFamily>> = {
45
+ catppuccin: { light: "catppuccin-latte", dark: "catppuccin-mocha" },
46
+ solarized: { light: "solarized-light", dark: "solarized-dark" },
47
+ "tokyo-night": { light: "tokyo-night-day", dark: "tokyo-night-night" },
48
+ one: { light: "one-light", dark: "one-dark" },
49
+ "rose-pine": { light: "rose-pine-dawn", dark: "rose-pine-main" },
50
+ github: { light: "github-light", dark: "github-dark" },
51
+ kanagawa: { light: "kanagawa-lotus", dark: "kanagawa-wave" },
52
+ };
53
+
54
+ /** The directory of the shipped theme files. */
55
+ export const SHIPPED_DIRECTORY = join(import.meta.dir, "..", "themes");
56
+
57
+ /** The file of one shipped theme. */
58
+ export function shippedThemeFile(name: string): string {
59
+ return join(SHIPPED_DIRECTORY, `${name}.json`);
60
+ }