freezmo/components/LibraryScreen.tsx
Martin Dvorak 9fb728d735 Mobile UI pass: sheet swipe, ice-scene layering, contrast, touch targets
Phones (<=639px) only for layout/gestures; the theme-level fixes apply
everywhere, as they are token/design changes.

Settings sheet
- Swipe-to-dismiss reusing the InstallSheet gesture: the sheet follows the
  finger, closes past ~90px or on a fast flick, snaps back otherwise. Drag
  starts only from the handle/header and only while the body is scrolled to
  the top. Backdrop tap still closes.
- Fixed header + scrollable body: pb-safe + spacer, so nothing is clipped;
  a scroll cue (chevron) fades in while more content is below and out at
  the end.
- Show/Save stack under the field at 44px on phones; close, Test connection
  and Remove key are 44px too. Remove key is now a rose destructive action
  with a confirmation that the full-screen key setup comes back.
- API key note split into a short privacy line plus a collapsible
  'Using the local daemon?' tip (OLLAMA_AUTH=local / .env.local / signin).
- Fixed the missing space in the English tip ('ollama signin instead.').
- Health: kept the auto-check and banner; added a loading row and a
  'Checked just now' / 'Checked at HH:MM' freshness label (also for errors).

Ice scene / readability
- Verified the orbs were never above content (fixed z-index:-1 layer,
  pointer-events:none); they were just shining through the glass. Phones get
  lower blob/orb opacity and orbs tucked to the edges; the bottom-right orb
  is moved out from under the tab bar and the tab bar paints a more opaque
  surface so its labels hold contrast.

Contrast / themes
- Dark --text-subtle raised to #9db1d0 (8.6:1 page, 7.2:1 glass); helper
  text now uses the tokens.
- Disabled buttons are a visible muted chip (.btn-disabled) instead of a
  40%-opacity ghost.
- One ice primary gradient in both themes; danger/success now actually show
  their colour (bg-none strips the primary background-image that used to
  paint over !bg-rose-600).
- Light mode: cool card rims instead of white-on-white, stronger shadow.

Redundancy / touch
- Removed only the header gear; the hamburger drawer (folders, Settings,
  theme) and the tab-bar Settings stay.
- Theme toggle is a bordered chip with an action aria-label (drawer row too).
- Empty library hides the folder pills, demotes Import to a quiet link and
  keeps a single primary CTA. 44px targets for nav rows, segmented control
  and folder pills on phones.
- Fixed a pre-existing 16px horizontal overflow (header -mx-4 vs a
  padding-less parent) and let info values wrap instead of truncating.

Verified: mobile suite 47/47 (EN+CS, 360/390px), pixel-sampled contrast
audit 0 runs below WCAG AA (8 runs, both themes/locales; axe marks the glass
'incomplete'), i18n 27/27, desktop regression 72/72, lint + build clean.
Service worker cache bumped to freezmo-v5.
2026-10-08 17:37:51 +00:00

372 lines
15 KiB
TypeScript

