dracosh 0.1.0 → 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 (51) hide show
  1. package/README.md +42 -20
  2. package/assets/sounds/badge-1.wav +0 -0
  3. package/assets/sounds/badge-2.wav +0 -0
  4. package/assets/sounds/badge-3.wav +0 -0
  5. package/assets/sounds/badge-4.wav +0 -0
  6. package/data/tips.json +31 -1361
  7. package/package.json +1 -1
  8. package/src/alerts.js +4 -3
  9. package/src/backup.js +95 -0
  10. package/src/cli.js +97 -16
  11. package/src/commands.js +7 -7
  12. package/src/judge.js +33 -12
  13. package/src/library.js +127 -0
  14. package/src/lock.js +63 -0
  15. package/src/manage.js +75 -0
  16. package/src/pause.js +23 -0
  17. package/src/progress.js +145 -53
  18. package/src/quiet.js +1 -1
  19. package/src/scheduler.js +38 -26
  20. package/src/session.js +128 -30
  21. package/src/settings.js +4 -9
  22. package/src/starter.js +38 -0
  23. package/src/store.js +55 -16
  24. package/src/tips.js +7 -24
  25. package/src/ui/AddCard.js +172 -0
  26. package/src/ui/AnswerInput.js +8 -5
  27. package/src/ui/App.js +211 -71
  28. package/src/ui/BadgeUnlock.js +50 -0
  29. package/src/ui/Badges.js +75 -17
  30. package/src/ui/Choice.js +33 -0
  31. package/src/ui/Companion.js +20 -35
  32. package/src/ui/Decks.js +49 -0
  33. package/src/ui/DieRoll.js +104 -0
  34. package/src/ui/Evolution.js +6 -5
  35. package/src/ui/Hatch.js +5 -4
  36. package/src/ui/Header.js +7 -6
  37. package/src/ui/Help.js +68 -0
  38. package/src/ui/Mascot.js +88 -38
  39. package/src/ui/Missed.js +6 -5
  40. package/src/ui/Preview.js +92 -17
  41. package/src/ui/Reset.js +72 -0
  42. package/src/ui/Settings.js +15 -11
  43. package/src/ui/Stats.js +10 -7
  44. package/src/ui/Summary.js +12 -5
  45. package/src/ui/TheOne.js +121 -0
  46. package/src/ui/icons.js +156 -24
  47. package/src/ui/kit.js +58 -1
  48. package/src/vacation.js +7 -2
  49. package/src/words.js +21 -14
  50. package/assets/sounds/badge.wav +0 -0
  51. package/src/ui/Tip.js +0 -25
package/src/manage.js ADDED
@@ -0,0 +1,75 @@
1
+ import { backupNow } from "./backup.js";
2
+ import { seedLibrary } from "./starter.js";
3
+ import { addCard, cardsOf, createDeck, emptyLibrary, findDeck, findDuplicate, removeDeck } from "./library.js";
4
+ import { loadLibrary, saveLibrary } from "./store.js";
5
+
6
+ // Library changes made from inside the app (/add for now). Each one reads the library fresh, so
7
+ // nothing written meanwhile by another Dracosh window is lost.
8
+
9
+ // every deck, the tour too, with its card count: /decks switches between them
10
+ export async function allDecks() {
11
+ const library = await loadLibrary();
12
+ return library.decks.map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, tour: Boolean(deck.tour) }));
13
+ }
14
+
15
+ // your decks (the tour isn't one), with how many cards each holds: /add lets you pick one
16
+ export async function ownDecks() {
17
+ const library = await loadLibrary();
18
+ return library.decks.filter((deck) => !deck.tour).map((deck) => ({ name: deck.name, cards: cardsOf(library, deck.id).length, bothWays: deck.directions !== "forward" }));
19
+ }
20
+
21
+ // A new deck. Your first one replaces the tour: it's removed (after a backup) and the ids of its cards are
22
+ // returned, so their progress can go too.
23
+ export async function startDeck({ name, bothWays }) {
24
+ const library = await loadLibrary();
25
+ const tour = library.decks.find((d) => d.tour);
26
+ let removed = [];
27
+ if (tour) {
28
+ await backupNow("before-delete");
29
+ removed = removeDeck(library, tour.id);
30
+ }
31
+ const deck = createDeck(library, { name, type: "translation", languages: null, directions: bothWays ? "both" : "forward" });
32
+ await saveLibrary(library);
33
+ return { deck, removed };
34
+ }
35
+
36
+ export const SLASH_ANSWER = "An answer can't start with /: in the quiz that opens the commands.";
37
+ export const SLASH_FRONT = "In a deck asked both ways the front is an answer too, so it can't start with /.";
38
+
39
+ // the deck with this name (ignoring case), if any: /add says so before asking anything else
40
+ export const existingDeck = async (name) => {
41
+ const deck = findDeck(await loadLibrary(), name.trim());
42
+ return deck && !deck.tour ? deck : null; // the tour is about to make room, so its name is free
43
+ };
44
+
45
+ // the card with this front already in the deck, if any: /add says so before asking for the answer
46
+ export async function existingCard(deckName, front) {
47
+ const library = await loadLibrary();
48
+ const deck = findDeck(library, deckName);
49
+ return deck ? findDuplicate(library, deck.id, front) : null;
50
+ }
51
+
52
+ // a reset is always preceded by a backup, so `dracosh restore` can undo it
53
+ export const backupBeforeReset = () => backupNow("before-reset");
54
+
55
+ // "Everything" in the reset: your decks and cards go, and the tour comes back as on a fresh install
56
+ export async function resetLibrary() {
57
+ const library = emptyLibrary();
58
+ seedLibrary(library);
59
+ await saveLibrary(library);
60
+ return library.decks[0].name;
61
+ }
62
+
63
+ // → { card, duplicate }, like addCard
64
+ export async function addCardTo(deckName, fields) {
65
+ const library = await loadLibrary();
66
+ const deck = findDeck(library, deckName);
67
+ if (!deck) throw new Error(`The deck "${deckName}" is gone.`);
68
+ // in the quiz "/" opens the commands, so nothing you'd have to type may start with it
69
+ const slash = (text) => String(text ?? "").trim().startsWith("/");
70
+ if ([fields.back].flat().some(slash)) throw new Error(SLASH_ANSWER);
71
+ if (deck.directions !== "forward" && slash(fields.front)) throw new Error(SLASH_FRONT);
72
+ const result = addCard(library, deck.id, fields);
73
+ if (result.card) await saveLibrary(library);
74
+ return result;
75
+ }
package/src/pause.js ADDED
@@ -0,0 +1,23 @@
1
+ import { parseSnooze } from "./quiet.js";
2
+ import { parseVacation } from "./vacation.js";
3
+
4
+ export const PAUSE_HELP = "Try /pause 30m, /pause 2h, /pause 3d or /pause 24.12 2.01";
5
+
6
+ // "/pause" arguments, one command for a short break and for days off:
7
+ // "" → { action: "list" } what's paused or planned
8
+ // "off" → { action: "off" } questions back, days off cancelled
9
+ // "30m", "2h", "90s" → { action: "snooze", ms } a break today; the streak isn't touched
10
+ // "3d", "24.12 2.01"… → { action: "days", from, to } days off that keep your streak
11
+ // A bare whole number is refused: "30" could mean minutes or days ("24.12" is a date). → null when not understood.
12
+ export function parsePause(args, today) {
13
+ const text = args.trim().toLowerCase();
14
+ if (!text) return { action: "list" };
15
+ if (["off", "cancel", "clear"].includes(text)) return { action: "off" };
16
+ if (/^\d+$/.test(text)) return null;
17
+ if (/^\d+(\.\d+)?\s*(s|m|h)$/.test(text)) {
18
+ const ms = parseSnooze(text);
19
+ return typeof ms === "number" ? { action: "snooze", ms } : null;
20
+ }
21
+ const days = parseVacation(text, today);
22
+ return days?.action === "add" ? { action: "days", from: days.from, to: days.to } : null;
23
+ }
package/src/progress.js CHANGED
@@ -4,8 +4,17 @@ import { BOX_INTERVALS_DAYS } from "./scheduler.js";
4
4
  export const MAX_FREEZES = 2;
5
5
  const MAX_BOX = BOX_INTERVALS_DAYS.length;
6
6
  const AT_RISK_HOUR = 19;
7
- const COMEBACK_AFTER_DAYS = 7;
7
+ const COMEBACK_AFTER_DAYS = 5;
8
8
  const MISSED_KEEP_DAYS = 14;
9
+ const FALL_MIN = 30; // a lost streak this long counts as a fall for "Dragon's die"
10
+
11
+ // The die's faces: winning "Dragon's die" rolls one, and the dragon keeps that element for good.
12
+ export const ELEMENTS = ["earth", "wind", "water", "ice", "fire", "cosmos"];
13
+ export const rollElement = (random = Math.random) => ELEMENTS[Math.floor(random() * ELEMENTS.length)];
14
+ export const ELEMENT_ADJECTIVE = { earth: "Earth", wind: "Wind", water: "Water", ice: "Ice", fire: "Fire", cosmos: "Cosmic" };
15
+
16
+ // what the dragon is called: its form, with its element in front once it has one ("Ice Drake")
17
+ export const dragonName = (stage, element = null) => (element ? `${ELEMENT_ADJECTIVE[element]} ${STAGES[stage].name}` : STAGES[stage].name);
9
18
 
10
19
  // The companion evolves permanently with your best streak, so a broken streak never takes a form away.
11
20
  export const STAGES = [
@@ -27,20 +36,15 @@ export function stageFor(bestStreak) {
27
36
  export function ensureProgress(state, now = Date.now()) {
28
37
  state.progress ??= {
29
38
  days: {},
30
- streak: { count: 0, best: 0, lastGoalDay: null, freezes: 1, freezeWeek: weekStart(dayKey(now)), freezesUsed: 0 },
39
+ streak: { count: 0, best: 0, lastGoalDay: null, freezes: MAX_FREEZES, freezeWeek: weekStart(dayKey(now)), freezesUsed: 0 },
31
40
  badges: {},
32
41
  bestCombo: 0,
33
42
  lastActiveDay: null,
34
43
  vacations: []
35
44
  };
36
45
  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
- }
46
+ // badges already shown in /badges; ones unlocked before this was tracked count as seen, so they don't all flash at once
47
+ state.progress.seenBadges ??= Object.keys(state.progress.badges);
44
48
  return state.progress;
45
49
  }
46
50
 
@@ -49,6 +53,7 @@ export function ensureProgress(state, now = Date.now()) {
49
53
  const NO_RULES = { skipWeekends: false };
50
54
 
51
55
  export function isRestDay(progress, key, rules = NO_RULES) {
56
+ if (progress.days?.[key]?.nothingDue) return true; // opened, but no card anywhere was waiting
52
57
  if (rules.skipWeekends) {
53
58
  const weekday = new Date(`${key}T12:00:00`).getDay();
54
59
  if (weekday === 0 || weekday === 6) return true;
@@ -56,37 +61,56 @@ export function isRestDay(progress, key, rules = NO_RULES) {
56
61
  return (progress.vacations ?? []).some((v) => key >= v.from && key <= v.to);
57
62
  }
58
63
 
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
+ // Freezes as they stand today, walking day by day from the last goal day: every new week gives one
65
+ // back (never more than MAX_FREEZES in stock), every missed working day takes one. A gap with more
66
+ // missed days than freezes breaks the streak and takes none. The stored streak.freezes / freezeWeek
67
+ // are as of the last time this was settled (a goal day); nothing is spent until then, but the
68
+ // screens show this walk, so they never promise freezes that are already used.
69
+ function walkFreezes(progress, today, rules) {
70
+ const { lastGoalDay, freezes: stored, freezeWeek } = progress.streak;
71
+ const walk = (spend) => {
72
+ let freezes = stored;
73
+ let week = freezeWeek ?? weekStart(today);
74
+ let used = 0;
75
+ for (let day = lastGoalDay ? addDays(lastGoalDay, 1) : today; day <= today; day = addDays(day, 1)) {
76
+ const dayWeek = weekStart(day);
77
+ if (dayWeek > week) {
78
+ freezes = Math.min(MAX_FREEZES, freezes + Math.round(daysBetween(week, dayWeek) / 7));
79
+ week = dayWeek;
80
+ }
81
+ if (!spend || day === today || isRestDay(progress, day, rules)) continue;
82
+ if (freezes === 0) return null; // the streak breaks here
83
+ freezes -= 1;
84
+ used += 1;
85
+ }
86
+ return { freezes, week, used };
87
+ };
88
+ const spent = lastGoalDay ? walk(true) : null;
89
+ return spent ? { ...spent, broken: false } : { ...walk(false), used: 0, broken: Boolean(lastGoalDay) };
64
90
  }
65
91
 
66
92
  // the streak as shown right now: alive while no working day was skipped, or while freezes can cover the gap
67
93
  export function currentStreak(progress, today, rules = NO_RULES) {
68
- const { count, lastGoalDay, freezes } = progress.streak;
94
+ const { count, lastGoalDay } = progress.streak;
69
95
  if (!lastGoalDay || !count) return 0;
70
- return missedDaysBetween(progress, lastGoalDay, today, rules) <= freezes ? count : 0;
96
+ return walkFreezes(progress, today, rules).broken ? 0 : count;
71
97
  }
72
98
 
99
+ export const freezesNow = (progress, today, rules = NO_RULES) => walkFreezes(progress, today, rules).freezes;
100
+
73
101
  function completeDay(progress, today, rules) {
74
102
  const streak = progress.streak;
103
+ const { freezes, week, used, broken } = walkFreezes(progress, today, rules);
75
104
  if (!streak.lastGoalDay) {
76
105
  streak.count = 1;
106
+ } else if (broken) {
107
+ if (streak.count >= FALL_MIN) streak.fallen = streak.count; // the most recent long streak that was lost
108
+ streak.count = 1;
77
109
  } 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
- }
110
+ streak.count += 1;
111
+ streak.freezesUsed = (streak.freezesUsed ?? 0) + used;
88
112
  }
89
- streak.lastGoalDay = today;
113
+ Object.assign(streak, { freezes, freezeWeek: week, lastGoalDay: today });
90
114
  streak.best = Math.max(streak.best, streak.count);
91
115
  return streak.count;
92
116
  }
@@ -138,20 +162,23 @@ export const BADGES = [
138
162
  { id: "hello", name: "Hello!", desc: "your first correct answer", test: (s) => s.totalCorrect >= 1 },
139
163
  { id: "first-steps", name: "First steps", desc: "10 correct answers", test: (s) => s.totalCorrect >= 10 },
140
164
  { 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 },
165
+ { id: "thousand", name: "Thousand", desc: "1,000 correct answers", test: (s) => s.totalCorrect >= 1000 },
166
+ { id: "five-thousand", name: "Five thousand", desc: "5,000 correct answers", test: (s) => s.totalCorrect >= 5000 },
167
+ { id: "ten-thousand", name: "Ten thousand", desc: "10,000 correct answers", test: (s) => s.totalCorrect >= 10000 },
168
+ { id: "dragons-hoard", name: "Dragon's hoard", desc: "20,000 correct answers", test: (s) => s.totalCorrect >= 20000 },
144
169
 
145
170
  { id: "on-a-roll", name: "On a roll", desc: "3-day streak", test: (s) => s.bestStreak >= 3 },
146
171
  { id: "week", name: "Full week", desc: "7-day streak", test: (s) => s.bestStreak >= 7 },
147
172
  { id: "fortnight", name: "Fortnight", desc: "14-day streak", test: (s) => s.bestStreak >= 14 },
148
173
  { id: "month", name: "Iron habit", desc: "30-day streak", test: (s) => s.bestStreak >= 30 },
149
174
  { id: "hundred-days", name: "Centurion", desc: "100-day streak", test: (s) => s.bestStreak >= 100 },
175
+ { id: "dragonheart", name: "Dragonheart", desc: "180-day streak", test: (s) => s.bestStreak >= 180 },
150
176
 
151
177
  { 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 },
178
+ { id: "collector", name: "Collector", desc: "25 cards mastered", test: (s) => s.mastered >= 25 },
179
+ { id: "dictionary", name: "Walking dictionary", desc: "50 cards mastered", test: (s) => s.mastered >= 50 },
180
+ { id: "lexicon", name: "Living lexicon", desc: "150 cards mastered", test: (s) => s.mastered >= 150 },
181
+ { id: "explorer", name: "Explorer", desc: "250 cards practised", test: (s) => s.practiced >= 250 },
155
182
 
156
183
  { 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
184
  { id: "overachiever", name: "Overachiever", desc: "double your daily goal in a day", test: (s) => s.today.correct >= s.goal * 2 },
@@ -164,7 +191,7 @@ export const BADGES = [
164
191
  { id: "early-bird", name: "Early bird", desc: "a correct answer before 8:00", test: (s) => s.event.correct && s.event.hour < 8 },
165
192
  { id: "night-owl", name: "Night owl", desc: "a correct answer after 23:00", test: (s) => s.event.correct && s.event.hour >= 23 },
166
193
 
167
- { id: "comeback", name: "Welcome back", desc: "back after 7+ days away", test: (s) => s.event.correct && s.event.daysAway >= COMEBACK_AFTER_DAYS },
194
+ { id: "comeback", name: "Welcome back", desc: "back after 5+ days away", test: (s) => s.event.correct && s.event.daysAway >= COMEBACK_AFTER_DAYS },
168
195
  { id: "redemption", name: "Redemption", desc: "5 words missed today, got right later the same day", test: (s) => s.recoveredToday >= 5 },
169
196
  { id: "frozen", name: "Frozen in time", desc: "a freeze saved your streak", test: (s) => s.freezesUsed >= 1 },
170
197
  { id: "weekend", name: "Weekend warrior", desc: "goal on both Saturday and Sunday", test: (s) => s.weekendDone },
@@ -173,16 +200,35 @@ export const BADGES = [
173
200
  { id: "machine", name: "The machine", desc: "goal on 25 days in one month", test: (s) => s.goalDaysThisMonth >= 25 },
174
201
  { id: "hundred-club", name: "Hundred club", desc: "goal reached on 100 days in total", test: (s) => s.totalGoalDays >= 100 },
175
202
 
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 }
203
+
204
+ // keep this one last: it checks the others, including any unlocked earlier in the same answer
205
+ { id: "one-ring", name: "The One...", desc: "every other badge", test: (s) => BADGES.every((b) => b.id === "one-ring" || b.hidden || s.badges[b.id]) },
206
+
207
+ // hidden: shown as "???" until won, and not needed for The One
208
+ {
209
+ id: "dragons-die",
210
+ name: "Dragon's die",
211
+ desc: "lost a 30+ day streak, then built a longer one",
212
+ hidden: true,
213
+ test: (s) => s.fallenStreak >= FALL_MIN && s.streakCount > s.fallenStreak
214
+ }
177
215
  ];
178
216
 
217
+ // progress is kept per card and direction ("id:en-pl"); badges count cards
218
+ const cardOf = (key) => key.slice(0, key.lastIndexOf(":"));
219
+
220
+ // a card is mastered once every direction it's been asked in has reached the last box
221
+ function masteredCards(items) {
222
+ const byCard = new Map();
223
+ for (const [key, entry] of items) byCard.set(cardOf(key), (byCard.get(cardOf(key)) ?? true) && entry.box === MAX_BOX);
224
+ return [...byCard.values()].filter(Boolean).length;
225
+ }
226
+
179
227
  function collectStats(state, now, goal) {
180
228
  const progress = state.progress;
181
229
  const todayKey = dayKey(now);
182
230
  const today = progress.days[todayKey] ?? { asked: 0, correct: 0 };
183
231
  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
232
 
187
233
  // words missed today that were answered correctly again later the same day (one per card)
188
234
  const lastMissByKey = new Map();
@@ -196,13 +242,15 @@ function collectStats(state, now, goal) {
196
242
  const isSunday = new Date(`${todayKey}T12:00:00`).getDay() === 0;
197
243
  return {
198
244
  goal,
245
+ badges: progress.badges, // live: badges unlocked earlier in the same award pass count too
246
+ fallenStreak: progress.streak.fallen ?? 0,
247
+ streakCount: progress.streak.count,
199
248
  totalCorrect: Object.values(progress.days).reduce((sum, d) => sum + d.correct, 0),
200
249
  bestStreak: progress.streak.best,
201
250
  bestCombo: progress.bestCombo ?? 0,
202
251
  freezesUsed: progress.streak.freezesUsed ?? 0,
203
- mastered: items.filter(([, e]) => e.box === MAX_BOX).length,
204
- practiced: items.length,
205
- correctByDirection,
252
+ mastered: masteredCards(items),
253
+ practiced: new Set(items.map(([key]) => cardOf(key))).size,
206
254
  goalDaysThisMonth: goalDaysInMonth(progress, todayKey),
207
255
  totalGoalDays: Object.values(progress.days).filter((d) => d.goalMet).length,
208
256
  recoveredToday,
@@ -213,13 +261,16 @@ function collectStats(state, now, goal) {
213
261
  }
214
262
 
215
263
  // Goal check, evolution and badges after something was credited today → cheers
216
- function award(state, progress, day, today, { correct, goal, rules, now, daysAway = 0 }) {
264
+ // `caughtUp`: nothing is left to practise today, which counts as reaching the goal (a small deck can't
265
+ // give 20 answers a day, and doing everything there is to do shouldn't cost a streak).
266
+ function award(state, progress, day, today, { correct, goal, rules, now, daysAway = 0, caughtUp = false, random = Math.random }) {
217
267
  const cheers = [];
218
- if (correct && !day.goalMet && day.correct >= goal) {
268
+ if (((correct && day.correct >= goal) || caughtUp) && !day.goalMet) {
219
269
  day.goalMet = true;
270
+ if (caughtUp) day.caughtUp = true;
220
271
  const stageBefore = stageFor(progress.streak.best);
221
272
  const streak = completeDay(progress, today, rules);
222
- cheers.push({ kind: "goal", text: `Daily goal reached · ${streak}-day streak` });
273
+ cheers.push({ kind: "goal", text: `${caughtUp ? "All done for today" : "Daily goal reached"} · ${streak}-day streak` });
223
274
  const stageAfter = stageFor(progress.streak.best);
224
275
  if (stageAfter.index > stageBefore.index)
225
276
  cheers.push({ kind: "evolve", text: `Your companion evolved into a${/^[aeiou]/i.test(stageAfter.name) ? "n" : ""} ${stageAfter.name}!` });
@@ -229,7 +280,12 @@ function award(state, progress, day, today, { correct, goal, rules, now, daysAwa
229
280
  for (const badge of BADGES) {
230
281
  if (!progress.badges[badge.id] && badge.test(stats)) {
231
282
  progress.badges[badge.id] = today;
232
- cheers.push({ kind: "badge", text: `Badge unlocked: ${badge.name} · ${badge.desc}` });
283
+ cheers.push({ kind: "badge", id: badge.id, name: badge.name, desc: badge.desc, text: `Badge unlocked: ${badge.name} · ${badge.desc}` });
284
+ // rolled and saved right away, before any animation, so quitting mid-roll can't reroll it
285
+ if (badge.id === "dragons-die" && !progress.element && !progress.elementDropped) {
286
+ progress.element = rollElement(random);
287
+ progress.elementRoll = { face: ELEMENTS.indexOf(progress.element) + 1, on: today };
288
+ }
233
289
  }
234
290
  }
235
291
  return cheers;
@@ -238,29 +294,49 @@ function award(state, progress, day, today, { correct, goal, rules, now, daysAwa
238
294
  const dayOf = (progress, today) => (progress.days[today] ??= { asked: 0, correct: 0 });
239
295
 
240
296
  // 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() }) {
297
+ export function applyAnswer(state, { result, goal, rules = NO_RULES, combo = 0, now = Date.now(), random = Math.random }) {
242
298
  const progress = ensureProgress(state, now);
243
299
  const today = dayKey(now);
244
300
  const day = dayOf(progress, today);
245
301
  const correct = result !== "wrong";
246
- const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) : 0;
302
+ // full days away since the last correct answer (a wrong first answer back doesn't end the absence)
303
+ const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) - 1 : 0;
247
304
 
248
305
  day.asked += 1;
249
306
  day.correct += correct ? 1 : 0;
250
307
  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 }) };
308
+ if (correct) progress.lastActiveDay = today;
309
+ return { cheers: award(state, progress, day, today, { correct, goal, rules, now, daysAway, random }) };
253
310
  }
254
311
 
255
312
  // 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() }) {
313
+ export function applyOverrule(state, { goal, rules = NO_RULES, combo = 0, now = Date.now(), random = Math.random }) {
257
314
  const progress = ensureProgress(state, now);
258
315
  const today = dayKey(now);
259
316
  const day = dayOf(progress, today);
260
317
 
318
+ const daysAway = progress.lastActiveDay ? daysBetween(progress.lastActiveDay, today) - 1 : 0;
261
319
  day.correct += 1;
262
320
  progress.bestCombo = Math.max(progress.bestCombo ?? 0, combo);
263
- return { cheers: award(state, progress, day, today, { correct: true, goal, rules, now }) };
321
+ progress.lastActiveDay = today;
322
+ return { cheers: award(state, progress, day, today, { correct: true, goal, rules, now, daysAway, random }) };
323
+ }
324
+
325
+ // Nothing left to practise today in the whole library → cheers. After at least one right answer today
326
+ // that counts as the goal (see award); with nothing answered at all the day only becomes a rest day, so just
327
+ // opening Dracosh never builds a streak. Nothing happens once the goal is met.
328
+ export function applyCaughtUp(state, { goal, rules = NO_RULES, now = Date.now(), random = Math.random }) {
329
+ const progress = ensureProgress(state, now);
330
+ const today = dayKey(now);
331
+ const day = dayOf(progress, today);
332
+ if (day.goalMet) return { cheers: [] };
333
+ if (!day.asked) {
334
+ day.nothingDue = true;
335
+ return { cheers: [] };
336
+ }
337
+ if (!day.correct) return { cheers: [] }; // a day of misses only isn't a day done
338
+
339
+ return { cheers: award(state, progress, day, today, { correct: false, goal, rules, now, caughtUp: true, random }) };
264
340
  }
265
341
 
266
342
  // everything the screens display, derived from state
@@ -277,17 +353,17 @@ export function snapshot(state, { goal, rules = NO_RULES, now = Date.now() }) {
277
353
  streak: {
278
354
  days,
279
355
  best: progress.streak.best,
280
- freezes: progress.streak.freezes,
356
+ freezes: freezesNow(progress, today, rules),
281
357
  atRisk: days > 0 && !goalMet && !restToday && new Date(now).getHours() >= AT_RISK_HOUR
282
358
  },
283
359
  restToday,
284
360
  skipWeekends: rules.skipWeekends,
285
361
  vacation: vacationInfo(progress, today),
286
- companion: stageFor(progress.streak.best),
362
+ companion: { ...stageFor(progress.streak.best), element: progress.element ?? null, roll: progress.elementRoll ?? null },
287
363
  totalCorrect: stats.totalCorrect,
288
364
  mastered: stats.mastered,
289
365
  practiced: stats.practiced,
290
- badges: BADGES.map((b) => ({ id: b.id, name: b.name, desc: b.desc, unlockedOn: progress.badges[b.id] ?? null }))
366
+ badges: BADGES.map((b) => ({ id: b.id, name: b.name, desc: b.desc, hidden: Boolean(b.hidden), unlockedOn: progress.badges[b.id] ?? null }))
291
367
  };
292
368
  }
293
369
 
@@ -361,3 +437,19 @@ export function missedOn(state, { offset = 0, now = Date.now() } = {}) {
361
437
  .sort((a, b) => b.at - a.at);
362
438
  return { date, items };
363
439
  }
440
+
441
+ // ---- badges you haven't looked at yet (they light up when /badges opens) ----------------------------------
442
+
443
+ // → ids of badges unlocked but not yet seen in /badges, in the order they were won
444
+ export function unseenBadges(state, now = Date.now()) {
445
+ const progress = ensureProgress(state, now);
446
+ return BADGES.map((badge, index) => ({ id: badge.id, index, on: progress.badges[badge.id] }))
447
+ .filter((b) => b.on && !progress.seenBadges.includes(b.id))
448
+ .sort((a, b) => (a.on === b.on ? a.index - b.index : a.on < b.on ? -1 : 1))
449
+ .map((b) => b.id);
450
+ }
451
+
452
+ export function markBadgesSeen(state, now = Date.now()) {
453
+ const progress = ensureProgress(state, now);
454
+ progress.seenBadges = Object.keys(progress.badges);
455
+ }
package/src/quiet.js CHANGED
@@ -18,7 +18,7 @@ export function quietEnd(ms, quiet) {
18
18
 
19
19
  export const formatQuiet = (quiet) => (quiet ? `${String(quiet.from).padStart(2, "0")}:00–${String(quiet.to).padStart(2, "0")}:00` : "off");
20
20
 
21
- // "/snooze" → 1 h, "30", "30m", "2h", "90s" → milliseconds, "off" → "off", anything else → null
21
+ // /pause durations: "" → 1 h, "30", "30m", "2h", "90s" → milliseconds, "off" → "off", anything else → null
22
22
  export function parseSnooze(arg) {
23
23
  const text = arg.trim().toLowerCase();
24
24
  if (!text) return HOUR;
package/src/scheduler.js CHANGED
@@ -3,7 +3,7 @@ import { dayKey } from "./dates.js";
3
3
  const MINUTE = 60_000;
4
4
  const DAY = 24 * 60 * MINUTE;
5
5
 
6
- // Leitner boxes: a correct answer moves the word one box up; a miss sends it back to box 1
6
+ // Leitner boxes: a correct answer moves the card one box up; a miss sends it back to box 1
7
7
  export const BOX_INTERVALS_DAYS = [1, 3, 7, 14, 30];
8
8
  export const RELEARN_DELAY = 10 * MINUTE;
9
9
  export const NEW_PER_DAY = 20;
@@ -16,9 +16,7 @@ export function newToday(state, now) {
16
16
  }
17
17
 
18
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
19
  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
20
 
23
21
  const pickRandom = (items, random) => items[Math.floor(random() * items.length)];
24
22
 
@@ -35,40 +33,54 @@ function pickDue(due, now, random) {
35
33
  }
36
34
 
37
35
  // 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 }) {
36
+ // Never asks the same note twice in a row when there is any alternative. A `tour` deck is different:
37
+ // each card is asked once, in deck order, and never comes back as a review (null when it's done).
38
+ // What to ask next: a due review or a new card (up to the daily cap), mixed at random; null when there
39
+ // is nothing to do right now. Cards are never asked before they're due: answering early would move them
40
+ // up the boxes without the spacing that makes them stick. Never the same note twice in a row while
41
+ // anything else is waiting. A `tour` deck is different: each card is asked once, in deck order, and
42
+ // never comes back as a review.
43
+ export function pickNext({ words, state, now = Date.now(), lastNoteId = null, directions = DIRECTIONS, tour = false, random = Math.random }) {
40
44
  const candidates = words.flatMap((word) => directions.map((direction) => ({ word, direction, entry: state.items[itemKey(word.noteId, direction)] })));
41
- if (!candidates.length) return null;
45
+ if (tour) return candidates.find((c) => !c.entry) ?? null;
42
46
 
43
- const pool = candidates.some((c) => c.word.noteId !== lastNoteId) ? candidates.filter((c) => c.word.noteId !== lastNoteId) : candidates;
47
+ const canIntroduce = newToday(state, now) < NEW_PER_DAY;
48
+ const waiting = candidates.filter((c) => (c.entry ? c.entry.due <= now : canIntroduce));
49
+ if (!waiting.length) return null;
50
+ const pool = waiting.some((c) => c.word.noteId !== lastNoteId) ? waiting.filter((c) => c.word.noteId !== lastNoteId) : waiting;
44
51
 
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);
52
+ const due = pool.filter((c) => c.entry);
53
+ const fresh = pool.filter((c) => !c.entry);
54
+ if (due.length && fresh.length && random() < NEW_RATIO) return pickRandom(fresh, random);
55
+ return due.length ? pickDue(due, now, random) : pickRandom(fresh, random);
56
+ }
50
57
 
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
+ // When something will next be waiting, once pickNext has nothing: the earliest due card, or the
59
+ // start of tomorrow when only new cards are left (the daily cap is reached). null = nothing ever.
60
+ export function nextDueAt({ words, state, now = Date.now(), directions = DIRECTIONS }) {
61
+ let next = null;
62
+ for (const word of words) {
63
+ for (const direction of directions) {
64
+ const entry = state.items[itemKey(word.noteId, direction)];
65
+ const at = entry ? entry.due : startOfTomorrow(now);
66
+ if (next === null || at < next) next = at;
67
+ }
58
68
  }
69
+ return next;
70
+ }
59
71
 
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;
72
+ export function startOfTomorrow(now) {
73
+ const date = new Date(now);
74
+ date.setHours(24, 0, 0, 0);
75
+ return date.getTime();
65
76
  }
66
77
 
67
- // → the updated entry (pure; caller stores it). A correct answer given with a hint counts, but doesn't move up a box.
68
78
  export function grade(entry, correct, now = Date.now(), { hinted = false } = {}) {
69
79
  const prev = entry ?? { box: 0, seen: 0, correct: 0, wrong: 0, streak: 0 };
70
80
  if (correct) {
71
- const box = hinted ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
81
+ // right after a miss the card starts over at box 1 (back tomorrow) instead of skipping ahead
82
+ const relearning = prev.seen > 0 && prev.streak === 0;
83
+ const box = hinted || relearning ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
72
84
  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
85
  }
74
86
  return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };