freezmo/components/SessionFeed.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

232 lines
8.4 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { ActivityRenderer } from "@/components/activities";
import { XIcon } from "@/components/icons";
import { ProgressBar } from "@/components/ui";
import type { Activity, Deck } from "@/lib/schemas";
import { useI18n } from "@/lib/i18n";
import { useWakeLock } from "@/lib/use-wake-lock";
import { cn } from "@/lib/utils";
export type SessionItem = { deck: Deck; activity: Activity };
export type SessionResult = { correct: boolean; userAnswer?: string };
export type SessionRenderResults = (state: {
results: Record<string, SessionResult>;
items: SessionItem[];
correct: number;
total: number;
score: number;
}) => React.ReactNode;
/**
* The scroll-snap activity feed shared by review, mistakes and exam sessions.
* Same mechanics as the study feed (remount per run, scroll tracking, keyboard
* navigation) but with a pluggable results slide and an optional timer.
*/
export function SessionFeed({
title,
items,
timerSeconds,
noHints = false,
testId,
onExit,
onAnswered,
renderResults,
}: {
title: string;
items: SessionItem[];
timerSeconds?: number;
noHints?: boolean;
testId?: string;
onExit: () => void;
onAnswered?: (item: SessionItem, correct: boolean, meta?: { userAnswer?: string }) => void;
renderResults: SessionRenderResults;
}) {
const { t } = useI18n();
useWakeLock(true);
const [index, setIndex] = useState(0);
const [results, setResults] = useState<Record<string, SessionResult>>({});
const [runId] = useState(0);
const [remaining, setRemaining] = useState(timerSeconds ?? 0);
const scrollRef = useRef<HTMLDivElement>(null);
const total = items.length;
const slideCount = total + 1;
const goTo = useCallback(
(target: number) => {
const container = scrollRef.current;
if (!container) return;
const clamped = Math.max(0, Math.min(target, slideCount - 1));
container.scrollTo({ top: clamped * container.clientHeight, behavior: "smooth" });
},
[slideCount],
);
const next = useCallback(() => goTo(index + 1), [goTo, index]);
useEffect(() => {
const container = scrollRef.current;
if (!container) return;
let frame = 0;
const onScroll = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const height = container.clientHeight || 1;
const current = Math.round(container.scrollTop / height);
setIndex((previous) => (previous === current ? previous : current));
});
};
container.addEventListener("scroll", onScroll, { passive: true });
return () => {
container.removeEventListener("scroll", onScroll);
cancelAnimationFrame(frame);
};
}, [runId]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
if (target && (/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || target.isContentEditable)) return;
if (event.metaKey || event.ctrlKey || event.altKey) return;
if (event.key === "ArrowDown" || event.key === "PageDown" || event.key === "j") {
event.preventDefault();
next();
} else if (event.key === "ArrowUp" || event.key === "PageUp" || event.key === "k") {
event.preventDefault();
goTo(index - 1);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [goTo, index, next]);
// Countdown (exam mode); reaching zero jumps to the results slide.
useEffect(() => {
if (!timerSeconds) return;
const interval = window.setInterval(() => {
setRemaining((value) => {
if (value <= 1) {
window.clearInterval(interval);
return 0;
}
return value - 1;
});
}, 1000);
return () => window.clearInterval(interval);
}, [timerSeconds]);
useEffect(() => {
if (timerSeconds && remaining === 0) goTo(slideCount - 1);
}, [remaining, timerSeconds, goTo, slideCount]);
const handleAnswered = useCallback(
(item: SessionItem, correct: boolean, meta?: { userAnswer?: string }) => {
setResults((current) => {
if (current[item.activity.id]) return current;
return { ...current, [item.activity.id]: { correct, userAnswer: meta?.userAnswer } };
});
onAnswered?.(item, correct, meta);
},
[onAnswered],
);
const finished = index >= total;
const correct = items.filter((item) => results[item.activity.id]?.correct).length;
const score = total > 0 ? Math.round((correct / total) * 100) : 0;
return (
<div className="frost-bg fixed inset-0 flex flex-col fade-in-mobile">
<header className="pt-safe absolute inset-x-0 top-0 z-30 px-3">
<div className="study-chrome mx-auto max-w-xl space-y-1.5 rounded-full px-3 py-2">
<div className="flex items-center gap-3">
<button
type="button"
onClick={onExit}
aria-label={t("feed.back")}
className="grid size-9 shrink-0 place-items-center rounded-xl bg-[var(--surface-sunken)] text-[var(--text)] transition hover:bg-[var(--hover)]"
>
<XIcon className="size-4" />
</button>
<div className="min-w-0 flex-1">
<ProgressBar
value={Math.min(index + 1, slideCount)}
max={slideCount}
label={t("feed.activityOf", { n: Math.min(index + 1, total), total })}
/>
</div>
{timerSeconds ? (
<span
className={cn(
"shrink-0 rounded-xl px-2 py-1 text-xs font-extrabold tabular-nums",
remaining <= 30 ? "tint-peach" : "bg-[var(--surface-sunken)] text-[var(--text-muted)]",
)}
aria-label={t("exam.timeLeft", { time: formatClock(remaining) })}
>
{formatClock(remaining)}
</span>
) : null}
</div>
<div className="flex items-center justify-between gap-2 text-[11px] font-semibold text-[var(--text-muted)]">
<span className="min-w-0 truncate">{title}</span>
<span className="shrink-0 tabular-nums">
{Math.min(index + 1, total)}/{total}
</span>
</div>
</div>
</header>
<div
key={runId}
ref={scrollRef}
data-testid={testId ?? "session-feed"}
className="no-scrollbar h-full snap-y snap-mandatory overflow-y-scroll overscroll-y-contain [overflow-anchor:none]"
>
{items.map((item, itemIndex) => (
<section
key={`${item.deck.id}-${item.activity.id}-${runId}`}
aria-label={t("feed.activityOf", { n: itemIndex + 1, total })}
className="flex h-full snap-start snap-always items-stretch justify-center overflow-y-auto overscroll-y-contain"
>
<div className="mx-auto flex min-h-full w-full max-w-xl flex-col gap-4 px-4 pb-24 pt-24 [justify-content:safe_center]">
<ActivityRenderer
activity={item.activity}
active={index === itemIndex}
language={item.deck.language}
noHints={noHints}
onAnswered={(correct, meta) => handleAnswered(item, correct, meta)}
onNext={next}
isLast={itemIndex === total - 1}
nextLabel={itemIndex === total - 1 ? t("review.seeResults") : undefined}
/>
</div>
</section>
))}
<section
aria-label={t("review.results")}
className="flex h-full snap-start snap-always items-stretch justify-center overflow-y-auto overscroll-y-contain"
>
<div className="mx-auto flex min-h-full w-full max-w-xl flex-col gap-4 px-4 pb-24 pt-24 [justify-content:safe_center]">
{finished
? renderResults({ results, items, correct, total, score })
: (
<div className="card space-y-2 p-5 text-center">
<p className="text-sm font-semibold text-[var(--text-muted)]">{t("review.results")}</p>
<p className="text-[13px] text-[var(--text-subtle)]">{t("review.finishFirst")}</p>
</div>
)}
</div>
</section>
</div>
</div>
);
}
function formatClock(seconds: number): string {
const safe = Math.max(0, seconds);
const minutes = Math.floor(safe / 60);
return `${minutes}:${String(safe % 60).padStart(2, "0")}`;
}