dracosh 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 (54) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +10 -0
  3. package/README.md +78 -2
  4. package/assets/sounds/ask.wav +0 -0
  5. package/assets/sounds/badge.wav +0 -0
  6. package/assets/sounds/close.wav +0 -0
  7. package/assets/sounds/combo.wav +0 -0
  8. package/assets/sounds/correct-0.wav +0 -0
  9. package/assets/sounds/correct-1.wav +0 -0
  10. package/assets/sounds/correct-2.wav +0 -0
  11. package/assets/sounds/correct-3.wav +0 -0
  12. package/assets/sounds/correct-4.wav +0 -0
  13. package/assets/sounds/correct-5.wav +0 -0
  14. package/assets/sounds/evolve.wav +0 -0
  15. package/assets/sounds/goal.wav +0 -0
  16. package/assets/sounds/wrong.wav +0 -0
  17. package/data/tips.json +1362 -0
  18. package/package.json +47 -4
  19. package/src/alerts.js +37 -0
  20. package/src/anki.js +36 -0
  21. package/src/cli.js +116 -0
  22. package/src/commands.js +28 -0
  23. package/src/dates.js +15 -0
  24. package/src/demo.js +11 -0
  25. package/src/diff.js +46 -0
  26. package/src/hint.js +12 -0
  27. package/src/judge.js +57 -0
  28. package/src/parse.js +42 -0
  29. package/src/progress.js +363 -0
  30. package/src/quiet.js +32 -0
  31. package/src/scheduler.js +82 -0
  32. package/src/session.js +129 -0
  33. package/src/settings.js +43 -0
  34. package/src/store.js +61 -0
  35. package/src/tips.js +47 -0
  36. package/src/ui/AnswerInput.js +82 -0
  37. package/src/ui/App.js +369 -0
  38. package/src/ui/Badges.js +64 -0
  39. package/src/ui/Companion.js +60 -0
  40. package/src/ui/Confetti.js +46 -0
  41. package/src/ui/Evolution.js +58 -0
  42. package/src/ui/Hatch.js +99 -0
  43. package/src/ui/Header.js +116 -0
  44. package/src/ui/Mascot.js +128 -0
  45. package/src/ui/Missed.js +52 -0
  46. package/src/ui/Preview.js +181 -0
  47. package/src/ui/Settings.js +65 -0
  48. package/src/ui/Stats.js +108 -0
  49. package/src/ui/Summary.js +34 -0
  50. package/src/ui/Tip.js +25 -0
  51. package/src/ui/icons.js +209 -0
  52. package/src/ui/kit.js +63 -0
  53. package/src/vacation.js +51 -0
  54. package/src/words.js +16 -0
package/src/store.js ADDED
@@ -0,0 +1,61 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { dayKey } from "./dates.js";
5
+ import { itemKey, newToday } from "./scheduler.js";
6
+
7
+ export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
8
+ const STATE_FILE = join(HOME, "state.json");
9
+ const WORDS_FILE = join(HOME, "words.json");
10
+ const SETTINGS_FILE = join(HOME, "settings.json");
11
+
12
+ const emptyState = () => ({ version: 1, items: {}, newToday: { date: "", count: 0 } });
13
+
14
+ async function readJson(file, fallback) {
15
+ try {
16
+ return JSON.parse(await readFile(file, "utf8"));
17
+ } catch (err) {
18
+ if (err.code === "ENOENT") return fallback;
19
+ throw new Error(`Can't read ${file}: ${err.message}`);
20
+ }
21
+ }
22
+
23
+ // Writes are queued (one at a time) and go through write-then-rename: a crash mid-write can't corrupt the file,
24
+ // and two saves in quick succession (an answer and a shown tip, say) can't trip over each other's temp file.
25
+ let writes = Promise.resolve();
26
+
27
+ function writeJson(file, data) {
28
+ const json = JSON.stringify(data, null, 2); // snapshot now: the state object keeps changing
29
+ const job = writes.then(async () => {
30
+ await mkdir(HOME, { recursive: true });
31
+ const tmp = `${file}.tmp`;
32
+ await writeFile(tmp, json);
33
+ await rename(tmp, file);
34
+ });
35
+ writes = job.catch(() => {}); // one failed write must not block the next ones
36
+ return job;
37
+ }
38
+
39
+ export const loadState = () => readJson(STATE_FILE, emptyState());
40
+ export const saveState = (state) => writeJson(STATE_FILE, state);
41
+
42
+ // last successful read from Anki, so the quiz still works while Anki is closed
43
+ export const loadWordsCache = () => readJson(WORDS_FILE, null);
44
+ export const saveWordsCache = (deck, words) => writeJson(WORDS_FILE, { deck, words });
45
+
46
+ export function recordAnswer(state, noteId, direction, entry, now = Date.now()) {
47
+ const key = itemKey(noteId, direction);
48
+ const isNew = !state.items[key];
49
+ const date = dayKey(now);
50
+ state.items[key] = entry;
51
+ if (isNew) state.newToday = { date, count: newToday(state, now) + 1 };
52
+ return state;
53
+ }
54
+
55
+ export const loadSettingsRaw = () => readJson(SETTINGS_FILE, {});
56
+
57
+ // merges into what's on disk, so a one-off CLI flag never gets persisted by accident
58
+ export async function patchSettings(patch) {
59
+ const current = await readJson(SETTINGS_FILE, {});
60
+ await writeJson(SETTINGS_FILE, { ...current, ...patch });
61
+ }
package/src/tips.js ADDED
@@ -0,0 +1,47 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { HOME } from "./store.js";
4
+
5
+ const BUNDLED = JSON.parse(readFileSync(new URL("../data/tips.json", import.meta.url), "utf8"));
6
+ const USER_FILE = join(HOME, "tips.json");
7
+ const SOMETIMES_CHANCE = 1 / 3;
8
+
9
+ // Your own tips: ~/.dracosh/tips.json, an array of { "cat": "...", "text": "..." } (the id is optional).
10
+ // A broken or missing file just means no extra tips.
11
+ export function loadUserTips(file = USER_FILE) {
12
+ let raw;
13
+ try {
14
+ raw = JSON.parse(readFileSync(file, "utf8"));
15
+ } catch {
16
+ return [];
17
+ }
18
+ if (!Array.isArray(raw)) return [];
19
+ return raw
20
+ .filter((tip) => tip && typeof tip.text === "string" && tip.text.trim())
21
+ .map((tip, i) => ({ id: `u-${tip.id ?? i + 1}`, cat: typeof tip.cat === "string" && tip.cat ? tip.cat : "My tips", text: tip.text.trim() }));
22
+ }
23
+
24
+ export const allTips = () => [...BUNDLED, ...loadUserTips()];
25
+
26
+ // "always" shows a tip on every wait, "sometimes" on about one in three
27
+ export function shouldShowTip(mode, random = Math.random) {
28
+ return mode === "always" || (mode === "sometimes" && random() < SOMETIMES_CHANCE);
29
+ }
30
+
31
+ // Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen.
32
+ export function createTipDeck({ state, tips = allTips(), random = Math.random }) {
33
+ return {
34
+ next() {
35
+ const seen = new Set(state.tips?.seen ?? []);
36
+ let fresh = tips.filter((tip) => !seen.has(tip.id));
37
+ if (!fresh.length) {
38
+ seen.clear();
39
+ fresh = tips;
40
+ }
41
+ const tip = fresh[Math.floor(random() * fresh.length)];
42
+ seen.add(tip.id);
43
+ state.tips = { seen: [...seen] };
44
+ return tip;
45
+ }
46
+ };
47
+ }
@@ -0,0 +1,82 @@
1
+ import { useState } from "react";
2
+ import { Box, Text, useInput } from "ink";
3
+ import { COMMANDS, matchCommands } from "../commands.js";
4
+ import { html, theme } from "./kit.js";
5
+
6
+ function Palette({ matches, selected }) {
7
+ return html`
8
+ <${Box} flexDirection="column" marginTop=${1}>
9
+ ${matches.map(
10
+ (command, i) => html`
11
+ <${Box} key=${command.name}>
12
+ <${Text} color=${i === selected ? theme.accent : undefined} bold=${i === selected} dimColor=${i !== selected}>${i === selected ? "❯" : " "} ${command.name.padEnd(12)}<//>
13
+ <${Text} dimColor>${command.hint}<//>
14
+ <//>
15
+ `
16
+ )}
17
+ <//>
18
+ `;
19
+ }
20
+
21
+ // everything after the command name: "/snooze 30m" → "30m"
22
+ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
23
+
24
+ // Answer line with a movable cursor (←/→, Ctrl+A/E). Typing "/" opens a command palette:
25
+ // ↑/↓ choose, Tab completes, Enter runs.
26
+ // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
27
+ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, commands = COMMANDS, initial = "", commandOnly = false }) {
28
+ const [value, setValue] = useState(initial);
29
+ const [cursor, setCursor] = useState(initial.length);
30
+ const [selected, setSelected] = useState(0);
31
+ const matches = value.startsWith("/") ? matchCommands(value, commands) : [];
32
+ const pick = Math.min(selected, Math.max(matches.length - 1, 0));
33
+
34
+ const edit = (next, at = next.length) => {
35
+ setValue(next);
36
+ setCursor(Math.max(0, Math.min(at, next.length)));
37
+ setSelected(0);
38
+ onEdit?.();
39
+ };
40
+
41
+ useInput((input, key) => {
42
+ if (key.escape) return commandOnly ? onCancel() : value ? edit("") : onExit();
43
+ if (key.return) {
44
+ if (!value.startsWith("/")) return onSubmit(value);
45
+ const [token, ...rest] = value.trim().split(/\s+/);
46
+ edit("");
47
+ return onCommand(matches[pick]?.name ?? token, rest.join(" "));
48
+ }
49
+ if (key.tab) return matches.length ? edit(`${matches[pick].name}${args(value) ? ` ${args(value)}` : ""}`) : undefined;
50
+ if (key.upArrow) return setSelected(Math.max(0, pick - 1));
51
+ if (key.downArrow) return setSelected(Math.min(matches.length - 1, pick + 1));
52
+ if (key.leftArrow) return setCursor((c) => Math.max(0, c - 1));
53
+ if (key.rightArrow) return setCursor((c) => Math.min(value.length, c + 1));
54
+ if (key.backspace || key.delete) {
55
+ if (commandOnly && value.length <= 1) return onCancel();
56
+ if (cursor === 0) return;
57
+ return edit(value.slice(0, cursor - 1) + value.slice(cursor), cursor - 1);
58
+ }
59
+ if (key.ctrl && input === "u") return commandOnly ? onCancel() : edit("");
60
+ if (key.ctrl && input === "a") return setCursor(0);
61
+ if (key.ctrl && input === "e") return setCursor(value.length);
62
+ if (key.ctrl || key.meta || key.pageUp || key.pageDown) return;
63
+ if (input) {
64
+ const typed = input.replace(/[\r\n]+/g, " ");
65
+ edit(value.slice(0, cursor) + typed + value.slice(cursor), cursor + typed.length);
66
+ }
67
+ });
68
+
69
+ const before = value.slice(0, cursor);
70
+ const at = value[cursor] ?? " ";
71
+ const after = value.slice(cursor + 1);
72
+ return html`
73
+ <${Box} flexDirection="column">
74
+ <${Box}>
75
+ <${Text} color=${theme.accent}>❯ <//>
76
+ <${Text}>${before}<${Text} inverse>${at}<//>${after}<//>
77
+ <//>
78
+ ${matches.length > 0 && html`<${Palette} matches=${matches} selected=${pick} />`}
79
+ ${value.startsWith("/") && matches.length === 0 && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>unknown command<//><//>`}
80
+ <//>
81
+ `;
82
+ }
package/src/ui/App.js ADDED
@@ -0,0 +1,369 @@
1
+ import { Fragment, useCallback, useEffect, useRef, useState } from "react";
2
+ import { Box, Text, useApp, useInput, useStdout } from "ink";
3
+ import { commandsFor } from "../commands.js";
4
+ import { diffChars } from "../diff.js";
5
+ import { AnswerInput } from "./AnswerInput.js";
6
+ import { Header } from "./Header.js";
7
+ import { html, Bar, PANEL_WIDTH, theme, Typewriter } from "./kit.js";
8
+ import { hintTarget, makeHint } from "../hint.js";
9
+ import { formatClock, inQuietHours, parseSnooze, quietEnd } from "../quiet.js";
10
+ import { shouldShowTip } from "../tips.js";
11
+ import { Badges } from "./Badges.js";
12
+ import { Companion } from "./Companion.js";
13
+ import { Confetti } from "./Confetti.js";
14
+ import { Evolution } from "./Evolution.js";
15
+ import { Hatch } from "./Hatch.js";
16
+ import { Missed } from "./Missed.js";
17
+ import { Settings } from "./Settings.js";
18
+ import { Stats } from "./Stats.js";
19
+ import { Summary } from "./Summary.js";
20
+ import { Tip } from "./Tip.js";
21
+
22
+ const SPINNER = ["▘", "▝", "▗", "▖"]; // a rotating pixel, in keeping with the sprite work
23
+ const TICK_MS = 250; // the steady redraw: slow enough to stay idle for hours, fast enough for the spinner
24
+ const SLEEP_AFTER_MS = 3 * 60_000; // no key pressed for this long while waiting → the dragon dozes off
25
+ const PAUSED_SLEEP_AFTER_MS = 15_000; // during snooze or quiet hours it nods off again much sooner
26
+ const CHEER_STYLE = {
27
+ goal: { icon: "★", color: theme.good },
28
+ evolve: { icon: "▲", color: theme.accent },
29
+ badge: { icon: "✦", color: theme.warn },
30
+ combo: { icon: "»", color: theme.warn }
31
+ };
32
+
33
+ function clock(ms) {
34
+ const total = Math.max(0, Math.ceil(ms / 1000));
35
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
36
+ }
37
+
38
+ // your answer with every letter judged: green lined up with the expected word, red didn't
39
+ function AnswerDiff({ given, closest }) {
40
+ const parts = diffChars(given, closest);
41
+ return html`
42
+ <${Text}>
43
+ <${Text} dimColor>you wrote <//>
44
+ ${parts.map((p, i) => html`<${Text} key=${i} color=${p.ok ? theme.good : theme.bad} bold=${!p.ok}>${p.ch}<//>`)}
45
+ <//>
46
+ `;
47
+ }
48
+
49
+ function Verdict({ outcome, question }) {
50
+ if (outcome.result === "skipped") return html`<${Text} dimColor>– skipped<//>`;
51
+ const wrong = outcome.result === "wrong";
52
+ const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
53
+ return html`
54
+ <${Box} flexDirection="column">
55
+ <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${question.expected.join(", ")}${outcome.result === "typo" ? " (close enough)" : ""}<//>
56
+ ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
57
+ ${question.word.example && html`<${Text} dimColor>${question.word.example}<//>`}
58
+ ${(outcome.hinted || outcome.overruled) &&
59
+ html`
60
+ <${Box} marginTop=${1} flexDirection="column">
61
+ ${outcome.hinted && html`<${Text} dimColor>hint used · the card stays in its box<//>`}
62
+ ${outcome.overruled && html`<${Text} color=${theme.good}>counted as correct · "${outcome.accepted}" is accepted from now on<//>`}
63
+ <//>
64
+ `}
65
+ <//>
66
+ `;
67
+ }
68
+
69
+ function Cheers({ cheers }) {
70
+ return html`
71
+ <${Box} flexDirection="column" paddingX=${1} marginTop=${1}>
72
+ ${cheers.map((cheer, i) => {
73
+ const style = CHEER_STYLE[cheer.kind] ?? CHEER_STYLE.combo;
74
+ return html`<${Text} key=${i} color=${style.color} bold>${style.icon} ${cheer.text}<//>`;
75
+ })}
76
+ <//>
77
+ `;
78
+ }
79
+
80
+ // The card's top edge with the direction ("EN → PL") set into its right corner, like a title on the border
81
+ function CardTop({ label, width, color }) {
82
+ const tag = ` ${label} `;
83
+ const tail = 2;
84
+ const dashes = Math.max(0, width - 2 - tag.length - tail);
85
+ return html`
86
+ <${Text}>
87
+ <${Text} color=${color}>╭${"─".repeat(dashes)}<//>
88
+ <${Text} dimColor>${tag}<//>
89
+ <${Text} color=${color}>${"─".repeat(tail)}╮<//>
90
+ <//>
91
+ `;
92
+ }
93
+
94
+ function TipBox({ tip, width }) {
95
+ return html`
96
+ <${Box} flexDirection="column" paddingX=${1} marginTop=${2} width=${width}>
97
+ <${Box} marginBottom=${1}><${Text} color=${theme.accent}>tip · ${tip.cat}<//><//>
98
+ <${Typewriter} text=${tip.text} dimColor />
99
+ <//>
100
+ `;
101
+ }
102
+
103
+ export function App({ session, deck, initialSettings, alerts, persistSettings, onExit }) {
104
+ const { exit: exitApp } = useApp();
105
+ const exit = onExit ?? exitApp; // the preview gallery runs the quiz as a scene and takes quitting back to its menu
106
+ const { stdout } = useStdout();
107
+ const [settings, setSettings] = useState(initialSettings);
108
+ // quiz | settings | stats | badges | companion | tip | missed | evolve | summary | hatch
109
+ const [screen, setScreen] = useState(() => (session.isFirstRun() ? "hatch" : "quiz"));
110
+ const [tip, setTip] = useState(null);
111
+ const [phase, setPhase] = useState("loading"); // loading | asking | waiting
112
+ const [question, setQuestion] = useState(null);
113
+ const [outcome, setOutcome] = useState(null);
114
+ const [problem, setProblem] = useState("");
115
+ const [commandMode, setCommandMode] = useState(false); // typing a "/" command between questions
116
+ const [notice, setNotice] = useState("");
117
+ const [hintLevel, setHintLevel] = useState(0);
118
+ const [snoozeUntil, setSnoozeUntil] = useState(0);
119
+ const [nextAt, setNextAt] = useState(0);
120
+ const [now, setNow] = useState(Date.now());
121
+ const [petEvent, setPetEvent] = useState(null); // { kind: "jump" | "shake", at } → a little hop or head-shake
122
+ const [confetti, setConfetti] = useState(false);
123
+ const [evolution, setEvolution] = useState(null); // { from, to, name } while the ceremony plays
124
+ const [lastActive, setLastActive] = useState(Date.now()); // last key press or new question: the dragon sleeps after a long gap
125
+ const busy = useRef(false);
126
+ const asleepRef = useRef(false);
127
+ const bestCombo = useRef(0);
128
+ const settingsRef = useRef(settings);
129
+ settingsRef.current = settings;
130
+ const snoozeRef = useRef(0);
131
+ snoozeRef.current = snoozeUntil;
132
+
133
+ // when questions may resume: the end of a snooze or of quiet hours, whichever is later; 0 = not paused
134
+ const pauseEnd = (t) => {
135
+ const quiet = settingsRef.current.quiet;
136
+ return Math.max(snoozeRef.current > t ? snoozeRef.current : 0, inQuietHours(t, quiet) ? quietEnd(t, quiet) : 0);
137
+ };
138
+
139
+ const waitForNext = useCallback(() => {
140
+ setNextAt(Date.now() + settingsRef.current.everyMs);
141
+ setPhase("waiting");
142
+ setTip(shouldShowTip(settingsRef.current.tips) ? session.nextTip() : null);
143
+ }, [session]);
144
+
145
+ const ask = useCallback(async () => {
146
+ setLastActive(Date.now());
147
+ setPhase("loading");
148
+ setProblem("");
149
+ setNotice("");
150
+ setHintLevel(0);
151
+ setCommandMode(false);
152
+ try {
153
+ const next = await session.next();
154
+ setQuestion(next);
155
+ setOutcome(null);
156
+ setPhase("asking");
157
+ } catch (err) {
158
+ setProblem(err.message);
159
+ waitForNext();
160
+ }
161
+ }, [session, waitForNext]);
162
+
163
+ useEffect(() => {
164
+ ask();
165
+ }, [ask]);
166
+
167
+ // one steady clock for the whole app: spinner, countdown, mascot blink and combo flicker
168
+ useEffect(() => {
169
+ const id = setInterval(() => setNow(Date.now()), TICK_MS);
170
+ return () => clearInterval(id);
171
+ }, []);
172
+
173
+ useEffect(() => {
174
+ if (phase !== "waiting" || screen === "summary" || screen === "evolve") return;
175
+ if (now >= nextAt && !pauseEnd(now)) {
176
+ alerts.ask();
177
+ ask();
178
+ }
179
+ }, [now, phase, nextAt, screen, ask, alerts]);
180
+
181
+ // quitting goes through the session summary when there is anything to sum up
182
+ const requestExit = useCallback(() => {
183
+ if (session.totals.asked > 0) return setScreen("summary");
184
+ exit();
185
+ }, [session, exit]);
186
+
187
+ // any key wakes a sleeping dragon, with a little start
188
+ useInput(() => {
189
+ if (asleepRef.current) setPetEvent({ kind: "jump", at: Date.now() });
190
+ setLastActive(Date.now());
191
+ });
192
+
193
+ useInput((input, key) => {
194
+ if (screen !== "quiz" || phase !== "waiting" || commandMode) return;
195
+ if (input === "/") return setCommandMode(true);
196
+ if (key.escape || input === "q") return requestExit();
197
+ if (key.return) ask();
198
+ });
199
+
200
+ const clearProblem = useCallback(() => {
201
+ setProblem("");
202
+ setNotice("");
203
+ }, []);
204
+
205
+ // every graded answer: sound, a hop or a shake, confetti on the daily goal, the evolution ceremony
206
+ function celebrate(result) {
207
+ alerts.result(result.result, { cheers: result.cheers.map((c) => c.kind), combo: result.combo });
208
+ bestCombo.current = Math.max(bestCombo.current, result.combo);
209
+ setPetEvent({ kind: result.result === "wrong" ? "shake" : "jump", at: Date.now() });
210
+ if (result.cheers.some((c) => c.kind === "goal")) setConfetti(true);
211
+ if (result.cheers.some((c) => c.kind === "evolve")) {
212
+ const companion = session.stats().companion;
213
+ setEvolution({ from: Math.max(0, companion.index - 1), to: companion.index, name: companion.name });
214
+ setScreen("evolve");
215
+ }
216
+ }
217
+
218
+ function runCommand(name, args = "") {
219
+ setCommandMode(false);
220
+ if (name === "/quit") return requestExit();
221
+ if (name === "/settings") return setScreen("settings");
222
+ if (name === "/stats") return setScreen("stats");
223
+ if (name === "/badges") return setScreen("badges");
224
+ if (name === "/companion") return setScreen("companion");
225
+ if (name === "/tip") return setScreen("tip");
226
+ if (name === "/missed") return setScreen("missed");
227
+ if (name === "/hint" && phase === "asking") return setHintLevel((level) => level + 1);
228
+ if (name === "/vacation") {
229
+ return session
230
+ .vacation(args)
231
+ .then(setNotice)
232
+ .catch((err) => setProblem(err.message));
233
+ }
234
+ if (name === "/snooze") {
235
+ const length = parseSnooze(args);
236
+ if (length === null) return setProblem("Try /snooze 30m, /snooze 2h or /snooze off");
237
+ if (length === "off") {
238
+ setSnoozeUntil(0);
239
+ return setNotice("Snooze off: questions are back");
240
+ }
241
+ setSnoozeUntil(Date.now() + length);
242
+ return phase === "asking" ? setNotice(`Questions paused until ${formatClock(Date.now() + length)}`) : undefined; // while waiting, the status line says it
243
+ }
244
+ if (name === "/skip") {
245
+ setOutcome({ result: "skipped", cheers: [] });
246
+ return waitForNext();
247
+ }
248
+ if (name === "/correct" && session.canOverrule()) {
249
+ return session
250
+ .overrule()
251
+ .then((result) => {
252
+ setOutcome(result);
253
+ celebrate(result);
254
+ })
255
+ .catch((err) => setProblem(`Couldn't save progress: ${err.message}`));
256
+ }
257
+ setProblem(`Unknown command ${name}`);
258
+ }
259
+
260
+ function changeSettings(patch) {
261
+ const previous = settingsRef.current;
262
+ const next = { ...previous, ...patch };
263
+ settingsRef.current = next;
264
+ setSettings(next);
265
+ alerts.configure({ sound: next.sound, volume: next.volume });
266
+ persistSettings(patch).catch(() => {});
267
+ if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
268
+ if (patch.volume !== undefined || patch.sound === true) alerts.play("correct-0"); // audible preview
269
+ }
270
+
271
+ async function submit(raw) {
272
+ const text = raw.trim();
273
+ if (!text || busy.current) return;
274
+ busy.current = true;
275
+ try {
276
+ const result = await session.answer(question, text, { hinted: hintLevel > 0 });
277
+ setOutcome(result);
278
+ celebrate(result);
279
+ } catch (err) {
280
+ setProblem(`Couldn't save progress: ${err.message}`);
281
+ } finally {
282
+ busy.current = false;
283
+ waitForNext();
284
+ }
285
+ }
286
+
287
+ const width = Math.min((stdout?.columns ?? PANEL_WIDTH + 2) - 2, PANEL_WIDTH);
288
+ const border = !outcome ? theme.accent : outcome.result === "wrong" ? theme.bad : outcome.result === "skipped" ? "gray" : theme.good;
289
+ const pausedUntil = pauseEnd(now);
290
+ const tick = Math.floor(now / TICK_MS);
291
+ const frame = SPINNER[tick % SPINNER.length];
292
+ const stats = session.stats();
293
+ // mood: how the last answer went, otherwise whether today's goal is done (Header adds the blinking)
294
+ const resting = stats.today.goalMet ? "smile" : "idle";
295
+ const face = outcome?.result === "wrong" ? "sad" : outcome && outcome.result !== "skipped" ? "happy" : resting;
296
+ // strictly boolean: a bare 0 leaking into the markup crashes Ink ("Text string must be rendered inside <Text>")
297
+ const paused = pausedUntil > nextAt || (now >= nextAt && pausedUntil > 0);
298
+ // asleep: no key pressed for a while, whether a question is open or not; a key always wakes it,
299
+ // even during snooze or quiet hours (where it nods off again sooner)
300
+ const idleLimit = phase === "waiting" && pausedUntil > 0 ? PAUSED_SLEEP_AFTER_MS : SLEEP_AFTER_MS;
301
+ const asleep = phase !== "loading" && now - lastActive > idleLimit;
302
+ asleepRef.current = asleep;
303
+
304
+ if (screen === "hatch")
305
+ return html`<${Box} flexDirection="column" marginY=${1}><${Hatch} play=${alerts.play} onDone=${() => {
306
+ session.markHatched().catch(() => {});
307
+ setScreen("quiz");
308
+ }} /><//>`;
309
+ if (screen === "summary") return html`<${Box} flexDirection="column" marginY=${1}><${Summary} stats=${stats} totals=${session.totals} bestCombo=${bestCombo.current} onDone=${exit} /><//>`;
310
+ if (screen === "evolve" && evolution)
311
+ return html`<${Box} flexDirection="column" marginY=${1}><${Evolution} ...${evolution} onClose=${() => {
312
+ setEvolution(null);
313
+ setScreen("quiz");
314
+ }} /><//>`;
315
+ if (screen === "stats") return html`<${Box} flexDirection="column" marginY=${1}><${Stats} stats=${stats} getMonth=${session.month} onClose=${() => setScreen("quiz")} /><//>`;
316
+ if (screen === "companion") return html`<${Box} flexDirection="column" marginY=${1}><${Companion} current=${stats.companion.index} best=${stats.streak.best} onClose=${() => setScreen("quiz")} /><//>`;
317
+ if (screen === "tip") return html`<${Box} flexDirection="column" marginY=${1}><${Tip} nextTip=${session.nextTip} onClose=${() => setScreen("quiz")} /><//>`;
318
+ if (screen === "missed") return html`<${Box} flexDirection="column" marginY=${1}><${Missed} getMissed=${session.missed} onClose=${() => setScreen("quiz")} /><//>`;
319
+ if (screen === "badges") return html`<${Box} flexDirection="column" marginY=${1}><${Badges} badges=${stats.badges} onClose=${() => setScreen("quiz")} /><//>`;
320
+
321
+ return html`
322
+ <${Box} flexDirection="column" marginY=${1}>
323
+ <${Header} deck=${deck} everyMs=${settings.everyMs} wordCount=${question?.wordCount} stats=${stats} combo=${session.totals.combo} face=${face} event=${petEvent} tick=${tick} asleep=${asleep} />
324
+ <${Box} marginTop=${1} flexDirection="column">
325
+ ${screen === "settings"
326
+ ? html`<${Settings} settings=${settings} onChange=${changeSettings} onClose=${() => setScreen("quiz")} />`
327
+ : html`
328
+ <${Fragment}>
329
+ ${question &&
330
+ html`
331
+ <${Box} flexDirection="column" width=${width}>
332
+ <${CardTop} label=${question.label} width=${width} color=${border} />
333
+ <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${border} paddingX=${2} paddingTop=${1}>
334
+ <${Text} bold>${question.prompt}<//>
335
+ ${phase === "asking" && hintLevel > 0 && html`<${Text} dimColor>hint ${makeHint(hintTarget(question.expected), hintLevel)}<//>`}
336
+ <${Box} marginTop=${1} flexDirection="column">
337
+ ${phase === "asking" && html`<${AnswerInput} key=${question.word.noteId + question.direction} onSubmit=${submit} onCommand=${runCommand} onExit=${requestExit} onEdit=${clearProblem} commands=${commandsFor({ phase: "asking" })} />`}
338
+ ${phase !== "asking" && outcome && html`<${Verdict} outcome=${outcome} question=${question} />`}
339
+ <//>
340
+ <//>
341
+ <//>
342
+ `}
343
+ ${confetti && html`<${Confetti} width=${width} onDone=${() => setConfetti(false)} />`}
344
+ ${outcome?.cheers?.length > 0 && html`<${Cheers} cheers=${outcome.cheers} />`}
345
+ ${phase === "waiting" && tip && html`<${TipBox} tip=${tip} width=${width} />`}
346
+ <${Box} paddingX=${1} marginTop=${1} flexDirection="column">
347
+ ${question?.cached && html`<${Text} color=${theme.warn}>Anki is offline, using the saved word list<//>`}
348
+ ${problem && html`<${Text} color=${theme.bad}>${problem}<//>`}
349
+ ${phase === "loading" && html`<${Text} dimColor>${frame} loading…<//>`}
350
+ ${notice && html`<${Text} color=${theme.accent}>${notice}<//>`}
351
+ ${phase === "waiting" && paused && html`<${Text} dimColor>paused until ${formatClock(pausedUntil)}${inQuietHours(now, settings.quiet) ? " (quiet hours)" : ""}<//>`}
352
+ ${phase === "waiting" &&
353
+ !paused &&
354
+ html`
355
+ <${Text}>
356
+ <${Text} dimColor>${frame} <//>
357
+ <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color="#6b5e8a" />
358
+ <${Text} dimColor> next word in ${clock(nextAt - now)}<//>
359
+ <//>
360
+ `}
361
+ ${phase === "waiting" && commandMode && html`<${AnswerInput} commandOnly initial="/" commands=${commandsFor({ phase: "waiting", canOverrule: session.canOverrule() })} onCommand=${runCommand} onCancel=${() => setCommandMode(false)} onEdit=${clearProblem} />`}
362
+ ${phase !== "loading" && !commandMode && html`<${Text} dimColor>${phase === "asking" ? "enter submit · / commands · esc quit" : `${session.canOverrule() ? "/correct if you were right · " : ""}enter ask now · / commands · q quit`}<//>`}
363
+ <//>
364
+ <//>
365
+ `}
366
+ <//>
367
+ <//>
368
+ `;
369
+ }
@@ -0,0 +1,64 @@
1
+ import { Fragment, useState } from "react";
2
+ import { Box, Text, useInput } from "ink";
3
+ import { html, PANEL_WIDTH, theme } from "./kit.js";
4
+ import { BadgeIcon, ICON_WIDTH } from "./icons.js";
5
+
6
+ // Two columns of badges with a pixel-icon preview of the selected one.
7
+ // ↑/↓ walk a column, ←/→ jump between columns, esc closes.
8
+ export function Badges({ badges, onClose }) {
9
+ const [selected, setSelected] = useState(0);
10
+ const rows = Math.ceil(badges.length / 2);
11
+ useInput((input, key) => {
12
+ if (key.escape || input === "q") return onClose();
13
+ if (key.upArrow) return setSelected((s) => Math.max(0, s - 1));
14
+ if (key.downArrow) return setSelected((s) => Math.min(badges.length - 1, s + 1));
15
+ if (key.leftArrow) return setSelected((s) => Math.max(0, s - rows));
16
+ if (key.rightArrow) return setSelected((s) => Math.min(badges.length - 1, s + rows));
17
+ });
18
+
19
+ const unlocked = badges.filter((b) => b.unlockedOn).length;
20
+ const badge = badges[selected];
21
+
22
+ return html`
23
+ <${Fragment}>
24
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${PANEL_WIDTH}>
25
+ <${Box}>
26
+ <${Text} bold color=${theme.accent}>Badges<//>
27
+ <${Text} dimColor> ${unlocked}/${badges.length}<//>
28
+ <//>
29
+
30
+ <${Box} marginTop=${1}>
31
+ <${Box} flexDirection="column" width=${ICON_WIDTH + 3}>
32
+ <${BadgeIcon} id=${badge.id} locked=${!badge.unlockedOn} />
33
+ <//>
34
+ <${Box} flexDirection="column" justifyContent="center">
35
+ <${Box}><${Text} bold color=${badge.unlockedOn ? theme.warn : undefined} dimColor=${!badge.unlockedOn}>${badge.name}<//><//>
36
+ <${Box}><${Text}>${badge.desc}<//><//>
37
+ <${Box}><${Text} dimColor>${badge.unlockedOn ? `unlocked ${badge.unlockedOn}` : "still locked"}<//><//>
38
+ <//>
39
+ <//>
40
+
41
+ <${Box} marginTop=${1}>
42
+ ${[0, 1].map(
43
+ (column) => html`
44
+ <${Box} key=${column} flexDirection="column" width=${column === 0 ? 34 : undefined}>
45
+ ${badges.slice(column * rows, column * rows + rows).map((b, r) => {
46
+ const index = column * rows + r;
47
+ const current = index === selected;
48
+ return html`
49
+ <${Box} key=${b.id}>
50
+ <${Text} color=${current ? theme.accent : b.unlockedOn ? theme.warn : undefined} bold=${current} dimColor=${!current && !b.unlockedOn}>
51
+ ${current ? "❯" : " "} ${b.unlockedOn ? "●" : "○"} ${b.name}
52
+ <//>
53
+ <//>
54
+ `;
55
+ })}
56
+ <//>
57
+ `
58
+ )}
59
+ <//>
60
+ <//>
61
+ <${Box} paddingX=${1}><${Text} dimColor>↑/↓ browse · ←/→ column · esc back<//><//>
62
+ <//>
63
+ `;
64
+ }