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.
Files changed (61) hide show
  1. package/README.md +49 -22
  2. package/assets/sounds/badge-1.wav +0 -0
  3. package/assets/sounds/badge-2.wav +0 -0
  4. package/assets/sounds/badge-3.wav +0 -0
  5. package/assets/sounds/badge-4.wav +0 -0
  6. package/locales/de.json +1046 -0
  7. package/locales/en.json +1029 -0
  8. package/locales/fr.json +1094 -0
  9. package/locales/pl.json +1117 -0
  10. package/locales/uk.json +1118 -0
  11. package/package.json +2 -2
  12. package/src/alerts.js +7 -4
  13. package/src/backup.js +96 -0
  14. package/src/cardline.js +71 -0
  15. package/src/cli.js +106 -38
  16. package/src/commands.js +15 -13
  17. package/src/demo.js +11 -0
  18. package/src/diff.js +13 -7
  19. package/src/i18n.js +68 -0
  20. package/src/judge.js +51 -12
  21. package/src/library.js +154 -0
  22. package/src/lock.js +64 -0
  23. package/src/manage.js +165 -0
  24. package/src/pause.js +22 -0
  25. package/src/progress.js +202 -93
  26. package/src/quiet.js +4 -3
  27. package/src/scheduler.js +39 -30
  28. package/src/session.js +181 -33
  29. package/src/settings.js +15 -13
  30. package/src/starter.js +47 -0
  31. package/src/store.js +58 -17
  32. package/src/tips.js +17 -25
  33. package/src/ui/AddCard.js +496 -0
  34. package/src/ui/AnswerInput.js +28 -13
  35. package/src/ui/App.js +360 -89
  36. package/src/ui/BadgeUnlock.js +51 -0
  37. package/src/ui/Badges.js +79 -20
  38. package/src/ui/Choice.js +38 -0
  39. package/src/ui/Companion.js +24 -39
  40. package/src/ui/Confetti.js +2 -2
  41. package/src/ui/Decks.js +99 -0
  42. package/src/ui/DieRoll.js +104 -0
  43. package/src/ui/Evolution.js +11 -10
  44. package/src/ui/Hatch.js +9 -7
  45. package/src/ui/Header.js +62 -19
  46. package/src/ui/Help.js +74 -0
  47. package/src/ui/Mascot.js +89 -40
  48. package/src/ui/Missed.js +15 -13
  49. package/src/ui/Preview.js +123 -29
  50. package/src/ui/Reset.js +71 -0
  51. package/src/ui/Settings.js +34 -23
  52. package/src/ui/Stats.js +28 -24
  53. package/src/ui/Summary.js +18 -10
  54. package/src/ui/TheOne.js +122 -0
  55. package/src/ui/icons.js +156 -25
  56. package/src/ui/kit.js +87 -2
  57. package/src/vacation.js +9 -3
  58. package/src/words.js +22 -14
  59. package/assets/sounds/badge.wav +0 -0
  60. package/data/tips.json +0 -1362
  61. package/src/ui/Tip.js +0 -25
package/src/judge.js CHANGED
@@ -1,16 +1,47 @@
1
1
  // Typos are forgiven only on longer answers: on short words one edit often makes a different word
2
2
  const TYPO_MIN_LENGTH = 6;
3
3
 
4
- // lowercase, strip diacritics (ł doesn't decompose, so it is mapped by hand), drop punctuation
5
- export function normalize(s) {
6
- return s
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
7
13
  .toLowerCase()
8
- .replace(/ł/g, "l")
9
- .normalize("NFD")
10
- .replace(/[̀-ͯ]/g, "")
11
- .replace(/[^\p{L}\p{N}\s]/gu, "")
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(/\.+$/, "")
12
20
  .replace(/\s+/g, " ")
13
21
  .trim();
22
+ return text || s.trim().toLowerCase(); // an answer made only of punctuation ("?") is still itself
23
+ }
24
+
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
43
+ export function normalize(s) {
44
+ return fold(plain(s));
14
45
  }
15
46
 
16
47
  // Damerau-Levenshtein (optimal string alignment): a swap of two neighbours counts as one edit
@@ -46,12 +77,20 @@ export function closestCandidate(answer, candidates) {
46
77
  return best;
47
78
  }
48
79
 
