dracosh 0.6.0 → 0.8.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/src/cli.js CHANGED
@@ -9,6 +9,7 @@ import { language, setLanguage, t } from "./i18n.js";
9
9
  import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup, saveUpgraded } from "./backup.js";
10
10
  import { ensureProgress, snapshot } from "./progress.js";
11
11
  import { intervalDays, MASTERED_DAYS } from "./scheduler.js";
12
+ import { setOwnLanguage } from "./language.js";
12
13
  import { createSession } from "./session.js";
13
14
  import { DEFAULTS, formatInterval, normalizeSettings } from "./settings.js";
14
15
  import { seedLibrary } from "./starter.js";
@@ -112,7 +113,9 @@ async function restore(choice, { yes }) {
112
113
  }
113
114
 
114
115
  async function main() {
115
- setLanguage(normalizeSettings(await loadSettingsRaw().catch(() => ({}))).language);
116
+ const early = normalizeSettings(await loadSettingsRaw().catch(() => ({})));
117
+ setLanguage(early.language);
118
+ setOwnLanguage(early.homeLanguage);
116
119
  const { values, positionals } = parseArgs({
117
120
  allowPositionals: true,
118
121
  options: {
@@ -151,7 +154,7 @@ async function main() {
151
154
 
152
155
  if (values.preview) {
153
156
  if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
154
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
157
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
155
158
  return render(React.createElement(Preview, { alerts })).waitUntilExit();
156
159
  }
157
160
 
@@ -174,15 +177,16 @@ async function main() {
174
177
 
175
178
  let current = settings; // the session reads settings live, so /settings changes apply immediately
176
179
  let active = deck.name; // /add can switch to your first own deck
177
- const session = createSession({ loadWords: () => loadWords(active), loadAllWords, state, getSettings: () => current });
178
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
180
+ let mix = values.deck ? null : settings.mix; // decks practised together (/decks); --deck is one deck
181
+ const session = createSession({ loadWords: () => loadWords(mix ?? active), loadAllWords, state, getSettings: () => current });
182
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
179
183
  const persistSettings = async (patch) => {
180
184
  current = { ...current, ...patch };
181
185
  await patchSettings(patch);
182
186
  };
183
187
 
184
188
  // the session summary screen stays on screen after exit, so nothing more to print here
185
- const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name) }));
189
+ const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, initialMix: mix, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name), onMix: (decks) => (mix = decks) }));
186
190
  await app.waitUntilExit();
187
191
  }
188
192
 
package/src/commands.js CHANGED
@@ -4,7 +4,10 @@ import { t } from "./i18n.js";
4
4
  export const COMMANDS = [
5
5
  { name: "/hint", only: "asking", get hint() { return t("commands.hint"); } },
6
6
  { name: "/add", get hint() { return t("commands.add"); } },
7
+ { name: "/import", get hint() { return t("commands.import"); } },
8
+ { name: "/cards", get hint() { return t("commands.cards"); } },
7
9
  { name: "/decks", get hint() { return t("commands.decks"); } },
10
+ { name: "/trash", get hint() { return t("commands.trash"); } },
8
11
  { name: "/settings", get hint() { return t("commands.settings"); } },
9
12
  { name: "/stats", get hint() { return t("commands.stats"); } },
10
13
  { name: "/badges", get hint() { return t("commands.badges"); } },
@@ -0,0 +1,49 @@
1
+ // The deck the welcome offers: 30 everyday words for any pair of these languages. Each word has one
2
+ // usual translation in every language, so the card can be asked both ways; a noun keeps its article
3
+ // where the language has one. `also`: other answers that count, in that language, when it's the one
4
+ // you speak (the card's back); the one you're learning is always asked in its first form.
5
+ export const FIRST_WORDS_LANGUAGES = ["en", "pl", "de", "fr", "uk", "es", "it"];
6
+
7
+ const WORDS = [
8
+ { en: "water", pl: "woda", de: "das Wasser", fr: "l'eau", uk: "вода", es: "el agua", it: "l'acqua" },
9
+ { en: "bread", pl: "chleb", de: "das Brot", fr: "le pain", uk: "хліб", es: "el pan", it: "il pane" },
10
+ { en: "milk", pl: "mleko", de: "die Milch", fr: "le lait", uk: "молоко", es: "la leche", it: "il latte" },
11
+ { en: "apple", pl: "jabłko", de: "der Apfel", fr: "la pomme", uk: "яблуко", es: "la manzana", it: "la mela" },
12
+ { en: "coffee", pl: "kawa", de: "der Kaffee", fr: "le café", uk: "кава", es: "el café", it: "il caffè" },
13
+ { en: "egg", pl: "jajko", de: "das Ei", fr: "l'œuf", uk: "яйце", es: "el huevo", it: "l'uovo", also: { pl: ["jajo"] } },
14
+ { en: "dog", pl: "pies", de: "der Hund", fr: "le chien", uk: "собака", es: "el perro", it: "il cane", also: { uk: ["пес"] } },
15
+ { en: "cat", pl: "kot", de: "die Katze", fr: "le chat", uk: "кіт", es: "el gato", it: "il gatto", also: { uk: ["кішка"] } },
16
+ { en: "bird", pl: "ptak", de: "der Vogel", fr: "l'oiseau", uk: "птах", es: "el pájaro", it: "l'uccello", also: { es: ["el ave"], uk: ["пташка"] } },
17
+ { en: "book", pl: "książka", de: "das Buch", fr: "le livre", uk: "книга", es: "el libro", it: "il libro", also: { uk: ["книжка"] } },
18
+ { en: "school", pl: "szkoła", de: "die Schule", fr: "l'école", uk: "школа", es: "la escuela", it: "la scuola", also: { es: ["el colegio"] } },
19
+ { en: "city", pl: "miasto", de: "die Stadt", fr: "la ville", uk: "місто", es: "la ciudad", it: "la città", also: { en: ["town"] } },
20
+ { en: "train", pl: "pociąg", de: "der Zug", fr: "le train", uk: "поїзд", es: "el tren", it: "il treno", also: { uk: ["потяг"] } },
21
+ { en: "key", pl: "klucz", de: "der Schlüssel", fr: "la clé", uk: "ключ", es: "la llave", it: "la chiave", also: { fr: ["la clef"] } },
22
+ { en: "door", pl: "drzwi", de: "die Tür", fr: "la porte", uk: "двері", es: "la puerta", it: "la porta" },
23
+ { en: "window", pl: "okno", de: "das Fenster", fr: "la fenêtre", uk: "вікно", es: "la ventana", it: "la finestra" },
24
+ { en: "sun", pl: "słońce", de: "die Sonne", fr: "le soleil", uk: "сонце", es: "el sol", it: "il sole" },
25
+ { en: "rain", pl: "deszcz", de: "der Regen", fr: "la pluie", uk: "дощ", es: "la lluvia", it: "la pioggia" },
26
+ { en: "snow", pl: "śnieg", de: "der Schnee", fr: "la neige", uk: "сніг", es: "la nieve", it: "la neve" },
27
+ { en: "fire", pl: "ogień", de: "das Feuer", fr: "le feu", uk: "вогонь", es: "el fuego", it: "il fuoco" },
28
+ { en: "tree", pl: "drzewo", de: "der Baum", fr: "l'arbre", uk: "дерево", es: "el árbol", it: "l'albero" },
29
+ { en: "day", pl: "dzień", de: "der Tag", fr: "le jour", uk: "день", es: "el día", it: "il giorno", also: { fr: ["la journée"], it: ["la giornata"] } },
30
+ { en: "night", pl: "noc", de: "die Nacht", fr: "la nuit", uk: "ніч", es: "la noche", it: "la notte" },
31
+ { en: "week", pl: "tydzień", de: "die Woche", fr: "la semaine", uk: "тиждень", es: "la semana", it: "la settimana" },
32
+ { en: "to eat", pl: "jeść", de: "essen", fr: "manger", uk: "їсти", es: "comer", it: "mangiare" },
33
+ { en: "to drink", pl: "pić", de: "trinken", fr: "boire", uk: "пити", es: "beber", it: "bere" },
34
+ { en: "to sleep", pl: "spać", de: "schlafen", fr: "dormir", uk: "спати", es: "dormir", it: "dormire" },
35
+ { en: "to read", pl: "czytać", de: "lesen", fr: "lire", uk: "читати", es: "leer", it: "leggere" },
36
+ { en: "to speak", pl: "mówić", de: "sprechen", fr: "parler", uk: "говорити", es: "hablar", it: "parlare", also: { en: ["to talk"], pl: ["rozmawiać"], de: ["reden"], uk: ["розмовляти"] } },
37
+ { en: "thank you", pl: "dziękuję", de: "danke", fr: "merci", uk: "дякую", es: "gracias", it: "grazie", also: { en: ["thanks"], pl: ["dzięki"], de: ["danke schön", "dankeschön"] } }
38
+ ];
39
+
40
+ export const hasFirstWords = (home, learning) => home !== learning && [home, learning].every((code) => FIRST_WORDS_LANGUAGES.includes(code));
41
+
42
+ // the cards for someone who speaks `home` and learns `learning`: the new word on the front
43
+ export const firstWords = (home, learning) => WORDS.map((word) => ({ front: word[learning], back: [word[home], ...(word.also?.[home] ?? [])] }));
44
+
45
+ // one card of the pair, as /add's example of a card ("el gato = cat")
46
+ export function sampleCard(home, learning) {
47
+ const cat = WORDS.find((word) => word.en === "cat");
48
+ return { front: cat[learning], back: [cat[home]] };
49
+ }
package/src/language.js CHANGED
@@ -264,15 +264,20 @@ const SAMPLE_CARDS = 200; // enough to tell, and cheap to read before every ques
264
264
  const SAMPLE_LENGTH = 300; // characters of each side of a card: long answers say no more
265
265
 
266
266
  // What a person's own language seems to be, from outside the deck → [{ code, sure }], likeliest first: the
267
- // one most of their other language decks share (sure), then Dracosh's language and the system's, which
268
- // are only hints (plenty of people run both in English and speak something else)
269
- export function homeLanguages({ others = [], ui = language(), system = systemLocale() } = {}) {
267
+ // one they said they speak (`own`) and the one most of their other language decks share (both sure),
268
+ // then Dracosh's language and the system's, which are only hints (plenty of people run both in English
269
+ // and speak something else)
270
+ export function homeLanguages({ others = [], ui = language(), system = systemLocale(), own = ownLanguage } = {}) {
270
271
  const counts = new Map();
271
272
  for (const pair of others) for (const code of new Set([pair.front, pair.back].filter(isKnown))) counts.set(code, (counts.get(code) ?? 0) + 1);
272
- const shared = [...counts].filter(([, n]) => n >= 2 && n > others.length / 2).sort((a, b) => b[1] - a[1]).map(([code]) => code);
273
- const hints = [ui, system].filter((code) => code && !shared.includes(code));
274
- return [...shared.map((code) => ({ code, sure: true })), ...[...new Set(hints)].map((code) => ({ code, sure: false }))];
273
+ const shared = [...counts].filter(([, n]) => n >= 2 && n > others.length / 2).sort((a, b) => b[1] - a[1]).map(([code]) => code).filter((code) => code !== own);
274
+ const hints = [ui, system].filter((code) => code && code !== own && !shared.includes(code));
275
+ return [...(own ? [own] : []), ...shared].map((code) => ({ code, sure: true })).concat([...new Set(hints)].map((code) => ({ code, sure: false })));
275
276
  }
277
+
278
+ // the language you said you speak (the welcome, /settings): sure, ahead of any guess
279
+ let ownLanguage = null;
280
+ export const setOwnLanguage = (code) => (ownLanguage = code ?? null);
276
281
  const systemLocale = () => {
277
282
  const set = [process.env.LC_ALL, process.env.LC_MESSAGES, process.env.LANG].find((v) => v && !/^(C|POSIX)\b/i.test(v));
278
283
  return (set ?? Intl.DateTimeFormat().resolvedOptions().locale).slice(0, 2).toLowerCase();
package/src/library.js CHANGED
@@ -67,7 +67,127 @@ export function upgradeLibrary(raw) {
67
67
  return null;
68
68
  }
69
69
  };
70
- return { version: LIBRARY_VERSION, decks: decks.map((deck) => ({ ...deck, languages: tidy(deck.languages) })), cards };
70
+ const trash = cleanTrash(raw.trash);
71
+ return { version: LIBRARY_VERSION, decks: decks.map((deck) => ({ ...deck, languages: tidy(deck.languages) })), cards, ...(trash.length && { trash }) };
72
+ }
73
+
74
+ // The trash: decks and cards deleted in the last TRASH_DAYS, each with their progress, so they can come
75
+ // back whole (/trash). A deck's entry holds the deck and all its cards; deleted cards (`kind: "cards"`)
76
+ // hold the deck they were in, as it was, to go back into. An entry that doesn't hold a deck and its cards is dropped: there'd be
77
+ // nothing to bring back.
78
+ export const TRASH_DAYS = 30;
79
+ const DAY = 24 * 60 * 60 * 1000;
80
+ function cleanTrash(trash) {
81
+ if (!Array.isArray(trash)) return [];
82
+ const object = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
83
+ return trash
84
+ .filter((entry) => entry && isText(entry.id) && Number.isFinite(entry.deletedAt) && validDeck(entry.deck) && Array.isArray(entry.cards) && entry.cards.every(validCard))
85
+ .map((entry) => {
86
+ // progress edited into something odd comes back as none, not as garbage in the quiz's state
87
+ const progress = object(entry.progress);
88
+ return { ...entry, progress: { items: object(progress.items), accepted: object(progress.accepted), dormant: Array.isArray(progress.dormant) ? progress.dormant.filter(isText) : [] } };
89
+ });
90
+ }
91
+
92
+ // a deck into the trash, with its cards and their `progress` (as the session gave it) → the entry
93
+ export function trashDeck(library, deckId, { progress = {}, now = Date.now() } = {}) {
94
+ const deck = library.decks.find((d) => d.id === deckId);
95
+ if (!deck) throw new Error("That deck doesn't exist.");
96
+ const cards = cardsOf(library, deckId);
97
+ removeDeck(library, deckId);
98
+ const entry = { id: newId("t"), deletedAt: now, deck, cards, progress };
99
+ library.trash = [...(library.trash ?? []), entry];
100
+ return entry;
101
+ }
102
+
103
+ // cards of one deck into the trash, with their `progress` → the entry
104
+ export function trashCards(library, cardIds, { progress = {}, now = Date.now() } = {}) {
105
+ const ids = new Set(cardIds);
106
+ const cards = library.cards.filter((card) => ids.has(card.id));
107
+ if (!cards.length) throw new Error("Those cards don't exist.");
108
+ const deck = library.decks.find((d) => d.id === cards[0].deckId);
109
+ if (cards.some((card) => card.deckId !== deck.id)) throw new Error("Cards of one deck at a time.");
110
+ library.cards = library.cards.filter((card) => !ids.has(card.id));
111
+ const entry = { id: newId("t"), kind: "cards", deletedAt: now, deck: { ...deck }, cards, progress };
112
+ library.trash = [...(library.trash ?? []), entry];
113
+ return entry;
114
+ }
115
+
116
+ // Cards into another deck, their progress with them; one whose front is in that deck already stays
117
+ // → { moved, duplicates }: card ids
118
+ export function moveCards(library, cardIds, toDeckId) {
119
+ const target = library.decks.find((d) => d.id === toDeckId);
120
+ if (!target) throw new Error("That deck doesn't exist.");
121
+ const index = frontIndex(library, toDeckId);
122
+ const moved = [];
123
+ const duplicates = [];
124
+ for (const card of library.cards.filter((each) => cardIds.includes(each.id) && each.deckId !== toDeckId)) {
125
+ if (index.has(frontKey(card.front))) {
126
+ duplicates.push(card.id);
127
+ continue;
128
+ }
129
+ card.deckId = toDeckId;
130
+ index.set(frontKey(card.front), card);
131
+ moved.push(card.id);
132
+ }
133
+ return { moved, duplicates };
134
+ }
135
+
136
+ // the entries older than TRASH_DAYS go for good → whether any did
137
+ export function emptyOldTrash(library, now = Date.now()) {
138
+ const kept = (library.trash ?? []).filter((entry) => now - entry.deletedAt < TRASH_DAYS * DAY);
139
+ if (kept.length === (library.trash ?? []).length) return false;
140
+ if (kept.length) library.trash = kept;
141
+ else delete library.trash;
142
+ return true;
143
+ }
144
+
145
+ export const trashedUntil = (entry) => entry.deletedAt + TRASH_DAYS * DAY;
146
+
147
+ // A deck back from the trash, under its own name, or numbered when a deck has it now ("Spanish 2").
148
+ // Deleted cards go back into their deck, if it's still there (a card whose front it has now stays in
149
+ // the trash: `skipped`), or come back in a deck of their own. → { deck, entry, skipped }
150
+ export function restoreDeck(library, entryId) {
151
+ const entry = (library.trash ?? []).find((each) => each.id === entryId);
152
+ if (!entry) throw new Error(t("errors.notInTrash"));
153
+ const home = entry.kind === "cards" && library.decks.find((d) => d.id === entry.deck.id);
154
+ if (home) {
155
+ const index = frontIndex(library, home.id);
156
+ const back = entry.cards.filter((card) => !index.has(frontKey(card.front)));
157
+ const skipped = entry.cards.filter((card) => !back.includes(card));
158
+ library.cards.push(...back);
159
+ if (skipped.length) entry.cards = skipped;
160
+ else library.trash = library.trash.filter((each) => each !== entry);
161
+ if (!library.trash.length) delete library.trash;
162
+ return { deck: home, entry: { ...entry, cards: back }, skipped: skipped.length };
163
+ }
164
+ let name = entry.deck.name;
165
+ for (let n = 2; findDeck(library, name); n++) name = `${Array.from(entry.deck.name).slice(0, MAX_DECK_NAME - String(n).length - 1).join("")} ${n}`;
166
+ // its id may be taken by now (cards of it brought back first came in a deck of their own): a new one
167
+ const id = library.decks.some((d) => d.id === entry.deck.id) ? newId("d") : entry.deck.id;
168
+ const deck = { ...entry.deck, id, name };
169
+ library.decks.push(deck);
170
+ library.cards.push(...entry.cards.map((card) => Object.assign(card, { deckId: id })));
171
+ // a deck merged into another takes its cards back from there, the ones still in it
172
+ const merged = Array.isArray(entry.merged?.cardIds) && new Set(entry.merged.cardIds);
173
+ const taken = merged ? library.cards.filter((card) => merged.has(card.id) && card.deckId === entry.merged.into) : [];
174
+ for (const card of taken) card.deckId = deck.id;
175
+ library.trash = library.trash.filter((each) => each !== entry);
176
+ if (!library.trash.length) delete library.trash;
177
+ return { deck, entry: { ...entry, cards: [...entry.cards, ...taken] }, skipped: 0 };
178
+ }
179
+
180
+ // A deck's new name: not empty, not too long, and not another deck's → the deck
181
+ export function renameDeck(library, deckId, name) {
182
+ const trimmed = String(name ?? "").trim();
183
+ if (!trimmed) throw new Error(t("errors.deckNeedsName"));
184
+ if (Array.from(trimmed).length > MAX_DECK_NAME) throw new Error(t("errors.deckNameTooLong", { max: MAX_DECK_NAME }));
185
+ const deck = library.decks.find((d) => d.id === deckId);
186
+ if (!deck) throw new Error("That deck doesn't exist.");
187
+ const other = findDeck(library, trimmed);
188
+ if (other && other !== deck) throw new Error(t("errors.deckExists", { deck: other.name }));
189
+ deck.name = trimmed;
190
+ return deck;
71
191
  }
72
192
 
73
193
  export const findDeck = (library, nameOrId) =>
@@ -140,7 +260,7 @@ export const frontIndex = (library, deckId) => new Map(cardsOf(library, deckId).
140
260
  // `index`: the deck's frontIndex, kept up to date here (see findDuplicate)
141
261
  // `guid`: the note in a Dracosh package it came from, so going back to Anki it's that note again;
142
262
  // `fromAnki`: it came from a note of Anki's own (see apkg.js), which Anki still has
143
- export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, now = Date.now() }, index = null) {
263
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, ai = false, now = Date.now() }, index = null) {
144
264
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
145
265
  const cleanFront = String(front ?? "").trim();
146
266
  const cleanBack = cleanList(back);
@@ -151,7 +271,7 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
151
271
  const duplicate = findDuplicate(library, deckId, cleanFront, index);
152
272
  if (duplicate) return { card: null, duplicate };
153
273
 
154
- const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), created: now, updated: now };
274
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), ...(ai && { ai: true }), created: now, updated: now };
155
275
  if (id && library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
156
276
  library.cards.push(card);
157
277
  index?.set(frontKey(cleanFront), card);
@@ -173,10 +293,21 @@ export function updateCard(library, cardId, patch, now = Date.now()) {
173
293
  else delete card.cloze;
174
294
  if (patch.example !== undefined) card.example = String(patch.example).trim();
175
295
  if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
296
+ // a card written by AI help stays marked (`ai`) until it's changed or checked
297
+ if (patch.ai) card.ai = true;
298
+ else delete card.ai;
176
299
  card.updated = now;
177
300
  return card;
178
301
  }
179
302
 
303
+ // a card written by AI help, looked over and found right: its mark goes
304
+ export function confirmCard(library, cardId) {
305
+ const card = library.cards.find((c) => c.id === cardId);
306
+ if (!card) throw new Error("That card doesn't exist.");
307
+ delete card.ai;
308
+ return card;
309
+ }
310
+
180
311
  // The quiz's word shape, so the scheduler and session keep working unchanged. A cloze card is asked one
181
312
  // gap at a time ("c1", "c2"…), whatever the deck's direction.
182
313
  export const toWords = (cards) =>
@@ -185,5 +316,6 @@ export const toWords = (cards) =>
185
316
  word: card.front,
186
317
  translations: card.back,
187
318
  example: card.example,
319
+ ...(card.ai && { ai: true }),
188
320
  ...(card.cloze && { cloze: gapsOf(card.front), directions: gapsOf(card.front).map((_, i) => `c${i + 1}`) })
189
321
  }));
