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.
This commit is contained in:
parent
303e73f555
commit
982391ca45
57 changed files with 714 additions and 497 deletions
29
README.md
29
README.md
|
|
@ -1423,6 +1423,35 @@ Things I chose while building, with the reasoning:
|
|||
(measured: 268..1280 at a 1280 window) — a flat pane floating 40px inside the scene read as
|
||||
"cut off next to the sidebar".
|
||||
|
||||
89. **Codebase-wide audit (bugs, performance, dead code, edge cases).**
|
||||
- *Bugs fixed:* Backup schema now accepts `theme: "aero"` (backups exported under Frutiger Aero
|
||||
used to fail `parseBackup` on import), and `applyImport` in `"replace"` mode now replaces SRS
|
||||
schedules, answer history and chats instead of merging into existing SRS or skipping empty
|
||||
arrays; typed `FillBlank` cards (without word-bank options) now bind the `<input>` to the live
|
||||
typed state (`chosen ?? value` instead of `chosen ?? ""`) and preserve non-ASCII Unicode
|
||||
letters (`\p{L}\p{N}`) when checking answers; OpenAI-compatible vision calls (`contentFor` in
|
||||
`lib/openai-compat.ts`) now prefix `data:image/jpeg;base64,` when routes pass stripped base64;
|
||||
streaming calls (`ollamaChatStream`, `providerChatStream`) keep their `AbortController`
|
||||
attached for 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 show "Checked" instead of "Step-by-step guide";
|
||||
desktop dropzones on `/create` and `/homework` accept dropped documents as well as images;
|
||||
`LibraryScreen` excludes reported questions from its due and mistake counts (matching
|
||||
`ReviewClient`); clearing a provider key resets `generation` if it pointed at that provider,
|
||||
chat conversations persist and restore `provider`, and `ModelPicker` keys items by
|
||||
`provider:name`; `RouteTransition` no longer mutates module-level `lastPath` during render;
|
||||
`public/sw.js` falls back to `Response.error()` when an uncached asset fetch fails offline;
|
||||
confetti and `.ice-orb`/`.ice-bubble` respect the in-app `reduce-motion` class.
|
||||
- *Performance & cleanup:* The six `localStorage` stores now attach a single `storage` listener
|
||||
while subscribed instead of one per subscriber (avoiding $N^2$ notifications and $N\times$ JSON
|
||||
parses); `LibraryScreen` uses `todayAnswerCount` instead of building the full 35-day stats
|
||||
object on every render and passes sorted `folders` down to `DeckCard`; `MessageRow` is wrapped
|
||||
in `React.memo` with stable callbacks so streaming tokens only re-render the active message;
|
||||
`prepareImageFromBlob` closes its `ImageBitmap` and `extractPdf` destroys the `pdf.js`
|
||||
document proxy in `finally`; `POST /api/sync` no longer re-parses the serialized sync blob;
|
||||
`lib/share.ts` reuses `copyText` from `lib/clipboard.ts` (including its HTTP LAN fallback);
|
||||
and unused helpers and `create-next-app` SVG placeholders in `public/` were removed.
|
||||
|
||||
88. **A custom 404, Frutiger Aero style.** Unknown URLs used to fall through to Next's default
|
||||
"This page could not be found". `app/not-found.tsx` now renders a standalone screen — the root
|
||||
layout's ice scene is the backdrop, and the glass card, the rim and the rising bubbles come from
|
||||
|
|
|
|||
|
|
@ -87,6 +87,9 @@ export async function POST(request: Request) {
|
|||
if ("response" in gate) return gate.response;
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), config.timeoutMs);
|
||||
const onRequestAbort = () => abort.abort();
|
||||
if (request.signal.aborted) abort.abort();
|
||||
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
|
||||
try {
|
||||
if (images.length === 0) {
|
||||
// Plain text needs no model call at all.
|
||||
|
|
@ -117,6 +120,7 @@ export async function POST(request: Request) {
|
|||
);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -158,6 +158,9 @@ export async function POST(request: Request) {
|
|||
const encode = encoder();
|
||||
const abort = new AbortController();
|
||||
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs);
|
||||
const onRequestAbort = () => abort.abort();
|
||||
if (request.signal.aborted) abort.abort();
|
||||
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
|
|
@ -208,6 +211,7 @@ export async function POST(request: Request) {
|
|||
}
|
||||
} finally {
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
try {
|
||||
controller.close();
|
||||
|
|
@ -218,6 +222,7 @@ export async function POST(request: Request) {
|
|||
},
|
||||
cancel() {
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
abort.abort();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -131,6 +131,9 @@ export async function POST(request: Request) {
|
|||
const abort = new AbortController();
|
||||
// A single hard deadline for the whole pipeline (two sequential model calls).
|
||||
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2);
|
||||
const onRequestAbort = () => abort.abort();
|
||||
if (request.signal.aborted) abort.abort();
|
||||
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
|
||||
// Heartbeats: one quiet model call can run for minutes, and the client's
|
||||
// stall guard needs to tell "slow" from "dead" — a silent stream is how the
|
||||
// wizard ended up loading forever. Cleared with the stream either way.
|
||||
|
|
@ -234,6 +237,7 @@ export async function POST(request: Request) {
|
|||
} finally {
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
try {
|
||||
controller.close();
|
||||
|
|
@ -245,6 +249,7 @@ export async function POST(request: Request) {
|
|||
cancel() {
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
abort.abort();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -81,6 +81,11 @@ export async function POST(request: Request) {
|
|||
|
||||
const gate = acquireModelGate(request, config, locale);
|
||||
if ("response" in gate) return gate.response;
|
||||
const abort = new AbortController();
|
||||
const timer = setTimeout(() => abort.abort(), Math.min(config.timeoutMs, 180_000));
|
||||
const onRequestAbort = () => abort.abort();
|
||||
if (request.signal.aborted) abort.abort();
|
||||
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
|
||||
try {
|
||||
const text = await refineHomeworkText({
|
||||
model: textModel,
|
||||
|
|
@ -89,6 +94,7 @@ export async function POST(request: Request) {
|
|||
instruction: parsed.data.instruction,
|
||||
text: parsed.data.text,
|
||||
context: parsed.data.context,
|
||||
signal: abort.signal,
|
||||
});
|
||||
return Response.json(
|
||||
{ text, model: provider ? textModel : resolveModelName(config.textModel, baseAuth.directCloud) },
|
||||
|
|
@ -105,6 +111,8 @@ export async function POST(request: Request) {
|
|||
{ status: 502 },
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,6 +124,9 @@ export async function POST(request: Request) {
|
|||
const abort = new AbortController();
|
||||
// A single hard deadline for the whole pipeline (two sequential model calls).
|
||||
const globalTimer = setTimeout(() => abort.abort(), config.timeoutMs * 2);
|
||||
const onRequestAbort = () => abort.abort();
|
||||
if (request.signal.aborted) abort.abort();
|
||||
else request.signal.addEventListener("abort", onRequestAbort, { once: true });
|
||||
// Heartbeats so the client's stall guard can tell "slow" from "dead".
|
||||
let heartbeat: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
|
|
@ -291,6 +294,7 @@ export async function POST(request: Request) {
|
|||
} finally {
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
try {
|
||||
controller.close();
|
||||
|
|
@ -302,6 +306,7 @@ export async function POST(request: Request) {
|
|||
cancel() {
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
clearTimeout(globalTimer);
|
||||
request.signal.removeEventListener("abort", onRequestAbort);
|
||||
gate.gate.release();
|
||||
abort.abort();
|
||||
},
|
||||
|
|
|
|||
|
|
@ -144,7 +144,8 @@ export async function POST(request: Request) {
|
|||
}
|
||||
|
||||
const file = fileFor(config.sync.dir, parsed.data.id);
|
||||
const serialised = JSON.stringify({ updatedAt: Date.now(), envelope: parsed.data.envelope });
|
||||
const updatedAt = Date.now();
|
||||
const serialised = JSON.stringify({ updatedAt, envelope: parsed.data.envelope });
|
||||
|
||||
// Total storage cap, checked only when a new blob is created.
|
||||
const exists = await fs
|
||||
|
|
@ -162,7 +163,6 @@ export async function POST(request: Request) {
|
|||
}
|
||||
|
||||
await writeAtomic(file, serialised);
|
||||
const updatedAt = (JSON.parse(serialised) as { updatedAt: number }).updatedAt;
|
||||
return Response.json({ updatedAt }, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1597,10 +1597,6 @@ body:has(.overlay-open) :is(.app-header, .segmented, .tabbar, .cookie-notice) {
|
|||
.fade-in-mobile { animation: none; }
|
||||
}
|
||||
|
||||
@media (display-mode: standalone) {
|
||||
.standalone-hide { display: none }
|
||||
}
|
||||
|
||||
/* Phones: Apple's 44px minimum for touch targets. The class is a no-op on
|
||||
desktop (and on tablets), so components can carry it unconditionally. */
|
||||
@media (max-width: 639px) {
|
||||
|
|
@ -1657,7 +1653,17 @@ html.reduce-motion .ice-blob,
|
|||
html.reduce-motion .ice-orb,
|
||||
html.reduce-motion .ice-bubble {
|
||||
animation: none !important;
|
||||
will-change: auto;
|
||||
}
|
||||
html.reduce-motion.aero .ice-bubble {
|
||||
opacity: 0.55;
|
||||
transform: translate3d(0, -60vh, 0);
|
||||
}
|
||||
html.reduce-motion .ice-orb-1 { top: 14%; left: 12%; }
|
||||
html.reduce-motion .ice-orb-2 { top: 58%; left: 4%; }
|
||||
html.reduce-motion .ice-orb-3 { top: auto; bottom: -70px; right: 10%; }
|
||||
html.reduce-motion .ice-orb-4 { top: 24%; right: 28%; }
|
||||
html.reduce-motion .ice-orb-5 { top: auto; bottom: 16%; left: 38%; }
|
||||
html.reduce-motion *,
|
||||
html.reduce-motion *::before,
|
||||
html.reduce-motion *::after {
|
||||
|
|
|
|||
|
|
@ -119,11 +119,7 @@ export function DataSection() {
|
|||
<span className="min-w-0">
|
||||
<span className="block text-[12px] font-semibold text-[var(--text)]">{t("settings.storage")}</span>
|
||||
<span className="block text-[11px] leading-snug text-[var(--text-subtle)]">
|
||||
{persistence === "persistent"
|
||||
? t("settings.storagePersistent")
|
||||
: persistence === "unsupported"
|
||||
? t("settings.storageBestEffort")
|
||||
: t("settings.storageBestEffort")}
|
||||
{persistence === "persistent" ? t("settings.storagePersistent") : t("settings.storageBestEffort")}
|
||||
</span>
|
||||
</span>
|
||||
{persistence === "best-effort" ? (
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { createFolder as makeFolder, listFolders } from "@/lib/folders";
|
|||
import { haptic } from "@/lib/haptics";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { springGentle } from "@/lib/motion";
|
||||
import { UNORGANIZED_ID, type Deck } from "@/lib/schemas";
|
||||
import { UNORGANIZED_ID, type Deck, type Folder } from "@/lib/schemas";
|
||||
import { shareDeck } from "@/lib/share";
|
||||
import { appendActivities, deleteDeck, deleteNotesText, downloadDeck, renameDeck, upsertDeck } from "@/lib/storage";
|
||||
import { showToast } from "@/lib/toast";
|
||||
|
|
@ -30,17 +30,19 @@ const ADD_OPTIONS = [3, 5, 8];
|
|||
*/
|
||||
export function DeckCard({
|
||||
deck,
|
||||
folders: foldersProp,
|
||||
onMove,
|
||||
index = 0,
|
||||
}: {
|
||||
deck: Deck;
|
||||
folders?: Folder[];
|
||||
onMove?: (folderId: string | undefined) => void;
|
||||
/** Position in the list — used for the capped first-load stagger. */
|
||||
index?: number;
|
||||
}) {
|
||||
const { t, plural } = useI18n();
|
||||
const isPhone = useIsPhone();
|
||||
const folders = listFolders();
|
||||
const folders = foldersProp ?? listFolders();
|
||||
const [busy, setBusy] = useState<Busy>(null);
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ import { useRef, useState } from "react";
|
|||
import { FolderIcon, PlusIcon } from "@/components/icons";
|
||||
import { createFolder } from "@/lib/folders";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { ALL_FOLDERS } from "@/lib/nav";
|
||||
import type { Folder } from "@/lib/schemas";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const ALL_FOLDERS = "all";
|
||||
export { ALL_FOLDERS };
|
||||
|
||||
/**
|
||||
* Folder switcher. Reads like a row of quiet pills (ChatGPT sidebar items):
|
||||
|
|
|
|||
|
|
@ -4,8 +4,9 @@ import { motion } from "framer-motion";
|
|||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
import { BoltIcon, ChevronDownIcon, PlayIcon, XIcon } from "@/components/icons";
|
||||
import { BoltIcon, CheckCircleIcon, ChevronDownIcon, PlayIcon, XIcon } from "@/components/icons";
|
||||
import { Button } from "@/components/ui";
|
||||
import { homeworkModeLabelKey } from "@/lib/homework";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { springGentle } from "@/lib/motion";
|
||||
import type { HomeworkRecord } from "@/lib/schemas";
|
||||
|
|
@ -70,8 +71,14 @@ export function HomeworkCard({
|
|||
</h2>
|
||||
<p className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[12.5px] text-[var(--text-subtle)]">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{record.mode === "make" ? <BoltIcon className="size-3.5" /> : <PlayIcon className="size-3.5" />}
|
||||
{t(record.mode === "make" ? "homework.history.made" : "homework.history.guide")}
|
||||
{record.mode === "make" ? (
|
||||
<BoltIcon className="size-3.5" />
|
||||
) : record.mode === "check" ? (
|
||||
<CheckCircleIcon className="size-3.5" />
|
||||
) : (
|
||||
<PlayIcon className="size-3.5" />
|
||||
)}
|
||||
{t(homeworkModeLabelKey(record.mode))}
|
||||
</span>
|
||||
<span aria-hidden>·</span>
|
||||
{formatDate(record.updatedAt)}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ import { createFolder, folderStore, renameFolder } from "@/lib/folders";
|
|||
import { deleteHomework, homeworkStore, sortHomework } from "@/lib/homework";
|
||||
import { learningStore } from "@/lib/history";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { computeStats, dueItems, mistakeItems } from "@/lib/learning";
|
||||
import { dueItems, mistakeItems, todayAnswerCount } from "@/lib/learning";
|
||||
import { isReported, reportStore } from "@/lib/question-reports";
|
||||
import { settingsStore } from "@/lib/settings";
|
||||
import { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav";
|
||||
import { springGentle, springSheet } from "@/lib/motion";
|
||||
|
|
@ -110,17 +111,30 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
|
|||
() => settingsStore.getSnapshot().dailyGoal,
|
||||
() => 20,
|
||||
);
|
||||
/* Smart-review counts resolve against the live deck list: deleting a deck
|
||||
must drop its due schedules and its mistakes right away. `dueCount` is not
|
||||
used directly because it counts raw schedules, including decks that no
|
||||
longer exist. */
|
||||
const deckIds = useMemo(() => new Set(decks.map((deck) => deck.id)), [decks]);
|
||||
const due = useMemo(() => dueItems(srs).filter((item) => deckIds.has(item.deck.id)).length, [srs, deckIds]);
|
||||
const mistakes = useMemo(
|
||||
() => mistakeItems(answers).filter((item) => deckIds.has(item.deck.id)).length,
|
||||
[answers, deckIds],
|
||||
const reports = useSyncExternalStore(
|
||||
reportStore.subscribe,
|
||||
reportStore.getSnapshot,
|
||||
reportStore.getServerSnapshot,
|
||||
);
|
||||
const todayCount = useMemo(() => computeStats(answers).todayCount, [answers]);
|
||||
/* Smart-review counts resolve against the live deck list and reported set:
|
||||
deleting a deck or reporting a question must drop its due schedules and
|
||||
its mistakes right away, matching ReviewClient. */
|
||||
const deckIds = useMemo(() => new Set(decks.map((deck) => deck.id)), [decks]);
|
||||
const due = useMemo(
|
||||
() => {
|
||||
void reports;
|
||||
return dueItems(srs).filter((item) => deckIds.has(item.deck.id) && !isReported(item.deck.id, item.activity.id)).length;
|
||||
},
|
||||
[srs, deckIds, reports],
|
||||
);
|
||||
const mistakes = useMemo(
|
||||
() => {
|
||||
void reports;
|
||||
return mistakeItems(answers).filter((item) => deckIds.has(item.deck.id) && !isReported(item.deck.id, item.activity.id)).length;
|
||||
},
|
||||
[answers, deckIds, reports],
|
||||
);
|
||||
const todayCount = useMemo(() => todayAnswerCount(answers), [answers]);
|
||||
const importRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const sorted = useMemo(() => sortDecks(decks), [decks]);
|
||||
|
|
@ -512,6 +526,7 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
|
|||
<DeckCard
|
||||
key={deck.id}
|
||||
deck={deck}
|
||||
folders={folderList}
|
||||
index={index}
|
||||
onMove={(folderId) => {
|
||||
upsertDeck({ ...deck, folderId });
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
import { motion } from "framer-motion";
|
||||
import { useAppReducedMotion as useReducedMotion } from "@/lib/motion-pref";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { screenVariants, tabVariants } from "@/lib/motion";
|
||||
|
||||
|
|
@ -31,12 +32,18 @@ export function RouteTransition({ children }: { children: React.ReactNode }) {
|
|||
const pathname = usePathname();
|
||||
const reduceMotion = useReducedMotion();
|
||||
|
||||
const previous = lastPath;
|
||||
lastPath = pathname;
|
||||
const [{ isTabSwitch, direction }] = useState(() => {
|
||||
const previous = typeof window === "undefined" ? null : lastPath;
|
||||
return {
|
||||
isTabSwitch: previous !== null && depth(previous) === depth(pathname) && previous !== pathname,
|
||||
direction: (previous === null || depth(pathname) >= depth(previous) ? 1 : -1) as 1 | -1,
|
||||
};
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
lastPath = pathname;
|
||||
}, [pathname]);
|
||||
|
||||
const isTabSwitch = previous !== null && depth(previous) === depth(pathname) && previous !== pathname;
|
||||
const direction: 1 | -1 =
|
||||
previous === null || depth(pathname) >= depth(previous) ? 1 : -1;
|
||||
const variants = isTabSwitch ? tabVariants(!!reduceMotion) : screenVariants(direction, !!reduceMotion);
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ export function SessionFeed({
|
|||
);
|
||||
|
||||
const finished = index >= total;
|
||||
const correct = items.filter((item) => results[item.activity.id]?.correct).length;
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { ProvidersSection } from "@/components/ProvidersSection";
|
|||
import { SyncSection } from "@/components/SyncSection";
|
||||
import { clearApiKey, saveSettings, settingsStore } from "@/lib/settings";
|
||||
import { useBackClose } from "@/lib/use-back-close";
|
||||
import { useIsPhone } from "@/lib/use-phone";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { openInstallSheet, useInstallAvailable } from "@/lib/install";
|
||||
import { useHealth } from "@/lib/use-health";
|
||||
|
|
@ -84,21 +85,13 @@ export function SettingsDialog({
|
|||
const [saved, setSaved] = useState(false);
|
||||
const [confirmRemove, setConfirmRemove] = useState(false);
|
||||
const [canScroll, setCanScroll] = useState(false);
|
||||
const [phone, setPhone] = useState(false);
|
||||
// Swipe-to-dismiss is a phone gesture; the desktop dialog is unchanged.
|
||||
const phone = useIsPhone();
|
||||
const dragControls = useDragControls();
|
||||
const reduceMotion = useReducedMotion();
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Swipe-to-dismiss is a phone gesture; the desktop dialog is unchanged.
|
||||
useEffect(() => {
|
||||
const query = window.matchMedia("(max-width: 639px)");
|
||||
const sync = () => setPhone(query.matches);
|
||||
sync();
|
||||
query.addEventListener("change", sync);
|
||||
return () => query.removeEventListener("change", sync);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setKeyDraft(apiKey);
|
||||
|
|
|
|||
|
|
@ -113,19 +113,25 @@ export function StudyFeed({ deck }: { deck: Deck }) {
|
|||
if (!retryMode && !recordedRef.current) {
|
||||
recordedRef.current = true;
|
||||
const answered = Object.values(results);
|
||||
const correct = answered.filter((entry) => entry.correct).length;
|
||||
const correct = queue.filter((activity) => !skipped.includes(activity.id) && results[activity.id]?.correct).length;
|
||||
const attempted = Math.max(0, total - skipped.length);
|
||||
const score = attempted > 0 ? (correct / attempted) * 100 : 0;
|
||||
// Only a run with at least one answer counts. Without this, the scroll
|
||||
// anchoring shift when a regenerated deck swaps in could fire a bogus
|
||||
// 0% attempt before the feed had snapped back to the first slide.
|
||||
if (answered.length > 0) {
|
||||
recordAttempt(currentDeck.id, { scorePercent: score, correct, total });
|
||||
recordAttempt(currentDeck.id, { scorePercent: score, correct, total: attempted });
|
||||
setCurrentDeck((prev) => ({
|
||||
...prev,
|
||||
attempts: prev.attempts + 1,
|
||||
bestScore: Math.max(prev.bestScore ?? 0, Math.round(score)),
|
||||
updatedAt: Date.now(),
|
||||
}));
|
||||
haptic("celebrate");
|
||||
void celebrate("big");
|
||||
}
|
||||
}
|
||||
}, [finished, results, total, skipped.length, currentDeck.id, retryMode]);
|
||||
}, [finished, queue, results, total, skipped, currentDeck.id, retryMode]);
|
||||
|
||||
const handleAnswered = useCallback(
|
||||
(activity: Activity, correct: boolean, meta?: { userAnswer?: string }) => {
|
||||
|
|
@ -166,8 +172,8 @@ export function StudyFeed({ deck }: { deck: Deck }) {
|
|||
const attemptedTotal = Math.max(0, total - skipped.length);
|
||||
|
||||
const correctCount = useMemo(
|
||||
() => queue.filter((activity) => results[activity.id]?.correct).length,
|
||||
[queue, results],
|
||||
() => queue.filter((activity) => !skipped.includes(activity.id) && results[activity.id]?.correct).length,
|
||||
[queue, results, skipped],
|
||||
);
|
||||
|
||||
const restart = useCallback(
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
DOCUMENT_ACCEPT_ATTR,
|
||||
KIND_LABELS,
|
||||
describeDocumentError,
|
||||
describeExtraction,
|
||||
documentKindOf,
|
||||
documentsToText,
|
||||
extractDocument,
|
||||
|
|
@ -71,20 +72,6 @@ const MAX_IMAGES_TO_SEND = 12;
|
|||
/** Cap for the merged text sent to the API. */
|
||||
const MAX_TEXT_TO_SEND = 100_000;
|
||||
|
||||
function describeExtraction(
|
||||
document: ExtractedDocument,
|
||||
tr: (key: string, vars?: Record<string, string | number>) => string,
|
||||
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
|
||||
): string {
|
||||
const parts = [
|
||||
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
|
||||
document.pages ? pl(document.pages, "upload.pages") : "",
|
||||
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
|
||||
document.truncated ? tr("upload.truncated") : "",
|
||||
];
|
||||
return parts.filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
const DIFFICULTIES: Array<{ value: Difficulty; labelKey: string; icon: React.ReactNode; blurbKey: string }> = [
|
||||
{ value: "easy", labelKey: "upload.easy", icon: <SunIcon className="size-5" />, blurbKey: "upload.easyBlurb" },
|
||||
{
|
||||
|
|
@ -1106,7 +1093,8 @@ export function UploadScreen() {
|
|||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(false);
|
||||
void addFiles(imageFilesFromDataTransfer(event.dataTransfer));
|
||||
const dropped = Array.from(event.dataTransfer?.files ?? []);
|
||||
void addFiles(dropped.length > 0 ? dropped : imageFilesFromDataTransfer(event.dataTransfer));
|
||||
}}
|
||||
className={cn(
|
||||
"card relative overflow-hidden p-4 transition-all sm:p-5",
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ function normalise(value: string): string {
|
|||
.toLowerCase()
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^a-z0-9\s]/g, " ")
|
||||
.replace(/[^\p{L}\p{N}\s]/gu, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
|
@ -89,7 +89,7 @@ export function FillBlank({ activity, active, onAnswered, onNext, isLast, nextLa
|
|||
onAnswered(correct, { userAnswer: answerValue });
|
||||
};
|
||||
|
||||
const displayAnswer = chosen ?? "";
|
||||
const displayAnswer = chosen ?? value;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
|
|||
|
|
@ -20,7 +20,13 @@ type OrderingActivity = Extract<Activity, { type: "ordering" }>;
|
|||
|
||||
export function Ordering({ activity, onAnswered, onNext, isLast, nextLabel }: ActivityComponentProps<OrderingActivity>) {
|
||||
const { t } = useI18n();
|
||||
const initial = useMemo(() => shuffle(activity.items), [activity]);
|
||||
const initial = useMemo(() => {
|
||||
const out = shuffle(activity.items);
|
||||
if (out.length > 1 && out.every((item, index) => item === activity.items[index])) {
|
||||
[out[0], out[1]] = [out[1], out[0]];
|
||||
}
|
||||
return out;
|
||||
}, [activity]);
|
||||
const [items, setItems] = useState<string[]>(initial);
|
||||
const [checked, setChecked] = useState(false);
|
||||
const [correct, setCorrect] = useState(false);
|
||||
|
|
|
|||
|
|
@ -116,6 +116,10 @@ export function ChatScreen() {
|
|||
/* History: hydrate once, then open ?c=<id> conversations. */
|
||||
useEffect(() => {
|
||||
void ensureChatsHydrated();
|
||||
return () => {
|
||||
abortRef.current?.abort();
|
||||
chatActive.set(null);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadedRef = useRef<string | null>(null);
|
||||
|
|
@ -129,7 +133,7 @@ export function ChatScreen() {
|
|||
setDraft("");
|
||||
setError(null);
|
||||
if (found.model) setModel(found.model);
|
||||
if ((found as { provider?: string }).provider) setProvider((found as { provider?: string }).provider ?? "ollama");
|
||||
if (found.provider) setProvider(found.provider);
|
||||
loadedRef.current = found.id;
|
||||
chatActive.set(found.id);
|
||||
}, []);
|
||||
|
|
@ -188,15 +192,23 @@ export function ChatScreen() {
|
|||
return [...ollama, ...cloud];
|
||||
}, [health, providerState]);
|
||||
|
||||
const activeProvider = provider !== "ollama" && !providerState.keys[provider] ? "ollama" : provider;
|
||||
|
||||
const activeModel = useMemo(() => {
|
||||
if (model && chatModels.some((entry) => entry.name === model && (entry.provider ?? "ollama") === provider)) return model;
|
||||
const sameProvider = chatModels.find((entry) => (entry.provider ?? "ollama") === provider && entry.available !== false);
|
||||
if (model && sameProvider?.name === model) return model;
|
||||
if (model && chatModels.some((entry) => entry.name === model && (entry.provider ?? "ollama") === activeProvider)) {
|
||||
return model;
|
||||
}
|
||||
// The server puts the default first, but a different server may not have
|
||||
// it — fall back to the first model that is actually available.
|
||||
const firstAvailable = chatModels.find((entry) => (entry.provider ?? "ollama") === provider && entry.available !== false);
|
||||
return (firstAvailable ?? chatModels.find((entry) => (entry.provider ?? "ollama") === provider) ?? chatModels[0])?.name ?? model;
|
||||
}, [model, chatModels, provider]);
|
||||
const firstAvailable = chatModels.find(
|
||||
(entry) => (entry.provider ?? "ollama") === activeProvider && entry.available !== false,
|
||||
);
|
||||
return (
|
||||
firstAvailable ??
|
||||
chatModels.find((entry) => (entry.provider ?? "ollama") === activeProvider) ??
|
||||
chatModels[0]
|
||||
)?.name ?? model;
|
||||
}, [model, chatModels, activeProvider]);
|
||||
|
||||
const scopeText = useMemo(() => {
|
||||
if (scope.kind === "all") return t("chat.scope.all");
|
||||
|
|
@ -266,7 +278,10 @@ export function ChatScreen() {
|
|||
};
|
||||
|
||||
const persist = useCallback(
|
||||
(nextMessages: ChatMessage[], options: { title?: string; model?: string; scope?: ChatScope } = {}) => {
|
||||
(
|
||||
nextMessages: ChatMessage[],
|
||||
options: { title?: string; model?: string; provider?: string; scope?: ChatScope } = {},
|
||||
) => {
|
||||
const id = conversationId ?? chatMessageId("chat");
|
||||
if (!conversationId) {
|
||||
setConversationId(id);
|
||||
|
|
@ -285,12 +300,13 @@ export function ChatScreen() {
|
|||
messages: nextMessages,
|
||||
scope: options.scope ?? scope,
|
||||
model: options.model ?? (activeModel || undefined),
|
||||
provider: options.provider ?? activeProvider,
|
||||
createdAt: existing?.createdAt ?? Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
if (nextTitle && nextTitle !== title) setTitle(nextTitle);
|
||||
},
|
||||
[conversationId, title, scope, activeModel],
|
||||
[conversationId, title, scope, activeModel, activeProvider],
|
||||
);
|
||||
|
||||
const run = async (history: ChatMessage[], extraChunks: ExtraChunk[]) => {
|
||||
|
|
@ -321,7 +337,7 @@ export function ChatScreen() {
|
|||
try {
|
||||
await streamChat({
|
||||
model: activeModel || undefined,
|
||||
provider,
|
||||
provider: activeProvider,
|
||||
messages: history.map((message) => ({ role: message.role, content: message.content })),
|
||||
context: context.chunks.map(({ deckId, deckTitle, section, text }) => ({ deckId, deckTitle, section, text })),
|
||||
signal: controller.signal,
|
||||
|
|
@ -412,28 +428,24 @@ export function ChatScreen() {
|
|||
void run(history, extras);
|
||||
};
|
||||
|
||||
const retryLast = () => {
|
||||
const retryLast = useCallback(() => {
|
||||
if (busy) return;
|
||||
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user");
|
||||
if (lastUserIndex < 0) return;
|
||||
const history = messages.slice(0, lastUserIndex + 1);
|
||||
setError(null);
|
||||
setMessages(history);
|
||||
void run(history, extrasRef.current[history[lastUserIndex].id] ?? []);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [busy, messages]);
|
||||
|
||||
const regenerate = () => {
|
||||
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user");
|
||||
if (lastUserIndex < 0) return;
|
||||
const history = messages.slice(0, lastUserIndex + 1);
|
||||
setMessages(history);
|
||||
void run(history, extrasRef.current[history[lastUserIndex].id] ?? []);
|
||||
};
|
||||
|
||||
const editLast = () => {
|
||||
const editLast = useCallback(() => {
|
||||
if (busy) return;
|
||||
const lastUserIndex = messages.map((message) => message.role).lastIndexOf("user");
|
||||
if (lastUserIndex < 0) return;
|
||||
setDraft(messages[lastUserIndex].content);
|
||||
setMessages(messages.slice(0, lastUserIndex));
|
||||
};
|
||||
}, [busy, messages]);
|
||||
|
||||
const resetView = useCallback(() => {
|
||||
abortRef.current?.abort();
|
||||
|
|
@ -498,28 +510,34 @@ export function ChatScreen() {
|
|||
return undefined;
|
||||
}, [scope, seed, decks]);
|
||||
|
||||
const saveToNotes = (message: ChatMessage) => {
|
||||
if (!noteTargetDeck) return;
|
||||
const current = noteTargetDeck.sourceText?.trim() ?? "";
|
||||
const addition = `\n\n— ${t("chat.savedFromChat")} —\n${message.content.trim()}`;
|
||||
let next = `${current}${addition}`;
|
||||
let trimmed = false;
|
||||
if (next.length > 40_000) {
|
||||
next = next.slice(-40_000);
|
||||
trimmed = true;
|
||||
}
|
||||
upsertDeck({ ...noteTargetDeck, sourceText: next, updatedAt: Date.now() });
|
||||
showToast({
|
||||
message: trimmed
|
||||
? t("chat.savedToNotesTrimmed", { deck: noteTargetDeck.title })
|
||||
: t("chat.savedToNotes", { deck: noteTargetDeck.title }),
|
||||
});
|
||||
};
|
||||
const saveToNotes = useCallback(
|
||||
(message: ChatMessage) => {
|
||||
if (!noteTargetDeck) return;
|
||||
const current = noteTargetDeck.sourceText?.trim() ?? "";
|
||||
const addition = `\n\n— ${t("chat.savedFromChat")} —\n${message.content.trim()}`;
|
||||
let next = `${current}${addition}`;
|
||||
let trimmed = false;
|
||||
if (next.length > 40_000) {
|
||||
next = next.slice(-40_000);
|
||||
trimmed = true;
|
||||
}
|
||||
upsertDeck({ ...noteTargetDeck, sourceText: next, updatedAt: Date.now() });
|
||||
showToast({
|
||||
message: trimmed
|
||||
? t("chat.savedToNotesTrimmed", { deck: noteTargetDeck.title })
|
||||
: t("chat.savedToNotes", { deck: noteTargetDeck.title }),
|
||||
});
|
||||
},
|
||||
[noteTargetDeck, t],
|
||||
);
|
||||
|
||||
const toFlashcards = (message: ChatMessage) => {
|
||||
setDeckSeed({ text: message.content.slice(0, 40_000), step: 2 });
|
||||
router.push("/create");
|
||||
};
|
||||
const toFlashcards = useCallback(
|
||||
(message: ChatMessage) => {
|
||||
setDeckSeed({ text: message.content.slice(0, 40_000), step: 2 });
|
||||
router.push("/create");
|
||||
},
|
||||
[router],
|
||||
);
|
||||
|
||||
const handleAttach = async (file: File) => {
|
||||
setAttachBusy(true);
|
||||
|
|
@ -545,9 +563,19 @@ export function ChatScreen() {
|
|||
}
|
||||
};
|
||||
|
||||
const lastAssistantId = [...messages].reverse().find((message) => message.role === "assistant")?.id;
|
||||
const lastUserId = [...messages].reverse().find((message) => message.role === "user")?.id;
|
||||
const lastFailedAssistant = [...messages].reverse().find((message) => message.role === "assistant" && message.error)?.id;
|
||||
let lastAssistantId: string | undefined;
|
||||
let lastUserId: string | undefined;
|
||||
let lastFailedAssistant: string | undefined;
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
const message = messages[i];
|
||||
if (message.role === "assistant") {
|
||||
if (!lastAssistantId) lastAssistantId = message.id;
|
||||
if (!lastFailedAssistant && message.error) lastFailedAssistant = message.id;
|
||||
} else if (!lastUserId) {
|
||||
lastUserId = message.id;
|
||||
}
|
||||
if (lastAssistantId && lastUserId && lastFailedAssistant) break;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 w-full">
|
||||
|
|
@ -659,11 +687,11 @@ export function ChatScreen() {
|
|||
isLastAssistant={message.id === lastAssistantId}
|
||||
isLastUser={message.id === lastUserId}
|
||||
busy={busy}
|
||||
onRegenerate={regenerate}
|
||||
onRegenerate={retryLast}
|
||||
onEdit={editLast}
|
||||
onRetry={message.id === lastFailedAssistant ? retryLast : undefined}
|
||||
onToFlashcards={() => toFlashcards(message)}
|
||||
onSaveNotes={noteTargetDeck ? () => saveToNotes(message) : undefined}
|
||||
onToFlashcards={toFlashcards}
|
||||
onSaveNotes={noteTargetDeck ? saveToNotes : undefined}
|
||||
/>
|
||||
</motion.div>
|
||||
))}
|
||||
|
|
@ -718,12 +746,12 @@ export function ChatScreen() {
|
|||
scopeLabel={scopeText}
|
||||
modelLabel={
|
||||
activeModel
|
||||
? provider !== "ollama"
|
||||
? `${providerInfo(provider)?.label ?? provider} · ${prettyModelName(activeModel)}`
|
||||
? activeProvider !== "ollama"
|
||||
? `${providerInfo(activeProvider)?.label ?? activeProvider} · ${prettyModelName(activeModel)}`
|
||||
: prettyModelName(activeModel)
|
||||
: t("chat.modelTitle")
|
||||
}
|
||||
modelTitle={activeModel ? `${activeModel} · ${providerInfo(provider)?.label ?? provider}` : undefined}
|
||||
modelTitle={activeModel ? `${activeModel} · ${providerInfo(activeProvider)?.label ?? activeProvider}` : undefined}
|
||||
scopeOpen={scopeOpen}
|
||||
modelOpen={modelOpen}
|
||||
// The chips toggle their own popover (and open one at a time), so a
|
||||
|
|
@ -746,13 +774,14 @@ export function ChatScreen() {
|
|||
onClose={() => setModelOpen(false)}
|
||||
models={chatModels}
|
||||
value={activeModel}
|
||||
valueProvider={provider}
|
||||
valueProvider={activeProvider}
|
||||
onChange={(next, nextProvider) => {
|
||||
setProvider(nextProvider ?? "ollama");
|
||||
storeChatProvider(nextProvider ?? "ollama");
|
||||
const chosenProvider = nextProvider ?? "ollama";
|
||||
setProvider(chosenProvider);
|
||||
storeChatProvider(chosenProvider);
|
||||
setModel(next);
|
||||
storeChatModel(next);
|
||||
if (messages.length > 0) persist(messages, { model: next });
|
||||
if (messages.length > 0) persist(messages, { model: next, provider: chosenProvider });
|
||||
}}
|
||||
/>
|
||||
<ContextPicker
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { memo } from "react";
|
||||
|
||||
import { CopyIconButton } from "./CopyIconButton";
|
||||
import { Markdown } from "./Markdown";
|
||||
|
|
@ -15,7 +16,7 @@ import type { ChatMessage } from "@/lib/chat";
|
|||
* One turn: user bubbles on the right, assistant answers as full-width text
|
||||
* (no bubble) with the Thinking row, sources, actions and error recovery.
|
||||
*/
|
||||
export function MessageRow({
|
||||
export const MessageRow = memo(function MessageRow({
|
||||
message,
|
||||
streaming,
|
||||
isLastAssistant,
|
||||
|
|
@ -35,8 +36,8 @@ export function MessageRow({
|
|||
onRegenerate?: () => void;
|
||||
onEdit?: () => void;
|
||||
onRetry?: () => void;
|
||||
onToFlashcards?: () => void;
|
||||
onSaveNotes?: () => void;
|
||||
onToFlashcards?: (message: ChatMessage) => void;
|
||||
onSaveNotes?: (message: ChatMessage) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
|
||||
|
|
@ -117,7 +118,7 @@ export function MessageRow({
|
|||
{onToFlashcards ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToFlashcards}
|
||||
onClick={() => onToFlashcards(message)}
|
||||
className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
|
||||
>
|
||||
<SparklesIcon className="size-3.5" />
|
||||
|
|
@ -127,7 +128,7 @@ export function MessageRow({
|
|||
{onSaveNotes ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSaveNotes}
|
||||
onClick={() => onSaveNotes(message)}
|
||||
className="flex items-center gap-1.5 rounded-xl border border-[var(--glass-border)] bg-[var(--surface-strong)] px-2.5 py-2 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
|
|
@ -155,4 +156,4 @@ export function MessageRow({
|
|||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ export function ModelPicker({
|
|||
const selected = model.name === value && (model.provider ?? "ollama") === (valueProvider ?? "ollama");
|
||||
const unavailable = model.available === false;
|
||||
return (
|
||||
<li key={model.name}>
|
||||
<li key={`${model.provider ?? "ollama"}:${model.name}`}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={unavailable}
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ import { Button } from "@/components/ui";
|
|||
import { WizardActionBar } from "@/components/WizardActionBar";
|
||||
import {
|
||||
DOCUMENT_ACCEPT_ATTR,
|
||||
describeExtraction,
|
||||
documentsToText,
|
||||
type ExtractedDocument,
|
||||
} from "@/lib/documents";
|
||||
import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas";
|
||||
import { ACCEPTED_TYPES, formatBytes, imageFilesFromDataTransfer } from "@/lib/image";
|
||||
|
|
@ -31,21 +31,6 @@ import { cn, truncate } from "@/lib/utils";
|
|||
|
||||
import { HomeworkHistory } from "./HomeworkHistory";
|
||||
|
||||
/** Same wording the create screen uses for an extracted document. */
|
||||
function describeExtraction(
|
||||
document: ExtractedDocument,
|
||||
tr: (key: string, vars?: Record<string, string | number>) => string,
|
||||
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
|
||||
): string {
|
||||
const parts = [
|
||||
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
|
||||
document.pages ? pl(document.pages, "upload.pages") : "",
|
||||
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
|
||||
document.truncated ? tr("upload.truncated") : "",
|
||||
];
|
||||
return parts.filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
const MODES: Array<{ id: HomeworkMode; icon: React.ReactNode; titleKey: string; subtitleKey: string }> = [
|
||||
{ id: "make", icon: <SparklesIcon className="size-5" />, titleKey: "homework.mode.make.title", subtitleKey: "homework.mode.make.subtitle" },
|
||||
{ id: "guide", icon: <PlayIcon className="size-5" />, titleKey: "homework.mode.guide.title", subtitleKey: "homework.mode.guide.subtitle" },
|
||||
|
|
@ -95,6 +80,7 @@ export function HomeworkInput({
|
|||
const [pasteOpen, setPasteOpen] = useState(false);
|
||||
/** Phones: the check card reveals the solution field instead of starting. */
|
||||
const [checkOpen, setCheckOpen] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const isPhone = useIsPhone();
|
||||
const reduceMotion = useReducedMotion();
|
||||
const online = useOnline();
|
||||
|
|
@ -130,10 +116,9 @@ export function HomeworkInput({
|
|||
|
||||
/* Persist the typed assignment while the user works (debounced). */
|
||||
useEffect(() => {
|
||||
if (!isPhone) return;
|
||||
const timer = window.setTimeout(() => saveWizardDraft("homework", { text }), 400);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [text, isPhone]);
|
||||
}, [text]);
|
||||
|
||||
// Clipboard: screenshots become photos, long copied text becomes the assignment.
|
||||
useEffect(() => {
|
||||
|
|
@ -744,7 +729,23 @@ export function HomeworkInput({
|
|||
{errorCard}
|
||||
|
||||
{/* ------------------------------------------------ the assignment */}
|
||||
<section className="card p-4 sm:p-5">
|
||||
<section
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragging(false);
|
||||
const dropped = Array.from(event.dataTransfer?.files ?? []);
|
||||
void intake.addFiles(dropped.length > 0 ? dropped : imageFilesFromDataTransfer(event.dataTransfer));
|
||||
}}
|
||||
className={cn(
|
||||
"card p-4 transition-all sm:p-5",
|
||||
dragging && "border-frost-400 bg-frost-50 ring-4 ring-frost-200 dark:bg-frost-500/10 dark:ring-frost-500/30",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--text)]">
|
||||
|
|
|
|||
|
|
@ -259,10 +259,12 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
|
|||
}
|
||||
|
||||
if (view.kind === "record") {
|
||||
const recordKey = `${view.record.id}-${view.record.updatedAt}`;
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{view.record.mode === "make" ? (
|
||||
<HomeworkResult
|
||||
key={recordKey}
|
||||
record={view.record}
|
||||
onAgain={() => again(view.record)}
|
||||
onNew={newAssignment}
|
||||
|
|
@ -271,6 +273,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
|
|||
/>
|
||||
) : view.record.mode === "check" ? (
|
||||
<HomeworkCheckResult
|
||||
key={recordKey}
|
||||
record={view.record}
|
||||
onAgain={() => again(view.record)}
|
||||
onNew={newAssignment}
|
||||
|
|
@ -279,6 +282,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
|
|||
/>
|
||||
) : (
|
||||
<HomeworkGuide
|
||||
key={recordKey}
|
||||
record={view.record}
|
||||
onClose={() => setView({ kind: "start" })}
|
||||
onAgain={() => again(view.record)}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
|
||||
import { z } from "zod";
|
||||
|
||||
import { applyTheme } from "./theme";
|
||||
import { applyTheme, type Theme } from "./theme";
|
||||
import { chatHistoryStore, ensureChatsHydrated, replaceChats } from "./chat-store";
|
||||
import { replaceFolders, folderStore } from "./folders";
|
||||
import { homeworkStore, replaceHomework } from "./homework";
|
||||
|
|
@ -26,7 +26,7 @@ export const BACKUP_VERSION = 1;
|
|||
const settingsSchema = z.object({
|
||||
haptics: z.boolean().optional(),
|
||||
locale: z.enum(["en", "cs"]).optional(),
|
||||
theme: z.enum(["light", "dark"]).optional(),
|
||||
theme: z.enum(["light", "dark", "aero"]).optional(),
|
||||
dailyGoal: z.number().int().min(1).max(500).optional(),
|
||||
});
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ export async function buildBackup(): Promise<BackupFile> {
|
|||
haptics: settingsStore.getSnapshot().haptics,
|
||||
dailyGoal: settingsStore.getSnapshot().dailyGoal,
|
||||
locale: (window.localStorage.getItem("freezmo.locale.v1") as "en" | "cs" | null) ?? undefined,
|
||||
theme: (window.localStorage.getItem("freezmo.theme") as "light" | "dark" | null) ?? undefined,
|
||||
theme: (window.localStorage.getItem("freezmo.theme") as Theme | null) ?? undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -174,15 +174,18 @@ export async function applyImport(
|
|||
replaceDecks(decks);
|
||||
replaceHomework(homework);
|
||||
|
||||
// Answer log + schedule: merge by id (answers) and by key (schedules).
|
||||
// Answer log + schedule: merge by id (answers) and by key (schedules), or
|
||||
// replace wholesale when mode === "replace".
|
||||
await ensureLearningHydrated();
|
||||
const incomingAnswers = data.history ?? [];
|
||||
const incomingSrs = data.srs ?? [];
|
||||
if (incomingAnswers.length > 0 || incomingSrs.length > 0) {
|
||||
if (mode === "replace") {
|
||||
const srsByKey = new Map(incomingSrs.map((entry) => [entry.key, entry]));
|
||||
await replaceLearning(incomingAnswers, [...srsByKey.values()]);
|
||||
} else if (incomingAnswers.length > 0 || incomingSrs.length > 0) {
|
||||
const currentAnswers = learningStore.getAnswersSnapshot();
|
||||
const currentSrs = learningStore.getSrsSnapshot();
|
||||
const answers =
|
||||
mode === "replace" ? incomingAnswers : mergeById(currentAnswers, incomingAnswers);
|
||||
const answers = mergeById(currentAnswers, incomingAnswers);
|
||||
const srsByKey = new Map(currentSrs.map((entry) => [entry.key, entry]));
|
||||
for (const entry of incomingSrs) {
|
||||
const current = srsByKey.get(entry.key);
|
||||
|
|
@ -194,8 +197,10 @@ export async function applyImport(
|
|||
// Chat conversations: merge by id (newest wins) or replace wholesale.
|
||||
await ensureChatsHydrated();
|
||||
const incomingChats = data.chats ?? [];
|
||||
if (incomingChats.length > 0) {
|
||||
replaceChats(mode === "replace" ? incomingChats : mergeById(chatHistoryStore.getSnapshot(), incomingChats));
|
||||
if (mode === "replace") {
|
||||
replaceChats(incomingChats);
|
||||
} else if (incomingChats.length > 0) {
|
||||
replaceChats(mergeById(chatHistoryStore.getSnapshot(), incomingChats));
|
||||
}
|
||||
|
||||
const settings = data.settings;
|
||||
|
|
|
|||
|
|
@ -56,10 +56,10 @@ function openDb(): Promise<IDBDatabase> {
|
|||
});
|
||||
}
|
||||
|
||||
async function withDb<T>(mode: IDBTransactionMode, run: (db: IDBDatabase) => T): Promise<T> {
|
||||
async function withDb<T>(_mode: IDBTransactionMode, run: (db: IDBDatabase) => T | Promise<T>): Promise<T> {
|
||||
const db = await openDb();
|
||||
try {
|
||||
return run(db);
|
||||
return await run(db);
|
||||
} finally {
|
||||
window.setTimeout(() => db.close(), 1000);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
*/
|
||||
|
||||
import type { ChatAttachment, ChatMessage, ChatScope, ChatSource } from "./schemas";
|
||||
import { uid } from "./utils";
|
||||
|
||||
export type { ChatAttachment, ChatMessage, ChatScope, ChatSource };
|
||||
|
||||
|
|
@ -59,11 +60,7 @@ export function storeChatProvider(provider: string): void {
|
|||
}
|
||||
|
||||
export function chatMessageId(prefix: string): string {
|
||||
const rand =
|
||||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||||
? crypto.randomUUID().slice(0, 8)
|
||||
: Math.random().toString(36).slice(2, 10);
|
||||
return `${prefix}_${Date.now().toString(36)}_${rand}`;
|
||||
return uid(prefix);
|
||||
}
|
||||
|
||||
/** Auto title from the first user turn (markdown stripped, one line). */
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
"use client";
|
||||
|
||||
/** Confetti helper that respects prefers-reduced-motion. */
|
||||
/** Confetti helper that respects prefers-reduced-motion and the in-app toggle. */
|
||||
|
||||
export function prefersReducedMotion(): boolean {
|
||||
if (typeof window === "undefined" || !window.matchMedia) return false;
|
||||
if (typeof window === "undefined") return false;
|
||||
if (document.documentElement.classList.contains("reduce-motion")) return true;
|
||||
if (!window.matchMedia) return false;
|
||||
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
}
|
||||
|
||||
|
|
@ -35,22 +37,3 @@ export async function celebrate(intensity: "normal" | "big" = "normal"): Promise
|
|||
/* confetti is a nice-to-have */
|
||||
}
|
||||
}
|
||||
|
||||
export function burstAt(x: number, y: number): void {
|
||||
if (prefersReducedMotion()) return;
|
||||
void (async () => {
|
||||
try {
|
||||
const confetti = (await import("canvas-confetti")).default;
|
||||
confetti({
|
||||
particleCount: 40,
|
||||
spread: 55,
|
||||
startVelocity: 26,
|
||||
origin: { x: x / window.innerWidth, y: y / window.innerHeight },
|
||||
colors: ["#7ea6c2", "#aac6da", "#cfd8e3", "#ffffff"],
|
||||
disableForReducedMotion: true,
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
|
|
|||
120
lib/documents.ts
120
lib/documents.ts
|
|
@ -217,58 +217,65 @@ async function extractPdf(
|
|||
const images: PreparedImage[] = [];
|
||||
const warnings: string[] = [];
|
||||
let imagesTruncated = false;
|
||||
const numPages = document.numPages;
|
||||
|
||||
const totalPages = Math.min(document.numPages, 80);
|
||||
if (document.numPages > totalPages) {
|
||||
warnings.push(`Only the first ${totalPages} of ${document.numPages} pages were read.`);
|
||||
}
|
||||
|
||||
for (let pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
|
||||
onProgress?.({
|
||||
message: t("doc.readingPage", { n: pageNumber, total: totalPages }),
|
||||
progress: pageNumber / totalPages,
|
||||
});
|
||||
|
||||
const page = (await document.getPage(pageNumber)) as unknown as PdfPage;
|
||||
let pageText = "";
|
||||
try {
|
||||
const content = await page.getTextContent();
|
||||
pageText = textFromPdfItems(content.items);
|
||||
} catch {
|
||||
warnings.push(`Page ${pageNumber} text could not be extracted.`);
|
||||
try {
|
||||
const totalPages = Math.min(numPages, 80);
|
||||
if (numPages > totalPages) {
|
||||
warnings.push(`Only the first ${totalPages} of ${numPages} pages were read.`);
|
||||
}
|
||||
|
||||
if (pageText.trim().length >= SCANNED_PAGE_CHAR_THRESHOLD) {
|
||||
pages.push(`--- page ${pageNumber} ---\n${pageText.trim()}`);
|
||||
} else if (images.length < MAX_DOCUMENT_IMAGES) {
|
||||
// Scanned or image-only page: render it so the vision model can read it.
|
||||
for (let pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
|
||||
onProgress?.({
|
||||
message: t("doc.readingPage", { n: pageNumber, total: totalPages }),
|
||||
progress: pageNumber / totalPages,
|
||||
});
|
||||
|
||||
const page = (await document.getPage(pageNumber)) as unknown as PdfPage;
|
||||
let pageText = "";
|
||||
try {
|
||||
const viewport = page.getViewport({ scale: PDF_RENDER_SCALE });
|
||||
const canvas = window.document.createElement("canvas");
|
||||
canvas.width = Math.floor(viewport.width);
|
||||
canvas.height = Math.floor(viewport.height);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("no 2d context");
|
||||
context.fillStyle = "#ffffff";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
|
||||
if (blob) {
|
||||
images.push(await prepareImageFromBlob(blob, `${file.name} p${pageNumber}`));
|
||||
}
|
||||
const content = await page.getTextContent();
|
||||
pageText = textFromPdfItems(content.items);
|
||||
} catch {
|
||||
warnings.push(`Page ${pageNumber} looks scanned but could not be rendered.`);
|
||||
warnings.push(`Page ${pageNumber} text could not be extracted.`);
|
||||
}
|
||||
} else {
|
||||
imagesTruncated = true;
|
||||
}
|
||||
|
||||
if (pageText.trim().length < SCANNED_PAGE_CHAR_THRESHOLD) {
|
||||
// Nothing to add to the text; the image carries the content.
|
||||
imagesTruncated = images.length >= MAX_DOCUMENT_IMAGES;
|
||||
}
|
||||
if (pageText.trim().length >= SCANNED_PAGE_CHAR_THRESHOLD) {
|
||||
pages.push(`--- page ${pageNumber} ---\n${pageText.trim()}`);
|
||||
} else if (images.length < MAX_DOCUMENT_IMAGES) {
|
||||
// Scanned or image-only page: render it so the vision model can read it.
|
||||
try {
|
||||
const viewport = page.getViewport({ scale: PDF_RENDER_SCALE });
|
||||
const canvas = window.document.createElement("canvas");
|
||||
canvas.width = Math.floor(viewport.width);
|
||||
canvas.height = Math.floor(viewport.height);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("no 2d context");
|
||||
context.fillStyle = "#ffffff";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
|
||||
canvas.width = 0;
|
||||
canvas.height = 0;
|
||||
if (blob) {
|
||||
images.push(await prepareImageFromBlob(blob, `${file.name} p${pageNumber}`));
|
||||
}
|
||||
} catch {
|
||||
warnings.push(`Page ${pageNumber} looks scanned but could not be rendered.`);
|
||||
}
|
||||
} else {
|
||||
imagesTruncated = true;
|
||||
}
|
||||
|
||||
page.cleanup?.();
|
||||
if (pageText.trim().length < SCANNED_PAGE_CHAR_THRESHOLD) {
|
||||
// Nothing to add to the text; the image carries the content.
|
||||
imagesTruncated = images.length >= MAX_DOCUMENT_IMAGES;
|
||||
}
|
||||
|
||||
page.cleanup?.();
|
||||
}
|
||||
} finally {
|
||||
await (document as { destroy?: () => Promise<void> }).destroy?.().catch(() => {});
|
||||
}
|
||||
|
||||
if (images.length > 0) {
|
||||
|
|
@ -280,7 +287,7 @@ async function extractPdf(
|
|||
}
|
||||
|
||||
return withLimits(file.name, "pdf", pages.join("\n\n"), images, {
|
||||
pages: document.numPages,
|
||||
pages: numPages,
|
||||
warnings,
|
||||
imagesTruncated,
|
||||
});
|
||||
|
|
@ -342,14 +349,18 @@ async function extractDocx(file: File): Promise<ExtractedDocument> {
|
|||
const XML_TEXT_RUN = /<a:t[^>]*>([\s\S]*?)<\/a:t>/g;
|
||||
const XML_PARAGRAPH = /<\/a:p>/g;
|
||||
|
||||
function safeCodePoint(cp: number): string {
|
||||
return Number.isFinite(cp) && cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "";
|
||||
}
|
||||
|
||||
function decodeXmlEntities(value: string): string {
|
||||
return value
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code)))
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, code: string) => String.fromCodePoint(Number.parseInt(code, 16)))
|
||||
.replace(/&#(\d+);/g, (_, code: string) => safeCodePoint(Number(code)))
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, code: string) => safeCodePoint(Number.parseInt(code, 16)))
|
||||
.replace(/&/g, "&");
|
||||
}
|
||||
|
||||
|
|
@ -475,3 +486,18 @@ export function documentsToText(documents: ExtractedDocument[]): string {
|
|||
.join("\n\n")
|
||||
.slice(0, MAX_DOCUMENT_CHARS * 2);
|
||||
}
|
||||
|
||||
/** Human-readable summary line for an extracted document (words · pages · images). */
|
||||
export function describeExtraction(
|
||||
document: ExtractedDocument,
|
||||
tr: (key: string, vars?: Record<string, string | number>) => string,
|
||||
pl: (n: number, base: string, vars?: Record<string, string | number>) => string,
|
||||
): string {
|
||||
const parts = [
|
||||
pl(document.words, "upload.words", { n: document.words.toLocaleString() }),
|
||||
document.pages ? pl(document.pages, "upload.pages") : "",
|
||||
document.images.length ? pl(document.images.length, "upload.pageImages") : "",
|
||||
document.truncated ? tr("upload.truncated") : "",
|
||||
];
|
||||
return parts.filter(Boolean).join(" · ");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,21 +71,22 @@ export function replaceFolders(next: Folder[]): void {
|
|||
write(valid);
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
folders = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
}
|
||||
|
||||
export const folderStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
folders = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): Folder[] {
|
||||
|
|
@ -155,13 +156,3 @@ export function removeFolder(id: string): void {
|
|||
ensureLoaded();
|
||||
write(folderStore.getSnapshot().filter((folder) => folder.id !== id));
|
||||
}
|
||||
|
||||
/** Deleting a folder must never delete decks: callers pair this with unfileDecks(). */
|
||||
export function hasFolder(id: string): boolean {
|
||||
return Boolean(getFolder(id));
|
||||
}
|
||||
|
||||
export function emptyFolder(): void {
|
||||
ensureLoaded();
|
||||
write([]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,10 +64,10 @@ function openDb(): Promise<IDBDatabase> {
|
|||
});
|
||||
}
|
||||
|
||||
async function withDb<T>(mode: IDBTransactionMode, run: (db: IDBDatabase) => T): Promise<T> {
|
||||
async function withDb<T>(_mode: IDBTransactionMode, run: (db: IDBDatabase) => T | Promise<T>): Promise<T> {
|
||||
const db = await openDb();
|
||||
try {
|
||||
return run(db);
|
||||
return await run(db);
|
||||
} finally {
|
||||
// Transactions keep the connection alive until they settle; close on the
|
||||
// next task so pending requests finish first.
|
||||
|
|
|
|||
|
|
@ -80,21 +80,22 @@ export function replaceHomework(next: HomeworkRecord[]): void {
|
|||
write(valid);
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
records = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
}
|
||||
|
||||
export const homeworkStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
records = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): HomeworkRecord[] {
|
||||
|
|
|
|||
17
lib/i18n.ts
17
lib/i18n.ts
|
|
@ -45,19 +45,20 @@ function emit(): void {
|
|||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
cached = read();
|
||||
emit();
|
||||
}
|
||||
}
|
||||
|
||||
export const localeStore = {
|
||||
subscribe(listener: () => void): () => void {
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
cached = read();
|
||||
emit();
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): Locale {
|
||||
|
|
|
|||
|
|
@ -45,7 +45,10 @@ async function loadBitmap(blob: Blob, fallbackName: string): Promise<{ width: nu
|
|||
return {
|
||||
width: bitmap.width,
|
||||
height: bitmap.height,
|
||||
draw: (ctx, w, h) => ctx.drawImage(bitmap, 0, 0, w, h),
|
||||
draw: (ctx, w, h) => {
|
||||
ctx.drawImage(bitmap, 0, 0, w, h);
|
||||
bitmap.close();
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
/* fall through to the <img> path (Safari/HEIC edge cases) */
|
||||
|
|
@ -91,6 +94,8 @@ export async function prepareImageFromBlob(blob: Blob, name = "image.jpg"): Prom
|
|||
bitmap.draw(ctx, width, height);
|
||||
|
||||
const dataUrl = canvas.toDataURL("image/jpeg", JPEG_QUALITY);
|
||||
canvas.width = 0;
|
||||
canvas.height = 0;
|
||||
|
||||
return {
|
||||
id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
|
|
|
|||
|
|
@ -94,6 +94,16 @@ export function dayKey(at: number): string {
|
|||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/** Fast count of answers recorded today (avoids building the full stats buckets). */
|
||||
export function todayAnswerCount(answers: AnswerRecord[], now = Date.now()): number {
|
||||
const today = dayKey(now);
|
||||
let count = 0;
|
||||
for (const answer of answers) {
|
||||
if (dayKey(answer.at) === today) count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export function computeStats(answers: AnswerRecord[], now = Date.now()): LearningStats {
|
||||
const total = answers.length;
|
||||
const correct = answers.filter((entry) => entry.correct).length;
|
||||
|
|
|
|||
|
|
@ -36,14 +36,6 @@ export const fade: Transition = { duration: 0.18, ease: "easeOut" };
|
|||
/** Plain ease for fades and progress bars. */
|
||||
export const EASE_OUT = [0.22, 1, 0.36, 1] as const;
|
||||
|
||||
/** Durations (seconds) used across the pass. */
|
||||
export const DURATION = {
|
||||
press: 0.1,
|
||||
small: 0.2,
|
||||
screen: 0.3,
|
||||
sheet: 0.34,
|
||||
} as const;
|
||||
|
||||
/** A screen entering from the right (drill-in) or left (back). */
|
||||
export function screenVariants(direction: 1 | -1, reduceMotion: boolean): Variants {
|
||||
if (reduceMotion) {
|
||||
|
|
@ -83,17 +75,6 @@ export function stepVariants(direction: 1 | -1, reduceMotion: boolean): Variants
|
|||
};
|
||||
}
|
||||
|
||||
/** Capped stagger for a list's first paint. */
|
||||
export const listContainer: Variants = {
|
||||
hidden: {},
|
||||
show: { transition: { staggerChildren: 0.045, delayChildren: 0.02 } },
|
||||
};
|
||||
|
||||
export const listItem: Variants = {
|
||||
hidden: { opacity: 0, y: 12 },
|
||||
show: { opacity: 1, y: 0, transition: springGentle },
|
||||
};
|
||||
|
||||
/**
|
||||
* Counts a number up over ~600ms with an ease-out curve (score, XP). Pass
|
||||
* `disabled` (desktop, reduced motion) to jump straight to the value.
|
||||
|
|
|
|||
182
lib/ollama.ts
182
lib/ollama.ts
|
|
@ -120,7 +120,10 @@ async function fetchWithTimeout(
|
|||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const onAbort = () => controller.abort();
|
||||
external?.addEventListener("abort", onAbort);
|
||||
if (external) {
|
||||
if (external.aborted) controller.abort();
|
||||
else external.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal });
|
||||
|
|
@ -273,89 +276,104 @@ export async function ollamaChatStream(options: StreamOptions): Promise<ChatStre
|
|||
}
|
||||
if (config.think !== null) body.think = config.think;
|
||||
|
||||
let response: Response;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs);
|
||||
const onAbort = () => controller.abort();
|
||||
if (options.signal) {
|
||||
if (options.signal.aborted) controller.abort();
|
||||
else options.signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
response = await fetchWithTimeout(
|
||||
`${baseUrl}/api/chat`,
|
||||
{ method: "POST", headers, body: JSON.stringify(body), cache: "no-store" },
|
||||
options.timeoutMs ?? config.timeoutMs,
|
||||
options.signal,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new OllamaError("timeout", "The request to Ollama timed out.");
|
||||
}
|
||||
throw new OllamaError("unreachable", `Could not connect to Ollama at ${baseUrl}.`, {
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throwForStatus(response.status, text, model);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new OllamaError("bad_response", "Ollama sent an empty stream.");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let content = "";
|
||||
let thinking = "";
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let event: unknown;
|
||||
let response: Response;
|
||||
try {
|
||||
event = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return; // a half-written line must never break the stream
|
||||
}
|
||||
if (!event || typeof event !== "object") return;
|
||||
const record = event as Record<string, unknown>;
|
||||
if (typeof record.error === "string" && record.error) {
|
||||
throw new OllamaError("http", record.error.slice(0, 300));
|
||||
}
|
||||
const message = record.message as Record<string, unknown> | undefined;
|
||||
const delta = typeof message?.content === "string" ? message.content : "";
|
||||
const reason = typeof message?.thinking === "string" ? message.thinking : "";
|
||||
if (reason) {
|
||||
thinking += reason;
|
||||
options.onThinking?.(reason);
|
||||
}
|
||||
if (delta) {
|
||||
content += delta;
|
||||
options.onToken?.(delta);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let newline = buffer.indexOf("\n");
|
||||
while (newline !== -1) {
|
||||
handleLine(buffer.slice(0, newline));
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
response = await fetch(`${baseUrl}/api/chat`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new OllamaError("timeout", "The request to Ollama timed out.");
|
||||
}
|
||||
throw new OllamaError("unreachable", `Could not connect to Ollama at ${baseUrl}.`, {
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
handleLine(buffer);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new OllamaError("timeout", "The request to Ollama timed out.");
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throwForStatus(response.status, text, model);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new OllamaError("bad_response", "Ollama sent an empty stream.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!content.trim()) {
|
||||
throw new OllamaError("bad_response", "Ollama finished the stream without any answer text.");
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let content = "";
|
||||
let thinking = "";
|
||||
|
||||
return { content, thinking, model };
|
||||
const handleLine = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let event: unknown;
|
||||
try {
|
||||
event = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return; // a half-written line must never break the stream
|
||||
}
|
||||
if (!event || typeof event !== "object") return;
|
||||
const record = event as Record<string, unknown>;
|
||||
if (typeof record.error === "string" && record.error) {
|
||||
throw new OllamaError("http", record.error.slice(0, 300));
|
||||
}
|
||||
const message = record.message as Record<string, unknown> | undefined;
|
||||
const delta = typeof message?.content === "string" ? message.content : "";
|
||||
const reason = typeof message?.thinking === "string" ? message.thinking : "";
|
||||
if (reason) {
|
||||
thinking += reason;
|
||||
options.onThinking?.(reason);
|
||||
}
|
||||
if (delta) {
|
||||
content += delta;
|
||||
options.onToken?.(delta);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let newline = buffer.indexOf("\n");
|
||||
while (newline !== -1) {
|
||||
handleLine(buffer.slice(0, newline));
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
}
|
||||
}
|
||||
handleLine(buffer);
|
||||
} catch (error) {
|
||||
void reader.cancel().catch(() => {});
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new OllamaError("timeout", "The request to Ollama timed out.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!content.trim()) {
|
||||
throw new OllamaError("bad_response", "Ollama finished the stream without any answer text.");
|
||||
}
|
||||
|
||||
return { content, thinking, model };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
function extractContent(payload: unknown): string | null {
|
||||
|
|
@ -493,6 +511,16 @@ export async function ollamaVerifyKey(auth: OllamaAuth, model: string, timeoutMs
|
|||
: { valid: null, reason: "throttled", detail };
|
||||
} else probe = { valid: null, detail: `HTTP ${response.status}` };
|
||||
|
||||
if (probeCache.size >= 500) {
|
||||
const now = Date.now();
|
||||
for (const [k, entry] of probeCache) {
|
||||
if (now - entry.at >= PROBE_TTL_MS) probeCache.delete(k);
|
||||
}
|
||||
if (probeCache.size >= 500) {
|
||||
const oldest = probeCache.keys().next().value;
|
||||
if (oldest) probeCache.delete(oldest);
|
||||
}
|
||||
}
|
||||
probeCache.set(cacheKey, { ...probe, at: Date.now() });
|
||||
return probe;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -125,7 +125,8 @@ function contentFor(user: string, images?: string[]): string | ChatPart[] {
|
|||
if (!images || images.length === 0) return user;
|
||||
const parts: ChatPart[] = [{ type: "text", text: user }];
|
||||
for (const image of images.slice(0, 8)) {
|
||||
parts.push({ type: "image_url", image_url: { url: image } });
|
||||
const url = image.startsWith("data:") || /^https?:\/\//i.test(image) ? image : `data:image/jpeg;base64,${image}`;
|
||||
parts.push({ type: "image_url", image_url: { url } });
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
|
@ -188,72 +189,103 @@ export async function providerChatStream(input: {
|
|||
})),
|
||||
stream: true,
|
||||
};
|
||||
const response = await runFetch(
|
||||
`${trimBase(input.target.baseUrl)}/chat/completions`,
|
||||
{ method: "POST", headers: requestHeaders(input.target), body: JSON.stringify(body), signal: input.signal, cache: "no-store" },
|
||||
input.model,
|
||||
input.target,
|
||||
300_000,
|
||||
);
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw failure(response.status, text, input.model, input.target);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new ProviderError("http", `${input.target.label} sent an empty stream.`, input.target.label);
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 300_000);
|
||||
const onAbort = () => controller.abort();
|
||||
if (input.signal) {
|
||||
if (input.signal.aborted) controller.abort();
|
||||
else input.signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let model = input.model;
|
||||
let sawDone = false;
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith("data:")) return;
|
||||
const data = trimmed.slice(5).trim();
|
||||
if (!data || data === "[DONE]") {
|
||||
if (data === "[DONE]") sawDone = true;
|
||||
return;
|
||||
}
|
||||
let event: {
|
||||
model?: string;
|
||||
choices?: Array<{ delta?: { content?: unknown; reasoning?: unknown; reasoning_content?: unknown } }>;
|
||||
error?: { message?: string };
|
||||
};
|
||||
try {
|
||||
let response: Response;
|
||||
try {
|
||||
event = JSON.parse(data);
|
||||
} catch {
|
||||
return;
|
||||
response = await fetch(`${trimBase(input.target.baseUrl)}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: requestHeaders(input.target),
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (error) {
|
||||
if (input.signal?.aborted) throw error;
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new ProviderError("timeout", `${input.target.label} took too long to answer.`, input.target.label);
|
||||
}
|
||||
throw new ProviderError("unreachable", `Could not reach ${input.target.label}. Check your connection.`, input.target.label);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw failure(response.status, text, input.model, input.target);
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new ProviderError("http", `${input.target.label} sent an empty stream.`, input.target.label);
|
||||
}
|
||||
if (event.error?.message) throw new ProviderError("http", `${input.target.label}: ${event.error.message}`, input.target.label);
|
||||
if (event.model) model = event.model;
|
||||
const delta = event.choices?.[0]?.delta;
|
||||
if (!delta) return;
|
||||
const thinking = delta.reasoning_content ?? delta.reasoning;
|
||||
if (typeof thinking === "string" && thinking) input.onThinking?.(thinking);
|
||||
if (typeof delta.content === "string" && delta.content) input.onToken?.(delta.content);
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let newline = buffer.indexOf("\n");
|
||||
while (newline !== -1) {
|
||||
handleLine(buffer.slice(0, newline));
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let model = input.model;
|
||||
let sawDone = false;
|
||||
|
||||
const handleLine = (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith("data:")) return;
|
||||
const data = trimmed.slice(5).trim();
|
||||
if (!data || data === "[DONE]") {
|
||||
if (data === "[DONE]") sawDone = true;
|
||||
return;
|
||||
}
|
||||
let event: {
|
||||
model?: string;
|
||||
choices?: Array<{ delta?: { content?: unknown; reasoning?: unknown; reasoning_content?: unknown } }>;
|
||||
error?: { message?: string };
|
||||
};
|
||||
try {
|
||||
event = JSON.parse(data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (event.error?.message) throw new ProviderError("http", `${input.target.label}: ${event.error.message}`, input.target.label);
|
||||
if (event.model) model = event.model;
|
||||
const delta = event.choices?.[0]?.delta;
|
||||
if (!delta) return;
|
||||
const thinking = delta.reasoning_content ?? delta.reasoning;
|
||||
if (typeof thinking === "string" && thinking) input.onThinking?.(thinking);
|
||||
if (typeof delta.content === "string" && delta.content) input.onToken?.(delta.content);
|
||||
};
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
let newline = buffer.indexOf("\n");
|
||||
while (newline !== -1) {
|
||||
handleLine(buffer.slice(0, newline));
|
||||
buffer = buffer.slice(newline + 1);
|
||||
newline = buffer.indexOf("\n");
|
||||
}
|
||||
}
|
||||
handleLine(buffer);
|
||||
} catch (error) {
|
||||
void reader.cancel().catch(() => {});
|
||||
if (input.signal?.aborted) throw error;
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new ProviderError("timeout", `${input.target.label} took too long to answer.`, input.target.label);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!sawDone) {
|
||||
// Some gateways close the stream without [DONE]; tokens already arrived,
|
||||
// so this is only worth a debug note.
|
||||
console.warn(`[freezmo] ${input.target.label} stream ended without [DONE]`);
|
||||
}
|
||||
return { model };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
input.signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
handleLine(buffer);
|
||||
if (!sawDone) {
|
||||
// Some gateways close the stream without [DONE]; tokens already arrived,
|
||||
// so this is only worth a debug note.
|
||||
console.warn(`[freezmo] ${input.target.label} stream ended without [DONE]`);
|
||||
}
|
||||
return { model };
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -117,11 +117,13 @@ export function saveProviderKey(id: string, key: string) {
|
|||
}
|
||||
|
||||
export function clearProviderKey(id: string) {
|
||||
const keys = { ...providersStore.getSnapshot().keys };
|
||||
const current = providersStore.getSnapshot();
|
||||
const keys = { ...current.keys };
|
||||
delete keys[id];
|
||||
const models = { ...providersStore.getSnapshot().models };
|
||||
const models = { ...current.models };
|
||||
delete models[id];
|
||||
update({ keys, models });
|
||||
const generation = current.generation?.provider === id ? null : current.generation;
|
||||
update({ keys, models, generation });
|
||||
}
|
||||
|
||||
export function setProviderModels(id: string, models: string[]) {
|
||||
|
|
|
|||
|
|
@ -72,21 +72,22 @@ function write(next: QuestionReport[]): void {
|
|||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
reports = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
}
|
||||
|
||||
export const reportStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
reports = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): QuestionReport[] {
|
||||
|
|
|
|||
|
|
@ -105,16 +105,6 @@ export const generatedActivitySchema = z.discriminatedUnion("type", [
|
|||
]);
|
||||
export type GeneratedActivity = z.infer<typeof generatedActivitySchema>;
|
||||
|
||||
export const generatedDeckSchema = z.object({
|
||||
title: z.string().min(1).max(120),
|
||||
subject: z.string().max(80).optional(),
|
||||
summary: z.string().max(400).optional(),
|
||||
/** Language of the generated content, e.g. "Czech" or "cs". */
|
||||
language: z.string().max(60).optional(),
|
||||
activities: z.array(generatedActivitySchema).min(4).max(20),
|
||||
});
|
||||
export type GeneratedDeck = z.infer<typeof generatedDeckSchema>;
|
||||
|
||||
/** What the vision step must return. */
|
||||
export const extractedNotesSchema = z.object({
|
||||
title: z.string().min(1).max(120),
|
||||
|
|
@ -197,12 +187,11 @@ export const homeworkStepSchema = z.object({
|
|||
checkpoint: generatedActivitySchema.optional(),
|
||||
});
|
||||
|
||||
export const homeworkGuideSchema = z.object({
|
||||
title: z.string().min(1).max(200),
|
||||
language: z.string().max(60).optional(),
|
||||
steps: z.array(homeworkStepSchema).min(2).max(10),
|
||||
});
|
||||
export type HomeworkGuide = z.infer<typeof homeworkGuideSchema>;
|
||||
export type HomeworkGuide = {
|
||||
title: string;
|
||||
language?: string;
|
||||
steps: z.infer<typeof homeworkStepSchema>[];
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Client-side homework types (checkpoints carry id/xp, plus storage) */
|
||||
|
|
@ -397,6 +386,7 @@ export const chatConversationSchema = z.object({
|
|||
messages: z.array(chatMessageSchema).max(300),
|
||||
scope: chatScopeSchema,
|
||||
model: z.string().max(120).optional(),
|
||||
provider: z.string().max(60).optional(),
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
});
|
||||
|
|
|
|||
13
lib/share.ts
13
lib/share.ts
|
|
@ -1,5 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import { copyText } from "./clipboard";
|
||||
import { exportDeck } from "./storage";
|
||||
import { showToast } from "./toast";
|
||||
import type { Deck, HomeworkRecord } from "./schemas";
|
||||
|
|
@ -21,18 +22,6 @@ function deckFile(deck: Deck): File {
|
|||
});
|
||||
}
|
||||
|
||||
async function copyText(text: string): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function shareDeck(deck: Deck): Promise<void> {
|
||||
const nav = navigator as ShareNavigator;
|
||||
const file = deckFile(deck);
|
||||
|
|
|
|||
|
|
@ -70,22 +70,22 @@ export function replaceDecks(next: Deck[]): void {
|
|||
write(valid);
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
decks = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
}
|
||||
|
||||
export const deckStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
// Another tab may have changed the library.
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
decks = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): Deck[] {
|
||||
|
|
|
|||
|
|
@ -78,21 +78,22 @@ function write(next: SyncRecord): void {
|
|||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
function onStorage(event: StorageEvent): void {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
record = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
}
|
||||
|
||||
export const syncStore = {
|
||||
subscribe(listener: Listener): () => void {
|
||||
ensureLoaded();
|
||||
if (listeners.size === 0) window.addEventListener("storage", onStorage);
|
||||
listeners.add(listener);
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY) {
|
||||
record = null;
|
||||
ensureLoaded();
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
},
|
||||
getSnapshot(): SyncRecord {
|
||||
|
|
|
|||
|
|
@ -55,15 +55,20 @@ export function useHealth() {
|
|||
const run = useCallback(async (force: boolean) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const key = settingsStore.getSnapshot().apiKey;
|
||||
try {
|
||||
const key = settingsStore.getSnapshot().apiKey;
|
||||
setHealth(await loadHealth(key, force));
|
||||
const result = await loadHealth(key, force);
|
||||
if (settingsStore.getSnapshot().apiKey !== key) return;
|
||||
setHealth(result);
|
||||
} catch (loadError) {
|
||||
if (settingsStore.getSnapshot().apiKey !== key) return;
|
||||
setError(loadError instanceof Error ? loadError.message : t("api.unreachableShort"));
|
||||
} finally {
|
||||
// Even a failed check is a check: the panel can say when it last ran.
|
||||
setCheckedAt(Date.now());
|
||||
setLoading(false);
|
||||
if (settingsStore.getSnapshot().apiKey === key) {
|
||||
// Even a failed check is a check: the panel can say when it last ran.
|
||||
setCheckedAt(Date.now());
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
|
|
|||
|
|
@ -27,9 +27,14 @@ export function useWakeLock(active = true): void {
|
|||
|
||||
const acquire = async () => {
|
||||
try {
|
||||
sentinel = await wakeLock.request("screen");
|
||||
sentinel.addEventListener("release", () => {
|
||||
sentinel = null;
|
||||
const acquired = await wakeLock.request("screen");
|
||||
if (disposed) {
|
||||
void acquired.release().catch(() => {});
|
||||
return;
|
||||
}
|
||||
sentinel = acquired;
|
||||
acquired.addEventListener("release", () => {
|
||||
if (sentinel === acquired) sentinel = null;
|
||||
});
|
||||
} catch {
|
||||
/* denied or not allowed without a gesture — fine */
|
||||
|
|
|
|||
|
|
@ -37,7 +37,9 @@ export function stripFences(text: string): string {
|
|||
let value = text.trim();
|
||||
const fence = value.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
||||
if (fence) value = fence[1].trim();
|
||||
if (value.startsWith("{") || value.startsWith("[")) return value;
|
||||
if ((value.startsWith("{") && value.endsWith("}")) || (value.startsWith("[") && value.endsWith("]"))) {
|
||||
return value;
|
||||
}
|
||||
const start = value.indexOf("{");
|
||||
const end = value.lastIndexOf("}");
|
||||
if (start !== -1 && end > start) return value.slice(start, end + 1);
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ function keyFor(scope: "deck" | "homework"): string {
|
|||
|
||||
export function saveWizardDraft(scope: "deck" | "homework", draft: Omit<WizardDraft, "v" | "savedAt">): void {
|
||||
try {
|
||||
const images = (draft.images ?? []).filter(() => true);
|
||||
const images = draft.images ?? [];
|
||||
const size = images.reduce((sum, image) => sum + image.dataUrl.length, 0);
|
||||
const payload: WizardDraft = {
|
||||
v: 1,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "freezmo",
|
||||
"version": "0.5.7",
|
||||
"version": "0.5.8",
|
||||
"private": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
Before Width: | Height: | Size: 391 B |
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
Before Width: | Height: | Size: 1 KiB |
|
|
@ -1 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
|
@ -9,7 +9,7 @@
|
|||
*
|
||||
* Bumping CACHE_VERSION is how a new deploy invalidates old assets.
|
||||
*/
|
||||
const CACHE_VERSION = "freezmo-v79";
|
||||
const CACHE_VERSION = "freezmo-v80";
|
||||
const SHELL_CACHE = `${CACHE_VERSION}-shell`;
|
||||
const ASSET_CACHE = `${CACHE_VERSION}-assets`;
|
||||
|
||||
|
|
@ -131,7 +131,7 @@ self.addEventListener("fetch", (event) => {
|
|||
if (response.ok) cache.put(request, response.clone()).catch(() => {});
|
||||
return response;
|
||||
})
|
||||
.catch(() => cached);
|
||||
.catch(() => cached ?? Response.error());
|
||||
return cached ?? network;
|
||||
})(),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
Before Width: | Height: | Size: 128 B |
|
|
@ -1 +0,0 @@
|
|||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
Before Width: | Height: | Size: 385 B |
|
|
@ -160,5 +160,54 @@ const browser = await launchBrowser();
|
|||
await cs.context.close();
|
||||
}
|
||||
|
||||
/* 7. typed fill-blank + checked homework card ------------------------ */
|
||||
{
|
||||
const typedDeck = {
|
||||
...DECK,
|
||||
id: "typed_fill_deck",
|
||||
activities: [
|
||||
{
|
||||
id: "act_typed_fill",
|
||||
type: "fill_blank",
|
||||
topic: "Optics",
|
||||
sentence: "Short wavelengths scatter ____ than long ones.",
|
||||
answer: "more",
|
||||
explanation: "Blue light scatters more strongly.",
|
||||
xp: 15,
|
||||
},
|
||||
],
|
||||
};
|
||||
const { context, page } = await makePage(browser);
|
||||
await seed(page, {
|
||||
decks: [typedDeck],
|
||||
extra: {
|
||||
"freezmo.homework.v1": JSON.stringify([
|
||||
{
|
||||
id: "hw_check_1",
|
||||
mode: "check",
|
||||
title: "Linear equations check",
|
||||
sourceText: "2x + 2 = 6",
|
||||
verdict: "One sign error.",
|
||||
correct: ["Good setup"],
|
||||
wrong: [],
|
||||
corrected: "x = 2",
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
await page.goto(`${BASE}/deck/typed_fill_deck`, { waitUntil: "networkidle" });
|
||||
await page.waitForTimeout(700);
|
||||
const input = page.getByLabel("Type the missing word");
|
||||
await input.fill("more");
|
||||
check("fill-blank: typed input displays the value", (await input.inputValue()) === "more");
|
||||
|
||||
await page.goto(`${BASE}/?tab=homework`, { waitUntil: "networkidle" });
|
||||
await page.waitForTimeout(700);
|
||||
check("homework card: check mode shows Checked badge", await page.getByText("Checked").first().isVisible());
|
||||
await context.close();
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
finish();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue