dracosh 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -22
- package/assets/sounds/badge-1.wav +0 -0
- package/assets/sounds/badge-2.wav +0 -0
- package/assets/sounds/badge-3.wav +0 -0
- package/assets/sounds/badge-4.wav +0 -0
- package/locales/de.json +1046 -0
- package/locales/en.json +1029 -0
- package/locales/fr.json +1094 -0
- package/locales/pl.json +1117 -0
- package/locales/uk.json +1118 -0
- package/package.json +2 -2
- package/src/alerts.js +7 -4
- package/src/backup.js +96 -0
- package/src/cardline.js +71 -0
- package/src/cli.js +106 -38
- package/src/commands.js +15 -13
- package/src/demo.js +11 -0
- package/src/diff.js +13 -7
- package/src/i18n.js +68 -0
- package/src/judge.js +51 -12
- package/src/library.js +154 -0
- package/src/lock.js +64 -0
- package/src/manage.js +165 -0
- package/src/pause.js +22 -0
- package/src/progress.js +202 -93
- package/src/quiet.js +4 -3
- package/src/scheduler.js +39 -30
- package/src/session.js +181 -33
- package/src/settings.js +15 -13
- package/src/starter.js +47 -0
- package/src/store.js +58 -17
- package/src/tips.js +17 -25
- package/src/ui/AddCard.js +496 -0
- package/src/ui/AnswerInput.js +28 -13
- package/src/ui/App.js +360 -89
- package/src/ui/BadgeUnlock.js +51 -0
- package/src/ui/Badges.js +79 -20
- package/src/ui/Choice.js +38 -0
- package/src/ui/Companion.js +24 -39
- package/src/ui/Confetti.js +2 -2
- package/src/ui/Decks.js +99 -0
- package/src/ui/DieRoll.js +104 -0
- package/src/ui/Evolution.js +11 -10
- package/src/ui/Hatch.js +9 -7
- package/src/ui/Header.js +62 -19
- package/src/ui/Help.js +74 -0
- package/src/ui/Mascot.js +89 -40
- package/src/ui/Missed.js +15 -13
- package/src/ui/Preview.js +123 -29
- package/src/ui/Reset.js +71 -0
- package/src/ui/Settings.js +34 -23
- package/src/ui/Stats.js +28 -24
- package/src/ui/Summary.js +18 -10
- package/src/ui/TheOne.js +122 -0
- package/src/ui/icons.js +156 -25
- package/src/ui/kit.js +87 -2
- package/src/vacation.js +9 -3
- package/src/words.js +22 -14
- package/assets/sounds/badge.wav +0 -0
- package/data/tips.json +0 -1362
- package/src/ui/Tip.js +0 -25
package/src/session.js
CHANGED
|
@@ -1,72 +1,158 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as say } from "./i18n.js"; // `t` and `text` are taken here (the clock, an answer)
|
|
2
|
+
import { blankGap } from "./cardline.js";
|
|
2
3
|
import { closestCandidate, judge } from "./judge.js";
|
|
3
|
-
import { addVacation, applyAnswer, applyOverrule, calendarMonth, cancelVacations, ensureProgress, missedOn, recordMiss, snapshot, undoMiss, vacationInfo } from "./progress.js";
|
|
4
|
-
import { describeDue, grade, itemKey, pickNext } from "./scheduler.js";
|
|
4
|
+
import { addVacation, applyAnswer, applyCaughtUp, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
|
|
5
|
+
import { describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
|
|
5
6
|
import { recordAnswer, saveState } from "./store.js";
|
|
6
7
|
import { createTipDeck } from "./tips.js";
|
|
7
8
|
import { dayKey } from "./dates.js";
|
|
8
|
-
import {
|
|
9
|
+
import { parsePause } from "./pause.js";
|
|
10
|
+
import { formatRange } from "./vacation.js";
|
|
9
11
|
|
|
10
12
|
const LABELS = { "en-pl": "EN → PL", "pl-en": "PL → EN" };
|
|
13
|
+
|
|
14
|
+
// the tag on the card's border: the language pair for a language deck, the deck's name otherwise
|
|
15
|
+
function labelOf(deck, direction) {
|
|
16
|
+
if (!deck) return LABELS[direction] ?? "";
|
|
17
|
+
if (direction.startsWith("c")) return deck.name; // a cloze gap: no direction to show
|
|
18
|
+
if (!deck.languages) return deck.name;
|
|
19
|
+
const { front, back } = deck.languages;
|
|
20
|
+
const [from, to] = direction === "en-pl" ? [front, back] : [back, front];
|
|
21
|
+
return `${from.toUpperCase()} → ${to.toUpperCase()}`;
|
|
22
|
+
}
|
|
11
23
|
const COMBO_CHEER_EVERY = 5;
|
|
12
24
|
|
|
13
25
|
// Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
|
|
14
|
-
|
|
26
|
+
// `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
|
|
27
|
+
export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
|
|
15
28
|
const rules = () => ({ skipWeekends: getSettings().skipWeekends });
|
|
16
29
|
const totals = { asked: 0, correct: 0, combo: 0 };
|
|
17
30
|
let lastNoteId = null;
|
|
31
|
+
let inTour = false; // the tour teaches one thing per card; tips on top of that are too much
|
|
18
32
|
let lastWrong = null; // the latest wrong answer, until the next question: /correct can still overrule it
|
|
33
|
+
let current = { words: [], deck: null }; // the deck the last question came from
|
|
34
|
+
|
|
35
|
+
// When nothing is waiting in any of your decks before tomorrow, the day is done → { done, cheers }
|
|
36
|
+
async function settleDay() {
|
|
37
|
+
const decks = loadAllWords ? await loadAllWords() : [current].filter((d) => !d.deck?.tour);
|
|
38
|
+
const t = now();
|
|
39
|
+
for (const { words, deck } of decks) {
|
|
40
|
+
const directions = directionsOf(deck);
|
|
41
|
+
if (pickNext({ words, state, now: t, directions })) return { done: false, cheers: [] };
|
|
42
|
+
const due = nextDueAt({ words, state, now: t, directions });
|
|
43
|
+
if (due !== null && due < startOfTomorrow(t)) return { done: false, cheers: [] };
|
|
44
|
+
}
|
|
45
|
+
const { cheers } = applyCaughtUp(state, { goal: getSettings().dailyGoal, rules: rules(), now: t });
|
|
46
|
+
await save(state);
|
|
47
|
+
return { done: true, cheers };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// when the deck's next card is due, if nothing is waiting in it right now (null: something is)
|
|
51
|
+
function upNext() {
|
|
52
|
+
const { words, deck } = current;
|
|
53
|
+
if (deck?.tour || pickNext({ words, state, now: now(), directions: directionsOf(deck) })) return null;
|
|
54
|
+
return nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
|
|
55
|
+
}
|
|
19
56
|
|
|
20
57
|
async function next() {
|
|
21
|
-
const { words,
|
|
22
|
-
|
|
23
|
-
|
|
58
|
+
const { words, deck } = await loadWords();
|
|
59
|
+
current = { words, deck };
|
|
60
|
+
inTour = Boolean(deck?.tour);
|
|
61
|
+
const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsOf(deck), tour: deck?.tour });
|
|
62
|
+
// nothing to ask is a normal state, not an error: the UI shows a way on (a finished tour, a new
|
|
63
|
+
// deck) or when the next card is due. Done with everything for today counts as the daily goal.
|
|
64
|
+
if (!item) {
|
|
65
|
+
const empty = { empty: true, tour: Boolean(deck?.tour), count: words.length, nextDue: null, cheers: [], dayDone: false };
|
|
66
|
+
if (!deck?.tour && words.length) {
|
|
67
|
+
empty.nextDue = nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
|
|
68
|
+
const day = await settleDay();
|
|
69
|
+
empty.cheers = day.cheers;
|
|
70
|
+
empty.dayDone = day.done; // false: this deck is done, but another one still has cards today
|
|
71
|
+
}
|
|
72
|
+
const message = deck?.tour ? say("quiz.empty.tourTitle") : words.length ? say("quiz.empty.laterTitle") : say("quiz.empty.noCardsTitle", { deck: deck?.name });
|
|
73
|
+
throw Object.assign(new Error(message), empty);
|
|
74
|
+
}
|
|
24
75
|
lastNoteId = item.word.noteId;
|
|
25
76
|
lastWrong = null;
|
|
26
77
|
|
|
27
|
-
const
|
|
78
|
+
const forward = item.direction === "en-pl";
|
|
79
|
+
const gap = item.direction.startsWith("c") ? Number(item.direction.slice(1)) - 1 : null;
|
|
80
|
+
const [prompt, expected] =
|
|
81
|
+
gap !== null
|
|
82
|
+
? [blankGap(item.word.word, gap), [item.word.cloze[gap]]]
|
|
83
|
+
: forward
|
|
84
|
+
? [item.word.word, item.word.translations]
|
|
85
|
+
: [item.word.translations.join(" / "), [item.word.word]];
|
|
28
86
|
return {
|
|
29
87
|
word: item.word,
|
|
30
88
|
direction: item.direction,
|
|
31
|
-
label:
|
|
32
|
-
prompt
|
|
33
|
-
expected
|
|
89
|
+
label: labelOf(deck, item.direction),
|
|
90
|
+
prompt,
|
|
91
|
+
expected,
|
|
92
|
+
// a cloze card's back is a hint under the sentence ("Cieszę się na to")
|
|
93
|
+
context: gap !== null ? item.word.translations.join(" / ") : "",
|
|
34
94
|
wordCount: words.length,
|
|
35
|
-
|
|
95
|
+
tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
|
|
36
96
|
};
|
|
37
97
|
}
|
|
38
98
|
|
|
99
|
+
// Each deck decides which way it's asked (picked after its first card): front to back ("2 + 2" → "4"),
|
|
100
|
+
// back to front (a definition shown, its term typed), or both. The front-to-back direction is keyed
|
|
101
|
+
// "en-pl" internally, whatever the languages; a cloze card's gaps ("c1", "c2"…) come with the card.
|
|
102
|
+
function directionsOf(deck) {
|
|
103
|
+
return deck?.directions === "forward" ? ["en-pl"] : deck?.directions === "backward" ? ["pl-en"] : ["en-pl", "pl-en"];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// A typed answer, checked. (An empty one is a reveal: see reveal and selfGrade.)
|
|
39
107
|
async function answer(question, text, { hinted = false } = {}) {
|
|
40
108
|
const key = itemKey(question.word.noteId, question.direction);
|
|
41
109
|
// answers you once declared right (/correct) count for this card from now on
|
|
42
110
|
const result = judge(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
|
|
111
|
+
return record(question, { result, text, hinted });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// An empty Enter shows the answer and nothing is written yet: you say whether you knew it (selfGrade).
|
|
115
|
+
const reveal = (question) => ({ expected: question.expected, example: question.word.example });
|
|
116
|
+
|
|
117
|
+
// After a reveal. "Knew it" counts exactly like a typed right answer: boxes, goal, streak, combo and
|
|
118
|
+
// badges. Long answers can't be typed word for word, and they must be able to earn everything too.
|
|
119
|
+
async function selfGrade(question, knew, { hinted = false } = {}) {
|
|
120
|
+
return { ...(await record(question, { result: knew ? "exact" : "wrong", text: "", hinted })), self: true };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function record(question, { result, text, hinted }) {
|
|
124
|
+
const key = itemKey(question.word.noteId, question.direction);
|
|
43
125
|
const correct = result !== "wrong";
|
|
44
126
|
const t = now();
|
|
45
127
|
const before = state.items[key];
|
|
46
128
|
const comboBefore = totals.combo;
|
|
47
129
|
const entry = grade(before, correct, t, { hinted });
|
|
48
|
-
recordAnswer(state, question.word.noteId, question.direction, entry, t);
|
|
130
|
+
recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
|
|
49
131
|
|
|
50
132
|
totals.asked += 1;
|
|
51
133
|
totals.correct += correct ? 1 : 0;
|
|
52
134
|
totals.combo = correct ? totals.combo + 1 : 0;
|
|
53
135
|
lastWrong = correct ? null : { question, text, key, before, comboBefore, hinted, at: t };
|
|
54
|
-
|
|
136
|
+
// a blank answer on a tour card just shows it: the tour isn't something to have "missed"
|
|
137
|
+
const prompt = question.context ? `${question.prompt} (${question.context})` : question.prompt; // a cloze gap keeps its hint
|
|
138
|
+
if (!correct && !(question.tour && !text.trim())) recordMiss(state, { key, label: question.label, prompt, expected: question.expected, answer: text, at: t }, t);
|
|
55
139
|
|
|
56
140
|
const reward = applyAnswer(state, { result, goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: t });
|
|
57
141
|
const cheers = [...reward.cheers];
|
|
58
|
-
if (correct && totals.combo % COMBO_CHEER_EVERY === 0) cheers.push({ kind: "combo", text:
|
|
142
|
+
if (correct && totals.combo % COMBO_CHEER_EVERY === 0) cheers.push({ kind: "combo", text: say("cheers.combo", { count: totals.combo }) });
|
|
59
143
|
|
|
60
144
|
await save(state);
|
|
145
|
+
// the last card of the day settles it right away, so quitting now doesn't lose the goal
|
|
146
|
+
if (!question.tour) cheers.push(...(await settleDay()).cheers);
|
|
61
147
|
// given/closest feed the per-letter diff the UI shows after a miss or a forgiven typo
|
|
62
|
-
const closest = result === "exact" ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
|
|
63
|
-
return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest };
|
|
148
|
+
const closest = result === "exact" || !text ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
|
|
149
|
+
return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest, nextDue: upNext() };
|
|
64
150
|
}
|
|
65
151
|
|
|
66
152
|
// Re-grade the last wrong answer as correct and remember the answer for this card.
|
|
67
153
|
async function overrule() {
|
|
68
|
-
if (!lastWrong) throw new Error("
|
|
69
|
-
const { text, key, before, comboBefore, hinted, at } = lastWrong;
|
|
154
|
+
if (!lastWrong) throw new Error(say("errors.nothingToCorrect"));
|
|
155
|
+
const { question, text, key, before, comboBefore, hinted, at } = lastWrong;
|
|
70
156
|
lastWrong = null;
|
|
71
157
|
|
|
72
158
|
const entry = grade(before, true, at, { hinted });
|
|
@@ -80,34 +166,40 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
|
|
|
80
166
|
const { cheers } = applyOverrule(state, { goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: at });
|
|
81
167
|
|
|
82
168
|
await save(state);
|
|
83
|
-
|
|
169
|
+
if (!question.tour) cheers.push(...(await settleDay()).cheers);
|
|
170
|
+
return { result: "exact", overruled: true, accepted: text, dueIn: describeDue(entry, now()), combo: totals.combo, cheers, nextDue: upNext() };
|
|
84
171
|
}
|
|
85
172
|
|
|
86
|
-
const canOverrule = () => lastWrong !== null;
|
|
173
|
+
const canOverrule = () => lastWrong !== null && lastWrong.text.trim() !== ""; // nothing typed, nothing to accept
|
|
174
|
+
const wrongAnswer = () => lastWrong?.text ?? "";
|
|
87
175
|
|
|
88
176
|
const stats = () => snapshot(state, { goal: getSettings().dailyGoal, rules: rules(), now: now() });
|
|
89
177
|
|
|
90
178
|
const month = (offset) => calendarMonth(state, { offset, rules: rules(), now: now() });
|
|
91
179
|
const missed = (offset) => missedOn(state, { offset, now: now() });
|
|
92
180
|
|
|
93
|
-
// /
|
|
94
|
-
|
|
181
|
+
// /pause: a break today (the UI holds it, this returns its length) or days off that keep the
|
|
182
|
+
// streak (saved here). → { snooze?: ms | "off", list?: true, message? }
|
|
183
|
+
async function pause(args) {
|
|
95
184
|
const today = dayKey(now());
|
|
96
|
-
const parsed =
|
|
97
|
-
if (!parsed) throw new Error("
|
|
98
|
-
|
|
99
|
-
if (parsed.action === "
|
|
100
|
-
|
|
185
|
+
const parsed = parsePause(args, today);
|
|
186
|
+
if (!parsed) throw new Error(say("pause.help"));
|
|
187
|
+
if (parsed.action === "snooze") return { snooze: parsed.ms };
|
|
188
|
+
if (parsed.action === "days") {
|
|
189
|
+
// days off start today at the earliest: missed days can't be turned into days off afterwards
|
|
190
|
+
const from = parsed.from < today ? today : parsed.from;
|
|
191
|
+
if (parsed.to < today) throw new Error(say("pause.past"));
|
|
192
|
+
addVacation(state, from, parsed.to, now());
|
|
101
193
|
await save(state);
|
|
102
|
-
return
|
|
194
|
+
return { message: from === parsed.to ? say("pause.dayOff", { day: formatRange(from, from) }) : say("pause.daysOff", { range: formatRange(from, parsed.to) }) };
|
|
103
195
|
}
|
|
104
196
|
if (parsed.action === "off") {
|
|
105
197
|
cancelVacations(state, now());
|
|
106
198
|
await save(state);
|
|
107
|
-
return "
|
|
199
|
+
return { snooze: "off", message: say("pause.off") };
|
|
108
200
|
}
|
|
109
201
|
const { upcoming } = vacationInfo(ensureProgress(state, now()), today);
|
|
110
|
-
return upcoming.length ?
|
|
202
|
+
return { list: true, message: upcoming.length ? say("pause.list", { ranges: upcoming.map((v) => formatRange(v.from, v.to)).join(", ") }) : say("pause.none", { help: say("pause.help") }) };
|
|
111
203
|
}
|
|
112
204
|
|
|
113
205
|
// a tip for the wait between questions; remembering which ones were shown is best-effort
|
|
@@ -117,6 +209,52 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
|
|
|
117
209
|
return tip;
|
|
118
210
|
}
|
|
119
211
|
|
|
212
|
+
// progress of cards that are gone (a removed deck) is dropped with them
|
|
213
|
+
async function forget(cardIds) {
|
|
214
|
+
const ids = new Set(cardIds);
|
|
215
|
+
const gone = (key) => ids.has(key.slice(0, key.lastIndexOf(":")));
|
|
216
|
+
for (const key of Object.keys(state.items)) if (gone(key)) delete state.items[key];
|
|
217
|
+
for (const key of Object.keys(state.accepted ?? {})) if (gone(key)) delete state.accepted[key];
|
|
218
|
+
if (state.dormant) state.dormant = state.dormant.filter((key) => !gone(key));
|
|
219
|
+
await save(state);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// A deck is asked another way now (/decks): the directions it no longer asks rest. Their progress stays
|
|
223
|
+
// for when they're back, but doesn't count against mastering the card.
|
|
224
|
+
async function setDirections(cardIds, directions) {
|
|
225
|
+
const asked = new Set(directions === "forward" ? ["en-pl"] : directions === "backward" ? ["pl-en"] : ["en-pl", "pl-en"]);
|
|
226
|
+
const dormant = new Set(state.dormant ?? []);
|
|
227
|
+
for (const id of cardIds) for (const direction of ["en-pl", "pl-en"]) (asked.has(direction) ? dormant.delete : dormant.add).call(dormant, itemKey(id, direction));
|
|
228
|
+
state.dormant = [...dormant];
|
|
229
|
+
await save(state);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// progress of cards that changed shape (a cloze card fixed into a plain one, a gap removed) is dropped
|
|
233
|
+
async function forgetKeys(keys) {
|
|
234
|
+
for (const key of keys) {
|
|
235
|
+
delete state.items[key];
|
|
236
|
+
delete state.accepted?.[key];
|
|
237
|
+
}
|
|
238
|
+
if (state.dormant) state.dormant = state.dormant.filter((key) => !keys.includes(key));
|
|
239
|
+
await save(state);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Reset from /settings (the caller makes a backup first). "progress" starts the game over: badges,
|
|
243
|
+
// streak, stats and the dragon's form and element; your cards and their boxes stay. "everything"
|
|
244
|
+
// empties the state as on a fresh install, so the egg hatches again.
|
|
245
|
+
async function reset(scope) {
|
|
246
|
+
if (scope === "everything") {
|
|
247
|
+
for (const key of Object.keys(state)) delete state[key];
|
|
248
|
+
Object.assign(state, { version: 1, items: {}, newToday: { date: "", count: 0 } });
|
|
249
|
+
} else {
|
|
250
|
+
delete state.progress;
|
|
251
|
+
delete state.tips;
|
|
252
|
+
}
|
|
253
|
+
totals.combo = 0;
|
|
254
|
+
lastWrong = null;
|
|
255
|
+
await save(state);
|
|
256
|
+
}
|
|
257
|
+
|
|
120
258
|
// the hatching intro plays once ever: on a brand-new state that has never answered anything
|
|
121
259
|
const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
|
|
122
260
|
|
|
@@ -125,5 +263,15 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
|
|
|
125
263
|
await save(state);
|
|
126
264
|
}
|
|
127
265
|
|
|
128
|
-
|
|
266
|
+
// /badges: the ones won since it was last opened, which light up one by one; opening it marks them seen
|
|
267
|
+
async function openBadges() {
|
|
268
|
+
const fresh = unseenBadges(state, now());
|
|
269
|
+
if (fresh.length) {
|
|
270
|
+
markBadgesSeen(state, now());
|
|
271
|
+
await save(state);
|
|
272
|
+
}
|
|
273
|
+
return fresh;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return { totals, next, answer, reveal, selfGrade, setDirections, forgetKeys, overrule, canOverrule, wrongAnswer, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
|
|
129
277
|
}
|
package/src/settings.js
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
|
|
1
|
+
import { LANGUAGES, systemLanguage, t } from "./i18n.js";
|
|
2
|
+
|
|
3
|
+
export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null };
|
|
2
4
|
|
|
3
5
|
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
6
|
export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
|
|
5
7
|
export const VOLUMES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1];
|
|
6
8
|
export const TIP_MODES = ["always", "sometimes", "off"];
|
|
7
|
-
|
|
9
|
+
// how cards come: one every few minutes (everyMs), or a session where Enter asks the next one right
|
|
10
|
+
// away, endless or for a set number of cards, after which the minutes take over again
|
|
11
|
+
export const RHYTHMS = ["minutes", "session", "session-10", "session-20"];
|
|
12
|
+
export const sessionLength = (rhythm) => (rhythm.startsWith("session-") ? Number(rhythm.slice("session-".length)) : null);
|
|
8
13
|
// presets for /settings; any { from, to } in settings.json works too
|
|
9
14
|
export const QUIET_PRESETS = [null, { from: 21, to: 7 }, { from: 22, to: 8 }, { from: 23, to: 7 }, { from: 0, to: 8 }];
|
|
10
|
-
export const DIRECTION_OPTIONS = ["both", "en-pl", "pl-en"];
|
|
11
|
-
|
|
12
|
-
export const DIRECTION_LABELS = { both: "EN ⇄ PL", "en-pl": "EN → PL only", "pl-en": "PL → EN only" };
|
|
13
15
|
|
|
14
16
|
export function formatInterval(ms) {
|
|
15
|
-
if (ms < 60_000) return
|
|
16
|
-
if (ms < 3_600_000) return
|
|
17
|
-
return
|
|
17
|
+
if (ms < 60_000) return t("time.seconds", { n: Math.round(ms / 1000) });
|
|
18
|
+
if (ms < 3_600_000) return t("time.minutes", { n: Math.round(ms / 60_000) });
|
|
19
|
+
return t("time.hours", { n: Math.round(ms / 3_600_000) });
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
// older versions saved tips as a boolean
|
|
@@ -26,18 +28,18 @@ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
|
|
|
26
28
|
|
|
27
29
|
// settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
|
|
28
30
|
export function normalizeSettings(raw = {}) {
|
|
31
|
+
raw = raw && typeof raw === "object" ? raw : {};
|
|
29
32
|
return {
|
|
30
33
|
everyMs: isNumber(raw.everyMs) && raw.everyMs >= 1000 ? raw.everyMs : DEFAULTS.everyMs,
|
|
34
|
+
rhythm: RHYTHMS.includes(raw.rhythm) ? raw.rhythm : DEFAULTS.rhythm,
|
|
31
35
|
sound: typeof raw.sound === "boolean" ? raw.sound : DEFAULTS.sound,
|
|
32
36
|
volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
|
|
33
37
|
dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
|
|
34
|
-
directions: DIRECTION_OPTIONS.includes(raw.directions) ? raw.directions : DEFAULTS.directions,
|
|
35
38
|
tips: normalizeTips(raw.tips),
|
|
36
39
|
skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
|
|
37
|
-
quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null
|
|
40
|
+
quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
|
|
41
|
+
deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null, // picked in /decks; null = your first deck
|
|
42
|
+
language: typeof raw.language === "string" && Object.hasOwn(LANGUAGES, raw.language) ? raw.language : systemLanguage() // until picked in /settings, the system's
|
|
38
43
|
};
|
|
39
44
|
}
|
|
40
45
|
|
|
41
|
-
export function directionsFor(setting) {
|
|
42
|
-
return setting === "en-pl" ? ["en-pl"] : setting === "pl-en" ? ["pl-en"] : ["en-pl", "pl-en"];
|
|
43
|
-
}
|
package/src/starter.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { entry, language, t } from "./i18n.js";
|
|
2
|
+
import { addCard, cardsOf, createDeck, findDeck } from "./library.js";
|
|
3
|
+
|
|
4
|
+
// The deck a fresh install starts with: a short tour that teaches Dracosh by doing. Its cards live in
|
|
5
|
+
// the locale (tour.cards): every card says exactly what to type, and the line shown after the answer
|
|
6
|
+
// explains the next thing. It's a `tour` deck: every card is asked once, in this order, and never
|
|
7
|
+
// comes back as a review. `Backticks` mark what to type (or a command); the quiz shows them
|
|
8
|
+
// highlighted, in the tour only. Answers never start with "/", because "/" opens the commands.
|
|
9
|
+
export const STARTER_DECK = "Getting started"; // the tour's English name, which the first versions were found by
|
|
10
|
+
// bump it when the cards change: an older copy of the tour in someone's library gets replaced
|
|
11
|
+
const STARTER_VERSION = 8;
|
|
12
|
+
|
|
13
|
+
// the tour as an earlier version created it (the first one had no version number yet)
|
|
14
|
+
const isStarter = (deck) => deck.starter !== undefined || (deck.name === STARTER_DECK && deck.type === "qa" && !deck.languages);
|
|
15
|
+
|
|
16
|
+
const tourCards = () => entry("tour.cards");
|
|
17
|
+
|
|
18
|
+
// The app's language changed: the tour's cards say the same in the new one. They keep their ids, so
|
|
19
|
+
// the cards already done stay done. The deck takes the new name unless one of yours has it.
|
|
20
|
+
function translateTour(library, deck, lang) {
|
|
21
|
+
const cards = tourCards();
|
|
22
|
+
cardsOf(library, deck.id).forEach((card, i) => Object.assign(card, { front: cards[i].front, back: [...cards[i].back], example: cards[i].example }));
|
|
23
|
+
const name = t("tour.deck");
|
|
24
|
+
if ((findDeck(library, name) ?? deck) === deck) deck.name = name;
|
|
25
|
+
deck.tourLanguage = lang;
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Adds the tour to an empty library, brings an older copy of it up to date (its progress is dropped
|
|
30
|
+
// with the old cards), or translates it into the app's language. Returns true when the library
|
|
31
|
+
// changed and needs saving.
|
|
32
|
+
export function seedLibrary(library, now = Date.now()) {
|
|
33
|
+
let deck = library.decks.find(isStarter);
|
|
34
|
+
if (library.decks.length && !deck) return false;
|
|
35
|
+
const lang = language();
|
|
36
|
+
const current = deck && (deck.starter ?? 1) >= STARTER_VERSION && cardsOf(library, deck.id).length === tourCards().length;
|
|
37
|
+
if (current) return (deck.tourLanguage ?? "en") === lang ? false : translateTour(library, deck, lang);
|
|
38
|
+
|
|
39
|
+
if (deck) {
|
|
40
|
+
library.cards = library.cards.filter((card) => card.deckId !== deck.id);
|
|
41
|
+
const name = t("tour.deck");
|
|
42
|
+
if ((findDeck(library, name) ?? deck) === deck) deck.name = name;
|
|
43
|
+
} else deck = createDeck(library, { name: t("tour.deck"), type: "qa", languages: null, directions: "forward", tour: true, now });
|
|
44
|
+
Object.assign(deck, { tour: true, starter: STARTER_VERSION, tourLanguage: lang });
|
|
45
|
+
for (const card of tourCards()) addCard(library, deck.id, { ...card, now });
|
|
46
|
+
return true;
|
|
47
|
+
}
|
package/src/store.js
CHANGED
|
@@ -1,22 +1,34 @@
|
|
|
1
|
+
import { t } from "./i18n.js";
|
|
1
2
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
4
5
|
import { dayKey } from "./dates.js";
|
|
6
|
+
import { upgradeLibrary } from "./library.js";
|
|
5
7
|
import { itemKey, newToday } from "./scheduler.js";
|
|
6
8
|
|
|
7
9
|
export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
|
|
10
|
+
const LIBRARY_FILE = join(HOME, "library.json");
|
|
8
11
|
const STATE_FILE = join(HOME, "state.json");
|
|
9
|
-
const WORDS_FILE = join(HOME, "words.json");
|
|
10
12
|
const SETTINGS_FILE = join(HOME, "settings.json");
|
|
13
|
+
// everything a backup holds, by name
|
|
14
|
+
export const DATA_FILES = { library: LIBRARY_FILE, state: STATE_FILE, settings: SETTINGS_FILE };
|
|
11
15
|
|
|
12
|
-
const
|
|
16
|
+
export const STATE_VERSION = 1;
|
|
17
|
+
const emptyState = () => ({ version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
|
|
13
18
|
|
|
14
|
-
|
|
19
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20
|
+
|
|
21
|
+
// what to say when a data file can't be used as it is
|
|
22
|
+
// marked, not only worded: the message is in the app's language
|
|
23
|
+
export const damaged = (file, why) => Object.assign(new Error(t("errors.damaged", { file, why })), { damaged: true });
|
|
24
|
+
|
|
25
|
+
export async function readJson(file, fallback) {
|
|
15
26
|
try {
|
|
16
27
|
return JSON.parse(await readFile(file, "utf8"));
|
|
17
28
|
} catch (err) {
|
|
18
29
|
if (err.code === "ENOENT") return fallback;
|
|
19
|
-
|
|
30
|
+
if (err instanceof SyntaxError) throw damaged(file, err.message);
|
|
31
|
+
throw new Error(t("errors.cantRead", { file, error: err.message }));
|
|
20
32
|
}
|
|
21
33
|
}
|
|
22
34
|
|
|
@@ -24,11 +36,11 @@ async function readJson(file, fallback) {
|
|
|
24
36
|
// and two saves in quick succession (an answer and a shown tip, say) can't trip over each other's temp file.
|
|
25
37
|
let writes = Promise.resolve();
|
|
26
38
|
|
|
27
|
-
function writeJson(file, data) {
|
|
39
|
+
export function writeJson(file, data) {
|
|
28
40
|
const json = JSON.stringify(data, null, 2); // snapshot now: the state object keeps changing
|
|
29
41
|
const job = writes.then(async () => {
|
|
30
|
-
await mkdir(
|
|
31
|
-
const tmp = `${file}.tmp`;
|
|
42
|
+
await mkdir(dirname(file), { recursive: true });
|
|
43
|
+
const tmp = `${file}.${process.pid}.tmp`; // another Dracosh process never shares it
|
|
32
44
|
await writeFile(tmp, json);
|
|
33
45
|
await rename(tmp, file);
|
|
34
46
|
});
|
|
@@ -36,26 +48,55 @@ function writeJson(file, data) {
|
|
|
36
48
|
return job;
|
|
37
49
|
}
|
|
38
50
|
|
|
39
|
-
export
|
|
40
|
-
|
|
51
|
+
export async function loadLibrary() {
|
|
52
|
+
try {
|
|
53
|
+
return upgradeLibrary(await readJson(LIBRARY_FILE, undefined));
|
|
54
|
+
} catch (err) {
|
|
55
|
+
throw err.damaged ? damaged(LIBRARY_FILE, err.message) : err;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
|
|
41
59
|
|
|
42
|
-
//
|
|
43
|
-
export
|
|
44
|
-
|
|
60
|
+
// Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten
|
|
61
|
+
export async function loadState() {
|
|
62
|
+
const state = await readJson(STATE_FILE, undefined);
|
|
63
|
+
if (state === undefined) return emptyState();
|
|
64
|
+
if (!isObject(state) || !isObject(state.items)) throw damaged(STATE_FILE, t("errors.why.noProgress"));
|
|
65
|
+
if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(STATE_FILE, t("errors.why.progressEntry"));
|
|
66
|
+
const { progress } = state;
|
|
67
|
+
const validProgress =
|
|
68
|
+
isObject(progress) &&
|
|
69
|
+
isObject(progress.days) &&
|
|
70
|
+
Object.values(progress.days).every(isObject) &&
|
|
71
|
+
isObject(progress.streak) &&
|
|
72
|
+
["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
|
|
73
|
+
isObject(progress.badges) &&
|
|
74
|
+
(progress.vacations === undefined || Array.isArray(progress.vacations));
|
|
75
|
+
if (progress !== undefined && !validProgress) throw damaged(STATE_FILE, t("errors.why.streak"));
|
|
76
|
+
if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file: STATE_FILE }));
|
|
77
|
+
if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
|
|
78
|
+
return state;
|
|
79
|
+
}
|
|
80
|
+
export const saveState = (state) => writeJson(STATE_FILE, state);
|
|
45
81
|
|
|
46
|
-
|
|
82
|
+
// `countNew: false` keeps a card out of the daily cap on new cards (the tour's don't use it up)
|
|
83
|
+
export function recordAnswer(state, noteId, direction, entry, now = Date.now(), { countNew = true } = {}) {
|
|
47
84
|
const key = itemKey(noteId, direction);
|
|
48
|
-
const isNew = !state.items[key];
|
|
85
|
+
const isNew = countNew && !state.items[key];
|
|
49
86
|
const date = dayKey(now);
|
|
50
87
|
state.items[key] = entry;
|
|
51
88
|
if (isNew) state.newToday = { date, count: newToday(state, now) + 1 };
|
|
52
89
|
return state;
|
|
53
90
|
}
|
|
54
91
|
|
|
55
|
-
|
|
92
|
+
// hand-edited into something odd, even broken JSON: the defaults take over (nothing worth a restore)
|
|
93
|
+
export const loadSettingsRaw = async () => {
|
|
94
|
+
const raw = await readJson(SETTINGS_FILE, {}).catch((err) => (err.damaged ? {} : Promise.reject(err)));
|
|
95
|
+
return isObject(raw) ? raw : {};
|
|
96
|
+
};
|
|
56
97
|
|
|
57
98
|
// merges into what's on disk, so a one-off CLI flag never gets persisted by accident
|
|
58
99
|
export async function patchSettings(patch) {
|
|
59
|
-
const current = await
|
|
100
|
+
const current = await loadSettingsRaw();
|
|
60
101
|
await writeJson(SETTINGS_FILE, { ...current, ...patch });
|
|
61
102
|
}
|
package/src/tips.js
CHANGED
|
@@ -1,38 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { HOME } from "./store.js";
|
|
1
|
+
import { englishMessages, t } from "./i18n.js";
|
|
4
2
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
15
|
-
} catch {
|
|
16
|
-
return [];
|
|
3
|
+
// Short tips about Dracosh itself, shown now and then while you wait for the next card. They live in
|
|
4
|
+
// the locale (tips.<id>); the ids come from English, the text from the language in use.
|
|
5
|
+
export const TIPS = Object.keys(englishMessages().tips).map((id) => ({
|
|
6
|
+
id,
|
|
7
|
+
get cat() {
|
|
8
|
+
return t(`tips.${id}.cat`);
|
|
9
|
+
},
|
|
10
|
+
get text() {
|
|
11
|
+
return t(`tips.${id}.text`);
|
|
17
12
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
.filter((tip) => tip && typeof tip.text === "string" && tip.text.trim())
|
|
21
|
-
.map((tip, i) => ({ id: `u-${tip.id ?? i + 1}`, cat: typeof tip.cat === "string" && tip.cat ? tip.cat : "My tips", text: tip.text.trim() }));
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export const allTips = () => [...BUNDLED, ...loadUserTips()];
|
|
13
|
+
}));
|
|
14
|
+
const SOMETIMES_CHANCE = 1 / 3;
|
|
25
15
|
|
|
26
16
|
// "always" shows a tip on every wait, "sometimes" on about one in three
|
|
27
17
|
export function shouldShowTip(mode, random = Math.random) {
|
|
28
18
|
return mode === "always" || (mode === "sometimes" && random() < SOMETIMES_CHANCE);
|
|
29
19
|
}
|
|
30
20
|
|
|
31
|
-
// Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen
|
|
32
|
-
|
|
21
|
+
// Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen
|
|
22
|
+
// (ids of tips that no longer exist are dropped from it).
|
|
23
|
+
export function createTipDeck({ state, tips = TIPS, random = Math.random }) {
|
|
24
|
+
const known = new Set(tips.map((tip) => tip.id));
|
|
33
25
|
return {
|
|
34
26
|
next() {
|
|
35
|
-
const seen = new Set(state.tips?.seen ?? []);
|
|
27
|
+
const seen = new Set((state.tips?.seen ?? []).filter((id) => known.has(id)));
|
|
36
28
|
let fresh = tips.filter((tip) => !seen.has(tip.id));
|
|
37
29
|
if (!fresh.length) {
|
|
38
30
|
seen.clear();
|