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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dracosh",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "A gamified language or definitions trainer for your terminal. Your personal pixel dragon grows with your progress.",
5
5
  "author": "Tomasz Przyborowski (https://github.com/lynthius)",
6
6
  "license": "Apache-2.0",
@@ -30,7 +30,7 @@
30
30
  "files": [
31
31
  "src",
32
32
  "assets",
33
- "data",
33
+ "locales",
34
34
  "NOTICE"
35
35
  ],
36
36
  "engines": {
package/src/alerts.js CHANGED
@@ -1,14 +1,54 @@
1
+ import { t } from "./i18n.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import path from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { rm } from "node:fs/promises";
3
6
  import { fileURLToPath } from "node:url";
4
7
 
5
8
  // 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
6
9
  const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
7
10
  const LADDER_STEPS = 6; // correct-0 … correct-5: the pitch climbs with your combo
8
11
 
12
+ // Voices macOS has for a language (`say -v ?`), the novelty ones left out, the best first: a premium or
13
+ // enhanced voice, then a plain named one. Read once, when the first word is spoken.
14
+ const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
15
+ const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
16
+ const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
17
+ const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
18
+ let voices = null;
19
+ function voicesOnce() {
20
+ voices ??= new Promise((resolve) =>
21
+ execFile("say", ["-v", "?"], (err, out) =>
22
+ resolve(err ? [] : String(out).split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region })))
23
+ )
24
+ );
25
+ return voices;
26
+ }
27
+ // the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
28
+ const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
29
+ const rank = (voice) => {
30
+ const regions = REGIONS[voice.lang] ?? [];
31
+ const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
32
+ const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
33
+ return region * 10 + quality;
34
+ };
35
+ export async function voiceFor(lang) {
36
+ const code = SPEECH_CODE[lang] ?? lang;
37
+ const found = (await voicesOnce()).filter((voice) => voice.lang === code && !NOVELTY.has(voice.name));
38
+ return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
39
+ }
40
+
9
41
  export function createAlerts(initial = {}) {
10
42
  const enabled = process.platform === "darwin";
11
- const config = { sound: true, volume: 0.5, ...initial };
43
+ const config = { sound: true, volume: 0.5, speak: false, ...initial };
44
+ // one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
45
+ let waiting = null;
46
+ let speaking = null;
47
+ const hush = () => {
48
+ clearTimeout(waiting);
49
+ speaking?.kill();
50
+ waiting = speaking = null;
51
+ };
12
52
 
13
53
  const play = (name) => {
14
54
  if (!config.sound || !enabled) return;
@@ -17,21 +57,48 @@ export function createAlerts(initial = {}) {
17
57
 
18
58
  return {
19
59
  play,
20
- configure: (patch) => Object.assign(config, patch),
60
+ configure(patch) {
61
+ Object.assign(config, patch);
62
+ if (!config.speak) hush();
63
+ },
21
64
  // a new question while you're in another window: sound plus a Notification Center banner
22
65
  ask() {
23
66
  play("ask");
24
- if (enabled) execFile("osascript", ["-e", 'display notification "A new word is waiting" with title "Dracosh"'], () => {});
67
+ // the text goes to AppleScript as an argument, never into the script itself
68
+ if (enabled) execFile("osascript", ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", t("alerts.newCard")], () => {});
25
69
  },
26
70
  // The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
27
71
  // On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
28
72
  // on their own, each as its line lights up (see BadgeUnlock).
73
+ // a word read aloud in its language (/settings → Pronunciation); nothing when macOS has no voice for it
74
+ // Rendered to a file and played with afplay, so it follows the volume like the sounds do (say's own
75
+ // volume command is ignored by today's voices).
76
+ async speak(text, lang) {
77
+ hush();
78
+ if (!config.speak || !enabled || !text || !lang) return;
79
+ const voice = await voiceFor(lang);
80
+ if (!voice) return;
81
+ hush(); // another word may have come meanwhile
82
+ const words = text.replace(/\[\[|\]\]|[{}\\]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
83
+ const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
84
+ waiting = setTimeout(() => {
85
+ waiting = null;
86
+ if (!config.speak) return;
87
+ const render = (speaking = execFile("say", ["-v", voice, "-o", file, "--", words], (err) => {
88
+ if (err || speaking !== render) return void rm(file, { force: true }).catch(() => {});
89
+ const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], () => rm(file, { force: true }).catch(() => {})));
90
+ voiceOut.unref();
91
+ }));
92
+ render.unref();
93
+ }, SPEAK_AFTER_MS);
94
+ waiting.unref(); // quitting right after an answer doesn't wait for the word
95
+ },
29
96
  result(result, { cheers = [], combo = 0 } = {}) {
30
97
  if (result === "wrong") return play("wrong");
31
98
  for (const kind of ["evolve", "goal", "combo"]) {
32
99
  if (cheers.includes(kind)) return play(kind);
33
100
  }
34
- if (result === "typo") return play("close");
101
+ if (result === "typo" || result === "article" || result === "umlaut" || result === "article-umlaut") return play("close");
35
102
  play(`correct-${Math.min(Math.max(combo - 1, 0), LADDER_STEPS - 1)}`);
36
103
  }
37
104
  };
package/src/backup.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { t } from "./i18n.js";
1
2
  import { copyFile, readdir, rm } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import { dayKey } from "./dates.js";
@@ -87,7 +88,7 @@ export async function listBackups() {
87
88
  // A file the backup doesn't have is left as it is: a restore never deletes your cards or progress.
88
89
  export async function restoreBackup(file, now = Date.now()) {
89
90
  const backup = await readJson(file, null);
90
- if (backup?.format !== BACKUP_FORMAT || !backup.files) throw new Error(`${file} isn't a Dracosh backup.`);
91
+ if (backup?.format !== BACKUP_FORMAT || !backup.files) throw new Error(t("errors.notABackup", { file }));
91
92
  await backupNow("before-restore", now);
92
93
  for (const [name, target] of Object.entries(DATA_FILES)) {
93
94
  if (backup.files[name]) await writeJson(target, backup.files[name]);
@@ -0,0 +1,71 @@
1
+ // One card written as one line, the way /add (and later import) takes it:
2
+ //
3
+ // kot = cat; kitty // Mój kot śpi.
4
+ //
5
+ // Only " = " with spaces around it splits front and back, so "E=mc²" or "x=1" stays whole. ";"
6
+ // separates right answers (commas belong to sentences: "Yes, I do"). " // " with spaces starts the
7
+ // example, so "https://…" stays whole. "{{…}}" in the front makes a gap: a cloze card, asked one gap
8
+ // at a time. A backslash keeps any of these as plain text: \= \; \// \{{ (and \\ is a backslash).
9
+ //
10
+ // A cloze card keeps its escaped braces ("\{{") in the stored front, so they never turn into gaps.
11
+
12
+ const ESCAPES = { "\\\\": "\u0005", "\\=": "\u0001", "\\;": "\u0002", "\\//": "\u0003", "\\{{": "\u0004" };
13
+ const RESTORE = { "\u0005": "\\", "\u0001": "=", "\u0002": ";", "\u0003": "//", "\u0004": "{{" };
14
+ const hide = (text) => text.replace(/\\(\\|=|;|\/\/|\{\{)/g, (match) => ESCAPES[match]);
15
+ const show = (text, keep = {}) => text.replace(/[\u0001-\u0005]/g, (ch) => keep[ch] ?? RESTORE[ch]);
16
+
17
+ // a gap holds some text and no braces: "{{ }}" or "{{a {{b}} c}}" aren't gaps (only "{{b}}" is)
18
+ export const GAP = /(?<!\\)\{\{\s*([^\s{}][^{}]*?)\s*\}\}/g;
19
+ const hasGap = (front) => new RegExp(GAP.source).test(front);
20
+ const unescapeBraces = (text) => text.replace(/\\\{\{/g, "{{");
21
+
22
+ // a cloze card's gaps, in order: "I {{look forward}} to {{it}}" → ["look forward", "it"]
23
+ export const gapsOf = (front) => [...front.matchAll(GAP)].map((match) => match[1]);
24
+
25
+ // The front with gap `index` blanked and the others filled in: "I ____ to it"
26
+ export const blankGap = (front, index) => {
27
+ let i = 0;
28
+ return unescapeBraces(front.replace(GAP, (_, gap) => (i++ === index ? "____" : gap)));
29
+ };
30
+
31
+ // The front as read: the gaps filled in, no braces
32
+ export const plainFront = (front) => unescapeBraces(front.replace(GAP, (_, gap) => gap));
33
+
34
+ const splitAnswers = (text) => text.split(";").map((part) => show(part).trim()).filter(Boolean);
35
+
36
+ // `separator` is " = " for typed lines; a pasted export can use a tab instead.
37
+ // → { front, back: [], example, cloze, hasBack }: `hasBack` is false when the line has no separator,
38
+ // so /add asks for the back next (a cloze card doesn't need one: the gaps are its answers).
39
+ export function parseLine(line, { separator = " = " } = {}) {
40
+ let hidden = hide(String(line ?? "").trim());
41
+ // "kot =" is a front still waiting for its back
42
+ if (separator === " = " && !hidden.includes(separator) && hidden.endsWith(" =")) hidden = hidden.slice(0, -2).trimEnd();
43
+ const at = hidden.indexOf(separator);
44
+ const frontPart = at === -1 ? hidden : hidden.slice(0, at);
45
+ const rest = at === -1 ? "" : ` ${hidden.slice(at + separator.length)}`; // the space lets the back start with "// "
46
+ const exampleAt = rest.indexOf(" // ");
47
+ const backPart = exampleAt === -1 ? rest : rest.slice(0, exampleAt);
48
+ const example = exampleAt === -1 ? "" : show(rest.slice(exampleAt + 4)).trim();
49
+ // braces escaped with \{{ are plain text, so only the visible ones make gaps
50
+ const cloze = hasGap(frontPart.replace(/\u0004/g, ""));
51
+ const front = show(frontPart, cloze ? { "\u0004": "\\{{" } : {}).trim();
52
+ return { front, back: splitAnswers(backPart), example, cloze, hasBack: at !== -1 };
53
+ }
54
+
55
+ // What goes into a second step's field: the back of a card, maybe with its example ("cat; kitty // …")
56
+ export function parseBack(text) {
57
+ const { back, example } = parseLine(`x = ${text}`);
58
+ return { back, example };
59
+ }
60
+
61
+ // A card as one line, for fixing it: the reverse of parseLine. A backslash is doubled where it would
62
+ // otherwise read as an escape (before = ; // {{ \ or at the end of a piece).
63
+ const backslashes = (text, { cloze = false } = {}) => text.replace(cloze ? /\\(?=[=;\\]|\/\/|$)/g : /\\(?=[=;\\]|\/\/|\{\{|$)/g, "\\\\");
64
+ export function formatLine({ front, back = [], example = "", cloze = false }) {
65
+ let line = backslashes(front, { cloze }).replace(/ =/g, " \\=");
66
+ if (!cloze) line = line.replace(/\{\{/g, "\\{{");
67
+ const backText = back.map((answer) => backslashes(answer).replace(/;/g, "\\;").replace(/(^|\s)\/\//g, "$1\\//")).join("; ");
68
+ if (backText || example) line += ` = ${backText}`;
69
+ if (example) line += ` // ${backslashes(example)}`;
70
+ return line;
71
+ }
package/src/cli.js CHANGED
@@ -5,6 +5,7 @@ import { parseArgs } from "node:util";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { createAlerts } from "./alerts.js";
7
7
  import { existsSync } from "node:fs";
8
+ import { language, setLanguage, t } from "./i18n.js";
8
9
  import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup } from "./backup.js";
9
10
  import { ensureProgress, snapshot } from "./progress.js";
10
11
  import { BOX_INTERVALS_DAYS } from "./scheduler.js";
@@ -19,36 +20,17 @@ import * as manage from "./manage.js";
19
20
  import { findDeck } from "./library.js";
20
21
  import { loadAllWords, loadWords, missingDeck } from "./words.js";
21
22
 
22
- const HELP = `Dracosh: a vocabulary and quiz trainer for your terminal
23
-
24
- Usage: dracosh [options]
25
- dracosh restore [number] list your backups, or bring one back
26
-
27
- --deck <name> quiz this deck, this run only (otherwise the one picked in /decks)
28
- --every <time> pause between questions: 30s, 10m, 1h (default: ${formatInterval(DEFAULTS.everyMs)})
29
- --no-sound turn sound effects off
30
- --volume <0-1> sound volume (default: ${DEFAULTS.volume})
31
- --stats print progress and exit
32
- --data show where your cards, progress and backups are kept
33
- --preview browse every animation and screen on made-up data (nothing is saved)
34
- -y, --yes restore without asking first
35
- -h, --help show this help
36
-
37
- Flags override your saved settings for this run only. Change the saved ones with /settings.
38
-
39
- While running: Enter submits, "/" opens the command menu (/add, /decks, /settings, /stats, /help…),
40
- Esc quits (clears the line first if you typed something). Ctrl+C also works.
41
- Between cards: Enter asks the next one right away, q quits. /help explains the rest.`;
23
+ const help = () => t("cli.help", { interval: formatInterval(DEFAULTS.everyMs), volume: DEFAULTS.volume });
42
24
 
43
25
  function parseEvery(value) {
44
26
  const match = /^(\d+(?:\.\d+)?)(s|m|h)$/.exec(value);
45
- if (!match) throw new Error(`Invalid --every "${value}". Use e.g. 30s, 10m, 1h.`);
27
+ if (!match) throw new Error(t("cli.badEvery", { value }));
46
28
  return Number(match[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[match[2]];
47
29
  }
48
30
 
49
31
  function parseVolume(value) {
50
32
  const volume = Number(value);
51
- if (!(volume >= 0 && volume <= 1)) throw new Error(`Invalid --volume "${value}". Use a number from 0 to 1.`);
33
+ if (!(volume >= 0 && volume <= 1)) throw new Error(t("cli.badVolume", { value }));
52
34
  return volume;
53
35
  }
54
36
 
@@ -56,26 +38,26 @@ function printStats(state, settings) {
56
38
  ensureProgress(state);
57
39
  const stats = snapshot(state, { goal: settings.dailyGoal });
58
40
  const { streak, today } = stats;
59
- console.log(`Streak ${streak.days} days (best ${streak.best}) · ${streak.freezes} freeze(s) in stock`);
60
- console.log(`Today ${today.correct}/${stats.goal} correct${today.goalMet ? " ✓ goal reached" : ""}`);
61
- console.log(`Badges ${stats.badges.filter((b) => b.unlockedOn).length}/${stats.badges.length} · ${stats.mastered} cards mastered · companion: ${stats.companion.name}`);
41
+ console.log(t("cli.stats.streak", { days: streak.days, best: streak.best, count: streak.freezes }));
42
+ console.log(t("cli.stats.today", { correct: today.correct, goal: stats.goal, goal_reached: today.goalMet ? t("cli.stats.goalReached") : "" }));
43
+ console.log(t("cli.stats.badges", { unlocked: stats.badges.filter((b) => b.unlockedOn).length, total: stats.badges.length, mastered: stats.mastered, companion: stats.companion.name }));
62
44
 
63
45
  const entries = Object.values(state.items);
64
46
  if (!entries.length) return;
65
- const perBox = BOX_INTERVALS_DAYS.map((days, i) => `box ${i + 1} (${days}d): ${entries.filter((e) => e.box === i + 1).length}`);
47
+ const perBox = BOX_INTERVALS_DAYS.map((days, i) => t("cli.stats.box", { box: i + 1, days, count: entries.filter((e) => e.box === i + 1).length }));
66
48
  const correct = entries.reduce((sum, e) => sum + e.correct, 0);
67
49
  const total = entries.reduce((sum, e) => sum + e.seen, 0);
68
- console.log(`${entries.length} cards practised, ${correct}/${total} correct (${Math.round((correct / total) * 100)}%)`);
50
+ console.log(t("cli.stats.practised", { count: entries.length, correct, total, percent: Math.round((correct / total) * 100) }));
69
51
  console.log(perBox.join(" "));
70
52
  }
71
53
 
72
54
  const formatTime = (ms) => new Date(ms).toLocaleString("sv").slice(0, 16);
73
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
74
55
 
75
56
  async function confirm(question) {
76
57
  const rl = createInterface({ input: process.stdin, output: process.stdout });
77
58
  try {
78
- return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
59
+ const answer = (await rl.question(`${question} ${t("cli.restore.askSuffix")} `)).trim().toLowerCase();
60
+ return t("cli.restore.yes").split("|").includes(answer);
79
61
  } finally {
80
62
  rl.close();
81
63
  }
@@ -86,43 +68,48 @@ async function printData() {
86
68
  const library = await loadLibrary();
87
69
  const state = await loadState();
88
70
  const backups = await listBackups();
89
- const at = (file) => (existsSync(file) ? "" : " (not created yet)");
90
- console.log(`Dracosh keeps everything in ${HOME}\n`);
91
- console.log(` library.json your decks and cards: ${plural(library.decks.length, "deck")} · ${plural(library.cards.length, "card")}${at(DATA_FILES.library)}`);
92
- console.log(` state.json progress, streak and badges: ${Object.keys(state.items).length} practised${at(DATA_FILES.state)}`);
93
- console.log(` settings.json your settings${at(DATA_FILES.settings)}`);
94
- console.log(` backups/ ${backups.length ? `${plural(backups.length, "backup")}, the newest from ${formatTime(backups[0].created)}` : "none yet"}`);
95
- console.log(`\nTo keep it somewhere else (a synced folder, say), set DRACOSH_HOME. dracosh restore brings a backup back.`);
71
+ const missing = (file) => (existsSync(file) ? "" : t("cli.data.notCreated"));
72
+ console.log(`${t("cli.data.where", { home: HOME })}\n`);
73
+ console.log(t("cli.data.library", { decks: t("count.decks", { count: library.decks.length }), cards: t("count.cards", { count: library.cards.length }), missing: missing(DATA_FILES.library) }));
74
+ console.log(t("cli.data.state", { count: Object.keys(state.items).length, missing: missing(DATA_FILES.state) }));
75
+ console.log(t("cli.data.settings", { missing: missing(DATA_FILES.settings) }));
76
+ const what = backups.length ? t("cli.data.backupsSome", { backups: t("cli.backups", { count: backups.length }), time: formatTime(backups[0].created) }) : t("cli.data.none");
77
+ console.log(t("cli.data.backups", { what }));
78
+ console.log(`\n${t("cli.data.footer")}`);
96
79
  }
97
80
 
98
81
  async function restore(choice, { yes }) {
99
82
  const backups = await listBackups();
100
- if (!backups.length) return console.log(`No backups yet. Dracosh makes one every day you use it, in ${BACKUP_DIR}`);
83
+ if (!backups.length) return console.log(t("cli.restore.none", { dir: BACKUP_DIR }));
101
84
  if (!choice) {
102
- console.log(`Backups in ${BACKUP_DIR}, newest first:\n`);
85
+ console.log(`${t("cli.restore.listTitle", { dir: BACKUP_DIR })}\n`);
86
+ const reason = (b) => t(`cli.restore.reasons.${b.reason}`);
87
+ const width = Math.max(...backups.map((b) => reason(b).length));
103
88
  backups.forEach((b, i) => {
104
- const what = `${plural(b.decks, "deck")} · ${plural(b.cards, "card")} · ${b.practiced} practised`;
105
- console.log(` ${String(i + 1).padStart(2)} ${formatTime(b.created)} ${b.reason.padEnd(14)} ${what}`);
89
+ const what = t("cli.restore.row", { decks: t("count.decks", { count: b.decks }), cards: t("count.cards", { count: b.cards }), practised: b.practiced });
90
+ console.log(` ${String(i + 1).padStart(2)} ${formatTime(b.created)} ${reason(b).padEnd(width)} ${what}`);
106
91
  });
107
- return console.log(`\nBring one back with: dracosh restore <number>`);
92
+ return console.log(`\n${t("cli.restore.howTo")}`);
108
93
  }
109
94
 
110
95
  const backup = backups[Number(choice) - 1];
111
- if (!backup) throw new Error(`There's no backup number ${choice}. Run "dracosh restore" to see the list.`);
96
+ if (!backup) throw new Error(t("cli.restore.noSuch", { number: choice }));
112
97
  const running = runningPid();
113
98
  if (running) throw new Error(ALREADY_RUNNING(running));
114
99
  const has = ["cards", "progress", "settings"].filter((_, i) => [backup.cards || backup.decks, backup.hasState, backup.hasSettings][i]);
115
- console.log(`This brings back your ${has.join(", ").replace(/, (?=[^,]*$)/, " and ")} from the backup of ${formatTime(backup.created)}.`);
116
- console.log("What you have now is backed up first, so you can undo this.");
100
+ const what = new Intl.ListFormat(language(), { type: "conjunction" }).format(has.map((part) => t(`cli.restore.what.${part}`)));
101
+ console.log(t("cli.restore.bringsBack", { what, time: formatTime(backup.created) }));
102
+ console.log(t("cli.restore.undo"));
117
103
  if (!yes) {
118
- if (!process.stdin.isTTY) throw new Error("Add --yes to restore without a prompt.");
119
- if (!(await confirm("Restore it?"))) return console.log("Nothing changed.");
104
+ if (!process.stdin.isTTY) throw new Error(t("cli.restore.needsYes"));
105
+ if (!(await confirm(t("cli.restore.ask")))) return console.log(t("cli.restore.nothingChanged"));
120
106
  }
121
107
  await restoreBackup(backup.file);
122
- console.log("Restored.");
108
+ console.log(t("cli.restore.done"));
123
109
  }
124
110
 
125
111
  async function main() {
112
+ setLanguage(normalizeSettings(await loadSettingsRaw().catch(() => ({}))).language);
126
113
  const { values, positionals } = parseArgs({
127
114
  allowPositionals: true,
128
115
  options: {
@@ -137,10 +124,10 @@ async function main() {
137
124
  help: { type: "boolean", short: "h", default: false }
138
125
  }
139
126
  });
140
- if (values.help) return console.log(HELP);
127
+ if (values.help) return console.log(help());
141
128
  const [command, ...args] = positionals;
142
129
  if (command === "restore") return restore(args[0], values);
143
- if (command) throw new Error(`Unknown command "${command}". See dracosh --help.`);
130
+ if (command) throw new Error(t("cli.unknownCommand", { command }));
144
131
  if (values.data) return printData();
145
132
 
146
133
  const saved = normalizeSettings(await loadSettingsRaw());
@@ -152,14 +139,14 @@ async function main() {
152
139
  };
153
140
 
154
141
  if (values.preview) {
155
- if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
156
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
142
+ if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
143
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
157
144
  return render(React.createElement(Preview, { alerts })).waitUntilExit();
158
145
  }
159
146
 
160
147
  const state = await loadState();
161
148
  if (values.stats) return printStats(state, settings);
162
- if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
149
+ if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
163
150
  // a fresh install starts with the "Getting started" deck
164
151
  const library = await loadLibrary();
165
152
  const seeded = seedLibrary(library);
@@ -176,7 +163,7 @@ async function main() {
176
163
  let current = settings; // the session reads settings live, so /settings changes apply immediately
177
164
  let active = deck.name; // /add can switch to your first own deck
178
165
  const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
179
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
166
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
180
167
  const persistSettings = async (patch) => {
181
168
  current = { ...current, ...patch };
182
169
  await patchSettings(patch);
@@ -189,7 +176,7 @@ async function main() {
189
176
 
190
177
  main().catch((err) => {
191
178
  if (["EACCES", "EPERM", "ENOTDIR", "EEXIST"].includes(err.code)) {
192
- console.error(`Dracosh can't use ${HOME} for its data (${err.code}). Point DRACOSH_HOME at a folder you can write to.`);
179
+ console.error(t("cli.cantUseFolder", { home: HOME, code: err.code }));
193
180
  process.exit(1);
194
181
  }
195
182
  console.error(err.message);
package/src/commands.js CHANGED
@@ -1,19 +1,21 @@
1
+ import { t } from "./i18n.js";
2
+
1
3
  // `only` limits a command to one phase: "asking" (a question is open) or "waiting" (between questions)
2
4
  export const COMMANDS = [
3
- { name: "/hint", only: "asking", hint: "Reveal another letter (the card won't climb a box)" },
4
- { name: "/add", hint: "Add cards to a deck, or start a new one" },
5
- { name: "/decks", hint: "Switch to another deck, or start a new one" },
6
- { name: "/settings", hint: "Interval, quiet hours, sound, goal, tips" },
7
- { name: "/stats", hint: "Streak, month calendar and badges summary" },
8
- { name: "/badges", hint: "All badges and what unlocks them" },
9
- { name: "/companion", hint: "Your dragon, its element and the forms ahead" },
10
- { name: "/missed", hint: "Cards you got wrong today" },
11
- { name: "/pause", hint: "A break (30m, 2h) or days off (3d, 24.12 2.01)" },
12
- { name: "/help", aliases: ["/?"], hint: "Keys, how cards come back, the streak" },
13
- { name: "/quit", hint: "Exit Dracosh" }
5
+ { name: "/hint", only: "asking", get hint() { return t("commands.hint"); } },
6
+ { name: "/add", get hint() { return t("commands.add"); } },
7
+ { name: "/decks", get hint() { return t("commands.decks"); } },
8
+ { name: "/settings", get hint() { return t("commands.settings"); } },
9
+ { name: "/stats", get hint() { return t("commands.stats"); } },
10
+ { name: "/badges", get hint() { return t("commands.badges"); } },
11
+ { name: "/companion", get hint() { return t("commands.companion"); } },
12
+ { name: "/missed", get hint() { return t("commands.missed"); } },
13
+ { name: "/pause", get hint() { return t("commands.pause"); } },
14
+ { name: "/help", aliases: ["/?"], get hint() { return t("commands.help"); } },
15
+ { name: "/quit", get hint() { return t("commands.quit"); } }
14
16
  ];
15
17
 
16
- const CORRECT = { name: "/correct", hint: "Count my last answer as correct" };
18
+ const CORRECT = { name: "/correct", get hint() { return t("commands.correct"); } };
17
19
 
18
20
  // What the "/" menu offers right now (phase-only commands, and /correct right after a wrong answer)
19
21
  export function commandsFor({ phase, canOverrule = false }) {
package/src/demo.js CHANGED
@@ -9,3 +9,14 @@ export const DEMO_WORDS = [
9
9
  { noteId: 7, word: "fire", translations: ["ogień"], example: "Dragons breathe fire." },
10
10
  { noteId: 8, word: "streak", translations: ["seria", "passa"], example: "She kept her streak for a month." }
11
11
  ];
12
+
13
+ // Cards for the preview's answering scenes: sentences too long to type word for word (reveal them and
14
+ // grade yourself), and cloze cards asked one gap at a time
15
+ export const DEMO_SENTENCES = [
16
+ { noteId: "s1", word: "Drop me a line when you get there.", translations: ["Odezwij się, jak dojedziesz."] },
17
+ { noteId: "s2", word: "It's not my cup of tea.", translations: ["To nie moja bajka."], example: "Opera? It's not my cup of tea." }
18
+ ];
19
+ export const DEMO_CLOZE = [
20
+ { noteId: "z1", word: "I'm {{looking forward}} to {{it}}.", translations: ["Cieszę się na to."], cloze: ["looking forward", "it"], directions: ["c1", "c2"] },
21
+ { noteId: "z2", word: "Dragons {{breathe}} fire.", translations: ["Smoki zieją ogniem."], cloze: ["breathe"], directions: ["c1"] }
22
+ ];
package/src/diff.js CHANGED
@@ -1,17 +1,14 @@
1
1
  // Character diff of your answer against the expected one, for the "you wrote" line after a miss.
2
- // Comparison is as forgiving as the judge: case, Polish diacritics and ł are ignored per character.
2
+ // Comparison is as forgiving as the judge: case and diacritics are ignored per character.
3
+ import { fold } from "./judge.js";
3
4
 
4
- const foldChar = (ch) =>
5
- ch
6
- .toLowerCase()
7
- .replace(/ł/g, "l")
8
- .normalize("NFD")
9
- .replace(/[̀-ͯ]/g, "");
5
+ const foldChar = (ch) => fold(ch.toLowerCase());
10
6
 
11
7
  // → [{ ch, ok }] for every character of `given`: ok = this character lines up with `target`.
12
8
  // Alignment comes from a Levenshtein backtrace, so a single missing or extra letter doesn't
13
9
  // mark the whole rest of the word wrong.
14
- export function diffChars(given, target) {
10
+ // `gaps`: also a { ch: "_", missing: true } where letters of `target` were left out ("tomor_ow")
11
+ export function diffChars(given, target, { gaps = false } = {}) {
15
12
  const a = [...given].map(foldChar);
16
13
  const b = [...target].map(foldChar);
17
14
  const rows = a.length + 1;
@@ -28,6 +25,7 @@ export function diffChars(given, target) {
28
25
 
29
26
  // walk back, preferring matches; deletions in `target` don't produce a character of `given`
30
27
  const marks = new Array(a.length).fill(false);
28
+ const missedBefore = new Array(a.length + 1).fill(false);
31
29
  let i = a.length;
32
30
  let j = b.length;
33
31
  while (i > 0 || j > 0) {
@@ -39,8 +37,20 @@ export function diffChars(given, target) {
39
37
  marks[i - 1] = false; // extra character you typed
40
38
  i -= 1;
41
39
  } else {
42
- j -= 1; // character you missed: nothing of yours to mark
40
+ missedBefore[i] = true; // character you missed: nothing of yours to mark, a gap at most
41
+ j -= 1;
43
42
  }
44
43
  }
45
- return [...given].map((ch, k) => ({ ch, ok: marks[k] }));
44
+ const parts = [...given].flatMap((ch, k) => [...(gaps && missedBefore[k] ? [{ ch: "_", ok: false, missing: true }] : []), { ch, ok: marks[k] }]);
45
+ return gaps && missedBefore[a.length] ? [...parts, { ch: "_", ok: false, missing: true }] : parts;
46
+ }
47
+
48
+ // → [{ ch, ok }] for every character of `target`, after an answer right but for its accents ("jablko"
49
+ // for "jabłko"): ok = you wrote this very letter, so only ł is marked. null when the two don't line
50
+ // up letter for letter ("strasse" for "straße").
51
+ export function accentMarks(given, target) {
52
+ const mine = [...given.trim().normalize("NFKC").toLowerCase()]; // "neko" typed full-width is "neko"
53
+ const letters = [...target.normalize("NFC")];
54
+ if (mine.length !== letters.length) return null;
55
+ return letters.map((ch, i) => ({ ch, ok: ch.toLowerCase() === mine[i] }));
46
56
  }
package/src/i18n.js ADDED
@@ -0,0 +1,68 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ // UI text lives in locales/<lang>.json under nested keys, read as "help.title". English is complete;
4
+ // any other language may leave keys out, and English fills the gaps.
5
+ const load = (lang) => {
6
+ try {
7
+ return JSON.parse(readFileSync(new URL(`../locales/${lang}.json`, import.meta.url), "utf8"));
8
+ } catch {
9
+ return null;
10
+ }
11
+ };
12
+
13
+ // the languages Dracosh speaks, each named in its own language for /settings
14
+ export const LANGUAGES = { en: "English", pl: "Polski", de: "Deutsch", fr: "Français", uk: "Українська" };
15
+
16
+ const english = load("en");
17
+ let current = { lang: "en", messages: english };
18
+
19
+ // → the language now in use: the one asked for, or English when there is no such locale file
20
+ export function setLanguage(lang) {
21
+ const messages = lang === "en" ? english : load(lang);
22
+ current = messages ? { lang, messages } : { lang: "en", messages: english };
23
+ return current.lang;
24
+ }
25
+
26
+ export const language = () => current.lang;
27
+
28
+ // The system's language, the way POSIX tools pick it (LC_ALL, then LC_MESSAGES, then LANG), or
29
+ // Intl's when none is set; English when Dracosh doesn't speak it.
30
+ export function systemLanguage(env = process.env) {
31
+ const set = [env.LC_ALL, env.LC_MESSAGES, env.LANG].find((value) => value && !/^(C|POSIX)\b/i.test(value));
32
+ const code = (set ?? Intl.DateTimeFormat().resolvedOptions().locale).toLowerCase().slice(0, 2);
33
+ return Object.hasOwn(LANGUAGES, code) ? code : "en";
34
+ }
35
+
36
+ // the locale for dates and times: British English keeps "14 Oct" and a 24-hour clock
37
+ export const dateLocale = () => (current.lang === "en" ? "en-GB" : current.lang);
38
+
39
+ const lookup = (messages, key) => key.split(".").reduce((node, part) => node?.[part], messages);
40
+
41
+ // a locale entry as it is, for data that isn't a single text (the tour's cards)
42
+ export const entry = (key) => lookup(current.messages, key) ?? lookup(english, key);
43
+
44
+ // Plural text is an object of forms ({ one, few, many, other }); Intl.PluralRules picks the form the
45
+ // language uses for `count` (Polish: 1 karta, 2 karty, 5 kart).
46
+ function pluralForm(forms, count) {
47
+ return forms[new Intl.PluralRules(current.lang).select(count)] ?? forms.other;
48
+ }
49
+
50
+ // t("help.title"), t("count.cards", { count: 3 }): {placeholders} are filled from `vars`.
51
+ // An unknown key comes back as itself, so a missing text shows up instead of crashing.
52
+ export function t(key, vars = {}) {
53
+ let text = lookup(current.messages, key) ?? lookup(english, key);
54
+ if (text === undefined) return key;
55
+ if (typeof text === "object") text = pluralForm(text, vars.count ?? 0);
56
+ return text.replace(/\{(\w+)\}/g, (match, name) => (vars[name] === undefined ? match : String(vars[name])));
57
+ }
58
+
59
+ // every key of a locale, flattened ("help.title"); plural forms and lists count as one key
60
+ export const isPlural = (value) => Boolean(value) && typeof value === "object" && "other" in value;
61
+ export function keysOf(messages, prefix = "") {
62
+ return Object.entries(messages).flatMap(([name, value]) => {
63
+ const key = prefix ? `${prefix}.${name}` : name;
64
+ return value && typeof value === "object" && !Array.isArray(value) && !isPlural(value) ? keysOf(value, key) : [key];
65
+ });
66
+ }
67
+
68
+ export const englishMessages = () => english;