dracosh 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -22
- package/assets/sounds/badge-1.wav +0 -0
- package/assets/sounds/badge-2.wav +0 -0
- package/assets/sounds/badge-3.wav +0 -0
- package/assets/sounds/badge-4.wav +0 -0
- package/locales/de.json +1046 -0
- package/locales/en.json +1029 -0
- package/locales/fr.json +1094 -0
- package/locales/pl.json +1117 -0
- package/locales/uk.json +1118 -0
- package/package.json +2 -2
- package/src/alerts.js +7 -4
- package/src/backup.js +96 -0
- package/src/cardline.js +71 -0
- package/src/cli.js +106 -38
- package/src/commands.js +15 -13
- package/src/demo.js +11 -0
- package/src/diff.js +13 -7
- package/src/i18n.js +68 -0
- package/src/judge.js +51 -12
- package/src/library.js +154 -0
- package/src/lock.js +64 -0
- package/src/manage.js +165 -0
- package/src/pause.js +22 -0
- package/src/progress.js +202 -93
- package/src/quiet.js +4 -3
- package/src/scheduler.js +39 -30
- package/src/session.js +181 -33
- package/src/settings.js +15 -13
- package/src/starter.js +47 -0
- package/src/store.js +58 -17
- package/src/tips.js +17 -25
- package/src/ui/AddCard.js +496 -0
- package/src/ui/AnswerInput.js +28 -13
- package/src/ui/App.js +360 -89
- package/src/ui/BadgeUnlock.js +51 -0
- package/src/ui/Badges.js +79 -20
- package/src/ui/Choice.js +38 -0
- package/src/ui/Companion.js +24 -39
- package/src/ui/Confetti.js +2 -2
- package/src/ui/Decks.js +99 -0
- package/src/ui/DieRoll.js +104 -0
- package/src/ui/Evolution.js +11 -10
- package/src/ui/Hatch.js +9 -7
- package/src/ui/Header.js +62 -19
- package/src/ui/Help.js +74 -0
- package/src/ui/Mascot.js +89 -40
- package/src/ui/Missed.js +15 -13
- package/src/ui/Preview.js +123 -29
- package/src/ui/Reset.js +71 -0
- package/src/ui/Settings.js +34 -23
- package/src/ui/Stats.js +28 -24
- package/src/ui/Summary.js +18 -10
- package/src/ui/TheOne.js +122 -0
- package/src/ui/icons.js +156 -25
- package/src/ui/kit.js +87 -2
- package/src/vacation.js +9 -3
- package/src/words.js +22 -14
- package/assets/sounds/badge.wav +0 -0
- package/data/tips.json +0 -1362
- package/src/ui/Tip.js +0 -25
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dracosh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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
|
-
"
|
|
33
|
+
"locales",
|
|
34
34
|
"NOTICE"
|
|
35
35
|
],
|
|
36
36
|
"engines": {
|
package/src/alerts.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t } from "./i18n.js";
|
|
1
2
|
import { execFile } from "node:child_process";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -21,13 +22,15 @@ export function createAlerts(initial = {}) {
|
|
|
21
22
|
// a new question while you're in another window: sound plus a Notification Center banner
|
|
22
23
|
ask() {
|
|
23
24
|
play("ask");
|
|
24
|
-
|
|
25
|
+
// the text goes to AppleScript as an argument, never into the script itself
|
|
26
|
+
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
27
|
},
|
|
26
|
-
// The biggest thing that just happened wins: evolution >
|
|
27
|
-
// On a plain correct answer the pitch rises with the combo and resets on a miss.
|
|
28
|
+
// The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
|
|
29
|
+
// On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
|
|
30
|
+
// on their own, each as its line lights up (see BadgeUnlock).
|
|
28
31
|
result(result, { cheers = [], combo = 0 } = {}) {
|
|
29
32
|
if (result === "wrong") return play("wrong");
|
|
30
|
-
for (const kind of ["evolve", "
|
|
33
|
+
for (const kind of ["evolve", "goal", "combo"]) {
|
|
31
34
|
if (cheers.includes(kind)) return play(kind);
|
|
32
35
|
}
|
|
33
36
|
if (result === "typo") return play("close");
|
package/src/backup.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { t } from "./i18n.js";
|
|
2
|
+
import { copyFile, readdir, rm } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { dayKey } from "./dates.js";
|
|
5
|
+
import { DATA_FILES, HOME, readJson, writeJson } from "./store.js";
|
|
6
|
+
|
|
7
|
+
// A backup is one JSON file in ~/.dracosh/backups holding the library, progress and settings as they
|
|
8
|
+
// were. One is taken on the first start of each day, and right before anything that changes a lot at
|
|
9
|
+
// once (a restore now; imports, deletions and resets later).
|
|
10
|
+
export const BACKUP_DIR = join(HOME, "backups");
|
|
11
|
+
const BACKUP_FORMAT = 1;
|
|
12
|
+
export const KEEP = 7; // per kind: the last 7 daily ones, and the last 7 taken before an operation
|
|
13
|
+
|
|
14
|
+
// "2026-10-09T21:15:03.120Z" → "2026-10-09_21-15-03", so file names sort by time
|
|
15
|
+
const stamp = (now) => new Date(now).toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-");
|
|
16
|
+
|
|
17
|
+
// → the file it wrote, or null when there is nothing to back up (or, with `skipDamaged`, when a data file
|
|
18
|
+
// is too damaged to read: a backup missing the library would push the good ones out). Otherwise a damaged
|
|
19
|
+
// file is set aside as it is (library.json.damaged-<day>, one a day) and the backup goes on, so a
|
|
20
|
+
// restore still works.
|
|
21
|
+
export async function backupNow(reason, now = Date.now(), { skipDamaged = false } = {}) {
|
|
22
|
+
const files = {};
|
|
23
|
+
for (const [name, file] of Object.entries(DATA_FILES)) {
|
|
24
|
+
try {
|
|
25
|
+
const data = await readJson(file, null);
|
|
26
|
+
if (data) files[name] = data;
|
|
27
|
+
} catch {
|
|
28
|
+
if (name === "settings") continue; // broken settings just mean the defaults: back up the rest
|
|
29
|
+
if (skipDamaged) return null;
|
|
30
|
+
await copyFile(file, `${file}.damaged-${dayKey(now)}`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!Object.keys(files).length) return null;
|
|
34
|
+
const file = join(BACKUP_DIR, `${stamp(now)}-${reason}.json`);
|
|
35
|
+
await writeJson(file, { format: BACKUP_FORMAT, created: now, reason, files });
|
|
36
|
+
await prune();
|
|
37
|
+
return file;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function backupFiles() {
|
|
41
|
+
try {
|
|
42
|
+
return (await readdir(BACKUP_DIR)).filter((name) => name.endsWith(".json")).sort().reverse(); // newest first
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err.code === "ENOENT") return [];
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const isDaily = (name) => name.endsWith("-daily.json");
|
|
50
|
+
|
|
51
|
+
async function prune() {
|
|
52
|
+
const names = await backupFiles();
|
|
53
|
+
const old = [...names.filter(isDaily).slice(KEEP), ...names.filter((name) => !isDaily(name)).slice(KEEP)];
|
|
54
|
+
await Promise.all(old.map((name) => rm(join(BACKUP_DIR, name), { force: true })));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// the first start of a day backs up what the day before left behind
|
|
58
|
+
export async function dailyBackup(now = Date.now()) {
|
|
59
|
+
const today = dayKey(now);
|
|
60
|
+
const backups = await listBackups();
|
|
61
|
+
if (backups.some((b) => b.reason === "daily" && dayKey(b.created) === today)) return null;
|
|
62
|
+
return backupNow("daily", now, { skipDamaged: true });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// → newest first: { file, created, reason, decks, cards, practiced }
|
|
66
|
+
export async function listBackups() {
|
|
67
|
+
const list = [];
|
|
68
|
+
for (const name of await backupFiles()) {
|
|
69
|
+
const file = join(BACKUP_DIR, name);
|
|
70
|
+
const backup = await readJson(file, null).catch(() => null); // a damaged file just isn't offered
|
|
71
|
+
if (backup?.format !== BACKUP_FORMAT || !backup.files || typeof backup.files !== "object") continue;
|
|
72
|
+
const { library, state } = backup.files;
|
|
73
|
+
list.push({
|
|
74
|
+
file,
|
|
75
|
+
created: backup.created,
|
|
76
|
+
reason: backup.reason,
|
|
77
|
+
decks: library?.decks?.length ?? 0,
|
|
78
|
+
cards: library?.cards?.length ?? 0,
|
|
79
|
+
practiced: Object.keys(state?.items ?? {}).length,
|
|
80
|
+
hasState: Boolean(state),
|
|
81
|
+
hasSettings: Boolean(backup.files.settings)
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return list.sort((a, b) => b.created - a.created); // file names only go down to the second
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Puts a backup's files back. What's there now is backed up first, so a restore can be undone too.
|
|
88
|
+
// A file the backup doesn't have is left as it is: a restore never deletes your cards or progress.
|
|
89
|
+
export async function restoreBackup(file, now = Date.now()) {
|
|
90
|
+
const backup = await readJson(file, null);
|
|
91
|
+
if (backup?.format !== BACKUP_FORMAT || !backup.files) throw new Error(t("errors.notABackup", { file }));
|
|
92
|
+
await backupNow("before-restore", now);
|
|
93
|
+
for (const [name, target] of Object.entries(DATA_FILES)) {
|
|
94
|
+
if (backup.files[name]) await writeJson(target, backup.files[name]);
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/cardline.js
ADDED
|
@@ -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
|
@@ -2,45 +2,35 @@
|
|
|
2
2
|
import { render } from "ink";
|
|
3
3
|
import React from "react";
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
5
6
|
import { createAlerts } from "./alerts.js";
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
|
+
import { language, setLanguage, t } from "./i18n.js";
|
|
9
|
+
import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup } from "./backup.js";
|
|
6
10
|
import { ensureProgress, snapshot } from "./progress.js";
|
|
7
11
|
import { BOX_INTERVALS_DAYS } from "./scheduler.js";
|
|
8
12
|
import { createSession } from "./session.js";
|
|
9
13
|
import { DEFAULTS, formatInterval, normalizeSettings } from "./settings.js";
|
|
10
|
-
import {
|
|
14
|
+
import { seedLibrary } from "./starter.js";
|
|
15
|
+
import { DATA_FILES, HOME, loadLibrary, loadSettingsRaw, loadState, patchSettings, saveLibrary } from "./store.js";
|
|
11
16
|
import { App } from "./ui/App.js";
|
|
12
17
|
import { Preview } from "./ui/Preview.js";
|
|
13
|
-
import {
|
|
18
|
+
import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
|
|
19
|
+
import * as manage from "./manage.js";
|
|
20
|
+
import { findDeck } from "./library.js";
|
|
21
|
+
import { loadAllWords, loadWords, missingDeck } from "./words.js";
|
|
14
22
|
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
const HELP = `Dracosh: vocabulary quiz from your Anki deck (read-only)
|
|
18
|
-
|
|
19
|
-
Usage: dracosh [options]
|
|
20
|
-
|
|
21
|
-
--deck <name> Anki deck to take words from (default: ${DEFAULT_DECK})
|
|
22
|
-
--every <time> pause between questions: 30s, 10m, 1h (default: ${formatInterval(DEFAULTS.everyMs)})
|
|
23
|
-
--no-sound turn sound effects off
|
|
24
|
-
--volume <0-1> sound volume (default: ${DEFAULTS.volume})
|
|
25
|
-
--stats print progress and exit
|
|
26
|
-
--preview browse every animation and screen on made-up data (nothing is saved)
|
|
27
|
-
-h, --help show this help
|
|
28
|
-
|
|
29
|
-
Flags override your saved settings for this run only. Change the saved ones with /settings.
|
|
30
|
-
|
|
31
|
-
While running: Enter submits, "/" opens the command menu (/settings, /stats, /badges, /skip, /quit),
|
|
32
|
-
Esc quits (clears the line first if you typed something). Ctrl+C also works.
|
|
33
|
-
Between questions: Enter asks the next word right away, q quits.`;
|
|
23
|
+
const help = () => t("cli.help", { interval: formatInterval(DEFAULTS.everyMs), volume: DEFAULTS.volume });
|
|
34
24
|
|
|
35
25
|
function parseEvery(value) {
|
|
36
26
|
const match = /^(\d+(?:\.\d+)?)(s|m|h)$/.exec(value);
|
|
37
|
-
if (!match) throw new Error(
|
|
27
|
+
if (!match) throw new Error(t("cli.badEvery", { value }));
|
|
38
28
|
return Number(match[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[match[2]];
|
|
39
29
|
}
|
|
40
30
|
|
|
41
31
|
function parseVolume(value) {
|
|
42
32
|
const volume = Number(value);
|
|
43
|
-
if (!(volume >= 0 && volume <= 1)) throw new Error(
|
|
33
|
+
if (!(volume >= 0 && volume <= 1)) throw new Error(t("cli.badVolume", { value }));
|
|
44
34
|
return volume;
|
|
45
35
|
}
|
|
46
36
|
|
|
@@ -48,32 +38,97 @@ function printStats(state, settings) {
|
|
|
48
38
|
ensureProgress(state);
|
|
49
39
|
const stats = snapshot(state, { goal: settings.dailyGoal });
|
|
50
40
|
const { streak, today } = stats;
|
|
51
|
-
console.log(
|
|
52
|
-
console.log(
|
|
53
|
-
console.log(
|
|
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 }));
|
|
54
44
|
|
|
55
45
|
const entries = Object.values(state.items);
|
|
56
46
|
if (!entries.length) return;
|
|
57
|
-
const perBox = BOX_INTERVALS_DAYS.map((days, i) =>
|
|
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 }));
|
|
58
48
|
const correct = entries.reduce((sum, e) => sum + e.correct, 0);
|
|
59
49
|
const total = entries.reduce((sum, e) => sum + e.seen, 0);
|
|
60
|
-
console.log(
|
|
50
|
+
console.log(t("cli.stats.practised", { count: entries.length, correct, total, percent: Math.round((correct / total) * 100) }));
|
|
61
51
|
console.log(perBox.join(" "));
|
|
62
52
|
}
|
|
63
53
|
|
|
54
|
+
const formatTime = (ms) => new Date(ms).toLocaleString("sv").slice(0, 16);
|
|
55
|
+
|
|
56
|
+
async function confirm(question) {
|
|
57
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
58
|
+
try {
|
|
59
|
+
const answer = (await rl.question(`${question} ${t("cli.restore.askSuffix")} `)).trim().toLowerCase();
|
|
60
|
+
return t("cli.restore.yes").split("|").includes(answer);
|
|
61
|
+
} finally {
|
|
62
|
+
rl.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// --data: where everything lives, and what's in it
|
|
67
|
+
async function printData() {
|
|
68
|
+
const library = await loadLibrary();
|
|
69
|
+
const state = await loadState();
|
|
70
|
+
const backups = await listBackups();
|
|
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")}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function restore(choice, { yes }) {
|
|
82
|
+
const backups = await listBackups();
|
|
83
|
+
if (!backups.length) return console.log(t("cli.restore.none", { dir: BACKUP_DIR }));
|
|
84
|
+
if (!choice) {
|
|
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));
|
|
88
|
+
backups.forEach((b, i) => {
|
|
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}`);
|
|
91
|
+
});
|
|
92
|
+
return console.log(`\n${t("cli.restore.howTo")}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const backup = backups[Number(choice) - 1];
|
|
96
|
+
if (!backup) throw new Error(t("cli.restore.noSuch", { number: choice }));
|
|
97
|
+
const running = runningPid();
|
|
98
|
+
if (running) throw new Error(ALREADY_RUNNING(running));
|
|
99
|
+
const has = ["cards", "progress", "settings"].filter((_, i) => [backup.cards || backup.decks, backup.hasState, backup.hasSettings][i]);
|
|
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"));
|
|
103
|
+
if (!yes) {
|
|
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"));
|
|
106
|
+
}
|
|
107
|
+
await restoreBackup(backup.file);
|
|
108
|
+
console.log(t("cli.restore.done"));
|
|
109
|
+
}
|
|
110
|
+
|
|
64
111
|
async function main() {
|
|
65
|
-
|
|
112
|
+
setLanguage(normalizeSettings(await loadSettingsRaw().catch(() => ({}))).language);
|
|
113
|
+
const { values, positionals } = parseArgs({
|
|
114
|
+
allowPositionals: true,
|
|
66
115
|
options: {
|
|
67
|
-
deck: { type: "string"
|
|
116
|
+
deck: { type: "string" },
|
|
68
117
|
every: { type: "string" },
|
|
69
118
|
volume: { type: "string" },
|
|
70
119
|
"no-sound": { type: "boolean", default: false },
|
|
71
120
|
stats: { type: "boolean", default: false },
|
|
121
|
+
data: { type: "boolean", default: false },
|
|
72
122
|
preview: { type: "boolean", default: false },
|
|
123
|
+
yes: { type: "boolean", short: "y", default: false },
|
|
73
124
|
help: { type: "boolean", short: "h", default: false }
|
|
74
125
|
}
|
|
75
126
|
});
|
|
76
|
-
if (values.help) return console.log(
|
|
127
|
+
if (values.help) return console.log(help());
|
|
128
|
+
const [command, ...args] = positionals;
|
|
129
|
+
if (command === "restore") return restore(args[0], values);
|
|
130
|
+
if (command) throw new Error(t("cli.unknownCommand", { command }));
|
|
131
|
+
if (values.data) return printData();
|
|
77
132
|
|
|
78
133
|
const saved = normalizeSettings(await loadSettingsRaw());
|
|
79
134
|
const settings = {
|
|
@@ -84,21 +139,30 @@ async function main() {
|
|
|
84
139
|
};
|
|
85
140
|
|
|
86
141
|
if (values.preview) {
|
|
87
|
-
if (!process.stdin.isTTY) throw new Error("
|
|
142
|
+
if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
|
|
88
143
|
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
89
144
|
return render(React.createElement(Preview, { alerts })).waitUntilExit();
|
|
90
145
|
}
|
|
91
146
|
|
|
92
147
|
const state = await loadState();
|
|
93
148
|
if (values.stats) return printStats(state, settings);
|
|
94
|
-
if (!process.stdin.isTTY) throw new Error("
|
|
149
|
+
if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
|
|
150
|
+
// a fresh install starts with the "Getting started" deck
|
|
151
|
+
const library = await loadLibrary();
|
|
152
|
+
const seeded = seedLibrary(library);
|
|
153
|
+
if (values.deck && !findDeck(library, values.deck)) throw missingDeck(library, values.deck); // before anything is written
|
|
95
154
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (
|
|
155
|
+
acquireLock();
|
|
156
|
+
await dailyBackup();
|
|
157
|
+
if (seeded) await saveLibrary(library);
|
|
158
|
+
|
|
159
|
+
// --deck must exist (fail fast, before taking over the screen); a deck saved in /decks that has
|
|
160
|
+
// since gone just falls back to the first one
|
|
161
|
+
const { deck } = values.deck ? await loadWords(values.deck) : await loadWords(settings.deck).catch(() => loadWords());
|
|
99
162
|
|
|
100
163
|
let current = settings; // the session reads settings live, so /settings changes apply immediately
|
|
101
|
-
|
|
164
|
+
let active = deck.name; // /add can switch to your first own deck
|
|
165
|
+
const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
|
|
102
166
|
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
103
167
|
const persistSettings = async (patch) => {
|
|
104
168
|
current = { ...current, ...patch };
|
|
@@ -106,11 +170,15 @@ async function main() {
|
|
|
106
170
|
};
|
|
107
171
|
|
|
108
172
|
// the session summary screen stays on screen after exit, so nothing more to print here
|
|
109
|
-
const app = render(React.createElement(App, { session, deck:
|
|
173
|
+
const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name) }));
|
|
110
174
|
await app.waitUntilExit();
|
|
111
175
|
}
|
|
112
176
|
|
|
113
177
|
main().catch((err) => {
|
|
178
|
+
if (["EACCES", "EPERM", "ENOTDIR", "EEXIST"].includes(err.code)) {
|
|
179
|
+
console.error(t("cli.cantUseFolder", { home: HOME, code: err.code }));
|
|
180
|
+
process.exit(1);
|
|
181
|
+
}
|
|
114
182
|
console.error(err.message);
|
|
115
183
|
process.exit(1);
|
|
116
184
|
});
|
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
|
|
4
|
-
{ name: "/
|
|
5
|
-
{ name: "/
|
|
6
|
-
{ name: "/
|
|
7
|
-
{ name: "/
|
|
8
|
-
{ name: "/
|
|
9
|
-
{ name: "/
|
|
10
|
-
{ name: "/
|
|
11
|
-
{ name: "/
|
|
12
|
-
{ name: "/
|
|
13
|
-
{ name: "/quit", hint
|
|
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
|
|
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 }) {
|
|
@@ -21,7 +23,7 @@ export function commandsFor({ phase, canOverrule = false }) {
|
|
|
21
23
|
return canOverrule ? [CORRECT, ...base] : base;
|
|
22
24
|
}
|
|
23
25
|
|
|
24
|
-
// "/s" narrows to commands starting with it (aliases count: "
|
|
26
|
+
// "/s" narrows to commands starting with it (aliases count: "/?" finds /help). Arguments are ignored: "/pause 30m" matches /pause.
|
|
25
27
|
export function matchCommands(value, commands = COMMANDS) {
|
|
26
28
|
const query = value.trim().split(/\s+/)[0].toLowerCase();
|
|
27
29
|
return commands.filter((command) => command.name.startsWith(query) || command.aliases?.some((alias) => alias.startsWith(query)));
|
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,12 +1,8 @@
|
|
|
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
|
|
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
|
|
@@ -44,3 +40,13 @@ export function diffChars(given, target) {
|
|
|
44
40
|
}
|
|
45
41
|
return [...given].map((ch, k) => ({ ch, ok: marks[k] }));
|
|
46
42
|
}
|
|
43
|
+
|
|
44
|
+
// → [{ ch, ok }] for every character of `target`, after an answer right but for its accents ("jablko"
|
|
45
|
+
// for "jabłko"): ok = you wrote this very letter, so only ł is marked. null when the two don't line
|
|
46
|
+
// up letter for letter ("strasse" for "straße").
|
|
47
|
+
export function accentMarks(given, target) {
|
|
48
|
+
const mine = [...given.trim().normalize("NFC").toLowerCase()];
|
|
49
|
+
const letters = [...target.normalize("NFC")];
|
|
50
|
+
if (mine.length !== letters.length) return null;
|
|
51
|
+
return letters.map((ch, i) => ({ ch, ok: ch.toLowerCase() === mine[i] }));
|
|
52
|
+
}
|
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;
|