dracosh 0.0.0-stage → 0.2.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 (70) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +10 -0
  3. package/README.md +100 -2
  4. package/assets/sounds/ask.wav +0 -0
  5. package/assets/sounds/badge-1.wav +0 -0
  6. package/assets/sounds/badge-2.wav +0 -0
  7. package/assets/sounds/badge-3.wav +0 -0
  8. package/assets/sounds/badge-4.wav +0 -0
  9. package/assets/sounds/close.wav +0 -0
  10. package/assets/sounds/combo.wav +0 -0
  11. package/assets/sounds/correct-0.wav +0 -0
  12. package/assets/sounds/correct-1.wav +0 -0
  13. package/assets/sounds/correct-2.wav +0 -0
  14. package/assets/sounds/correct-3.wav +0 -0
  15. package/assets/sounds/correct-4.wav +0 -0
  16. package/assets/sounds/correct-5.wav +0 -0
  17. package/assets/sounds/evolve.wav +0 -0
  18. package/assets/sounds/goal.wav +0 -0
  19. package/assets/sounds/wrong.wav +0 -0
  20. package/data/tips.json +32 -0
  21. package/package.json +47 -4
  22. package/src/alerts.js +38 -0
  23. package/src/anki.js +36 -0
  24. package/src/backup.js +95 -0
  25. package/src/cli.js +197 -0
  26. package/src/commands.js +28 -0
  27. package/src/dates.js +15 -0
  28. package/src/demo.js +11 -0
  29. package/src/diff.js +46 -0
  30. package/src/hint.js +12 -0
  31. package/src/judge.js +78 -0
  32. package/src/library.js +127 -0
  33. package/src/lock.js +63 -0
  34. package/src/manage.js +75 -0
  35. package/src/parse.js +42 -0
  36. package/src/pause.js +23 -0
  37. package/src/progress.js +455 -0
  38. package/src/quiet.js +32 -0
  39. package/src/scheduler.js +94 -0
  40. package/src/session.js +227 -0
  41. package/src/settings.js +38 -0
  42. package/src/starter.js +38 -0
  43. package/src/store.js +100 -0
  44. package/src/tips.js +30 -0
  45. package/src/ui/AddCard.js +172 -0
  46. package/src/ui/AnswerInput.js +85 -0
  47. package/src/ui/App.js +509 -0
  48. package/src/ui/BadgeUnlock.js +50 -0
  49. package/src/ui/Badges.js +122 -0
  50. package/src/ui/Choice.js +33 -0
  51. package/src/ui/Companion.js +45 -0
  52. package/src/ui/Confetti.js +46 -0
  53. package/src/ui/Decks.js +49 -0
  54. package/src/ui/DieRoll.js +104 -0
  55. package/src/ui/Evolution.js +59 -0
  56. package/src/ui/Hatch.js +100 -0
  57. package/src/ui/Header.js +117 -0
  58. package/src/ui/Help.js +68 -0
  59. package/src/ui/Mascot.js +178 -0
  60. package/src/ui/Missed.js +53 -0
  61. package/src/ui/Preview.js +256 -0
  62. package/src/ui/Reset.js +72 -0
  63. package/src/ui/Settings.js +69 -0
  64. package/src/ui/Stats.js +111 -0
  65. package/src/ui/Summary.js +41 -0
  66. package/src/ui/TheOne.js +121 -0
  67. package/src/ui/icons.js +341 -0
  68. package/src/ui/kit.js +120 -0
  69. package/src/vacation.js +56 -0
  70. package/src/words.js +23 -0
@@ -0,0 +1,85 @@
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: "/pause 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
+ // `plain` is a text field with no commands at all ("and/or" is just text there).
28
+ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
29
+ const [value, setValue] = useState(initial);
30
+ const [cursor, setCursor] = useState(initial.length);
31
+ const [selected, setSelected] = useState(0);
32
+ const isCommand = !plain && value.startsWith("/");
33
+ const matches = isCommand ? matchCommands(value, commands) : [];
34
+ const pick = Math.min(selected, Math.max(matches.length - 1, 0));
35
+
36
+ const edit = (next, at = next.length) => {
37
+ setValue(next);
38
+ setCursor(Math.max(0, Math.min(at, next.length)));
39
+ setSelected(0);
40
+ onEdit?.();
41
+ };
42
+
43
+ useInput((input, key) => {
44
+ if (key.escape) return commandOnly ? onCancel() : value ? edit("") : onExit();
45
+ if (key.return) {
46
+ // no command starts like this: on a card it's simply the answer (some answers begin with "/")
47
+ if (!isCommand || (!matches.length && !commandOnly)) return onSubmit(value);
48
+ const [token, ...rest] = value.trim().split(/\s+/);
49
+ edit("");
50
+ return onCommand(matches[pick]?.name ?? token, rest.join(" "));
51
+ }
52
+ if (key.tab) return matches.length ? edit(`${matches[pick].name}${args(value) ? ` ${args(value)}` : ""}`) : undefined;
53
+ if (key.upArrow) return setSelected(Math.max(0, pick - 1));
54
+ if (key.downArrow) return setSelected(Math.min(matches.length - 1, pick + 1));
55
+ if (key.leftArrow) return setCursor((c) => Math.max(0, c - 1));
56
+ if (key.rightArrow) return setCursor((c) => Math.min(value.length, c + 1));
57
+ if (key.backspace || key.delete) {
58
+ if (commandOnly && value.length <= 1) return onCancel();
59
+ if (cursor === 0) return;
60
+ return edit(value.slice(0, cursor - 1) + value.slice(cursor), cursor - 1);
61
+ }
62
+ if (key.ctrl && input === "u") return commandOnly ? onCancel() : edit("");
63
+ if (key.ctrl && input === "a") return setCursor(0);
64
+ if (key.ctrl && input === "e") return setCursor(value.length);
65
+ if (key.ctrl || key.meta || key.pageUp || key.pageDown) return;
66
+ if (input) {
67
+ const typed = input.replace(/[\r\n]+/g, " ");
68
+ edit(value.slice(0, cursor) + typed + value.slice(cursor), cursor + typed.length);
69
+ }
70
+ });
71
+
72
+ const before = value.slice(0, cursor);
73
+ const at = value[cursor] ?? " ";
74
+ const after = value.slice(cursor + 1);
75
+ return html`
76
+ <${Box} flexDirection="column">
77
+ <${Box}>
78
+ <${Text} color=${theme.accent}>❯ <//>
79
+ <${Text}>${before}<${Text} inverse>${at}<//>${after}<//>
80
+ <//>
81
+ ${matches.length > 0 && html`<${Palette} matches=${matches} selected=${pick} />`}
82
+ ${isCommand && matches.length === 0 && html`<${Box} marginTop=${1}>${commandOnly ? html`<${Text} color=${theme.bad}>unknown command<//>` : html`<${Text} dimColor>no command like that · enter sends it as your answer<//>`}<//>`}
83
+ <//>
84
+ `;
85
+ }
package/src/ui/App.js ADDED
@@ -0,0 +1,509 @@
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 { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, theme, Typewriter, usePanelWidth } from "./kit.js";
8
+ import { hintTarget, makeHint } from "../hint.js";
9
+ import { formatClock, inQuietHours, quietEnd } from "../quiet.js";
10
+ import { startOfTomorrow } from "../scheduler.js";
11
+ import { formatDay } from "../vacation.js";
12
+ import { dayKey } from "../dates.js";
13
+ import { shouldShowTip } from "../tips.js";
14
+ import { Badges } from "./Badges.js";
15
+ import { Companion } from "./Companion.js";
16
+ import { Confetti } from "./Confetti.js";
17
+ import { BadgeUnlock, badgeSound } from "./BadgeUnlock.js";
18
+ import { DieRoll } from "./DieRoll.js";
19
+ import { Evolution } from "./Evolution.js";
20
+ import { Hatch } from "./Hatch.js";
21
+ import { AddCard } from "./AddCard.js";
22
+ import { Decks } from "./Decks.js";
23
+ import { Reset } from "./Reset.js";
24
+ import { Help } from "./Help.js";
25
+ import { Missed } from "./Missed.js";
26
+ import { Settings } from "./Settings.js";
27
+ import { Stats } from "./Stats.js";
28
+ import { Summary } from "./Summary.js";
29
+ import { TheOne } from "./TheOne.js";
30
+
31
+ const SPINNER = ["⠚", "⠓", "⠋", "⠙"]; // the old braille dots on a 2×2 square: the gap goes round
32
+ const TICK_MS = 250; // the steady redraw: slow enough to stay idle for hours, fast enough for the spinner
33
+ const SLEEP_AFTER_MS = 3 * 60_000; // no key pressed for this long while waiting → the dragon dozes off
34
+ const PAUSED_SLEEP_AFTER_MS = 15_000; // during a pause or quiet hours it nods off again much sooner
35
+ const CHEER_STYLE = {
36
+ goal: { icon: "▪", color: theme.good },
37
+ evolve: { icon: "▴", color: theme.accent },
38
+ badge: { icon: "✦", color: theme.warn },
39
+ combo: { icon: "»", color: theme.warn }
40
+ };
41
+
42
+ function clock(ms) {
43
+ const total = Math.max(0, Math.ceil(ms / 1000));
44
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
45
+ }
46
+
47
+ // your answer with every letter judged: green lined up with the expected word, underlined didn't
48
+ function AnswerDiff({ given, closest }) {
49
+ const parts = diffChars(given, closest);
50
+ return html`
51
+ <${Text}>
52
+ <${Text} dimColor>you wrote <//>
53
+ ${parts.map((p, i) => html`<${Text} key=${i} color=${p.ok ? theme.good : theme.text} underline=${!p.ok}>${p.ch}<//>`)}
54
+ <//>
55
+ `;
56
+ }
57
+
58
+ function Verdict({ outcome, question }) {
59
+ const wrong = outcome.result === "wrong";
60
+ const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
61
+ return html`
62
+ <${Box} flexDirection="column">
63
+ <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${question.expected.join(", ")}${outcome.result === "typo" ? " (close enough)" : ""}<//>
64
+ ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
65
+ ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
66
+ ${(outcome.hinted || outcome.overruled) &&
67
+ html`
68
+ <${Box} marginTop=${1} flexDirection="column">
69
+ ${outcome.hinted && html`<${Text} dimColor>hint used · the card stays in its box<//>`}
70
+ ${outcome.overruled && html`<${Text} color=${theme.good}>counted as correct${question.tour ? "" : ` · "${outcome.accepted}" is accepted from now on`}<//>`}
71
+ <//>
72
+ `}
73
+ <//>
74
+ `;
75
+ }
76
+
77
+ const BADGE_FIRST_MS = 400; // after the answer's own sound
78
+ const BADGE_STAGGER_MS = 700; // several badges at once light up one after another
79
+
80
+ function Cheers({ cheers, play }) {
81
+ const lines = cheers.filter((cheer) => cheer.kind !== "badge");
82
+ const badges = cheers.filter((cheer) => cheer.kind === "badge");
83
+ return html`
84
+ <${Box} flexDirection="column" paddingX=${1} marginTop=${1}>
85
+ ${lines.map((cheer, i) => {
86
+ const style = CHEER_STYLE[cheer.kind] ?? CHEER_STYLE.combo;
87
+ return html`<${Text} key=${i} color=${style.color} bold>${style.icon} ${cheer.text}<//>`;
88
+ })}
89
+ ${badges.map((badge, i) => html`<${BadgeUnlock} key=${badge.id} ...${badge} delay=${BADGE_FIRST_MS + i * BADGE_STAGGER_MS} sound=${badgeSound(i)} play=${play} />`)}
90
+ <//>
91
+ `;
92
+ }
93
+
94
+ // The card's top edge with the direction ("EN → PL") set into its right corner, like a title on the border
95
+ function CardTop({ label, width, color }) {
96
+ const tail = 2;
97
+ const room = Math.max(4, width - 2 - tail - 4); // a label too long for a narrow window is cut short
98
+ const tag = ` ${cutToWidth(label, room)} `;
99
+ const dashes = Math.max(0, width - 2 - cellWidth(tag) - tail);
100
+ return html`
101
+ <${Text}>
102
+ <${Text} color=${color}>╭${"─".repeat(dashes)}<//>
103
+ <${Text} dimColor>${tag}<//>
104
+ <${Text} color=${color}>${"─".repeat(tail)}╮<//>
105
+ <//>
106
+ `;
107
+ }
108
+
109
+ // "at 14:30", "tomorrow", "on 14 Oct"
110
+ function whenDue(at, now) {
111
+ const tomorrow = startOfTomorrow(now);
112
+ if (at < tomorrow) return `at ${formatClock(at)}`;
113
+ return at < startOfTomorrow(tomorrow) ? "tomorrow" : `on ${formatDay(dayKey(at))}`;
114
+ }
115
+
116
+ // what the quiz shows when the deck has nothing to ask: no countdown, just the way on
117
+ function EmptyDeck({ deck, tour, count, nextDue, dayDone, now, width }) {
118
+ const [title, next] = tour
119
+ ? ["You've finished the tour.", "Now make it yours: type /add to start your own deck."]
120
+ : !count
121
+ ? [`"${deck}" has no cards yet.`, "Type /add to add the first one."]
122
+ : nextDue >= startOfTomorrow(now) && !dayDone
123
+ ? [`Nothing more in "${deck}" today.`, `Its cards come back ${whenDue(nextDue, now)}. Other decks still have cards: /decks`]
124
+ : nextDue >= startOfTomorrow(now)
125
+ ? ["All done for today.", `Your cards come back ${whenDue(nextDue, now)}. Want more today? /add some new ones.`]
126
+ : ["Nothing to practise right now.", `The next card is due ${whenDue(nextDue, now)}. It will come by itself.`];
127
+ return html`
128
+ <${Box} flexDirection="column" width=${width}>
129
+ <${CardTop} label=${deck} width=${width} color=${theme.accent} />
130
+ <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${theme.accent} paddingX=${2} paddingY=${1}>
131
+ <${Text} bold>${title}<//>
132
+ <${Text}>${next}<//>
133
+ <//>
134
+ <//>
135
+ `;
136
+ }
137
+
138
+ function TipBox({ tip, width }) {
139
+ return html`
140
+ <${Box} flexDirection="column" paddingX=${1} marginTop=${2} width=${width}>
141
+ <${Box} marginBottom=${1}><${Text} color=${theme.accent}>tip · ${tip.cat}<//><//>
142
+ <${Typewriter} text=${tip.text} dimColor />
143
+ <//>
144
+ `;
145
+ }
146
+
147
+ // `library` holds the /add actions (src/manage.js) and `onSwitchDeck` points the session at another
148
+ // deck; the preview gallery passes neither.
149
+ export function App({ session, deck: initialDeck, initialSettings, alerts, persistSettings, onExit, library, onSwitchDeck }) {
150
+ const { exit: exitApp } = useApp();
151
+ const exit = onExit ?? exitApp; // the preview gallery runs the quiz as a scene and takes quitting back to its menu
152
+ const { stdout } = useStdout();
153
+ const [settings, setSettings] = useState(initialSettings);
154
+ const [deck, setDeck] = useState(initialDeck);
155
+ const [addNew, setAddNew] = useState(false); // /add opened from "+ New deck" in /decks
156
+ const [restUntil, setRestUntil] = useState(null); // nothing is waiting until then (after the last card due now)
157
+ const [empty, setEmpty] = useState(null); // { tour, count, nextDue } when there is nothing to ask right now
158
+ // quiz | settings | reset | add | decks | stats | badges | companion | help | missed | evolve | the-one | die | summary | hatch
159
+ const [screen, setScreen] = useState(() => (session.isFirstRun() ? "hatch" : "quiz"));
160
+ const [tip, setTip] = useState(null);
161
+ const [phase, setPhase] = useState("loading"); // loading | asking | waiting | empty
162
+ const [question, setQuestion] = useState(null);
163
+ const [outcome, setOutcome] = useState(null);
164
+ const [problem, setProblem] = useState("");
165
+ const [commandMode, setCommandMode] = useState(false); // typing a "/" command between questions
166
+ const [notice, setNotice] = useState("");
167
+ const [hintLevel, setHintLevel] = useState(0);
168
+ const [snoozeUntil, setSnoozeUntil] = useState(0);
169
+ const [nextAt, setNextAt] = useState(0);
170
+ const [now, setNow] = useState(Date.now());
171
+ const [petEvent, setPetEvent] = useState(null); // { kind: "jump" | "shake", at } → a little hop or head-shake
172
+ const [confetti, setConfetti] = useState(false);
173
+ const [evolution, setEvolution] = useState(null); // { from, to, name } while the ceremony plays
174
+ const [freshBadges, setFreshBadges] = useState([]); // won since /badges was last opened; they light up there
175
+ const [ceremonies, setCeremonies] = useState([]); // full-screen moments still to show: "evolve", "the-one"
176
+ const [lastActive, setLastActive] = useState(Date.now()); // last key press or new question: the dragon sleeps after a long gap
177
+ const busy = useRef(false);
178
+ const asleepRef = useRef(false);
179
+ const bestCombo = useRef(0);
180
+ const settingsRef = useRef(settings);
181
+ settingsRef.current = settings;
182
+ const snoozeRef = useRef(0);
183
+ snoozeRef.current = snoozeUntil;
184
+
185
+ // when questions may resume: the end of a snooze or of quiet hours, whichever is later; 0 = not paused
186
+ const pauseEnd = (t) => {
187
+ const quiet = settingsRef.current.quiet;
188
+ return Math.max(snoozeRef.current > t ? snoozeRef.current : 0, inQuietHours(t, quiet) ? quietEnd(t, quiet) : 0);
189
+ };
190
+
191
+ // `nextDue`: nothing is waiting until then, so the next question waits for it (never sooner than usual)
192
+ const waitForNext = useCallback((nextDue = null) => {
193
+ const usual = Date.now() + settingsRef.current.everyMs;
194
+ setNextAt(nextDue ? Math.max(nextDue, usual) : usual);
195
+ setRestUntil(nextDue);
196
+ setPhase("waiting");
197
+ setTip(!session.inTour() && shouldShowTip(settingsRef.current.tips) ? session.nextTip() : null);
198
+ }, [session]);
199
+
200
+ const ask = useCallback(async () => {
201
+ setLastActive(Date.now());
202
+ setPhase("loading");
203
+ setProblem("");
204
+ setNotice("");
205
+ setHintLevel(0);
206
+ setCommandMode(false);
207
+ try {
208
+ const next = await session.next();
209
+ setQuestion(next);
210
+ setOutcome(null);
211
+ setEmpty(null);
212
+ setPhase("asking");
213
+ } catch (err) {
214
+ if (!err.empty) {
215
+ setProblem(err.message);
216
+ return waitForNext();
217
+ }
218
+ setQuestion(null);
219
+ setEmpty({ tour: err.tour, count: err.count, nextDue: err.nextDue, dayDone: err.dayDone });
220
+ setOutcome(err.cheers.length ? { result: "done", cheers: err.cheers } : null);
221
+ if (err.cheers.length) celebrate({ result: "exact", cheers: err.cheers, combo: session.totals.combo });
222
+ setPhase("empty");
223
+ }
224
+ }, [session, waitForNext]);
225
+
226
+ useEffect(() => {
227
+ ask();
228
+ }, [ask]);
229
+
230
+ // one steady clock for the whole app: spinner, countdown, mascot blink and combo flicker
231
+ useEffect(() => {
232
+ const id = setInterval(() => setNow(Date.now()), TICK_MS);
233
+ return () => clearInterval(id);
234
+ }, []);
235
+
236
+ // with nothing to practise, the quiz picks up again by itself once the next card is due
237
+ useEffect(() => {
238
+ if (phase !== "empty" || !empty?.nextDue || screen !== "quiz" || now < empty.nextDue || pauseEnd(now)) return;
239
+ alerts.ask();
240
+ ask();
241
+ }, [now, phase, empty, screen, ask, alerts]);
242
+
243
+ useEffect(() => {
244
+ if (phase !== "waiting" || screen === "summary" || screen === "evolve" || screen === "the-one" || screen === "die") return;
245
+ if (now >= nextAt && !pauseEnd(now)) {
246
+ alerts.ask();
247
+ ask();
248
+ }
249
+ }, [now, phase, nextAt, screen, ask, alerts]);
250
+
251
+ // quitting goes through the session summary when there is anything to sum up
252
+ const requestExit = useCallback(() => {
253
+ if (session.totals.asked > 0) return setScreen("summary");
254
+ exit();
255
+ }, [session, exit]);
256
+
257
+ // any key wakes a sleeping dragon, with a little start
258
+ useInput(() => {
259
+ if (asleepRef.current) setPetEvent({ kind: "jump", at: Date.now() });
260
+ setLastActive(Date.now());
261
+ });
262
+
263
+ useInput((input, key) => {
264
+ if (screen !== "quiz" || (phase !== "waiting" && phase !== "empty") || commandMode) return;
265
+ if (input === "/") return setCommandMode(true);
266
+ if (key.escape || input === "q") return requestExit();
267
+ if (key.return && phase === "waiting") ask();
268
+ });
269
+
270
+ const clearProblem = useCallback(() => {
271
+ setProblem("");
272
+ setNotice("");
273
+ }, []);
274
+
275
+ // every graded answer: sound, a hop or a shake, confetti on the daily goal, the evolution ceremony
276
+ function celebrate(result) {
277
+ alerts.result(result.result, { cheers: result.cheers.map((c) => c.kind), combo: result.combo });
278
+ bestCombo.current = Math.max(bestCombo.current, result.combo);
279
+ setPetEvent({ kind: result.result === "wrong" ? "shake" : "jump", at: Date.now() });
280
+ if (result.cheers.some((c) => c.kind === "goal")) setConfetti(true);
281
+ const queue = [];
282
+ if (result.cheers.some((c) => c.kind === "evolve")) {
283
+ const companion = session.stats().companion;
284
+ setEvolution({ from: Math.max(0, companion.index - 1), to: companion.index, name: companion.name, element: companion.element });
285
+ queue.push("evolve");
286
+ }
287
+ if (result.cheers.some((c) => c.id === "dragons-die")) queue.push("die");
288
+ if (result.cheers.some((c) => c.id === "one-ring")) queue.push("the-one");
289
+ if (queue.length) {
290
+ setCeremonies(queue.slice(1));
291
+ setScreen(queue[0]);
292
+ }
293
+ }
294
+
295
+ // after a full-screen ceremony: the next one if both happened at once, otherwise back to the quiz
296
+ function nextCeremony() {
297
+ const [next, ...rest] = ceremonies;
298
+ setCeremonies(rest);
299
+ setScreen(next ?? "quiz");
300
+ }
301
+
302
+ function runCommand(name, args = "") {
303
+ setCommandMode(false);
304
+ if (name === "/quit") return requestExit();
305
+ if (name === "/settings") return setScreen("settings");
306
+ if (name === "/stats") return setScreen("stats");
307
+ if (name === "/badges") {
308
+ return session
309
+ .openBadges()
310
+ .then((fresh) => {
311
+ setFreshBadges(fresh);
312
+ setScreen("badges");
313
+ })
314
+ .catch((err) => setProblem(err.message));
315
+ }
316
+ if (name === "/companion") return setScreen("companion");
317
+ if (name === "/missed") return setScreen("missed");
318
+ if (name === "/help") return setScreen("help");
319
+ if (name === "/add") return library ? (setAddNew(false), setScreen("add")) : setNotice("The preview can't add cards; run dracosh for that.");
320
+ if (name === "/decks") return library ? setScreen("decks") : setNotice("The preview has one demo deck; run dracosh for yours.");
321
+ if (name === "/hint" && phase === "asking") return setHintLevel((level) => level + 1);
322
+ if (name === "/pause") {
323
+ return session
324
+ .pause(args)
325
+ .then(({ snooze, list, message }) => {
326
+ if (snooze === "off") setSnoozeUntil(0);
327
+ if (typeof snooze === "number") {
328
+ setSnoozeUntil(Date.now() + snooze);
329
+ return phase === "asking" ? setNotice(`Paused until ${formatClock(Date.now() + snooze)}`) : undefined; // while waiting, the status line says it
330
+ }
331
+ const paused = list && snoozeRef.current > Date.now() ? `Paused until ${formatClock(snoozeRef.current)}. ` : "";
332
+ setNotice(paused + message);
333
+ })
334
+ .catch((err) => setProblem(err.message));
335
+ }
336
+ if (name === "/correct" && session.canOverrule()) {
337
+ return session
338
+ .overrule()
339
+ .then((result) => {
340
+ setOutcome(result);
341
+ celebrate(result);
342
+ if (phase === "empty") return ask(); // the card's next date changed: look again
343
+ waitForNext(result.nextDue);
344
+ })
345
+ .catch((err) => setProblem(`Couldn't save progress: ${err.message}`));
346
+ }
347
+ setProblem(`Unknown command ${name}`);
348
+ }
349
+
350
+ function changeSettings(patch) {
351
+ const previous = settingsRef.current;
352
+ const next = { ...previous, ...patch };
353
+ settingsRef.current = next;
354
+ setSettings(next);
355
+ alerts.configure({ sound: next.sound, volume: next.volume });
356
+ persistSettings(patch).catch(() => {});
357
+ if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
358
+ if (patch.volume !== undefined || patch.sound === true) alerts.play("correct-0"); // audible preview
359
+ }
360
+
361
+ // an empty answer means "I don't know": the answer is shown and the card counts as missed
362
+ async function submit(raw) {
363
+ const text = raw.trim();
364
+ if (busy.current) return;
365
+ busy.current = true;
366
+ let nextDue = null;
367
+ try {
368
+ const result = await session.answer(question, text, { hinted: hintLevel > 0 });
369
+ nextDue = result.nextDue;
370
+ setOutcome(result);
371
+ celebrate(result);
372
+ } catch (err) {
373
+ setProblem(`Couldn't save progress: ${err.message}`);
374
+ } finally {
375
+ busy.current = false;
376
+ waitForNext(nextDue);
377
+ }
378
+ }
379
+
380
+ // /decks and a first deck from /add: quiz another deck from now on, and remember it
381
+ function switchDeck(name) {
382
+ setScreen("quiz");
383
+ if (name === deck) return;
384
+ onSwitchDeck?.(name);
385
+ setDeck(name);
386
+ changeSettings({ deck: name });
387
+ ask();
388
+ }
389
+
390
+ // Reset (from /settings), after a backup. Everything brings back the tour and the hatching egg.
391
+ async function reset(scope) {
392
+ await library.backupBeforeReset();
393
+ await session.reset(scope);
394
+ setFreshBadges([]);
395
+ if (scope === "progress") {
396
+ setScreen("quiz");
397
+ return setNotice("Your progress starts over. Your cards are all still here.");
398
+ }
399
+ const tour = await library.resetLibrary();
400
+ onSwitchDeck?.(tour);
401
+ setDeck(tour);
402
+ changeSettings({ deck: null });
403
+ setScreen("hatch");
404
+ ask();
405
+ }
406
+
407
+ // after /add: a first deck of your own replaces the tour; a deck started from /decks (or in place
408
+ // of an empty one) becomes the one you practise; new cards end an empty state
409
+ function addDone({ deck: started, removed, added, dropped }) {
410
+ setScreen("quiz");
411
+ if (removed.length) session.forget(removed).catch(() => {});
412
+ const switching = started && (removed.length || phase === "empty" || addNew);
413
+ if (switching) switchDeck(started);
414
+ else if (phase === "empty" && added) ask();
415
+ const notes = [dropped && "The card you were writing wasn't saved.", started && !switching && `"${started}" is ready; you're still practising "${deck}". Switch with /decks.`];
416
+ setNotice(notes.filter(Boolean).join(" ")); // after ask(), which clears the notice
417
+ }
418
+
419
+ const width = usePanelWidth();
420
+ const border = !outcome ? theme.accent : outcome.result === "wrong" ? theme.bad : theme.good;
421
+ const pausedUntil = pauseEnd(now);
422
+ const tick = Math.floor(now / TICK_MS);
423
+ const frame = SPINNER[tick % SPINNER.length];
424
+ const stats = session.stats();
425
+ // mood: how the last answer went, otherwise whether today's goal is done (Header adds the blinking)
426
+ const resting = stats.today.goalMet ? "smile" : "idle";
427
+ const face = outcome?.result === "wrong" ? "sad" : outcome ? "happy" : resting;
428
+ // strictly boolean: a bare 0 leaking into the markup crashes Ink ("Text string must be rendered inside <Text>")
429
+ const paused = pausedUntil > nextAt || (now >= nextAt && pausedUntil > 0);
430
+ // asleep: no key pressed for a while, whether a question is open or not; a key always wakes it,
431
+ // even during a pause or quiet hours (where it nods off again sooner)
432
+ const idleLimit = phase === "waiting" && pausedUntil > 0 ? PAUSED_SLEEP_AFTER_MS : SLEEP_AFTER_MS;
433
+ const asleep = phase !== "loading" && now - lastActive > idleLimit;
434
+ asleepRef.current = asleep;
435
+
436
+ if (screen === "hatch")
437
+ return html`<${Box} flexDirection="column" marginY=${1}><${Hatch} play=${alerts.play} onDone=${() => {
438
+ session.markHatched().catch(() => {});
439
+ setScreen("quiz");
440
+ }} /><//>`;
441
+ if (screen === "summary") return html`<${Box} flexDirection="column" marginY=${1}><${Summary} stats=${stats} totals=${session.totals} bestCombo=${bestCombo.current} onDone=${exit} /><//>`;
442
+ if (screen === "evolve" && evolution)
443
+ return html`<${Box} flexDirection="column" marginY=${1}><${Evolution} ...${evolution} onClose=${() => {
444
+ setEvolution(null);
445
+ nextCeremony();
446
+ }} /><//>`;
447
+ if (screen === "die")
448
+ return html`<${Box} flexDirection="column" marginY=${1}><${DieRoll} element=${stats.companion.element} stage=${stats.companion.index} play=${alerts.play} onClose=${nextCeremony} /><//>`;
449
+ if (screen === "the-one") return html`<${Box} flexDirection="column" marginY=${1}><${TheOne} play=${alerts.play} onClose=${nextCeremony} /><//>`;
450
+ if (screen === "stats") return html`<${Box} flexDirection="column" marginY=${1}><${Stats} stats=${stats} getMonth=${session.month} onClose=${() => setScreen("quiz")} /><//>`;
451
+ if (screen === "companion") return html`<${Box} flexDirection="column" marginY=${1}><${Companion} current=${stats.companion.index} best=${stats.streak.best} element=${stats.companion.element} roll=${stats.companion.roll} onClose=${() => setScreen("quiz")} /><//>`;
452
+ if (screen === "help") return html`<${Box} flexDirection="column" marginY=${1}><${Help} onClose=${() => setScreen("quiz")} /><//>`;
453
+ if (screen === "missed") return html`<${Box} flexDirection="column" marginY=${1}><${Missed} getMissed=${session.missed} onClose=${() => setScreen("quiz")} /><//>`;
454
+ if (screen === "badges") return html`<${Box} flexDirection="column" marginY=${1}><${Badges} badges=${stats.badges} fresh=${freshBadges} onClose=${() => setScreen("quiz")} /><//>`;
455
+
456
+ return html`
457
+ <${Box} flexDirection="column" marginY=${1}>
458
+ <${Header} deck=${deck} everyMs=${settings.everyMs} wordCount=${question?.wordCount ?? empty?.count} stats=${stats} combo=${session.totals.combo} face=${face} event=${petEvent} tick=${tick} asleep=${asleep} />
459
+ <${Box} marginTop=${1} flexDirection="column">
460
+ ${screen === "settings" && html`<${Settings} settings=${settings} onChange=${changeSettings} onClose=${() => setScreen("quiz")} onAction=${library ? () => setScreen("reset") : null} />`}
461
+ ${screen === "reset" && html`<${Reset} stats=${stats} actions=${library} onConfirm=${reset} onClose=${() => setScreen("settings")} />`}
462
+ ${screen === "add" && html`<${AddCard} current=${deck} actions=${library} onDone=${addDone} startNew=${addNew} />`}
463
+ ${screen === "decks" && html`<${Decks} current=${deck} actions=${library} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onClose=${() => setScreen("quiz")} />`}
464
+ ${!["settings", "reset", "add", "decks"].includes(screen) &&
465
+ html`
466
+ <${Fragment}>
467
+ ${question &&
468
+ html`
469
+ <${Box} flexDirection="column" width=${width}>
470
+ <${CardTop} label=${question.label} width=${width} color=${border} />
471
+ <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${border} paddingX=${2} paddingTop=${1}>
472
+ <${Marked} bold text=${question.prompt} plain=${!question.tour} />
473
+ ${phase === "asking" && hintLevel > 0 && html`<${Text} dimColor>hint ${makeHint(hintTarget(question.expected), hintLevel)}<//>`}
474
+ <${Box} marginTop=${1} flexDirection="column">
475
+ ${phase === "asking" && html`<${AnswerInput} key=${question.word.noteId + question.direction} onSubmit=${submit} onCommand=${runCommand} onExit=${requestExit} onEdit=${clearProblem} commands=${commandsFor({ phase: "asking" })} />`}
476
+ ${phase !== "asking" && outcome && html`<${Verdict} outcome=${outcome} question=${question} />`}
477
+ <//>
478
+ <//>
479
+ <//>
480
+ `}
481
+ ${phase === "empty" && html`<${EmptyDeck} deck=${deck} ...${empty} now=${now} width=${width} />`}
482
+ ${confetti && html`<${Confetti} width=${width} onDone=${() => setConfetti(false)} />`}
483
+ ${outcome?.cheers?.length > 0 && html`<${Cheers} cheers=${outcome.cheers} play=${alerts.play} />`}
484
+ ${phase === "waiting" && tip && html`<${TipBox} tip=${tip} width=${width} />`}
485
+ <${Box} paddingX=${1} marginTop=${1} flexDirection="column">
486
+ ${problem && html`<${Text} color=${theme.bad}>${problem}<//>`}
487
+ ${phase === "loading" && html`<${Text}><${Text} color=${theme.accent}>${frame}<//><${Text} dimColor> loading…<//><//>`}
488
+ ${notice && html`<${Text} color=${theme.accent}>${notice}<//>`}
489
+ ${phase === "waiting" && paused && html`<${Text} dimColor>paused until ${formatClock(pausedUntil)}${inQuietHours(now, settings.quiet) ? " (quiet hours)" : ""}<//>`}
490
+ ${phase === "waiting" && !paused && restUntil && nextAt - now > settings.everyMs && html`<${Text} dimColor>nothing waiting · next card ${whenDue(restUntil, now)}<//>`}
491
+ ${phase === "waiting" &&
492
+ !paused &&
493
+ !(restUntil && nextAt - now > settings.everyMs) &&
494
+ html`
495
+ <${Text}>
496
+ <${Text} color=${theme.accent}>${frame} <//>
497
+ <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color="#6b5e8a" />
498
+ <${Text} dimColor> next card in ${clock(nextAt - now)}<//>
499
+ <//>
500
+ `}
501
+ ${(phase === "waiting" || phase === "empty") && commandMode && html`<${AnswerInput} commandOnly initial="/" commands=${commandsFor({ phase: "waiting", canOverrule: session.canOverrule() })} onCommand=${runCommand} onCancel=${() => setCommandMode(false)} onEdit=${clearProblem} />`}
502
+ ${phase !== "loading" && !commandMode && html`<${KeyHints} text=${phase === "asking" ? "enter submit (empty: reveal) · / commands · esc quit" : phase === "empty" ? "/add · / commands · q quit" : `${session.canOverrule() ? "/correct if you were right · " : ""}enter ask now · / commands · q quit`} />`}
503
+ <//>
504
+ <//>
505
+ `}
506
+ <//>
507
+ <//>
508
+ `;
509
+ }
@@ -0,0 +1,50 @@
1
+ import { useEffect, useState } from "react";
2
+ import { Box, Text } from "ink";
3
+ import { badgeColor } from "./icons.js";
4
+ import { html, theme } from "./kit.js";
5
+
6
+ const FRAME_MS = 90;
7
+ const FLASH_FRAMES = [5, 7]; // white-out frames before the name lights up in its rank color
8
+ const COLOR_FROM = 8;
9
+ const SPARKS_UNTIL = 22;
10
+ const SPARKS = ["✦", "·", "✧", "·"];
11
+ const GREY = "#4a5058";
12
+ const WHITE = "#ffffff";
13
+ const STEPS = 4; // badge-1 … badge-4 (scripts/make-sounds.js)
14
+
15
+ // Badges won with the same answer ring one after another, each a step higher. The climb starts
16
+ // over with every answer: a badge won later, on its own, plays the first step again.
17
+ export const badgeSound = (i) => `badge-${Math.min(i + 1, STEPS)}`;
18
+
19
+ // A badge just won, as one line under the card: the name comes out of grey, flashes white and
20
+ // lights up in its rank color while a few sparks fly. The badge art lives in /badges.
21
+ // `delay` staggers several badges won at once; `sound` rings as the line appears.
22
+ export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0), play }) {
23
+ const [frame, setFrame] = useState(-Math.round(delay / FRAME_MS));
24
+ useEffect(() => {
25
+ if (frame === 0) play?.(sound);
26
+ }, [frame === 0]);
27
+ useEffect(() => {
28
+ const timer = setInterval(() => {
29
+ setFrame((f) => {
30
+ if (f >= SPARKS_UNTIL) clearInterval(timer);
31
+ return f + 1;
32
+ });
33
+ }, FRAME_MS);
34
+ return () => clearInterval(timer);
35
+ }, []);
36
+
37
+ if (frame < 0) return null;
38
+ const color = FLASH_FRAMES.includes(frame) ? WHITE : frame >= COLOR_FROM ? badgeColor(id) : GREY;
39
+ const sparks = frame < SPARKS_UNTIL ? ` ${Array.from({ length: 3 }, (_, i) => SPARKS[(frame + i) % SPARKS.length]).join(" ")}` : "";
40
+
41
+ return html`
42
+ <${Box}>
43
+ <${Text} color=${color}>✦ <//>
44
+ <${Text} color=${theme.warn}>Badge unlocked: <//>
45
+ <${Text} bold color=${color}>${name}<//>
46
+ <${Text} dimColor> · ${desc}<//>
47
+ <${Text} color=${theme.warn}>${sparks}<//>
48
+ <//>
49
+ `;
50
+ }