simplify auth entry and centralize toasts

This commit is contained in:
nstarikov 2026-08-11 16:32:18 +03:00
parent db34a9ab2f
commit ffd982468f

View file

@ -17,7 +17,6 @@ import {
ImagePlus, ImagePlus,
Link2, Link2,
Loader2, Loader2,
LogIn,
Radio, Radio,
RefreshCw, RefreshCw,
Save, Save,
@ -375,6 +374,18 @@ function loadVkIdSdk() {
}) })
} }
function ToastNotice({ message, onClose }: { message: string; onClose?: () => void }) {
if (!message) return null
return (
<div className="fixed inset-x-4 top-4 z-[100] flex justify-center pointer-events-none sm:inset-x-6">
<div className="pointer-events-auto flex max-w-xl items-start gap-3 rounded-lg border border-foreground/10 bg-foreground px-4 py-3 text-sm text-background shadow-xl">
<span className="min-w-0 flex-1 break-words">{message}</span>
{onClose ? <button aria-label="Закрыть уведомление" className="shrink-0 rounded-sm opacity-70 transition-opacity hover:opacity-100" onClick={onClose} type="button"><X className="size-4" /></button> : null}
</div>
</div>
)
}
function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; onAuthenticated: () => void }) { function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; onAuthenticated: () => void }) {
const [message, setMessage] = useState("") const [message, setMessage] = useState("")
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
@ -444,25 +455,6 @@ function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; on
} }
} }
async function registerPasskey() {
if (!vkAuthenticated) {
setMessage("Сначала войдите через VK ID.")
return
}
setBusy(true)
try {
const started = await api<{ challengeId: string; options: any }>("/api/auth/register/options", { method: "POST" })
const credential = await navigator.credentials.create({ publicKey: registrationOptionsForBrowser(started.options) }) as PublicKeyCredential | null
if (!credential) throw new Error("Регистрация passkey отменена")
await api("/api/auth/register/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) })
onAuthenticated()
} catch (error) {
setMessage(error instanceof Error ? error.message : String(error))
} finally {
setBusy(false)
}
}
return ( return (
<main className="auth-screen flex min-h-screen items-center justify-center p-4 sm:p-6"> <main className="auth-screen flex min-h-screen items-center justify-center p-4 sm:p-6">
<section className="auth-card w-full max-w-md rounded-lg border bg-background/90 p-4 shadow-xl sm:p-6"> <section className="auth-card w-full max-w-md rounded-lg border bg-background/90 p-4 shadow-xl sm:p-6">
@ -470,7 +462,7 @@ function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; on
<img alt="Логотип Дзен-ассистента" className="size-12 rounded-md" src="/favicon.png" /> <img alt="Логотип Дзен-ассистента" className="size-12 rounded-md" src="/favicon.png" />
<div><h1 className="text-xl font-semibold">Дзен-ассистент</h1><p className="text-sm text-muted-foreground">Вход в редакторскую панель</p></div> <div><h1 className="text-xl font-semibold">Дзен-ассистент</h1><p className="text-sm text-muted-foreground">Вход в редакторскую панель</p></div>
</div> </div>
{message ? <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{message}</div> : null} <ToastNotice message={message} onClose={() => setMessage("")} />
<div ref={vkContainerRef} className="min-h-12" /> <div ref={vkContainerRef} className="min-h-12" />
{hasPasskeys ? ( {hasPasskeys ? (
<Button className="mt-3 w-full" disabled={busy} onClick={loginWithPasskey}> <Button className="mt-3 w-full" disabled={busy} onClick={loginWithPasskey}>
@ -483,17 +475,9 @@ function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; on
<Button className="mt-3 min-h-11 w-full whitespace-normal px-4 py-3 text-center leading-5" disabled={busy} onClick={onAuthenticated} variant="outline"> <Button className="mt-3 min-h-11 w-full whitespace-normal px-4 py-3 text-center leading-5" disabled={busy} onClick={onAuthenticated} variant="outline">
Продолжить через VK ID Продолжить через VK ID
</Button> </Button>
<Button className="mt-3 min-h-11 w-full whitespace-normal px-4 py-3 text-center leading-5" disabled={busy} onClick={registerPasskey}>
<Fingerprint data-icon="inline-start" />
Добавить Face ID / Touch ID
</Button>
</> </>
) : null} ) : null}
{!hasPasskeys ? <p className="mt-4 text-xs text-muted-foreground">После входа через VK ID можно будет добавить Face ID, Touch ID или Windows Hello.</p> : null} {!hasPasskeys ? <p className="mt-4 text-xs text-muted-foreground">После входа через VK ID добавьте биометрию в разделе «Настройки».</p> : null}
<Button className="mt-4 min-h-11 w-full whitespace-normal px-4 py-3 text-center leading-5" variant="ghost" disabled={busy} onClick={registerPasskey}>
<LogIn data-icon="inline-start" />
Зарегистрировать это устройство после входа через VK ID
</Button>
</section> </section>
</main> </main>
) )
@ -676,6 +660,7 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [dirty, setDirty] = useState(false) const [dirty, setDirty] = useState(false)
const [message, setMessage] = useState("") const [message, setMessage] = useState("")
const [passkeyBusy, setPasskeyBusy] = useState(false)
const signatureHolderRef = useRef<HTMLDivElement | null>(null) const signatureHolderRef = useRef<HTMLDivElement | null>(null)
const signatureEditorRef = useRef<EditorJS | null>(null) const signatureEditorRef = useRef<EditorJS | null>(null)
@ -745,6 +730,21 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
} }
} }
async function registerPasskey() {
setPasskeyBusy(true)
try {
const started = await api<{ challengeId: string; options: any }>("/api/auth/register/options", { method: "POST" })
const credential = await navigator.credentials.create({ publicKey: registrationOptionsForBrowser(started.options) }) as PublicKeyCredential | null
if (!credential) throw new Error("Регистрация устройства отменена")
await api("/api/auth/register/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) })
setMessage("Устройство зарегистрировано для входа по биометрии")
} catch (error) {
setMessage(`Не удалось зарегистрировать устройство: ${error instanceof Error ? error.message : String(error)}`)
} finally {
setPasskeyBusy(false)
}
}
return ( return (
<section className="flex flex-col gap-6"> <section className="flex flex-col gap-6">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
@ -757,7 +757,7 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
К роликам К роликам
</Button> </Button>
</div> </div>
{message ? <div className="rounded-md border bg-background px-4 py-3 text-sm text-muted-foreground">{message}</div> : null} <ToastNotice message={message} onClose={() => setMessage("")} />
{loading ? ( {loading ? (
<Card><CardContent className="p-6 text-sm text-muted-foreground">Загрузка настроек...</CardContent></Card> <Card><CardContent className="p-6 text-sm text-muted-foreground">Загрузка настроек...</CardContent></Card>
) : ( ) : (
@ -791,6 +791,10 @@ function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (sett
</div> </div>
)} )}
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<Button disabled={passkeyBusy || loading} onClick={registerPasskey} variant="outline">
{passkeyBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
Добавить биометрию
</Button>
<Button disabled={saving || loading || !dirty} onClick={saveSettings}> <Button disabled={saving || loading || !dirty} onClick={saveSettings}>
{saving ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Save data-icon="inline-start" />} {saving ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Save data-icon="inline-start" />}
Сохранить Сохранить
@ -1073,6 +1077,12 @@ export default function App() {
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined) api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}, [authState]) }, [authState])
useEffect(() => {
if (!statusMessage) return
const timer = window.setTimeout(() => setStatusMessage(""), 4200)
return () => window.clearTimeout(timer)
}, [statusMessage])
useEffect(() => { useEffect(() => {
if (authState !== "authenticated" || activeVideos.length === 0) return if (authState !== "authenticated" || activeVideos.length === 0) return
const timer = window.setInterval(() => { const timer = window.setInterval(() => {
@ -1664,6 +1674,10 @@ export default function App() {
return ( return (
<main className="min-h-screen bg-muted/35 editorial-studio"> <main className="min-h-screen bg-muted/35 editorial-studio">
<ToastNotice
message={copyToast || statusMessage}
onClose={() => (copyToast ? setCopyToast("") : setStatusMessage(""))}
/>
<div className="mx-auto flex w-full max-w-[1920px] flex-col gap-6 p-4 sm:p-6"> <div className="mx-auto flex w-full max-w-[1920px] flex-col gap-6 p-4 sm:p-6">
<header className="app-header flex flex-col gap-4 rounded-lg border bg-background p-4 md:flex-row md:items-center md:justify-between"> <header className="app-header flex flex-col gap-4 rounded-lg border bg-background p-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
@ -1709,7 +1723,6 @@ export default function App() {
Добавить ролик Добавить ролик
</Button> </Button>
</form> </form>
{statusMessage ? <div className="status-message flex min-w-0 items-center rounded-md border bg-background px-4 py-3 text-sm text-muted-foreground">{statusMessage}</div> : null}
</div> </div>
) : null} ) : null}
@ -2071,11 +2084,6 @@ export default function App() {
) : null} ) : null}
{selectedArticle ? ( {selectedArticle ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-3 backdrop-blur-sm"> <div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-3 backdrop-blur-sm">
{copyToast ? (
<div className="pointer-events-none fixed left-1/2 top-5 z-[60] -translate-x-1/2 rounded-md border bg-zinc-950 px-4 py-2 text-sm font-medium text-white shadow-lg">
{copyToast}
</div>
) : null}
<div className="modal-panel flex max-h-[92vh] w-full max-w-[1280px] flex-col overflow-hidden rounded-lg border bg-background shadow-lg"> <div className="modal-panel flex max-h-[92vh] w-full max-w-[1280px] flex-col overflow-hidden rounded-lg border bg-background shadow-lg">
<div className="article-modal-header flex min-w-0 items-start justify-between gap-4 border-b p-5"> <div className="article-modal-header flex min-w-0 items-start justify-between gap-4 border-b p-5">
<div className="article-modal-intro min-w-0 flex-1"> <div className="article-modal-intro min-w-0 flex-1">