dracosh 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/doctor.js ADDED
@@ -0,0 +1,123 @@
1
+ import { constants } from "node:fs";
2
+ import { access } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { aiLabel, listModels } from "./ai.js";
5
+ import { t } from "./i18n.js";
6
+ import { findNotifier } from "./notify.js";
7
+ import { findPlayers } from "./player.js";
8
+ import { findSpeech } from "./speech.js";
9
+ import { DATA_FILES, HOME, loadLibrary, loadState, readJson } from "./store.js";
10
+ import { findVoiceKey, listVoices, voiceLabel } from "./voice.js";
11
+
12
+ // `dracosh doctor`: what works on this computer and what to do about what doesn't. Each check is
13
+ // { status, label, detail, safe }: ok, warn (works, could be better), fail (needs fixing) or off (not
14
+ // set up); `safe` is the detail with nothing personal in it (no paths, addresses, names or what a
15
+ // server said), for a bug report.
16
+ // Online checks only list models or voices: free, and they prove the key and the address.
17
+
18
+ const NEEDED = [22, 15];
19
+ const newEnough = (version) => {
20
+ const [major, minor] = version.split(".").map(Number);
21
+ return major > NEEDED[0] || (major === NEEDED[0] && minor >= NEEDED[1]);
22
+ };
23
+
24
+ const exists = (path) => access(path).then(() => true, () => false);
25
+ const writable = (path) => access(path, constants.W_OK).then(() => true, () => false);
26
+
27
+ // the first folder on the way up that's there: where a data folder not made yet would go
28
+ async function nearest(path) {
29
+ while (!(await exists(path)) && dirname(path) !== path) path = dirname(path);
30
+ return path;
31
+ }
32
+
33
+ // platform, has (what's on PATH), env, node, home and online (listModels, listVoices, findVoiceKey):
34
+ // given by tests
35
+ export async function checkAll(settings, { platform = process.platform, has, env = process.env, node = process.versions.node, home = HOME, online = {} } = {}) {
36
+ const found = { platform, env, ...(has && { has }) };
37
+ const models = online.listModels ?? listModels;
38
+ const voices = online.listVoices ?? listVoices;
39
+ const voiceKey = online.findVoiceKey ?? findVoiceKey;
40
+ const checks = [];
41
+ const add = (status, label, detail, safe = detail) => checks.push({ status, label, detail, safe });
42
+
43
+ add(newEnough(node) ? "ok" : "fail", "Node", newEnough(node) ? node : t("cli.doctor.nodeOld", { version: node, needed: NEEDED.join(".") }));
44
+
45
+ const data = t("cli.doctor.data");
46
+ if (!(await exists(home))) {
47
+ const canMake = await writable(await nearest(home));
48
+ add(canMake ? "ok" : "fail", data, t(canMake ? "cli.doctor.dataNew" : "cli.doctor.dataReadOnly", { home }), canMake ? "not created yet" : "can't be written to");
49
+ } else if (!(await writable(home))) add("fail", data, t("cli.doctor.dataReadOnly", { home }), "can't be written to");
50
+ else {
51
+ try {
52
+ // settings read as they are: the app quietly falls back to the defaults when they're damaged
53
+ await Promise.all([loadLibrary(), loadState(), readJson(DATA_FILES.settings, {})]);
54
+ add("ok", data, home, "readable");
55
+ } catch (err) {
56
+ add("fail", data, err.message, err.damaged ? "a file is damaged" : "a file can't be read");
57
+ }
58
+ }
59
+
60
+ const sound = t("settings.rows.sound.label");
61
+ const players = findPlayers(found);
62
+ if (platform === "win32") add("off", sound, t("cli.doctor.noSoundWindows"));
63
+ else if (players.length) add(settings.sound ? "ok" : "off", sound, settings.sound ? players.join(", ") : t("settings.off"));
64
+ else add(settings.sound ? "fail" : "off", sound, t("cli.doctor.noPlayer"));
65
+
66
+ const notifier = findNotifier(found);
67
+ const overSsh = Boolean(env.SSH_CONNECTION || env.SSH_TTY); // the bell is the right thing there
68
+ const bellOnly = notifier === "bell" && platform !== "win32" && platform !== "darwin" && !overSsh;
69
+ add(bellOnly ? "warn" : "ok", t("cli.doctor.notifications"), t(`cli.doctor.notifier.${bellOnly ? "bellLinux" : notifier}`));
70
+
71
+ if (platform !== "win32") {
72
+ const speak = t("settings.rows.speak.label");
73
+ const speech = findSpeech(found);
74
+ if (!settings.speak) add("off", speak, t("settings.off"));
75
+ else if (speech) add("ok", speak, speech);
76
+ else add(settings.voice ? "warn" : "fail", speak, t("cli.doctor.noSpeech"));
77
+
78
+ if (settings.speak && settings.voice) {
79
+ const label = t("settings.rows.voice.label");
80
+ const name = voiceLabel(settings.voice);
81
+ if (!findPlayers({ ...found, mp3: true }).length) add("fail", label, t("cli.doctor.noMp3Player", { voice: name }), "ElevenLabs: no player for mp3");
82
+ else {
83
+ try {
84
+ const key = (await voiceKey())?.key ?? null;
85
+ const list = await voices({ key, url: settings.voice.url });
86
+ // a voice's name is often the person it was cloned from: never in a report
87
+ if (list.some((voice) => voice.id === settings.voice.id)) add("ok", label, name, "ElevenLabs");
88
+ else add("fail", label, t("voice.errors.noVoice"), "ElevenLabs: noVoice");
89
+ } catch (err) {
90
+ add("fail", label, err.message, `ElevenLabs: ${err.code ?? "failed"}`);
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ const aiRow = t("settings.rows.ai.label");
97
+ if (!settings.ai) add("off", aiRow, t("settings.off"));
98
+ else {
99
+ try {
100
+ const names = await models(settings.ai);
101
+ // a server that lists nothing (some don't) isn't held against the model; a short name stands for
102
+ // its dated versions ("claude-x" for "claude-x-20260101")
103
+ const { model } = settings.ai;
104
+ // the provider only: a model's name can carry an account's ("ft:…:acme:…"), a message its address
105
+ const provider = settings.ai.provider;
106
+ if (!names.length || names.some((name) => name === model || name.startsWith(`${model}-`))) add("ok", aiRow, aiLabel(settings.ai), provider);
107
+ else add("warn", aiRow, t("cli.doctor.aiNoModel", { label: aiLabel(settings.ai), model: settings.ai.model }), `${provider}: model not listed`);
108
+ } catch (err) {
109
+ add("fail", aiRow, err.message, `${settings.ai.provider}: ${err.code ?? "failed"}`);
110
+ }
111
+ }
112
+ return checks;
113
+ }
114
+
115
+ const MARKS = { ok: "✓", warn: "!", fail: "✗", off: "–" };
116
+
117
+ // safe: each line's detail with nothing personal in it (for `dracosh bug`)
118
+ export function report(checks, { safe = false } = {}) {
119
+ const width = Math.max(...checks.map((check) => check.label.length));
120
+ const lines = checks.map((check) => ` ${MARKS[check.status]} ${check.label.padEnd(width)} ${safe ? (check.safe ?? check.detail) : check.detail}`);
121
+ const problems = checks.filter((check) => check.status === "fail").length;
122
+ return [t("cli.doctor.title"), "", ...lines, "", problems ? t("cli.doctor.problems", { count: problems }) : t("cli.doctor.allGood")].join("\n");
123
+ }
package/src/notify.js ADDED
@@ -0,0 +1,44 @@
1
+ import { execFile } from "node:child_process";
2
+ import { onPath } from "./player.js";
3
+
4
+ // A new card while you're in another window: a Notification Center banner on macOS, a desktop
5
+ // notification through notify-send on Linux, the terminal's bell elsewhere and wherever the native way
6
+ // doesn't work. Over SSH a desktop notification would show on the remote screen: the bell instead.
7
+
8
+ export function findNotifier({ platform = process.platform, has = onPath, env = process.env } = {}) {
9
+ if (env.SSH_CONNECTION || env.SSH_TTY) return "bell";
10
+ if (platform === "darwin") return "osascript";
11
+ if (platform !== "win32" && has("notify-send")) return "notify-send";
12
+ return "bell";
13
+ }
14
+
15
+ const COMMANDS = {
16
+ // the text goes to AppleScript as an argument, never into the script itself
17
+ osascript: (text) => ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", text],
18
+ "notify-send": (text) => ["--app-name=Dracosh", "--", "Dracosh", text]
19
+ };
20
+ const TIMEOUT_MS = 5_000; // notify-send can wait on a session bus with no notification daemon behind it
21
+
22
+ // BEL is zero-width, so it doesn't upset Ink's drawing; piped output doesn't get it
23
+ const ringBell = () => {
24
+ if (process.stdout.isTTY) process.stdout.write("\x07");
25
+ };
26
+
27
+ // notify(text, { bell }). The bell rings only when asked: Windows Terminal plays the system's sound for
28
+ // it by default, which would sound on top of the app's own chime. A native notification that fails (no
29
+ // notification daemon) gives way to the bell for the rest of the run.
30
+ export function createNotifier({ kind = findNotifier(), run = execFile, bell = ringBell } = {}) {
31
+ let use = kind;
32
+ return {
33
+ notify(text, { bell: ring = true } = {}) {
34
+ if (use === "bell") return void (ring && bell());
35
+ const tried = use;
36
+ const child = run(tried, COMMANDS[tried](text), { windowsHide: true, timeout: TIMEOUT_MS }, (err) => {
37
+ if (!err || use !== tried) return;
38
+ use = "bell";
39
+ if (ring) bell();
40
+ });
41
+ child?.unref?.(); // quitting doesn't wait for it
42
+ }
43
+ };
44
+ }
package/src/player.js ADDED
@@ -0,0 +1,117 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+
7
+ // The program that plays a .wav on this system: afplay on macOS, paplay, aplay or ffplay on Linux.
8
+ // Windows has none: PowerShell, its only built-in way, takes a third of a second to start for each
9
+ // sound, so the chime would come late after every answer. With none that works, sounds stay silent.
10
+
11
+ export const onPath = (name, env = process.env) =>
12
+ (env.PATH ?? "").split(path.delimiter).some((dir) => {
13
+ if (!dir) return false;
14
+ try {
15
+ accessSync(path.join(dir, name), constants.X_OK);
16
+ return true;
17
+ } catch {
18
+ return false;
19
+ }
20
+ });
21
+
22
+ // volume: whether the player takes a level; one that doesn't gets a quieter copy of the sound
23
+ const PLAYERS = {
24
+ afplay: { volume: true, args: (file, volume) => ["-v", String(volume), file] },
25
+ // PulseAudio's volume is cubic: the cube root gives the same loudness as afplay's linear level
26
+ paplay: { volume: true, args: (file, volume) => [`--volume=${Math.round(Math.cbrt(volume) * 65536)}`, file] },
27
+ aplay: { volume: false, args: (file) => ["-q", file] },
28
+ ffplay: { volume: true, args: (file, volume) => ["-nodisp", "-autoexit", "-loglevel", "quiet", "-volume", String(Math.round(volume * 100)), file] }
29
+ };
30
+ const LINUX = ["paplay", "aplay", "ffplay"];
31
+ const LINUX_MP3 = ["paplay", "ffplay"]; // aplay reads .wav only; paplay reads .mp3 with libsndfile 1.1+
32
+
33
+ // whether this system plays sounds at all (Settings leaves Sound, Volume and Read aloud out where it doesn't)
34
+ export const PLAYS_SOUNDS = process.platform !== "win32";
35
+
36
+ // The players on PATH to try, best first. mp3: only those that can play one (a natural voice's file).
37
+ export function findPlayers({ platform = process.platform, has = onPath, mp3 = false } = {}) {
38
+ if (platform === "win32") return [];
39
+ return (platform === "darwin" ? ["afplay"] : mp3 ? LINUX_MP3 : LINUX).filter((name) => has(name));
40
+ }
41
+
42
+ // How to run a player for a file at a volume: { command, args }
43
+ export function playCommand(name, file, volume, dir) {
44
+ const player = PLAYERS[name];
45
+ return { command: name, args: player.args(player.volume ? file : scaledWav(file, volume, dir), volume) };
46
+ }
47
+
48
+ // play(file, volume, done): plays, then calls done() whether it played or not; returns { kill } to cut
49
+ // it off. silent: no player left that works. A player that fails (paplay with no sound server, aplay
50
+ // with no sound card) is dropped for the rest of the run and the sound goes to the next one.
51
+ // dir: where quieter copies go.
52
+ export function createPlayer({ players = findPlayers(), run = execFile, dir } = {}) {
53
+ const left = [...players];
54
+ const play = (file, volume, done = () => {}) => {
55
+ let child = null;
56
+ let stopped = false;
57
+ const start = () => {
58
+ const name = left[0];
59
+ if (!name || stopped) return void done();
60
+ const { command, args } = playCommand(name, file, volume, dir);
61
+ child = run(command, args, (err) => {
62
+ if (!err || stopped || err.killed || err.signal) return void done();
63
+ if (left[0] === name) left.shift();
64
+ start();
65
+ });
66
+ };
67
+ start();
68
+ return {
69
+ kill() {
70
+ stopped = true;
71
+ child?.kill?.();
72
+ }
73
+ };
74
+ };
75
+ return {
76
+ play,
77
+ get silent() {
78
+ return left.length === 0;
79
+ }
80
+ };
81
+ }
82
+
83
+ // A 16-bit PCM .wav (what scripts/make-sounds.js writes) at a lower volume, made once per level in the
84
+ // system's temp folder and kept there for the next run, under a name that changes with the sound.
85
+ // Written under another name first, so a second Dracosh never plays half a file; made again if the
86
+ // system cleans the temp folder meanwhile.
87
+ const HEADER = 44;
88
+ const sources = new Map(); // file → its contents and a short hash of them, read once a run
89
+ export function scaledWav(file, volume, dir = path.join(tmpdir(), "dracosh-sounds")) {
90
+ if (volume >= 1) return file;
91
+ const level = Math.round(volume * 100);
92
+ let part = null;
93
+ try {
94
+ if (!sources.has(file)) {
95
+ const data = readFileSync(file);
96
+ sources.set(file, { data, hash: createHash("sha256").update(data).digest("hex").slice(0, 8) });
97
+ }
98
+ const { data: original, hash } = sources.get(file);
99
+ const out = path.join(dir, String(level), `${path.basename(file, ".wav")}-${hash}.wav`);
100
+ if (existsSync(out)) return out;
101
+ const data = Buffer.from(original);
102
+ for (let at = HEADER; at + 1 < data.length; at += 2) data.writeInt16LE(Math.round((data.readInt16LE(at) * level) / 100), at);
103
+ mkdirSync(path.dirname(out), { recursive: true });
104
+ part = `${out}.${process.pid}.part`;
105
+ writeFileSync(part, data);
106
+ try {
107
+ renameSync(part, out);
108
+ } catch (err) {
109
+ rmSync(part, { force: true });
110
+ if (!existsSync(out)) throw err; // another Dracosh made it first (Windows won't replace a file in use)
111
+ }
112
+ return out;
113
+ } catch {
114
+ if (part) rmSync(part, { force: true });
115
+ return file; // no temp folder to write to: the sound at full volume beats no sound
116
+ }
117
+ }
package/src/settings.js CHANGED
@@ -2,12 +2,14 @@ import { normalizeAi } from "./ai.js";
2
2
  import { normalizeVoice } from "./voice.js";
3
3
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
4
4
 
5
- export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null, ai: null, voice: null };
5
+ export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null, ai: null, voice: null, theme: "auto" };
6
6
 
7
7
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
8
8
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
9
9
  export const VOLUMES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1];
10
10
  export const TIP_MODES = ["always", "sometimes", "off"];
11
+ // auto follows the terminal's background; dark and light are the palettes in src/ui/kit.js
12
+ export const THEMES = ["auto", "dark", "light"];
11
13
  // how cards come: one every few minutes (everyMs), or a session where Enter asks the next one right
12
14
  // away, endless or for a set number of cards, after which the minutes take over again
13
15
  export const RHYTHMS = ["minutes", "session", "session-10", "session-20"];
@@ -40,6 +42,7 @@ export function normalizeSettings(raw = {}) {
40
42
  volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
41
43
  dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
42
44
  tips: normalizeTips(raw.tips),
45
+ theme: THEMES.includes(raw.theme) ? raw.theme : DEFAULTS.theme,
43
46
  skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
44
47
  quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
45
48
  deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null, // picked in /decks; null = your first deck
package/src/speech.js ADDED
@@ -0,0 +1,82 @@
1
+ import { execFile } from "node:child_process";
2
+ import { onPath } from "./player.js";
3
+
4
+ // The system's own voices: `say` on macOS, `espeak-ng` on Linux; none on Windows. Each one writes the
5
+ // word to an audio file, which the app then plays like its sounds, so it follows the volume and can be
6
+ // cut off. voiceFor(lang): the best voice for a language, or null; render(voice, words, file, volume,
7
+ // done): the running process, so it can be stopped. Voices are read once, when the first word is spoken.
8
+
9
+ // the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
10
+ const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
11
+ const NORWEGIAN = { no: "nb", nn: "nb" }; // both systems read Norwegian as Bokmål
12
+
13
+ const listOnce = (command, args, parse, run) => {
14
+ let voices = null;
15
+ return () =>
16
+ (voices ??= new Promise((resolve) => run(command, args, (err, out) => resolve(err ? [] : parse(String(out))))));
17
+ };
18
+
19
+ // macOS: `say -v ?` lists "Name pl_PL # sample"; the novelty voices are left out, and a premium or
20
+ // enhanced voice comes before a plain named one
21
+ const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
22
+ export const parseSay = (out) =>
23
+ out.split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region }));
24
+ const sayRank = (voice) => {
25
+ const regions = REGIONS[voice.lang] ?? [];
26
+ const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
27
+ const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
28
+ return region * 10 + quality;
29
+ };
30
+
31
+ // Linux: `espeak-ng --voices` lists " 5 en-us --/M English_(America) gmw/en-US ..."; the
32
+ // language column is what -v takes. Chinese is "cmn" there, and a plain code beats an odd variant.
33
+ const ESPEAK_CODE = { ...NORWEGIAN, zh: "cmn" };
34
+ export const parseEspeak = (out) =>
35
+ out.split("\n").slice(1).map((line) => line.trim().split(/\s+/)[1]).filter(Boolean).map((code) => {
36
+ const [lang, region = ""] = code.split("-");
37
+ return { name: code, lang, region: region.toUpperCase(), plain: !code.includes("-") || /^[a-z]+-[a-z]{2,3}$/.test(code) };
38
+ });
39
+ const espeakRank = (voice) => {
40
+ const regions = REGIONS[voice.lang === "cmn" ? "zh" : voice.lang] ?? [];
41
+ // a voice with no region is the language's main one ("pt" is Portugal's, "es" Spain's)
42
+ const region = !voice.region ? 0 : regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
43
+ return region * 10 + (voice.plain ? 0 : 1);
44
+ };
45
+
46
+ const SYSTEMS = {
47
+ say: {
48
+ ext: "aiff",
49
+ list: (run) => listOnce("say", ["-v", "?"], parseSay, run),
50
+ pick: (voices, lang) => voices.filter((voice) => voice.lang === (NORWEGIAN[lang] ?? lang) && !NOVELTY.has(voice.name)).sort((a, b) => sayRank(a) - sayRank(b))[0]?.name ?? null,
51
+ // say's own volume is ignored by today's voices: the player sets it
52
+ render: (run, voice, words, file, done) => run("say", ["-v", voice, "-o", file, "--", words], done),
53
+ playVolume: (volume) => volume
54
+ },
55
+ "espeak-ng": {
56
+ ext: "wav",
57
+ list: (run) => listOnce("espeak-ng", ["--voices"], parseEspeak, run),
58
+ pick: (voices, lang) => voices.filter((voice) => voice.lang === (ESPEAK_CODE[lang] ?? lang)).sort((a, b) => espeakRank(a) - espeakRank(b))[0]?.name ?? null,
59
+ // the volume goes into the file (-a, 100 is normal), so any player can play it as it is
60
+ render: (run, voice, words, file, done, volume) => run("espeak-ng", ["-v", voice, "-a", String(Math.round(volume * 100)), "-w", file, "--", words], done),
61
+ playVolume: () => 1
62
+ }
63
+ };
64
+
65
+ export function findSpeech({ platform = process.platform, has = onPath } = {}) {
66
+ if (platform === "win32") return null;
67
+ const name = platform === "darwin" ? "say" : "espeak-ng";
68
+ return has(name) ? name : null;
69
+ }
70
+
71
+ // null where the system has no voices
72
+ export function createSpeech({ name = findSpeech(), run = execFile } = {}) {
73
+ const system = SYSTEMS[name];
74
+ if (!system) return null;
75
+ const voices = system.list(run);
76
+ return {
77
+ ext: system.ext,
78
+ voiceFor: async (lang) => system.pick(await voices(), lang),
79
+ render: (voice, words, file, volume, done) => system.render(run, voice, words, file, done, volume),
80
+ playVolume: system.playVolume
81
+ };
82
+ }
package/src/ui/App.js CHANGED
@@ -7,7 +7,7 @@ import { toSpeak } from "../session.js";
7
7
  import { AnswerInput } from "./AnswerInput.js";
