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
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue