Files
faunosteo/apps/app/src/components/account/AvatarSection.tsx
T
bchanot 6f885eccb2 feat(ui): modal dialogs on the native dialog element (D13)
ModalDialog wraps showModal(): the page behind is inert and does not scroll, focus starts on the first control and returns to the opener, or to the first control of its nearest container when the opener is gone. Escape and close requests only ask the consumer. Dialog gains aria-labelledby and an optional described message; the confirmations pass theirs. The mobile drawer uses the same primitive and closes at the sidebar breakpoint.
2026-10-25 22:36:31 +01:00

286 lines
9.6 KiB
TypeScript

import { useEffect, useRef, useState, type ChangeEvent } from 'react'
import {
beginAvatarUpload,
classifyAssetError,
confirmAssetUpload,
isAvatarRejectionCode,
removeAvatar,
uploadToQuarantine,
type AssetFailureKind,
type AvatarRejectionCode,
type AvatarState,
} from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { monogram } from '@/components/shell/UserBadge'
import { prepareAvatarUpload, type PreparedAvatar } from '@/account/avatarTransport'
import { getSupabaseClient } from '@/lib/supabase'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/** Polling of the own row after a save (docs/development/STORAGE.md §4 step 4). */
export const POLL_INTERVAL_MS = 1000
export const POLL_MAX_MS = 30_000
const ACCEPT = 'image/jpeg,image/png,image/webp'
type Phase =
| { kind: 'idle' }
| { kind: 'picked'; prepared: PreparedAvatar }
| { kind: 'saving' }
| { kind: 'processing'; long: boolean }
| { kind: 'saved' }
| { kind: 'removed' }
| { kind: 'rejected'; code: AvatarRejectionCode }
| { kind: 'failed'; failure: AssetFailureKind }
function revoke(url: string | undefined) {
if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url)
}
/** Photo, preview or monogram in the circle; the busy state replaces it with a label. */
function Circle({
src,
label,
busy,
busyLabel,
}: {
src: string | null
label: string
busy: boolean
busyLabel: string
}) {
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const base =
'grid h-24 w-24 shrink-0 place-items-center overflow-hidden rounded-full bg-[var(--color-accent)] text-2xl font-semibold text-white'
if (busy) {
return (
<div className={`${base} bg-[var(--color-surface-strong)] text-xs font-medium text-[var(--color-ink-muted)]`} role="status">
<span className="px-2 text-center leading-tight">{busyLabel}</span>
</div>
)
}
if (src) {
return (
<div className={base}>
<img src={src} alt={label} className="h-full w-full object-cover" />
</div>
)
}
return (
<div className={base} aria-hidden="true">
{monogram(profile?.display_name, user?.email)}
</div>
)
}
/**
* Profile photo block of "Mon compte": pick → local preview → save (begin,
* quarantine upload, confirm) → poll until the worker's verdict → photo.
* Removal asks once. Every message is a closed i18n key.
*/
export default function AvatarSection() {
const t = useT()
const avatarUrl = useAuthStore((s) => s.avatarUrl)
const avatar = useAuthStore((s) => s.avatar)
const refreshAvatar = useAuthStore((s) => s.refreshAvatar)
const clearAvatar = useAuthStore((s) => s.clearAvatar)
const [phase, setPhase] = useState<Phase>(() =>
avatar?.inFlight ? { kind: 'processing', long: false } : { kind: 'idle' },
)
const [confirmOpen, setConfirmOpen] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const pollRef = useRef<number | null>(null)
const stopPolling = () => {
if (pollRef.current !== null) {
window.clearInterval(pollRef.current)
pollRef.current = null
}
}
/** One tick per second until the row leaves `uploaded`, 30 s at most. */
const startPolling = () => {
stopPolling()
const startedAt = Date.now()
pollRef.current = window.setInterval(() => {
void refreshAvatar()
.then((state: AvatarState) => {
if (state.inFlight === null) {
stopPolling()
setPhase(settledPhase(state))
} else if (Date.now() - startedAt >= POLL_MAX_MS) {
stopPolling()
setPhase({ kind: 'processing', long: true })
}
})
.catch((error: unknown) => {
stopPolling()
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
})
}, POLL_INTERVAL_MS)
}
// A row already in flight at mount resumes the bounded polling (refs: no stale closure, no deps).
const startPollingRef = useRef(startPolling)
startPollingRef.current = startPolling
const resumeOnMount = useRef(phase.kind === 'processing')
useEffect(() => {
if (resumeOnMount.current) startPollingRef.current()
return () => {
if (pollRef.current !== null) window.clearInterval(pollRef.current)
}
}, [])
useEffect(() => {
return () => {
if (phase.kind === 'picked') revoke(phase.prepared.previewUrl)
}
}, [phase])
async function onPick(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
try {
const prepared = await prepareAvatarUpload(file)
setPhase({ kind: 'picked', prepared })
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
async function onSave() {
if (phase.kind !== 'picked') return
const client = getSupabaseClient()
if (!client) return
const { blob } = phase.prepared
setPhase({ kind: 'saving' })
try {
const ticket = await beginAvatarUpload(client, {
declaredMime: 'image/jpeg',
declaredSize: blob.size,
})
await uploadToQuarantine(client, { ...ticket, blob })
await confirmAssetUpload(client, ticket.assetId)
setPhase({ kind: 'processing', long: false })
startPolling()
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
async function onRemove() {
const client = getSupabaseClient()
setConfirmOpen(false)
if (!client) return
try {
await removeAvatar(client)
clearAvatar()
setPhase({ kind: 'removed' })
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
const busy = phase.kind === 'saving' || phase.kind === 'processing'
const picked = phase.kind === 'picked'
const shown = picked ? phase.prepared.previewUrl : avatarUrl
const rejected =
phase.kind === 'rejected'
? phase.code
: phase.kind === 'idle' && avatar?.lastRejected && isAvatarRejectionCode(avatar.lastRejected.rejection_reason)
? avatar.lastRejected.rejection_reason
: null
return (
<div className="space-y-3" data-testid="avatar-section">
<h3 className="text-sm font-medium text-[var(--color-ink)]">{t('account.avatar.title')}</h3>
<div className="flex flex-wrap items-center gap-4">
<Circle
src={shown}
label={t('account.avatar.alt')}
busy={busy}
busyLabel={phase.kind === 'saving' ? t('account.avatar.saving') : t('account.avatar.processing')}
/>
<div className="flex flex-wrap items-center gap-2">
<input
ref={inputRef}
type="file"
accept={ACCEPT}
onChange={onPick}
className="sr-only"
aria-label={t('account.avatar.change')}
disabled={busy}
/>
{picked ? (
<>
<Button type="button" onClick={onSave}>
{t('account.avatar.save')}
</Button>
<Button type="button" variant="ghost" onClick={() => setPhase({ kind: 'idle' })}>
{t('account.avatar.cancel')}
</Button>
</>
) : (
<>
<Button
type="button"
variant="secondary"
disabled={busy}
onClick={() => inputRef.current?.click()}
>
{t('account.avatar.change')}
</Button>
{avatarUrl && !busy && (
<Button type="button" variant="danger" onClick={() => setConfirmOpen(true)}>
{t('account.avatar.remove')}
</Button>
)}
</>
)}
</div>
</div>
<p className="text-xs text-[var(--color-ink-muted)]">
{phase.kind === 'processing' && !phase.long
? t('account.avatar.processing_hint')
: t('account.avatar.hint')}
</p>
{phase.kind === 'processing' && phase.long && (
<Notice tone="info">{t('account.avatar.processing_long')}</Notice>
)}
{phase.kind === 'saved' && <Notice tone="success">{t('account.avatar.saved')}</Notice>}
{phase.kind === 'removed' && <Notice tone="success">{t('account.avatar.removed')}</Notice>}
{phase.kind === 'failed' && (
<Notice tone="error">{t(`account.avatar.error.${phase.failure}`)}</Notice>
)}
{rejected && <Notice tone="error">{t(`account.avatar.rejected.${rejected}`)}</Notice>}
<Dialog
open={confirmOpen}
onClose={() => setConfirmOpen(false)}
title={t('account.avatar.remove_title')}
description={<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>}
size="sm"
>
<div className="mt-4 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => setConfirmOpen(false)}>
{t('common.cancel')}
</Button>
<Button type="button" variant="danger" onClick={onRemove}>
{t('account.avatar.remove_confirm')}
</Button>
</div>
</Dialog>
</div>
)
}
/** The verdict once no row is in flight: the clean photo, a rejection, or nothing new. */
function settledPhase(state: AvatarState): Phase {
if (state.lastRejected && isAvatarRejectionCode(state.lastRejected.rejection_reason)) {
return { kind: 'rejected', code: state.lastRejected.rejection_reason }
}
return state.clean ? { kind: 'saved' } : { kind: 'idle' }
}