Native-feel pass: PWA integration, system back, offline, haptics, undo

Mobile only (<=639px / coarse pointers); desktop keeps its behaviour.

System integration
- Manifest: id, display_override, monochrome icon, Make my homework
  shortcut and a share target (text/URL via GET, files via POST).
  iOS startup images for the common iPhone sizes. Pinch-zoom is allowed
  again (double-tap zoom is disabled via touch-action instead).
- Share target: /share chooser with New deck / Make my homework; POSTed
  files wait in a 10-minute in-memory store, reach the wizard through
  sessionStorage and never touch disk.
- Web Share: Share rows for decks (JSON file where supported) and the
  homework result, with a clipboard fallback and a toast.
- Offline: a quiet pill appears and Freeze / mode cards are disabled
  with a clear reason; input is never lost (error cards keep Retry).
- State: wizard drafts (text, options, photos up to a size budget)
  survive reloads and OS kills and are cleared on success; re-tapping
  the active tab scrolls to the top; the deck page shows a skeleton
  instead of a spinner.

Navigation and gestures
- System Back closes the topmost layer first: a small history-entry
  stack (lib/use-back-close.ts) covers the drawer, Settings sheet,
  install sheet, deck actions panel and one wizard step; navigations
  are never rewound and stale entries are skipped.
- Destructive-but-reversible actions use Undo toasts: deleting a deck
  (no confirm) and removing a file in the wizard. Irreversible ones
  keep their confirm.

Input and feedback
- Every phone input got inputmode / enterkeyhint / autocomplete /
  autocapitalize / spellcheck; Enter on the last field advances the
  wizard; a clipboard-paste button appears where the API exists.
- Haptics behind a Settings toggle (on by default): tab switches,
  toggles, correct/wrong, completion; Vibration API + the iOS hidden
  switch tick, throttled and silent everywhere else.
- Wake lock during the study feed and homework guide, released on
  leave and re-acquired when the tab returns.

Verified: new native suite 35/35 (manifest/head/viewport, offline,
share target GET + POST, back-gesture layers, undo, share fallback,
tab re-tap, haptics persistence, draft restore), regression 74/74,
mobile 52/52, wizard 80/80, declutter 116/116, animation 8/8,
i18n 25/25. Lint + build clean. SW freezmo-v23.

Needs a real device (documented in the README): iOS haptic tick,
system share sheet entry, wake-lock grant, iPhone startup images,
iOS edge-swipe back, install prompts. Pull-to-refresh and the app
badge were skipped on purpose.
This commit is contained in:
Martin Dvořák 2026-10-10 12:16:03 +00:00
commit 4369ba1a17
34 changed files with 1354 additions and 65 deletions

View file

