dracosh 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +25 -17
  2. package/locales/de.json +1098 -0
  3. package/locales/en.json +1081 -0
  4. package/locales/fr.json +1148 -0
  5. package/locales/pl.json +1173 -0
  6. package/locales/uk.json +1174 -0
  7. package/package.json +2 -2
  8. package/src/alerts.js +71 -4
  9. package/src/backup.js +2 -1
  10. package/src/cardline.js +71 -0
  11. package/src/cli.js +41 -54
  12. package/src/commands.js +14 -12
  13. package/src/demo.js +11 -0
  14. package/src/diff.js +20 -10
  15. package/src/i18n.js +68 -0
  16. package/src/judge.js +164 -13
  17. package/src/language.js +355 -0
  18. package/src/library.js +91 -38
  19. package/src/lock.js +2 -1
  20. package/src/manage.js +193 -58
  21. package/src/pause.js +1 -2
  22. package/src/progress.js +119 -63
  23. package/src/quiet.js +3 -2
  24. package/src/scheduler.js +26 -9
  25. package/src/session.js +118 -36
  26. package/src/settings.js +14 -6
  27. package/src/starter.js +36 -27
  28. package/src/store.js +11 -8
  29. package/src/tips.js +12 -3
  30. package/src/ui/AddCard.js +449 -81
  31. package/src/ui/AnswerInput.js +22 -10
  32. package/src/ui/App.js +209 -57
  33. package/src/ui/BadgeUnlock.js +5 -4
  34. package/src/ui/Badges.js +9 -8
  35. package/src/ui/Choice.js +14 -9
  36. package/src/ui/Companion.js +13 -13
  37. package/src/ui/Confetti.js +2 -2
  38. package/src/ui/Decks.js +167 -9
  39. package/src/ui/DieRoll.js +9 -9
  40. package/src/ui/Evolution.js +7 -7
  41. package/src/ui/Hatch.js +7 -6
  42. package/src/ui/Header.js +58 -16
  43. package/src/ui/Help.js +43 -25
  44. package/src/ui/Languages.js +167 -0
  45. package/src/ui/Mascot.js +1 -2
  46. package/src/ui/Missed.js +13 -12
  47. package/src/ui/Preview.js +48 -29
  48. package/src/ui/Reset.js +13 -14
  49. package/src/ui/Settings.js +27 -19
  50. package/src/ui/Stats.js +24 -23
  51. package/src/ui/Summary.js +30 -15
  52. package/src/ui/TheOne.js +7 -6
  53. package/src/ui/icons.js +1 -2
  54. package/src/ui/kit.js +34 -6
  55. package/src/vacation.js +2 -1
  56. package/src/words.js +8 -2
  57. package/data/tips.json +0 -32
package/src/library.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { t } from "./i18n.js";
1
2
  import { randomBytes } from "node:crypto";
2
3
  import { normalize } from "./judge.js";
4
+ import { gapsOf } from "./cardline.js";
3
5
 
4
6
  // The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
5
7
  //
@@ -7,11 +9,18 @@ import { normalize } from "./judge.js";
7
9
  // note id as their id, so progress recorded by 0.1.0 (keyed by note id) carries over unchanged.
8
10
  // New cards get a "c"-prefixed id, which can never collide with Anki's numeric ids.
9
11
 
10
- export const LIBRARY_VERSION = 1;
12
+ // 2: cloze cards, whose back may be empty (an older Dracosh would call such a library damaged)
13
+ export const LIBRARY_VERSION = 2;
11
14
 
15
+ // Older libraries carry a card type on each deck; every card is front = back now, so it's only kept.
12
16
  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" };
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"]);
15
24
 
16
25
  export const MAX_DECK_NAME = 40; // it has to fit the card's border and the header
17
26
 
@@ -28,47 +37,83 @@ function cleanList(values) {
28
37
 
29
38
  const isText = (value) => typeof value === "string";
30
39
  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);
