dracosh 0.0.0-stage → 0.1.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 (54) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +10 -0
  3. package/README.md +78 -2
  4. package/assets/sounds/ask.wav +0 -0
  5. package/assets/sounds/badge.wav +0 -0
  6. package/assets/sounds/close.wav +0 -0
  7. package/assets/sounds/combo.wav +0 -0
  8. package/assets/sounds/correct-0.wav +0 -0
  9. package/assets/sounds/correct-1.wav +0 -0
  10. package/assets/sounds/correct-2.wav +0 -0
  11. package/assets/sounds/correct-3.wav +0 -0
  12. package/assets/sounds/correct-4.wav +0 -0
  13. package/assets/sounds/correct-5.wav +0 -0
  14. package/assets/sounds/evolve.wav +0 -0
  15. package/assets/sounds/goal.wav +0 -0
  16. package/assets/sounds/wrong.wav +0 -0
  17. package/data/tips.json +1362 -0
  18. package/package.json +47 -4
  19. package/src/alerts.js +37 -0
  20. package/src/anki.js +36 -0
  21. package/src/cli.js +116 -0
  22. package/src/commands.js +28 -0
  23. package/src/dates.js +15 -0
  24. package/src/demo.js +11 -0
  25. package/src/diff.js +46 -0
  26. package/src/hint.js +12 -0
  27. package/src/judge.js +57 -0
  28. package/src/parse.js +42 -0
  29. package/src/progress.js +363 -0
  30. package/src/quiet.js +32 -0
  31. package/src/scheduler.js +82 -0
  32. package/src/session.js +129 -0
  33. package/src/settings.js +43 -0
  34. package/src/store.js +61 -0
  35. package/src/tips.js +47 -0
  36. package/src/ui/AnswerInput.js +82 -0
  37. package/src/ui/App.js +369 -0
  38. package/src/ui/Badges.js +64 -0
  39. package/src/ui/Companion.js +60 -0
  40. package/src/ui/Confetti.js +46 -0
  41. package/src/ui/Evolution.js +58 -0
  42. package/src/ui/Hatch.js +99 -0
  43. package/src/ui/Header.js +116 -0
  44. package/src/ui/Mascot.js +128 -0
  45. package/src/ui/Missed.js +52 -0
  46. package/src/ui/Preview.js +181 -0
  47. package/src/ui/Settings.js +65 -0
  48. package/src/ui/Stats.js +108 -0
  49. package/src/ui/Summary.js +34 -0
  50. package/src/ui/Tip.js +25 -0
  51. package/src/ui/icons.js +209 -0
  52. package/src/ui/kit.js +63 -0
  53. package/src/vacation.js +51 -0
  54. package/src/words.js +16 -0
@@ -0,0 +1,363 @@
1
+ import { addDays, dayKey, daysBetween, weekStart } from "./dates.js";
2
+ import { BOX_INTERVALS_DAYS } from "./scheduler.js";
3
+
4
+ export const MAX_FREEZES = 2;
5
+ const MAX_BOX = BOX_INTERVALS_DAYS.length;
6
+ const AT_RISK_HOUR = 19;
7
+ const COMEBACK_AFTER_DAYS = 7;
8
+ const MISSED_KEEP_DAYS = 14;
9
+
10
+ // The companion evolves permanently with your best streak, so a broken streak never takes a form away.
11
+ export const STAGES = [
12
+ { name: "Hatchling", from: 0 },
13
+ { name: "Imp", from: 7 },
14
+ { name: "Whelp", from: 30 },
15
+ { name: "Drake", from: 90 },
16
+ { name: "Dragon", from: 180 },
17
+ { name: "Legend", from: 365 }
18
+ ];
19
+
20
+ export function stageFor(bestStreak) {
21
+ let index = 0;
22
+ while (index + 1 < STAGES.length && bestStreak >= STAGES[index + 1].from) index += 1;
23
+ const next = STAGES[index + 1] ?? null;
24
+ return { index, name: STAGES[index].name, nextName: next?.name ?? null, nextAt: next?.from ?? null };
25
+ }
26
+
27
+ export function ensureProgress(state, now = Date.now()) {
28
+ state.progress ??= {
29
+ days: {},
30
+ streak: { count: 0, best: 0, lastGoalDay: null, freezes: 1, freezeWeek: weekStart(dayKey(now)), freezesUsed: 0 },
31
+ badges: {},
32
+ bestCombo: 0,
33
+ lastActiveDay: null,
34
+ vacations: []
35
+ };
36
+ state.progress.vacations ??= [];
37
+ // one free freeze per calendar week, never more than MAX_FREEZES in stock
38
+ const week = weekStart(dayKey(now));
39
+ const { streak } = state.progress;
40
+ if (streak.freezeWeek !== week) {
41
+ streak.freezeWeek = week;
42
+ streak.freezes = Math.min(MAX_FREEZES, streak.freezes + 1);
43
+ }
44
+ return state.progress;
45
+ }
46
+
47
+ // ---- rest days: weekends (a setting) and vacations never break a streak ----------------------------------------
48
+
49
+ const NO_RULES = { skipWeekends: false };
50
+
51
+ export function isRestDay(progress, key, rules = NO_RULES) {
52
+ if (rules.skipWeekends) {
53
+ const weekday = new Date(`${key}T12:00:00`).getDay();
54
+ if (weekday === 0 || weekday === 6) return true;
55
+ }
56
+ return (progress.vacations ?? []).some((v) => key >= v.from && key <= v.to);
57
+ }
58
+
59
+ // working days strictly between two days on which you did nothing: these are the ones that cost a freeze
60
+ function missedDaysBetween(progress, from, to, rules) {
61
+ let missed = 0;
62
+ for (let day = addDays(from, 1); day < to; day = addDays(day, 1)) if (!isRestDay(progress, day, rules)) missed += 1;
63
+ return missed;
64
+ }
65
+
66
+ // the streak as shown right now: alive while no working day was skipped, or while freezes can cover the gap
67
+ export function currentStreak(progress, today, rules = NO_RULES) {
68
+ const { count, lastGoalDay, freezes } = progress.streak;
69
+ if (!lastGoalDay || !count) return 0;
70
+ return missedDaysBetween(progress, lastGoalDay, today, rules) <= freezes ? count : 0;
71
+ }
72
+
73
+ function completeDay(progress, today, rules) {
74
+ const streak = progress.streak;
75
+ if (!streak.lastGoalDay) {
76
+ streak.count = 1;
77
+ } else {
78
+ const missed = missedDaysBetween(progress, streak.lastGoalDay, today, rules);
79
+ if (missed === 0) {
80
+ streak.count += 1;
81
+ } else if (missed <= streak.freezes) {
82
+ streak.freezes -= missed;
83
+ streak.freezesUsed = (streak.freezesUsed ?? 0) + missed;
84
+ streak.count += 1;
85
+ } else {
86
+ streak.count = 1;
87
+ }
88
+ }
89
+ streak.lastGoalDay = today;
90
+ streak.best = Math.max(streak.best, streak.count);
91
+ return streak.count;
92
+ }
93
+
94
+ // ---- vacations ---------------------------------------------------------------------------------------------------
95
+
96
+ export function addVacation(state, from, to, now = Date.now()) {
97
+ const progress = ensureProgress(state, now);
98
+ const merged = [...progress.vacations, { from, to }].sort((a, b) => (a.from < b.from ? -1 : 1));
99
+ progress.vacations = merged.reduce((out, v) => {
100
+ const last = out[out.length - 1];
101
+ if (last && v.from <= addDays(last.to, 1)) last.to = v.to > last.to ? v.to : last.to; // overlapping or touching: one vacation
102
+ else out.push({ ...v });
103
+ return out;
104
+ }, []);
105
+ }
106
+
107
+ // ends the vacation that is running (as of yesterday) and drops the ones still ahead
108
+ export function cancelVacations(state, now = Date.now()) {
109
+ const progress = ensureProgress(state, now);
110
+ const today = dayKey(now);
111
+ progress.vacations = progress.vacations
112
+ .map((v) => (v.to < today ? v : v.from < today ? { from: v.from, to: addDays(today, -1) } : null))
113
+ .filter(Boolean);
114
+ }
115
+
116
+ // the vacation running today (if any) and the ones still ahead
117
+ export function vacationInfo(progress, today) {
118
+ const upcoming = (progress.vacations ?? []).filter((v) => v.to >= today);
119
+ const active = upcoming.find((v) => v.from <= today) ?? null;
120
+ return { activeUntil: active?.to ?? null, upcoming };
121
+ }
122
+
123
+ const goalMetOn = (progress, key) => Boolean(progress.days[key]?.goalMet);
124
+
125
+ function goalDaysInMonth(progress, today) {
126
+ const prefix = today.slice(0, 7);
127
+ return Object.entries(progress.days).filter(([key, day]) => key.startsWith(prefix) && day.goalMet).length;
128
+ }
129
+
130
+ // Every day of the Monday-to-Sunday week containing `today` hit its goal
131
+ function perfectWeek(progress, today) {
132
+ const monday = weekStart(today);
133
+ return Array.from({ length: 7 }, (_, i) => addDays(monday, i)).every((key) => goalMetOn(progress, key));
134
+ }
135
+
136
+ // `s` = stats from collectStats() plus `event`: what this very answer was (correct, hour, days since last activity)
137
+ export const BADGES = [
138
+ { id: "hello", name: "Hello!", desc: "your first correct answer", test: (s) => s.totalCorrect >= 1 },
139
+ { id: "first-steps", name: "First steps", desc: "10 correct answers", test: (s) => s.totalCorrect >= 10 },
140
+ { id: "century", name: "Century", desc: "100 correct answers", test: (s) => s.totalCorrect >= 100 },
141
+ { id: "five-hundred", name: "Five hundred", desc: "500 correct answers", test: (s) => s.totalCorrect >= 500 },
142
+ { id: "thousand", name: "Thousand", desc: "1000 correct answers", test: (s) => s.totalCorrect >= 1000 },
143
+ { id: "two-thousand", name: "Two thousand", desc: "2000 correct answers", test: (s) => s.totalCorrect >= 2000 },
144
+
145
+ { id: "on-a-roll", name: "On a roll", desc: "3-day streak", test: (s) => s.bestStreak >= 3 },
146
+ { id: "week", name: "Full week", desc: "7-day streak", test: (s) => s.bestStreak >= 7 },
147
+ { id: "fortnight", name: "Fortnight", desc: "14-day streak", test: (s) => s.bestStreak >= 14 },
148
+ { id: "month", name: "Iron habit", desc: "30-day streak", test: (s) => s.bestStreak >= 30 },
149
+ { id: "hundred-days", name: "Centurion", desc: "100-day streak", test: (s) => s.bestStreak >= 100 },
150
+
151
+ { id: "keeper", name: "Word keeper", desc: "10 cards mastered", test: (s) => s.mastered >= 10 },
152
+ { id: "collector", name: "Collector", desc: "50 cards mastered", test: (s) => s.mastered >= 50 },
153
+ { id: "dictionary", name: "Walking dictionary", desc: "100 cards mastered", test: (s) => s.mastered >= 100 },
154
+ { id: "explorer", name: "Explorer", desc: "250 cards practiced", test: (s) => s.practiced >= 250 },
155
+
156
+ { id: "flawless", name: "Flawless", desc: "10+ answers in a day, no miss", test: (s) => s.today.asked >= 10 && s.today.correct === s.today.asked },
157
+ { id: "overachiever", name: "Overachiever", desc: "double your daily goal in a day", test: (s) => s.today.correct >= s.goal * 2 },
158
+ { id: "marathon", name: "Marathon", desc: "30 correct answers in a day", test: (s) => s.today.correct >= 30 },
159
+
160
+ { id: "hot-streak", name: "Hot streak", desc: "10 correct in a row", test: (s) => s.bestCombo >= 10 },
161
+ { id: "unstoppable", name: "Unstoppable", desc: "25 correct in a row", test: (s) => s.bestCombo >= 25 },
162
+ { id: "combo-master", name: "Combo master", desc: "50 correct in a row", test: (s) => s.bestCombo >= 50 },
163
+
164
+ { id: "early-bird", name: "Early bird", desc: "a correct answer before 8:00", test: (s) => s.event.correct && s.event.hour < 8 },
165
+ { id: "night-owl", name: "Night owl", desc: "a correct answer after 23:00", test: (s) => s.event.correct && s.event.hour >= 23 },
166
+
167
+ { id: "comeback", name: "Welcome back", desc: "back after 7+ days away", test: (s) => s.event.correct && s.event.daysAway >= COMEBACK_AFTER_DAYS },
168
+ { id: "redemption", name: "Redemption", desc: "5 words missed today, got right later the same day", test: (s) => s.recoveredToday >= 5 },
169
+ { id: "frozen", name: "Frozen in time", desc: "a freeze saved your streak", test: (s) => s.freezesUsed >= 1 },
170
+ { id: "weekend", name: "Weekend warrior", desc: "goal on both Saturday and Sunday", test: (s) => s.weekendDone },
171
+ { id: "perfect-week", name: "Perfect week", desc: "goal every day, Monday to Sunday", test: (s) => s.perfectWeek },
172
+ { id: "regular", name: "Regular", desc: "goal on 20 days in one month", test: (s) => s.goalDaysThisMonth >= 20 },
173
+ { id: "machine", name: "The machine", desc: "goal on 25 days in one month", test: (s) => s.goalDaysThisMonth >= 25 },
174
+ { id: "hundred-club", name: "Hundred club", desc: "goal reached on 100 days in total", test: (s) => s.totalGoalDays >= 100 },
175
+
176
+ { id: "both-ways", name: "Both ways", desc: "50 correct in each direction", test: (s) => s.correctByDirection["en-pl"] >= 50 && s.correctByDirection["pl-en"] >= 50 }
177
+ ];
178
+
179
+ function collectStats(state, now, goal) {
180
+ const progress = state.progress;
181
+ const todayKey = dayKey(now);
182
+ const today = progress.days[todayKey] ?? { asked: 0, correct: 0 };
183
+ const items = Object.entries(state.items);
184
+ const correctByDirection = { "en-pl": 0, "pl-en": 0 };
185
+ for (const [key, entry] of items) correctByDirection[key.split(":")[1]] += entry.correct;
186
+
187
+ // words missed today that were answered correctly again later the same day (one per card)
188
+ const lastMissByKey = new Map();
189
+ for (const miss of progress.days[todayKey]?.missed ?? []) lastMissByKey.set(miss.key, miss);
190
+ let recoveredToday = 0;
191
+ for (const [key, miss] of lastMissByKey) {
192
+ const entry = state.items[key];
193
+ if (entry && entry.streak > 0 && entry.last > miss.at) recoveredToday += 1;
194
+ }
195
+
196
+ const isSunday = new Date(`${todayKey}T12:00:00`).getDay() === 0;
197
+ return {
198
+ goal,
199
+ totalCorrect: Object.values(progress.days).reduce((sum, d) => sum + d.correct, 0),
200
+ bestStreak: progress.streak.best,
201
+ bestCombo: progress.bestCombo ?? 0,
202
+ freezesUsed: progress.streak.freezesUsed ?? 0,
203
+ mastered: items.filter(([, e]) => e.box === MAX_BOX).length,
204
+ practiced: items.length,
205
+ correctByDirection,
206
+ goalDaysThisMonth: goalDaysInMonth(progress, todayKey),
207
+ totalGoalDays: Object.values(progress.days).filter((d) => d.goalMet).length,
208
+ recoveredToday,
209
+ weekendDone: isSunday && goalMetOn(progress, todayKey) && goalMetOn(progress, addDays(todayKey, -1)),
210
+ perfectWeek: goalMetOn(progress, todayKey) && perfectWeek(progress, todayKey),
211
+ today
212
+ };
213
+ }
214
+
215
+ // Goal check, evolution and badges after something was credited today → cheers
216
+ function award(state, progress, day, today, { correct, goal, rules, now, daysAway = 0 }) {
217
+ const cheers = [];
218
+ if (correct && !day.goalMet && day.correct >= goal) {
219
+ day.goalMet = true;
220
+ const stageBefore = stageFor(progress.streak.best);
221
+ const streak = completeDay(progress, today, rules);
222
+ cheers.push({ kind: "goal", text: `Daily goal reached · ${streak}-day streak` });
223
+ const stageAfter = stageFor(progress.streak.best);
224
+ if (stageAfter.index > stageBefore.index)
225
+ cheers.push({ kind: "evolve", text: `Your companion evolved into a${/^[aeiou]/i.test(stageAfter.name) ? "n" : ""} ${stageAfter.name}!` });
226
+ }
227
+
228
+ const stats = { ...collectStats(state, now, goal), event: { correct, hour: new Date(now).getHours(), daysAway } };
229
+ for (const badge of BADGES) {
230
+ if (!progress.badges[badge.id] && badge.test(stats)) {
231
+ progress.badges[badge.id] = today;
232
+ cheers.push({ kind: "badge", text: `Badge unlocked: ${badge.name} · ${badge.desc}` });
233
+ }
234
+ }
235
+ return cheers;
236
+ }
237
+
238
+ const dayOf = (progress, today) => (progress.days[today] ??= { asked: 0, correct: 0 });
239
+
240
+ // Records one answer in the progress log → { cheers[] }. `state.items` must already include this answer.
241
+ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0, now = Date.now() }) {
242
+ const progress = ensureProgress(state, now);
243
+ const today = dayKey(now);
244
+ const day = dayOf(progress, today);
245
+ const correct = result !== "wrong";
246
+ const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) : 0;
247
+
248
+ day.asked += 1;
249
+ day.correct += correct ? 1 : 0;
250
+ progress.bestCombo = Math.max(progress.bestCombo ?? 0, combo);
251
+ progress.lastActiveDay = today;
252
+ return { cheers: award(state, progress, day, today, { correct, goal, rules, now, daysAway }) };
253
+ }
254
+
255
+ // A wrong answer the user then declared right: it was already counted as asked, so only credit the correct one
256
+ export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now = Date.now() }) {
257
+ const progress = ensureProgress(state, now);
258
+ const today = dayKey(now);
259
+ const day = dayOf(progress, today);
260
+
261
+ day.correct += 1;
262
+ progress.bestCombo = Math.max(progress.bestCombo ?? 0, combo);
263
+ return { cheers: award(state, progress, day, today, { correct: true, goal, rules, now }) };
264
+ }
265
+
266
+ // everything the screens display, derived from state
267
+ export function snapshot(state, { goal, rules = NO_RULES, now = Date.now() }) {
268
+ const progress = ensureProgress(state, now);
269
+ const stats = collectStats(state, now, goal);
270
+ const today = dayKey(now);
271
+ const days = currentStreak(progress, today, rules);
272
+ const restToday = isRestDay(progress, today, rules);
273
+ const goalMet = Boolean(stats.today.goalMet) || stats.today.correct >= goal;
274
+ return {
275
+ today: { ...stats.today, goalMet },
276
+ goal,
277
+ streak: {
278
+ days,
279
+ best: progress.streak.best,
280
+ freezes: progress.streak.freezes,
281
+ atRisk: days > 0 && !goalMet && !restToday && new Date(now).getHours() >= AT_RISK_HOUR
282
+ },
283
+ restToday,
284
+ skipWeekends: rules.skipWeekends,
285
+ vacation: vacationInfo(progress, today),
286
+ companion: stageFor(progress.streak.best),
287
+ totalCorrect: stats.totalCorrect,
288
+ mastered: stats.mastered,
289
+ practiced: stats.practiced,
290
+ badges: BADGES.map((b) => ({ id: b.id, name: b.name, desc: b.desc, unlockedOn: progress.badges[b.id] ?? null }))
291
+ };
292
+ }
293
+
294
+ const MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
295
+
296
+ // One calendar month, weeks Monday..Sunday: each day has the number of correct answers and whether the goal was met.
297
+ // `offset` moves back (negative) or forward from the current month.
298
+ export function calendarMonth(state, { offset = 0, rules = NO_RULES, now = Date.now() } = {}) {
299
+ const progress = ensureProgress(state, now);
300
+ const today = dayKey(now);
301
+ const [year, month] = today.split("-").map(Number);
302
+ const first = new Date(year, month - 1 + offset, 1, 12);
303
+ const firstKey = dayKey(first);
304
+ const daysInMonth = new Date(first.getFullYear(), first.getMonth() + 1, 0).getDate();
305
+
306
+ const cells = Array.from({ length: daysInMonth }, (_, i) => {
307
+ const key = addDays(firstKey, i);
308
+ const day = progress.days[key];
309
+ return { key, day: i + 1, correct: day?.correct ?? 0, goalMet: Boolean(day?.goalMet), rest: isRestDay(progress, key, rules), future: daysBetween(today, key) > 0, today: key === today };
310
+ });
311
+
312
+ const lead = (first.getDay() + 6) % 7; // blank cells before the 1st so columns line up Mon..Sun
313
+ const padded = [...Array(lead).fill(null), ...cells];
314
+ const weeks = [];
315
+ for (let i = 0; i < padded.length; i += 7) weeks.push([...padded.slice(i, i + 7), ...Array(Math.max(0, i + 7 - padded.length)).fill(null)]);
316
+
317
+ return {
318
+ label: `${MONTH_NAMES[first.getMonth()]} ${first.getFullYear()}`,
319
+ weeks,
320
+ goalDays: cells.filter((c) => c.goalMet).length,
321
+ correct: cells.reduce((sum, c) => sum + c.correct, 0),
322
+ daysSoFar: cells.filter((c) => !c.future).length
323
+ };
324
+ }
325
+
326
+ // ---- words you got wrong (for /missed) -------------------------------------------------------------------------
327
+
328
+ // miss = { key, label, prompt, expected[], answer, at }; kept per day, and only for the last MISSED_KEEP_DAYS days
329
+ export function recordMiss(state, miss, now = Date.now()) {
330
+ const progress = ensureProgress(state, now);
331
+ const today = dayKey(now);
332
+ (dayOf(progress, today).missed ??= []).push(miss);
333
+ for (const [key, day] of Object.entries(progress.days)) {
334
+ if (day.missed && daysBetween(key, today) > MISSED_KEEP_DAYS) delete day.missed;
335
+ }
336
+ }
337
+
338
+ // the miss no longer counts (the user declared that answer right)
339
+ export function undoMiss(state, key, at) {
340
+ const day = state.progress?.days[dayKey(at)];
341
+ if (!day?.missed) return;
342
+ const index = day.missed.findLastIndex((m) => m.key === key && m.at === at);
343
+ if (index >= 0) day.missed.splice(index, 1);
344
+ }
345
+
346
+ // Misses of one day (offset 0 = today, -1 = yesterday...), one row per card with how often it was missed.
347
+ // `recovered` = answered correctly since.
348
+ export function missedOn(state, { offset = 0, now = Date.now() } = {}) {
349
+ const progress = ensureProgress(state, now);
350
+ const date = addDays(dayKey(now), offset);
351
+ const rows = new Map();
352
+ for (const miss of progress.days[date]?.missed ?? []) {
353
+ const row = rows.get(miss.key);
354
+ rows.set(miss.key, { ...miss, times: (row?.times ?? 0) + 1 });
355
+ }
356
+ const items = [...rows.values()]
357
+ .map((row) => {
358
+ const entry = state.items[row.key];
359
+ return { ...row, recovered: Boolean(entry && entry.streak > 0 && entry.last > row.at) };
360
+ })
361
+ .sort((a, b) => b.at - a.at);
362
+ return { date, items };
363
+ }
package/src/quiet.js ADDED
@@ -0,0 +1,32 @@
1
+ const MINUTE = 60_000;
2
+ const HOUR = 60 * MINUTE;
3
+
4
+ // quiet = { from, to } in whole hours (22 → 8 means 22:00 until 08:00, past midnight), or null for no quiet hours
5
+ export function inQuietHours(ms, quiet) {
6
+ if (!quiet || quiet.from === quiet.to) return false;
7
+ const hour = new Date(ms).getHours();
8
+ return quiet.from < quiet.to ? hour >= quiet.from && hour < quiet.to : hour >= quiet.from || hour < quiet.to;
9
+ }
10
+
11
+ // the next moment quiet hours end after `ms`
12
+ export function quietEnd(ms, quiet) {
13
+ const end = new Date(ms);
14
+ end.setHours(quiet.to, 0, 0, 0);
15
+ if (end.getTime() <= ms) end.setDate(end.getDate() + 1);
16
+ return end.getTime();
17
+ }
18
+
19
+ export const formatQuiet = (quiet) => (quiet ? `${String(quiet.from).padStart(2, "0")}:00–${String(quiet.to).padStart(2, "0")}:00` : "off");
20
+
21
+ // "/snooze" → 1 h, "30", "30m", "2h", "90s" → milliseconds, "off" → "off", anything else → null
22
+ export function parseSnooze(arg) {
23
+ const text = arg.trim().toLowerCase();
24
+ if (!text) return HOUR;
25
+ if (text === "off" || text === "0") return "off";
26
+ const match = /^(\d+(?:\.\d+)?)\s*(s|m|h)?$/.exec(text);
27
+ if (!match) return null;
28
+ const amount = Number(match[1]) * { s: 1000, m: MINUTE, h: HOUR }[match[2] ?? "m"];
29
+ return amount > 0 ? amount : null;
30
+ }
31
+
32
+ export const formatClock = (ms) => new Date(ms).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
@@ -0,0 +1,82 @@
1
+ import { dayKey } from "./dates.js";
2
+
3
+ const MINUTE = 60_000;
4
+ const DAY = 24 * 60 * MINUTE;
5
+
6
+ // Leitner boxes: a correct answer moves the word one box up; a miss sends it back to box 1
7
+ export const BOX_INTERVALS_DAYS = [1, 3, 7, 14, 30];
8
+ export const RELEARN_DELAY = 10 * MINUTE;
9
+ export const NEW_PER_DAY = 20;
10
+
11
+ export const DIRECTIONS = ["en-pl", "pl-en"];
12
+ export const itemKey = (noteId, direction) => `${noteId}:${direction}`;
13
+
14
+ export function newToday(state, now) {
15
+ return state.newToday?.date === dayKey(now) ? state.newToday.count : 0;
16
+ }
17
+
18
+ const NEW_RATIO = 0.3; // when both due and unseen items exist, this share of questions introduces a new one
19
+ const EXTRA_PRACTICE_POOL = 10; // with nothing due, practice one of the next few upcoming items
20
+ const MAX_OVERDUE_WEIGHT_DAYS = 3;
21
+ const SOLO_DUE_MIX = 0.35; // how often a lone due card yields to other material instead of repeating
22
+
23
+ const pickRandom = (items, random) => items[Math.floor(random() * items.length)];
24
+
25
+ // Random among due items, but the longer overdue the likelier: weight 1 (just due) up to 4 (3+ days late).
26
+ // Sorting by due date instead would replay every review in the order it was first answered.
27
+ function pickDue(due, now, random) {
28
+ const weights = due.map((c) => 1 + Math.min(Math.max(now - c.entry.due, 0) / DAY, MAX_OVERDUE_WEIGHT_DAYS));
29
+ let roll = random() * weights.reduce((sum, w) => sum + w, 0);
30
+ for (let i = 0; i < due.length; i++) {
31
+ roll -= weights[i];
32
+ if (roll < 0) return due[i];
33
+ }
34
+ return due[due.length - 1];
35
+ }
36
+
37
+ // Mixes due reviews with new words (up to the daily cap), at random; with nothing to do, practises a soon-due item.
38
+ // Never asks the same note twice in a row when there is any alternative.
39
+ export function pickNext({ words, state, now = Date.now(), lastNoteId = null, directions = DIRECTIONS, random = Math.random }) {
40
+ const candidates = words.flatMap((word) => directions.map((direction) => ({ word, direction, entry: state.items[itemKey(word.noteId, direction)] })));
41
+ if (!candidates.length) return null;
42
+
43
+ const pool = candidates.some((c) => c.word.noteId !== lastNoteId) ? candidates.filter((c) => c.word.noteId !== lastNoteId) : candidates;
44
+
45
+ const due = pool.filter((c) => c.entry && c.entry.due <= now);
46
+ const unseen = pool.filter((c) => !c.entry);
47
+ const canIntroduce = unseen.length > 0 && newToday(state, now) < NEW_PER_DAY;
48
+
49
+ if (due.length && canIntroduce && random() < NEW_RATIO) return pickRandom(unseen, random);
50
+
51
+ // A single due card is usually a word you keep missing (back every RELEARN_DELAY): if it were always
52
+ // picked, every session would open with the same word and a miss would loop it forever. Sometimes
53
+ // practise something else instead and come back to it a question later.
54
+ if (due.length === 1 && random() < SOLO_DUE_MIX) {
55
+ const others = pool.filter((c) => c.entry && c.word.noteId !== due[0].word.noteId).sort((a, b) => a.entry.due - b.entry.due).slice(0, EXTRA_PRACTICE_POOL);
56
+ if (others.length) return pickRandom(others, random);
57
+ if (canIntroduce) return pickRandom(unseen, random);
58
+ }
59
+
60
+ if (due.length) return pickDue(due, now, random);
61
+ if (canIntroduce) return pickRandom(unseen, random);
62
+
63
+ const upcoming = pool.filter((c) => c.entry).sort((a, b) => a.entry.due - b.entry.due).slice(0, EXTRA_PRACTICE_POOL);
64
+ return upcoming.length ? pickRandom(upcoming, random) : pickRandom(unseen, random) ?? null;
65
+ }
66
+
67
+ // → the updated entry (pure; caller stores it). A correct answer given with a hint counts, but doesn't move up a box.
68
+ export function grade(entry, correct, now = Date.now(), { hinted = false } = {}) {
69
+ const prev = entry ?? { box: 0, seen: 0, correct: 0, wrong: 0, streak: 0 };
70
+ if (correct) {
71
+ const box = hinted ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
72
+ return { ...prev, box, due: now + BOX_INTERVALS_DAYS[box - 1] * DAY, seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
73
+ }
74
+ return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };
75
+ }
76
+
77
+ export function describeDue(entry, now = Date.now()) {
78
+ const ms = entry.due - now;
79
+ if (ms < 60 * MINUTE) return `${Math.max(1, Math.round(ms / MINUTE))} min`;
80
+ const hours = Math.round(ms / (60 * MINUTE));
81
+ return hours < 24 ? `${hours} h` : `${Math.round(ms / DAY)} d`;
82
+ }
package/src/session.js ADDED
@@ -0,0 +1,129 @@
1
+ import { directionsFor } from "./settings.js";
2
+ 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";
5
+ import { recordAnswer, saveState } from "./store.js";
6
+ import { createTipDeck } from "./tips.js";
7
+ import { dayKey } from "./dates.js";
8
+ import { formatRange, parseVacation } from "./vacation.js";
9
+
10
+ const LABELS = { "en-pl": "EN → PL", "pl-en": "PL → EN" };
11
+ const COMBO_CHEER_EVERY = 5;
12
+
13
+ // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
14
+ export function createSession({ loadWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
15
+ const rules = () => ({ skipWeekends: getSettings().skipWeekends });
16
+ const totals = { asked: 0, correct: 0, combo: 0 };
17
+ let lastNoteId = null;
18
+ let lastWrong = null; // the latest wrong answer, until the next question: /correct can still overrule it
19
+
20
+ async function next() {
21
+ const { words, cached } = await loadWords();
22
+ const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsFor(getSettings().directions) });
23
+ if (!item) throw new Error("No words to ask about.");
24
+ lastNoteId = item.word.noteId;
25
+ lastWrong = null;
26
+
27
+ const toPolish = item.direction === "en-pl";
28
+ return {
29
+ word: item.word,
30
+ direction: item.direction,
31
+ label: LABELS[item.direction],
32
+ prompt: toPolish ? item.word.word : item.word.translations.join(", "),
33
+ expected: toPolish ? item.word.translations : [item.word.word],
34
+ wordCount: words.length,
35
+ cached
36
+ };
37
+ }
38
+
39
+ async function answer(question, text, { hinted = false } = {}) {
40
+ const key = itemKey(question.word.noteId, question.direction);
41
+ // answers you once declared right (/correct) count for this card from now on
42
+ const result = judge(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
43
+ const correct = result !== "wrong";
44
+ const t = now();
45
+ const before = state.items[key];
46
+ const comboBefore = totals.combo;
47
+ const entry = grade(before, correct, t, { hinted });
48
+ recordAnswer(state, question.word.noteId, question.direction, entry, t);
49
+
50
+ totals.asked += 1;
51
+ totals.correct += correct ? 1 : 0;
52
+ totals.combo = correct ? totals.combo + 1 : 0;
53
+ lastWrong = correct ? null : { question, text, key, before, comboBefore, hinted, at: t };
54
+ if (!correct) recordMiss(state, { key, label: question.label, prompt: question.prompt, expected: question.expected, answer: text, at: t }, t);
55
+
56
+ const reward = applyAnswer(state, { result, goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: t });
57
+ const cheers = [...reward.cheers];
58
+ if (correct && totals.combo % COMBO_CHEER_EVERY === 0) cheers.push({ kind: "combo", text: `Combo ×${totals.combo}` });
59
+
60
+ await save(state);
61
+ // 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 };
64
+ }
65
+
66
+ // Re-grade the last wrong answer as correct and remember the answer for this card.
67
+ async function overrule() {
68
+ if (!lastWrong) throw new Error("There is no wrong answer to correct.");
69
+ const { text, key, before, comboBefore, hinted, at } = lastWrong;
70
+ lastWrong = null;
71
+
72
+ const entry = grade(before, true, at, { hinted });
73
+ state.items[key] = entry;
74
+ undoMiss(state, key, at);
75
+ state.accepted ??= {};
76
+ state.accepted[key] = [...(state.accepted[key] ?? []), text];
77
+
78
+ totals.correct += 1;
79
+ totals.combo = comboBefore + 1;
80
+ const { cheers } = applyOverrule(state, { goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: at });
81
+
82
+ await save(state);
83
+ return { result: "exact", overruled: true, accepted: text, dueIn: describeDue(entry, now()), combo: totals.combo, cheers };
84
+ }
85
+
86
+ const canOverrule = () => lastWrong !== null;
87
+
88
+ const stats = () => snapshot(state, { goal: getSettings().dailyGoal, rules: rules(), now: now() });
89
+
90
+ const month = (offset) => calendarMonth(state, { offset, rules: rules(), now: now() });
91
+ const missed = (offset) => missedOn(state, { offset, now: now() });
92
+
93
+ // /vacation: plan, list or cancel rest days that keep the streak alive → a message for the user
94
+ async function vacation(args) {
95
+ const today = dayKey(now());
96
+ const parsed = parseVacation(args, today);
97
+ if (!parsed) throw new Error("Try /vacation 7, /vacation 24.12 2.01 or /vacation off");
98
+
99
+ if (parsed.action === "add") {
100
+ addVacation(state, parsed.from, parsed.to, now());
101
+ await save(state);
102
+ return `Vacation ${formatRange(parsed.from, parsed.to)}: your streak is safe until then`;
103
+ }
104
+ if (parsed.action === "off") {
105
+ cancelVacations(state, now());
106
+ await save(state);
107
+ return "Vacation cancelled";
108
+ }
109
+ const { upcoming } = vacationInfo(ensureProgress(state, now()), today);
110
+ return upcoming.length ? `Vacations: ${upcoming.map((v) => formatRange(v.from, v.to)).join(", ")}` : "No vacation planned. Try /vacation 7 or /vacation 24.12 2.01";
111
+ }
112
+
113
+ // a tip for the wait between questions; remembering which ones were shown is best-effort
114
+ function nextTip() {
115
+ const tip = tipDeck.next();
116
+ save(state).catch(() => {});
117
+ return tip;
118
+ }
119
+
120
+ // the hatching intro plays once ever: on a brand-new state that has never answered anything
121
+ const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
122
+
123
+ async function markHatched() {
124
+ state.hatched = true;
125
+ await save(state);
126
+ }
127
+
128
+ return { totals, next, answer, overrule, canOverrule, stats, month, missed, nextTip, vacation, isFirstRun, markHatched };
129
+ }
@@ -0,0 +1,43 @@
1
+ export const DEFAULTS = { everyMs: 600_000, sound: true, volume: 0.5, dailyGoal: 20, directions: "both", tips: "always", quiet: null, skipWeekends: true };
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
+ 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
+
14
+ export function formatInterval(ms) {
15
+ if (ms < 60_000) return `${Math.round(ms / 1000)} s`;
16
+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)} min`;
17
+ return `${Math.round(ms / 3_600_000)} h`;
18
+ }
19
+
20
+ // older versions saved tips as a boolean
21
+ const normalizeTips = (value) => (value === true ? "always" : value === false ? "off" : TIP_MODES.includes(value) ? value : DEFAULTS.tips);
22
+
23
+ const isHour = (v) => Number.isInteger(v) && v >= 0 && v <= 23;
24
+
25
+ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
26
+
27
+ // settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
28
+ export function normalizeSettings(raw = {}) {
29
+ return {
30
+ everyMs: isNumber(raw.everyMs) && raw.everyMs >= 1000 ? raw.everyMs : DEFAULTS.everyMs,
31
+ sound: typeof raw.sound === "boolean" ? raw.sound : DEFAULTS.sound,
32
+ volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
33
+ 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
+ tips: normalizeTips(raw.tips),
36
+ 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
38
+ };
39
+ }
40
+
41
+ export function directionsFor(setting) {
42
+ return setting === "en-pl" ? ["en-pl"] : setting === "pl-en" ? ["pl-en"] : ["en-pl", "pl-en"];
43
+ }