package/src/lock.js CHANGED
@@ -59,6 +59,6 @@ export function acquireLock() {
59
59
  };
60
60
  process.on("exit", release);
61
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 });
62
+ for (const name of readdirSync(HOME)) if (/^(library|state|settings|keys)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
63
63
  return release;
64
64
  }
package/src/manage.js CHANGED
@@ -1,9 +1,11 @@
1
- import { t } from "./i18n.js";
1
+ import { language as uiLanguage, t } from "./i18n.js";
2
2
  import { backupNow } from "./backup.js";
3
3
  import { seedLibrary } from "./starter.js";
4
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";
5
+ import { addCard, cardsOf, confirmCard, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
6
+ import { firstWords } from "./firstwords.js";
7
+ import { applyImport, planImport } from "./importer.js";
8
+ import { deckLanguages, homeLanguages, languageName, learningSide } from "./language.js";
7
9
  import { itemKey } from "./scheduler.js";
8
10
  import { loadLibrary, saveLibrary } from "./store.js";
9
11
 
@@ -82,6 +84,32 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
82
84
  return { deck, removed };
83
85
  },
84
86
 
87
+ // The welcome's deck of first words: the new word shown, yours typed (/decks can add the other way);
88
+ // like a deck of your own, it replaces the tour.
89
+ // Taken again (a welcome done twice), the deck made then is the one. → { deck, removed }
90
+ async startFirstWords({ home, learning }) {
91
+ const library = await load();
92
+ const language = languageName(learning);
93
+ const name = t("welcome.firstWordsDeck", { language: language.charAt(0).toLocaleUpperCase(uiLanguage()) + language.slice(1) });
94
+ const pair = (deck) => deck.firstWords && deck.languages?.front === learning && deck.languages?.back === home;
95
+ const existing = library.decks.find(pair);
96
+ if (existing) return { deck: existing, removed: [] };
97
+ // a deck of yours with that name keeps it: these get a number ("German: first words 2")
98
+ let named = name;
99
+ for (let n = 2; findDeck(library, named); n++) named = `${name} ${n}`;
100
+ const tour = library.decks.find((d) => d.tour);
101
+ let removed = [];
102
+ if (tour) {
103
+ await backup("before-delete");
104
+ removed = removeDeck(library, tour.id);
105
+ }
106
+ const deck = createDeck(library, { name: named, languages: { front: learning, back: home }, directions: "forward" });
107
+ deck.firstWords = true;
108
+ for (const fields of firstWords(home, learning)) addCard(library, deck.id, fields);
109
+ await save(library);
110
+ return { deck, removed };
111
+ },
112
+
85
113
  // → { deck, cardIds }: the session rests the directions no longer asked (session.setDirections).
