dracosh 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +10 -0
  3. package/README.md +100 -2
  4. package/assets/sounds/ask.wav +0 -0
  5. package/assets/sounds/badge-1.wav +0 -0
  6. package/assets/sounds/badge-2.wav +0 -0
  7. package/assets/sounds/badge-3.wav +0 -0
  8. package/assets/sounds/badge-4.wav +0 -0
  9. package/assets/sounds/close.wav +0 -0
  10. package/assets/sounds/combo.wav +0 -0
  11. package/assets/sounds/correct-0.wav +0 -0
  12. package/assets/sounds/correct-1.wav +0 -0
  13. package/assets/sounds/correct-2.wav +0 -0
  14. package/assets/sounds/correct-3.wav +0 -0
  15. package/assets/sounds/correct-4.wav +0 -0
  16. package/assets/sounds/correct-5.wav +0 -0
  17. package/assets/sounds/evolve.wav +0 -0
  18. package/assets/sounds/goal.wav +0 -0
  19. package/assets/sounds/wrong.wav +0 -0
  20. package/data/tips.json +32 -0
  21. package/package.json +47 -4
  22. package/src/alerts.js +38 -0
  23. package/src/anki.js +36 -0
  24. package/src/backup.js +95 -0
  25. package/src/cli.js +197 -0
  26. package/src/commands.js +28 -0
  27. package/src/dates.js +15 -0
  28. package/src/demo.js +11 -0
  29. package/src/diff.js +46 -0
  30. package/src/hint.js +12 -0
  31. package/src/judge.js +78 -0
  32. package/src/library.js +127 -0
  33. package/src/lock.js +63 -0
  34. package/src/manage.js +75 -0
  35. package/src/parse.js +42 -0
  36. package/src/pause.js +23 -0
  37. package/src/progress.js +455 -0
  38. package/src/quiet.js +32 -0
  39. package/src/scheduler.js +94 -0
  40. package/src/session.js +227 -0
  41. package/src/settings.js +38 -0
  42. package/src/starter.js +38 -0
  43. package/src/store.js +100 -0
  44. package/src/tips.js +30 -0
  45. package/src/ui/AddCard.js +172 -0
  46. package/src/ui/AnswerInput.js +85 -0
  47. package/src/ui/App.js +509 -0
  48. package/src/ui/BadgeUnlock.js +50 -0
  49. package/src/ui/Badges.js +122 -0
  50. package/src/ui/Choice.js +33 -0
  51. package/src/ui/Companion.js +45 -0
  52. package/src/ui/Confetti.js +46 -0
  53. package/src/ui/Decks.js +49 -0
  54. package/src/ui/DieRoll.js +104 -0
  55. package/src/ui/Evolution.js +59 -0
  56. package/src/ui/Hatch.js +100 -0
  57. package/src/ui/Header.js +117 -0
  58. package/src/ui/Help.js +68 -0
  59. package/src/ui/Mascot.js +178 -0
  60. package/src/ui/Missed.js +53 -0
  61. package/src/ui/Preview.js +256 -0
  62. package/src/ui/Reset.js +72 -0
  63. package/src/ui/Settings.js +69 -0
  64. package/src/ui/Stats.js +111 -0
  65. package/src/ui/Summary.js +41 -0
  66. package/src/ui/TheOne.js +121 -0
  67. package/src/ui/icons.js +341 -0
  68. package/src/ui/kit.js +120 -0
  69. package/src/vacation.js +56 -0
  70. package/src/words.js +23 -0
