dracosh 0.2.0 → 0.4.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 (57) hide show
  1. package/README.md +25 -17
  2. package/locales/de.json +1098 -0
  3. package/locales/en.json +1081 -0
  4. package/locales/fr.json +1148 -0
  5. package/locales/pl.json +1173 -0
  6. package/locales/uk.json +1174 -0
  7. package/package.json +2 -2
  8. package/src/alerts.js +71 -4
  9. package/src/backup.js +2 -1
  10. package/src/cardline.js +71 -0
  11. package/src/cli.js +41 -54
  12. package/src/commands.js +14 -12
  13. package/src/demo.js +11 -0
  14. package/src/diff.js +20 -10
  15. package/src/i18n.js +68 -0
  16. package/src/judge.js +164 -13
  17. package/src/language.js +355 -0
  18. package/src/library.js +91 -38
  19. package/src/lock.js +2 -1
  20. package/src/manage.js +193 -58
  21. package/src/pause.js +1 -2
  22. package/src/progress.js +119 -63
  23. package/src/quiet.js +3 -2
  24. package/src/scheduler.js +26 -9
  25. package/src/session.js +118 -36
  26. package/src/settings.js +14 -6
  27. package/src/starter.js +36 -27
  28. package/src/store.js +11 -8
  29. package/src/tips.js +12 -3
  30. package/src/ui/AddCard.js +449 -81
  31. package/src/ui/AnswerInput.js +22 -10
  32. package/src/ui/App.js +209 -57
  33. package/src/ui/BadgeUnlock.js +5 -4
  34. package/src/ui/Badges.js +9 -8
  35. package/src/ui/Choice.js +14 -9
  36. package/src/ui/Companion.js +13 -13
  37. package/src/ui/Confetti.js +2 -2
  38. package/src/ui/Decks.js +167 -9
  39. package/src/ui/DieRoll.js +9 -9
  40. package/src/ui/Evolution.js +7 -7
  41. package/src/ui/Hatch.js +7 -6
  42. package/src/ui/Header.js +58 -16
  43. package/src/ui/Help.js +43 -25
  44. package/src/ui/Languages.js +167 -0
  45. package/src/ui/Mascot.js +1 -2
  46. package/src/ui/Missed.js +13 -12
  47. package/src/ui/Preview.js +48 -29
  48. package/src/ui/Reset.js +13 -14
  49. package/src/ui/Settings.js +27 -19
  50. package/src/ui/Stats.js +24 -23
  51. package/src/ui/Summary.js +30 -15
  52. package/src/ui/TheOne.js +7 -6
  53. package/src/ui/icons.js +1 -2
  54. package/src/ui/kit.js +34 -6
  55. package/src/vacation.js +2 -1
  56. package/src/words.js +8 -2
  57. package/data/tips.json +0 -32
@@ -1,7 +1,8 @@
1
+ import { t } from "../i18n.js";
1
2
  import { useState } from "react";
2
- import { Box, Text, useInput } from "ink";
3
+ import { Box, useInput, usePaste } from "ink";
3
4
  import { COMMANDS, matchCommands } from "../commands.js";
4
- import { html, theme } from "./kit.js";
5
+ import { html, Text, theme } from "./kit.js";
5
6
 
6
7
  function Palette({ matches, selected }) {
7
8
  return html`
@@ -9,7 +10,7 @@ function Palette({ matches, selected }) {
9
10
  ${matches.map(
10
11
  (command, i) => html`
11
12
  <${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
+ <${Box} flexShrink=${0}><${Text} color=${i === selected ? theme.accent : undefined} bold=${i === selected} dimColor=${i !== selected}>${i === selected ? "❯" : " "} ${command.name.padEnd(12)}<//><//>
13
14
  <${Text} dimColor>${command.hint}<//>
14
15
  <//>
15
16
  `
@@ -25,7 +26,9 @@ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
25
26
  // ↑/↓ choose, Tab completes, Enter runs.
26
27
  // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
27
28
  // `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
+ // `onChange` hears every edit; `onRecall` is ↑ on an empty plain field (/add brings back the last card);
30
+ // `onPaste` takes a paste of several lines (/add reviews them as cards), anything else is typed in.
31
+ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
29
32
  const [value, setValue] = useState(initial);
30
33
  const [cursor, setCursor] = useState(initial.length);
31
34
  const [selected, setSelected] = useState(0);
@@ -38,8 +41,18 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, com
38
41
  setCursor(Math.max(0, Math.min(at, next.length)));
39
42
  setSelected(0);
40
43
  onEdit?.();
44
+ onChange?.(next);
41
45
  };
42
46
 
47
+ // pasted text arrives whole (bracketed paste); lines become spaces unless /add takes them as cards
48
+ const paste = (text) => {
49
+ const lines = /[\r\n]/.test(text) ? text.split(/\r\n|\r|\n/).filter((line) => line.trim()) : [text];
50
+ if (onPaste && lines.length > 1) return onPaste(lines);
51
+ const typed = lines.join(" ");
52
+ edit(value.slice(0, cursor) + typed + value.slice(cursor), cursor + typed.length);
53
+ };
54
+ usePaste(paste);
55
+
43
56
  useInput((input, key) => {
44
57
  if (key.escape) return commandOnly ? onCancel() : value ? edit("") : onExit();
45
58
  if (key.return) {
@@ -50,6 +63,7 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, com
50
63
  return onCommand(matches[pick]?.name ?? token, rest.join(" "));
51
64
  }
52
65
  if (key.tab) return matches.length ? edit(`${matches[pick].name}${args(value) ? ` ${args(value)}` : ""}`) : undefined;
66
+ if (key.upArrow && !value && onRecall) return onRecall();
53
67
  if (key.upArrow) return setSelected(Math.max(0, pick - 1));
54
68
  if (key.downArrow) return setSelected(Math.min(matches.length - 1, pick + 1));
55
69
  if (key.leftArrow) return setCursor((c) => Math.max(0, c - 1));
@@ -63,10 +77,8 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, com
63
77
  if (key.ctrl && input === "a") return setCursor(0);
64
78
  if (key.ctrl && input === "e") return setCursor(value.length);
65
79
  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
- }
80
+ // a terminal without bracketed paste sends a paste as typed text, line breaks and all
81
+ if (input) paste(input);
70
82
  });