40
+ const validDeck = (deck) => deck && isText(deck.id) && filled(deck.name); // odd languages are tidied below
41
+ // a cloze card's answers are its gaps, so its back (shown as a hint) may be empty
42
+ const validCard = (card) =>
43
+ 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);
34
44
  const broken = (why) => Object.assign(new Error(why), { damaged: true });
35
45
 
36
46
  // → the library in its current shape (undefined: there's none yet). Throws on a file written by a newer
37
47
  // Dracosh, so it's never overwritten, and on one that isn't a library, so nothing is lost by saving over it.
38
48
  export function upgradeLibrary(raw) {
39
49
  if (raw === undefined) return emptyLibrary();
40
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw broken("not a library");
50
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw broken(t("errors.why.notLibrary"));
41
51
  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.`);
52
+ throw new Error(t("errors.newerLibrary", { format: raw.version }));
43
53
  }
44
54
  const decks = raw.decks ?? [];
45
55
  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");
56
+ if (!Array.isArray(decks) || !decks.every(validDeck)) throw broken(t("errors.why.deck"));
57
+ if (!Array.isArray(cards) || !cards.every(validCard)) throw broken(t("errors.why.card"));
48
58
  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 };
59
+ if (!cards.every((card) => deckIds.has(card.deckId))) throw broken(t("errors.why.cardDeck"));
60
+ if (new Set(cards.map((card) => card.id)).size !== cards.length) throw broken(t("errors.why.cardIds"));
61
+ // languages edited by hand ("EN", "pt-BR", "english") are tidied, or left to be guessed again
62
+ const tidy = (languages) => {
63
+ try {
64
+ if (!languages || typeof languages !== "object") return null;
65
+ return cleanLanguages({ front: String(languages.front).split(/[-_]/)[0], back: String(languages.back).split(/[-_]/)[0] });
66
+ } catch {
67
+ return null;
68
+ }
69
+ };
70
+ return { version: LIBRARY_VERSION, decks: decks.map((deck) => ({ ...deck, languages: tidy(deck.languages) })), cards };
52
71
  }
53
72
 
54
73
  export const findDeck = (library, nameOrId) =>
55
74
  library.decks.find((deck) => deck.id === nameOrId) ?? library.decks.find((deck) => sameName(deck.name, nameOrId)) ?? null;
56
75
 
57
- export function createDeck(library, { name, type = "translation", languages = { front: "en", back: "pl" }, answerMode, directions = "both", tour = false, now = Date.now() }) {
76
+ export function createDeck(library, { name, type = "translation", languages = null, directions = "both", tour = false, now = Date.now() }) {
58
77
  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.`);
78
+ if (!trimmed) throw new Error(t("errors.deckNeedsName"));
79
+ if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(t("errors.deckNameTooLong", { max: MAX_DECK_NAME }));
61
80
  const existing = findDeck(library, trimmed);
62
- if (existing) throw new Error(`There is already a deck called "${existing.name}".`);
81
+ if (existing) throw new Error(t("errors.deckExists", { deck: existing.name }));
63
82
  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}".`);
83
+ if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
66
84
 
67
- const deck = { id: newId("d"), name: trimmed, type, languages: languages ? { ...languages } : null, answerMode: mode, directions, tour, created: now };
85
+ const deck = { id: newId("d"), name: trimmed, type, languages: cleanLanguages(languages), directions, tour, created: now };
68
86
  library.decks.push(deck);
69
87
  return deck;
70
88
  }
71
89
 