8
8
  import { Header } from "./Header.js";
9
9
  import { setLanguage, t } from "../i18n.js";
10
- import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
10
+ import { applyTheme, Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
11
11
  import { hintTarget, makeHint } from "../hint.js";
12
12
  import { formatClock, inQuietHours, quietEnd } from "../quiet.js";
13
13
  import { NEW_PER_DAY, startOfTomorrow } from "../scheduler.js";
@@ -49,11 +49,11 @@ const SLEEP_AFTER_MS = 3 * 60_000; // no key pressed for this long while waiting
49
49
  const PAUSED_SLEEP_AFTER_MS = 15_000; // during a pause or quiet hours it nods off again much sooner
50
50
  const SETTLE_MS = 400; // keys right after a card appears or its answer is revealed are a double press, not a choice
51
51
  const CHEER_STYLE = {
52
- goal: { icon: "▪", color: theme.good },
53
- evolve: { icon: "▴", color: theme.accent },
54
- badge: { icon: "✦", color: theme.warn },
55
- combo: { icon: "»", color: theme.warn }
56
- };
52
+ goal: { icon: "▪", color: "good" },
53
+ evolve: { icon: "▴", color: "accent" },
54
+ badge: { icon: "✦", color: "warn" },
55
+ combo: { icon: "»", color: "warn" }
56
+ }; // colors are theme keys, read when drawn
57
57
 
