diff --git a/README.md b/README.md index fdfdf7e..6af0567 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,15 @@ no database, no data leaving your machine except the requests you send to Ollama *Edit* link back to its step. A flat Back/Cancel + Next/Freeze bar sits at the bottom above the safe area (the tab bar hides inside the wizard), and it is portalled to `` so the screen entrance animation can never displace it. The desktop page is unchanged. +- **Native-feel touches (phones)**: the Android Back gesture closes the topmost layer first + (sheet, drawer, actions panel, then one wizard step); deleting a deck shows an *Undo* + toast instead of a confirm; the deck menu can share a deck as JSON through the system share + sheet (clipboard fallback); content shared from other apps opens a chooser and lands + pre-filled in either wizard; haptics (Settings → Haptics, on by default) tick on tab + switches, toggles, correct/wrong answers and completion; the screen stays awake during + study sessions and homework guides; wizard drafts survive a reload or an OS kill; re-tapping + the active tab scrolls to the top; an offline pill appears and generation is disabled with + a reason until the connection is back. - **Photos and documents**: JPG/PNG/WEBP/HEIC images plus **PDF, DOCX, PPTX, ODT/ODP/ODS, TXT, MD, CSV** - Documents are read **in the browser**: PDF text layers are extracted, scanned PDF pages are rendered as images for the vision model, DOCX/PPTX text, speaker notes and embedded images are pulled out. @@ -505,12 +514,13 @@ What's included: | Piece | Detail | | --- | --- | -| `app/manifest.ts` | `display: standalone`, portrait, theme/background colours, app shortcuts | -| Icons | 192/512 px, a maskable 512 px icon, and 180/167/152 px `apple-touch-icon`s, all rendered from `assets/app-icon-source.jpeg` | -| iOS meta | `apple-mobile-web-app-capable`, `-title`, `-status-bar-style`, `viewport-fit=cover` | +| `app/manifest.ts` | `id`, `display: standalone`, portrait, theme/background colours, `any` + `maskable` + `monochrome` icons, three app shortcuts (New deck, Make my homework, Library) and a **share target** (text/URL via GET, files via POST) | +| Icons | 192/512 px, a maskable 512 px icon, a monochrome SVG and 180/167/152 px `apple-touch-icon`s, all rendered from `assets/app-icon-source.jpeg` | +| iOS meta | `apple-mobile-web-app-capable`, `-title`, `-status-bar-style`, `viewport-fit=cover`, plus **startup images** for the common iPhone sizes so launch has no white flash | | Service worker | `public/sw.js`, **production only**: cached app shell, stale-while-revalidate for static assets, network-first navigations with an `/offline` fallback. `/api/*` is never cached | | Offline page | `/offline` — "your decks are still here, reconnect to generate" | | Safe areas | `pb-safe` / `pt-safe` utilities plus `pb-tabbar` so nothing hides behind the tab bar | +| Share target | `/share` chooser (New deck / Make my homework); POSTed files wait in a short-lived in-memory store, are handed to the wizard through `sessionStorage`, and are never written to disk | The icons are generated by `scripts/make-icons.mjs` from `assets/app-icon-source.jpeg` (headless Chromium); it is a one-off tool and is not part of the app's dependencies. It also writes @@ -884,10 +894,11 @@ Things I chose while building, with the reasoning: device, uses Chrome's deferred `beforeinstallprompt` for a one-tap install where available, and stays reachable from Settings. It is mounted in the root layout, so it can appear over any screen — including the key gate — without blocking the page underneath. -30. **Phones don't zoom, and mobile fields are 16px.** The viewport sets `maximum-scale=1` / - `user-scalable=no` for an app-like feel, and a mobile-only rule keeps every input and textarea at - 16px so iOS Safari's focus auto-zoom never fires (iOS ignores `user-scalable=no` for that). - Desktop keeps the designed 12–14px field sizes. +30. **Phones use touch-action, not a zoom lock.** The viewport allows pinch-zoom (accessibility), + and double-tap zoom is disabled by `touch-action: manipulation` on the UI chrome instead. A + mobile-only rule keeps every input and textarea at 16px so iOS Safari's focus auto-zoom never + fires (iOS ignores `user-scalable=no` for that anyway). Desktop keeps the designed 12–14px + field sizes. 31. **The app icon drives the palette.** The navy rounded-square artwork in `assets/app-icon-source.jpeg` is the source of truth: `frost-*` is navy-tinted, the accent is glacier cyan, the ice scene uses the artwork's blues, the primary CTA is an icy gradient, and @@ -970,6 +981,26 @@ Things I chose while building, with the reasoning: position across the entrance (5 frames, 60–450ms) from the tab bar, the drawer and the empty state, at 360/390, both themes, both languages and with reduced motion. +39. **Native feel is layered onto the platform, never around it.** The Back gesture closes the + topmost layer through a small history-entry stack (`lib/use-back-close.ts`): each layer pushes + a same-URL entry, only the top of the stack reacts, and a layer closed by a navigation leaves + its entry for the permanent listener to skip. Haptics are best-effort behind a Settings toggle + (Vibration API; the hidden `` tick on iOS, throttled); the wake lock is requested + only while a study feed or guide is open and released on leave. Destructive-but-reversible + actions (delete deck, remove file) became Undo toasts; irreversible ones keep their confirm. + Wizard drafts and the last URL are per-browser; the share target hands POSTed files to the + client through a ten-minute in-memory store so nothing touches disk. Verified by the native + suite (35 checks: manifest/head/viewport, offline banner + disabled generate, share target GET + and POST, back-gesture closing for drawer/sheet/wizard, undo toast, share fallback, tab + re-tap, haptics persistence, draft restore) plus the six standing suites. + + **Needs a real device to verify** (emulation can't do these honestly): the iOS hidden-switch + haptic tick, the Android/iOS **share target** entry in the system share sheet, the actual + **wake lock** grant, the **startup images** on an installed iPhone, the iOS **edge-swipe** + back gesture in standalone, and installability/rich-install prompts (Lighthouse covers the + manifest side). Pull-to-refresh and the app badge were skipped on purpose — the Settings + refresh icon already re-checks the connection, and there is no meaningful badge number. + 14. **`gpt-oss:120b` does all content work — but it cannot read images** (`this model does not support image input`), so `VISION_MODEL` has to stay a multimodal model (`gemma4:31b-cloud`). Text-only inputs — pasted text, PDFs with a text layer, DOCX/PPTX/ODT — never touch the vision diff --git a/app/deck/[id]/page.tsx b/app/deck/[id]/page.tsx index c2cf11e..bb6eac8 100644 --- a/app/deck/[id]/page.tsx +++ b/app/deck/[id]/page.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from "react"; import { ApiKeyGate } from "@/components/ApiKeyGate"; import { StudyFeed } from "@/components/StudyFeed"; -import { Button, Spinner } from "@/components/ui"; +import { Button } from "@/components/ui"; import { useI18n } from "@/lib/i18n"; import type { Deck } from "@/lib/schemas"; import { getDeck } from "@/lib/storage"; @@ -29,9 +29,15 @@ export default function DeckPage() { if (!loaded) { return ( -
-
- {t("deckPage.loading")} +
+
+
+
+
+
+
+
+
); diff --git a/app/layout.tsx b/app/layout.tsx index 3b1041f..fec4a7f 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -2,7 +2,9 @@ import type { Metadata, Viewport } from "next"; import { IceBackdrop } from "@/components/IceBackdrop"; import { InstallSheet } from "@/components/InstallSheet"; +import { OfflineBanner } from "@/components/OfflineBanner"; import { ServiceWorkerRegistrar } from "@/components/ServiceWorkerRegistrar"; +import { Toaster } from "@/components/Toaster"; import "./globals.css"; export const metadata: Metadata = { @@ -18,6 +20,18 @@ export const metadata: Metadata = { capable: true, title: "Freezmo", statusBarStyle: "default", + /* Startup images so launching from the home screen has no white flash. + Sized for the common iPhone logical sizes at their device pixel ratio. */ + startupImage: [ + { url: "/icons/splash-750x1334.png", media: "(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2)" }, + { url: "/icons/splash-828x1792.png", media: "(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2)" }, + { url: "/icons/splash-1170x2532.png", media: "(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3)" }, + { url: "/icons/splash-1179x2556.png", media: "(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3)" }, + { url: "/icons/splash-1284x2778.png", media: "(device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3)" }, + { url: "/icons/splash-1290x2796.png", media: "(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3)" }, + { url: "/icons/splash-1536x2048.png", media: "(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2)" }, + { url: "/icons/splash-1668x2388.png", media: "(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2)" }, + ], }, icons: { icon: [ @@ -43,11 +57,10 @@ export const metadata: Metadata = { export const viewport: Viewport = { width: "device-width", initialScale: 1, - // Phones: no pinch/double-tap zoom (the app-like feel). The input font-size - // rule in globals.css is what actually stops iOS Safari's focus auto-zoom, - // which ignores user-scalable=no. - maximumScale: 1, - userScalable: false, + // Pinch-zoom stays available for accessibility (double-tap zoom is disabled + // by `touch-action: manipulation` on the chrome instead). The input + // font-size rule in globals.css stops iOS Safari's focus auto-zoom, which + // ignores the viewport meta anyway. viewportFit: "cover", themeColor: [ { media: "(prefers-color-scheme: light)", color: "#f4f7fd" }, @@ -82,6 +95,8 @@ export default function RootLayout({ children }: { children: React.ReactNode }) {children} + + diff --git a/app/manifest.ts b/app/manifest.ts index a38a6fc..c03ba08 100644 --- a/app/manifest.ts +++ b/app/manifest.ts @@ -6,6 +6,7 @@ import type { MetadataRoute } from "next"; */ export default function manifest(): MetadataRoute.Manifest { return { + id: "/", name: "Freezmo — notes to study feed", short_name: "Freezmo", description: @@ -13,6 +14,7 @@ export default function manifest(): MetadataRoute.Manifest { start_url: "/", scope: "/", display: "standalone", + display_override: ["standalone", "minimal-ui"], orientation: "portrait", background_color: "#0e1424", theme_color: "#0e1424", @@ -21,10 +23,39 @@ export default function manifest(): MetadataRoute.Manifest { { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, { src: "/icons/maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, + { src: "/icons/monochrome.svg", sizes: "any", type: "image/svg+xml", purpose: "monochrome" }, ], shortcuts: [ { name: "New deck", short_name: "New", url: "/create" }, + { name: "Make my homework", short_name: "Homework", url: "/homework" }, { name: "Library", short_name: "Library", url: "/" }, ], + /* Share text and links from other apps (GET). Files are POSTed to the + same route and handed over through a short-lived in-memory store. */ + share_target: { + action: "/share-target", + method: "POST", + enctype: "multipart/form-data", + params: { + title: "title", + text: "text", + url: "url", + files: [ + { + name: "files", + accept: [ + "image/*", + "application/pdf", + "text/*", + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.oasis.opendocument.text", + "application/vnd.oasis.opendocument.presentation", + ], + }, + ], + }, + }, }; } diff --git a/app/share-target/route.ts b/app/share-target/route.ts new file mode 100644 index 0000000..90e0367 --- /dev/null +++ b/app/share-target/route.ts @@ -0,0 +1,55 @@ +import { MAX_SHARE_BYTES, putShare, takeShare, type SharedFile } from "@/lib/share-inbox"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +function asString(value: FormDataEntryValue | null): string | undefined { + return typeof value === "string" && value.trim() ? value.trim().slice(0, 20_000) : undefined; +} + +/** GET /share?id=… — read (and consume) a payload that was POSTed in. */ +export async function GET(request: Request) { + const id = new URL(request.url).searchParams.get("id"); + if (!id) return Response.json({ error: "missing id" }, { status: 400 }); + const payload = takeShare(id); + if (!payload) return Response.json({ error: "expired" }, { status: 404 }); + return Response.json(payload); +} + +/** + * POST /share — the Web Share Target. Text/URL arrive as form fields, files + * as multipart uploads; both are stashed briefly and the browser is redirected + * to the chooser page with an opaque id. + */ +export async function POST(request: Request) { + let form: FormData; + try { + form = await request.formData(); + } catch { + return Response.redirect(new URL("/share?error=bad", request.url), 303); + } + + const uploads = form.getAll("files").filter((entry): entry is File => entry instanceof File); + const total = uploads.reduce((sum, file) => sum + file.size, 0); + if (total > MAX_SHARE_BYTES) { + return Response.redirect(new URL("/share?error=large", request.url), 303); + } + const files: SharedFile[] = []; + for (const file of uploads.slice(0, 6)) { + files.push({ + name: file.name || "shared", + type: file.type || "application/octet-stream", + data: Buffer.from(await file.arrayBuffer()).toString("base64"), + }); + } + + const id = crypto.randomUUID(); + putShare(id, { + title: asString(form.get("title")), + text: asString(form.get("text")), + url: asString(form.get("url")), + files, + }); + + return Response.redirect(new URL(`/share?id=${id}`, request.url), 303); +} diff --git a/app/share/page.tsx b/app/share/page.tsx new file mode 100644 index 0000000..704fd02 --- /dev/null +++ b/app/share/page.tsx @@ -0,0 +1,36 @@ +import { ApiKeyGate } from "@/components/ApiKeyGate"; +import { AppHeader } from "@/components/AppHeader"; +import { ShareChooser } from "@/components/ShareChooser"; +import { MobileSidebar, Sidebar, SidebarOffset } from "@/components/Sidebar"; + +export const metadata = { + title: "Add to Freezmo", +}; + +export default async function SharePage({ + searchParams, +}: { + searchParams: Promise<{ [key: string]: string | string[] | undefined }>; +}) { + const { id, text, url, error } = await searchParams; + return ( + +
+ + + +
+ +
+ +
+
+
+
+ ); +} diff --git a/components/DeckCard.tsx b/components/DeckCard.tsx index 4798c57..8c01438 100644 --- a/components/DeckCard.tsx +++ b/components/DeckCard.tsx @@ -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(null); const [notice, setNotice] = useState(null); const [addCount, setAddCount] = useState(5); const [newFolder, setNewFolder] = useState(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({ {t("deck.export")} + - -
- ) : ( - - )} + {/* Deleting is reversible: no confirm, just an Undo toast. */} + {/* folder ---------------------------------------------------- */}
diff --git a/components/InstallSheet.tsx b/components/InstallSheet.tsx index a9c94d0..d42c435 100644 --- a/components/InstallSheet.tsx +++ b/components/InstallSheet.tsx @@ -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(); diff --git a/components/OfflineBanner.tsx b/components/OfflineBanner.tsx new file mode 100644 index 0000000..10fd7b1 --- /dev/null +++ b/components/OfflineBanner.tsx @@ -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 ( + + {!online ? ( + +

+ {t("offline.banner")} +

+
+ ) : null} +
+ ); +} diff --git a/components/SettingsDialog.tsx b/components/SettingsDialog.tsx index 1df6dbd..518c94f 100644 --- a/components/SettingsDialog.tsx +++ b/components/SettingsDialog.tsx @@ -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 ? : null} @@ -306,6 +318,42 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =

+ + {/* haptics: best-effort vibration feedback */} +
+ + + {t("settings.haptics")} + + + {t("settings.hapticsNote")} + + + +
{/* ----------------------------------------------- install */} diff --git a/components/ShareChooser.tsx b/components/ShareChooser.tsx new file mode 100644 index 0000000..a67c389 --- /dev/null +++ b/components/ShareChooser.tsx @@ -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(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 ( +
+

+ 🧊 +

+

{t(error === "large" ? "share.tooLarge" : "share.expired")}

+
+ + +
+
+ ); + } + + if (!payload) { + return ( +
+ {t("share.loading")} +
+ ); + } + + return ( +
+
+

+ {t("share.title")} +

+

{t("share.intro")}

+
+ +
+

{t("share.preview")}

+ {fileCount > 0 ? ( +

+ {fileCount === 1 ? payload.files[0].name : `${fileCount} files`} +

+ ) : null} + {combinedText ? ( +

{combinedText}

+ ) : null} + {fileCount === 0 && !combinedText ? ( +

{t("share.nothing")}

+ ) : null} +
+ +
+ + +
+
+ ); +} diff --git a/components/Sidebar.tsx b/components/Sidebar.tsx index 8c26c2f..8158f5c 100644 --- a/components/Sidebar.tsx +++ b/components/Sidebar.tsx @@ -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({ diff --git a/components/ThemeToggle.tsx b/components/ThemeToggle.tsx index 815ae33..0d7662d 100644 --- a/components/ThemeToggle.tsx +++ b/components/ThemeToggle.tsx @@ -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 ( + ) : ( + + )} + + ))} + + + ); +} diff --git a/components/UploadScreen.tsx b/components/UploadScreen.tsx index 008f332..fd49f1e 100644 --- a/components/UploadScreen.tsx +++ b/components/UploadScreen.tsx @@ -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" /> + {clipboardAvailable ? ( + + ) : null} {pasteOpen || text.trim().length > 0 ? (