dracosh 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +10 -0
- package/README.md +100 -2
- package/assets/sounds/ask.wav +0 -0
- 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/assets/sounds/close.wav +0 -0
- package/assets/sounds/combo.wav +0 -0
- package/assets/sounds/correct-0.wav +0 -0
- package/assets/sounds/correct-1.wav +0 -0
- package/assets/sounds/correct-2.wav +0 -0
- package/assets/sounds/correct-3.wav +0 -0
- package/assets/sounds/correct-4.wav +0 -0
- package/assets/sounds/correct-5.wav +0 -0
- package/assets/sounds/evolve.wav +0 -0
- package/assets/sounds/goal.wav +0 -0
- package/assets/sounds/wrong.wav +0 -0
- package/data/tips.json +32 -0
- package/package.json +47 -4
- package/src/alerts.js +38 -0
- package/src/anki.js +36 -0
- package/src/backup.js +95 -0
- package/src/cli.js +197 -0
- package/src/commands.js +28 -0
- package/src/dates.js +15 -0
- package/src/demo.js +11 -0
- package/src/diff.js +46 -0
- package/src/hint.js +12 -0
- package/src/judge.js +78 -0
- package/src/library.js +127 -0
- package/src/lock.js +63 -0
- package/src/manage.js +75 -0
- package/src/parse.js +42 -0
- package/src/pause.js +23 -0
- package/src/progress.js +455 -0
- package/src/quiet.js +32 -0
- package/src/scheduler.js +94 -0
- package/src/session.js +227 -0
- package/src/settings.js +38 -0
- package/src/starter.js +38 -0
- package/src/store.js +100 -0
- package/src/tips.js +30 -0
- package/src/ui/AddCard.js +172 -0
- package/src/ui/AnswerInput.js +85 -0
- package/src/ui/App.js +509 -0
- package/src/ui/BadgeUnlock.js +50 -0
- package/src/ui/Badges.js +122 -0
- package/src/ui/Choice.js +33 -0
- package/src/ui/Companion.js +45 -0
- package/src/ui/Confetti.js +46 -0
- package/src/ui/Decks.js +49 -0
- package/src/ui/DieRoll.js +104 -0
- package/src/ui/Evolution.js +59 -0
- package/src/ui/Hatch.js +100 -0
- package/src/ui/Header.js +117 -0
- package/src/ui/Help.js +68 -0
- package/src/ui/Mascot.js +178 -0
- package/src/ui/Missed.js +53 -0
- package/src/ui/Preview.js +256 -0
- package/src/ui/Reset.js +72 -0
- package/src/ui/Settings.js +69 -0
- package/src/ui/Stats.js +111 -0
- package/src/ui/Summary.js +41 -0
- package/src/ui/TheOne.js +121 -0
- package/src/ui/icons.js +341 -0
- package/src/ui/kit.js +120 -0
- package/src/vacation.js +56 -0
- package/src/words.js +23 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { render } from "ink";
|
|
3
|
+
import React from "react";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { createAlerts } from "./alerts.js";
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
|
+
import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup } from "./backup.js";
|
|
9
|
+
import { ensureProgress, snapshot } from "./progress.js";
|
|
10
|
+
import { BOX_INTERVALS_DAYS } from "./scheduler.js";
|
|
11
|
+
import { createSession } from "./session.js";
|
|
12
|
+
import { DEFAULTS, formatInterval, normalizeSettings } from "./settings.js";
|
|
13
|
+
import { seedLibrary } from "./starter.js";
|
|
14
|
+
import { DATA_FILES, HOME, loadLibrary, loadSettingsRaw, loadState, patchSettings, saveLibrary } from "./store.js";
|
|
15
|
+
import { App } from "./ui/App.js";
|
|
16
|
+
import { Preview } from "./ui/Preview.js";
|
|
17
|
+
import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
|
|
18
|
+
import * as manage from "./manage.js";
|
|
19
|
+
import { findDeck } from "./library.js";
|
|
20
|
+
import { loadAllWords, loadWords, missingDeck } from "./words.js";
|
|
21
|
+
|
|
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.`;
|
|
42
|
+
|
|
43
|
+
function parseEvery(value) {
|
|
44
|
+
const match = /^(\d+(?:\.\d+)?)(s|m|h)$/.exec(value);
|
|
45
|
+
if (!match) throw new Error(`Invalid --every "${value}". Use e.g. 30s, 10m, 1h.`);
|
|
46
|
+
return Number(match[1]) * { s: 1000, m: 60_000, h: 3_600_000 }[match[2]];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseVolume(value) {
|
|
50
|
+
const volume = Number(value);
|
|
51
|
+
if (!(volume >= 0 && volume <= 1)) throw new Error(`Invalid --volume "${value}". Use a number from 0 to 1.`);
|
|
52
|
+
return volume;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function printStats(state, settings) {
|
|
56
|
+
ensureProgress(state);
|
|
57
|
+
const stats = snapshot(state, { goal: settings.dailyGoal });
|
|
58
|
+
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}`);
|
|
62
|
+
|
|
63
|
+
const entries = Object.values(state.items);
|
|
64
|
+
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}`);
|
|
66
|
+
const correct = entries.reduce((sum, e) => sum + e.correct, 0);
|
|
67
|
+
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)}%)`);
|
|
69
|
+
console.log(perBox.join(" "));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const formatTime = (ms) => new Date(ms).toLocaleString("sv").slice(0, 16);
|
|
73
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
74
|
+
|
|
75
|
+
async function confirm(question) {
|
|
76
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
77
|
+
try {
|
|
78
|
+
return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
|
|
79
|
+
} finally {
|
|
80
|
+
rl.close();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// --data: where everything lives, and what's in it
|
|
85
|
+
async function printData() {
|
|
86
|
+
const library = await loadLibrary();
|
|
87
|
+
const state = await loadState();
|
|
88
|
+
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.`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function restore(choice, { yes }) {
|
|
99
|
+
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}`);
|
|
101
|
+
if (!choice) {
|
|
102
|
+
console.log(`Backups in ${BACKUP_DIR}, newest first:\n`);
|
|
103
|
+
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}`);
|
|
106
|
+
});
|
|
107
|
+
return console.log(`\nBring one back with: dracosh restore <number>`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
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.`);
|
|
112
|
+
const running = runningPid();
|
|
113
|
+
if (running) throw new Error(ALREADY_RUNNING(running));
|
|
114
|
+
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.");
|
|
117
|
+
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.");
|
|
120
|
+
}
|
|
121
|
+
await restoreBackup(backup.file);
|
|
122
|
+
console.log("Restored.");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function main() {
|
|
126
|
+
const { values, positionals } = parseArgs({
|
|
127
|
+
allowPositionals: true,
|
|
128
|
+
options: {
|
|
129
|
+
deck: { type: "string" },
|
|
130
|
+
every: { type: "string" },
|
|
131
|
+
volume: { type: "string" },
|
|
132
|
+
"no-sound": { type: "boolean", default: false },
|
|
133
|
+
stats: { type: "boolean", default: false },
|
|
134
|
+
data: { type: "boolean", default: false },
|
|
135
|
+
preview: { type: "boolean", default: false },
|
|
136
|
+
yes: { type: "boolean", short: "y", default: false },
|
|
137
|
+
help: { type: "boolean", short: "h", default: false }
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
if (values.help) return console.log(HELP);
|
|
141
|
+
const [command, ...args] = positionals;
|
|
142
|
+
if (command === "restore") return restore(args[0], values);
|
|
143
|
+
if (command) throw new Error(`Unknown command "${command}". See dracosh --help.`);
|
|
144
|
+
if (values.data) return printData();
|
|
145
|
+
|
|
146
|
+
const saved = normalizeSettings(await loadSettingsRaw());
|
|
147
|
+
const settings = {
|
|
148
|
+
...saved,
|
|
149
|
+
...(values.every && { everyMs: parseEvery(values.every) }),
|
|
150
|
+
...(values.volume && { volume: parseVolume(values.volume) }),
|
|
151
|
+
...(values["no-sound"] && { sound: false })
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
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 });
|
|
157
|
+
return render(React.createElement(Preview, { alerts })).waitUntilExit();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const state = await loadState();
|
|
161
|
+
if (values.stats) return printStats(state, settings);
|
|
162
|
+
if (!process.stdin.isTTY) throw new Error("dracosh needs an interactive terminal.");
|
|
163
|
+
// a fresh install starts with the "Getting started" deck
|
|
164
|
+
const library = await loadLibrary();
|
|
165
|
+
const seeded = seedLibrary(library);
|
|
166
|
+
if (values.deck && !findDeck(library, values.deck)) throw missingDeck(library, values.deck); // before anything is written
|
|
167
|
+
|
|
168
|
+
acquireLock();
|
|
169
|
+
await dailyBackup();
|
|
170
|
+
if (seeded) await saveLibrary(library);
|
|
171
|
+
|
|
172
|
+
// --deck must exist (fail fast, before taking over the screen); a deck saved in /decks that has
|
|
173
|
+
// since gone just falls back to the first one
|
|
174
|
+
const { deck } = values.deck ? await loadWords(values.deck) : await loadWords(settings.deck).catch(() => loadWords());
|
|
175
|
+
|
|
176
|
+
let current = settings; // the session reads settings live, so /settings changes apply immediately
|
|
177
|
+
let active = deck.name; // /add can switch to your first own deck
|
|
178
|
+
const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
|
|
179
|
+
const alerts = createAlerts({ sound: settings.sound, volume: settings.volume });
|
|
180
|
+
const persistSettings = async (patch) => {
|
|
181
|
+
current = { ...current, ...patch };
|
|
182
|
+
await patchSettings(patch);
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// the session summary screen stays on screen after exit, so nothing more to print here
|
|
186
|
+
const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name) }));
|
|
187
|
+
await app.waitUntilExit();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
main().catch((err) => {
|
|
191
|
+
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.`);
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
console.error(err.message);
|
|
196
|
+
process.exit(1);
|
|
197
|
+
});
|
package/src/commands.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// `only` limits a command to one phase: "asking" (a question is open) or "waiting" (between questions)
|
|
2
|
+
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" }
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const CORRECT = { name: "/correct", hint: "Count my last answer as correct" };
|
|
17
|
+
|
|
18
|
+
// What the "/" menu offers right now (phase-only commands, and /correct right after a wrong answer)
|
|
19
|
+
export function commandsFor({ phase, canOverrule = false }) {
|
|
20
|
+
const base = COMMANDS.filter((command) => !command.only || command.only === phase);
|
|
21
|
+
return canOverrule ? [CORRECT, ...base] : base;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// "/s" narrows to commands starting with it (aliases count: "/?" finds /help). Arguments are ignored: "/pause 30m" matches /pause.
|
|
25
|
+
export function matchCommands(value, commands = COMMANDS) {
|
|
26
|
+
const query = value.trim().split(/\s+/)[0].toLowerCase();
|
|
27
|
+
return commands.filter((command) => command.name.startsWith(query) || command.aliases?.some((alias) => alias.startsWith(query)));
|
|
28
|
+
}
|
package/src/dates.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Calendar days as local "YYYY-MM-DD" keys. Noon avoids DST edge cases when doing day arithmetic.
|
|
2
|
+
export const dayKey = (now) => new Date(now).toLocaleDateString("sv");
|
|
3
|
+
|
|
4
|
+
const parse = (key) => new Date(`${key}T12:00:00`);
|
|
5
|
+
|
|
6
|
+
export const daysBetween = (from, to) => Math.round((parse(to) - parse(from)) / 86_400_000);
|
|
7
|
+
|
|
8
|
+
export function addDays(key, n) {
|
|
9
|
+
const date = parse(key);
|
|
10
|
+
date.setDate(date.getDate() + n);
|
|
11
|
+
return dayKey(date);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Monday of the week containing `key`
|
|
15
|
+
export const weekStart = (key) => addDays(key, -((parse(key).getDay() + 6) % 7));
|
package/src/demo.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// A small built-in EN ↔ PL word set: used by the preview gallery, and a seed for the future demo deck.
|
|
2
|
+
export const DEMO_WORDS = [
|
|
3
|
+
{ noteId: 1, word: "dragon", translations: ["smok"], example: "The dragon guarded its gold." },
|
|
4
|
+
{ noteId: 2, word: "egg", translations: ["jajko", "jajo"], example: "The egg began to crack." },
|
|
5
|
+
{ noteId: 3, word: "to hatch", translations: ["wykluć się"], example: "The chicks will hatch tomorrow." },
|
|
6
|
+
{ noteId: 4, word: "genuine", translations: ["autentyczny", "szczery"], example: "Her apology felt genuine." },
|
|
7
|
+
{ noteId: 5, word: "software", translations: ["oprogramowanie"], example: "The software update fixed the bug." },
|
|
8
|
+
{ noteId: 6, word: "to grow", translations: ["rosnąć"], example: "Plants grow towards the light." },
|
|
9
|
+
{ noteId: 7, word: "fire", translations: ["ogień"], example: "Dragons breathe fire." },
|
|
10
|
+
{ noteId: 8, word: "streak", translations: ["seria", "passa"], example: "She kept her streak for a month." }
|
|
11
|
+
];
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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.
|
|
3
|
+
|
|
4
|
+
const foldChar = (ch) =>
|
|
5
|
+
ch
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/ł/g, "l")
|
|
8
|
+
.normalize("NFD")
|
|
9
|
+
.replace(/[̀-ͯ]/g, "");
|
|
10
|
+
|
|
11
|
+
// → [{ ch, ok }] for every character of `given`: ok = this character lines up with `target`.
|
|
12
|
+
// Alignment comes from a Levenshtein backtrace, so a single missing or extra letter doesn't
|
|
13
|
+
// mark the whole rest of the word wrong.
|
|
14
|
+
export function diffChars(given, target) {
|
|
15
|
+
const a = [...given].map(foldChar);
|
|
16
|
+
const b = [...target].map(foldChar);
|
|
17
|
+
const rows = a.length + 1;
|
|
18
|
+
const cols = b.length + 1;
|
|
19
|
+
const d = Array.from({ length: rows }, (_, i) => new Array(cols).fill(0));
|
|
20
|
+
for (let i = 0; i < rows; i++) d[i][0] = i;
|
|
21
|
+
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
22
|
+
for (let i = 1; i < rows; i++) {
|
|
23
|
+
for (let j = 1; j < cols; j++) {
|
|
24
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
25
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// walk back, preferring matches; deletions in `target` don't produce a character of `given`
|
|
30
|
+
const marks = new Array(a.length).fill(false);
|
|
31
|
+
let i = a.length;
|
|
32
|
+
let j = b.length;
|
|
33
|
+
while (i > 0 || j > 0) {
|
|
34
|
+
if (i > 0 && j > 0 && d[i][j] === d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)) {
|
|
35
|
+
marks[i - 1] = a[i - 1] === b[j - 1];
|
|
36
|
+
i -= 1;
|
|
37
|
+
j -= 1;
|
|
38
|
+
} else if (i > 0 && d[i][j] === d[i - 1][j] + 1) {
|
|
39
|
+
marks[i - 1] = false; // extra character you typed
|
|
40
|
+
i -= 1;
|
|
41
|
+
} else {
|
|
42
|
+
j -= 1; // character you missed: nothing of yours to mark
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return [...given].map((ch, k) => ({ ch, ok: marks[k] }));
|
|
46
|
+
}
|
package/src/hint.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const isLetter = (ch) => /\p{L}/u.test(ch);
|
|
2
|
+
|
|
3
|
+
// The answer to hint at: the shortest of the accepted ones (the easiest to recall).
|
|
4
|
+
export const hintTarget = (expected) => [...expected].sort((a, b) => a.length - b.length)[0];
|
|
5
|
+
|
|
6
|
+
// "fine-tuned" at level 2 → "f i _ _ - _ _ _ _ _". Never reveals the last letter, so a hint is never the answer.
|
|
7
|
+
export function makeHint(answer, level) {
|
|
8
|
+
const letters = [...answer].filter(isLetter).length;
|
|
9
|
+
const reveal = Math.min(level, Math.max(letters - 1, 0));
|
|
10
|
+
let shown = 0;
|
|
11
|
+
return [...answer].map((ch) => (isLetter(ch) ? (shown++ < reveal ? ch : "_") : ch)).join(" ");
|
|
12
|
+
}
|
package/src/judge.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Typos are forgiven only on longer answers: on short words one edit often makes a different word
|
|
2
|
+
const TYPO_MIN_LENGTH = 6;
|
|
3
|
+
|
|
4
|
+
// Sentence punctuation that never changes what an answer means ("Hello, world!" = "hello world").
|
|
5
|
+
// Everything else stays: "3.14" isn't "31.4", "-5" isn't "5", "C#" isn't "C", and 🐉 is an answer too.
|
|
6
|
+
const LOOSE = /[;!?¡¿"“”„«»()[\]'’`]/g;
|
|
7
|
+
|
|
8
|
+
// lowercase, loose punctuation dropped, a trailing full stop dropped, hyphens between letters as spaces.
|
|
9
|
+
// Commas and colons count between digits only: "3,14" is "3.14" (a decimal comma), "10:30" stays.
|
|
10
|
+
function plain(s) {
|
|
11
|
+
const text = s
|
|
12
|
+
.normalize("NFC") // "café" typed or pasted with a separate accent mark is the same word
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/(?<=\d),(?=\d)/g, ".")
|
|
15
|
+
.replace(/,/g, " ")
|
|
16
|
+
.replace(/(?<!\d):|:(?!\d)/g, "")
|
|
17
|
+
.replace(LOOSE, "")
|
|
18
|
+
.replace(/(?<=\p{L})[-‐–—](?=\p{L})/gu, " ")
|
|
19
|
+
.replace(/\.+$/, "")
|
|
20
|
+
.replace(/\s+/g, " ")
|
|
21
|
+
.trim();
|
|
22
|
+
return text || s.trim().toLowerCase(); // an answer made only of punctuation ("?") is still itself
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// plain(), and diacritics folded too (ł doesn't decompose, so it is mapped by hand)
|
|
26
|
+
export function normalize(s) {
|
|
27
|
+
return plain(s).replace(/ł/g, "l").normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
|
|
31
|
+
export function editDistance(a, b) {
|
|
32
|
+
const rows = a.length + 1;
|
|
33
|
+
const cols = b.length + 1;
|
|
34
|
+
const d = Array.from({ length: rows }, (_, i) => [i, ...new Array(cols - 1).fill(0)]);
|
|
35
|
+
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
36
|
+
for (let i = 1; i < rows; i++) {
|
|
37
|
+
for (let j = 1; j < cols; j++) {
|
|
38
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
39
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
40
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
41
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return d[rows - 1][cols - 1];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The candidate the answer came closest to (fewest edits after normalizing): what a miss is diffed against
|
|
49
|
+
export function closestCandidate(answer, candidates) {
|
|
50
|
+
const given = normalize(answer);
|
|
51
|
+
let best = candidates[0];
|
|
52
|
+
let bestDistance = Infinity;
|
|
53
|
+
for (const candidate of candidates) {
|
|
54
|
+
const distance = editDistance(given, normalize(candidate));
|
|
55
|
+
if (distance < bestDistance) {
|
|
56
|
+
bestDistance = distance;
|
|
57
|
+
best = candidate;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return best;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// → "exact" | "typo" | "wrong"; accepts any one of the candidate answers. Missing or wrong
|
|
64
|
+
// diacritics ("zolw" for "żółw") count, as "typo", so the right spelling is shown. One more typo is
|
|
65
|
+
// forgiven on longer answers, but never in numbers: "123457" isn't "123456".
|
|
66
|
+
export function judge(answer, candidates) {
|
|
67
|
+
if (!answer.trim()) return "wrong";
|
|
68
|
+
const given = normalize(answer);
|
|
69
|
+
if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
|
|
70
|
+
const targets = candidates.map(normalize);
|
|
71
|
+
if (targets.includes(given)) return "typo";
|
|
72
|
+
// "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
|
|
73
|
+
const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
|
|
74
|
+
if (targets.some((t) => compact(t) === compact(given))) return "typo";
|
|
75
|
+
const numbers = /\d/.test(given);
|
|
76
|
+
const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && !numbers && !/\d/.test(t) && editDistance(given, t) <= 1);
|
|
77
|
+
return close ? "typo" : "wrong";
|
|
78
|
+
}
|
package/src/library.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { normalize } from "./judge.js";
|
|
3
|
+
|
|
4
|
+
// The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
|
|
5
|
+
//
|
|
6
|
+
// Progress (state.items) is keyed by `${card.id}:${direction}`. Cards that came from Anki use the Anki
|
|
7
|
+
// note id as their id, so progress recorded by 0.1.0 (keyed by note id) carries over unchanged.
|
|
8
|
+
// New cards get a "c"-prefixed id, which can never collide with Anki's numeric ids.
|
|
9
|
+
|
|
10
|
+
export const LIBRARY_VERSION = 1;
|
|
11
|
+
|
|
12
|
+
export const CARD_TYPES = ["translation", "definition", "qa"];
|
|
13
|
+
export const ANSWER_MODES = ["typed", "self"];
|
|
14
|
+
const DEFAULT_ANSWER_MODE = { translation: "typed", definition: "typed", qa: "self" };
|
|
15
|
+
|
|
16
|
+
export const MAX_DECK_NAME = 40; // it has to fit the card's border and the header
|
|
17
|
+
|
|
18
|
+
export const emptyLibrary = () => ({ version: LIBRARY_VERSION, decks: [], cards: [] });
|
|
19
|
+
|
|
20
|
+
export const newId = (prefix) => `${prefix}${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
|
|
21
|
+
|
|
22
|
+
const sameName = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
23
|
+
|
|
24
|
+
function cleanList(values) {
|
|
25
|
+
const list = (Array.isArray(values) ? values : [values]).map((v) => String(v ?? "").trim()).filter(Boolean);
|
|
26
|
+
return [...new Set(list)];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const isText = (value) => typeof value === "string";
|
|
30
|
+
const filled = (value) => isText(value) && value.trim() !== "";
|
|
31
|
+
const validLanguages = (languages) => languages == null || (typeof languages === "object" && filled(languages.front) && filled(languages.back));
|
|
32
|
+
const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name) && validLanguages(deck.languages);
|
|
33
|
+
const validCard = (card) => card && isText(card.id) && isText(card.deckId) && filled(card.front) && Array.isArray(card.back) && card.back.length > 0 && card.back.every(filled);
|
|
34
|
+
const broken = (why) => Object.assign(new Error(why), { damaged: true });
|
|
35
|
+
|
|
36
|
+
// → the library in its current shape (undefined: there's none yet). Throws on a file written by a newer
|
|
37
|
+
// Dracosh, so it's never overwritten, and on one that isn't a library, so nothing is lost by saving over it.
|
|
38
|
+
export function upgradeLibrary(raw) {
|
|
39
|
+
if (raw === undefined) return emptyLibrary();
|
|
40
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw broken("not a library");
|
|
41
|
+
if (raw.version > LIBRARY_VERSION) {
|
|
42
|
+
throw new Error(`This library was saved by a newer version of Dracosh (format ${raw.version}). Please update Dracosh.`);
|
|
43
|
+
}
|
|
44
|
+
const decks = raw.decks ?? [];
|
|
45
|
+
const cards = raw.cards ?? [];
|
|
46
|
+
if (!Array.isArray(decks) || !decks.every(validDeck)) throw broken("a deck without a name or an id");
|
|
47
|
+
if (!Array.isArray(cards) || !cards.every(validCard)) throw broken("a card without a front or an answer");
|
|
48
|
+
const deckIds = new Set(decks.map((deck) => deck.id));
|
|
49
|
+
if (!cards.every((card) => deckIds.has(card.deckId))) throw broken("a card in a deck that doesn't exist");
|
|
50
|
+
if (new Set(cards.map((card) => card.id)).size !== cards.length) throw broken("two cards with the same id");
|
|
51
|
+
return { version: LIBRARY_VERSION, decks, cards };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const findDeck = (library, nameOrId) =>
|
|
55
|
+
library.decks.find((deck) => deck.id === nameOrId) ?? library.decks.find((deck) => sameName(deck.name, nameOrId)) ?? null;
|
|
56
|
+
|
|
57
|
+
export function createDeck(library, { name, type = "translation", languages = { front: "en", back: "pl" }, answerMode, directions = "both", tour = false, now = Date.now() }) {
|
|
58
|
+
const trimmed = String(name ?? "").trim();
|
|
59
|
+
if (!trimmed) throw new Error("A deck needs a name.");
|
|
60
|
+
if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(`Keep the deck name to ${MAX_DECK_NAME} characters or fewer.`);
|
|
61
|
+
const existing = findDeck(library, trimmed);
|
|
62
|
+
if (existing) throw new Error(`There is already a deck called "${existing.name}".`);
|
|
63
|
+
if (!CARD_TYPES.includes(type)) throw new Error(`Unknown card type "${type}".`);
|
|
64
|
+
const mode = answerMode ?? DEFAULT_ANSWER_MODE[type];
|
|
65
|
+
if (!ANSWER_MODES.includes(mode)) throw new Error(`Unknown answer mode "${mode}".`);
|
|
66
|
+
|
|
67
|
+
const deck = { id: newId("d"), name: trimmed, type, languages: languages ? { ...languages } : null, answerMode: mode, directions, tour, created: now };
|
|
68
|
+
library.decks.push(deck);
|
|
69
|
+
return deck;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// → the ids of the cards that went with it, so their progress can be dropped too
|
|
73
|
+
export function removeDeck(library, deckId) {
|
|
74
|
+
const removed = cardsOf(library, deckId).map((card) => card.id);
|
|
75
|
+
library.decks = library.decks.filter((deck) => deck.id !== deckId);
|
|
76
|
+
library.cards = library.cards.filter((card) => card.deckId !== deckId);
|
|
77
|
+
return removed;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const cardsOf = (library, deckId) => library.cards.filter((card) => card.deckId === deckId);
|
|
81
|
+
|
|
82
|
+
// a card with the same front (ignoring case, accents and punctuation) in the same deck
|
|
83
|
+
export const findDuplicate = (library, deckId, front) => {
|
|
84
|
+
const key = normalize(front);
|
|
85
|
+
return library.cards.find((card) => card.deckId === deckId && normalize(card.front) === key) ?? null;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// → { card, duplicate }: `duplicate` is the existing card when the front is already in the deck (nothing is added then)
|
|
89
|
+
export function addCard(library, deckId, { front, back, example = "", tags = [], id, now = Date.now() }) {
|
|
90
|
+
if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
|
|
91
|
+
const cleanFront = String(front ?? "").trim();
|
|
92
|
+
const cleanBack = cleanList(back);
|
|
93
|
+
if (!cleanFront) throw new Error("A card needs a front.");
|
|
94
|
+
if (!cleanBack.length) throw new Error("A card needs at least one answer on the back.");
|
|
95
|
+
|
|
96
|
+
const duplicate = findDuplicate(library, deckId, cleanFront);
|
|
97
|
+
if (duplicate) return { card: null, duplicate };
|
|
98
|
+
|
|
99
|
+
const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), created: now, updated: now };
|
|
100
|
+
if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
|
|
101
|
+
library.cards.push(card);
|
|
102
|
+
return { card, duplicate: null };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function updateCard(library, cardId, patch, now = Date.now()) {
|
|
106
|
+
const card = library.cards.find((c) => c.id === cardId);
|
|
107
|
+
if (!card) throw new Error("That card doesn't exist.");
|
|
108
|
+
if (patch.front !== undefined) {
|
|
109
|
+
const front = String(patch.front).trim();
|
|
110
|
+
if (!front) throw new Error("A card needs a front.");
|
|
111
|
+
const duplicate = findDuplicate(library, card.deckId, front);
|
|
112
|
+
if (duplicate && duplicate.id !== card.id) throw new Error(`"${front}" is already in this deck.`);
|
|
113
|
+
card.front = front;
|
|
114
|
+
}
|
|
115
|
+
if (patch.back !== undefined) {
|
|
116
|
+
const back = cleanList(patch.back);
|
|
117
|
+
if (!back.length) throw new Error("A card needs at least one answer on the back.");
|
|
118
|
+
card.back = back;
|
|
119
|
+
}
|
|
120
|
+
if (patch.example !== undefined) card.example = String(patch.example).trim();
|
|
121
|
+
if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
|
|
122
|
+
card.updated = now;
|
|
123
|
+
return card;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The quiz's word shape, so the scheduler and session keep working unchanged.
|
|
127
|
+
export const toWords = (cards) => cards.map((card) => ({ noteId: card.id, word: card.front, translations: card.back, example: card.example }));
|
package/src/lock.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { HOME } from "./store.js";
|
|
4
|
+
|
|
5
|
+
// One quiz at a time per data folder: each window keeps the progress in memory and saves all of it,
|
|
6
|
+
// so two windows would overwrite each other's answers. The lock file holds the running window's pid.
|
|
7
|
+
const LOCK_FILE = join(HOME, "dracosh.lock");
|
|
8
|
+
|
|
9
|
+
const alive = (pid) => {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
} catch (err) {
|
|
14
|
+
return err.code === "EPERM"; // running, but someone else's process
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const readPid = () => {
|
|
19
|
+
try {
|
|
20
|
+
return Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) || null;
|
|
21
|
+
} catch {
|
|
22
|
+
return null; // no lock, or an unreadable one
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// the pid of a Dracosh quiz running on this data folder, or null
|
|
27
|
+
export function runningPid() {
|
|
28
|
+
const pid = readPid();
|
|
29
|
+
return pid && pid !== process.pid && alive(pid) ? pid : null; // a lock left by a crash doesn't count
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const ALREADY_RUNNING = (pid) => `Dracosh is already running in another window (process ${pid}). Close it first: two windows would overwrite each other's progress.`;
|
|
33
|
+
|
|
34
|
+
// → a release function; throws when another quiz holds the lock. The lock file is created exclusively
|
|
35
|
+
// ("wx"), so of two windows started at the same moment only one gets it; a stale one is replaced once.
|
|
36
|
+
export function acquireLock() {
|
|
37
|
+
mkdirSync(HOME, { recursive: true });
|
|
38
|
+
const lock = JSON.stringify({ pid: process.pid, since: new Date().toISOString() });
|
|
39
|
+
for (let attempt = 0; ; attempt++) {
|
|
40
|
+
try {
|
|
41
|
+
writeFileSync(LOCK_FILE, lock, { flag: "wx" });
|
|
42
|
+
break;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err.code !== "EEXIST" || attempt > 0) throw err.code === "EEXIST" ? new Error(ALREADY_RUNNING(runningPid() ?? "?")) : err;
|
|
45
|
+
const pid = runningPid();
|
|
46
|
+
if (pid) throw new Error(ALREADY_RUNNING(pid));
|
|
47
|
+
rmSync(LOCK_FILE, { force: true }); // left behind by a window that crashed
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Two windows that both found the same stale lock may each have removed it and written their own:
|
|
51
|
+
// after a moment only one of them is still in the file, and the other one stops here.
|
|
52
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60);
|
|
53
|
+
if (readPid() !== process.pid) throw new Error(ALREADY_RUNNING(readPid() ?? "?"));
|
|
54
|
+
const release = () => {
|
|
55
|
+
try {
|
|
56
|
+
if (Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) === process.pid) rmSync(LOCK_FILE);
|
|
57
|
+
} catch {}
|
|
58
|
+
};
|
|
59
|
+
process.on("exit", release);
|
|
60
|
+
// with the lock held no other window writes here: temp files left by a crash can go
|
|
61
|
+
for (const name of readdirSync(HOME)) if (/^(library|state|settings)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
|
|
62
|
+
return release;
|
|
63
|
+
}
|
package/src/manage.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { backupNow } from "./backup.js";
|
|
2
|
+
import { seedLibrary } from "./starter.js";
|
|
3
|
+
import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck } from "./library.js";
|
|
4
|
+
import { loadLibrary, saveLibrary } from "./store.js";
|
|
5
|
+
|
|
6
|
+
// Library changes made from inside the app (/add for now). Each one reads the library fresh, so
|
|
7
|
+
// nothing written meanwhile by another Dracosh window is lost.
|
|
8
|
+
|
|
9
|
+
// every deck, the tour too, with its card count: /decks switches between them
|
|
10
|
+
export async function allDecks() {
|
|
11
|
+
const library = await loadLibrary();
|
|
12
|
+
return library.decks.map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, tour: Boolean(deck.tour) }));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// your decks (the tour isn't one), with how many cards each holds: /add lets you pick one
|
|
16
|
+
export async function ownDecks() {
|
|
17
|
+
const library = await loadLibrary();
|
|
18
|
+
return library.decks.filter((deck) => !deck.tour).map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, bothWays: deck.directions !== "forward" }));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A new deck. Your first one replaces the tour: it's removed (after a backup) and the ids of its cards are
|
|
22
|
+
// returned, so their progress can go too.
|
|
23
|
+
export async function startDeck({ name, bothWays }) {
|
|
24
|
+
const library = await loadLibrary();
|
|
25
|
+
const tour = library.decks.find((d) => d.tour);
|
|
26
|
+
let removed = [];
|
|
27
|
+
if (tour) {
|
|
28
|
+
await backupNow("before-delete");
|
|
29
|
+
removed = removeDeck(library, tour.id);
|
|
30
|
+
}
|
|
31
|
+
const deck = createDeck(library, { name, type: "translation", languages: null, directions: bothWays ? "both" : "forward" });
|
|
32
|
+
await saveLibrary(library);
|
|
33
|
+
return { deck, removed };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const SLASH_ANSWER = "An answer can't start with /: in the quiz that opens the commands.";
|
|
37
|
+
export const SLASH_FRONT = "In a deck asked both ways the front is an answer too, so it can't start with /.";
|
|
38
|
+
|
|
39
|
+
// the deck with this name (ignoring case), if any: /add says so before asking anything else
|
|
40
|
+
export const existingDeck = async (name) => {
|
|
41
|
+
const deck = findDeck(await loadLibrary(), name.trim());
|
|
42
|
+
return deck && !deck.tour ? deck : null; // the tour is about to make room, so its name is free
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// the card with this front already in the deck, if any: /add says so before asking for the answer
|
|
46
|
+
export async function existingCard(deckName, front) {
|
|
47
|
+
const library = await loadLibrary();
|
|
48
|
+
const deck = findDeck(library, deckName);
|
|
49
|
+
return deck ? findDuplicate(library, deck.id, front) : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// a reset is always preceded by a backup, so `dracosh restore` can undo it
|
|
53
|
+
export const backupBeforeReset = () => backupNow("before-reset");
|
|
54
|
+
|
|
55
|
+
// "Everything" in the reset: your decks and cards go, and the tour comes back as on a fresh install
|
|
56
|
+
export async function resetLibrary() {
|
|
57
|
+
const library = emptyLibrary();
|
|
58
|
+
seedLibrary(library);
|
|
59
|
+
await saveLibrary(library);
|
|
60
|
+
return library.decks[0].name;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// → { card, duplicate }, like addCard
|
|
64
|
+
export async function addCardTo(deckName, fields) {
|
|
65
|
+
const library = await loadLibrary();
|
|
66
|
+
const deck = findDeck(library, deckName);
|
|
67
|
+
if (!deck) throw new Error(`The deck "${deckName}" is gone.`);
|
|
68
|
+
// in the quiz "/" opens the commands, so nothing you'd have to type may start with it
|
|
69
|
+
const slash = (text) => String(text ?? "").trim().startsWith("/");
|
|
70
|
+
if ([fields.back].flat().some(slash)) throw new Error(SLASH_ANSWER);
|
|
71
|
+
if (deck.directions !== "forward" && slash(fields.front)) throw new Error(SLASH_FRONT);
|
|
72
|
+
const result = addCard(library, deck.id, fields);
|
|
73
|
+
if (result.card) await saveLibrary(library);
|
|
74
|
+
return result;
|
|
75
|
+
}
|