"use client";
import Link from "next/link";
import { useMemo, useRef, useState, useSyncExternalStore } from "react";
import { DeckCard } from "@/components/DeckCard";
import { FolderBar } from "@/components/FolderBar";
import { FolderIcon, UploadIcon } from "@/components/icons";
import { Button, EmptyState } from "@/components/ui";
import { folderStore, renameFolder } from "@/lib/folders";
import { useI18n } from "@/lib/i18n";
import { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav";
import { openSettings } from "@/lib/ui-events";
import { UNORGANIZED_ID, type Deck } from "@/lib/schemas";
import { deckStore, deleteFolder, importDeck, sortDecks, upsertDeck } from "@/lib/storage";
import { cn } from "@/lib/utils";
/**
* Dashboard: page title, folder pills, then a spacious responsive grid of
* deck cards grouped by folder.
*/
export function LibraryScreen() {
const decks = useSyncExternalStore(deckStore.subscribe, deckStore.getSnapshot, deckStore.getServerSnapshot);
const folders = useSyncExternalStore(
folderStore.subscribe,
folderStore.getSnapshot,
folderStore.getServerSnapshot,
);
const selected = useSelectedFolder();
const setSelected = folderSelection.set;
const { t, plural } = useI18n();
const [message, setMessage] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
const [editingFolder, setEditingFolder] = useState<{ id: string; name: string } | null>(null);
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
const importRef = useRef<HTMLInputElement>(null);
const sorted = useMemo(() => sortDecks(decks), [decks]);
const folderList = useMemo(
() => [...folders].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" })),
[folders],
);
const counts = useMemo(() => {
const map: Record<string, number> = {};
for (const folder of folderList) 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, folderList]);
const groups = useMemo(() => {
const unorganized: { id: string; name: string; decks: Deck[]; virtual: boolean } = {
id: UNORGANIZED_ID,
name: t("common.unorganized"),
decks: sorted.filter((deck) => !deck.folderId),
virtual: true,
};
if (selected === UNORGANIZED_ID) return [unorganized];
if (selected !== ALL_FOLDERS) {
const folder = folderList.find((entry) => entry.id === selected);
if (!folder) return [unorganized];
return [
{ id: folder.id, name: folder.name, decks: sorted.filter((deck) => deck.folderId === folder.id), virtual: false },
];
}
const named = folderList.map((folder) => ({
id: folder.id,
name: folder.name,
decks: sorted.filter((deck) => deck.folderId === folder.id),
virtual: false,
}));
return [...named, unorganized];
}, [folderList, selected, sorted, t]);
const totalActivities = decks.reduce((sum, deck) => sum + deck.activities.length, 0);
const bestEver = decks.reduce((best, deck) => Math.max(best, deck.bestScore ?? 0), 0);
const played = decks.some((deck) => deck.attempts > 0);
const handleImport = async (file: File | undefined) => {
if (!file) return;
try {
const text = await file.text();
const result = importDeck(text);
if ("error" in result) setMessage({ tone: "error", text: result.error });
else setMessage({ tone: "ok", text: t("library.imported", { title: result.deck.title }) });
} catch {
setMessage({ tone: "error", text: t("library.couldNotRead") });
}
};
const removeFolderEverywhere = (folderId: string) => {
deleteFolder(folderId);
setConfirmDelete(null);
setSelected(ALL_FOLDERS);
setMessage({ tone: "ok", text: t("library.folderDeleted") });
};
const isEmpty = sorted.length === 0 && folderList.length === 0;
// Group headings only earn their keep once real folders exist; with none,
// desktop shows a single quiet “All decks” label instead of “Unorganized”.
const hasFolders = folderList.length > 0;
return (
<div className="relative">
{/* page header ---------------------------------------------------- */}
<section className="mb-6 space-y-5">
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="text-[24px] font-semibold leading-tight tracking-[-0.02em] text-[var(--text)] sm:text-[26px]">
{t("library.title")}
</h1>
<p className="mt-1.5 text-[13.5px] text-[var(--text-subtle)]">
{t("library.subtitle")}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{/* With nothing in the library, Import drops to a quiet text link
so the single primary action is “Make your first deck”. */}
{isEmpty ? (
<button
type="button"
onClick={() => importRef.current?.click()}
className="inline-flex items-center gap-1.5 text-[13px] font-medium text-[var(--text-muted)] transition hover:text-[var(--text)] hover:underline"
>
<UploadIcon className="size-4" />
{t("library.import")}
</button>
) : (
<>
<Button
variant="secondary"
size="md"
className="touch-target lg:hidden"
onClick={() => importRef.current?.click()}
>
<UploadIcon className="size-4" />
{t("library.import")}
</Button>
<button
type="button"
onClick={() => importRef.current?.click()}
className="hidden items-center gap-1.5 text-[13px] font-medium text-[var(--text-muted)] transition hover:text-[var(--text)] hover:underline lg:inline-flex"
>
<UploadIcon className="size-4" />
{t("library.import")}
</button>
</>
)}
<input
ref={importRef}
type="file"
accept="application/json,.json"
className="sr-only"
onChange={(event) => {
void handleImport(event.target.files?.[0]);
event.target.value = "";
}}
/>
</div>
</div>
{/* Secondary stats folded into the header as quiet text on desktop,
where the sidebar already shows per-folder counts. */}
{decks.length > 0 ? (
<p className="text-[13px] text-[var(--text-subtle)] lg:hidden">
{plural(decks.length, "stats.decks")}
<span aria-hidden> · </span>
{plural(folderList.length, "stats.folders")}
<span aria-hidden> · </span>
{plural(totalActivities, "stats.activities")}
{played ? (
<>
<span aria-hidden> · </span>
{t("library.stats.best", { n: bestEver })}
</>
) : null}
</p>
) : null}
{/* Mobile folder switcher; the sidebar covers desktop. With an empty
library there is nothing to filter, and the pills would compete
with the empty state's single call to action. */}
{!isEmpty ? (
<FolderBar
className="lg:hidden"
folders={folderList}
counts={counts}
selected={selected}
onSelect={(id) => {
setSelected(id);
setConfirmDelete(null);
}}
onCreated={(id) => {
setSelected(id);
setMessage({
tone: "ok",
text: t("library.folderCreated"),
});
}}
/>
) : null}
{message ? (
<p
role="status"
className={cn(
"flex items-center gap-2 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] px-3.5 py-2.5 text-[13px] font-medium",
message.tone === "ok" ? "text-emerald-700 dark:text-emerald-300" : "text-rose-700 dark:text-rose-300",
)}
>
{message.text}
</p>
) : null}
</section>
{/* deck grid ------------------------------------------------------ */}
{isEmpty ? (
<EmptyState
title={t("library.noDecks")}
action={
<Link href="/create" className="btn-primary touch-target h-10 px-4 text-sm">
{t("library.makeFirst")}
</Link>
}
>
{t("library.emptyBody")}
<span className="mt-3 block text-[12.5px] text-[var(--text-subtle)]">
{t("library.emptyHint")}{" "}
<button
type="button"
onClick={openSettings}
className="font-medium text-[var(--text-muted)] underline underline-offset-2 hover:text-[var(--text)]"
>
{t("library.emptySettings")}
</button>
.
</span>
</EmptyState>
) : (
<div className="space-y-8">
{groups.map((group) => {
const isEditing = editingFolder?.id === group.id;
return (
<section key={group.id} aria-label={group.name}>
{/* group header -------------------------------------- */}
<div className={cn("mb-4 flex items-center gap-2", !hasFolders && "lg:hidden")}>
<FolderIcon className="size-4 shrink-0 text-[var(--text-subtle)]" />
{isEditing && editingFolder ? (
<span className="flex flex-1 items-center gap-2">
<input
autoFocus
value={editingFolder.name}
onChange={(event) => setEditingFolder({ ...editingFolder, name: event.target.value })}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Enter") {
const result = renameFolder(editingFolder.id, editingFolder.name);
if ("error" in result) setMessage({ tone: "error", text: result.error });
else setEditingFolder(null);
}
if (event.key === "Escape") setEditingFolder(null);
}}
aria-label={t("library.renameFolderAria")}
maxLength={60}
className="min-w-32 max-w-xs flex-1 rounded-lg border border-[var(--hairline)] bg-[var(--surface-strong)] px-2.5 py-1.5 text-[15px] font-semibold text-[var(--text)] outline-none focus:border-accent-400"
/>
<Button
size="sm"
onClick={() => {
const result = renameFolder(editingFolder.id, editingFolder.name);
if ("error" in result) setMessage({ tone: "error", text: result.error });
else setEditingFolder(null);
}}
>
{t("common.save")}
</Button>
</span>
) : (
<button
type="button"
onClick={() => setSelected(group.virtual ? UNORGANIZED_ID : group.id)}
className="truncate text-[15px] font-semibold tracking-[-0.01em] text-[var(--text)]"
>
{group.name}
<span className="ml-2 text-[13px] font-normal tabular-nums text-[var(--text-subtle)]">
{group.decks.length}
</span>
</button>
)}
{!group.virtual && !isEditing ? (
<div className="flex items-center gap-0.5">
<button
type="button"
onClick={() => setEditingFolder({ id: group.id, name: group.name })}
className="rounded-lg px-2 py-1 text-[12.5px] font-medium text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
>
{t("common.rename")}
</button>
{confirmDelete === group.id ? (
<>
<Button size="sm" variant="danger" onClick={() => removeFolderEverywhere(group.id)}>
{t("common.delete")}
</Button>
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(null)}>
{t("common.cancel")}
</Button>
</>
) : (
<button
type="button"
onClick={() => setConfirmDelete(group.id)}
className="rounded-lg px-2 py-1 text-[12.5px] font-medium text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-rose-600 dark:hover:text-rose-300"
>
{t("common.delete")}
</button>
)}
</div>
) : null}
</div>
{/* One quiet label replaces the redundant single-group heading. */}
{!hasFolders ? (
<p className="mb-4 hidden text-[12px] font-medium text-[var(--text-subtle)] lg:block">
{t("common.allDecks")}
</p>
) : null}
{confirmDelete === group.id ? (
<p className="mb-3 text-[12.5px] text-[var(--text-muted)]">
{plural(group.decks.length, "library.deleteWarning")}
</p>
) : null}
{group.decks.length === 0 ? (
<div className="rounded-2xl border border-dashed border-[var(--hairline)] px-5 py-8 text-center text-[13px] text-[var(--text-subtle)]">
{group.virtual ? t("library.nothingUnfiled") : t("library.emptyFolder")}
</div>
) : (
<ul className="grid list-none grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4 lg:grid-cols-[repeat(auto-fill,minmax(320px,1fr))]">
{group.decks.map((deck) => (
<DeckCard
key={deck.id}
deck={deck}
onMove={(folderId) => {
upsertDeck({ ...deck, folderId });
setMessage({
tone: "ok",
text: folderId ? t("library.deckMoved") : t("library.deckMovedUnorganized"),
});
}}
/>
))}
</ul>
)}
</section>
);
})}
</div>
)}
</div>
);
}