feat(app): profile photo — avatar upload in Mon compte, photo in the sidebar, drawer and top bar
packages/supabase assets module: closed AssetFailure kinds, begin / quarantine upload (upsert off) / confirm / remove, own-row state read with an explicit column list, download under the SELECT policy. App: client transport (magic byte sniff, never SVG, createImageBitmap, canvas 1024 px, JPEG 0.9, 5 MiB cap), AvatarSection (preview, save, 1 s polling up to 30 s, rejection and failure messages per closed code, removal with confirmation, in-flight row resumed at mount), auth store blob URL revoked on change and sign-out, AvatarCircle in UserBadge and the top bar link to Mon compte (D3), FR/EN strings, fake client extended, 27 new tests (app 300).
This commit is contained in:
1 parent
614887470c
commit
926dd7df8c
18 files changed
+1550
-31
No files matched your search
@@ -0,0 +1,280 @@
|
||||
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')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>
|
||||
<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' }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Profile } from '@faunosteo/supabase'
|
||||
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import AvatarSection from './AvatarSection'
|
||||
import SaveRow from './SaveRow'
|
||||
import SectionCard from './SectionCard'
|
||||
import { personalPatch, personalSchema, translateFieldError, type PersonalValues } from '@/account/validation'
|
||||
@@ -27,7 +28,8 @@ export default function PersonalInfoForm({ profile }: { profile: Profile }) {
|
||||
title={t('account.personal.title')}
|
||||
description={t('account.personal.description')}
|
||||
>
|
||||
<form onSubmit={form.submit} noValidate className="space-y-4">
|
||||
<AvatarSection />
|
||||
<form onSubmit={form.submit} noValidate className="mt-6 space-y-4 border-t border-[var(--color-border)] pt-6">
|
||||
<FormField id="display_name" label={t('account.personal.display_name')} error={err('display_name')}>
|
||||
<Input
|
||||
id="display_name"
|
||||
|
||||
@@ -6,7 +6,8 @@ import Icon from '@/components/ui/Icon'
|
||||
import MobileDrawer from './MobileDrawer'
|
||||
import SidebarNav, { NAV_ITEMS } from './SidebarNav'
|
||||
import SignOutButton from './SignOutButton'
|
||||
import UserBadge from './UserBadge'
|
||||
import UserBadge, { AvatarCircle } from './UserBadge'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Title of the current /app page for the top bar, from the nav table. */
|
||||
@@ -25,6 +26,9 @@ export default function AppLayout() {
|
||||
const t = useT()
|
||||
const location = useLocation()
|
||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||
const profile = useAuthStore((s) => s.profile)
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const displayName = profile?.display_name ?? user?.email ?? ''
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh bg-[var(--color-bg)]">
|
||||
@@ -60,8 +64,17 @@ export default function AppLayout() {
|
||||
<h1 className="hidden lg:block text-sm font-medium text-[var(--color-ink-muted)]">
|
||||
{t(pageTitleKey(location.pathname))}
|
||||
</h1>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<div className="ml-auto flex items-center gap-2 sm:gap-3">
|
||||
<LanguageSwitcher />
|
||||
<Link
|
||||
to="/app/account"
|
||||
aria-label={t('shell.nav.account')}
|
||||
data-testid="topbar-account"
|
||||
className="flex min-h-11 items-center gap-2 rounded-full pr-1 pl-1 text-sm text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] sm:pr-3"
|
||||
>
|
||||
<AvatarCircle size="sm" />
|
||||
<span className="hidden max-w-[12rem] truncate sm:inline">{displayName}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Two-letter monogram from the display name, else the email. */
|
||||
export function monogram(name: string | undefined, email: string | undefined) {
|
||||
@@ -10,19 +11,38 @@ export function monogram(name: string | undefined, email: string | undefined) {
|
||||
return letters.toUpperCase()
|
||||
}
|
||||
|
||||
/** Avatar monogram + display name + email, as shown at the bottom of the sidebar. */
|
||||
const CIRCLE =
|
||||
'grid shrink-0 place-items-center overflow-hidden rounded-full bg-[var(--color-accent)] font-semibold text-white'
|
||||
|
||||
/** The photo when the store holds one, the monogram otherwise; decorative. */
|
||||
export function AvatarCircle({ size = 'md' }: { size?: 'sm' | 'md' }) {
|
||||
const t = useT()
|
||||
const avatarUrl = useAuthStore((s) => s.avatarUrl)
|
||||
const profile = useAuthStore((s) => s.profile)
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const dims = size === 'sm' ? 'h-8 w-8 text-xs' : 'h-9 w-9 text-sm'
|
||||
if (avatarUrl) {
|
||||
return (
|
||||
<span className={`${CIRCLE} ${dims}`}>
|
||||
<img src={avatarUrl} alt={t('account.avatar.alt')} className="h-full w-full object-cover" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<span aria-hidden="true" className={`${CIRCLE} ${dims}`}>
|
||||
{monogram(profile?.display_name, user?.email)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Avatar + display name + email, as shown at the bottom of the sidebar. */
|
||||
export default function UserBadge() {
|
||||
const profile = useAuthStore((s) => s.profile)
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const name = profile?.display_name ?? user?.email ?? ''
|
||||
return (
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[var(--color-accent)] text-sm font-semibold text-white"
|
||||
>
|
||||
{monogram(profile?.display_name, user?.email)}
|
||||
</span>
|
||||
<AvatarCircle />
|
||||
<span className="flex min-w-0 flex-col leading-tight">
|
||||
<span className="truncate text-sm font-medium text-[var(--color-ink)]">
|
||||
{name}
|
||||
|
||||
Reference in new issue
Block a user