90
+ // Progress is kept per direction, so turning one off only stops asking it: its boxes stay for later.
91
+ export function setDirections(library, deckId, directions) {
92
+ if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
93
+ const deck = library.decks.find((d) => d.id === deckId);
94
+ if (!deck) throw new Error("That deck doesn't exist.");
95
+ deck.directions = directions;
96
+ return deck;
97
+ }
98
+
99
+ // `languages`: { front, back } as ISO 639-1 codes ("und": not one language), or null to go back to guessing
100
+ const LANGUAGE_CODE = /^[a-z]{2,3}$/;
101
+ function cleanLanguages(languages) {
102
+ if (!languages) return null;
103
+ const code = (value) => (typeof value === "string" ? value.trim().toLowerCase() : "");
104
+ const [front, back] = [code(languages.front), code(languages.back)];
105
+ if (!LANGUAGE_CODE.test(front) || !LANGUAGE_CODE.test(back)) throw new Error(`Unknown language "${languages.front} → ${languages.back}".`);
106
+ return { front, back };
107
+ }
108
+
109
+ export function setLanguages(library, deckId, languages) {
110
+ const clean = cleanLanguages(languages);
111
+ const deck = library.decks.find((d) => d.id === deckId);
112
+ if (!deck) throw new Error("That deck doesn't exist.");
113
+ deck.languages = clean;
114
+ return deck;
115
+ }
116
+
72
117
  // → the ids of the cards that went with it, so their progress can be dropped too
73
118
  export function removeDeck(library, deckId) {
74
119
  const removed = cardsOf(library, deckId).map((card) => card.id);
@@ -86,17 +131,19 @@ export const findDuplicate = (library, deckId, front) => {
86
131
  };
87
132
 
88
133
  // → { 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() }) {
134
+ // `cloze`: the front has {{gaps}}, each asked as a card of its own; the back is then only a hint
135
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, now = Date.now() }) {
90
136
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
91
137
  const cleanFront = String(front ?? "").trim();
92
138
  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.");
139
+ const isCloze = Boolean(cloze) && gapsOf(cleanFront).length > 0;
140
+ if (!cleanFront) throw new Error(t("errors.cardNeedsFront"));
141
+ if (!cleanBack.length && !isCloze) throw new Error(t("errors.cardNeedsBack"));
95
142
 
96
143
  const duplicate = findDuplicate(library, deckId, cleanFront);
97
144
  if (duplicate) return { card: null, duplicate };
98
145
 
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 };
146
+ 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 };
100
147
  if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
101
148
  library.cards.push(card);
102
149
  return { card, duplicate: null };
@@ -105,23 +152,29 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
105
152
  export function updateCard(library, cardId, patch, now = Date.now()) {
106
153
  const card = library.cards.find((c) => c.id === cardId);
107
154
  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
- }
155
+ const front = patch.front !== undefined ? String(patch.front).trim() : card.front;
156
+ const back = patch.back !== undefined ? cleanList(patch.back) : card.back;
157
+ const cloze = (patch.cloze !== undefined ? Boolean(patch.cloze) : Boolean(card.cloze)) && gapsOf(front).length > 0;
158
+ if (!front) throw new Error(t("errors.cardNeedsFront"));
159
+ if (!back.length && !cloze) throw new Error(t("errors.cardNeedsBack"));
160
+ const duplicate = findDuplicate(library, card.deckId, front);
161
+ if (duplicate && duplicate.id !== card.id) throw new Error(t("errors.frontExists", { front }));
162
+ Object.assign(card, { front, back });
163
+ if (cloze) card.cloze = true;
164
+ else delete card.cloze;
120
165
  if (patch.example !== undefined) card.example = String(patch.example).trim();
121
166
  if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
122
167
  card.updated = now;
123
168
  return card;
124
169
  }
125
170
 
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 }));
171
+ // The quiz's word shape, so the scheduler and session keep working unchanged. A cloze card is asked one
172
+ // gap at a time ("c1", "c2"…), whatever the deck's direction.
173
+ export const toWords = (cards) =>
174
+ cards.map((card) => ({
175
+ noteId: card.id,
176
+ word: card.front,
177
+ translations: card.back,
178
+ example: card.example,
179
+ ...(card.cloze && { cloze: gapsOf(card.front), directions: gapsOf(card.front).map((_, i) => `c${i + 1}`) })
180
+ }));
package/src/lock.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { t } from "./i18n.js";
1
2
  import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { HOME } from "./store.js";
@@ -29,7 +30,7 @@ export function runningPid() {
29
30
  return pid && pid !== process.pid && alive(pid) ? pid : null; // a lock left by a crash doesn't count
30
31
  }