49
- // → "exact" | "typo" | "wrong"; accepts any one of the candidate answers
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".
50
84
  export function judge(answer, candidates) {
85
+ if (!answer.trim()) return "wrong";
51
86
  const given = normalize(answer);
52
- if (!given) return "wrong";
53
- const targets = candidates.map(normalize).filter(Boolean);
54
- if (targets.includes(given)) return "exact";
55
- const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && editDistance(given, t) <= 1);
87
+ if (candidates.some((c) => plain(c) === plain(answer))) return "exact";
88
+ const targets = candidates.map(normalize);
89
+ if (targets.includes(given)) return "accent";
90
+ // "email" for "e-mail", "icecream" for "ice cream": right, but shown with the spelling
91
+ const compact = (s) => s.replace(/\s/g, ""); // hyphens between letters are spaces by now
92
+ if (targets.some((t) => compact(t) === compact(given))) return "typo";
93
+ const numbers = /\d/.test(given);
94
+ const close = targets.some((t) => t.length >= TYPO_MIN_LENGTH && !numbers && !/\d/.test(t) && editDistance(given, t) <= 1);
56
95
  return close ? "typo" : "wrong";
57
96
  }
package/src/library.js ADDED
@@ -0,0 +1,154 @@
1
+ import { t } from "./i18n.js";
2
+ import { randomBytes } from "node:crypto";
3
+ import { normalize } from "./judge.js";
4
+ import { gapsOf } from "./cardline.js";
5
+
6
+ // The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
7
+ //
8
+ // Progress (state.items) is keyed by `${card.id}:${direction}`. Cards that came from Anki use the Anki
9
+ // note id as their id, so progress recorded by 0.1.0 (keyed by note id) carries over unchanged.
10
+ // New cards get a "c"-prefixed id, which can never collide with Anki's numeric ids.
11
+
12
+ // 2: cloze cards, whose back may be empty (an older Dracosh would call such a library damaged)
13
+ export const LIBRARY_VERSION = 2;
14
+
15
+ // Older libraries carry a card type on each deck; every card is front = back now, so it's only kept.
16
+ export const CARD_TYPES = ["translation", "definition", "qa"];
17
+
18
+ // How a deck is asked: front → back, back → front, or both. Picked after its first card.
19
+ export const DIRECTIONS = ["forward", "backward", "both"];
20
+
21
+ // the sides of a card typed as an answer in the quiz: in the quiz "/" opens the commands, so neither
22
+ // may start with it. A cloze card is asked by its gaps, whatever the deck's direction.
23
+ export const typedSides = (deck) => (deck.directions === "forward" ? ["back"] : deck.directions === "backward" ? ["front"] : ["front", "back"]);
24
+
25
+ export const MAX_DECK_NAME = 40; // it has to fit the card's border and the header
26
+
27
+ export const emptyLibrary = () => ({ version: LIBRARY_VERSION, decks: [], cards: [] });
28
+
29
+ export const newId = (prefix) => `${prefix}${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
30
+
31
+ const sameName = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
32
+
33
+ function cleanList(values) {
34
+ const list = (Array.isArray(values) ? values : [values]).map((v) => String(v ?? "").trim()).filter(Boolean);
35
+ return [...new Set(list)];
36
+ }
37
+
38
+ const isText = (value) => typeof value === "string";
39
+ const filled = (value) => isText(value) && value.trim() !== "";
40
+ const validLanguages = (languages) => languages == null || (typeof languages === "object" && filled(languages.front) && filled(languages.back));
41
+ const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name) && validLanguages(deck.languages);
42
+ // a cloze card's answers are its gaps, so its back (shown as a hint) may be empty
43
+ const validCard = (card) =>
44
+ card && isText(card.id) && isText(card.deckId) && filled(card.front) && Array.isArray(card.back) && (card.cloze ? gapsOf(card.front).length > 0 : card.back.length > 0) && card.back.every(filled);
45
+ const broken = (why) => Object.assign(new Error(why), { damaged: true });
46
+
47
+ // → the library in its current shape (undefined: there's none yet). Throws on a file written by a newer
48
+ // Dracosh, so it's never overwritten, and on one that isn't a library, so nothing is lost by saving over it.
49
+ export function upgradeLibrary(raw) {
50
+ if (raw === undefined) return emptyLibrary();
51
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw broken(t("errors.why.notLibrary"));
52
+ if (raw.version > LIBRARY_VERSION) {
53
+ throw new Error(t("errors.newerLibrary", { format: raw.version }));
54
+ }
55
+ const decks = raw.decks ?? [];
56
+ const cards = raw.cards ?? [];
57
+ if (!Array.isArray(decks) || !decks.every(validDeck)) throw broken(t("errors.why.deck"));
58
+ if (!Array.isArray(cards) || !cards.every(validCard)) throw broken(t("errors.why.card"));
59
+ const deckIds = new Set(decks.map((deck) => deck.id));
60
+ if (!cards.every((card) => deckIds.has(card.deckId))) throw broken(t("errors.why.cardDeck"));
61
+ if (new Set(cards.map((card) => card.id)).size !== cards.length) throw broken(t("errors.why.cardIds"));
62
+ return { version: LIBRARY_VERSION, decks, cards };
63
+ }
64
+
65
+ export const findDeck = (library, nameOrId) =>
66
+ library.decks.find((deck) => deck.id === nameOrId) ?? library.decks.find((deck) => sameName(deck.name, nameOrId)) ?? null;
67
+
68
+ export function createDeck(library, { name, type = "translation", languages = { front: "en", back: "pl" }, directions = "both", tour = false, now = Date.now() }) {
69
+ const trimmed = String(name ?? "").trim();
70
+ if (!trimmed) throw new Error(t("errors.deckNeedsName"));
71
+ if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(t("errors.deckNameTooLong", { max: MAX_DECK_NAME }));
72
+ const existing = findDeck(library, trimmed);
73
+ if (existing) throw new Error(t("errors.deckExists", { deck: existing.name }));
74
+ if (!CARD_TYPES.includes(type)) throw new Error(`Unknown card type "${type}".`);
75
+ if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
76
+
77
+ const deck = { id: newId("d"), name: trimmed, type, languages: languages ? { ...languages } : null, directions, tour, created: now };
78
+ library.decks.push(deck);
79
+ return deck;
80
+ }
81
+
82
+ // Progress is kept per direction, so turning one off only stops asking it: its boxes stay for later.
83
+ export function setDirections(library, deckId, directions) {
84
+ if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
85
+ const deck = library.decks.find((d) => d.id === deckId);
86
+ if (!deck) throw new Error("That deck doesn't exist.");
87
+ deck.directions = directions;
88
+ return deck;
89
+ }
90
+
91
+ // → the ids of the cards that went with it, so their progress can be dropped too
92
+ export function removeDeck(library, deckId) {
93
+ const removed = cardsOf(library, deckId).map((card) => card.id);
94
+ library.decks = library.decks.filter((deck) => deck.id !== deckId);
95
+ library.cards = library.cards.filter((card) => card.deckId !== deckId);
96
+ return removed;
97
+ }
98
+
99
+ export const cardsOf = (library, deckId) => library.cards.filter((card) => card.deckId === deckId);
100
+
101
+ // a card with the same front (ignoring case, accents and punctuation) in the same deck
102
+ export const findDuplicate = (library, deckId, front) => {
103
+ const key = normalize(front);
104
+ return library.cards.find((card) => card.deckId === deckId && normalize(card.front) === key) ?? null;
105
+ };
106
+
107
+ // → { card, duplicate }: `duplicate` is the existing card when the front is already in the deck (nothing is added then)
108
+ // `cloze`: the front has {{gaps}}, each asked as a card of its own; the back is then only a hint
109
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, now = Date.now() }) {
110
+ if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
111
+ const cleanFront = String(front ?? "").trim();
112
+ const cleanBack = cleanList(back);
113
+ const isCloze = Boolean(cloze) && gapsOf(cleanFront).length > 0;
114
+ if (!cleanFront) throw new Error(t("errors.cardNeedsFront"));
115
+ if (!cleanBack.length && !isCloze) throw new Error(t("errors.cardNeedsBack"));
116
+
117
+ const duplicate = findDuplicate(library, deckId, cleanFront);
118
+ if (duplicate) return { card: null, duplicate };
119
+
120
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), created: now, updated: now };
121
+ if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
122
+ library.cards.push(card);
123
+ return { card, duplicate: null };
124
+ }
125
+
126
+ export function updateCard(library, cardId, patch, now = Date.now()) {
127
+ const card = library.cards.find((c) => c.id === cardId);
128
+ if (!card) throw new Error("That card doesn't exist.");
129
+ const front = patch.front !== undefined ? String(patch.front).trim() : card.front;
130
+ const back = patch.back !== undefined ? cleanList(patch.back) : card.back;
131
+ const cloze = (patch.cloze !== undefined ? Boolean(patch.cloze) : Boolean(card.cloze)) && gapsOf(front).length > 0;
132
+ if (!front) throw new Error(t("errors.cardNeedsFront"));
133
+ if (!back.length && !cloze) throw new Error(t("errors.cardNeedsBack"));
134
+ const duplicate = findDuplicate(library, card.deckId, front);
135
+ if (duplicate && duplicate.id !== card.id) throw new Error(t("errors.frontExists", { front }));
136
+ Object.assign(card, { front, back });
137
+ if (cloze) card.cloze = true;
138
+ else delete card.cloze;
139
+ if (patch.example !== undefined) card.example = String(patch.example).trim();
140
+ if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
141
+ card.updated = now;
142
+ return card;
143
+ }
144
+
145
+ // The quiz's word shape, so the scheduler and session keep working unchanged. A cloze card is asked one
146
+ // gap at a time ("c1", "c2"…), whatever the deck's direction.
147
+ export const toWords = (cards) =>
148
+ cards.map((card) => ({
149
+ noteId: card.id,
150
+ word: card.front,
151
+ translations: card.back,
152
+ example: card.example,
153
+ ...(card.cloze && { cloze: gapsOf(card.front), directions: gapsOf(card.front).map((_, i) => `c${i + 1}`) })
154
+ }));
package/src/lock.js ADDED
@@ -0,0 +1,64 @@
1
+ import { t } from "./i18n.js";
2
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { HOME } from "./store.js";
5
+
6
+ // One quiz at a time per data folder: each window keeps the progress in memory and saves all of it,
7
+ // so two windows would overwrite each other's answers. The lock file holds the running window's pid.
8
+ const LOCK_FILE = join(HOME, "dracosh.lock");
9
+
10
+ const alive = (pid) => {
11
+ try {
12
+ process.kill(pid, 0);
13
+ return true;
14
+ } catch (err) {
15
+ return err.code === "EPERM"; // running, but someone else's process
16
+ }
17
+ };
18
+
19
+ const readPid = () => {
20
+ try {
21
+ return Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) || null;
22
+ } catch {
23
+ return null; // no lock, or an unreadable one
24
+ }
25
+ };
26
+
27
+ // the pid of a Dracosh quiz running on this data folder, or null
28
+ export function runningPid() {
29
+ const pid = readPid();
30
+ return pid && pid !== process.pid && alive(pid) ? pid : null; // a lock left by a crash doesn't count
31
+ }
32
+
33
+ export const ALREADY_RUNNING = (pid) => t("errors.alreadyRunning", { pid });
34
+
35
+ // → a release function; throws when another quiz holds the lock. The lock file is created exclusively
36
+ // ("wx"), so of two windows started at the same moment only one gets it; a stale one is replaced once.
37
+ export function acquireLock() {
38
+ mkdirSync(HOME, { recursive: true });
39
+ const lock = JSON.stringify({ pid: process.pid, since: new Date().toISOString() });
40
+ for (let attempt = 0; ; attempt++) {
41
+ try {
42
+ writeFileSync(LOCK_FILE, lock, { flag: "wx" });
43
+ break;
44
+ } catch (err) {
45
+ if (err.code !== "EEXIST" || attempt > 0) throw err.code === "EEXIST" ? new Error(ALREADY_RUNNING(runningPid() ?? "?")) : err;
46
+ const pid = runningPid();
47
+ if (pid) throw new Error(ALREADY_RUNNING(pid));
48
+ rmSync(LOCK_FILE, { force: true }); // left behind by a window that crashed
49
+ }
50
+ }
51
+ // Two windows that both found the same stale lock may each have removed it and written their own:
52
+ // after a moment only one of them is still in the file, and the other one stops here.
53
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60);
54
+ if (readPid() !== process.pid) throw new Error(ALREADY_RUNNING(readPid() ?? "?"));
55
+ const release = () => {
56
+ try {
57
+ if (Number(JSON.parse(readFileSync(LOCK_FILE, "utf8")).pid) === process.pid) rmSync(LOCK_FILE);
58
+ } catch {}
59
+ };
60
+ process.on("exit", release);
61
+ // with the lock held no other window writes here: temp files left by a crash can go
62
+ for (const name of readdirSync(HOME)) if (/^(library|state|settings)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
63
+ return release;
64
+ }
package/src/manage.js ADDED
@@ -0,0 +1,165 @@
1
+ import { t } from "./i18n.js";
2
+ import { backupNow } from "./backup.js";
3
+ import { seedLibrary } from "./starter.js";
4
+ import { gapsOf } from "./cardline.js";
5
+ import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck, setDirections as setLibraryDirections, typedSides, updateCard } from "./library.js";
6
+ import { itemKey } from "./scheduler.js";
7
+ import { loadLibrary, saveLibrary } from "./store.js";
8
+
9
+ export const slashAnswer = () => t("errors.slashAnswer");
10
+ export const slashFront = () => t("errors.slashFront");
11
+
12
+ // in the quiz "/" opens the commands, so nothing you'd have to type may start with it
13
+ const slash = (text) => String(text ?? "").trim().startsWith("/");
14
+ function checkSlashes(deck, fields) {
15
+ if (fields.cloze) {
16
+ if (gapsOf(fields.front).some(slash)) throw new Error(slashAnswer());
17
+ return;
18
+ }
19
+ const typed = typedSides(deck);
20
+ if (typed.includes("back") && [fields.back].flat().some(slash)) throw new Error(slashAnswer());
21
+ if (typed.includes("front") && slash(fields.front)) throw new Error(slashFront());
22
+ }
23
+
24
+ // Library changes made from inside the app (/add, /decks). Each one reads the library fresh, so nothing
25
+ // written meanwhile by another Dracosh window is lost. `load`, `save` and `backup` are the store's; the
26
+ // preview gallery passes its own, so nothing it does is saved.
27
+ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup = backupNow } = {}) {
28
+ async function deckNamed(library, deckName) {
29
+ const deck = findDeck(library, deckName);
30
+ if (!deck) throw new Error(t("errors.deckGone", { deck: deckName }));
31
+ return deck;
32
+ }
33
+
34
+ return {
35
+ // every deck, the tour too, with its card count: /decks switches between them
36
+ async allDecks() {
37
+ const library = await load();
38
+ return library.decks.map((deck) => {
39
+ const cards = cardsOf(library, deck.id);
40
+ const sample = cards.find((card) => !card.cloze); // shows the deck's directions in /decks
41
+ return { name: deck.name, cards: cards.length, tour: Boolean(deck.tour), directions: deck.directions, sample: sample ? { front: sample.front, back: sample.back } : null };
42
+ });
43
+ },
44
+
45
+ // your decks (the tour isn't one), with how many cards each holds: /add lets you pick one
46
+ async ownDecks() {
47
+ const library = await load();
48
+ return library.decks.filter((deck) => !deck.tour).map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, directions: deck.directions }));
49
+ },
50
+
51
+ // A new deck, asked front → back until its first card says otherwise. Your first one replaces the
52
+ // tour: it's removed (after a backup) and the ids of its cards are returned, so their progress can go too.
53
+ async startDeck({ name }) {
54
+ const library = await load();
55
+ const tour = library.decks.find((d) => d.tour);
56
+ let removed = [];
57
+ if (tour) {
58
+ await backup("before-delete");
59
+ removed = removeDeck(library, tour.id);
60
+ }
61
+ const deck = createDeck(library, { name, languages: null, directions: "forward" });
62
+ await save(library);
63
+ return { deck, removed };
64
+ },
65
+
66
+ // → { deck, cardIds }: the session rests the directions no longer asked (session.setDirections).
67
+ // A side that becomes an answer to type may not start with "/", so such a switch is refused.
68
+ async setDirections(deckName, directions) {
69
+ const library = await load();
70
+ const found = await deckNamed(library, deckName);
71
+ const cards = cardsOf(library, found.id);
72
+ const typed = typedSides({ directions });
73
+ const blocked = cards.find((card) => !card.cloze && typed.some((side) => [card[side]].flat().some(slash)));
74
+ if (blocked) throw new Error(t("errors.slashSwitch", { text: [blocked.front, ...blocked.back].find(slash) }));
75
+ const deck = setLibraryDirections(library, found.id, directions);
76
+ await save(library);
77
+ return { deck, cardIds: cards.map((card) => card.id) };
78
+ },
79
+
80
+ // the deck with this name (ignoring case), if any: /add says so before asking anything else
81
+ async existingDeck(name) {
82
+ const deck = findDeck(await load(), name.trim());
83
+ return deck && !deck.tour ? deck : null; // the tour is about to make room, so its name is free
84
+ },
85
+
86
+ // the card with this front already in the deck, if any: /add says so as you type
87
+ async existingCard(deckName, front) {
88
+ const library = await load();
89
+ const deck = findDeck(library, deckName);
90
+ return deck ? findDuplicate(library, deck.id, front) : null;
91
+ },
92
+
93
+ // → { card, duplicate }, like addCard
94
+ async addCardTo(deckName, fields) {
95
+ const library = await load();
96
+ const deck = await deckNamed(library, deckName);
97
+ checkSlashes(deck, fields);
98
+ const result = addCard(library, deck.id, fields);
99
+ if (result.card) await save(library);
100
+ return result;
101
+ },
102
+
103
+ // Several cards at once (a pasted list), saved together → { added, duplicates }. Cards that can't be
104
+ // added (a duplicate, a "/" answer) are skipped; the paste review has flagged them already.
105
+ async addCardsTo(deckName, list) {
106
+ const library = await load();
107
+ const deck = await deckNamed(library, deckName);
108
+ const added = [];
109
+ const duplicates = [];
110
+ for (const fields of list) {
111
+ try {
112
+ checkSlashes(deck, fields);
113
+ const { card, duplicate } = addCard(library, deck.id, fields);
114
+ if (card) added.push(card);
115
+ else duplicates.push(duplicate);
116
+ } catch {
117
+ duplicates.push(null);
118
+ }
119
+ }
120
+ if (added.length) await save(library);
121
+ return { added, duplicates };
122
+ },
123
+
124
+ // A card fixed right after adding it (↑ in /add) → { card, staleKeys }: the progress keys it no
125
+ // longer has (a gap removed, a cloze card turned plain or the other way round), for the session to drop
126
+ async updateCardIn(deckName, cardId, fields) {
127
+ const library = await load();
128
+ const deck = await deckNamed(library, deckName);
129
+ checkSlashes(deck, fields);
130
+ const keysOf = (card) => (card.cloze ? gapsOf(card.front).map((_, i) => `c${i + 1}`) : ["en-pl", "pl-en"]).map((direction) => itemKey(card.id, direction));
131
+ const before = library.cards.find((c) => c.id === cardId);
132
+ const oldKeys = before ? keysOf(before) : [];
133
+ const card = updateCard(library, cardId, fields);
134
+ await save(library);
135
+ const kept = new Set(keysOf(card));
136
+ return { card, staleKeys: oldKeys.filter((key) => !kept.has(key)) };
137
+ },
138
+
139
+ // The app's language changed: the tour follows it. → { from, to }, its old and new name, or null
140
+ // when there is no tour or nothing changed.
141
+ async matchTourLanguage() {
142
+ const library = await load();
143
+ const tour = library.decks.find((d) => d.tour);
144
+ const from = tour?.name;
145
+ if (!tour || !seedLibrary(library)) return null;
146
+ await save(library);
147
+ return { from, to: library.decks.find((d) => d.tour).name };
148
+ },
149
+
150
+ // a reset is always preceded by a backup, so `dracosh restore` can undo it
151
+ backupBeforeReset: () => backup("before-reset"),
152
+
153
+ // "Everything" in the reset: your decks and cards go, and the tour comes back as on a fresh install
154
+ async resetLibrary() {
155
+ const library = emptyLibrary();
156
+ seedLibrary(library);
157
+ await save(library);
158
+ return library.decks[0].name;
159
+ }
160
+ };
161
+ }
162
+
163
+ // the app's own: reads and writes ~/.dracosh
164
+ const actions = libraryActions();
165
+ export const { allDecks, ownDecks, startDeck, setDirections, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/pause.js ADDED
@@ -0,0 +1,22 @@
1
+ import { t } from "./i18n.js";
2
+ import { parseSnooze } from "./quiet.js";
3
+ import { parseVacation } from "./vacation.js";
4
+
5
+ // "/pause" arguments, one command for a short break and for days off:
6
+ // "" → { action: "list" } what's paused or planned
7
+ // "off" → { action: "off" } questions back, days off cancelled
8
+ // "30m", "2h", "90s" → { action: "snooze", ms } a break today; the streak isn't touched
9
+ // "3d", "24.12 2.01"… → { action: "days", from, to } days off that keep your streak
10
+ // A bare whole number is refused: "30" could mean minutes or days ("24.12" is a date). → null when not understood.
11
+ export function parsePause(args, today) {
12
+ const text = args.trim().toLowerCase();
13
+ if (!text) return { action: "list" };
14
+ if (["off", "cancel", "clear"].includes(text)) return { action: "off" };
15
+ if (/^\d+$/.test(text)) return null;
16
+ if (/^\d+(\.\d+)?\s*(s|m|h)$/.test(text)) {
17
+ const ms = parseSnooze(text);
18
+ return typeof ms === "number" ? { action: "snooze", ms } : null;
19
+ }
20
+ const days = parseVacation(text, today);
21
+ return days?.action === "add" ? { action: "days", from: days.from, to: days.to } : null;
22
+ }