71
83
 
72
84
  const before = value.slice(0, cursor);
@@ -75,11 +87,11 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, com
75
87
  return html`
76
88
  <${Box} flexDirection="column">
77
89
  <${Box}>
78
- <${Text} color=${theme.accent}>❯ <//>
90
+ <${Box} flexShrink=${0}><${Text} color=${theme.accent}>❯ <//><//>
79
91
  <${Text}>${before}<${Text} inverse>${at}<//>${after}<//>
80
92
  <//>
81
93
  ${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<//>`}<//>`}
94
+ ${isCommand && matches.length === 0 && html`<${Box} marginTop=${1}>${commandOnly ? html`<${Text} color=${theme.bad}>${t("input.unknownCommand")}<//>` : html`<${Text} dimColor>${t("input.notACommand")}<//>`}<//>`}
83
95
  <//>
84
96
  `;
85
97
  }
package/src/ui/App.js CHANGED
@@ -1,16 +1,20 @@
1
1
  import { Fragment, useCallback, useEffect, useRef, useState } from "react";
2
- import { Box, Text, useApp, useInput, useStdout } from "ink";
2
+ import { Box, useApp, useInput, useStdout } from "ink";
3
3
  import { commandsFor } from "../commands.js";
4
- import { diffChars } from "../diff.js";
4
+ import { accentMarks, diffChars } from "../diff.js";
5
+ import { ALMOST } from "../judge.js";
6
+ import { toSpeak } from "../session.js";
5
7
  import { AnswerInput } from "./AnswerInput.js";
6
8
  import { Header } from "./Header.js";
7
- import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, theme, Typewriter, usePanelWidth } from "./kit.js";
9
+ import { setLanguage, t } from "../i18n.js";
10
+ import { Bar, cellWidth, cutToWidth, html, KeyHints, Marked, Text, theme, Typewriter, usePanelWidth } from "./kit.js";
8
11
  import { hintTarget, makeHint } from "../hint.js";
9
12
  import { formatClock, inQuietHours, quietEnd } from "../quiet.js";
10
- import { startOfTomorrow } from "../scheduler.js";
13
+ import { NEW_PER_DAY, startOfTomorrow } from "../scheduler.js";
11
14
  import { formatDay } from "../vacation.js";
12
15
  import { dayKey } from "../dates.js";
13
16
  import { shouldShowTip } from "../tips.js";
17
+ import { sessionLength } from "../settings.js";
14
18
  import { Badges } from "./Badges.js";
15
19
  import { Companion } from "./Companion.js";
16
20
  import { Confetti } from "./Confetti.js";
@@ -32,6 +36,7 @@ const SPINNER = ["⠚", "⠓", "⠋", "⠙"]; // the old braille dots on a 2×2
32
36
  const TICK_MS = 250; // the steady redraw: slow enough to stay idle for hours, fast enough for the spinner
33
37
  const SLEEP_AFTER_MS = 3 * 60_000; // no key pressed for this long while waiting → the dragon dozes off
34
38
  const PAUSED_SLEEP_AFTER_MS = 15_000; // during a pause or quiet hours it nods off again much sooner
39
+ const SETTLE_MS = 400; // keys right after a card appears or its answer is revealed are a double press, not a choice
35
40
  const CHEER_STYLE = {
36
41
  goal: { icon: "▪", color: theme.good },
37
42
  evolve: { icon: "▴", color: theme.accent },
@@ -39,6 +44,8 @@ const CHEER_STYLE = {
39
44
  combo: { icon: "»", color: theme.warn }
40
45
  };
41
46
 
47
+ const QUIET_NIGHT_UNTIL = 7; // o'clock: no "new card" sound before then when a day's cards come in
48
+
42
49
  function clock(ms) {
43
50
  const total = Math.max(0, Math.ceil(ms / 1000));
44
51
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
@@ -46,34 +53,63 @@ function clock(ms) {
46
53
 
47
54
  // your answer with every letter judged: green lined up with the expected word, underlined didn't
48
55
  function AnswerDiff({ given, closest }) {
49
- const parts = diffChars(given, closest);
56
+ const parts = diffChars(given, closest, { gaps: true });
57
+ if (parts.every((p) => p.ok)) return null; // the same letters after all: nothing to mark
50
58
  return html`
51
59
  <${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}<//>`)}
60
+ <${Text} dimColor>${t("quiz.youWrote")}<//>
61
+ ${parts.map((p, i) => html`<${Text} key=${i} color=${p.missing ? theme.bad : p.ok ? theme.good : theme.text} underline=${!p.ok && !p.missing}>${p.ch}<//>`)}
54
62
  <//>
55
63
  `;
56
64
  }
57
65
 
66
+ // the right answers after one written without its accents, the letters you wrote plain underlined: jabłko
67
+ function AccentedAnswers({ expected, given, closest }) {
68
+ return expected.map((answer, i) => {
69
+ const marks = answer === closest ? accentMarks(given, answer) : null;
70
+ return html`
71
+ <${Text} key=${i}>
72
+ ${i > 0 ? " / " : ""}${marks ? marks.map((p, k) => html`<${Text} key=${k} underline=${!p.ok}>${p.ch}<//>`) : answer}
73
+ <//>
74
+ `;
75
+ });
76
+ }
77
+
58
78
  function Verdict({ outcome, question }) {
59
79
  const wrong = outcome.result === "wrong";
60
80
  const showDiff = outcome.closest && outcome.given && !outcome.overruled && (wrong || outcome.result === "typo");
61
81
  return html`
62
82
  <${Box} flexDirection="column">
63
- <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${question.expected.join(", ")}${outcome.result === "typo" ? " (close enough)" : ""}<//>
83
+ <${Text} color=${wrong ? theme.bad : theme.good} bold>${wrong ? "✗" : "✓"} ${outcome.result === "accent" || outcome.result === "umlaut" || outcome.result === "article-umlaut" ? html`<${AccentedAnswers} expected=${question.expected} given=${outcome.given} closest=${outcome.closest} />` : question.expected.join(" / ")}${outcome.result === "typo" ? t("quiz.closeEnough") : ""}<//>
84
+ ${ALMOST.includes(outcome.result) &&
85
+ html`<${Text} color=${theme.warn}>${t(`quiz.almost.${outcome.result}`)}${outcome.held ? ` ${t("quiz.almost.held", { now: t("quiz.almost.days", { count: outcome.held.days }), would: t("quiz.almost.days", { count: outcome.held.would }) })}` : ""}<//>`}
64
86
  ${showDiff && html`<${AnswerDiff} given=${outcome.given} closest=${outcome.closest} />`}
65
87
  ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
66
88
  ${(outcome.hinted || outcome.overruled) &&
67
89
  html`
68
90
  <${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`}<//>`}
91
+ ${outcome.hinted && html`<${Text} dimColor>${t("quiz.hintUsed")}<//>`}
92
+ ${outcome.overruled && html`<${Text} color=${theme.good}>${t("quiz.countedCorrect")}${question.tour ? "" : t("quiz.acceptedFromNow", { answer: outcome.accepted })}<//>`}
71
93
  <//>
72
94
  `}
73
95
  <//>
74
96
  `;
75
97
  }
76
98
 
99
+ // the answer shown after an empty Enter, and the question that follows: did you know it?
100
+ function Revealed({ question, nudge }) {
101
+ return html`
102
+ <${Box} flexDirection="column">
103
+ <${Text} color=${theme.accent} bold>${question.expected.join(" / ")}<//>
104
+ ${question.word.example && html`<${Box} marginTop=${1}>${question.tour ? html`<${Marked} dimColor text=${question.word.example} />` : html`<${Text} dimColor italic>“${question.word.example}”<//>`}<//>`}
105
+ <${Box} marginTop=${1}>
106
+ <${Text} bold>${t("quiz.didYouKnow")} <//>
107
+ <${Text} color=${nudge ? theme.warn : theme.text} bold=${nudge}>${t("quiz.gradeKeys")}<//>
108
+ <//>
109
+ <//>
110
+ `;
111
+ }
112
+
77
113
  const BADGE_FIRST_MS = 400; // after the answer's own sound
78
114
  const BADGE_STAGGER_MS = 700; // several badges at once light up one after another
79
115
 
@@ -109,27 +145,28 @@ function CardTop({ label, width, color }) {
109
145
  // "at 14:30", "tomorrow", "on 14 Oct"
110
146
  function whenDue(at, now) {
111
147
  const tomorrow = startOfTomorrow(now);
112
- if (at < tomorrow) return `at ${formatClock(at)}`;
113
- return at < startOfTomorrow(tomorrow) ? "tomorrow" : `on ${formatDay(dayKey(at))}`;
148
+ if (at < tomorrow) return t("quiz.when.at", { time: formatClock(at) });
149
+ return at < startOfTomorrow(tomorrow) ? t("quiz.when.tomorrow") : t("quiz.when.on", { day: formatDay(dayKey(at)) });
114
150
  }
115
151
 
116
152
  // 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 }) {
153
+ function EmptyDeck({ deck, tour, count, nextDue, dayDone, heldNew = 0, now, width }) {
118
154
  const [title, next] = tour
119
- ? ["You've finished the tour.", "Now make it yours: type /add to start your own deck."]
155
+ ? [t("quiz.empty.tourTitle"), t("quiz.empty.tourNext")]
120
156
  : !count
121
- ? [`"${deck}" has no cards yet.`, "Type /add to add the first one."]
157
+ ? [t("quiz.empty.noCardsTitle", { deck }), t("quiz.empty.noCardsNext")]
122
158
  : nextDue >= startOfTomorrow(now) && !dayDone
123
- ? [`Nothing more in "${deck}" today.`, `Its cards come back ${whenDue(nextDue, now)}. Other decks still have cards: /decks`]
159
+ ? [t("quiz.empty.deckDoneTitle", { deck }), t("quiz.empty.deckDoneNext", { when: whenDue(nextDue, now) })]
124
160
  : 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.`];
