Safety net and errors, mobile-first, desktop unchanged in behaviour. Backup and persistence - Settings -> Data & backup: 'Export all data' writes one zod-validated JSON (decks, folders, homework, progress, safe settings; the API key is not part of the shape and never appears in the file). - 'Import backup' validates, shows a preview with added/replaced counts and offers merge or replace; invalid files get a friendly error. Storage persistence (navigator.storage.persist) is shown and requestable, with the result reported. - A dismissible nudge appears after 5 new decks or 14 days without a backup and stays snoozed for 14 days. Opt-in encrypted sync (off by default) - New lib/sync.ts: PBKDF2-SHA256 (310k) -> AES-GCM-256, derived key kept as a non-extractable CryptoKey in IndexedDB (lib/sync-key.ts); the passphrase and key never leave the browser. - New POST/GET/DELETE /api/sync following the route pattern (locale, cross-origin guard, body cap, rate limit RATE_LIMIT_SYNC, auth before body parsing, zod validation). One atomic JSON file per random 128-bit sync ID under SYNC_DIR; server-stamped updatedAt is the conflict clock; SYNC_MAX_BYTES and SYNC_TOTAL_BYTES enforced (413 / 507). The server only ever sees an opaque envelope. - Settings -> Sync: enable with a passphrase, copy the sync ID, sync now, last-synced time, explicit keep-this-device / use-synced-copy conflict choice, join from another device (ID + passphrase, wrong passphrase rejected), unlock after the key is gone, delete the synced copy (works even on a locked device). Every data store marks sync dirty on write; pulled payloads are applied without marking dirty again. Monthly usage vs short-term throttling - lib/ollama.ts classifies the real 429 body (monthly/quota/upgrade vs burst) into new 'usage_limit' and 'throttled' kinds, mapped in every route and in the health probe. - The client renders the same localized message in the deck flow, homework, grading and the Settings banner: the required upgrade/new-key copy with 'Open Settings' (jumps to and focuses the key field) and 'Open Ollama'. Input and wizard drafts are kept so Retry works right after swapping the key. No model fallback. Verified: new phase-1 suite 38/38 (backup content + no key, import preview/merge/replace, junk file, persistence row, nudge + snooze, sync enable/upload/opaque blob/push/join/wrong passphrase/delete, server validation 400/401, usage-limit copy and key focus, and the real route mapping against a stub Ollama for both 429 variants) plus regression 74/74, mobile 52/52, wizard 80/80, declutter 116/116, animation 8/8, native 35/35, i18n 25/25. Key parity 638/638. Lint + build clean. SW freezmo-v25.
167 lines
5.3 KiB
TypeScript
167 lines
5.3 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);
|
|
}
|
|
|
|
export const folderStore = {
|
|
subscribe(listener: Listener): () => void {
|
|
ensureLoaded();
|
|
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);
|
|
};
|
|
},
|
|
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));
|
|
}
|
|
|
|
/** 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([]);
|
|
}
|