31
32
 
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
+ export const ALREADY_RUNNING = (pid) => t("errors.alreadyRunning", { pid });
33
34
 
34
35
  // → a release function; throws when another quiz holds the lock. The lock file is created exclusively
35
36
  // ("wx"), so of two windows started at the same moment only one gets it; a stale one is replaced once.
package/src/manage.js CHANGED
@@ -1,75 +1,210 @@
1
+ import { t } from "./i18n.js";
1
2
  import { backupNow } from "./backup.js";
2
3
  import { seedLibrary } from "./starter.js";
3
- import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck } from "./library.js";
4
+ import { gapsOf } from "./cardline.js";
5
+ import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, typedSides, updateCard } from "./library.js";
6
+ import { deckLanguages, homeLanguages, learningSide } from "./language.js";
7
+ import { itemKey } from "./scheduler.js";
4
8
  import { loadLibrary, saveLibrary } from "./store.js";
5
9
 
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.
10
+ export const slashAnswer = () => t("errors.slashAnswer");
11
+ export const slashFront = () => t("errors.slashFront");
8
12
 
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
+ // in the quiz "/" opens the commands, so nothing you'd have to type may start with it
14
+ const slash = (text) => String(text ?? "").trim().startsWith("/");
15
+ function checkSlashes(deck, fields) {
16
+ if (fields.cloze) {
17
+ if (gapsOf(fields.front).some(slash)) throw new Error(slashAnswer());
18
+ return;
19
+ }
20
+ const typed = typedSides(deck);
21
+ if (typed.includes("back") && [fields.back].flat().some(slash)) throw new Error(slashAnswer());
22
+ if (typed.includes("front") && slash(fields.front)) throw new Error(slashFront());
13
23
  }
14
24
 
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" }));
25
+ // Library changes made from inside the app (/add, /decks). Each one reads the library fresh, so nothing
26
+ // written meanwhile by another Dracosh window is lost. `load`, `save` and `backup` are the store's; the
27
+ // preview gallery passes its own, so nothing it does is saved.
28
+ // your own language, as your other decks with languages set suggest (see homeLanguages)
29
+ const homeOf = (library, deck) => homeLanguages({ others: library.decks.filter((d) => d !== deck && d.languages).map((d) => d.languages) });
30
+ const learningOf = (library, deck, languages = deckLanguages(deck, cardsOf(library, deck.id))) => learningSide(languages, deck, homeOf(library, deck));
31
+ const withLearning = (library, deck) => {
32
+ const languages = deckLanguages(deck, cardsOf(library, deck.id));
33
+ return { ...languages, learning: learningOf(library, deck, languages), home: homeOf(library, deck) };
34
+ };
35
+
36
+ // A language picked as the one you're learning is kept, unless it's what a sure guess says anyway: then
37
+ // the guess goes on following the deck (its name, your other decks)
38
+ function chooseLearning(library, deck, lang) {
39
+ const languages = deckLanguages(deck, cardsOf(library, deck.id));
40
+ if (lang && lang !== languages.front && lang !== languages.back) return; // only a language the deck has
41
+ const guess = learningOf(library, { ...deck, learning: undefined });
42
+ deck.learning = !lang || (guess?.sure && guess.lang === lang) ? undefined : lang;
19
43
  }