58
58
  const QUIET_NIGHT_UNTIL = 7; // o'clock: no "new card" sound before then when a day's cards come in
59
59
 
@@ -138,7 +138,7 @@ function Cheers({ cheers, play }) {
138
138
  <${Box} flexDirection="column" paddingX=${1} marginTop=${1}>
139
139
  ${lines.map((cheer, i) => {
140
140
  const style = CHEER_STYLE[cheer.kind] ?? CHEER_STYLE.combo;
141
- return html`<${Text} key=${i} color=${style.color} bold>${style.icon} ${cheer.text}<//>`;
141
+ return html`<${Text} key=${i} color=${theme[style.color]} bold>${style.icon} ${cheer.text}<//>`;
142
142
  })}
143
143
  ${badges.map((badge, i) => html`<${BadgeUnlock} key=${badge.id} ...${badge} delay=${BADGE_FIRST_MS + i * BADGE_STAGGER_MS} sound=${badgeSound(i)} play=${play} />`)}
144
144
  <//>
@@ -223,6 +223,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
223
223
  const exit = onExit ?? exitApp; // the preview gallery runs the quiz as a scene and takes quitting back to its menu
224
224
  const { stdout } = useStdout();
225
225
  const [settings, setSettings] = useState(initialSettings);
226
+ applyTheme(settings.theme); // before anything below reads a color; a change in /settings repaints all
226
227
  const [deck, setDeck] = useState(initialDeck);
227
228
  const [mix, setMix] = useState(initialMix !== undefined ? initialMix : (initialSettings.mix ?? null)); // decks practised together: "all", or their names
228
229
  const [addNew, setAddNew] = useState(false); // /add opened from "+ New deck" in /decks
@@ -897,7 +898,7 @@ export function App({ session, deck: initialDeck, initialSettings, initialMix, a
897
898
  html`
898
899
  <${Text}>
899
900
  <${Text} color=${theme.accent}>${frame} <//>
900
- <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color="#6b5e8a" />
901
+ <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color=${theme.countdown} />
901
902
  <${Text} dimColor>${t("quiz.nextCardIn", { time: clock(nextAt - now) })}<//>
902
903
  <//>
903
904
  `}
@@ -2,22 +2,20 @@ import { t } from "../i18n.js";
2
2
  import { useEffect, useState } from "react";
3
3
  import { Box } from "ink";
4
4
  import { badgeColor } from "./icons.js";
5
- import { html, Text, theme } from "./kit.js";
5
+ import { html, readable, Text, theme } from "./kit.js";
6
6
 
7
7
  const FRAME_MS = 90;
8
- const FLASH_FRAMES = [5, 7]; // white-out frames before the name lights up in its rank color
8
+ const FLASH_FRAMES = [5, 7]; // flash frames before the name lights up in its rank color
9
9
  const COLOR_FROM = 8;
10
10
  const SPARKS_UNTIL = 22;
11
11
  const SPARKS = ["✦", "·", "✧", "·"];
12
- const GREY = "#4a5058";
13
- const WHITE = "#ffffff";
14
12
  const STEPS = 4; // badge-1 … badge-4 (scripts/make-sounds.js)
15
13
 
16
14
  // Badges won with the same answer ring one after another, each a step higher. The climb starts
17
15
  // over with every answer: a badge won later, on its own, plays the first step again.
18
16
  export const badgeSound = (i) => `badge-${Math.min(i + 1, STEPS)}`;
19
17
 
20
- // A badge just won, as one line under the card: the name comes out of grey, flashes white and
18
+ // A badge just won, as one line under the card: the name comes out of grey, flashes and
21
19
  // lights up in its rank color while a few sparks fly. The badge art lives in /badges.
22
20
  // `delay` staggers several badges won at once; `sound` rings as the line appears.
23
21
  export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0), play }) {
@@ -36,7 +34,7 @@ export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0),
36
34
  }, []);
