dracosh 0.5.0 → 0.7.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/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) =>
@@ -87,7 +207,7 @@ export function createDeck(library, { name, type = "translation", languages = nu
87
207
  return deck;
88
208
  }
89
209
 
90
- // Progress is kept per direction, so turning one off only stops asking it: its boxes stay for later.
210
+ // Progress is kept per direction, so turning one off only stops asking it: its progress stays for later.
91
211
  // `updated` says when: an Anki package written later makes its notes ask the new way too
92
212
  export function setDirections(library, deckId, directions, now = Date.now()) {
93
213
  if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
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, 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) {
@@ -192,6 +220,123 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
192
220
  return { from, to: library.decks.find((d) => d.tour).name };
193
221
  },
194
222
 
223
+ // /decks → Rename → the deck as it's called now
224
+ async renameDeck(oldName, newName) {
225
+ const library = await load();
226
+ const deck = renameLibraryDeck(library, (await deckNamed(library, oldName)).id, newName);
227
+ await save(library);
228
+ return deck;
229
+ },
230
+
231
+ // /decks → Delete, confirmed: a backup, then the deck goes to the trash with its cards and their
232
+ // progress (`progressOf(cardIds)`, from the session). The last deck leaves the tour in its place.
233
+ // → { entry, cardIds, next }: the trash entry, the cards gone (their progress goes from the
234
+ // session too) and the deck to practise if this one was it
235
+ async deleteDeck(name, progressOf = () => ({})) {
236
+ await backup("before-delete");
237
+ const library = await load();
238
+ const deck = await deckNamed(library, name);
239
+ const cardIds = cardsOf(library, deck.id).map((card) => card.id);
240
+ const entry = trashDeck(library, deck.id, { progress: progressOf(cardIds) });
241
+ if (!library.decks.length) seedLibrary(library);
242
+ await save(library);
243
+ const next = library.decks.find((d) => !d.tour) ?? library.decks[0];
244
+ return { entry: entry.id, cardIds, next: next.name };
245
+ },
246
+
247
+ // /trash: what's in it, newest first; anything there longer than the trash keeps it goes now.
248
+ // `card`: a deleted card's front and back, when that's what the entry holds (one card)
249
+ async trash() {
250
+ const library = await load();
251
+ if (emptyOldTrash(library)) await save(library);
252
+ return (library.trash ?? []).toReversed().map((entry) => ({
253
+ id: entry.id,
254
+ kind: entry.kind ?? "deck",
255
+ name: entry.deck.name,
256
+ cards: entry.cards.length,
257
+ card: entry.kind === "cards" && entry.cards.length === 1 ? { front: entry.cards[0].front, back: entry.cards[0].back, cloze: entry.cards[0].cloze } : null,
258
+ deletedAt: entry.deletedAt,
259
+ until: trashedUntil(entry)
260
+ }));
261
+ },
262
+
263
+ // /cards: a deck's cards as they are now, in the order they were added
264
+ async cardsIn(deckName) {
265
+ const library = await load();
266
+ return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze) }));
267
+ },
268
+
269
+ // /cards → Delete: into the trash with their progress (`progressOf`, from the session); the deck stays,
270
+ // even empty. No backup: the trash keeps them, and a backup for every card would push the others out.
271
+ // → { entry }
272
+ async deleteCards(deckName, cardIds, progressOf = () => ({})) {
273
+ const library = await load();
274
+ await deckNamed(library, deckName);
275
+ const entry = trashCards(library, cardIds, { progress: progressOf(cardIds) });
276
+ await save(library);
277
+ return { entry: entry.id };
278
+ },
279
+
280
+ // /cards → Move: into another deck of yours, progress and all → { moved, duplicates } (card ids)
281
+ async moveCards(fromName, cardIds, toName) {
282
+ const library = await load();
283
+ await deckNamed(library, fromName);
284
+ const result = moveLibraryCards(library, cardIds, (await deckNamed(library, toName)).id);
285
+ if (result.moved.length) await save(library);
286
+ return result;
287
+ },
288
+
289
+ // /decks → Merge: every card of one deck into another, after a backup; the emptied deck goes to the
290
+ // trash with the cards the other deck had already (same front), and their progress.
291
+ // Brought back from the trash, it takes the moved cards back with it.
292
+ // → { moved, left: card ids that went to the trash with the deck, entry }
293
+ async mergeDecks(fromName, intoName, progressOf = () => ({})) {
294
+ await backup("before-delete");
295
+ const library = await load();
296
+ const from = await deckNamed(library, fromName);
297
+ const into = await deckNamed(library, intoName);
298
+ const { moved, duplicates } = moveLibraryCards(library, cardsOf(library, from.id).map((card) => card.id), into.id);
299
+ const entry = trashDeck(library, from.id, { progress: progressOf(duplicates) });
300
+ entry.merged = { into: into.id, cardIds: moved }; // u (or /trash) takes them back out
301
+ await save(library);
302
+ return { moved, left: duplicates, entry: entry.id };
303
+ },
304
+
305
+ // A deck back from the trash (/trash, or u right after deleting it). Like a deck of your own, it takes
306
+ // the tour's place. → { deck, progress, removed }: its name now, the progress to give back to the
307
+ // session, and the tour's cards that went
308
+ async restoreFromTrash(entryId) {
309
+ const library = await load();
310
+ const { deck, entry, skipped } = restoreDeck(library, entryId);
311
+ const tour = library.decks.find((d) => d.tour && d !== deck);
312
+ const removed = tour ? removeDeck(library, tour.id) : [];
313
+ await save(library);
314
+ // the progress of the cards that came back (one left in the trash keeps its own there)
315
+ const back = new Set(entry.cards.map((card) => card.id));
316
+ const mine = (object = {}) => Object.fromEntries(Object.entries(object).filter(([key]) => back.has(key.slice(0, key.lastIndexOf(":")))));
317
+ 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(":")))) };
318
+ return { deck: deck.name, cards: entry.cards.length, kind: entry.kind ?? "deck", skipped, progress, removed };
319
+ },
320
+
321
+ // /import: what a file's cards would do to the library now (see planImport); `source` is { text, list }
322
+ // (each deck there already says how many cards it holds: `cards`)
323
+ async previewImport(source, choices) {
324
+ const library = await load();
325
+ const plan = planImport(library, source.text, { ...choices, list: source.list });
326
+ return { ...plan, decks: plan.decks.map((deck) => ({ ...deck, cards: deck.deck ? cardsOf(library, deck.deck.id).length : 0 })) };
327
+ },
328
+
329
+ // /import, carried out: a backup first, then the plan made again on the library as it is now (another
330
+ // window may have changed it). `update`: the changed cards take the file's version. → applyImport's
331
+ // result, and whether a backup was taken (none on a library with nothing in it yet)
332
+ async importCards(source, choices, { update = false } = {}) {
333
+ const backedUp = Boolean(await backup("before-import"));
334
+ const library = await load();
335
+ const result = applyImport(library, planImport(library, source.text, { ...choices, list: source.list }), { update, directions: choices.directions });
336
+ await save(library);
337
+ return { ...result, backedUp };
338
+ },
339
+
195
340
  // a reset is always preceded by a backup, so `dracosh restore` can undo it
196
341
  backupBeforeReset: () => backup("before-reset"),
197
342
 
@@ -207,4 +352,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
207
352
 
208
353
  // the app's own: reads and writes ~/.dracosh
209
354
  const actions = libraryActions();
210
- export const { allDecks, ownDecks, startDeck, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
355
+ export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/progress.js CHANGED
@@ -1,9 +1,8 @@
1
1
  import { dateLocale, t } from "./i18n.js";
2
2
  import { addDays, dayKey, daysBetween, weekStart } from "./dates.js";
3
- import { BOX_INTERVALS_DAYS } from "./scheduler.js";
3
+ import { isMastered } from "./scheduler.js";
4
4
 
5
5
  export const MAX_FREEZES = 2;
6
- const MAX_BOX = BOX_INTERVALS_DAYS.length;
7
6
  const AT_RISK_HOUR = 19;
8
7
  const COMEBACK_AFTER_DAYS = 5;
9
8
  const MISSED_KEEP_DAYS = 14;
@@ -35,6 +34,14 @@ export const STAGES = [
35
34
  stage("legend", 365)
36
35
  ];
37
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
+
38
45
  export function stageFor(bestStreak) {
39
46
  let index = 0;
40
47
  while (index + 1 < STAGES.length && bestStreak >= STAGES[index + 1].from) index += 1;
@@ -260,13 +267,14 @@ for (const badge of BADGES) {
260
267
  // progress is kept per card and direction ("id:en-pl"); badges count cards
261
268
  const cardOf = (key) => key.slice(0, key.lastIndexOf(":"));
262
269
 
263
- // a card is mastered once every direction it's asked in has reached the last box; a direction its deck
270
+ // a card is mastered once every direction it's asked in waits a month or more between reviews (see
271
+ // isMastered); a direction its deck
264
272
  // no longer asks (`dormant`, kept for when it's turned back on) doesn't hold it back
265
273
  function masteredCards(items, dormant = []) {
266
274
  const resting = new Set(dormant);
267
275
  items = items.filter(([key]) => !resting.has(key));
268
276
  const byCard = new Map();
269
- for (const [key, entry] of items) byCard.set(cardOf(key), (byCard.get(cardOf(key)) ?? true) && entry.box === MAX_BOX);
277
+ for (const [key, entry] of items) byCard.set(cardOf(key), (byCard.get(cardOf(key)) ?? true) && isMastered(entry));
270
278
  return [...byCard.values()].filter(Boolean).length;
271
279
  }
272
280
 
package/src/scheduler.js CHANGED
@@ -1,12 +1,19 @@
1
+ import { createEmptyCard, fsrs, Rating } from "ts-fsrs";
1
2
  import { dayKey } from "./dates.js";
2
3
 
3
4
  const MINUTE = 60_000;
4
5
  const DAY = 24 * 60 * MINUTE;
5
6
 
6
- // Leitner boxes: a correct answer moves the card one box up; a miss sends it back to box 1
7
- export const BOX_INTERVALS_DAYS = [1, 3, 7, 14, 30];
7
+ // Each card's next review comes from FSRS (the open-source scheduler Anki offers too): it keeps an estimate of how
8
+ // well you know the card (stability, in days, and difficulty, 1 to 10) and asks it again when
9
+ // you're about to forget it, at 90% recall. A miss brings the card back in 10 minutes, and a new card
10
+ // answered right waits a couple of days.
11
+ const scheduler = fsrs({ request_retention: 0.9, learning_steps: ["10m"], relearning_steps: ["10m"], enable_fuzz: true });
8
12
  export const RELEARN_DELAY = 10 * MINUTE;
9
13
  export const NEW_PER_DAY = 20;
14
+ // a card waiting a month or more between reviews is one you know
15
+ export const MASTERED_DAYS = 30;
16
+ export { Rating };
10
17
 
11
18
  export const DIRECTIONS = ["en-pl", "pl-en"];
12
19
  export const itemKey = (noteId, direction) => `${noteId}:${direction}`;
@@ -17,10 +24,11 @@ export function newToday(state, now) {
17
24
 
18
25
  // A review is waiting for the whole day it falls due, from midnight: a card answered at 17:00 yesterday
19
26
  // can be done this morning. But never sooner than half a day after it was answered, so a sitting across
20
- // midnight doesn't ask it again minutes later. A card just missed (streak 0) comes back at its minute.
27
+ // midnight doesn't ask it again minutes later. A card still being learned (just missed, or new) comes
28
+ // back at its minute.
21
29
  const MIN_GAP = 12 * 60 * MINUTE;
22
30
  export function readyAt(entry) {
23
- if (!entry.streak) return entry.due;
31
+ if (entry.phase !== "review") return entry.due;
24
32
  const day = new Date(entry.due);
25
33
  day.setHours(0, 0, 0, 0);
26
34
  return Math.min(entry.due, Math.max(day.getTime(), (entry.last ?? 0) + MIN_GAP));
@@ -51,8 +59,8 @@ function pickDue(due, now, random) {
51
59
  }
52
60
 
53
61
  // What to ask next: a due review or a new card (up to the daily cap), mixed at random; null when there
54
- // is nothing to do right now. Cards are never asked before they're due: answering early would move them
55
- // up the boxes without the spacing that makes them stick. Never the same note twice in a row while
62
+ // is nothing to do right now. Cards are never asked before they're due: answering early would count
63
+ // as knowing them without the spacing that makes them stick. Never the same note twice in a row while
56
64
  // anything else is waiting. A `tour` deck is different: each card is asked once, in deck order, and
57
65
  // never comes back as a review. A word's own `directions` (a cloze card's gaps) replace the deck's.
58
66
  export function pickNext({ words, state, now = Date.now(), lastNoteId = null, directions = DIRECTIONS, tour = false, random = Math.random }) {
@@ -92,15 +100,99 @@ export function startOfTomorrow(now) {
92
100
  return date.getTime();
93
101
  }
94
102
 
95
- export function grade(entry, correct, now = Date.now(), { hinted = false } = {}) {
96
- const prev = entry ?? { box: 0, seen: 0, correct: 0, wrong: 0, streak: 0 };
97
- if (correct) {
98
- // right after a miss the card starts over at box 1 (back tomorrow) instead of skipping ahead
99
- const relearning = prev.seen > 0 && prev.streak === 0;
100
- const box = hinted || relearning ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
101
- return { ...prev, box, due: daysLater(now, BOX_INTERVALS_DAYS[box - 1]), seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
102
- }
103
- return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };
103
+ // How an answer rates for FSRS: a miss or "didn't know" is Again; right, but with a hint, a typo or
104
+ // "almost" (an article, an umlaut), is Hard; right is Good. Easy isn't used: typing it is the test.
105
+ export const ratingFor = ({ correct, hinted = false, almost = false }) => (!correct ? Rating.Again : hinted || almost ? Rating.Hard : Rating.Good);
106
+
107
+ // a card's progress, as kept in state.json: the answers so far (seen, correct, wrong, streak), when it
108
+ // was last answered and is next due, and FSRS's memory of it
109
+ const PHASES = ["new", "learning", "review", "relearning"]; // FSRS's State, by number
110
+ const round = (value) => Math.round(value * 10_000) / 10_000;
111
+
112
+ function toCard(entry, now) {
113
+ if (!entry) return createEmptyCard(new Date(now));
114
+ return {
115
+ due: new Date(entry.due),
116
+ stability: entry.stability,
117
+ difficulty: entry.difficulty,
118
+ elapsed_days: 0,
119
+ scheduled_days: intervalDays(entry),
120
+ learning_steps: entry.step ?? 0,
121
+ reps: entry.seen,
122
+ lapses: entry.lapses ?? 0,
123
+ state: PHASES.indexOf(entry.phase),
124
+ last_review: new Date(entry.last)
125
+ };
126
+ }
127
+
128
+ // → the card's progress after an answer rated `rating` (see ratingFor) at `now`
129
+ export function grade(entry, rating, now = Date.now()) {
130
+ const prev = entry ?? { seen: 0, correct: 0, wrong: 0, streak: 0 };
131
+ // While a card is being learned, Hard repeats the step instead of moving on. Anki leaves that to
132
+ // you, but here a typo or a hint every time would keep the card at 15 minutes all day: the second
133
+ // right answer in a row (streak > 0 while still learning) moves it on, as Good does.
134
+ if (rating === Rating.Hard && entry && entry.phase !== "review" && entry.streak > 0) rating = Rating.Good;
135
+ // a clock set back since the last answer: FSRS can't answer before that, so it's taken as then
136
+ now = Math.max(now, entry?.last ?? now);
137
+ const { card } = scheduler.next(toCard(entry, now), new Date(now), rating);
138
+ const correct = rating !== Rating.Again;
139
+ const phase = PHASES[card.state];
140
+ // a review lands at the same time of day, so a day with a clock change is still one day
141
+ const due = phase === "review" ? daysLater(now, card.scheduled_days) : card.due.getTime();
142
+ return {
143
+ due,
144
+ last: now,
145
+ seen: prev.seen + 1,
146
+ correct: prev.correct + (correct ? 1 : 0),
147
+ wrong: prev.wrong + (correct ? 0 : 1),
148
+ streak: correct ? prev.streak + 1 : 0,
149
+ phase,
150
+ step: card.learning_steps,
151
+ stability: round(card.stability),
152
+ difficulty: round(card.difficulty),
153
+ lapses: card.lapses,
154
+ box: boxFor(phase === "review" ? card.scheduled_days : 0)
155
+ };
156
+ }
157
+
158
+ // Dracosh 0.5 and older read a Leitner `box` on every card before they look at the file's version, so
159
+ // one is kept, close to the interval: an older Dracosh then says the file is from a newer version
160
+ // instead of calling it damaged. Nothing here reads it.
161
+ const boxFor = (days) => Math.max(1, BOX_DAYS.filter((each) => each <= days).length);
162
+
163
+ // the days between the last answer and the next review (0 while it's still being learned)
164
+ export const intervalDays = (entry) => (entry.phase === "review" ? Math.max(0, Math.round((entry.due - entry.last) / DAY)) : 0);
165
+ export const isMastered = (entry) => intervalDays(entry) >= MASTERED_DAYS;
166
+
167
+ // Progress from Dracosh 0.5 and older, kept in Leitner boxes (1 to 5: 1, 3, 7, 14 and 30 days), as
168
+ // FSRS's memory of it. A box's interval is what the card was last trusted with, so it becomes the
169
+ // stability; the share of misses sets the difficulty, between FSRS's first guess after "Good" and
170
+ // after "Again". A card just missed (streak 0) is still relearning. Its due date stays.
171
+ const BOX_DAYS = [1, 3, 7, 14, 30];
172
+ export function fromBox(entry) {
173
+ const level = Math.min(Math.max(Math.round(entry.box) || 1, 1), BOX_DAYS.length);
174
+ const days = BOX_DAYS[level - 1];
175
+ // a count that isn't a number (a hand-edited file) is taken as none
176
+ const count = (value) => (Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
177
+ const [seen, correct, wrong, streak] = [count(entry.seen), count(entry.correct), count(entry.wrong), count(entry.streak)];
178
+ const missed = Math.min(wrong / Math.max(seen, 1), 1);
179
+ const [easy, hard] = [scheduler.init_difficulty(Rating.Good), scheduler.init_difficulty(Rating.Again)];
180
+ // never answered after it's due: FSRS counts the days between the two
181
+ const last = Number.isFinite(entry.last) ? Math.min(entry.last, entry.due) : entry.due - days * DAY;
182
+ return {
183
+ ...entry,
184
+ seen,
185
+ correct,
186
+ wrong,
187
+ streak,
188
+ last,
189
+ phase: !streak && seen > 0 ? "relearning" : "review",
190
+ step: 0,
191
+ stability: days,
192
+ difficulty: round(easy + (hard - easy) * missed),
193
+ lapses: wrong,
194
+ box: level
195
+ };
104
196
  }
105
197
 
106
198
  export function describeDue(entry, now = Date.now()) {