161
+ ? [t("quiz.empty.dayDoneTitle"), t(heldNew > 0 ? "quiz.empty.dayDoneHeldNext" : "quiz.empty.dayDoneNext", { when: whenDue(nextDue, now) })]
162
+ : [t("quiz.empty.laterTitle"), t("quiz.empty.laterNext", { when: whenDue(nextDue, now) })];
127
163
  return html`
128
164
  <${Box} flexDirection="column" width=${width}>
129
165
  <${CardTop} label=${deck} width=${width} color=${theme.accent} />
130
166
  <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${theme.accent} paddingX=${2} paddingY=${1}>
131
167
  <${Text} bold>${title}<//>
132
168
  <${Text}>${next}<//>
169
+ ${!tour && heldNew > 0 && html`<${Box} marginTop=${1}><${Text} dimColor>${t("quiz.empty.newTomorrow", { count: heldNew, max: NEW_PER_DAY })}<//><//>`}
133
170
  <//>
134
171
  <//>
135
172
  `;
@@ -138,7 +175,7 @@ function EmptyDeck({ deck, tour, count, nextDue, dayDone, now, width }) {
138
175
  function TipBox({ tip, width }) {
139
176
  return html`
140
177
  <${Box} flexDirection="column" paddingX=${1} marginTop=${2} width=${width}>
141
- <${Box} marginBottom=${1}><${Text} color=${theme.accent}>tip · ${tip.cat}<//><//>
178
+ <${Box} marginBottom=${1}><${Text} color=${theme.accent}>${t("quiz.tip", { cat: tip.cat })}<//><//>
142
179
  <${Typewriter} text=${tip.text} dimColor />
143
180
  <//>