37
35
 
38
36
  if (frame < 0) return null;
39
- const color = FLASH_FRAMES.includes(frame) ? WHITE : frame >= COLOR_FROM ? badgeColor(id) : GREY;
37
+ const color = FLASH_FRAMES.includes(frame) ? theme.flash : frame >= COLOR_FROM ? readable(badgeColor(id)) : theme.locked;
40
38
  const sparks = frame < SPARKS_UNTIL ? ` ${Array.from({ length: 3 }, (_, i) => SPARKS[(frame + i) % SPARKS.length]).join(" ")}` : "";
41
39
 
42
40
  return html`
package/src/ui/Badges.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t } from "../i18n.js";
2
2
  import { Fragment, useEffect, useState } from "react";
3
3
  import { Box, useInput } from "ink";
4
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
4
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
5
5
  import { badgeColor, BadgeIcon, ICON_WIDTH } from "./icons.js";
6
6
 
7
7
  const COLUMNS = 3;
@@ -12,12 +12,10 @@ const FRAME_MS = 90;
12
12
  const STAGGER = 7; // frames between two badges
13
13
  const FLASH_FRAMES = [2, 4];
14
14
  const LIT_FROM = 5;
15
- const GREY = "#4a5058";
16
15
 
17
16
  // a hidden badge reveals nothing until it's won
18
17
  const secret = () => ({ name: t("badgesScreen.secretName"), desc: t("badgesScreen.secretDesc") });
19
18
  const display = (badge) => (badge.hidden && !badge.unlockedOn ? { ...badge, ...secret() } : badge);
20
- const WHITE = "#ffffff";
21
19
 
22
20
  // where a fresh badge is in its little animation: "waiting" (still looks locked), "flash", or "lit"
23
21
  function phaseOf(freshIndex, frame) {
@@ -85,7 +83,7 @@ export function Badges({ badges, fresh = [], onClose }) {
85
83
  <${BadgeIcon} id=${badge.id} locked=${!badge.unlockedOn || phase === "waiting"} flash=${phase === "flash"} secret=${badge.hidden && !badge.unlockedOn} />
86
84
  <//>
87
85
  <${Box} flexDirection="column" justifyContent="center">
88
- <${Box}><${Text} bold color=${shownUnlocked ? badgeColor(badge.id) : undefined} dimColor=${!shownUnlocked}>${badge.name}<//><//>
86
+ <${Box}><${Text} bold color=${shownUnlocked ? readable(badgeColor(badge.id)) : undefined} dimColor=${!shownUnlocked}>${badge.name}<//><//>
89
87
  <${Box}><${Text}>${badge.desc}<//><//>
90
88
  <${Box}><${Text} dimColor>${badge.unlockedOn ? t("badgesScreen.unlocked", { day: badge.unlockedOn }) : t("badgesScreen.locked")}<//><//>
91
89
  <//>
@@ -100,13 +98,13 @@ export function Badges({ badges, fresh = [], onClose }) {
100
98
  const current = index === selected;
101
99
  const rowPhase = phaseOf(fresh.indexOf(b.id), frame);
102
100
  const shown = b.unlockedOn && rowPhase !== "waiting";
103
- const dotColor = !shown ? undefined : rowPhase === "flash" ? WHITE : badgeColor(b.id);
104
- const nameColor = current ? theme.accent : rowPhase === "flash" ? WHITE : shown ? theme.text : undefined;
101
+ const dotColor = !shown ? undefined : rowPhase === "flash" ? theme.flash : readable(badgeColor(b.id));
102
+ const nameColor = current ? theme.accent : rowPhase === "flash" ? theme.flash : shown ? theme.text : undefined;
105
103
  return html`
