freezmo/components/SessionFeed.tsx
Martin Dvorak 982391ca45 Codebase audit: fix bugs, performance issues, dead code, and edge cases
1. Bugs fixed:
- Backup schema now accepts theme: "aero" so backups exported under
  Frutiger Aero pass parseBackup on import, and applyImport in "replace"
  mode replaces SRS schedules, answer history, and chats instead of
  merging into existing SRS or skipping empty arrays.
- Typed FillBlank cards bind the input value to chosen ?? value instead
  of chosen ?? "", and normalise() preserves Unicode letters (\p{L}\p{N})
  when grading non-ASCII answers.
- OpenAI-compatible vision calls (contentFor in lib/openai-compat.ts)
  prefix data:image/jpeg;base64, when routes pass stripped base64.
- Streaming calls (ollamaChatStream, providerChatStream) keep their
  AbortController active across the entire body stream and API routes
  forward request.signal so stopping a chat or cancelling a run aborts
  the upstream request immediately.
- HomeworkCard uses homeworkModeLabelKey so "check" records display the
  Checked label instead of Step-by-step guide.
- Desktop dropzones on /create and /homework accept dropped documents as
  well as images.
- LibraryScreen filters reported questions out of its due and mistake
  counts to match ReviewClient.
- Clearing a provider key resets generation if it pointed at that
  provider; chat conversations persist and restore provider; ModelPicker
  keys items by provider:name.
- RouteTransition no longer mutates module-level lastPath during render.
- Service worker asset handler falls back to Response.error() when an
  uncached asset fetch fails offline.
- Confetti and .ice-orb / .ice-bubble respect the in-app reduce-motion
  toggle.

2. Performance & cleanup:
- Deduplicate window storage listeners across all six localStorage
  stores (one listener while subscribed instead of N^2 notifications).
- Use todayAnswerCount in LibraryScreen and pass sorted folders to
  DeckCard.
- Memoize MessageRow with stable callbacks in ChatScreen and compute
  last message IDs in a single pass.
- Close ImageBitmap after drawing in lib/image.ts and destroy pdf.js
  documents in finally in lib/documents.ts.
- Avoid re-parsing serialized sync payloads in POST /api/sync.
- Deduplicate copyText (lib/share.ts -> lib/clipboard.ts), chatMessageId,
  describeExtraction, ALL_FOLDERS, useIsPhone, and remove unused helpers
  and boilerplate public/*.svg files.

Version 0.5.8, SW -> freezmo-v80.
2026-10-14 19:00:17 +00:00

270 lines
10 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { ActivityRenderer } from "@/components/activities";
import { AiDisclaimer } from "@/components/AiDisclaimer";
import { XIcon } from "@/components/icons";
import { ReportQuestionButton } from "@/components/ReportQuestionButton";
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>>({});
/** Ids reported during this run: skipped, so they are not "missed". */
const [skipped, setSkipped] = useState<string[]>([]);
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) => !skipped.includes(item.activity.id) && results[item.activity.id]?.correct).length;
/** What the results slide counts: reported cards were never attempted. */
const attemptedTotal = Math.max(0, total - skipped.length);
const score = attemptedTotal > 0 ? Math.round((correct / attemptedTotal) * 100) : 0;
return (
<div className="frost-bg overlay-open fixed inset-0 z-[45] flex flex-col fade-in-mobile">
{/* Same pill as the study feed: round close button, title + position
above the bar, timer at the other end (nothing crowds the ends). */}
<header className="pt-safe absolute inset-x-0 top-0 z-30 px-3">
<div className="study-chrome mx-auto flex max-w-xl items-center gap-2.5 rounded-full px-2.5 py-2">
<button
type="button"
onClick={onExit}
aria-label={t("feed.back")}
title={t("feed.back")}
className="grid size-10 shrink-0 place-items-center rounded-full bg-[var(--surface-sunken)] text-[var(--text)] transition hover:bg-[var(--hover)]"
>
<XIcon className="size-4" />
</button>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-3">
<span className="min-w-0 truncate text-[13px] font-semibold leading-tight text-[var(--text)]">
{title}
</span>
<span className="shrink-0 text-[11.5px] font-bold tabular-nums text-[var(--text-muted)]">
{Math.min(index + 1, total)}/{total}
</span>
</div>
<ProgressBar
className="mt-1.5"
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-full px-3 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>
</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] [&>*]:shrink-0">
<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}
/>
{/* Under the card: disclaimer centred, report control in the
bottom-right corner (it used to sit in the top chrome). */}
{!finished && index === itemIndex ? (
<div className="grid grid-cols-[2.75rem_1fr_2.75rem] items-center gap-3">
<span aria-hidden />
<AiDisclaimer />
<div className="flex justify-end">
<ReportQuestionButton
deckId={item.deck.id}
deckTitle={item.deck.title}
activity={item.activity}
onSkip={() => {
setSkipped((current) => [...current, item.activity.id]);
goTo(itemIndex + 1);
}}
/>
</div>
</div>
) : (
<AiDisclaimer />
)}
</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] [&>*]:shrink-0">
{finished
? (
<>
{renderResults({ results, items, correct, total: attemptedTotal, score })}
<AiDisclaimer />
</>
)
: (
<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")}`;
}