144
181
  `;
@@ -158,7 +195,9 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
158
195
  // quiz | settings | reset | add | decks | stats | badges | companion | help | missed | evolve | the-one | die | summary | hatch
159
196
  const [screen, setScreen] = useState(() => (session.isFirstRun() ? "hatch" : "quiz"));
160
197
  const [tip, setTip] = useState(null);
161
- const [phase, setPhase] = useState("loading"); // loading | asking | waiting | empty
198
+ const [phase, setPhase] = useState("loading"); // loading | asking | grading (answer revealed) | waiting | empty
199
+ const [nudge, setNudge] = useState(false); // Enter while grading: the 1/2 keys light up
200
+ const [confirming, setConfirming] = useState(false); // /correct waits for yes or no
162
201
  const [question, setQuestion] = useState(null);
163
202
  const [outcome, setOutcome] = useState(null);
164
203
  const [problem, setProblem] = useState("");
@@ -175,9 +214,15 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
175
214
  const [ceremonies, setCeremonies] = useState([]); // full-screen moments still to show: "evolve", "the-one"
176
215
  const [lastActive, setLastActive] = useState(Date.now()); // last key press or new question: the dragon sleeps after a long gap
177
216
  const busy = useRef(false);
217
+ const shownAt = useRef(0); // when the card or its revealed answer appeared (SETTLE_MS)
218
+ const sessionDone = useRef(0); // cards answered in this study session (the "session" rhythm)
219
+ const [sessionWait, setSessionWait] = useState(false); // waiting for Enter, not for the clock
178
220
  const asleepRef = useRef(false);
179
221
  const bestCombo = useRef(0);
180
222
  const settingsRef = useRef(settings);
223
+ const tourSync = useRef(Promise.resolve());
224
+ const deckRef = useRef(deck);
225
+ deckRef.current = deck;
181
226
  settingsRef.current = settings;
182
227
  const snoozeRef = useRef(0);
183
228
  snoozeRef.current = snoozeUntil;
@@ -188,10 +233,14 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
188
233
  return Math.max(snoozeRef.current > t ? snoozeRef.current : 0, inQuietHours(t, quiet) ? quietEnd(t, quiet) : 0);
189
234
  };
190
235
 
191
- // `nextDue`: nothing is waiting until then, so the next question waits for it (never sooner than usual)
236
+ // `nextDue`: nothing is waiting until then, so the next question waits for it (never sooner than usual).
237
+ // In a study session Enter asks the next card instead of the clock, until the set number is done.
192
238
  const waitForNext = useCallback((nextDue = null) => {
193
239
  const usual = Date.now() + settingsRef.current.everyMs;
194
- setNextAt(nextDue ? Math.max(nextDue, usual) : usual);
240
+ const length = sessionLength(settingsRef.current.rhythm);
241
+ const studying = settingsRef.current.rhythm !== "minutes" && !nextDue && (length === null || sessionDone.current < length);
242
+ setSessionWait(studying);
243
+ setNextAt(studying ? Infinity : nextDue ? Math.max(nextDue, usual) : usual);
195
244
  setRestUntil(nextDue);
196
245
  setPhase("waiting");
197
246
  setTip(!session.inTour() && shouldShowTip(settingsRef.current.tips) ? session.nextTip() : null);
@@ -204,11 +253,13 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
204
253
  setNotice("");
205
254
  setHintLevel(0);
206
255
  setCommandMode(false);
256
+ setConfirming(false);
207
257
  try {
208
258
  const next = await session.next();
209
259
  setQuestion(next);
210
260
  setOutcome(null);
211
261
  setEmpty(null);
262
+ shownAt.current = Date.now();
212
263
  setPhase("asking");
213
264
  } catch (err) {
214
265
  if (!err.empty) {
@@ -216,7 +267,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
216
267
  return waitForNext();
217
268
  }
218
269
  setQuestion(null);
219
- setEmpty({ tour: err.tour, count: err.count, nextDue: err.nextDue, dayDone: err.dayDone });
270
+ setEmpty({ tour: err.tour, count: err.count, nextDue: err.nextDue, dayDone: err.dayDone, heldNew: err.heldNew });
220
271
  setOutcome(err.cheers.length ? { result: "done", cheers: err.cheers } : null);
221
272
  if (err.cheers.length) celebrate({ result: "exact", cheers: err.cheers, combo: session.totals.combo });
222
273
  setPhase("empty");
@@ -235,18 +286,28 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
235
286
 
236
287
  // with nothing to practise, the quiz picks up again by itself once the next card is due
237
288
  useEffect(() => {
238
- if (phase !== "empty" || !empty?.nextDue || screen !== "quiz" || now < empty.nextDue || pauseEnd(now)) return;
239
- alerts.ask();
289
+ if (phase !== "empty" || !empty?.nextDue || screen !== "quiz" || confirming || now < empty.nextDue || pauseEnd(now)) return;
290
+ // a new day's cards are ready from midnight: they wait quietly till morning instead of chiming at night
291
+ if (new Date(now).getHours() >= QUIET_NIGHT_UNTIL) alerts.ask();
240
292
  ask();
241
- }, [now, phase, empty, screen, ask, alerts]);
293
+ }, [now, phase, empty, screen, confirming, ask, alerts]);
242
294
 
243
295
  useEffect(() => {
244
- if (phase !== "waiting" || screen === "summary" || screen === "evolve" || screen === "the-one" || screen === "die") return;
296
+ // a /correct question stays open: the next card waits for its answer
297
+ if (phase !== "waiting" || confirming || screen === "summary" || screen === "evolve" || screen === "the-one" || screen === "die") return;
245
298
  if (now >= nextAt && !pauseEnd(now)) {
246
299
  alerts.ask();
247
300
  ask();
248
301
  }
249
- }, [now, phase, nextAt, screen, ask, alerts]);
302
+ }, [now, phase, nextAt, screen, confirming, ask, alerts]);
303
+
304
+ // Esc on an empty line is easy to press by habit: it quits only when pressed twice in a row
305
+ const escArmed = useRef(0);
306
+ const escapeExit = () => {
307
+ if (Date.now() - escArmed.current < 3000) return requestExit();
308
+ escArmed.current = Date.now();
309
+ setNotice(t("quiz.escAgain"));
310
+ };
250
311
 
251
312
  // quitting goes through the session summary when there is anything to sum up
252
313
  const requestExit = useCallback(() => {
@@ -260,11 +321,29 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
260
321
  setLastActive(Date.now());
261
322
  });
262
323
 
324
+ // the answer is revealed: you say whether you knew it. 1/2 or ←/→ (AZERTY's digits need Shift, so
325
+ // & and é too); Esc is "didn't know"; Enter never grades, it only shows the keys again
326
+ useInput((input, key) => {
327
+ if (screen !== "quiz" || phase !== "grading" || asleepRef.current || Date.now() - shownAt.current < SETTLE_MS) return;
328
+ if (input === "1" || input === "&" || key.leftArrow || key.escape) return gradeSelf(false);
329
+ if (input === "2" || input === "é" || key.rightArrow) return gradeSelf(true);
330
+ if (key.return) setNudge(true);
331
+ });
332
+
333
+ useInput((input, key) => {
334
+ // only the yes key accepts: Enter is too easy to press twice after "/correct" from the menu
335
+ if (screen !== "quiz" || !confirming || asleepRef.current) return;
336
+ const is = (keys) => t(keys).split("|").includes(input.toLowerCase());
337
+ if (is("choice.yesKey")) return overrule();
338
+ if (is("choice.noKey") || key.escape) setConfirming(false);
339
+ });
340
+
263
341
  useInput((input, key) => {
264
- if (screen !== "quiz" || (phase !== "waiting" && phase !== "empty") || commandMode) return;
342
+ if (screen !== "quiz" || (phase !== "waiting" && phase !== "empty") || commandMode || confirming) return;
265
343
  if (input === "/") return setCommandMode(true);
266
- if (key.escape || input === "q") return requestExit();
267
- if (key.return && phase === "waiting") ask();
344
+ if (input === "q") return requestExit();
345
+ if (key.escape) return escapeExit();
346
+ if (key.return && phase === "waiting" && !busy.current) ask();
268
347
  });
269
348
 
270
349
  const clearProblem = useCallback(() => {
@@ -316,8 +395,8 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
316
395
  if (name === "/companion") return setScreen("companion");
317
396
  if (name === "/missed") return setScreen("missed");
318
397
  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.");
398
+ if (name === "/add") return library ? (setAddNew(false), setScreen("add")) : setNotice(t("quiz.previewNoAdd"));
399
+ if (name === "/decks") return library ? setScreen("decks") : setNotice(t("quiz.previewNoDecks"));
321
400
  if (name === "/hint" && phase === "asking") return setHintLevel((level) => level + 1);
322
401
  if (name === "/pause") {
323
402
  return session
@@ -326,15 +405,23 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
326
405
  if (snooze === "off") setSnoozeUntil(0);
327
406
  if (typeof snooze === "number") {
328
407
  setSnoozeUntil(Date.now() + snooze);
329
- return phase === "asking" ? setNotice(`Paused until ${formatClock(Date.now() + snooze)}`) : undefined; // while waiting, the status line says it
408
+ return phase !== "waiting" ? setNotice(t("quiz.pausedUntilNotice", { time: formatClock(Date.now() + snooze) })) : undefined; // while waiting, the status line says it
330
409
  }
331
- const paused = list && snoozeRef.current > Date.now() ? `Paused until ${formatClock(snoozeRef.current)}. ` : "";
410
+ const paused = list && snoozeRef.current > Date.now() ? t("quiz.pausedUntilList", { time: formatClock(snoozeRef.current) }) : "";
332
411
  setNotice(paused + message);
333
412
  })
334
413
  .catch((err) => setProblem(err.message));
335
414
  }
336
- if (name === "/correct" && session.canOverrule()) {
337
- return session
415
+ if (name === "/correct" && session.canOverrule()) return setConfirming(true); // asked first: a misclick would accept the answer for good
416
+ setProblem(t("quiz.unknownCommand", { name }));
417
+ }
418
+
419
+ // /correct, confirmed: the last answer counts as right and is accepted from now on
420
+ function overrule() {
421
+ setConfirming(false);
422
+ if (busy.current) return;
423
+ busy.current = true;
424
+ return session
338
425
  .overrule()
339
426
  .then((result) => {
340
427
  setOutcome(result);
@@ -342,9 +429,10 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
342
429
  if (phase === "empty") return ask(); // the card's next date changed: look again
343
430
  waitForNext(result.nextDue);
344
431
  })
345
- .catch((err) => setProblem(`Couldn't save progress: ${err.message}`));
346
- }
347
- setProblem(`Unknown command ${name}`);
432
+ .catch((err) => setProblem(t("quiz.saveFailed", { error: err.message })))
433
+ .finally(() => {
434
+ busy.current = false;
435
+ });
348
436
  }