86
114
  // A side that becomes an answer to type may not start with "/", so such a switch is refused.
87
115
  async setDirections(deckName, directions) {
@@ -166,8 +194,19 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
166
194
  return { added, duplicates };
167
195
  },
168
196
 
197
+ // a card written by AI help, checked: it loses its ✦
198
+ async confirmCardIn(deckName, cardId) {
199
+ const library = await load();
200
+ const deck = await deckNamed(library, deckName);
201
+ if (!cardsOf(library, deck.id).some((card) => card.id === cardId)) throw new Error("That card doesn't exist.");
202
+ const card = confirmCard(library, cardId);
203
+ await save(library);
204
+ return card;
205
+ },
206
+
169
207
  // A card fixed right after adding it (↑ in /add) → { card, staleKeys }: the progress keys it no
170
208
  // longer has (a gap removed, a cloze card turned plain or the other way round), for the session to drop
209
+
171
210
  async updateCardIn(deckName, cardId, fields) {
172
211
  const library = await load();
173
212
  const deck = await deckNamed(library, deckName);
@@ -192,6 +231,123 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
192
231
  return { from, to: library.decks.find((d) => d.tour).name };
193
232
  },
194
233
 
234
+ // /decks → Rename → the deck as it's called now
235
+ async renameDeck(oldName, newName) {
236
+ const library = await load();
237
+ const deck = renameLibraryDeck(library, (await deckNamed(library, oldName)).id, newName);
238
+ await save(library);
239
+ return deck;
240
+ },
241
+
242
+ // /decks → Delete, confirmed: a backup, then the deck goes to the trash with its cards and their
243
+ // progress (`progressOf(cardIds)`, from the session). The last deck leaves the tour in its place.
244
+ // → { entry, cardIds, next }: the trash entry, the cards gone (their progress goes from the
245
+ // session too) and the deck to practise if this one was it
246
+ async deleteDeck(name, progressOf = () => ({})) {
247
+ await backup("before-delete");
248
+ const library = await load();
249
+ const deck = await deckNamed(library, name);
250
+ const cardIds = cardsOf(library, deck.id).map((card) => card.id);
251
+ const entry = trashDeck(library, deck.id, { progress: progressOf(cardIds) });
252
+ if (!library.decks.length) seedLibrary(library);
253
+ await save(library);
254
+ const next = library.decks.find((d) => !d.tour) ?? library.decks[0];
255
+ return { entry: entry.id, cardIds, next: next.name };
256
+ },
257
+
258
+ // /trash: what's in it, newest first; anything there longer than the trash keeps it goes now.
259
+ // `card`: a deleted card's front and back, when that's what the entry holds (one card)
260
+ async trash() {
261
+ const library = await load();
262
+ if (emptyOldTrash(library)) await save(library);
263
+ return (library.trash ?? []).toReversed().map((entry) => ({
264
+ id: entry.id,
265
+ kind: entry.kind ?? "deck",
266
+ name: entry.deck.name,
267
+ cards: entry.cards.length,
268
+ card: entry.kind === "cards" && entry.cards.length === 1 ? { front: entry.cards[0].front, back: entry.cards[0].back, cloze: entry.cards[0].cloze } : null,
269
+ deletedAt: entry.deletedAt,
270
+ until: trashedUntil(entry)
271
+ }));
272
+ },
273
+
274
+ // /cards: a deck's cards as they are now, in the order they were added
275
+ async cardsIn(deckName) {
276
+ const library = await load();
277
+ return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze, ai }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze), ai: Boolean(ai) }));
278
+ },
279
+
280
+ // /cards → Delete: into the trash with their progress (`progressOf`, from the session); the deck stays,
281
+ // even empty. No backup: the trash keeps them, and a backup for every card would push the others out.
282
+ // → { entry }
283
+ async deleteCards(deckName, cardIds, progressOf = () => ({})) {
284
+ const library = await load();
285
+ await deckNamed(library, deckName);
286
+ const entry = trashCards(library, cardIds, { progress: progressOf(cardIds) });
287
+ await save(library);
288
+ return { entry: entry.id };
289
+ },
290
+
291
+ // /cards → Move: into another deck of yours, progress and all → { moved, duplicates } (card ids)
292
+ async moveCards(fromName, cardIds, toName) {
293
+ const library = await load();
294
+ await deckNamed(library, fromName);
295
+ const result = moveLibraryCards(library, cardIds, (await deckNamed(library, toName)).id);
296
+ if (result.moved.length) await save(library);
297
+ return result;
298
+ },
299
+
300
+ // /decks → Merge: every card of one deck into another, after a backup; the emptied deck goes to the
301
+ // trash with the cards the other deck had already (same front), and their progress.
302
+ // Brought back from the trash, it takes the moved cards back with it.
303
+ // → { moved, left: card ids that went to the trash with the deck, entry }
304
+ async mergeDecks(fromName, intoName, progressOf = () => ({})) {
305
+ await backup("before-delete");
306
+ const library = await load();
307
+ const from = await deckNamed(library, fromName);
308
+ const into = await deckNamed(library, intoName);
309
+ const { moved, duplicates } = moveLibraryCards(library, cardsOf(library, from.id).map((card) => card.id), into.id);
310
+ const entry = trashDeck(library, from.id, { progress: progressOf(duplicates) });
311
+ entry.merged = { into: into.id, cardIds: moved }; // u (or /trash) takes them back out
312
+ await save(library);
313
+ return { moved, left: duplicates, entry: entry.id };
314
+ },
315
+
316
+ // A deck back from the trash (/trash, or u right after deleting it). Like a deck of your own, it takes
317
+ // the tour's place. → { deck, progress, removed }: its name now, the progress to give back to the
318
+ // session, and the tour's cards that went
319
+ async restoreFromTrash(entryId) {
320
+ const library = await load();
321
+ const { deck, entry, skipped } = restoreDeck(library, entryId);
322
+ const tour = library.decks.find((d) => d.tour && d !== deck);
323
+ const removed = tour ? removeDeck(library, tour.id) : [];
324
+ await save(library);
325
+ // the progress of the cards that came back (one left in the trash keeps its own there)
326
+ const back = new Set(entry.cards.map((card) => card.id));
327
+ const mine = (object = {}) => Object.fromEntries(Object.entries(object).filter(([key]) => back.has(key.slice(0, key.lastIndexOf(":")))));
328
+ const progress = { items: mine(entry.progress?.items), accepted: mine(entry.progress?.accepted), dormant: (entry.progress?.dormant ?? []).filter((key) => back.has(key.slice(0, key.lastIndexOf(":")))) };
329
+ return { deck: deck.name, cards: entry.cards.length, kind: entry.kind ?? "deck", skipped, progress, removed };
330
+ },
331
+
332
+ // /import: what a file's cards would do to the library now (see planImport); `source` is { text, list }
333
+ // (each deck there already says how many cards it holds: `cards`)
334
+ async previewImport(source, choices) {
335
+ const library = await load();
336
+ const plan = planImport(library, source.text, { ...choices, list: source.list });
337
+ return { ...plan, decks: plan.decks.map((deck) => ({ ...deck, cards: deck.deck ? cardsOf(library, deck.deck.id).length : 0 })) };
338
+ },
339
+
340
+ // /import, carried out: a backup first, then the plan made again on the library as it is now (another
341
+ // window may have changed it). `update`: the changed cards take the file's version. → applyImport's
342
+ // result, and whether a backup was taken (none on a library with nothing in it yet)
343
+ async importCards(source, choices, { update = false } = {}) {
344
+ const backedUp = Boolean(await backup("before-import"));
345
+ const library = await load();
346
+ const result = applyImport(library, planImport(library, source.text, { ...choices, list: source.list }), { update, directions: choices.directions });
347
+ await save(library);
348
+ return { ...result, backedUp };
349
+ },
350
+
195
351
  // a reset is always preceded by a backup, so `dracosh restore` can undo it
