dracosh 0.2.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 +16 -11
- 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 +3 -1
- package/src/backup.js +2 -1
- package/src/cardline.js +71 -0
- package/src/cli.js +39 -52
- package/src/commands.js +14 -12
- package/src/demo.js +11 -0
- package/src/diff.js +13 -7
- package/src/i18n.js +68 -0
- package/src/judge.js +24 -6
- package/src/library.js +62 -35
- package/src/lock.js +2 -1
- package/src/manage.js +150 -60
- package/src/pause.js +1 -2
- package/src/progress.js +76 -59
- package/src/quiet.js +3 -2
- package/src/scheduler.js +3 -6
- package/src/session.js +69 -19
- package/src/settings.js +13 -6
- package/src/starter.js +36 -27
- package/src/store.js +9 -7
- package/src/tips.js +12 -3
- package/src/ui/AddCard.js +405 -81
- package/src/ui/AnswerInput.js +22 -10
- package/src/ui/App.js +181 -50
- package/src/ui/BadgeUnlock.js +4 -3
- package/src/ui/Badges.js +9 -8
- package/src/ui/Choice.js +14 -9
- package/src/ui/Companion.js +13 -13
- package/src/ui/Confetti.js +2 -2
- package/src/ui/Decks.js +58 -8
- package/src/ui/DieRoll.js +9 -9
- package/src/ui/Evolution.js +7 -7
- package/src/ui/Hatch.js +7 -6
- package/src/ui/Header.js +58 -16
- package/src/ui/Help.js +31 -25
- package/src/ui/Mascot.js +1 -2
- package/src/ui/Missed.js +13 -12
- package/src/ui/Preview.js +48 -29
- package/src/ui/Reset.js +13 -14
- package/src/ui/Settings.js +26 -19
- package/src/ui/Stats.js +24 -23
- package/src/ui/Summary.js +10 -9
- package/src/ui/TheOne.js +7 -6
- package/src/ui/icons.js +1 -2
- package/src/ui/kit.js +34 -6
- package/src/vacation.js +2 -1
- package/src/words.js +2 -1
- package/data/tips.json +0 -32
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,7 +22,8 @@ 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
28
|
// The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
|
|
27
29
|
// On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
|
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(
|
|
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]);
|
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
|
@@ -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
|
|
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(
|
|
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(
|
|
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(
|
|
60
|
-
console.log(
|
|
61
|
-
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 }));
|
|
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) =>
|
|
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(
|
|
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
|
-
|
|
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
|
|
90
|
-
console.log(
|
|
91
|
-
console.log(
|
|
92
|
-
console.log(
|
|
93
|
-
console.log(
|
|
94
|
-
|
|
95
|
-
console.log(
|
|
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(
|
|
83
|
+
if (!backups.length) return console.log(t("cli.restore.none", { dir: BACKUP_DIR }));
|
|
101
84
|
if (!choice) {
|
|
102
|
-
console.log(
|
|
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 =
|
|
105
|
-
console.log(` ${String(i + 1).padStart(2)} ${formatTime(b.created)} ${b.
|
|
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(`\
|
|
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(
|
|
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
|
-
|
|
116
|
-
console.log("
|
|
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("
|
|
119
|
-
if (!(await confirm("
|
|
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("
|
|
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(
|
|
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(
|
|
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("
|
|
142
|
+
if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
|
|
156
143
|
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
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("
|
|
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);
|
|
@@ -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(
|
|
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
|
|
4
|
-
{ name: "/add", hint
|
|
5
|
-
{ name: "/decks", hint
|
|
6
|
-
{ name: "/settings", hint
|
|
7
|
-
{ name: "/stats", hint
|
|
8
|
-
{ name: "/badges", hint
|
|
9
|
-
{ name: "/companion", hint
|
|
10
|
-
{ name: "/missed", hint
|
|
11
|
-
{ name: "/pause", hint
|
|
12
|
-
{ name: "/help", aliases: ["/?"], hint
|
|
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 }) {
|
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;
|
package/src/judge.js
CHANGED
|
@@ -22,9 +22,26 @@ function plain(s) {
|
|
|
22
22
|
return text || s.trim().toLowerCase(); // an answer made only of punctuation ("?") is still itself
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
//
|
|
25
|
+
// Letters that don't decompose into a base letter and an accent, spelled the way a keyboard without them would
|
|
26
|
+
const SPELLED = { ł: "l", ß: "ss", æ: "ae", œ: "oe", ø: "o", đ: "d", ð: "d", þ: "th", ı: "i" };
|
|
27
|
+
// й, ї and ў are letters of their own in Ukrainian and Belarusian (on every keyboard there), not и, і, у with an accent
|
|
28
|
+
const OWN = { й: "\ue000", ї: "\ue001", ў: "\ue002" };
|
|
29
|
+
const OWN_BACK = Object.fromEntries(Object.entries(OWN).map(([letter, mark]) => [mark, letter]));
|
|
30
|
+
|
|
31
|
+
// Diacritics folded away from lowercase text: "żółw" → "zolw", "straße" → "strasse", "fi" → "fi"
|
|
32
|
+
export function fold(s) {
|
|
33
|
+
return s
|
|
34
|
+
.normalize("NFKC")
|
|
35
|
+
.replace(/[йїў]/g, (ch) => OWN[ch])
|
|
36
|
+
.replace(/[łßæœøđðþı]/g, (ch) => SPELLED[ch])
|
|
37
|
+
.normalize("NFD")
|
|
38
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
39
|
+
.replace(/[\ue000-\ue002]/g, (ch) => OWN_BACK[ch]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// plain(), and diacritics folded too
|
|
26
43
|
export function normalize(s) {
|
|
27
|
-
return plain(s)
|
|
44
|
+
return fold(plain(s));
|
|
28
45
|
}
|
|
29
46
|
|
|
30
47
|
// Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
|
|
@@ -60,15 +77,16 @@ export function closestCandidate(answer, candidates) {
|
|
|
60
77
|
return best;
|
|
61
78
|
}
|
|
62
79
|
|
|
63
|
-
// → "exact" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
|
|
64
|
-
// diacritics ("zolw" for "żółw")
|
|
65
|
-
//
|
|
80
|
+
// → "exact" | "accent" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
|
|
81
|
+
// diacritics ("zolw" for "żółw") are "accent": right, quietly (not everyone has the letters on their
|
|
82
|
+
// keyboard), with the missing letters marked in the verdict. One more typo is forgiven on longer answers, but
|
|
83
|
+
// never in numbers: "123457" isn't "123456".
|
|
66
84
|
export function judge(answer, candidates) {
|
|
67
85
|
if (!answer.trim()) return "wrong";
|
|
68
86
|
const given = normalize(answer);
|
|
69
87
|
if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
|
|
70
88
|
const targets = candidates.map(normalize);
|
|
71
|
-
if (targets.includes(given)) return "
|
|
89
|
+
if (targets.includes(given)) return "accent";
|
|
72
90
|
// "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
|
|
73
91
|
const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
|
|
74
92
|
if (targets.some((t) => compact(t) === compact(given))) return "typo";
|