freezmo/components/StatsScreen.tsx
Martin Dvorak e4a8e0ba01 Phase 2: learning engine — history, SRS review, mistakes, stats, exam, reminders
Answer history and schedules
- Every answer is recorded (deck, activity, topic, correct/wrong, time)
  in a versioned IndexedDB log (freezmo-learning v1, stores answers +
  srs), mirrored in memory for synchronous React reads and capped at
  20k answers (oldest pruned). StudyFeed records as it grades.
- Light SM-2 schedule per activity: 1 day, 3 days, then interval x
  ease; wrong answers return in ten minutes with the ease nudged down.

Review, mistakes, stats
- Library 'Smart review' card: due count, mistakes count (latest
  answer wrong — clears itself when answered correctly), today's goal
  progress. Review sessions freeze their item list at start.
- New /review (due across decks, ?mistakes=1 global or ?deck= per
  deck) built on a shared SessionFeed with the study feed's snap/keyboard
  mechanics, wake lock and a results slide.
- New /stats: day streak, five-week calendar, accuracy per subject and
  per deck, weakest topics (>=3 answers), daily-goal progress.
- Daily goal configurable in Settings (10/20/30/50).

Exam mode
- New /exam: pick decks, question count, optional timer; no hints
  (a NoHints context hides hint rows and the self-check escape);
  results with score, per-deck and per-topic breakdown; wrong answers
  land in the mistakes set through the normal history.

Reminders (conditional)
- VAPID-gated: GET/POST/DELETE /api/push and POST /api/push/test with
  the standard route pattern, RATE_LIMIT_PUSH, zod, auth before body.
  Subscriptions stored server-side as endpoint + keys only (PUSH_DIR).
  UI hidden entirely without keys; iOS install note; service worker
  push/notificationclick handlers; scripts/send-reminders.mjs for a
  cron/systemd timer; web-push added as the one server dependency.

Verified: new phase-2 suite 42/42 (history/SRS shapes from a real study
run, mistakes clearing, review session, stats math, exam timer and
breakdowns, VAPID-less hidden state plus the configured
subscribe/validate/test/delete path against a second instance) plus
regression 74/74, mobile 52/52, wizard 80/80, declutter 116/116,
animation 8/8, native 35/35, phase1 38/38, i18n 25/25. Key parity
709/709. Lint + build clean. SW freezmo-v26.
2026-10-10 14:15:21 +00:00

214 lines
9 KiB
TypeScript

"use client";
import Link from "next/link";
import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { Button, ProgressBar } from "@/components/ui";
import { ensureLearningHydrated, learningStore } from "@/lib/history";
import { useI18n } from "@/lib/i18n";
import { computeStats, dayKey } from "@/lib/learning";
import { settingsStore } from "@/lib/settings";
import { cn } from "@/lib/utils";
/**
* Progress: day streak, daily-goal progress, a five-week calendar, accuracy
* per subject and per deck, and the weakest topics (at least three answers).
*/
export function StatsScreen() {
const { t, plural, locale } = useI18n();
const answers = useSyncExternalStore(
learningStore.subscribe,
learningStore.getAnswersSnapshot,
learningStore.getServerAnswers,
);
const dailyGoal = useSyncExternalStore(
settingsStore.subscribe,
() => settingsStore.getSnapshot().dailyGoal,
() => 20,
);
const [ready, setReady] = useState(false);
useEffect(() => {
void ensureLearningHydrated().then(() => setReady(true));
}, []);
const stats = useMemo(() => computeStats(answers), [answers]);
if (!ready) {
return (
<div className="space-y-4" aria-busy="true">
<div className="skeleton h-24 rounded-3xl" />
<div className="skeleton h-40 rounded-3xl" />
</div>
);
}
if (stats.total === 0) {
return (
<div className="card mx-auto max-w-md space-y-3 p-6 text-center">
<p className="text-3xl" aria-hidden>
📈
</p>
<h1 className="text-xl font-extrabold text-[var(--text)]">{t("stats.empty")}</h1>
<p className="text-sm leading-relaxed text-[var(--text-muted)]">{t("stats.emptyBody")}</p>
<Button className="touch-target" onClick={() => window.history.back()}>
{t("stats.start")}
</Button>
</div>
);
}
// Calendar: five weeks, columns aligned to weekdays (Monday first).
const today = new Date();
const weekdayIndex = (today.getDay() + 6) % 7;
const start = new Date(today);
start.setDate(today.getDate() - weekdayIndex - 28);
const byDay = new Map(stats.days.map((entry) => [entry.day, entry]));
const cells = Array.from({ length: 35 }, (_, index) => {
const date = new Date(start);
date.setDate(start.getDate() + index);
const key = dayKey(date.getTime());
return { key, date, future: date.getTime() > today.getTime() + 86_400_000, entry: byDay.get(key) };
});
const weekdayLabels = Array.from({ length: 7 }, (_, index) => {
const date = new Date(start);
date.setDate(start.getDate() + index);
return new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(date);
});
const intensity = (count: number) =>
count === 0
? "bg-[var(--surface-sunken)]"
: count <= 2
? "bg-sky-200/80 dark:bg-sky-400/20"
: count <= 5
? "bg-sky-400/70 dark:bg-sky-400/40"
: "grad-ice";
return (
<div className="space-y-5">
<section className="space-y-1.5">
<h1 className="text-[26px] font-semibold leading-tight tracking-[-0.02em] text-[var(--text)]">
{t("stats.title")}
</h1>
<p className="text-[14px] text-frost-600 dark:text-frost-300">{t("stats.subtitle")}</p>
</section>
<section className="grid gap-3 sm:grid-cols-3">
<div className="card space-y-1 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.streak")}</p>
<p className="text-[28px] font-extrabold leading-none text-[var(--text)]">{stats.streak}</p>
<p className="text-[11.5px] text-[var(--text-muted)]">{plural(stats.total, "stats.answers")}</p>
</div>
<div className="card space-y-2 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.today")}</p>
<p className="text-[15px] font-bold text-[var(--text)]">
{t("stats.todayOf", { n: stats.todayCount, goal: dailyGoal })}
</p>
<ProgressBar value={Math.min(stats.todayCount, dailyGoal)} max={dailyGoal} label={t("stats.today")} />
{stats.todayCount >= dailyGoal ? (
<p className="text-[11.5px] font-semibold text-emerald-700 dark:text-emerald-300">{t("stats.goalDone")}</p>
) : null}
</div>
<div className="card space-y-1 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.accuracy")}</p>
<p className="text-[28px] font-extrabold leading-none text-[var(--text)]">
{Math.round(stats.accuracy * 100)}%
</p>
<p className="text-[11.5px] text-[var(--text-muted)]">
{t("stats.correctOf", { correct: stats.correct, total: stats.total })}
</p>
</div>
</section>
<section className="card space-y-3 p-4">
<div className="flex items-center justify-between gap-2">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.calendar")}</p>
<p className="flex items-center gap-1.5 text-[10.5px] text-[var(--text-subtle)]">
{t("stats.legendLess")}
<span className="size-3 rounded-[4px] bg-[var(--surface-sunken)]" />
<span className="size-3 rounded-[4px] bg-sky-200/80 dark:bg-sky-400/20" />
<span className="size-3 rounded-[4px] bg-sky-400/70 dark:bg-sky-400/40" />
<span className="size-3 rounded-[4px] grad-ice" />
{t("stats.legendMore")}
</p>
</div>
<div className="grid grid-cols-7 gap-1.5">
{weekdayLabels.map((label, index) => (
<span key={index} className="text-center text-[10px] font-semibold text-[var(--text-subtle)]">
{label}
</span>
))}
{cells.map((cell) => (
<span
key={cell.key}
title={`${cell.key}: ${cell.entry?.count ?? 0}`}
aria-label={`${cell.key}: ${cell.entry?.count ?? 0}`}
className={cn(
"aspect-square rounded-[6px]",
cell.future ? "opacity-30" : "",
intensity(cell.entry?.count ?? 0),
)}
/>
))}
</div>
</section>
{stats.subjects.length > 0 ? (
<section className="card space-y-2 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.bySubject")}</p>
{stats.subjects.map((entry) => (
<div key={entry.label} className="flex items-center justify-between gap-3 text-[13px]">
<span className="min-w-0 truncate font-medium text-[var(--text)]">{entry.label}</span>
<span className="shrink-0 tabular-nums text-[var(--text-muted)]">
{Math.round((entry.correct / Math.max(1, entry.answered)) * 100)}% ·{" "}
{t("stats.correctOf", { correct: entry.correct, total: entry.answered })}
</span>
</div>
))}
</section>
) : null}
<section className="card space-y-2 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.byDeck")}</p>
{stats.decks.map((entry) => (
<div key={entry.label} className="flex items-center justify-between gap-3 text-[13px]">
<span className="min-w-0 truncate font-medium text-[var(--text)]">{entry.label}</span>
<span className="shrink-0 tabular-nums text-[var(--text-muted)]">
{Math.round((entry.correct / Math.max(1, entry.answered)) * 100)}% ·{" "}
{t("stats.correctOf", { correct: entry.correct, total: entry.answered })}
</span>
</div>
))}
</section>
{stats.weakestTopics.length > 0 ? (
<section className="card space-y-2 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("stats.weakest")}</p>
{stats.weakestTopics.map((entry) => (
<div key={entry.label} className="flex items-center justify-between gap-3 text-[13px]">
<span className="min-w-0 truncate font-medium text-[var(--text)]">{entry.label}</span>
<span className="shrink-0 tabular-nums text-[var(--text-muted)]">
{Math.round((entry.correct / Math.max(1, entry.answered)) * 100)}%
</span>
</div>
))}
</section>
) : null}
<div className="flex flex-wrap gap-2">
<Link
href="/review"
className="inline-flex h-11 items-center justify-center rounded-[14px] btn-secondary px-5 text-[15px] font-medium touch-target"
>
{t("review.title")}
</Link>
<Link
href="/exam"
className="inline-flex h-11 items-center justify-center rounded-[14px] btn-ghost px-5 text-[15px] font-medium touch-target"
>
{t("exam.title")}
</Link>
</div>
</div>
);
}