20
44
 
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);
45
+ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup = backupNow } = {}) {
46
+ async function deckNamed(library, deckName) {
47
+ const deck = findDeck(library, deckName);
48
+ if (!deck) throw new Error(t("errors.deckGone", { deck: deckName }));
49
+ return deck;
30
50
  }
31
- const deck = createDeck(library, { name, type: "translation", languages: null, directions: bothWays ? "both" : "forward" });
32
- await saveLibrary(library);
33
- return { deck, removed };
34
- }
35
51
 
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 /.";
52
+ return {
53
+ // every deck, the tour too, with its card count: /decks switches between them
54
+ async allDecks() {
55
+ const library = await load();
56
+ return library.decks.map((deck) => {
57
+ const cards = cardsOf(library, deck.id);
58
+ const sample = cards.find((card) => !card.cloze); // shows the deck's directions in /decks
59
+ const languages = deckLanguages(deck, cards);
60
+ return { name: deck.name, cards: cards.length, tour: Boolean(deck.tour), directions: deck.directions, languages, learning: learningOf(library, deck, languages), home: homeOf(library, deck), sample: sample ? { front: sample.front, back: sample.back } : null };
61
+ });
62
+ },
38
63
 
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
- };
64
+ // your decks (the tour isn't one), with how many cards each holds: /add lets you pick one
65
+ async ownDecks() {
66
+ const library = await load();
67
+ return library.decks.filter((deck) => !deck.tour).map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, directions: deck.directions }));
68
+ },
44
69
 
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
- }
70
+ // A new deck, asked front → back until its first card says otherwise. Your first one replaces the
71
+ // tour: it's removed (after a backup) and the ids of its cards are returned, so their progress can go too.
72
+ async startDeck({ name }) {
73
+ const library = await load();
74
+ const tour = library.decks.find((d) => d.tour);
75
+ let removed = [];
76
+ if (tour) {
77
+ await backup("before-delete");
78
+ removed = removeDeck(library, tour.id);
79
+ }
80
+ const deck = createDeck(library, { name, languages: null, directions: "forward" });
81
+ await save(library);
82
+ return { deck, removed };
83
+ },
51
84
 
