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.
This commit is contained in:
parent
1dc2992fb5
commit
bb1f4e2018
31 changed files with 1933 additions and 36 deletions
|
|
@ -19,9 +19,14 @@ import { cn } from "@/lib/utils";
|
|||
export function AppHeader({ className, compact = false }: { className?: string; compact?: boolean }) {
|
||||
const { t } = useI18n();
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [settingsFocus, setSettingsFocus] = useState<{ field: "key"; nonce: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onOpen = () => setSettingsOpen(true);
|
||||
const onOpen = (event: Event) => {
|
||||
setSettingsOpen(true);
|
||||
const focus = (event as CustomEvent<{ focus?: string }>).detail?.focus;
|
||||
if (focus === "key") setSettingsFocus({ field: "key", nonce: Date.now() });
|
||||
};
|
||||
window.addEventListener(OPEN_SETTINGS_EVENT, onOpen);
|
||||
return () => window.removeEventListener(OPEN_SETTINGS_EVENT, onOpen);
|
||||
}, []);
|
||||
|
|
@ -78,7 +83,11 @@ export function AppHeader({ className, compact = false }: { className?: string;
|
|||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<SettingsDialog open={settingsOpen} onClose={() => setSettingsOpen(false)} />
|
||||
<SettingsDialog
|
||||
open={settingsOpen}
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
focusField={settingsFocus}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
134
components/DataSection.tsx
Normal file
134
components/DataSection.tsx
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui";
|
||||
import {
|
||||
applyImport,
|
||||
downloadBackup,
|
||||
getStoragePersistence,
|
||||
parseBackup,
|
||||
previewImport,
|
||||
requestStoragePersistence,
|
||||
type BackupFile,
|
||||
type ImportPreview,
|
||||
type PersistenceState,
|
||||
} from "@/lib/backup";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* Settings → Data & backup: export everything to one file, import a backup
|
||||
* with a preview and a merge/replace choice, and show whether the browser
|
||||
* treats this origin's storage as persistent.
|
||||
*/
|
||||
export function DataSection() {
|
||||
const { t } = useI18n();
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [persistence, setPersistence] = useState<PersistenceState | null>(null);
|
||||
const [pending, setPending] = useState<{ backup: BackupFile; preview: ImportPreview } | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void getStoragePersistence().then(setPersistence);
|
||||
}, []);
|
||||
|
||||
const pick = async (file: File | undefined) => {
|
||||
setNotice(null);
|
||||
if (!file) return;
|
||||
const raw = await file.text().catch(() => "");
|
||||
const result = parseBackup(raw);
|
||||
if ("error" in result) {
|
||||
setPending(null);
|
||||
setNotice(result.error);
|
||||
return;
|
||||
}
|
||||
setPending({ backup: result.backup, preview: previewImport(result.backup) });
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setPending(null);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
};
|
||||
|
||||
const apply = (mode: "merge" | "replace") => {
|
||||
if (!pending) return;
|
||||
const done = applyImport(pending.backup, mode);
|
||||
setNotice(t("settings.importDone", { decks: done.decks, homework: done.homework }));
|
||||
reset();
|
||||
};
|
||||
|
||||
const requestPersistent = async () => {
|
||||
const granted = await requestStoragePersistence();
|
||||
setPersistence(granted ? "persistent" : "best-effort");
|
||||
setNotice(granted ? t("settings.storageGranted") : t("settings.storageDenied"));
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mb-4 space-y-2 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-3">
|
||||
<h3 className="text-sm font-semibold text-frost-950 dark:text-frost-50">{t("settings.data")}</h3>
|
||||
<p className="text-[11.5px] leading-relaxed text-[var(--text-subtle)]">{t("settings.dataNote")}</p>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Button size="sm" variant="secondary" className="touch-target w-full" onClick={() => downloadBackup()}>
|
||||
{t("settings.exportAll")}
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" className="touch-target w-full" onClick={() => fileRef.current?.click()}>
|
||||
{t("settings.importBackup")}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
className="hidden"
|
||||
onChange={(event) => void pick(event.target.files?.[0])}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] leading-relaxed text-[var(--text-subtle)]">{t("settings.exportNote")}</p>
|
||||
|
||||
{pending ? (
|
||||
<div className="space-y-2 rounded-xl border border-[var(--hairline)] bg-[var(--surface)] p-3">
|
||||
<p className="text-[12px] font-medium text-[var(--text)]">
|
||||
{t("settings.importPreview", {
|
||||
decks: pending.preview.decks.added + pending.preview.decks.replaced,
|
||||
homework: pending.preview.homework.added + pending.preview.homework.replaced,
|
||||
folders: pending.preview.folders.added + pending.preview.folders.replaced,
|
||||
})}
|
||||
</p>
|
||||
<p className="text-[11px] leading-relaxed text-[var(--text-subtle)]">{t("settings.importMergeNote")}</p>
|
||||
<p className="text-[11px] leading-relaxed text-[var(--text-subtle)]">{t("settings.importReplaceNote")}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" onClick={() => apply("merge")}>
|
||||
{t("settings.importMerge")}
|
||||
</Button>
|
||||
<Button size="sm" variant="danger" onClick={() => apply("replace")}>
|
||||
{t("settings.importReplace")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={reset}>
|
||||
{t("settings.importCancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{notice ? <p className="text-[12px] font-medium text-[var(--text-muted)]">{notice}</p> : null}
|
||||
|
||||
<div className="flex items-center justify-between gap-3 border-t border-[var(--hairline-soft)] pt-2">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-[12px] font-semibold text-[var(--text)]">{t("settings.storage")}</span>
|
||||
<span className="block text-[11px] leading-snug text-[var(--text-subtle)]">
|
||||
{persistence === "persistent"
|
||||
? t("settings.storagePersistent")
|
||||
: persistence === "unsupported"
|
||||
? t("settings.storageBestEffort")
|
||||
: t("settings.storageBestEffort")}
|
||||
</span>
|
||||
</span>
|
||||
{persistence === "best-effort" ? (
|
||||
<Button size="sm" variant="secondary" className="shrink-0" onClick={() => void requestPersistent()}>
|
||||
{t("settings.storageRequest")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import Link from "next/link";
|
||||
import { useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
|
||||
import { DeckCard } from "@/components/DeckCard";
|
||||
import { FolderBar } from "@/components/FolderBar";
|
||||
|
|
@ -17,6 +17,7 @@ import { ALL_FOLDERS, folderSelection, useSelectedFolder } from "@/lib/nav";
|
|||
import { springGentle } from "@/lib/motion";
|
||||
import { UNORGANIZED_ID, type Deck } from "@/lib/schemas";
|
||||
import { deckStore, deleteFolder, importDeck, sortDecks, upsertDeck } from "@/lib/storage";
|
||||
import { backupNudgeDue, downloadBackup, snoozeBackupNudge } from "@/lib/backup";
|
||||
import { useIsPhone } from "@/lib/use-phone";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
|
|
@ -46,6 +47,11 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
|
|||
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 [nudgeDue, setNudgeDue] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setNudgeDue(backupNudgeDue(decks.length));
|
||||
}, [decks.length]);
|
||||
const importRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const sorted = useMemo(() => sortDecks(decks), [decks]);
|
||||
|
|
@ -227,6 +233,37 @@ export function LibraryScreen({ initialTab = "decks" }: { initialTab?: "decks" |
|
|||
exit={isPhone ? { opacity: 0, y: -6, transition: { duration: 0.16 } } : undefined}
|
||||
transition={springGentle}
|
||||
>
|
||||
{/* gentle backup nudge — dismissible, never blocks ---------------- */}
|
||||
{nudgeDue ? (
|
||||
<div className="mb-5 flex flex-wrap items-center gap-3 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] px-3.5 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[13px] font-semibold text-[var(--text)]">{t("settings.backupNudgeTitle")}</p>
|
||||
<p className="text-[12px] leading-snug text-[var(--text-subtle)]">{t("settings.backupNudgeBody")}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
downloadBackup();
|
||||
setNudgeDue(false);
|
||||
}}
|
||||
>
|
||||
{t("settings.backupNow")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
snoozeBackupNudge();
|
||||
setNudgeDue(false);
|
||||
}}
|
||||
>
|
||||
{t("settings.backupLater")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* decks: folders + card grid, or a decks-only empty state --------- */}
|
||||
{tab === "decks" && isEmpty ? (
|
||||
<EmptyState
|
||||
|
|
|
|||
31
components/ModelErrorActions.tsx
Normal file
31
components/ModelErrorActions.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { OLLAMA_SETTINGS_URL } from "@/lib/model-errors";
|
||||
import { openSettings } from "@/lib/ui-events";
|
||||
|
||||
/**
|
||||
* The two actions for an exhausted monthly usage: jump to the key field in
|
||||
* Settings, or open Ollama to upgrade the account. Renders nothing for any
|
||||
* other error kind (a plain Retry next to it is enough).
|
||||
*/
|
||||
export function ModelErrorActions({ kind }: { kind?: string }) {
|
||||
const { t } = useI18n();
|
||||
if (kind !== "usage_limit") return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button size="sm" onClick={() => openSettings("key")}>
|
||||
{t("upload.openSettings")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => window.open(OLLAMA_SETTINGS_URL, "_blank", "noopener,noreferrer")}
|
||||
>
|
||||
{t("error.openOllama")}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -5,7 +5,11 @@ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
|
|||
|
||||
import { LOCALES, useI18n, type Locale } from "@/lib/i18n";
|
||||
import { haptic } from "@/lib/haptics";
|
||||
import { modelErrorCopy } from "@/lib/model-errors";
|
||||
import { springSheet } from "@/lib/motion";
|
||||
import { ModelErrorActions } from "@/components/ModelErrorActions";
|
||||
import { DataSection } from "@/components/DataSection";
|
||||
import { SyncSection } from "@/components/SyncSection";
|
||||
import { clearApiKey, saveSettings, settingsStore } from "@/lib/settings";
|
||||
import { useBackClose } from "@/lib/use-back-close";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
|
@ -35,10 +39,20 @@ function freshnessLabel(checkedAt: number, locale: Locale, t: (key: string, vars
|
|||
return t("health.checkedAt", { time });
|
||||
}
|
||||
|
||||
export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
export function SettingsDialog({
|
||||
open,
|
||||
onClose,
|
||||
focusField,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/** Set by openSettings("key") — focuses the key input once the sheet opens. */
|
||||
focusField?: { field: "key"; nonce: number } | null;
|
||||
}) {
|
||||
const { health, loading, error, refresh, apiKey, checkedAt } = useHealth();
|
||||
const installAvailable = useInstallAvailable();
|
||||
const { locale, setLocale, t, plural } = useI18n();
|
||||
const keyInputRef = useRef<HTMLInputElement>(null);
|
||||
const settings = useSyncExternalStore(
|
||||
settingsStore.subscribe,
|
||||
settingsStore.getSnapshot,
|
||||
|
|
@ -46,6 +60,16 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
);
|
||||
/* The system Back gesture closes the sheet instead of leaving the page. */
|
||||
useBackClose(open, onClose);
|
||||
|
||||
/* "Open Settings" from a usage-limit error lands right on the key field. */
|
||||
useEffect(() => {
|
||||
if (!open || focusField?.field !== "key") return;
|
||||
const timer = window.setTimeout(() => {
|
||||
keyInputRef.current?.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||
keyInputRef.current?.focus({ preventScroll: true });
|
||||
}, 380);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [open, focusField]);
|
||||
const [keyDraft, setKeyDraft] = useState(apiKey);
|
||||
const [reveal, setReveal] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
|
@ -265,12 +289,24 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
<span className="min-w-0 flex-1 text-[var(--text)]">{statusText}</span>
|
||||
</div>
|
||||
|
||||
{/* monthly usage used up / short-term throttle */}
|
||||
{health?.kind === "usage_limit" || health?.kind === "throttled" ? (
|
||||
<div className="rounded-xl border border-amber-300 bg-amber-50 p-2.5 text-[12px] leading-relaxed text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/10 dark:text-amber-100">
|
||||
<p className="font-bold">{modelErrorCopy(health.kind)?.title}</p>
|
||||
<p className="mt-0.5">{modelErrorCopy(health.kind)?.body}</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<ModelErrorActions kind={health.kind} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="relative">
|
||||
<label className="sr-only" htmlFor="ollama-api-key-phone">
|
||||
{t("settings.apiKey")}
|
||||
</label>
|
||||
<input
|
||||
id="ollama-api-key-phone"
|
||||
ref={keyInputRef}
|
||||
type={reveal ? "text" : "password"}
|
||||
value={keyDraft}
|
||||
onChange={(event) => setKeyDraft(event.target.value)}
|
||||
|
|
@ -356,6 +392,10 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
</div>
|
||||
</section>
|
||||
|
||||
{/* ------------------------------------------- data & sync */}
|
||||
<DataSection />
|
||||
<SyncSection />
|
||||
|
||||
{/* ----------------------------------------------- install */}
|
||||
{installAvailable ? (
|
||||
<section className="mb-4 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-1.5">
|
||||
|
|
@ -566,6 +606,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
</label>
|
||||
<input
|
||||
id="ollama-api-key"
|
||||
ref={keyInputRef}
|
||||
type={reveal ? "text" : "password"}
|
||||
value={keyDraft}
|
||||
onChange={(event) => setKeyDraft(event.target.value)}
|
||||
|
|
@ -666,6 +707,10 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
|
|||
) : null}
|
||||
</section>
|
||||
|
||||
{/* ------------------------------------------- data & sync */}
|
||||
<DataSection />
|
||||
<SyncSection />
|
||||
|
||||
{/* ------------------------------------------------ install */}
|
||||
{installAvailable ? (
|
||||
<section className="mb-4 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-1.5">
|
||||
|
|
@ -772,6 +817,11 @@ function HealthPanel({ health }: { health: ReturnType<typeof useHealth>["health"
|
|||
? t("health.modelMissing")
|
||||
: t("health.unreachable")}
|
||||
{health.error ? <p className="mt-1 font-normal">{health.error}</p> : null}
|
||||
{health.kind === "usage_limit" || health.kind === "throttled" ? (
|
||||
<span className="mt-2 flex flex-wrap gap-2">
|
||||
<ModelErrorActions kind={health.kind} />
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ export function ShareChooser({
|
|||
<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}>
|
||||
<Button variant="secondary" onClick={() => openSettings()}>
|
||||
{t("common.settings")}
|
||||
</Button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -296,7 +296,7 @@ function NavContent({
|
|||
<div className="mt-2 space-y-0.5 border-t border-[var(--hairline)] pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={openSettings}
|
||||
onClick={() => openSettings()}
|
||||
title={t("common.settings")}
|
||||
className={cn("nav-row", collapsed && "justify-center px-2")}
|
||||
>
|
||||
|
|
|
|||
303
components/SyncSection.tsx
Normal file
303
components/SyncSection.tsx
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
|
||||
import { Button } from "@/components/ui";
|
||||
import { copyText } from "@/lib/clipboard";
|
||||
import { haptic } from "@/lib/haptics";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { deleteSyncedData, enableSync, forgetDeviceKey, hasDeviceKey, joinSync, syncNow, unlockSync, type SyncOutcome } from "@/lib/sync";
|
||||
import { syncStore } from "@/lib/sync-state";
|
||||
|
||||
/**
|
||||
* Settings → Sync (off by default). Enabling derives a key from the user's
|
||||
* passphrase, stores it as a non-extractable CryptoKey and uploads the first
|
||||
* encrypted blob. Joining needs the sync ID plus the passphrase. Conflicts
|
||||
* are surfaced with an explicit choice — never resolved silently.
|
||||
*/
|
||||
export function SyncSection() {
|
||||
const { t, locale } = useI18n();
|
||||
const record = useSyncExternalStore(syncStore.subscribe, syncStore.getSnapshot, syncStore.getServerSnapshot);
|
||||
const [mode, setMode] = useState<"idle" | "enable" | "join">("idle");
|
||||
const [pass, setPass] = useState("");
|
||||
const [pass2, setPass2] = useState("");
|
||||
const [joinId, setJoinId] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [locked, setLocked] = useState<boolean | null>(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!record.enabled) {
|
||||
setLocked(null);
|
||||
return;
|
||||
}
|
||||
void hasDeviceKey().then(setLocked);
|
||||
}, [record.enabled, record.id]);
|
||||
|
||||
const statusFor = (outcome: SyncOutcome): string | null => {
|
||||
switch (outcome.status) {
|
||||
case "pushed":
|
||||
return t("settings.syncPushed");
|
||||
case "pulled":
|
||||
return t("settings.syncPulled");
|
||||
case "up-to-date":
|
||||
return t("settings.syncDone");
|
||||
case "conflict":
|
||||
return t("settings.syncConflict");
|
||||
case "locked":
|
||||
return t("settings.syncLocked");
|
||||
case "error":
|
||||
return outcome.message ?? t("settings.syncError");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setMode("idle");
|
||||
setPass("");
|
||||
setPass2("");
|
||||
setJoinId("");
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const run = async (action: () => Promise<SyncOutcome>) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
try {
|
||||
const outcome = await action();
|
||||
const text = statusFor(outcome);
|
||||
if (outcome.status === "error" || outcome.status === "locked") setError(text);
|
||||
else setNotice(text);
|
||||
if (outcome.status !== "error" && outcome.status !== "locked") reset();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const startEnable = () => {
|
||||
if (pass.length < 8) return setError(t("settings.syncPassphraseShort"));
|
||||
if (pass !== pass2) return setError(t("settings.syncPassphraseMismatch"));
|
||||
void run(() => enableSync(pass));
|
||||
};
|
||||
|
||||
const startJoin = () => {
|
||||
if (!joinId.trim()) return setError(t("server.syncInvalidId"));
|
||||
if (pass.length < 8) return setError(t("settings.syncPassphraseShort"));
|
||||
void run(() => joinSync(joinId, pass));
|
||||
};
|
||||
|
||||
const startUnlock = () => {
|
||||
if (!pass) return setError(t("settings.syncPassphraseShort"));
|
||||
void run(async () => {
|
||||
const outcome = await unlockSync(pass);
|
||||
if (outcome.status !== "error") setLocked(true);
|
||||
return outcome;
|
||||
});
|
||||
};
|
||||
|
||||
const lastSynced = record.lastSyncedAt
|
||||
? t("settings.syncLast", { when: new Date(record.lastSyncedAt).toLocaleString(locale) })
|
||||
: t("settings.syncNever");
|
||||
|
||||
const fieldClass =
|
||||
"w-full rounded-xl border border-[var(--hairline)] bg-[var(--surface-strong)] px-3 py-2.5 text-sm text-frost-950 outline-none transition focus:border-accent-500 dark:text-frost-50";
|
||||
|
||||
/* Revoking the server copy must work even on a device that can't unlock
|
||||
(e.g. after the browser dropped the stored key). */
|
||||
const deleteBlock = (
|
||||
<div className="flex flex-wrap gap-2 border-t border-[var(--hairline-soft)] pt-2">
|
||||
{confirmDelete ? (
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[11.5px] text-[var(--text-muted)]">{t("settings.syncDeleteConfirm")}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
loading={busy}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
setConfirmDelete(false);
|
||||
return deleteSyncedData();
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("settings.syncDeleteYes")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(false)}>
|
||||
{t("settings.syncCancel")}
|
||||
</Button>
|
||||
</span>
|
||||
) : (
|
||||
<Button size="sm" variant="ghost" onClick={() => setConfirmDelete(true)}>
|
||||
{t("settings.syncDelete")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="mb-4 space-y-2 rounded-2xl border border-[var(--hairline)] bg-[var(--surface-sunken)] p-3">
|
||||
<h3 className="text-sm font-semibold text-frost-950 dark:text-frost-50">{t("settings.sync")}</h3>
|
||||
<p className="text-[11.5px] leading-relaxed text-[var(--text-subtle)]">{t("settings.syncNote")}</p>
|
||||
<p className="text-[11px] font-medium leading-relaxed text-[var(--text-muted)]">{t("settings.syncNoteKey")}</p>
|
||||
|
||||
{!record.enabled ? (
|
||||
mode === "enable" ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="password"
|
||||
value={pass}
|
||||
onChange={(event) => setPass(event.target.value)}
|
||||
placeholder={t("settings.syncPassphrase")}
|
||||
autoComplete="new-password"
|
||||
spellCheck={false}
|
||||
className={fieldClass}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={pass2}
|
||||
onChange={(event) => setPass2(event.target.value)}
|
||||
placeholder={t("settings.syncPassphraseConfirm")}
|
||||
autoComplete="new-password"
|
||||
spellCheck={false}
|
||||
className={fieldClass}
|
||||
/>
|
||||
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" loading={busy} onClick={startEnable}>
|
||||
{t("settings.syncStart")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={reset}>
|
||||
{t("settings.syncCancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : mode === "join" ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="text"
|
||||
value={joinId}
|
||||
onChange={(event) => setJoinId(event.target.value)}
|
||||
placeholder={t("settings.syncJoinId")}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className={fieldClass}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
value={pass}
|
||||
onChange={(event) => setPass(event.target.value)}
|
||||
placeholder={t("settings.syncPassphrase")}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className={fieldClass}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-[var(--text-subtle)]">{t("settings.syncJoinNote")}</p>
|
||||
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" loading={busy} onClick={startJoin}>
|
||||
{t("settings.syncJoinAction")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={reset}>
|
||||
{t("settings.syncCancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="secondary" onClick={() => setMode("enable")}>
|
||||
{t("settings.syncEnable")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setMode("join")}>
|
||||
{t("settings.syncJoin")}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
) : locked === false ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11.5px] leading-relaxed text-[var(--text-muted)]">{t("settings.syncLocked")}</p>
|
||||
<input
|
||||
type="password"
|
||||
value={pass}
|
||||
onChange={(event) => setPass(event.target.value)}
|
||||
placeholder={t("settings.syncPassphrase")}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className={fieldClass}
|
||||
/>
|
||||
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
|
||||
<Button size="sm" loading={busy} onClick={startUnlock}>
|
||||
{t("settings.syncUnlock")}
|
||||
</Button>
|
||||
{deleteBlock}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-[11px] font-semibold uppercase tracking-wide text-[var(--text-subtle)]">
|
||||
{t("settings.syncId")}
|
||||
</span>
|
||||
<span className="block truncate font-mono text-[12px] text-[var(--text)]">{record.id}</span>
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
void copyText(record.id).then((ok) => {
|
||||
haptic("tap");
|
||||
setNotice(ok ? t("settings.syncCopied") : t("settings.syncError"));
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t("settings.syncCopy")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-[11.5px] font-medium text-[var(--text-muted)]">{lastSynced}</p>
|
||||
|
||||
{record.conflict ? (
|
||||
<div className="space-y-2 rounded-xl border border-amber-300 bg-amber-50 p-2.5 text-[12px] text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/10 dark:text-amber-100">
|
||||
<p className="font-semibold">{t("settings.syncConflict")}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" loading={busy} onClick={() => void run(() => syncNow("push"))}>
|
||||
{t("settings.syncKeepLocal")}
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" loading={busy} onClick={() => void run(() => syncNow("pull"))}>
|
||||
{t("settings.syncKeepRemote")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Button size="sm" loading={busy} onClick={() => void run(() => syncNow("auto"))}>
|
||||
{t("settings.syncNow")}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{notice ? <p className="text-[12px] font-medium text-[var(--text-muted)]">{notice}</p> : null}
|
||||
{error ? <p className="text-[11.5px] font-medium text-rose-600 dark:text-rose-300">{error}</p> : null}
|
||||
|
||||
<div className="flex flex-wrap gap-2 border-t border-[var(--hairline-soft)] pt-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
void forgetDeviceKey().then(() => {
|
||||
setLocked(false);
|
||||
setNotice(null);
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t("settings.syncForget")}
|
||||
</Button>
|
||||
{deleteBlock}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -31,6 +31,16 @@ export function syncThemeColor(theme: "light" | "dark") {
|
|||
}
|
||||
}
|
||||
|
||||
export function applyTheme(next: "light" | "dark") {
|
||||
document.documentElement.classList.toggle("dark", next === "dark");
|
||||
syncThemeColor(next);
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, next);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const [theme, setTheme] = useState<"light" | "dark">("light");
|
||||
|
||||
|
|
@ -45,13 +55,7 @@ export function useTheme() {
|
|||
|
||||
const apply = (next: "light" | "dark") => {
|
||||
setTheme(next);
|
||||
document.documentElement.classList.toggle("dark", next === "dark");
|
||||
syncThemeColor(next);
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, next);
|
||||
} catch {
|
||||
/* private mode */
|
||||
}
|
||||
applyTheme(next);
|
||||
};
|
||||
|
||||
return { theme, toggle: () => apply(theme === "dark" ? "light" : "dark") };
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@ import { takePendingShare } from "@/lib/share-pending";
|
|||
import { upsertDeck } from "@/lib/storage";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import { openSettings } from "@/lib/ui-events";
|
||||
import { modelErrorCopy } from "@/lib/model-errors";
|
||||
import { ModelErrorActions } from "@/components/ModelErrorActions";
|
||||
import { useBackClose } from "@/lib/use-back-close";
|
||||
import { useIsPhone } from "@/lib/use-phone";
|
||||
import { useOnline } from "@/lib/use-online";
|
||||
|
|
@ -536,22 +538,28 @@ export function UploadScreen() {
|
|||
className="animate-rise rounded-3xl border-2 border-rose-300 bg-rose-50/95 p-4 text-sm text-rose-900 dark:border-rose-400/40 dark:bg-rose-400/10 dark:text-rose-100"
|
||||
>
|
||||
<p className="font-bold">
|
||||
{error.kind === "needs_key"
|
||||
? t("upload.errNeedsKey")
|
||||
: error.kind === "rate_limited"
|
||||
? t("upload.errRate")
|
||||
: error.kind === "auth"
|
||||
? t("upload.errAuth")
|
||||
: t("upload.errFailed")}
|
||||
{modelErrorCopy(error.kind)?.title ??
|
||||
(error.kind === "needs_key"
|
||||
? t("upload.errNeedsKey")
|
||||
: error.kind === "rate_limited"
|
||||
? t("upload.errRate")
|
||||
: error.kind === "auth"
|
||||
? t("upload.errAuth")
|
||||
: t("upload.errFailed"))}
|
||||
</p>
|
||||
<p className="mt-1">{error.message}</p>
|
||||
<p className="mt-1">{modelErrorCopy(error.kind)?.body ?? error.message}</p>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{error.kind === "needs_key" || error.kind === "auth" ? (
|
||||
<Button size="sm" onClick={openSettings}>
|
||||
<Button size="sm" onClick={() => openSettings("key")}>
|
||||
{t("upload.openSettings")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="sm" variant={error.kind === "needs_key" || error.kind === "auth" ? "secondary" : "primary"} onClick={() => void generate()}>
|
||||
<ModelErrorActions kind={error.kind} />
|
||||
<Button
|
||||
size="sm"
|
||||
variant={error.kind === "needs_key" || error.kind === "auth" ? "secondary" : "primary"}
|
||||
onClick={() => void generate()}
|
||||
>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -4,9 +4,11 @@ import { useEffect, useRef, useState } from "react";
|
|||
|
||||
import { ApiError, gradeAnswer } from "@/lib/client-api";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { modelErrorCopy } from "@/lib/model-errors";
|
||||
import type { Activity } from "@/lib/schemas";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button, Spinner } from "@/components/ui";
|
||||
import { ModelErrorActions } from "@/components/ModelErrorActions";
|
||||
|
||||
import {
|
||||
ActivityHeader,
|
||||
|
|
@ -23,7 +25,7 @@ type GradeState =
|
|||
| { status: "idle" }
|
||||
| { status: "grading" }
|
||||
| { status: "graded"; correct: boolean; feedback: string; missing: string[] }
|
||||
| { status: "error"; message: string }
|
||||
| { status: "error"; message: string; kind?: string }
|
||||
| { status: "self-check" };
|
||||
|
||||
export function ShortAnswer({ activity, active, language, onAnswered, onNext, isLast, nextLabel }: ActivityComponentProps<ShortAnswerActivity>) {
|
||||
|
|
@ -64,6 +66,7 @@ export function ShortAnswer({ activity, active, language, onAnswered, onNext, is
|
|||
error instanceof ApiError
|
||||
? error.message
|
||||
: t("short.gradeFailed"),
|
||||
kind: error instanceof ApiError ? error.kind : undefined,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -119,12 +122,13 @@ export function ShortAnswer({ activity, active, language, onAnswered, onNext, is
|
|||
|
||||
{state.status === "error" ? (
|
||||
<div className="rounded-2xl border-2 border-amber-300 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/10 dark:text-amber-100">
|
||||
<p className="font-bold">{t("short.couldNotGrade")}</p>
|
||||
<p className="mt-1">{state.message}</p>
|
||||
<p className="font-bold">{modelErrorCopy(state.kind)?.title ?? t("short.couldNotGrade")}</p>
|
||||
<p className="mt-1">{modelErrorCopy(state.kind)?.body ?? state.message}</p>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button size="sm" onClick={() => void grade()}>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
<ModelErrorActions kind={state.kind} />
|
||||
<Button size="sm" variant="secondary" onClick={() => setState({ status: "self-check" })}>
|
||||
{t("short.showAnswer")}
|
||||
</Button>
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ 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 { modelErrorCopy } from "@/lib/model-errors";
|
||||
import { takePendingShare } from "@/lib/share-pending";
|
||||
import { useBackClose } from "@/lib/use-back-close";
|
||||
import type { useNotesIntake } from "@/lib/use-notes-intake";
|
||||
|
|
@ -23,6 +24,7 @@ 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 { ModelErrorActions } from "@/components/ModelErrorActions";
|
||||
import { cn, truncate } from "@/lib/utils";
|
||||
|
||||
import { HomeworkHistory } from "./HomeworkHistory";
|
||||
|
|
@ -150,6 +152,7 @@ export function HomeworkInput({
|
|||
const hasContent =
|
||||
intake.images.length > 0 || documentImages.length > 0 || text.trim().length > 0 || documentText.trim().length > 0;
|
||||
const canSubmit = hasContent && !intake.busy && !documentsBusy;
|
||||
const modelCopy = modelErrorCopy(error?.kind);
|
||||
const keyError = error?.kind === "needs_key" || error?.kind === "auth";
|
||||
|
||||
const errorCard = error ? (
|
||||
|
|
@ -157,14 +160,15 @@ export function HomeworkInput({
|
|||
role="alert"
|
||||
className="animate-rise rounded-3xl border-2 border-rose-300 bg-rose-50/95 p-4 text-sm text-rose-900 dark:border-rose-400/40 dark:bg-rose-400/10 dark:text-rose-100"
|
||||
>
|
||||
<p className="font-bold">{keyError ? t("upload.errAuth") : t("homework.error.title")}</p>
|
||||
<p className="mt-1">{error.message || t("homework.error.body")}</p>
|
||||
<p className="font-bold">{modelCopy?.title ?? (keyError ? t("upload.errAuth") : t("homework.error.title"))}</p>
|
||||
<p className="mt-1">{modelCopy?.body ?? (error.message || t("homework.error.body"))}</p>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{keyError ? (
|
||||
<Button size="sm" onClick={openSettings}>
|
||||
<Button size="sm" onClick={() => openSettings("key")}>
|
||||
{t("upload.openSettings")}
|
||||
</Button>
|
||||
) : null}
|
||||
<ModelErrorActions kind={error.kind} />
|
||||
<Button size="sm" variant={keyError ? "secondary" : "primary"} onClick={() => onSubmit()}>
|
||||
{t("common.retry")}
|
||||
</Button>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue