freezmo/components/Sidebar.tsx
Martin Dvorak bb1f4e2018 Phase 1: backup, encrypted sync and monthly-usage handling
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.
2026-10-10 13:43:42 +00:00

459 lines
16 KiB
TypeScript

"use client";
import Link from "next/link";
import { useMemo, useState, useSyncExternalStore, type ReactNode } from "react";
import { AnimatePresence, motion } from "framer-motion";
import {
ChevronLeftIcon,
ChevronRightIcon,
FolderIcon,
GearIcon,
LayersIcon,
MoonIcon,
PlusIcon,
SparklesIcon,
SunIcon,
} from "@/components/icons";
import { useTheme } from "@/components/ThemeToggle";
import { createFolder, folderStore } from "@/lib/folders";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { springSheet } from "@/lib/motion";
import { ALL_FOLDERS, folderSelection, sidebarOpen, useSelectedFolder, useSidebarOpen } from "@/lib/nav";
import { UNORGANIZED_ID } from "@/lib/schemas";
import { deckStore } from "@/lib/storage";
import { openSettings } from "@/lib/ui-events";
import { useBackClose } from "@/lib/use-back-close";
import { cn } from "@/lib/utils";
const COLLAPSE_KEY = "freezmo.sidebarCollapsed";
/** Shared nav content for the desktop rail and the mobile drawer. */
function NavContent({
collapsed = false,
onNavigate,
desktop = false,
}: {
collapsed?: boolean;
onNavigate?: () => void;
desktop?: boolean;
}) {
const decks = useSyncExternalStore(deckStore.subscribe, deckStore.getSnapshot, deckStore.getServerSnapshot);
const folders = useSyncExternalStore(
folderStore.subscribe,
folderStore.getSnapshot,
folderStore.getServerSnapshot,
);
const selected = useSelectedFolder();
const { theme, toggle } = useTheme();
const { t } = useI18n();
const [creating, setCreating] = useState(false);
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const sortedFolders = useMemo(
() => [...folders].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" })),
[folders],
);
const counts = useMemo(() => {
const map: Record<string, number> = { [UNORGANIZED_ID]: 0 };
for (const folder of sortedFolders) map[folder.id] = 0;
for (const deck of decks) {
const key = deck.folderId && map[deck.folderId] !== undefined ? deck.folderId : UNORGANIZED_ID;
map[key] = (map[key] ?? 0) + 1;
}
return map;
}, [decks, sortedFolders]);
const submit = () => {
const result = createFolder(draft);
if ("error" in result) {
setError(result.error);
return;
}
folderSelection.set(result.folder.id);
setDraft("");
setError(null);
setCreating(false);
};
const select = (id: string) => {
folderSelection.set(id);
onNavigate?.();
};
/** Counts of 0 are noise — only show a count when there is something in it. */
const count = (value: number) =>
!collapsed && value > 0 ? <span className="text-[12px] tabular-nums opacity-60">{value}</span> : null;
/** One shared view row (All decks / Unorganized) for both nav layouts. */
const viewRow = (id: string, label: string, icon: ReactNode, trailing: ReactNode) => (
<button
type="button"
onClick={() => select(id)}
aria-pressed={selected === id}
title={label}
className={cn("nav-row", collapsed && "justify-center px-2")}
>
{icon}
{!collapsed ? <span className="flex-1 truncate text-left">{label}</span> : null}
{trailing}
</button>
);
return (
<div className="flex min-h-0 flex-1 flex-col">
{/* brand ---------------------------------------------------------- */}
<div className={cn("mb-1 flex items-center", collapsed ? "justify-center" : "justify-between")}>
<Link
href="/"
onClick={onNavigate}
className={cn("nav-row gap-2.5", collapsed ? "w-auto px-2" : "flex-1")}
aria-label={t("header.home")}
title="Freezmo"
>
{/* eslint-disable-next-line @next/next/no-img-element -- static app icon, no optimisation needed */}
<img
src="/icons/icon-192.png"
alt=""
aria-hidden
className="size-7 shrink-0 rounded-lg shadow-[0_1px_3px_rgb(14_21_40/0.35)]"
/>
{!collapsed ? (
<span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--text)]">Freezmo</span>
) : null}
</Link>
{!collapsed ? (
<button
type="button"
onClick={() => sidebarCollapse.set(true)}
aria-label={t("sidebar.collapse")}
title={t("sidebar.collapse")}
className="grid size-8 place-items-center rounded-lg text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
>
<ChevronLeftIcon className="size-4" />
</button>
) : null}
</div>
{/* new deck: a quiet row, not a competing primary button ---------- */}
<Link
href="/create"
onClick={onNavigate}
className={cn("nav-row mb-3", collapsed && "justify-center px-2")}
title={t("common.newDeck")}
>
<PlusIcon className="size-4 shrink-0" />
{!collapsed ? <span className="flex-1 truncate text-left">{t("common.newDeck")}</span> : null}
</Link>
{/* make my homework: same quiet row --------------------------------- */}
<Link
href="/homework"
onClick={onNavigate}
className={cn("nav-row mb-3", collapsed && "justify-center px-2")}
title={t("homework.nav")}
>
<SparklesIcon className="size-4 shrink-0" />
{!collapsed ? <span className="flex-1 truncate text-left">{t("homework.nav")}</span> : null}
</Link>
{/* folders --------------------------------------------------------- */}
{/* Mobile keeps the original layout: one Folders label above the list. */}
{!desktop && !collapsed ? (
<div className="flex items-center justify-between px-2 pb-1">
<span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--text-subtle)]">
{t("common.folders")}
</span>
<button
type="button"
onClick={() => setCreating(true)}
aria-label={t("common.newFolder")}
title={t("common.newFolder")}
className="grid size-6 place-items-center rounded-md text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
>
<PlusIcon className="size-3.5" />
</button>
</div>
) : null}
<nav
aria-label={desktop ? t("sidebar.library") : t("common.folders")}
className="thin-scroll min-h-0 flex-1 space-y-0.5 overflow-y-auto"
>
{collapsed ? (
<button
type="button"
onClick={() => sidebarCollapse.set(false)}
aria-label={t("sidebar.expand")}
title={t("sidebar.expand")}
className="nav-row justify-center px-2"
>
<ChevronRightIcon className="size-4" />
</button>
) : null}
{/* Desktop: All decks + Unorganized are views, so they sit above the
Folders label; mobile keeps them inside the folder list. */}
{desktop ? (
<div className={cn("space-y-0.5", !collapsed && "mb-1")}>
{viewRow(
ALL_FOLDERS,
t("common.allDecks"),
<LayersIcon className="size-4 shrink-0 opacity-70" />,
count(decks.length),
)}
{viewRow(
UNORGANIZED_ID,
t("common.unorganized"),
<FolderIcon className="size-4 shrink-0 opacity-70" />,
null,
)}
</div>
) : (
<>
{viewRow(
ALL_FOLDERS,
t("common.allDecks"),
<LayersIcon className="size-4 shrink-0 opacity-70" />,
count(decks.length),
)}
{viewRow(
UNORGANIZED_ID,
t("common.unorganized"),
<FolderIcon className="size-4 shrink-0 opacity-70" />,
count(counts[UNORGANIZED_ID] ?? 0),
)}
</>
)}
{/* Desktop: the Folders label sits between the views and the folders. */}
{desktop && !collapsed ? (
<div className="flex items-center justify-between px-2 pb-1 pt-1">
<span className="text-[11px] font-semibold uppercase tracking-wider text-[var(--text-subtle)]">
{t("common.folders")}
</span>
<button
type="button"
onClick={() => setCreating(true)}
aria-label={t("common.newFolder")}
title={t("common.newFolder")}
className="grid size-6 place-items-center rounded-md text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
>
<PlusIcon className="size-3.5" />
</button>
</div>
) : null}
{sortedFolders.map((folder) => (
<button
key={folder.id}
type="button"
onClick={() => select(folder.id)}
aria-pressed={selected === folder.id}
title={folder.name}
className={cn("nav-row", collapsed && "justify-center px-2")}
>
<FolderIcon className="size-4 shrink-0 opacity-70" />
{!collapsed ? <span className="flex-1 truncate text-left">{folder.name}</span> : null}
{desktop ? null : count(counts[folder.id] ?? 0)}
</button>
))}
{creating && !collapsed ? (
<div className="flex items-center gap-1 px-1 pt-1">
<input
autoFocus
value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Enter") submit();
if (event.key === "Escape") {
setCreating(false);
setDraft("");
setError(null);
}
}}
placeholder={t("common.folderName")}
aria-label={t("common.newFolderName")}
maxLength={60}
className="min-w-0 flex-1 rounded-lg border border-[var(--hairline)] bg-[var(--surface)] px-2.5 py-1.5 text-[13px] text-[var(--text)] outline-none focus:border-[var(--text-subtle)]"
/>
<button type="button" onClick={submit} className="btn-primary h-8 px-3 text-[12px]">
{t("common.add")}
</button>
</div>
) : null}
{error ? <p className="px-2 pt-1 text-[12px] text-rose-600 dark:text-rose-300">{error}</p> : null}
</nav>
{/* footer ---------------------------------------------------------- */}
<div className="mt-2 space-y-0.5 border-t border-[var(--hairline)] pt-2">
<button
type="button"
onClick={() => openSettings()}
title={t("common.settings")}
className={cn("nav-row", collapsed && "justify-center px-2")}
>
<GearIcon className="size-4 shrink-0 opacity-70" />
{!collapsed ? <span className="flex-1 truncate text-left">{t("common.settings")}</span> : null}
</button>
<button
type="button"
onClick={() => {
haptic("toggle");
toggle();
}}
aria-label={theme === "dark" ? t("common.switchToLight") : t("common.switchToDark")}
title={theme === "dark" ? t("common.lightMode") : t("common.darkMode")}
className={cn("nav-row", collapsed && "justify-center px-2")}
>
{theme === "dark" ? (
<SunIcon className="size-4 shrink-0 opacity-70" />
) : (
<MoonIcon className="size-4 shrink-0 opacity-70" />
)}
{!collapsed ? (
<span className="flex-1 truncate text-left">
{theme === "dark" ? t("common.lightMode") : t("common.darkMode")}
</span>
) : null}
</button>
</div>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Collapsed state (shared between rail and drawer) */
/* ------------------------------------------------------------------ */
let collapsed = false;
const collapseListeners = new Set<() => void>();
export const sidebarCollapse = {
subscribe(listener: () => void): () => void {
collapseListeners.add(listener);
return () => collapseListeners.delete(listener);
},
getSnapshot(): boolean {
return collapsed;
},
getServerSnapshot(): boolean {
return false;
},
set(value: boolean): void {
collapsed = value;
try {
window.localStorage.setItem(COLLAPSE_KEY, value ? "1" : "0");
} catch {
/* private mode */
}
collapseListeners.forEach((listener) => listener());
},
hydrate(): void {
try {
collapsed = window.localStorage.getItem(COLLAPSE_KEY) === "1";
} catch {
collapsed = false;
}
collapseListeners.forEach((listener) => listener());
},
};
function useCollapsed(): boolean {
return useSyncExternalStore(
sidebarCollapse.subscribe,
sidebarCollapse.getSnapshot,
sidebarCollapse.getServerSnapshot,
);
}
/* ------------------------------------------------------------------ */
/* Desktop rail + mobile drawer */
/* ------------------------------------------------------------------ */
export function Sidebar() {
const isCollapsed = useCollapsed();
const { t } = useI18n();
return (
<aside
aria-label={t("sidebar.label")}
className={cn(
"fixed inset-y-0 left-0 z-40 hidden p-3 transition-[width] duration-200 lg:flex",
isCollapsed ? "w-[84px]" : "w-[268px]",
)}
>
{/* One tall inset glass panel, so the ice scene shows around it. */}
<div className="sidebar-surface flex min-h-0 flex-1 flex-col px-2.5 py-3">
<NavContent collapsed={isCollapsed} desktop />
</div>
</aside>
);
}
export function MobileSidebar() {
const open = useSidebarOpen();
const { t } = useI18n();
/* Back closes the drawer before it navigates away. */
const { skipRewind } = useBackClose(open, () => sidebarOpen.set(false));
return (
<AnimatePresence>
{open ? (
<motion.div
className="fixed inset-0 z-50 flex lg:hidden"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<button
type="button"
aria-label={t("sidebar.closeMenu")}
onClick={() => sidebarOpen.set(false)}
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
/>
<motion.aside
aria-label={t("common.menu")}
initial={{ x: -280 }}
animate={{ x: 0 }}
exit={{ x: -280 }}
transition={springSheet}
drag="x"
dragConstraints={{ left: -280, right: 0 }}
dragElastic={{ left: 0.45, right: 0 }}
dragMomentum={false}
onDragEnd={(_, gesture) => {
if (gesture.offset.x < -80 || gesture.velocity.x < -500) sidebarOpen.set(false);
}}
className="sidebar-surface relative z-10 flex h-full w-[272px] flex-col rounded-l-none rounded-r-[1.5rem] px-2.5 py-3 pb-safe"
>
<NavContent
onNavigate={() => {
skipRewind();
sidebarOpen.set(false);
}}
/>
</motion.aside>
</motion.div>
) : null}
</AnimatePresence>
);
}
/** Spacer so page content clears the fixed rail (desktop only). */
export function SidebarOffset() {
const isCollapsed = useCollapsed();
return (
<div
aria-hidden
className={cn("hidden shrink-0 transition-[width] duration-200 lg:block", isCollapsed ? "w-[84px]" : "w-[268px]")}
/>
);
}