196
352
  backupBeforeReset: () => backup("before-reset"),
197
353
 
@@ -207,4 +363,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
207
363
 
208
364
  // the app's own: reads and writes ~/.dracosh
209
365
  const actions = libraryActions();
210
- export const { allDecks, ownDecks, startDeck, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
366
+ export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, confirmCardIn, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/progress.js CHANGED
@@ -34,6 +34,14 @@ export const STAGES = [
34
34
  stage("legend", 365)
35
35
  ];
36
36
 
37
+ // /settings → the default look: the element goes for good, and the die never rolls again
38
+ export function dropElement(state, now = Date.now()) {
39
+ const progress = ensureProgress(state, now);
40
+ delete progress.element;
41
+ delete progress.elementRoll;
42
+ progress.elementDropped = true;
43
+ }
44
+
37
45
  export function stageFor(bestStreak) {
38
46
  let index = 0;
39
47
  while (index + 1 < STAGES.length && bestStreak >= STAGES[index + 1].from) index += 1;
package/src/session.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as say } from "./i18n.js"; // `t` and `text` are taken here (the clock, an answer)
2
2
  import { blankGap, plainFront } from "./cardline.js";
3
3
  import { ALMOST, closestCandidate, judge } from "./judge.js";
4
- import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
4
+ import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, dropElement, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
5
  import { describeDue, grade, intervalDays, itemKey, nextDueAt, pickNext, Rating, ratingFor, startOfTomorrow } from "./scheduler.js";
6
6
  import { recordAnswer, saveState, STATE_VERSION } from "./store.js";
7
7
  import { createTipDeck } from "./tips.js";
@@ -98,6 +98,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
98
98
  }
99
99
  lastNoteId = item.word.noteId;
100
100
  lastWrong = null;
101
+ const from = item.word.deck ?? deck; // decks practised together: the card's own deck
101
102
 
102
103
  const forward = item.direction === "en-pl";
103
104
  const gap = item.direction.startsWith("c") ? Number(item.direction.slice(1)) - 1 : null;
@@ -110,15 +111,15 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
110
111
  return {
111
112
  word: item.word,
112
113
  direction: item.direction,
113
- label: labelOf(deck),
114
+ label: labelOf(from),
114
115
  prompt,
115
116
  expected,
116
117
  // a cloze card's back is a hint under the sentence ("Cieszę się na to")
117
118
  context: gap !== null ? item.word.translations.join(" / ") : "",
118
119
  // what the answer is written in, when the deck's languages are known: its own spellings count
119
- answerLanguage: (forward ? deck?.languages?.back : deck?.languages?.front) ?? null,
120
- promptLanguage: (forward ? deck?.languages?.front : deck?.languages?.back) ?? null,
121
- learningLanguage: deck?.learning?.lang ?? null,
120
+ answerLanguage: (forward ? from?.languages?.back : from?.languages?.front) ?? null,
121
+ promptLanguage: (forward ? from?.languages?.front : from?.languages?.back) ?? null,
122
+ learningLanguage: from?.learning?.lang ?? null,
122
123
  wordCount: words.length,
123
124
  tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
124
125
  };
@@ -253,6 +254,23 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
253
254
  await save(state);
254
255
  }
255
256
 
257
+ // the progress of these cards, as the trash keeps it with a deleted deck: how well each direction is
258
+ // known, answers you declared right, directions resting
259
+ function progressOf(cardIds) {
260
+ const ids = new Set(cardIds);
261
+ const mine = (key) => ids.has(key.slice(0, key.lastIndexOf(":")));
262
+ const pick = (object) => Object.fromEntries(Object.entries(object ?? {}).filter(([key]) => mine(key)));
263
+ return structuredClone({ items: pick(state.items), accepted: pick(state.accepted), dormant: (state.dormant ?? []).filter(mine) });
264
+ }
265
+
266
+ // a deck back from the trash: its progress with it
267
+ async function restoreProgress({ items = {}, accepted = {}, dormant = [] } = {}) {
268
+ Object.assign(state.items, items);
269
+ if (Object.keys(accepted).length) state.accepted = { ...state.accepted, ...accepted };
270
+ if (dormant.length) state.dormant = [...new Set([...(state.dormant ?? []), ...dormant])];
271
+ await save(state);
272
+ }
273
+
256
274
  // A deck is asked another way now (/decks): the directions it no longer asks rest. Their progress stays
257
275
  // for when they're back, but doesn't count against mastering the card.
258
276
  async function setDirections(cardIds, directions) {
@@ -292,8 +310,22 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
292
310
  // the hatching intro plays once ever: on a brand-new state that has never answered anything
293
311
  const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
294
312
 
313
+ // the welcome follows the hatching (languages, then a way to start); `welcome` is its step to come
314
+ // back to, so a welcome left halfway goes on there next time
295
315
  async function markHatched() {
296
316
  state.hatched = true;
317
+ state.welcome = "language";
318
+ await save(state);
319
+ }
320
+ const welcomeStep = () => state.welcome ?? null;
321
+ async function setWelcomeStep(step) {
322
+ if (step) state.welcome = step;
323
+ else delete state.welcome;
324
+ await save(state);
325
+ }
326
+
327
+ async function defaultLook() {
328
+ dropElement(state, now());
297
329
  await save(state);
298
330
  }
299
331
 
@@ -315,5 +347,5 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
315
347
  await settleDay(); // nothing askable after all (a direction switched off): the quiet stretch goes on
316
348
  }
317
349
 
318
- return { totals, next, answer, workAdded, reveal, selfGrade, setDirections, forgetKeys, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
350
+ return { totals, next, answer, workAdded, reveal, selfGrade, setDirections, forgetKeys, progressOf, restoreProgress, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, welcomeStep, setWelcomeStep, openBadges, defaultLook, forget, reset, inTour: () => inTour };
319
351
  }