52
- // a reset is always preceded by a backup, so `dracosh restore` can undo it
53
- export const backupBeforeReset = () => backupNow("before-reset");
85
+ // → { deck, cardIds }: the session rests the directions no longer asked (session.setDirections).
86
+ // A side that becomes an answer to type may not start with "/", so such a switch is refused.
87
+ async setDirections(deckName, directions) {
88
+ const library = await load();
89
+ const found = await deckNamed(library, deckName);
90
+ const cards = cardsOf(library, found.id);
91
+ const typed = typedSides({ directions });
92
+ const blocked = cards.find((card) => !card.cloze && typed.some((side) => [card[side]].flat().some(slash)));
93
+ if (blocked) throw new Error(t("errors.slashSwitch", { text: [blocked.front, ...blocked.back].find(slash) }));
94
+ const deck = setLibraryDirections(library, found.id, directions);
95
+ await save(library);
96
+ return { deck, cardIds: cards.map((card) => card.id) };
97
+ },
54
98
 
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
- }
99
+ // → { front, back, guessed }: the languages set for the deck, or guessed from its cards
100
+ // (with `learning`: the language you're learning, see learningSide; null for a deck in one language)
101
+ async languagesOf(deckName) {
102
+ const library = await load();
103
+ return withLearning(library, await deckNamed(library, deckName));
104
+ },
105
+
106
+ // { front, back, learning? } from /decks or /add (`learning`: a language code); null goes back to
107
+ // guessing from the cards
108
+ async setLanguages(deckName, languages) {
109
+ const library = await load();
110
+ const deck = setLibraryLanguages(library, (await deckNamed(library, deckName)).id, languages);
111
+ if (languages?.learning !== undefined) chooseLearning(library, deck, languages.learning);
112
+ await save(library);
113
+ return withLearning(library, deck);
114
+ },
115
+
116
+ // the language you're learning in a deck (a code), from /decks → Learning → as it now stands
117
+ async setLearning(deckName, lang) {
118
+ const library = await load();
119
+ const deck = await deckNamed(library, deckName);
120
+ chooseLearning(library, deck, lang);
121
+ await save(library);
122
+ return learningOf(library, deck);
123
+ },
62
124
 
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;
125
+ // the deck with this name (ignoring case), if any: /add says so before asking anything else
126
+ async existingDeck(name) {
127
+ const deck = findDeck(await load(), name.trim());
128
+ return deck && !deck.tour ? deck : null; // the tour is about to make room, so its name is free
129
+ },
130
+
131
+ // the card with this front already in the deck, if any: /add says so as you type
132
+ async existingCard(deckName, front) {
133
+ const library = await load();
134
+ const deck = findDeck(library, deckName);
135
+ return deck ? findDuplicate(library, deck.id, front) : null;
136
+ },
137
+
138
+ // → { card, duplicate }, like addCard
139
+ async addCardTo(deckName, fields) {
140
+ const library = await load();
141
+ const deck = await deckNamed(library, deckName);
142
+ checkSlashes(deck, fields);
143
+ const result = addCard(library, deck.id, fields);
144
+ if (result.card) await save(library);
145
+ return result;
146
+ },
147
+
148
+ // Several cards at once (a pasted list), saved together → { added, duplicates }. Cards that can't be
149
+ // added (a duplicate, a "/" answer) are skipped; the paste review has flagged them already.
150
+ async addCardsTo(deckName, list) {
151
+ const library = await load();
152
+ const deck = await deckNamed(library, deckName);
153
+ const added = [];
154
+ const duplicates = [];
155
+ for (const fields of list) {
156
+ try {
157
+ checkSlashes(deck, fields);
158
+ const { card, duplicate } = addCard(library, deck.id, fields);
159
+ if (card) added.push(card);
160
+ else duplicates.push(duplicate);
161
+ } catch {
162
+ duplicates.push(null);
163
+ }
164
+ }
165
+ if (added.length) await save(library);
166
+ return { added, duplicates };
167
+ },
168
+
169
+ // A card fixed right after adding it (↑ in /add) → { card, staleKeys }: the progress keys it no
170
+ // longer has (a gap removed, a cloze card turned plain or the other way round), for the session to drop
171
+ async updateCardIn(deckName, cardId, fields) {
172
+ const library = await load();
173
+ const deck = await deckNamed(library, deckName);
174
+ checkSlashes(deck, fields);
175
+ const keysOf = (card) => (card.cloze ? gapsOf(card.front).map((_, i) => `c${i + 1}`) : ["en-pl", "pl-en"]).map((direction) => itemKey(card.id, direction));
176
+ const before = library.cards.find((c) => c.id === cardId);
177
+ const oldKeys = before ? keysOf(before) : [];
178
+ const card = updateCard(library, cardId, fields);
179
+ await save(library);
180
+ const kept = new Set(keysOf(card));
181
+ return { card, staleKeys: oldKeys.filter((key) => !kept.has(key)) };
182
+ },
183
+
184
+ // The app's language changed: the tour follows it. → { from, to }, its old and new name, or null
185
+ // when there is no tour or nothing changed.
186
+ async matchTourLanguage() {
187
+ const library = await load();
188
+ const tour = library.decks.find((d) => d.tour);
189
+ const from = tour?.name;
190
+ if (!tour || !seedLibrary(library)) return null;
191
+ await save(library);
192
+ return { from, to: library.decks.find((d) => d.tour).name };
193
+ },
194
+
195
+ // a reset is always preceded by a backup, so `dracosh restore` can undo it
196
+ backupBeforeReset: () => backup("before-reset"),
197
+
198
+ // "Everything" in the reset: your decks and cards go, and the tour comes back as on a fresh install
199
+ async resetLibrary() {
200
+ const library = emptyLibrary();
201
+ seedLibrary(library);
202
+ await save(library);
203
+ return library.decks[0].name;
204
+ }
205
+ };
75
206
  }
207
+
208
+ // the app's own: reads and writes ~/.dracosh
209
+ const actions = libraryActions();
210
+ export const { allDecks, ownDecks, startDeck, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/pause.js CHANGED
@@ -1,8 +1,7 @@
1
+ import { t } from "./i18n.js";
1
2
  import { parseSnooze } from "./quiet.js";
2
3
  import { parseVacation } from "./vacation.js";
3
4
 
4
- export const PAUSE_HELP = "Try /pause 30m, /pause 2h, /pause 3d or /pause 24.12 2.01";
5
-
6
5
  // "/pause" arguments, one command for a short break and for days off:
7
6
  // "" → { action: "list" } what's paused or planned
8
7
  // "off" → { action: "off" } questions back, days off cancelled