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

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

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

158 lines
5.1 KiB
TypeScript

"use client";
/**
* Folder library, stored next to the decks in localStorage.
*
* Folders are pure organisation: deleting one never deletes decks, it just
* moves them back to "Unorganized". The virtual folder `UNORGANIZED_ID` is
* never persisted — it is simply every deck with no `folderId`.
*/
import { t } from "./i18n";
import { folderSchema, UNORGANIZED_ID, type Folder } from "./schemas";
import { markSyncDirty } from "./sync-state";
import { uid } from "./utils";
const STORAGE_KEY = "freezmo.folders.v1";
const EMPTY: Folder[] = [];
type Listener = () => void;
let folders: Folder[] | null = null;
let cached: Folder[] = EMPTY;
const listeners = new Set<Listener>();
function read(): Folder[] {
if (typeof window === "undefined") return EMPTY;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return EMPTY;
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return EMPTY;
const valid: Folder[] = [];
for (const entry of parsed) {
const result = folderSchema.safeParse(entry);
if (result.success) valid.push(result.data);
else console.warn("[freezmo] skipping invalid folder", result.error.issues);
}
return valid;
} catch (error) {
console.warn("[freezmo] could not read folders", error);
return EMPTY;
}
}
function ensureLoaded(): void {
if (folders !== null) return;
folders = read();
cached = folders;
}
function write(next: Folder[]): void {
folders = next;
cached = next;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch (error) {
console.warn("[freezmo] could not save folders", error);
}
markSyncDirty();
listeners.forEach((listener) => listener());
}
/** Used by backup import and sync: wholesale replacement of the folders. */
export function replaceFolders(next: Folder[]): void {
const valid: Folder[] = [];
for (const entry of next) {
const result = folderSchema.safeParse(entry);
if (result.success) valid.push(result.data);
else console.warn("[freezmo] skipping invalid folder in import", result.error.issues);
}
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);
return () => {
listeners.delete(listener);
if (listeners.size === 0) window.removeEventListener("storage", onStorage);
};
},
getSnapshot(): Folder[] {
ensureLoaded();
return cached;
},
getServerSnapshot(): Folder[] {
return EMPTY;
},
};
/* ------------------------------------------------------------------ */
/* Queries */
/* ------------------------------------------------------------------ */
export function listFolders(): Folder[] {
return [...folderStore.getSnapshot()].sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
}
export function getFolder(id: string | undefined): Folder | undefined {
if (!id || id === UNORGANIZED_ID) return undefined;
return folderStore.getSnapshot().find((folder) => folder.id === id);
}
export function folderName(id: string | undefined): string {
if (!id || id === UNORGANIZED_ID) return t("common.unorganized");
return getFolder(id)?.name ?? t("common.unorganized");
}
export function findFolderByName(name: string): Folder | undefined {
const wanted = name.trim().toLowerCase();
return folderStore.getSnapshot().find((folder) => folder.name.trim().toLowerCase() === wanted);
}
/** Case-insensitive uniqueness; returns the existing folder when it matches. */
export function createFolder(name: string): { folder: Folder } | { error: string } {
const trimmed = name.trim().replace(/\s+/g, " ");
if (!trimmed) return { error: t("folder.nameRequired") };
if (trimmed.length > 60) return { error: t("folder.nameTooLong") };
const existing = findFolderByName(trimmed);
if (existing) return { folder: existing };
const folder: Folder = { id: uid("fold"), name: trimmed, createdAt: Date.now() };
ensureLoaded();
write([...folderStore.getSnapshot(), folder]);
return { folder };
}
export function renameFolder(id: string, name: string): { ok: true } | { error: string } {
const trimmed = name.trim().replace(/\s+/g, " ");
if (!trimmed) return { error: t("folder.nameRequired") };
const clash = folderStore
.getSnapshot()
.find((folder) => folder.id !== id && folder.name.trim().toLowerCase() === trimmed.toLowerCase());
if (clash) return { error: t("folder.nameTaken") };
ensureLoaded();
write(folderStore.getSnapshot().map((folder) => (folder.id === id ? { ...folder, name: trimmed } : folder)));
return { ok: true };
}
/** Removes the folder. Decks inside it are handed back to the caller to re-home. */
export function removeFolder(id: string): void {
ensureLoaded();
write(folderStore.getSnapshot().filter((folder) => folder.id !== id));
}