package/src/session.js ADDED
@@ -0,0 +1,227 @@
1
+ import { closestCandidate, judge } from "./judge.js";
2
+ import { addVacation, applyAnswer, applyCaughtUp, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
3
+ import { describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
4
+ import { recordAnswer, saveState } from "./store.js";
5
+ import { createTipDeck } from "./tips.js";
6
+ import { dayKey } from "./dates.js";
7
+ import { PAUSE_HELP, parsePause } from "./pause.js";
8
+ import { formatRange } from "./vacation.js";
9
+
10
+ const LABELS = { "en-pl": "EN → PL", "pl-en": "PL → EN" };
11
+
12
+ // the tag on the card's border: the language pair for a language deck, the deck's name otherwise
13
+ function labelOf(deck, direction) {
14
+ if (!deck) return LABELS[direction];
15
+ if (!deck.languages) return deck.name;
16
+ const { front, back } = deck.languages;
17
+ const [from, to] = direction === "en-pl" ? [front, back] : [back, front];
18
+ return `${from.toUpperCase()} → ${to.toUpperCase()}`;
19
+ }
20
+ const COMBO_CHEER_EVERY = 5;
21
+
22
+ // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
23
+ // `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
24
+ export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
25
+ const rules = () => ({ skipWeekends: getSettings().skipWeekends });
26
+ const totals = { asked: 0, correct: 0, combo: 0 };
27
+ let lastNoteId = null;
28
+ let inTour = false; // the tour teaches one thing per card; tips on top of that are too much
29
+ let lastWrong = null; // the latest wrong answer, until the next question: /correct can still overrule it
30
+ let current = { words: [], deck: null }; // the deck the last question came from
31
+
32
+ // When nothing is waiting in any of your decks before tomorrow, the day is done → { done, cheers }
33
+ async function settleDay() {
34
+ const decks = loadAllWords ? await loadAllWords() : [current].filter((d) => !d.deck?.tour);
35
+ const t = now();
36
+ for (const { words, deck } of decks) {
37
+ const directions = directionsOf(deck);
38
+ if (pickNext({ words, state, now: t, directions })) return { done: false, cheers: [] };
39
+ const due = nextDueAt({ words, state, now: t, directions });
40
+ if (due !== null && due < startOfTomorrow(t)) return { done: false, cheers: [] };
41
+ }
42
+ const { cheers } = applyCaughtUp(state, { goal: getSettings().dailyGoal, rules: rules(), now: t });
43
+ await save(state);
44
+ return { done: true, cheers };
45
+ }
46
+
47
+ // when the deck's next card is due, if nothing is waiting in it right now (null: something is)
48
+ function upNext() {
49
+ const { words, deck } = current;
50
+ if (deck?.tour || pickNext({ words, state, now: now(), directions: directionsOf(deck) })) return null;
51
+ return nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
52
+ }
53
+
54
+ async function next() {
55
+ const { words, deck } = await loadWords();
56
+ current = { words, deck };
57
+ inTour = Boolean(deck?.tour);
58
+ const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsOf(deck), tour: deck?.tour });
59
+ // nothing to ask is a normal state, not an error: the UI shows a way on (a finished tour, a new
60
+ // deck) or when the next card is due. Done with everything for today counts as the daily goal.
61
+ if (!item) {
62
+ const empty = { empty: true, tour: Boolean(deck?.tour), count: words.length, nextDue: null, cheers: [], dayDone: false };
63
+ if (!deck?.tour && words.length) {
64
+ empty.nextDue = nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
65
+ const day = await settleDay();
66
+ empty.cheers = day.cheers;
67
+ empty.dayDone = day.done; // false: this deck is done, but another one still has cards today
68
+ }
69
+ const message = deck?.tour ? "You've finished the tour." : words.length ? "Nothing to practise right now." : `The deck "${deck?.name}" has no cards yet.`;
70
+ throw Object.assign(new Error(message), empty);
71
+ }
72
+ lastNoteId = item.word.noteId;
73
+ lastWrong = null;
74
+
75
+ const forward = item.direction === "en-pl";
76
+ return {
77
+ word: item.word,
78
+ direction: item.direction,
79
+ label: labelOf(deck, item.direction),
80
+ prompt: forward ? item.word.word : item.word.translations.join(", "),
81
+ expected: forward ? item.word.translations : [item.word.word],
82
+ wordCount: words.length,
83
+ tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
84
+ };
85
+ }
86
+
87
+ // Each deck decides which way it's asked (set when it's made): both ways, or one way only
88
+ // ("2 + 2" → "4"). The front-to-back direction is keyed "en-pl" internally, whatever the languages.
89
+ function directionsOf(deck) {
90
+ return deck?.directions === "forward" ? ["en-pl"] : ["en-pl", "pl-en"];
91
+ }
92
+
93
+ async function answer(question, text, { hinted = false } = {}) {
94
+ const key = itemKey(question.word.noteId, question.direction);
95
+ // answers you once declared right (/correct) count for this card from now on
96
+ const result = judge(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
97
+ const correct = result !== "wrong";
98
+ const t = now();
99
+ const before = state.items[key];
100
+ const comboBefore = totals.combo;
101
+ const entry = grade(before, correct, t, { hinted });
102
+ recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
103
+
104
+ totals.asked += 1;
105
+ totals.correct += correct ? 1 : 0;
106
+ totals.combo = correct ? totals.combo + 1 : 0;
107
+ lastWrong = correct ? null : { question, text, key, before, comboBefore, hinted, at: t };
108
+ // a blank answer on a tour card just shows it: the tour isn't something to have "missed"
109
+ if (!correct && !(question.tour && !text.trim())) recordMiss(state, { key, label: question.label, prompt: question.prompt, expected: question.expected, answer: text, at: t }, t);
110
+
111
+ const reward = applyAnswer(state, { result, goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: t });
112
+ const cheers = [...reward.cheers];
113
+ if (correct && totals.combo % COMBO_CHEER_EVERY === 0) cheers.push({ kind: "combo", text: `Combo ×${totals.combo}` });
114
+
115
+ await save(state);
116
+ // the last card of the day settles it right away, so quitting now doesn't lose the goal
117
+ if (!question.tour) cheers.push(...(await settleDay()).cheers);
118
+ // given/closest feed the per-letter diff the UI shows after a miss or a forgiven typo
119
+ const closest = result === "exact" ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
120
+ return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest, nextDue: upNext() };
121
+ }
122
+
123
+ // Re-grade the last wrong answer as correct and remember the answer for this card.
124
+ async function overrule() {
125
+ if (!lastWrong) throw new Error("There is no wrong answer to correct.");
126
+ const { question, text, key, before, comboBefore, hinted, at } = lastWrong;
127
+ lastWrong = null;
128
+
129
+ const entry = grade(before, true, at, { hinted });
130
+ state.items[key] = entry;
131
+ undoMiss(state, key, at);
132
+ state.accepted ??= {};
133
+ state.accepted[key] = [...(state.accepted[key] ?? []), text];
134
+
135
+ totals.correct += 1;
136
+ totals.combo = comboBefore + 1;
137
+ const { cheers } = applyOverrule(state, { goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: at });
138
+
139
+ await save(state);
140
+ if (!question.tour) cheers.push(...(await settleDay()).cheers);
141
+ return { result: "exact", overruled: true, accepted: text, dueIn: describeDue(entry, now()), combo: totals.combo, cheers, nextDue: upNext() };
142
+ }
143
+
144
+ const canOverrule = () => lastWrong !== null && lastWrong.text.trim() !== ""; // nothing typed, nothing to accept
145
+
146
+ const stats = () => snapshot(state, { goal: getSettings().dailyGoal, rules: rules(), now: now() });
147
+
148
+ const month = (offset) => calendarMonth(state, { offset, rules: rules(), now: now() });
149
+ const missed = (offset) => missedOn(state, { offset, now: now() });
150
+
151
+ // /pause: a break today (the UI holds it, this returns its length) or days off that keep the
152
+ // streak (saved here). → { snooze?: ms | "off", list?: true, message? }
153
+ async function pause(args) {
154
+ const today = dayKey(now());
155
+ const parsed = parsePause(args, today);
156
+ if (!parsed) throw new Error(PAUSE_HELP);
157
+ if (parsed.action === "snooze") return { snooze: parsed.ms };
158
+ if (parsed.action === "days") {
159
+ // days off start today at the earliest: missed days can't be turned into days off afterwards
160
+ const from = parsed.from < today ? today : parsed.from;
161
+ if (parsed.to < today) throw new Error("Those days are already over. Days off can only start today or later.");
162
+ addVacation(state, from, parsed.to, now());
163
+ await save(state);
164
+ const what = from === parsed.to ? `Day off on ${formatRange(from, from)}` : `Days off ${formatRange(from, parsed.to)}`;
165
+ return { message: `${what}: your streak is safe.` };
166
+ }
167
+ if (parsed.action === "off") {
168
+ cancelVacations(state, now());
169
+ await save(state);
170
+ return { snooze: "off", message: "Pause off: questions are back, and no days off are planned" };
171
+ }
172
+ const { upcoming } = vacationInfo(ensureProgress(state, now()), today);
173
+ return { list: true, message: upcoming.length ? `Days off: ${upcoming.map((v) => formatRange(v.from, v.to)).join(", ")}` : `No days off planned. ${PAUSE_HELP}` };
174
+ }
175
+
176
+ // a tip for the wait between questions; remembering which ones were shown is best-effort
177
+ function nextTip() {
178
+ const tip = tipDeck.next();
179
+ save(state).catch(() => {});
180
+ return tip;
181
+ }
182
+
183
+ // progress of cards that are gone (a removed deck) is dropped with them
184
+ async function forget(cardIds) {
185
+ const ids = new Set(cardIds);
186
+ const gone = (key) => ids.has(key.slice(0, key.lastIndexOf(":")));
187
+ for (const key of Object.keys(state.items)) if (gone(key)) delete state.items[key];
188
+ for (const key of Object.keys(state.accepted ?? {})) if (gone(key)) delete state.accepted[key];
189
+ await save(state);
190
+ }
191
+
192
+ // Reset from /settings (the caller makes a backup first). "progress" starts the game over: badges,
193
+ // streak, stats and the dragon's form and element; your cards and their boxes stay. "everything"
194
+ // empties the state as on a fresh install, so the egg hatches again.
195
+ async function reset(scope) {
196
+ if (scope === "everything") {
197
+ for (const key of Object.keys(state)) delete state[key];
198
+ Object.assign(state, { version: 1, items: {}, newToday: { date: "", count: 0 } });
199
+ } else {
200
+ delete state.progress;
201
+ delete state.tips;
202
+ }
203
+ totals.combo = 0;
204
+ lastWrong = null;
205
+ await save(state);
206
+ }
207
+
208
+ // the hatching intro plays once ever: on a brand-new state that has never answered anything
209
+ const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
210
+
211
+ async function markHatched() {
212
+ state.hatched = true;
213
+ await save(state);
214
+ }
215
+
216
+ // /badges: the ones won since it was last opened, which light up one by one; opening it marks them seen
217
+ async function openBadges() {
218
+ const fresh = unseenBadges(state, now());
219
+ if (fresh.length) {
220
+ markBadgesSeen(state, now());
221
+ await save(state);
222
+ }
223
+ return fresh;
224
+ }
225
+
226
+ return { totals, next, answer, overrule, canOverrule, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
227
+ }
@@ -0,0 +1,38 @@
1
+ export const DEFAULTS = { everyMs: 600_000, sound: true, volume: 0.5, dailyGoal: 20, tips: "always", quiet: null, skipWeekends: true, deck: null };
2
+
3
+ export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
4
+ export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
5
+ export const VOLUMES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1];
6
+ export const TIP_MODES = ["always", "sometimes", "off"];
7
+ export const TIP_LABELS = { always: "always", sometimes: "sometimes (1 in 3 waits)", off: "off" };
8
+ // presets for /settings; any { from, to } in settings.json works too
9
+ export const QUIET_PRESETS = [null, { from: 21, to: 7 }, { from: 22, to: 8 }, { from: 23, to: 7 }, { from: 0, to: 8 }];
10
+
11
+ export function formatInterval(ms) {
12
+ if (ms < 60_000) return `${Math.round(ms / 1000)} s`;
13
+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)} min`;
14
+ return `${Math.round(ms / 3_600_000)} h`;
15
+ }
16
+
17
+ // older versions saved tips as a boolean
18
+ const normalizeTips = (value) => (value === true ? "always" : value === false ? "off" : TIP_MODES.includes(value) ? value : DEFAULTS.tips);
19
+
20
+ const isHour = (v) => Number.isInteger(v) && v >= 0 && v <= 23;
21
+
22
+ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
23
+
24
+ // settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
25
+ export function normalizeSettings(raw = {}) {
26
+ raw = raw && typeof raw === "object" ? raw : {};
27
+ return {
28
+ everyMs: isNumber(raw.everyMs) && raw.everyMs >= 1000 ? raw.everyMs : DEFAULTS.everyMs,
29
+ sound: typeof raw.sound === "boolean" ? raw.sound : DEFAULTS.sound,
30
+ volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
31
+ dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
32
+ tips: normalizeTips(raw.tips),
33
+ skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
34
+ quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
35
+ deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null // picked in /decks; null = your first deck
36
+ };
37
+ }
38
+
package/src/starter.js ADDED
@@ -0,0 +1,38 @@
1
+ import { addCard, createDeck } from "./library.js";
2
+
3
+ // The deck a fresh install starts with: a short tour that teaches Dracosh by doing. Every card says
4
+ // exactly what to type, and the line shown after the answer explains the next thing. It's a `tour`
5
+ // deck: every card is asked once, in this order, and never comes back as a review. `Backticks` mark
6
+ // what to type (or a command); the quiz shows them highlighted, in the tour only. Answers never start with "/", because "/" opens the commands.
7
+ export const STARTER_DECK = "Getting started";
8
+ // bump it when the cards below change: an older copy of the tour in someone's library gets replaced
9
+ const STARTER_VERSION = 7;
10
+
11
+ const STARTER_CARDS = [
12
+ { front: "Welcome! Every few minutes a card asks you something. Type the answer and press Enter. Try it and type `hello`", back: ["hello"], example: "Press `Enter` now for the next card, or wait and it will come by itself." },
13
+ { front: "Small typos still count. Type `dragon`, but miss a letter on purpose (like `dragn`)", back: ["dragon"], example: "A typo counts as right, and Dracosh shows you the correct spelling." },
14
+ { front: "A card can accept more than one answer. What is 2 + 2? (`4` and `four` both work)", back: ["4", "four"], example: "Every right answer moves a card to a later box, so you see it less and less often." },
15
+ { front: "Stuck? Type `/hint` and press Enter, and the answer shows up letter by letter. Try it, then type `apple`", back: ["apple"], example: "A hinted answer still counts, but the card stays in its box for now." },
16
+ { front: "What is your dragon's secret name? Nobody knows, so get this one wrong on purpose and type `dog`", back: ["Asogaras"], example: "In your own decks a missed card comes back sooner. If you were marked wrong by mistake, type `/correct` now." },
17
+ { front: "Type `/` at any time to see all commands. Try `/badges` after this card. For now, type `ok`", back: ["ok", "okay"], example: "`/stats` shows your calendar, `/companion` your dragon, `/settings` how often cards come." },
18
+ { front: "Reach your daily goal every day to keep your streak. Your dragon grows with it. Type `every day`", back: ["every day", "everyday", "daily"], example: "Miss a day and a freeze saves your streak, if you have one left." },
19
+ { front: "Need a break? `/pause 1h` holds the cards for an hour, `/pause 3d` gives you days off. For now, type `later`", back: ["later"], example: "Leave Dracosh alone for a few minutes and the dragon dozes off. Any key wakes it." },
20
+ { front: "That's the tour! Type `done`", back: ["done"], example: "Now make it yours and type `/add` to start your own deck. The tour makes room for it." }
21
+ ];
22
+
23
+ // the tour as an earlier version created it (the first one had no version number yet)
24
+ const isStarter = (deck) => deck.starter !== undefined || (deck.name === STARTER_DECK && deck.type === "qa" && !deck.languages);
25
+
26
+ // Adds the tour to an empty library, or brings an older copy of it up to date (its progress is
27
+ // dropped with the old cards). Returns true when the library changed and needs saving.
28
+ export function seedLibrary(library, now = Date.now()) {
29
+ let deck = library.decks.find(isStarter);
30
+ if (library.decks.length && !deck) return false;
31
+ if (deck && (deck.starter ?? 1) >= STARTER_VERSION) return false;
32
+
33
+ if (deck) library.cards = library.cards.filter((card) => card.deckId !== deck.id);
34
+ else deck = createDeck(library, { name: STARTER_DECK, type: "qa", answerMode: "typed", languages: null, directions: "forward", tour: true, now });
35
+ Object.assign(deck, { tour: true, starter: STARTER_VERSION });
36
+ for (const card of STARTER_CARDS) addCard(library, deck.id, { ...card, now });
37
+ return true;
38
+ }
package/src/store.js ADDED
@@ -0,0 +1,100 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { dayKey } from "./dates.js";
5
+ import { upgradeLibrary } from "./library.js";
6
+ import { itemKey, newToday } from "./scheduler.js";
7
+
8
+ export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
9
+ const LIBRARY_FILE = join(HOME, "library.json");
10
+ const STATE_FILE = join(HOME, "state.json");
11
+ const SETTINGS_FILE = join(HOME, "settings.json");
12
+ // everything a backup holds, by name
13
+ export const DATA_FILES = { library: LIBRARY_FILE, state: STATE_FILE, settings: SETTINGS_FILE };
14
+
15
+ export const STATE_VERSION = 1;
16
+ const emptyState = () => ({ version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
17
+
18
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
19
+
20
+ // what to say when a data file can't be used as it is
21
+ export const damaged = (file, why) => new Error(`${file} looks damaged (${why}). Run "dracosh restore" to bring back a backup.`);
22
+
23
+ export async function readJson(file, fallback) {
24
+ try {
25
+ return JSON.parse(await readFile(file, "utf8"));
26
+ } catch (err) {
27
+ if (err.code === "ENOENT") return fallback;
28
+ if (err instanceof SyntaxError) throw damaged(file, err.message);
29
+ throw new Error(`Can't read ${file}: ${err.message}`);
30
+ }
31
+ }
32
+
33
+ // Writes are queued (one at a time) and go through write-then-rename: a crash mid-write can't corrupt the file,
34
+ // and two saves in quick succession (an answer and a shown tip, say) can't trip over each other's temp file.
35
+ let writes = Promise.resolve();
36
+
37
+ export function writeJson(file, data) {
38
+ const json = JSON.stringify(data, null, 2); // snapshot now: the state object keeps changing
39
+ const job = writes.then(async () => {
40
+ await mkdir(dirname(file), { recursive: true });
41
+ const tmp = `${file}.${process.pid}.tmp`; // another Dracosh process never shares it
42
+ await writeFile(tmp, json);
43
+ await rename(tmp, file);
44
+ });
45
+ writes = job.catch(() => {}); // one failed write must not block the next ones
46
+ return job;
47
+ }
48
+
49
+ export async function loadLibrary() {
50
+ try {
51
+ return upgradeLibrary(await readJson(LIBRARY_FILE, undefined));
52
+ } catch (err) {
53
+ throw err.damaged ? damaged(LIBRARY_FILE, err.message) : err;
54
+ }
55
+ }
56
+ export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
57
+
58
+ // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten
59
+ export async function loadState() {
60
+ const state = await readJson(STATE_FILE, undefined);
61
+ if (state === undefined) return emptyState();
62
+ if (!isObject(state) || !isObject(state.items)) throw damaged(STATE_FILE, "no progress in it");
63
+ if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(STATE_FILE, "a card without its box or date");
64
+ const { progress } = state;
65
+ const validProgress =
66
+ isObject(progress) &&
67
+ isObject(progress.days) &&
68
+ Object.values(progress.days).every(isObject) &&
69
+ isObject(progress.streak) &&
70
+ ["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
71
+ isObject(progress.badges) &&
72
+ (progress.vacations === undefined || Array.isArray(progress.vacations));
73
+ if (progress !== undefined && !validProgress) throw damaged(STATE_FILE, "the streak and badges are unreadable");
74
+ if (state.version > STATE_VERSION) throw new Error(`${STATE_FILE} was saved by a newer version of Dracosh. Please update Dracosh.`);
75
+ if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
76
+ return state;
77
+ }
78
+ export const saveState = (state) => writeJson(STATE_FILE, state);
79
+
80
+ // `countNew: false` keeps a card out of the daily cap on new cards (the tour's don't use it up)
81
+ export function recordAnswer(state, noteId, direction, entry, now = Date.now(), { countNew = true } = {}) {
82
+ const key = itemKey(noteId, direction);
83
+ const isNew = countNew && !state.items[key];
84
+ const date = dayKey(now);
85
+ state.items[key] = entry;
86
+ if (isNew) state.newToday = { date, count: newToday(state, now) + 1 };
87
+ return state;
88
+ }
89
+
90
+ // hand-edited into something odd, even broken JSON: the defaults take over (nothing worth a restore)
91
+ export const loadSettingsRaw = async () => {
92
+ const raw = await readJson(SETTINGS_FILE, {}).catch((err) => (err.message.includes("looks damaged") ? {} : Promise.reject(err)));
93
+ return isObject(raw) ? raw : {};
94
+ };
95
+
96
+ // merges into what's on disk, so a one-off CLI flag never gets persisted by accident
97
+ export async function patchSettings(patch) {
98
+ const current = await loadSettingsRaw();
99
+ await writeJson(SETTINGS_FILE, { ...current, ...patch });
100
+ }
package/src/tips.js ADDED
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ // Short tips about Dracosh itself, shown now and then while you wait for the next card.
4
+ export const TIPS = JSON.parse(readFileSync(new URL("../data/tips.json", import.meta.url), "utf8"));
5
+ const SOMETIMES_CHANCE = 1 / 3;
6
+
7
+ // "always" shows a tip on every wait, "sometimes" on about one in three
8
+ export function shouldShowTip(mode, random = Math.random) {
9
+ return mode === "always" || (mode === "sometimes" && random() < SOMETIMES_CHANCE);
10
+ }
11
+
12
+ // Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen
13
+ // (ids of tips that no longer exist are dropped from it).
14
+ export function createTipDeck({ state, tips = TIPS, random = Math.random }) {
15
+ const known = new Set(tips.map((tip) => tip.id));
16
+ return {
17
+ next() {
18
+ const seen = new Set((state.tips?.seen ?? []).filter((id) => known.has(id)));
19
+ let fresh = tips.filter((tip) => !seen.has(tip.id));
20
+ if (!fresh.length) {
21
+ seen.clear();
22
+ fresh = tips;
23
+ }
24
+ const tip = fresh[Math.floor(random() * fresh.length)];
25
+ seen.add(tip.id);
26
+ state.tips = { seen: [...seen] };
27
+ return tip;
28
+ }
29
+ };
30
+ }
@@ -0,0 +1,172 @@
1
+ import { Fragment, useEffect, useState } from "react";
2
+ import { Box, Text } from "ink";
3
+ import { MAX_DECK_NAME } from "../library.js";
4
+ import { SLASH_ANSWER, SLASH_FRONT } from "../manage.js";
5
+ import { AnswerInput } from "./AnswerInput.js";
6
+ import { Choice, CHOICE_KEYS } from "./Choice.js";
7
+ import { html, KeyHints, theme, usePanelWidth } from "./kit.js";
8
+
9
+ const FIELDS = {
10
+ deck: { label: "Name your deck", hint: "Polish, Biology, Capitals… whatever you want to learn" },
11
+ front: { label: "Front", hint: "the word or question, e.g. kot" },
12
+ back: { label: "Back", hint: "the answer; separate several with commas, e.g. cat, kitty" },
13
+ example: { label: "Example", hint: "optional: a sentence that helps you remember. Enter skips it" }
14
+ };
15
+
16
+ const splitAnswers = (text) => text.split(",").map((part) => part.trim()).filter(Boolean);
17
+
18
+ const NEW_DECK = "+ New deck";
19
+
20
+ // /add: a small form inside the app. You pick one of your decks or start a new one (your first one
21
+ // replaces the tour), then add cards one after another until Esc. `actions` reads and writes the library.
22
+ // `startNew` skips the deck list and goes straight to a new deck ("+ New deck" in /decks).
23
+ export function AddCard({ current, actions, onDone, startNew = false }) {
24
+ const panel = usePanelWidth();
25
+ const [step, setStep] = useState("loading"); // loading | pick | deck | ways | front | back | example | saving
26
+ const [decks, setDecks] = useState([]);
27
+ const [picked, setPicked] = useState(0);
28
+ const [ways, setWays] = useState(0);
29
+ const [bothWays, setBothWays] = useState(false); // the deck's front is an answer too
30
+ const [deck, setDeck] = useState(null);
31
+ const [newDeck, setNewDeck] = useState(null); // { name, removed } once a first deck was started here
32
+ const [draft, setDraft] = useState({ front: "", back: [] });
33
+ const [message, setMessage] = useState("");
34
+ const [error, setError] = useState("");
35
+ const [added, setAdded] = useState(0);
36
+
37
+ useEffect(() => {
38
+ actions.ownDecks().then(
39
+ (own) => {
40
+ setDecks(own);
41
+ setPicked(Math.max(0, own.findIndex((d) => d.name === current)));
42
+ setStep(own.length && !startNew ? "pick" : "deck");
43
+ },
44
+ (err) => setError(err.message)
45
+ );
46
+ }, []);
47
+
48
+ // `dropped`: a card was half written (its front typed) when Esc ended /add
49
+ const finish = () => onDone({ deck: newDeck?.name ?? null, removed: newDeck?.removed ?? [], added, dropped: Boolean(draft.front) && (step === "back" || step === "example") });
50
+
51
+ async function startDeck(bothWays) {
52
+ setStep("saving");
53
+ try {
54
+ const { deck: created, removed } = await actions.startDeck({ name: deck, bothWays });
55
+ setDeck(created.name);
56
+ setBothWays(bothWays);
57
+ setNewDeck({ name: created.name, removed });
58
+ setMessage(`Your deck "${created.name}" is ready. Now its first card:`);
59
+ setStep("front");
60
+ } catch (err) {
61
+ setError(err.message);
62
+ setStep("deck");
63
+ }
64
+ }
65
+
66
+ async function save(example) {
67
+ setStep("saving");
68
+ try {
69
+ const { duplicate } = await actions.addCardTo(deck, { ...draft, example });
70
+ if (duplicate) setError(`"${duplicate.front}" is already in ${deck}.`);
71
+ else {
72
+ setAdded((n) => n + 1);
73
+ setMessage(`Added "${draft.front}" to ${deck}. Next card, or Esc to finish.`);
74
+ }
75
+ } catch (err) {
76
+ setError(err.message);
77
+ }
78
+ setDraft({ front: "", back: [] });
79
+ setStep("front");
80
+ }
81
+
82
+ function submit(text) {
83
+ const value = text.trim();
84
+ setError("");
85
+ setMessage("");
86
+ if (step === "deck") {
87
+ if (!value) return setError("Your deck needs a name.");
88
+ if (Array.from(value).length > MAX_DECK_NAME) return setError(`Keep the name to ${MAX_DECK_NAME} characters or fewer.`);
89
+ return actions.existingDeck(value).then((existing) => {
90
+ if (existing) return setError(`There is already a deck called "${existing.name}".`);
91
+ setDeck(value);
92
+ setStep("ways");
93
+ }, (err) => setError(err.message));
94
+ }
95
+ if (step === "front") {
96
+ if (!value) return setError("A card needs a front.");
97
+ if (bothWays && value.startsWith("/")) return setError(SLASH_FRONT);
98
+ return actions.existingCard(deck, value).then((existing) => {
99
+ if (existing) return setError(`"${existing.front}" is already in ${deck}.`);
100
+ setDraft({ front: value, back: [] });
101
+ setStep("back");
102
+ }, (err) => setError(err.message));
103
+ }
104
+ if (step === "back") {
105
+ const answers = splitAnswers(value);
106
+ if (!answers.length) return setError("A card needs an answer.");
107
+ if (answers.some((a) => a.startsWith("/"))) return setError(SLASH_ANSWER);
108
+ setDraft((d) => ({ ...d, back: answers }));
109
+ return setStep("example");
110
+ }
111
+ if (step === "example") save(value);
112
+ }
113
+
114
+ function pickDeck(index) {
115
+ if (index === decks.length) return setStep("deck");
116
+ setDeck(decks[index].name);
117
+ setBothWays(decks[index].bothWays);
118
+ setStep("front");
119
+ }
120
+
121
+ const title = step === "pick" ? "Add cards to…" : step === "deck" || step === "ways" ? (decks.length ? "New deck" : "Start your first deck") : `Add a card · ${deck}`;
122
+ const field = FIELDS[step];
123
+ return html`
124
+ <${Fragment}>
125
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
126
+ <${Text} bold color=${theme.accent}>${title}<//>
127
+ ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
128
+ ${draft.front && step !== "front" && html`<${Box} marginTop=${1}><${Text} dimColor>${draft.front}${draft.back.length ? ` → ${draft.back.join(", ")}` : ""}<//><//>`}
129
+ ${field &&
130
+ html`
131
+ <${Box} flexDirection="column" marginTop=${1}>
132
+ <${Text} bold>${field.label}<//>
133
+ <${Text} dimColor>${field.hint}<//>
134
+ <${Box} marginTop=${1}><${AnswerInput} key=${step} plain onSubmit=${submit} onExit=${finish} onEdit=${() => setError("")} /><//>
135
+ <//>
136
+ `}
137
+ ${step === "pick" &&
138
+ html`
139
+ <${Box} marginTop=${1}>
140
+ <${Choice}
141
+ options=${[...decks.map((d) => ({ label: d.name, note: `${d.cards} card${d.cards === 1 ? "" : "s"}` })), { label: NEW_DECK }]}
142
+ selected=${picked}
143
+ onMove=${setPicked}
144
+ onPick=${pickDeck}
145
+ onCancel=${finish}
146
+ />
147
+ <//>
148
+ `}
149
+ ${step === "ways" &&
150
+ html`
151
+ <${Box} flexDirection="column" marginTop=${1}>
152
+ <${Text} bold>How should "${deck}" be asked?<//>
153
+ <${Box} marginTop=${1}>
154
+ <${Choice}
155
+ options=${[
156
+ { label: "Both ways", note: "for words: kot → cat, and cat → kot", key: "y" },
157
+ { label: "One way only", note: "for questions: front → back", key: "n" }
158
+ ]}
159
+ selected=${ways}
160
+ onMove=${setWays}
161
+ onPick=${(i) => startDeck(i === 0)}
162
+ onCancel=${finish}
163
+ />
164
+ <//>
165
+ <//>
166
+ `}
167
+ ${error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`}
168
+ <//>
169
+ <${Box} paddingX=${1}><${KeyHints} text=${step === "pick" || step === "ways" ? `${CHOICE_KEYS} · esc cancel` : "enter next · esc " + (added || newDeck ? "done" : "cancel")} /><//>
170
+ <//>
171
+ `;
172
+ }