349
437
 
350
438
  function changeSettings(patch) {
@@ -352,25 +440,78 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
352
440
  const next = { ...previous, ...patch };
353
441
  settingsRef.current = next;
354
442
  setSettings(next);
355
- alerts.configure({ sound: next.sound, volume: next.volume });
443
+ alerts.configure({ sound: next.sound, volume: next.volume, speak: next.speak });
356
444
  persistSettings(patch).catch(() => {});
357
445
  if (patch.everyMs && phase === "waiting") setNextAt((at) => at - previous.everyMs + patch.everyMs);
446
+ if (patch.rhythm) {
447
+ sessionDone.current = 0;
448
+ if (phase === "waiting" && !restUntil) waitForNext(); // the wait follows the new rhythm right away
449
+ }
358
450
  if (patch.volume !== undefined || patch.sound === true) alerts.play("correct-0"); // audible preview
451
+ if (patch.language) changeLanguage(patch.language);
359
452
  }
360
453
 
361
- // an empty answer means "I don't know": the answer is shown and the card counts as missed
454
+ // Every text follows at the next render; the tour is translated too, and asked again in the new
455
+ // language. One translation at a time, so flicking through languages ends on the last one.
456
+ function changeLanguage(lang) {
457
+ setLanguage(lang);
458
+ if (!library) return;
459
+ tourSync.current = tourSync.current
460
+ .then(() => library.matchTourLanguage())
461
+ .then((renamed) => {
462
+ if (!renamed) return;
463
+ if (deckRef.current === renamed.from) {
464
+ deckRef.current = renamed.to;
465
+ onSwitchDeck?.(renamed.to);
466
+ setDeck(renamed.to);
467
+ }
468
+ if (phase === "asking" && question?.tour) ask();
469
+ })
470
+ .catch(() => {});
471
+ }
472
+
473
+ // An empty answer reveals the card, and you grade yourself (gradeSelf). An empty Enter right after the
474
+ // card appeared is the second half of the Enter that asked it: ignored.
362
475
  async function submit(raw) {
363
476
  const text = raw.trim();
477
+ if (busy.current) return;
478
+ if (!text) {
479
+ if (Date.now() - shownAt.current < SETTLE_MS) return;
480
+ session.reveal(question);
481
+ say(question);
482
+ shownAt.current = Date.now();
483
+ setNudge(false);
484
+ return setPhase("grading");
485
+ }
486
+ const result = await settle(() => session.answer(question, text, { hinted: hintLevel > 0 }));
487
+ if (result) say(question, result.closest);
488
+ }
489
+
490
+ // pronunciation (/settings), once the answer is out
491
+ function say(q, answer) {
492
+ const spoken = toSpeak(q, answer);
493
+ if (spoken) alerts.speak(spoken.text, spoken.lang);
494
+ }
495
+
496
+ const gradeSelf = (knew) => settle(() => session.selfGrade(question, knew, { hinted: hintLevel > 0 }));
497
+
498
+ // a graded answer: the verdict, the celebration, then the wait for the next card
499
+ async function settle(grading) {
364
500
  if (busy.current) return;
365
501
  busy.current = true;
366
502
  let nextDue = null;
367
503
  try {
368
- const result = await session.answer(question, text, { hinted: hintLevel > 0 });
504
+ const result = await grading();
369
505
  nextDue = result.nextDue;
506
+ sessionDone.current += 1;
507
+ const length = sessionLength(settingsRef.current.rhythm);
508
+ if (length !== null && sessionDone.current === length) setNotice(t("quiz.sessionDone", { count: length }));
370
509
  setOutcome(result);
371
510
  celebrate(result);
511
+ return result;
372
512
  } catch (err) {
373
- setProblem(`Couldn't save progress: ${err.message}`);
513
+ setProblem(t("quiz.saveFailed", { error: err.message }));
514
+ return null;
374
515
  } finally {
375
516
  busy.current = false;
376
517
  waitForNext(nextDue);
@@ -394,7 +535,7 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
394
535
  setFreshBadges([]);
395
536
  if (scope === "progress") {
396
537
  setScreen("quiz");
397
- return setNotice("Your progress starts over. Your cards are all still here.");
538
+ return setNotice(t("quiz.progressReset"));
398
539
  }
399
540
  const tour = await library.resetLibrary();
400
541
  onSwitchDeck?.(tour);
@@ -406,13 +547,15 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
406
547
 
407
548
  // after /add: a first deck of your own replaces the tour; a deck started from /decks (or in place
408
549
  // of an empty one) becomes the one you practise; new cards end an empty state
409
- function addDone({ deck: started, removed, added, dropped }) {
550
+ function addDone({ deck: started, removed, stale = [], added, dropped }) {
410
551
  setScreen("quiz");
411
552
  if (removed.length) session.forget(removed).catch(() => {});
553
+ if (stale.length) session.forgetKeys(stale).catch(() => {});
554
+ if (added) session.workAdded().catch(() => {});
412
555
  const switching = started && (removed.length || phase === "empty" || addNew);
413
556
  if (switching) switchDeck(started);
414
557
  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.`];
558
+ const notes = [dropped && t("quiz.cardNotSaved"), started && !switching && t("quiz.deckReadyElsewhere", { deck: started, current: deck })];
416
559
  setNotice(notes.filter(Boolean).join(" ")); // after ask(), which clears the notice
417
560
  }
418
561
 
@@ -455,12 +598,16 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
455
598
 
456
599
  return html`
457
600
  <${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} />
601
+ <${Header} deck=${deck} everyMs=${settings.everyMs} rhythm=${settings.rhythm} wordCount=${question?.wordCount ?? empty?.count} stats=${stats} combo=${session.totals.combo} face=${face} event=${petEvent} tick=${tick} asleep=${asleep} />
459
602
  <${Box} marginTop=${1} flexDirection="column">
460
603
  ${screen === "settings" && html`<${Settings} settings=${settings} onChange=${changeSettings} onClose=${() => setScreen("quiz")} onAction=${library ? () => setScreen("reset") : null} />`}
461
604
  ${screen === "reset" && html`<${Reset} stats=${stats} actions=${library} onConfirm=${reset} onClose=${() => setScreen("settings")} />`}
462
605
  ${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")} />`}
606
+ ${screen === "decks" && html`<${Decks} current=${deck} actions=${library} onDirections=${async (cardIds, directions) => {
607
+ await session.setDirections(cardIds, directions);
608
+ await session.workAdded();
609
+ if (phase === "asking" && question && cardIds.includes(question.word.noteId)) ask(); // the open card follows the new way at once
610
+ }} onLanguages=${(name) => name === deck && phase === "asking" && ask()} onPick=${switchDeck} onNew=${() => (setAddNew(true), setScreen("add"))} onClose=${() => setScreen("quiz")} />`}
464
611
  ${!["settings", "reset", "add", "decks"].includes(screen) &&
465
612
  html`
466
613
  <${Fragment}>
@@ -470,10 +617,12 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
470
617
  <${CardTop} label=${question.label} width=${width} color=${border} />
471
618
  <${Box} flexDirection="column" borderStyle="round" borderTop=${false} borderColor=${border} paddingX=${2} paddingTop=${1}>
472
619
  <${Marked} bold text=${question.prompt} plain=${!question.tour} />
473
- ${phase === "asking" && hintLevel > 0 && html`<${Text} dimColor>hint ${makeHint(hintTarget(question.expected), hintLevel)}<//>`}
620
+ ${question.context && html`<${Text} dimColor>(${question.context})<//>`}
621
+ ${phase === "asking" && hintLevel > 0 && html`<${Text} dimColor>${t("quiz.hintLabel")} ${makeHint(hintTarget(question.expected), hintLevel)}<//>`}
474
622
  <${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} />`}
623
+ ${phase === "asking" && html`<${AnswerInput} key=${question.word.noteId + question.direction} onSubmit=${submit} onCommand=${runCommand} onExit=${escapeExit} onEdit=${clearProblem} commands=${commandsFor({ phase: "asking" })} />`}
624
+ ${phase === "grading" && html`<${Revealed} question=${question} nudge=${nudge} />`}
625
+ ${phase !== "asking" && phase !== "grading" && outcome && html`<${Verdict} outcome=${outcome} question=${question} />`}
477
626
  <//>
478
627
  <//>
479
628
  <//>
@@ -484,22 +633,25 @@ export function App({ session, deck: initialDeck, initialSettings, alerts, persi
484
633
  ${phase === "waiting" && tip && html`<${TipBox} tip=${tip} width=${width} />`}
485
634
  <${Box} paddingX=${1} marginTop=${1} flexDirection="column">
486
635
  ${problem && html`<${Text} color=${theme.bad}>${problem}<//>`}
487
- ${phase === "loading" && html`<${Text}><${Text} color=${theme.accent}>${frame}<//><${Text} dimColor> loading…<//><//>`}
636
+ ${phase === "loading" && html`<${Text}><${Text} color=${theme.accent}>${frame}<//><${Text} dimColor>${t("quiz.loading")}<//><//>`}
488
637
  ${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)}<//>`}
638
+ ${confirming && html`<${Text} color=${theme.warn}>${t("quiz.correctConfirm", { answer: session.wrongAnswer() })}<//>`}
639
+ ${phase === "waiting" && paused && html`<${Text} dimColor>${t("quiz.pausedUntil", { time: formatClock(pausedUntil) })}${inQuietHours(now, settings.quiet) ? t("quiz.quietHours") : ""}<//>`}
640
+ ${phase === "waiting" && !paused && restUntil && nextAt - now > settings.everyMs && html`<${Text} dimColor>${t("quiz.nothingWaiting", { when: whenDue(restUntil, now) })}<//>`}
641
+ ${phase === "waiting" && !paused && sessionWait && sessionLength(settings.rhythm) && html`<${Text} dimColor>${t("quiz.sessionProgress", { done: sessionDone.current, count: sessionLength(settings.rhythm) })}<//>`}
491
642
  ${phase === "waiting" &&
492
643
  !paused &&
644
+ !sessionWait &&
493
645
  !(restUntil && nextAt - now > settings.everyMs) &&
494
646
  html`
495
647
  <${Text}>
496
648
  <${Text} color=${theme.accent}>${frame} <//>
497
649
  <${Bar} value=${Math.max(0, nextAt - now)} max=${settings.everyMs} width=${14} color="#6b5e8a" />
498
- <${Text} dimColor> next card in ${clock(nextAt - now)}<//>
650
+ <${Text} dimColor>${t("quiz.nextCardIn", { time: clock(nextAt - now) })}<//>
499
651
  <//>
500
652
  `}
501
653
  ${(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`} />`}
654
+ ${phase !== "loading" && !commandMode && html`<${KeyHints} text=${confirming ? t("keyHints.confirm", { yes: t("choice.yesKey").split("|")[0], no: t("choice.noKey").split("|")[0] }) : phase === "grading" ? t("keyHints.grading") : phase === "asking" ? t("keyHints.asking") : phase === "empty" ? t("keyHints.empty") : session.canOverrule() ? t("keyHints.correctFirst", { rest: t(sessionWait ? "keyHints.sessionWaiting" : "keyHints.waiting") }) : t(sessionWait ? "keyHints.sessionWaiting" : "keyHints.waiting")} />`}
503
655
  <//>
504
656
  <//>
505
657
  `}
@@ -1,7 +1,8 @@
1
+ import { t } from "../i18n.js";
1
2
  import { useEffect, useState } from "react";
2
- import { Box, Text } from "ink";
3
+ import { Box } from "ink";
3
4
  import { badgeColor } from "./icons.js";
4
- import { html, theme } from "./kit.js";
5
+ import { html, Text, theme } from "./kit.js";
5
6
 
6
7
  const FRAME_MS = 90;
7
8
  const FLASH_FRAMES = [5, 7]; // white-out frames before the name lights up in its rank color
@@ -39,9 +40,9 @@ export function BadgeUnlock({ id, name, desc, delay = 0, sound = badgeSound(0),
39
40
  const sparks = frame < SPARKS_UNTIL ? ` ${Array.from({ length: 3 }, (_, i) => SPARKS[(frame + i) % SPARKS.length]).join(" ")}` : "";
40
41
 
41
42
  return html`
42
- <${Box}>
43
+ <${Text}>
43
44
  <${Text} color=${color}>✦ <//>
44
- <${Text} color=${theme.warn}>Badge unlocked: <//>
45
+ <${Text} color=${theme.warn}>${t("badgeUnlock.label")}<//>
45
46
  <${Text} bold color=${color}>${name}<//>
46
47
  <${Text} dimColor> · ${desc}<//>
47
48
  <${Text} color=${theme.warn}>${sparks}<//>