106
104
  <${Box} key=${b.id}>
107
105
  <${Text} bold=${current} dimColor=${!current && !shown} wrap="truncate">
108
106
  <${Text} color=${current ? theme.accent : undefined}>${current ? "❯" : " "} <//>
109
- <${Text} color=${dotColor ?? (b.unlockedOn ? GREY : undefined)}>${shown ? "●" : "○"} <//>
107
+ <${Text} color=${dotColor ?? (b.unlockedOn ? theme.locked : undefined)}>${shown ? "●" : "○"} <//>
110
108
  <${Text} color=${nameColor}>${display(b).name}<//>
111
109
  <//>
112
110
  <//>
@@ -2,7 +2,7 @@ import { t } from "../i18n.js";
2
2
  import { Fragment } from "react";
3
3
  import { Box, useInput } from "ink";
4
4
  import { dragonName, elementName, STAGES } from "../progress.js";
5
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
6
6
  import { ELEMENT_COLOR, Mascot } from "./Mascot.js";
7
7
 
8
8
  const requirement = (stage, locked) => (stage.from === 0 ? t("companion.fromStart") : t(locked ? "companion.needsDays" : "companion.days", { count: stage.from }));
@@ -21,7 +21,7 @@ export function Companion({ current, best, element = null, roll = null, onClose
21
21
  <${Text} bold color=${theme.accent}>${t("companion.title")}<//>
22
22
  <${Box} marginTop=${1}>
23
23
  <${Text}>${t("companion.yourDragon")}<//>
24
- <${Text} bold color=${element ? ELEMENT_COLOR[element] : undefined}>${dragonName(current, element)}<//>
24
+ <${Text} bold color=${element ? readable(ELEMENT_COLOR[element]) : undefined}>${dragonName(current, element)}<//>
25
25
  <//>
26
26
  <${Text} dimColor>${element ? `${t("companion.element", { element: elementName(element) })}${roll ? t("companion.rolled", { face: roll.face, day: roll.on }) : ""}` : t("companion.noElement")}<//>
27
27
  <${Box} marginTop=${1}><${Text} dimColor>${t("companion.evolves", { count: best })}<//><//>
@@ -4,7 +4,7 @@ import { html, Text, theme } from "./kit.js";
4
4
 
5
5
  const ROWS = 4;
6
6
  const FRAME_MS = 100;
7
- const COLORS = [theme.accent, theme.good, theme.warn, "#7dd3fc", "#f0abfc"];
7
+ const COLORS = ["accent", "good", "warn", "sky", "pink"]; // theme colors
8
8
  const GLYPHS = ["▪", "▘", "▝", "▖", "▗", "•"];
9
9
 
10
10
  // A short burst of falling pixels over the card, played once when the daily goal lands.
@@ -36,7 +36,7 @@ export function Confetti({ width, onDone }) {
36
36
  for (const p of here) {
37
37
  if (p.col < at) continue; // two particles on one cell: draw the first
38
38
  cells.push(html`<${Text} key=${`g${p.col}`}>${" ".repeat(p.col - at)}<//>`);
39
- cells.push(html`<${Text} key=${`p${p.col}`} color=${p.color}>${p.glyph}<//>`);
39
+ cells.push(html`<${Text} key=${`p${p.col}`} color=${theme[p.color]}>${p.glyph}<//>`);
40
40
  at = p.col + 1;
41
41
  }
42
42
  return html`<${Text} key=${r}>${cells.length ? cells : " "}<//>`;
package/src/ui/DieRoll.js CHANGED
@@ -2,7 +2,7 @@ import { t } from "../i18n.js";
2
2
  import React, { Fragment, useEffect, useState } from "react";
3
3
  import { Box, useInput } from "ink";
4
4
  import { elementName, ELEMENTS } from "../progress.js";
5
- import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
5
+ import { html, KeyHints, readable, Text, theme, usePanelWidth } from "./kit.js";
6
6
  import { ELEMENT_COLOR, Mascot } from "./Mascot.js";
7
7
 
8
8
  const FRAME_MS = 80;
@@ -26,9 +26,9 @@ const BOUNCE = [2, 1, 0, 0, 1, 2, 2, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0];
26
26
 
27
27
  function dieGrid(face, pipColor) {
28
28
  const last = SIZE - 1;
29
- const grid = Array.from({ length: SIZE }, (_, r) => Array.from({ length: SIZE }, (_, c) => ((r === 0 || r === last) && (c === 0 || c === last) ? null : "#f4f4f5")));
30
- for (let r = 1; r < last; r++) grid[r][last] = "#c7c9d1"; // a shaded edge
31
- for (let c = 1; c < last; c++) grid[last][c] = "#c7c9d1";
29
+ const grid = Array.from({ length: SIZE }, (_, r) => Array.from({ length: SIZE }, (_, c) => ((r === 0 || r === last) && (c === 0 || c === last) ? null : theme.dieFace)));
30
+ for (let r = 1; r < last; r++) grid[r][last] = theme.dieEdge; // a shaded edge
31
+ for (let c = 1; c < last; c++) grid[last][c] = theme.dieEdge;
32
32
  for (const pip of FACES[face]) {
33
33
  const [r, c] = PIPS[pip];
34
34
  grid[r][c] = pipColor;
@@ -81,7 +81,7 @@ export function DieRoll({ element, stage = 0, onClose, play = () => {} }) {
81
81
  <${Text} bold color=${theme.warn}>${t("die.title")}<//>
82
82
  <${Box} marginTop=${1} alignItems="flex-end">
83
83
  <${Box} flexDirection="column" marginBottom=${bounce} marginRight=${4}>
84
- <${BigGrid} grid=${dieGrid(face, landed ? color : "#2a2440")} />
84
+ <${BigGrid} grid=${dieGrid(face, landed ? color : theme.diePips)} />
85
85
  <//>
86
86
  <${Box} flexDirection="column">
87
87
  <${Mascot} stage=${stage} face=${revealed ? "happy" : "idle"} flash=${FLASH_FRAMES.includes(frame)} element=${revealed ? element : null} scale=${2} />
@@ -91,7 +91,7 @@ export function DieRoll({ element, stage = 0, onClose, play = () => {} }) {
91
91
  ${revealed
92
92
  ? html`
93
93
  <${Fragment}>
94
- <${Text} bold color=${color}>${t("die.result", { face: result, element: elementName(element) })}<//>
94
+ <${Text} bold color=${readable(color)}>${t("die.result", { face: result, element: elementName(element) })}<//>
95
95
  <${Text} dimColor>${t("die.awakened", { element: elementName(element) })}<//>
96
96
  <//>
97
97
  `