@ -7,13 +7,17 @@ import { useState } from "react";
import { ApiError, generateDeck } from "@/lib/client-api";
import { activityTypes, materialiseActivities } from "@/lib/deck-ops";
import { createFolder as makeFolder, listFolders } from "@/lib/folders";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { springGentle } from "@/lib/motion";
import { UNORGANIZED_ID, type Deck } from "@/lib/schemas";
import { shareDeck } from "@/lib/share";
import { appendActivities, deleteDeck, downloadDeck, renameDeck, upsertDeck } from "@/lib/storage";
import { showToast } from "@/lib/toast";
import { useBackClose } from "@/lib/use-back-close";
import { useIsPhone } from "@/lib/use-phone";
import { cn, formatDate, truncate } from "@/lib/utils";
import { ChevronDownIcon, DownloadIcon, EllipsisIcon, FolderIcon, PlayIcon, RefreshIcon } from "@/components/icons";
import { ChevronDownIcon, DownloadIcon, EllipsisIcon, FolderIcon, PlayIcon, RefreshIcon, ShareIcon } from "@/components/icons";
import { Button, ProgressBar } from "@/components/ui";
type Busy = null | "more" | "regenerate";
@ -41,13 +45,15 @@ export function DeckCard({
const [menuOpen, setMenuOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [title, setTitle] = useState(deck.title);
const [confirmDelete, setConfirmDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [addCount, setAddCount] = useState(5);
const [newFolder, setNewFolder] = useState<string | null>(null);
const [expanded, setExpanded] = useState(false);
/* System Back closes the actions panel first. */
useBackClose(isPhone && menuOpen, () => setMenuOpen(false));
const hasSource = deck.sourceText.trim().length > 20;
const saveTitle = () => {
@ -230,7 +236,10 @@ export function DeckCard({
type="button"
aria-label={t("deck.actions")}
aria-expanded={menuOpen}
onClick={() => setMenuOpen((value) => !value)}
onClick={() => {
haptic("tap");
setMenuOpen((value) => !value);
}}
className={cn(
"relative z-10 grid size-8 shrink-0 place-items-center rounded-full text-[var(--text-muted)] transition hover:bg-[var(--hover)] hover:text-[var(--text)] lg:-mt-1.5",
menuOpen && "bg-[var(--hover)] text-[var(--text)]",
@ -357,6 +366,18 @@ export function DeckCard({
<DownloadIcon className="size-4 text-[var(--text-subtle)]" />
{t("deck.export")}
</button>
<button
type="button"
className={menuRow}
onClick={() => {
setMenuOpen(false);
void shareDeck(deck);
}}
disabled={Boolean(busy)}
>
<ShareIcon className="size-4 text-[var(--text-subtle)]" />
{t("deck.share")}
</button>
<button
type="button"
className={menuRow}
@ -367,23 +388,25 @@ export function DeckCard({
{t("deck.regenerate")}
</button>
{confirmDelete ? (
<div className="flex items-center gap-2 px-3 py-2">
<Button size="sm" variant="danger" onClick={() => deleteDeck(deck.id)}>
{t("deck.reallyDelete")}
</Button>
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>
{t("common.cancel")}
</Button>
</div>
) : (
<button type="button" className={cn(menuRow, "text-rose-600 dark:text-rose-300")} onClick={() => setConfirmDelete(true)}>
<span aria-hidden className="w-4 text-center">
⌫
</span>
{t("deck.delete")}
</button>
)}
{/* Deleting is reversible: no confirm, just an Undo toast. */}
<button
type="button"
className={cn(menuRow, "text-rose-600 dark:text-rose-300")}
onClick={() => {
setMenuOpen(false);
deleteDeck(deck.id);
showToast({
message: t("toast.deckDeleted"),
actionLabel: t("toast.undo"),
onAction: () => upsertDeck(deck),
});
}}
>
<span aria-hidden className="w-4 text-center">
⌫
</span>
{t("deck.delete")}
</button>
{/* folder ---------------------------------------------------- */}
<div className="mt-2 rounded-xl bg-[var(--surface-sunken)] p-2.5">

View file

@ -16,6 +16,7 @@ import {
} from "@/components/icons";
import { Spinner } from "@/components/ui";
import { useI18n } from "@/lib/i18n";
import { useBackClose } from "@/lib/use-back-close";
import {
detectBrowser,
detectPlatform,
@ -56,6 +57,9 @@ export function InstallSheet() {
const { t } = useI18n();
const domain = typeof window === "undefined" ? "" : window.location.hostname;
/* System Back closes the sheet first. */
useBackClose(open, () => setOpen(false));
/** Everything needed to render the sheet, or null if it shouldn't appear. */
const prepare = useCallback((): SheetInfo | null => {
const platform = detectPlatform();

View file

@ -0,0 +1,32 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { useI18n } from "@/lib/i18n";
import { fade } from "@/lib/motion";
import { useOnline } from "@/lib/use-online";
/** A quiet offline pill under the header; saved decks keep working offline. */
export function OfflineBanner() {
const online = useOnline();
const { t } = useI18n();
return (
<AnimatePresence>
{!online ? (
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
transition={fade}
role="status"
className="pointer-events-none fixed inset-x-0 top-0 z-[60] flex justify-center px-4 pt-safe sm:hidden"
>
<p className="rounded-full border border-amber-300/70 bg-amber-50/95 px-3.5 py-1.5 text-[12px] font-semibold text-amber-900 shadow-lift backdrop-blur-xl dark:border-amber-400/30 dark:bg-amber-500/20 dark:text-amber-100">
{t("offline.banner")}
</p>
</motion.div>
) : null}
</AnimatePresence>
);
}

View file

@ -1,13 +1,15 @@
"use client";
import { AnimatePresence, motion, useDragControls, useReducedMotion } from "framer-motion";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { LOCALES, useI18n, type Locale } from "@/lib/i18n";
import { haptic } from "@/lib/haptics";
import { springSheet } from "@/lib/motion";
import { clearApiKey, saveSettings, settingsStore } from "@/lib/settings";
import { useBackClose } from "@/lib/use-back-close";
import { cn } from "@/lib/utils";
import { openInstallSheet, useInstallAvailable } from "@/lib/install";
import { clearApiKey, saveSettings } from "@/lib/settings";
import { useHealth } from "@/lib/use-health";
import {
AlertTriangleIcon,
@ -37,6 +39,13 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
const { health, loading, error, refresh, apiKey, checkedAt } = useHealth();
const installAvailable = useInstallAvailable();
const { locale, setLocale, t, plural } = useI18n();
const settings = useSyncExternalStore(
settingsStore.subscribe,
settingsStore.getSnapshot,
settingsStore.getServerSnapshot,
);
/* The system Back gesture closes the sheet instead of leaving the page. */
useBackClose(open, onClose);
const [keyDraft, setKeyDraft] = useState(apiKey);
const [reveal, setReveal] = useState(false);
const [saved, setSaved] = useState(false);
@ -221,7 +230,10 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
key={entry.id}
type="button"
aria-pressed={locale === entry.id}
onClick={() => setLocale(entry.id)}
onClick={() => {
haptic("toggle");
setLocale(entry.id);
}}
className={cn("relative", phone && "seg-slide")}
>
{phone && locale === entry.id ? <SegmentedPill layoutId="language-pill" /> : null}
@ -306,6 +318,42 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
</p>
</div>
</details>
{/* haptics: best-effort vibration feedback */}
<div className="flex items-center justify-between gap-3 border-t border-[var(--hairline-soft)] pt-3">
<span className="min-w-0">
<span className="block text-[13px] font-semibold text-[var(--text)]">
{t("settings.haptics")}
</span>
<span className="block text-[11.5px] leading-snug text-[var(--text-subtle)]">
{t("settings.hapticsNote")}
</span>
</span>
<button
type="button"
role="switch"
aria-checked={settings.haptics}
aria-label={t("settings.haptics")}
onClick={() => {
saveSettings({ haptics: !settings.haptics });
haptic("toggle");
}}
className={cn(
"touch-target relative h-7 w-12 shrink-0 rounded-full border transition-colors",
settings.haptics
? "grad-ice border-transparent"
: "border-[var(--hairline)] bg-[var(--surface-sunken)]",
)}
>
<span
aria-hidden
className={cn(
"absolute top-1/2 size-5 -translate-y-1/2 rounded-full bg-white shadow transition-[left] duration-200",
settings.haptics ? "left-6" : "left-0.5",
)}
/>
</button>
</div>
</section>
{/* ----------------------------------------------- install */}

119
components/ShareChooser.tsx Normal file
View file

@ -0,0 +1,119 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Spinner } from "@/components/ui";
import { useI18n } from "@/lib/i18n";
import { setPendingShare, type PendingShareFile } from "@/lib/share-pending";
import { openSettings } from "@/lib/ui-events";
type Payload = { title?: string; text?: string; url?: string; files: PendingShareFile[] };
/**
* The share-target chooser: shows what was shared and lets the user send it
* to New deck or Make my homework. Files are stashed in sessionStorage and
* picked up by the wizard on mount.
*/
export function ShareChooser({
id,
text,
url,
error,
}: {
id?: string;
text?: string;
url?: string;
error?: string;
}) {
const { t } = useI18n();
const router = useRouter();
const [payload, setPayload] = useState<Payload | null>(id ? null : { text, url, files: [] });
const [failed, setFailed] = useState(Boolean(error));
useEffect(() => {
if (!id) return;
let cancelled = false;
void (async () => {
try {
const response = await fetch(`/share-target?id=${encodeURIComponent(id)}`, { cache: "no-store" });
if (!response.ok) throw new Error("expired");
const data = (await response.json()) as Payload;
if (!cancelled) setPayload(data);
} catch {
if (!cancelled) setFailed(true);
}
})();
return () => {
cancelled = true;
};
}, [id]);
const combinedText = [payload?.text, payload?.url].filter(Boolean).join("\n\n").trim();
const fileCount = payload?.files.length ?? 0;
const go = (target: "/create" | "/homework") => {
setPendingShare({ text: combinedText || undefined, files: payload?.files ?? [] });
router.push(target);
};
if (failed) {
return (
<div className="card mx-auto max-w-md space-y-3 p-6 text-center">
<p className="text-3xl" aria-hidden>
🧊
</p>
<h1 className="text-xl font-extrabold text-[var(--text)]">{t(error === "large" ? "share.tooLarge" : "share.expired")}</h1>
<div className="flex justify-center gap-2 pt-1">
<Button onClick={() => router.push("/")}>{t("common.library")}</Button>
<Button variant="secondary" onClick={openSettings}>
{t("common.settings")}
</Button>
</div>
</div>
);
}
if (!payload) {
return (
<div className="flex items-center justify-center gap-3 py-16 text-sm font-semibold text-[var(--text-muted)]">
<Spinner className="size-5" /> {t("share.loading")}
</div>
);
}
return (
<div className="mx-auto max-w-md space-y-4">
<section className="space-y-1.5">
<h1 className="text-[26px] font-semibold leading-tight tracking-[-0.02em] text-[var(--text)]">
{t("share.title")}
</h1>
<p className="text-[14px] text-frost-600 dark:text-frost-300">{t("share.intro")}</p>
</section>
<div className="card space-y-2 p-4">
<p className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">{t("share.preview")}</p>
{fileCount > 0 ? (
<p className="text-[13px] font-medium text-[var(--text)]">
{fileCount === 1 ? payload.files[0].name : `${fileCount} files`}
</p>
) : null}
{combinedText ? (
<p className="line-clamp-4 text-[13px] leading-relaxed text-[var(--text-muted)]">{combinedText}</p>
) : null}
{fileCount === 0 && !combinedText ? (
<p className="text-[13px] text-[var(--text-subtle)]">{t("share.nothing")}</p>
) : null}
</div>
<div className="grid gap-2">
<Button size="lg" className="touch-target w-full" onClick={() => go("/create")}>
{t("common.newDeck")}
</Button>
<Button size="lg" variant="secondary" className="touch-target w-full" onClick={() => go("/homework")}>
{t("homework.nav")}
</Button>
</div>
</div>
);
}

View file

@ -17,12 +17,14 @@ import {
} 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";
@ -303,7 +305,10 @@ function NavContent({
</button>
<button
type="button"
onClick={toggle}
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")}
@ -396,6 +401,8 @@ export function Sidebar() {
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>
@ -427,7 +434,12 @@ export function MobileSidebar() {
}}
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={() => sidebarOpen.set(false)} />
<NavContent
onNavigate={() => {
skipRewind();
sidebarOpen.set(false);
}}
/>
</motion.aside>
</motion.div>
) : null}

View file

@ -8,9 +8,11 @@ import { ActivityRenderer } from "@/components/activities";
import { celebrate } from "@/lib/confetti";
import { ApiError, generateDeck } from "@/lib/client-api";
import { materialiseActivities } from "@/lib/deck-ops";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import type { Activity, Deck } from "@/lib/schemas";
import { recordAttempt, upsertDeck } from "@/lib/storage";
import { useWakeLock } from "@/lib/use-wake-lock";
import { cn } from "@/lib/utils";
import { BoltIcon, FlameIcon, XIcon } from "@/components/icons";
import { Button, ProgressBar } from "@/components/ui";
@ -21,6 +23,8 @@ export type AttemptResult = { correct: boolean; userAnswer?: string };
export function StudyFeed({ deck }: { deck: Deck }) {
const { t } = useI18n();
/* Keep the screen awake for the whole study session (feature-detected). */
useWakeLock(true);
const [currentDeck, setCurrentDeck] = useState(deck);
const [queue, setQueue] = useState<Activity[]>(deck.activities);
const [index, setIndex] = useState(0);
@ -108,6 +112,7 @@ export function StudyFeed({ deck }: { deck: Deck }) {
// 0% attempt before the feed had snapped back to the first slide.
if (answered.length > 0) {
recordAttempt(currentDeck.id, { scorePercent: score, correct, total });
haptic("celebrate");
void celebrate("big");
}
}
@ -120,12 +125,14 @@ export function StudyFeed({ deck }: { deck: Deck }) {
return { ...current, [activity.id]: { correct, userAnswer: meta?.userAnswer } };
});
if (correct) {
haptic("success");
const nextStreak = streak + 1;
setStreak(nextStreak);
setBestStreak((best) => Math.max(best, nextStreak));
setXp((value) => value + activity.xp);
if (nextStreak > 0 && nextStreak % 5 === 0) void celebrate("normal");
} else {
haptic("error");
setStreak(0);
}
},

View file

@ -5,6 +5,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { GearIcon, HomeIcon, PlusIcon } from "@/components/icons";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { springSnappy } from "@/lib/motion";
import { openSettings } from "@/lib/ui-events";
@ -67,6 +68,14 @@ export function TabBar() {
href="/"
aria-current={libraryActive ? "page" : undefined}
className={cn(item, libraryActive ? active : idle)}
onClick={(event) => {
haptic("tap");
// Re-tapping the active tab scrolls back to the top.
if (libraryActive) {
event.preventDefault();
window.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" });
}
}}
>
{pill(libraryActive)}
{icon(<HomeIcon className="size-6" />, libraryActive, "library")}
@ -76,6 +85,13 @@ export function TabBar() {
href="/create"
aria-current={createActive ? "page" : undefined}
className={cn(item, createActive ? active : idle)}
onClick={(event) => {
haptic("tap");
if (createActive) {
event.preventDefault();
window.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" });
}
}}
>
{pill(createActive)}
{icon(
@ -87,7 +103,14 @@ export function TabBar() {
)}
{label(t("common.newDeck"), createActive)}
</Link>
<button type="button" onClick={openSettings} className={cn(item, idle)}>
<button
type="button"
onClick={() => {
haptic("tap");
openSettings();
}}
className={cn(item, idle)}
>
{icon(<GearIcon className="size-6" />, false, "settings")}
{label(t("common.settings"), false)}
</button>

View file

@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import { useI18n } from "@/lib/i18n";
import { haptic } from "@/lib/haptics";
import { cn } from "@/lib/utils";
import { MoonIcon, SunIcon } from "@/components/icons";
@ -64,7 +65,10 @@ export function ThemeToggle({ className }: { className?: string }) {
return (
<button
type="button"
onClick={toggle}
onClick={() => {
haptic("toggle");
toggle();
}}
aria-label={dark ? t("common.switchToLight") : t("common.switchToDark")}
title={dark ? t("common.lightMode") : t("common.darkMode")}
className={cn(

67
components/Toaster.tsx Normal file
View file

@ -0,0 +1,67 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui";
import { springGentle } from "@/lib/motion";
import { toastBus, type Toast } from "@/lib/toast";
/**
* Global toast host: undo for reversible destructive actions, share fallbacks.
* Sits above the tab bar on phones and near the bottom on desktop.
*/
export function Toaster() {
const [toasts, setToasts] = useState<Toast[]>([]);
useEffect(
() =>
toastBus.subscribe((toast) => {
setToasts((current) => [...current.slice(-2), toast]);
window.setTimeout(
() => setToasts((current) => current.filter((entry) => entry.id !== toast.id)),
toast.durationMs ?? 5000,
);
}),
[],
);
const dismiss = (id: number) => setToasts((current) => current.filter((entry) => entry.id !== id));
return (
<div className="pointer-events-none fixed inset-x-0 bottom-[calc(env(safe-area-inset-bottom,0px)+5.25rem)] z-[60] flex flex-col items-center gap-2 px-4 sm:bottom-6">
<AnimatePresence initial={false}>
{toasts.map((toast) => (
<motion.div
key={toast.id}
layout
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
transition={springGentle}
role="status"
className="pointer-events-auto flex w-full max-w-md items-center gap-3 rounded-2xl border border-[var(--glass-border)] bg-[color-mix(in_oklab,var(--surface)_92%,transparent)] px-4 py-3 shadow-lift backdrop-blur-xl"
>
<p className="min-w-0 flex-1 text-[13px] font-medium text-[var(--text)]">{toast.message}</p>
{toast.actionLabel ? (
<button
type="button"
onClick={() => {
toast.onAction?.();
dismiss(toast.id);
}}
className="shrink-0 text-[13px] font-bold text-accent-700 dark:text-accent-200"
>
{toast.actionLabel}
</button>
) : (
<Button size="sm" variant="ghost" className="shrink-0" onClick={() => dismiss(toast.id)} aria-label="Dismiss">
✕
</Button>
)}
</motion.div>
))}
</AnimatePresence>
</div>
);
}

View file

@ -27,12 +27,18 @@ import {
type PreparedImage,
} from "@/lib/image";
import { createFolder, folderStore } from "@/lib/folders";
import { haptic } from "@/lib/haptics";
import { useI18n } from "@/lib/i18n";
import { stepVariants } from "@/lib/motion";
import { UNORGANIZED_ID, type Difficulty } from "@/lib/schemas";
import { takePendingShare } from "@/lib/share-pending";
import { upsertDeck } from "@/lib/storage";
import { showToast } from "@/lib/toast";
import { openSettings } from "@/lib/ui-events";
import { useBackClose } from "@/lib/use-back-close";
import { useIsPhone } from "@/lib/use-phone";
import { useOnline } from "@/lib/use-online";
import { clearWizardDraft, loadWizardDraft, saveWizardDraft } from "@/lib/wizard-draft";
import { cn, uid } from "@/lib/utils";
import { CameraIcon, ChevronDownIcon, FolderIcon, IceCubeIcon, PlusIcon, SnowflakeIcon, SparklesIcon, SunIcon } from "@/components/icons";
import { SegmentedPill } from "@/components/SegmentedPill";
@ -112,6 +118,20 @@ export function UploadScreen() {
const [pasteOpen, setPasteOpen] = useState(false);
const isPhone = useIsPhone();
const reduceMotion = useReducedMotion();
const online = useOnline();
const [clipboardAvailable, setClipboardAvailable] = useState(false);
/* System Back goes one wizard step back (phones), then leaves the page. */
useBackClose(isPhone && step > 1, () => {
setStepDir(-1);
setStep((value) => Math.max(1, value - 1));
});
useEffect(() => {
setClipboardAvailable(
typeof navigator !== "undefined" && typeof navigator.clipboard?.readText === "function",
);
}, []);
const folders = useSyncExternalStore(
folderStore.subscribe,
@ -264,6 +284,37 @@ export function UploadScreen() {
const imagesSkipped =
images.length + documentImages.length - imagesToSend.length;
/* Restore a draft after an OS kill / reload; clear it on success. */
useEffect(() => {
const draft = loadWizardDraft("deck");
if (!draft) return;
if (draft.text) setText(draft.text);
if (draft.focus) setFocus(draft.focus);
if (draft.difficulty === "easy" || draft.difficulty === "medium" || draft.difficulty === "hard") {
setDifficulty(draft.difficulty);
}
if (draft.count) setCount(draft.count);
if (draft.folderId) setFolderId(draft.folderId);
if (draft.images?.length) setImages(draft.images);
}, []);
/* Content shared in from another app (share target) lands here. */
useEffect(() => {
const pending = takePendingShare();
if (!pending) return;
if (pending.text) setText((current) => (current ? `${current}\n${pending.text}` : pending.text));
if (pending.files.length > 0) void addFiles(pending.files);
}, [addFiles]);
/* Persist the draft while the user works (debounced, best-effort). */
useEffect(() => {
if (phase === "loading") return;
const timer = window.setTimeout(() => {
saveWizardDraft("deck", { text, focus, difficulty, count, folderId, images });
}, 400);
return () => window.clearTimeout(timer);
}, [text, focus, difficulty, count, folderId, images, phase]);
const generate = async () => {
if (!canGenerate) return;
setError(null);
@ -300,6 +351,7 @@ export function UploadScreen() {
attempts: 0,
};
upsertDeck(stored);
clearWizardDraft("deck");
router.push(`/deck/${stored.id}`);
} catch (generateError) {
setError({
@ -330,7 +382,10 @@ export function UploadScreen() {
key={folder.id}
type="button"
aria-pressed={active}
onClick={() => setFolderId(folder.id)}
onClick={() => {
haptic("toggle");
setFolderId(folder.id);
}}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-[13px] font-medium transition",
active
@ -369,6 +424,10 @@ export function UploadScreen() {
aria-label={t("common.newFolderName")}
placeholder={t("upload.folderPlaceholder")}
maxLength={60}
enterKeyHint="done"
autoCapitalize="words"
autoComplete="off"
spellCheck={false}
className="w-32 rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-1.5 text-sm outline-none"
/>
<Button
@ -410,7 +469,10 @@ export function UploadScreen() {
type="button"
role="radio"
aria-checked={selected}
onClick={() => setDifficulty(option.value)}
onClick={() => {
haptic("toggle");
setDifficulty(option.value);
}}
className={cn(
"relative flex flex-col items-center gap-1 overflow-hidden rounded-2xl border px-2 py-3 text-center backdrop-blur-xl transition-colors",
selected && isPhone
@ -448,7 +510,10 @@ export function UploadScreen() {
key={option}
type="button"
aria-pressed={count === option}
onClick={() => setCount(option)}
onClick={() => {
haptic("toggle");
setCount(option);
}}
className={cn(
"relative min-w-12 overflow-hidden rounded-xl border-2 px-3 py-1.5 text-sm font-bold transition",
count === option && isPhone
@ -493,11 +558,13 @@ export function UploadScreen() {
</div>
) : null;
const phoneHelper = documentsBusy
? t("upload.readingDocs")
: hasContent
? t("upload.ready")
: t("upload.addToStart");
const phoneHelper = !online
? t("offline.generate")
: documentsBusy
? t("upload.readingDocs")
: hasContent
? t("upload.ready")
: t("upload.addToStart");
/* Phones: the 3-step flow. Same state as the desktop card, different shape. */
if (isPhone) {
@ -622,13 +689,50 @@ export function UploadScreen() {
{t("upload.pasteInstead")}
</Button>
</div>
{clipboardAvailable ? (
<Button
variant="ghost"
size="lg"
className="touch-target w-full"
onClick={() => {
void (async () => {
try {
const clip = await navigator.clipboard.readText();
if (clip) {
setText((current) => (current ? `${current}\n${clip}` : clip));
setPasteOpen(true);
}
haptic("tap");
} catch {
setFileError(t("upload.clipboardDenied"));
}
})();
}}
>
{t("upload.pasteClipboard")}
</Button>
) : null}
{pasteOpen || text.trim().length > 0 ? (
<textarea
value={text}
onChange={(event) => setText(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
if (hasContent && !documentsBusy) {
setStepDir(1);
setStep(2);
}
}
}}
rows={5}
placeholder={t("upload.pastedPlaceholder")}
aria-label={t("upload.pastedNotes")}
inputMode="text"
enterKeyHint="done"
autoComplete="off"
autoCapitalize="sentences"
spellCheck
className="w-full resize-y rounded-2xl border border-white/60 bg-white/55 px-4 py-3 text-sm text-frost-950 outline-none backdrop-blur-xl transition placeholder:text-frost-400 focus:border-accent-400 dark:border-white/12 dark:bg-white/[0.07] dark:text-frost-50"
/>
) : null}
@ -645,7 +749,20 @@ export function UploadScreen() {
/>
<button
type="button"
onClick={() => removeImage(image.id)}
onClick={() => {
const removed = images.find((entry) => entry.id === image.id);
removeImage(image.id);
if (removed) {
showToast({
message: t("toast.fileRemoved"),
actionLabel: t("toast.undo"),
onAction: () =>
setImages((current) =>
current.some((entry) => entry.id === removed.id) ? current : [...current, removed],
),
});
}
}}
aria-label={t("upload.remove", { name: image.name })}
className="absolute -right-1.5 -top-1.5 grid size-6 place-items-center rounded-full bg-frost-950/80 text-[11px] font-bold text-white"
>
@ -676,7 +793,20 @@ export function UploadScreen() {
) : null}
<button
type="button"
onClick={() => removeDocument(entry.id)}
onClick={() => {
const snapshot = documents.find((doc) => doc.id === entry.id);
removeDocument(entry.id);
if (snapshot) {
showToast({
message: t("toast.fileRemoved"),
actionLabel: t("toast.undo"),
onAction: () =>
setDocuments((current) =>
current.some((doc) => doc.id === snapshot.id) ? current : [...current, snapshot],
),
});
}
}}
aria-label={t("upload.remove", { name: entry.name })}
className="grid size-6 place-items-center rounded-full text-[11px] font-bold text-[var(--text-subtle)] transition hover:bg-[var(--hover)] hover:text-[var(--text)]"
>
@ -764,6 +894,11 @@ export function UploadScreen() {
value={focus}
onChange={(event) => setFocus(event.target.value)}
placeholder={t("upload.topicPlaceholder")}
inputMode="text"
enterKeyHint="done"
autoComplete="off"
autoCapitalize="sentences"
spellCheck={false}
className="w-full rounded-2xl border border-white/60 bg-white/55 px-4 py-3 text-sm text-frost-950 outline-none backdrop-blur-xl transition placeholder:text-frost-400 focus:border-accent-400 dark:border-white/12 dark:bg-white/[0.07] dark:text-frost-50"
/>
</div>
@ -874,7 +1009,7 @@ export function UploadScreen() {
{t("common.next")}
</Button>
) : (
<Button size="lg" className="touch-target flex-[1.5]" onClick={() => void generate()} disabled={!canGenerate}>
<Button size="lg" className="touch-target flex-[1.5]" onClick={() => void generate()} disabled={!canGenerate || !online}>
<SparklesIcon className="size-5" /> {t("upload.freezeDeck")}
</Button>
)}

View file

@ -10,6 +10,7 @@ import { Button, ProgressBar } from "@/components/ui";
import { assembleSolution } from "@/lib/homework";
import { useI18n } from "@/lib/i18n";
import type { HomeworkGuideRecord, HomeworkStep } from "@/lib/schemas";
import { useWakeLock } from "@/lib/use-wake-lock";
import { CopyButton } from "./CopyButton";
@ -33,6 +34,8 @@ export function HomeworkGuide({
againLoading: boolean;
}) {
const { t } = useI18n();
/* Keep the screen awake while working through the guide. */
useWakeLock(true);
const steps = record.steps;
const slideCount = steps.length + 1; // + the solution slide
const [index, setIndex] = useState(0);

View file

@ -16,8 +16,12 @@ import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas";
import { ACCEPTED_TYPES, formatBytes, imageFilesFromDataTransfer } from "@/lib/image";
import { useI18n } from "@/lib/i18n";
import { stepVariants } from "@/lib/motion";
import { takePendingShare } from "@/lib/share-pending";
import { useBackClose } from "@/lib/use-back-close";
import type { useNotesIntake } from "@/lib/use-notes-intake";
import { useIsPhone } from "@/lib/use-phone";
import { useOnline } from "@/lib/use-online";
import { clearWizardDraft, loadWizardDraft, saveWizardDraft } from "@/lib/wizard-draft";
import { openSettings } from "@/lib/ui-events";
import { cn, truncate } from "@/lib/utils";
@ -76,6 +80,43 @@ export function HomeworkInput({
const [pasteOpen, setPasteOpen] = useState(false);
const isPhone = useIsPhone();
const reduceMotion = useReducedMotion();
const online = useOnline();
const [clipboardAvailable, setClipboardAvailable] = useState(false);
/* System Back goes one wizard step back (phones), then leaves the page. */
useBackClose(isPhone && step > 1, () => {
setStepDir(-1);
setStep(1);
});
useEffect(() => {
setClipboardAvailable(
typeof navigator !== "undefined" && typeof navigator.clipboard?.readText === "function",
);
}, []);
/* Restore a draft after an OS kill / reload. */
useEffect(() => {
const draft = loadWizardDraft("homework");
if (draft?.text) onTextChange(draft.text);
// eslint-disable-next-line react-hooks/exhaustive-deps -- restore once on mount
}, []);
/* Content shared in from another app (share target) lands here. */
useEffect(() => {
const pending = takePendingShare();
if (!pending) return;
if (pending.text) onTextChange(pending.text);
if (pending.files.length > 0) void intake.addFiles(pending.files);
// eslint-disable-next-line react-hooks/exhaustive-deps -- once on mount
}, [intake.addFiles]);
/* Persist the typed assignment while the user works (debounced). */
useEffect(() => {
if (!isPhone) return;
const timer = window.setTimeout(() => saveWizardDraft("homework", { text }), 400);
return () => window.clearTimeout(timer);
}, [text, isPhone]);
// Clipboard: screenshots become photos, long copied text becomes the assignment.
useEffect(() => {
@ -286,15 +327,51 @@ export function HomeworkInput({
{t("upload.pasteInstead")}
</Button>
</div>
{clipboardAvailable ? (
<Button
variant="ghost"
size="lg"
className="touch-target w-full"
onClick={() => {
void (async () => {
try {
const clip = await navigator.clipboard.readText();
if (clip) {
onTextChange(text ? `${text}\n${clip}` : clip);
setPasteOpen(true);
}
} catch {
/* denied — the textarea still works */
}
})();
}}
>
{t("upload.pasteClipboard")}
</Button>
) : null}
{showPaste ? (
<textarea
id="homework-assignment-phone"
value={text}
onChange={(event) => onTextChange(event.target.value)}
onKeyDown={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
if (canSubmit) {
setStepDir(1);
setStep(2);
}
}
}}
rows={6}
placeholder={t("homework.source.placeholder")}
aria-label={t("homework.source.textLabel")}
inputMode="text"
enterKeyHint="done"
autoComplete="off"
autoCapitalize="sentences"
spellCheck
className="w-full resize-y rounded-2xl border border-white/60 bg-white/55 px-4 py-3 text-sm text-frost-950 outline-none backdrop-blur-xl transition placeholder:text-frost-400 focus:border-accent-400 dark:border-white/12 dark:bg-white/[0.07] dark:text-frost-50"
/>
) : null}
@ -397,13 +474,16 @@ export function HomeworkInput({
<div className="grid gap-3">
{MODES.map((option) =>
modeCard(option, () => {
if (!canSubmit) return;
if (!canSubmit || !online) return;
clearWizardDraft("homework");
onModeChange(option.id);
onSubmit(option.id);
}),
)}
</div>
<p className="text-center text-[12px] text-[var(--text-subtle)]">{t("homework.phone.startHint")}</p>
<p className="text-center text-[12px] text-[var(--text-subtle)]">
{online ? t("homework.phone.startHint") : t("offline.generate")}
</p>
</div>
) : null}
</motion.div>

View file

@ -3,6 +3,7 @@
import { Button } from "@/components/ui";
import { useI18n } from "@/lib/i18n";
import type { HomeworkMakeRecord } from "@/lib/schemas";
import { shareHomework } from "@/lib/share";
import { CopyButton } from "./CopyButton";
@ -39,6 +40,9 @@ export function HomeworkResult({
<div className="flex flex-wrap items-start gap-2">
<CopyButton text={record.answer} />
<Button variant="secondary" className="touch-target" onClick={() => void shareHomework(record)}>
{t("deck.share")}
</Button>
<Button variant="secondary" className="touch-target" onClick={onAgain} loading={againLoading}>
{t("homework.result.again")}
</Button>

View file

@ -16,6 +16,7 @@ import {
import { useI18n } from "@/lib/i18n";
import type { HomeworkMode, HomeworkRecord } from "@/lib/schemas";
import { useNotesIntake } from "@/lib/use-notes-intake";
import { clearWizardDraft } from "@/lib/wizard-draft";
import { HomeworkGuide } from "./HomeworkGuide";
import { HomeworkInput } from "./HomeworkInput";
@ -154,6 +155,7 @@ export function HomeworkScreen({ initialRecordId }: { initialRecordId?: string }
intake.clear();
setText("");
setError(null);
clearWizardDraft("homework");
setView({ kind: "start" });
};