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:
bchanot committed 2026-10-13 19:32:37 +02:00
1 parent 614887470c
commit 926dd7df8c
18 files changed
+1550 -31

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
import { AssetFailure } from '@faunosteo/supabase'
/**
* Browser-side preparation of a profile photo (docs/development/STORAGE.md
* §4): sniff the real type, decode, downscale to a transport size, re-encode
* as JPEG. Transport only: the worker re-decodes and judges the bytes again.
*/
export type SniffedImageType = 'image/jpeg' | 'image/png' | 'image/webp'
/** Largest file accepted at the picker (sanity bound before decoding). */
export const MAX_PICKED_BYTES = 20 * 1024 * 1024
/** Largest blob actually transferred (the bucket cap and the RPC CHECK). */
export const MAX_TRANSPORT_BYTES = 5 * 1024 * 1024
/** Longest side after the canvas downscale. */
export const TRANSPORT_MAX_SIDE = 1024
const JPEG_QUALITY = 0.9
function startsWith(bytes: Uint8Array, prefix: number[], at = 0): boolean {
if (bytes.length < at + prefix.length) return false
return prefix.every((b, i) => bytes[at + i] === b)
}
/** Magic bytes only: SVG, GIF, BMP or any text are null. */
export function sniffImageType(bytes: Uint8Array): SniffedImageType | null {
if (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'image/jpeg'
if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
return 'image/png'
}
if (
startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) &&
startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)
) {
return 'image/webp'
}
return null
}
/** Canvas size for a bitmap: longest side capped, never upscaled. */
export function transportSize(
width: number,
height: number,
maxSide = TRANSPORT_MAX_SIDE,
): { width: number; height: number } {
const longest = Math.max(width, height)
if (longest <= maxSide) return { width, height }
const scale = maxSide / longest
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
}
}
export interface BitmapLike {
width: number
height: number
close?: () => void
}
export interface CanvasLike {
width: number
height: number
getContext: (kind: '2d') => { drawImage: (image: unknown, x: number, y: number, w: number, h: number) => void } | null
toBlob: (cb: (blob: Blob | null) => void, type: string, quality: number) => void
}
/** The browser APIs involved, injectable for tests under happy-dom. */
export interface TransportDeps {
createImageBitmap: (file: Blob) => Promise<BitmapLike>
createCanvas: () => CanvasLike
createObjectURL: (blob: Blob) => string
}
function defaultDeps(): TransportDeps {
return {
createImageBitmap: (file) => createImageBitmap(file),
createCanvas: () => document.createElement('canvas') as unknown as CanvasLike,
createObjectURL: (blob) => URL.createObjectURL(blob),
}
}
export interface PreparedAvatar {
blob: Blob
previewUrl: string
}
async function readHead(file: Blob): Promise<Uint8Array> {
return new Uint8Array(await file.slice(0, 16).arrayBuffer())
}
function encodeJpeg(canvas: CanvasLike): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => (blob ? resolve(blob) : reject(new AssetFailure('unsupported_type'))),
'image/jpeg',
JPEG_QUALITY,
)
})
}
/**
* Sniff → decode → downscale → JPEG. Throws AssetFailure('too_large' |
* 'unsupported_type'); never uploads anything.
*/
export async function prepareAvatarUpload(
file: File,
deps: TransportDeps = defaultDeps(),
): Promise<PreparedAvatar> {
if (file.size > MAX_PICKED_BYTES) throw new AssetFailure('too_large')
if (sniffImageType(await readHead(file)) === null) {
throw new AssetFailure('unsupported_type')
}
let bitmap: BitmapLike
try {
bitmap = await deps.createImageBitmap(file)
} catch (cause) {
throw new AssetFailure('unsupported_type', cause)
}
try {
const size = transportSize(bitmap.width, bitmap.height)
const canvas = deps.createCanvas()
canvas.width = size.width
canvas.height = size.height
const context = canvas.getContext('2d')
if (!context) throw new AssetFailure('unsupported_type')
context.drawImage(bitmap, 0, 0, size.width, size.height)
const blob = await encodeJpeg(canvas)
if (blob.size > MAX_TRANSPORT_BYTES) throw new AssetFailure('too_large')
return { blob, previewUrl: deps.createObjectURL(blob) }
} finally {
bitmap.close?.()
}
}
@@ -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"
+15 -2
View File
@@ -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">
+27 -7
View File
@@ -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}
+42
View File
@@ -372,4 +372,46 @@ export const en: Dict = {
'Not available in this version yet. It will be offered, then required for platform roles.',
'account.security.sign_out_everywhere_note':
'Signing out closes the session on this device.',
'account.avatar.title': 'Profile photo',
'account.avatar.alt': 'Profile photo',
'account.avatar.change': 'Change photo',
'account.avatar.save': 'Save photo',
'account.avatar.saving': 'Uploading…',
'account.avatar.cancel': 'Cancel',
'account.avatar.remove': 'Remove photo',
'account.avatar.remove_title': 'Remove the photo?',
'account.avatar.remove_body':
'Your profile photo will be removed. You can add another one at any time.',
'account.avatar.remove_confirm': 'Remove',
'account.avatar.removed': 'Photo removed.',
'account.avatar.processing': 'Processing…',
'account.avatar.processing_hint':
'Your photo is being checked and resized. This takes a few seconds.',
'account.avatar.processing_long':
'Processing is taking longer than expected. Come back in a moment.',
'account.avatar.saved': 'Photo saved.',
'account.avatar.hint': 'JPEG, PNG or WebP, 5 MB at most once reduced.',
'account.avatar.error.too_large': 'Image too large (5 MB at most).',
'account.avatar.error.unsupported_type':
'Unsupported format: choose a JPEG, PNG or WebP image.',
'account.avatar.error.rate_limited':
'Too many attempts. Try again in an hour.',
'account.avatar.error.storage_full':
'Storage is full. Try again later.',
'account.avatar.error.upload_missing':
'The upload did not complete. Try again.',
'account.avatar.error.invalid_state':
'This action no longer matches your current photo. Reload the page.',
'account.avatar.error.not_found': 'Photo not found. Reload the page.',
'account.avatar.error.network':
'Cannot reach the server. Check your connection and try again.',
'account.avatar.error.unknown': 'Something went wrong. Try again.',
'account.avatar.rejected.unsupported_type':
'Photo refused: the file is not a JPEG, PNG or WebP image.',
'account.avatar.rejected.decode_failed':
'Photo refused: the file is corrupt or unreadable.',
'account.avatar.rejected.dimensions':
'Photo refused: between 64 and 4096 pixels per side.',
'account.avatar.rejected.processing_error':
'Photo refused: processing failed. Try another image.',
}
+42
View File
@@ -390,4 +390,46 @@ export const fr: Dict = {
'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.',
'account.security.sign_out_everywhere_note':
'Se déconnecter ferme la session sur cet appareil.',
'account.avatar.title': 'Photo de profil',
'account.avatar.alt': 'Photo de profil',
'account.avatar.change': 'Modifier la photo',
'account.avatar.save': 'Enregistrer la photo',
'account.avatar.saving': 'Envoi…',
'account.avatar.cancel': 'Annuler',
'account.avatar.remove': 'Supprimer la photo',
'account.avatar.remove_title': 'Supprimer la photo ?',
'account.avatar.remove_body':
'Votre photo de profil sera retirée. Vous pourrez en ajouter une autre à tout moment.',
'account.avatar.remove_confirm': 'Supprimer',
'account.avatar.removed': 'Photo supprimée.',
'account.avatar.processing': 'Traitement en cours…',
'account.avatar.processing_hint':
'Votre photo est vérifiée puis redimensionnée. Cela prend quelques secondes.',
'account.avatar.processing_long':
'Le traitement prend plus de temps que prévu. Revenez dans un instant.',
'account.avatar.saved': 'Photo enregistrée.',
'account.avatar.hint': 'JPEG, PNG ou WebP, 5 Mo maximum une fois réduite.',
'account.avatar.error.too_large': 'Image trop volumineuse (5 Mo maximum).',
'account.avatar.error.unsupported_type':
'Format non pris en charge : choisissez une image JPEG, PNG ou WebP.',
'account.avatar.error.rate_limited':
'Trop de tentatives. Réessayez dans une heure.',
'account.avatar.error.storage_full':
'Espace de stockage saturé. Réessayez plus tard.',
'account.avatar.error.upload_missing':
"L'envoi ne s'est pas terminé. Réessayez.",
'account.avatar.error.invalid_state':
'Cette opération ne correspond plus à votre photo actuelle. Rechargez la page.',
'account.avatar.error.not_found': 'Photo introuvable. Rechargez la page.',
'account.avatar.error.network':
"Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.",
'account.avatar.error.unknown': 'Une erreur est survenue. Réessayez.',
'account.avatar.rejected.unsupported_type':
'Photo refusée : le fichier n’est pas une image JPEG, PNG ou WebP.',
'account.avatar.rejected.decode_failed':
'Photo refusée : le fichier est corrompu ou illisible.',
'account.avatar.rejected.dimensions':
'Photo refusée : entre 64 et 4096 pixels de côté.',
'account.avatar.rejected.processing_error':
'Photo refusée : le traitement a échoué. Réessayez avec une autre image.',
}
+77 -13
View File
@@ -10,6 +10,9 @@ import {
signOut as signOutRequest,
updateOwnProfile,
type AuthFailureKind,
type AvatarState,
downloadAvatar,
fetchOwnAvatarState,
type FaunosteoClient,
type OwnProfilePatch,
type PlatformRole,
@@ -34,22 +37,59 @@ export interface AuthState {
recovery: boolean
/** Failure while reading the URL (expired link, bad code): shown by the landing routes. */
urlFailure: AuthFailureKind | null
/** Own avatar rows reduced to clean / in flight / last rejected; null until loaded. */
avatar: AvatarState | null
/** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */
avatarUrl: string | null
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void
refreshAccount: () => Promise<void>
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
/** Re-reads the own rows; downloads the clean photo when it changed. */
refreshAvatar: () => Promise<AvatarState>
/** Forgets the photo locally (after remove_avatar or on sign-out). */
clearAvatar: () => void
signOut: () => Promise<void>
clearRecovery: () => void
}
type Set = (patch: Partial<AuthState>) => void
type Get = () => AuthState
async function loadAccount(client: FaunosteoClient, user: User, set: Set) {
/** Blob URLs are a browser feature; tests under happy-dom may lack them. */
function revokeUrl(url: string | null) {
if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url)
}
/**
* Reads the avatar state and keeps `avatarUrl` in step with the clean row:
* a new clean id downloads once, no clean row drops the URL.
*/
async function syncAvatar(client: FaunosteoClient, user: User, set: Set, get: Get) {
const avatar = await fetchOwnAvatarState(client, user.id)
const previous = get().avatar?.clean?.id ?? null
const current = avatar.clean?.id ?? null
if (current === previous && (current === null || get().avatarUrl)) {
set({ avatar })
return avatar
}
let avatarUrl: string | null = null
if (avatar.clean && typeof URL.createObjectURL === 'function') {
const blob = await downloadAvatar(client, avatar.clean.object_key)
avatarUrl = URL.createObjectURL(blob)
}
revokeUrl(get().avatarUrl)
set({ avatar, avatarUrl })
return avatar
}
async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: Get) {
const [profile, roles] = await Promise.all([
fetchOwnProfile(client, user.id),
fetchOwnPlatformRoles(client, user.id),
])
set({ profile, roles })
await syncAvatar(client, user, set, get).catch(() => set({ avatar: null }))
}
/**
@@ -61,9 +101,11 @@ function applyAuthEvent(
event: AuthChangeEvent,
session: Session | null,
set: Set,
previousUserId: string | undefined,
get: Get,
) {
const previousUserId = get().user?.id
if (event === 'SIGNED_OUT' || session === null) {
revokeUrl(get().avatarUrl)
set({
status: 'signed_out',
session: null,
@@ -71,6 +113,8 @@ function applyAuthEvent(
profile: null,
roles: [],
recovery: false,
avatar: null,
avatarUrl: null,
})
return
}
@@ -83,7 +127,7 @@ function applyAuthEvent(
set(patch)
if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
setTimeout(() => {
void loadAccount(client, session.user, set).catch(() => {
void loadAccount(client, session.user, set, get).catch(() => {
set({ profile: null, roles: [] })
})
}, 0)
@@ -109,6 +153,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
roles: [],
recovery: false,
urlFailure: null,
avatar: null,
avatarUrl: null,
start: () => {
const client = getSupabaseClient()
@@ -120,13 +166,26 @@ export const useAuthStore = create<AuthState>((set, get) => ({
if (error) set({ urlFailure: classifyAuthError(error) })
})
const { data } = client.auth.onAuthStateChange((event, session) => {
applyAuthEvent(client, event, session, set, get().user?.id)
applyAuthEvent(client, event, session, set, get)
})
return () => data.subscription.unsubscribe()
},
refreshAccount: async () => {
await loadAccount(requireClient(), requireUser(get().user), set)
await loadAccount(requireClient(), requireUser(get().user), set, get)
},
refreshAvatar: async () => {
return syncAvatar(requireClient(), requireUser(get().user), set, get)
},
clearAvatar: () => {
revokeUrl(get().avatarUrl)
const avatar = get().avatar
set({
avatarUrl: null,
avatar: avatar ? { ...avatar, clean: null, inFlight: null } : null,
})
},
updateProfile: async (patch) => {
@@ -137,14 +196,19 @@ export const useAuthStore = create<AuthState>((set, get) => ({
},
signOut: async () => {
const clear = () => set({
status: 'signed_out',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
})
const clear = () => {
revokeUrl(get().avatarUrl)
set({
status: 'signed_out',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
avatar: null,
avatarUrl: null,
})
}
try {
// auth-js clears the local session even when the server call fails.
await signOutRequest(requireClient())
+74 -5
View File
@@ -1,10 +1,12 @@
/**
* In-memory stand-in for the parts of the Supabase client the identity step
* uses: auth events, profile select/update, profile_roles select. Tests mock
* In-memory stand-in for the parts of the Supabase client the identity and
* files steps use: auth events, profile select/update, profile_roles and
* assets selects, rpc, storage upload / download. Tests mock
* `@/lib/supabase` to hand this object out.
*/
import { vi } from 'vitest'
import type {
AssetRow,
AuthChangeEvent,
FaunosteoClient,
Profile,
@@ -58,11 +60,42 @@ export function fakeProfile(patch: Partial<Profile> = {}): Profile {
}
}
/** Minimal PostgREST builder: filters, then select / update, awaitable. */
export function fakeAssetRow(patch: Partial<AssetRow> = {}): AssetRow {
return {
id: 'asset-1',
owner_id: 'user-1',
kind: 'profile_avatar',
bucket_id: 'avatars',
object_key: 'profiles/user-1/asset-1/avatar.webp',
status: 'clean',
declared_mime: 'image/jpeg',
declared_size: 1000,
byte_size: 900,
sha256: null,
rejection_reason: null,
created_at: '2026-10-13T10:00:00Z',
updated_at: '2026-10-13T10:00:00Z',
...patch,
}
}
/** Minimal PostgREST builder: filters, order, limit, then select / update, awaitable. */
function builder(tables: Record<string, Row[]>, table: string) {
const filters: Array<(row: Row) => boolean> = []
let patch: Row | null = null
const rows = () => (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
let order: { col: string; ascending: boolean } | null = null
let max: number | null = null
const rows = () => {
let hit = (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
if (order) {
const { col, ascending } = order
hit = [...hit].sort((a, b) =>
(String(a[col]) < String(b[col]) ? -1 : String(a[col]) > String(b[col]) ? 1 : 0) *
(ascending ? 1 : -1),
)
}
return max === null ? hit : hit.slice(0, max)
}
const apply = () => {
if (!patch) return rows()
const hit = rows()
@@ -83,6 +116,18 @@ function builder(tables: Record<string, Row[]>, table: string) {
filters.push((r) => r[col] === value)
return api
},
in: (col: string, values: unknown[]) => {
filters.push((r) => values.includes(r[col]))
return api
},
order: (col: string, opts?: { ascending?: boolean }) => {
order = { col, ascending: opts?.ascending ?? true }
return api
},
limit: (n: number) => {
max = n
return api
},
maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }),
single: async () => {
const [first] = apply()
@@ -100,6 +145,13 @@ export interface FakeSupabase {
client: FaunosteoClient
tables: Record<string, Row[]>
emit: (event: AuthChangeEvent, session: Session | null) => void
/** Recorded rpc calls; program results with `rpcResults[name]`. */
rpcCalls: Array<[string, unknown]>
rpcResults: Record<string, { data?: unknown; error?: unknown } | (() => { data?: unknown; error?: unknown })>
storage: {
upload: ReturnType<typeof vi.fn>
download: ReturnType<typeof vi.fn>
}
auth: {
initialize: ReturnType<typeof vi.fn>
signInWithPassword: ReturnType<typeof vi.fn>
@@ -112,9 +164,16 @@ export interface FakeSupabase {
}
export function createFakeSupabase(
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [] },
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [], assets: [] },
): FakeSupabase {
tables.assets ??= []
const listeners: Listener[] = []
const rpcCalls: Array<[string, unknown]> = []
const rpcResults: FakeSupabase['rpcResults'] = {}
const storage = {
upload: vi.fn(async () => ({ data: null, error: null })),
download: vi.fn(async () => ({ data: new Blob([new Uint8Array([82, 73, 70, 70])]), error: null })),
}
const auth = {
initialize: vi.fn(async () => ({ error: null })),
onAuthStateChange: vi.fn((cb: Listener) => {
@@ -131,11 +190,21 @@ export function createFakeSupabase(
const client = {
auth,
from: (table: string) => builder(tables, table),
rpc: async (name: string, args?: unknown) => {
rpcCalls.push([name, args])
const entry = rpcResults[name]
const result = typeof entry === 'function' ? entry() : (entry ?? {})
return { data: result.data ?? null, error: result.error ?? null }
},
storage: { from: () => storage },
} as unknown as FaunosteoClient
return {
client,
tables,
auth,
rpcCalls,
rpcResults,
storage,
emit: (event, session) => listeners.forEach((cb) => cb(event, session)),
}
}
@@ -0,0 +1,120 @@
import { describe, expect, it, vi } from 'vitest'
import { AssetFailure } from '@faunosteo/supabase'
import {
MAX_PICKED_BYTES,
prepareAvatarUpload,
sniffImageType,
transportSize,
type TransportDeps,
} from '@/account/avatarTransport'
const JPEG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0])
const WEBP = new Uint8Array([...'RIFF'].map((c) => c.charCodeAt(0)).concat([0, 0, 0, 0], [...'WEBP'].map((c) => c.charCodeAt(0)), [0, 0, 0, 0]))
function file(bytes: Uint8Array, name = 'photo.jpg', type = 'image/jpeg', size?: number): File {
const f = new File([bytes as BlobPart], name, { type })
if (size !== undefined) Object.defineProperty(f, 'size', { value: size })
return f
}
function deps(bitmap: { width: number; height: number } | Error, blobSize = 1000): TransportDeps & { canvas: { width: number; height: number }; drawn: unknown[] } {
const canvas = { width: 0, height: 0 }
const drawn: unknown[] = []
return {
canvas,
drawn,
createImageBitmap: async () => {
if (bitmap instanceof Error) throw bitmap
return { ...bitmap, close: vi.fn() }
},
createCanvas: () => ({
get width() {
return canvas.width
},
set width(v: number) {
canvas.width = v
},
get height() {
return canvas.height
},
set height(v: number) {
canvas.height = v
},
getContext: () => ({ drawImage: (...args: unknown[]) => drawn.push(args) }),
toBlob: (cb: (b: Blob | null) => void) => {
const blob = new Blob([new Uint8Array(blobSize)], { type: 'image/jpeg' })
cb(blob)
},
}),
createObjectURL: () => 'blob:preview',
}
}
async function failureKind(p: Promise<unknown>) {
try {
await p
return null
} catch (e) {
return e instanceof AssetFailure ? e.kind : String(e)
}
}
describe('sniffImageType', () => {
it('recognises JPEG, PNG and WebP by magic bytes only', () => {
expect(sniffImageType(JPEG)).toBe('image/jpeg')
expect(sniffImageType(PNG)).toBe('image/png')
expect(sniffImageType(WEBP)).toBe('image/webp')
})
it('refuses SVG, GIF, a RIFF that is not WEBP and empty input', () => {
const svg = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>')
expect(sniffImageType(svg)).toBeNull()
expect(sniffImageType(new TextEncoder().encode('GIF89a......'))).toBeNull()
expect(sniffImageType(new TextEncoder().encode('RIFF....WAVE....'))).toBeNull()
expect(sniffImageType(new Uint8Array())).toBeNull()
})
})
describe('transportSize', () => {
it('caps the longest side at 1024 and never upscales', () => {
expect(transportSize(4000, 3000)).toEqual({ width: 1024, height: 768 })
expect(transportSize(3000, 4000)).toEqual({ width: 768, height: 1024 })
expect(transportSize(500, 500)).toEqual({ width: 500, height: 500 })
expect(transportSize(1024, 10)).toEqual({ width: 1024, height: 10 })
})
})
describe('prepareAvatarUpload', () => {
it('refuses an oversized file before any decode', async () => {
const d = deps({ width: 10, height: 10 })
const spy = vi.spyOn(d, 'createImageBitmap')
expect(await failureKind(prepareAvatarUpload(file(JPEG, 'big.jpg', 'image/jpeg', MAX_PICKED_BYTES + 1), d))).toBe('too_large')
expect(spy).not.toHaveBeenCalled()
})
it('refuses a file whose bytes are not a raster image, whatever its name or type', async () => {
const d = deps({ width: 10, height: 10 })
const svg = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>')
expect(await failureKind(prepareAvatarUpload(file(svg, 'logo.jpg', 'image/jpeg'), d))).toBe('unsupported_type')
})
it('maps a bitmap decode failure to unsupported_type', async () => {
const d = deps(new Error('not decodable'))
expect(await failureKind(prepareAvatarUpload(file(JPEG), d))).toBe('unsupported_type')
})
it('draws a downscaled canvas and returns a JPEG blob with a preview URL', async () => {
const d = deps({ width: 4000, height: 3000 })
const result = await prepareAvatarUpload(file(PNG, 'p.png', 'image/png'), d)
expect(d.canvas).toEqual({ width: 1024, height: 768 })
expect(d.drawn[0]).toEqual([expect.objectContaining({ width: 4000 }), 0, 0, 1024, 768])
expect(result.blob.type).toBe('image/jpeg')
expect(result.previewUrl).toBe('blob:preview')
})
it('keeps a small image at its size', async () => {
const d = deps({ width: 500, height: 500 })
await prepareAvatarUpload(file(JPEG), d)
expect(d.canvas).toEqual({ width: 500, height: 500 })
})
it('refuses a transport blob over 5 MiB', async () => {
const d = deps({ width: 1000, height: 1000 }, 5 * 1024 * 1024 + 1)
expect(await failureKind(prepareAvatarUpload(file(JPEG), d))).toBe('too_large')
})
})
@@ -0,0 +1,172 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AssetFailure } from '@faunosteo/supabase'
import {
createFakeSupabase,
fakeAssetRow,
fakeProfile,
fakeUser,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({
fake: null as unknown,
prepare: vi.fn(),
}))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
vi.mock('@/account/avatarTransport', () => ({
prepareAvatarUpload: (...args: unknown[]) => mocks.prepare(...args),
}))
import AvatarSection, { POLL_INTERVAL_MS } from '@/components/account/AvatarSection'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
const TICKET = {
asset_id: '11111111-1111-4111-8111-111111111111',
bucket_id: 'avatars',
quarantine_key: 'quarantine/user-1/11111111-1111-4111-8111-111111111111/upload',
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
mocks.prepare.mockReset()
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile(),
roles: [],
avatar: { clean: null, inFlight: null, lastRejected: null },
avatarUrl: null,
})
fake.rpcResults.begin_avatar_upload = { data: TICKET }
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
function pick(file = new File([new Uint8Array([0xff, 0xd8, 0xff])], 'p.jpg', { type: 'image/jpeg' })) {
const input = screen.getByLabelText(fr['account.avatar.change'])
fireEvent.change(input, { target: { files: [file] } })
}
describe('AvatarSection', () => {
it('shows the monogram and no remove button without a photo', () => {
render(<AvatarSection />)
expect(screen.getByText('AL')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: fr['account.avatar.remove'] })).toBeNull()
})
it('refuses a bad pick with the phrased message and makes no request', async () => {
mocks.prepare.mockRejectedValue(new AssetFailure('unsupported_type'))
render(<AvatarSection />)
pick()
expect(await screen.findByText(fr['account.avatar.error.unsupported_type'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
expect(fake.storage.upload).not.toHaveBeenCalled()
})
it('shows the preview with save / cancel before any request', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x'], { type: 'image/jpeg' }), previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
const img = await screen.findByRole('img', { name: fr['account.avatar.alt'] })
expect(img).toHaveAttribute('src', 'blob:preview')
expect(screen.getByRole('button', { name: fr['account.avatar.save'] })).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.cancel'] }))
expect(screen.queryByRole('img')).toBeNull()
})
it('saves in order begin → upload → confirm, polls, then shows the photo', async () => {
const blob = new Blob([new Uint8Array(1234)], { type: 'image/jpeg' })
mocks.prepare.mockResolvedValue({ blob, previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.map((c) => c[0])).toEqual(['begin_avatar_upload', 'confirm_asset_upload']))
expect(fake.rpcCalls[0][1]).toEqual({ declared_mime: 'image/jpeg', declared_size: 1234 })
expect(fake.storage.upload).toHaveBeenCalledWith(TICKET.quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' })
expect(fake.rpcCalls[1][1]).toEqual({ asset_id: TICKET.asset_id })
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
// The worker finishes: the next poll sees the clean row and downloads it.
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.saved'])).toBeInTheDocument())
expect(fake.storage.download).toHaveBeenCalledWith('profiles/user-1/asset-1/avatar.webp')
expect(screen.getByRole('button', { name: fr['account.avatar.remove'] })).toBeInTheDocument()
})
it('phrases a rejection per code once the poll settles', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.length).toBe(2))
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, status: 'rejected', rejection_reason: 'dimensions', created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.rejected.dimensions'])).toBeInTheDocument())
})
it('phrases an RPC refusal and keeps the circle usable', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
fake.rpcResults.begin_avatar_upload = { error: { code: 'P0001', message: 'rate_limited', status: 400 } }
render(<AvatarSection />)
pick()
await userEvent.click(await screen.findByRole('button', { name: fr['account.avatar.save'] }))
expect(await screen.findByText(fr['account.avatar.error.rate_limited'])).toBeInTheDocument()
expect(fake.storage.upload).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeEnabled()
})
it('removes the photo after the dialog confirmation', async () => {
useAuthStore.setState({ avatarUrl: 'blob:current', avatar: { clean: fakeAssetRow(), inFlight: null, lastRejected: null } })
fake.rpcResults.remove_avatar = { data: 1 }
render(<AvatarSection />)
expect(screen.getByRole('img', { name: fr['account.avatar.alt'] })).toHaveAttribute('src', 'blob:current')
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['account.avatar.remove_title'] })
expect(dialog).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove_confirm'] }))
expect(await screen.findByText(fr['account.avatar.removed'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([['remove_avatar', undefined]])
expect(useAuthStore.getState().avatarUrl).toBeNull()
expect(screen.queryByRole('img')).toBeNull()
})
it('resumes the processing state for a row in flight at mount', async () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: fakeAssetRow({ status: 'uploaded' }), lastRejected: null } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
})
it('shows the last rejection of a fresh mount', () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: null, lastRejected: fakeAssetRow({ status: 'rejected', rejection_reason: 'decode_failed' }) } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.rejected.decode_failed'])).toBeInTheDocument()
})
})
+29 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
@@ -27,6 +27,8 @@ beforeEach(() => {
user: fakeUser(),
profile: fakeProfile({ display_name: 'Alice Local' }),
roles: [],
avatar: null,
avatarUrl: null,
})
})
afterEach(cleanup)
@@ -56,9 +58,34 @@ describe('AppLayout', () => {
expect(screen.getByText('dashboard page')).toBeInTheDocument()
})
it('links the top-bar avatar and name to the account page', async () => {
const user = userEvent.setup()
mount()
const link = screen.getByTestId('topbar-account')
expect(link).toHaveAttribute('href', '/app/account')
expect(link).toHaveTextContent('Alice Local')
expect(link).toHaveAttribute('aria-label', fr['shell.nav.account'])
await user.click(link)
expect(await screen.findByText('account page')).toBeInTheDocument()
})
it('shows the photo everywhere once the store holds a blob URL, the monogram otherwise', () => {
mount()
expect(screen.queryAllByRole('img', { name: fr['account.avatar.alt'] })).toHaveLength(0)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
cleanup()
useAuthStore.setState({ avatarUrl: 'blob:photo' })
mount()
const imgs = screen.getAllByRole('img', { name: fr['account.avatar.alt'] })
expect(imgs.length).toBeGreaterThanOrEqual(2)
imgs.forEach((img) => expect(img).toHaveAttribute('src', 'blob:photo'))
expect(screen.queryByText('AL')).toBeNull()
})
it('marks the active destination', () => {
mount('/app/account')
const link = screen.getByRole('link', { name: new RegExp(fr['shell.nav.account']) })
const nav = screen.getByRole('navigation', { name: fr['shell.nav_label'] })
const link = within(nav).getByRole('link', { name: new RegExp(fr['shell.nav.account']) })
expect(link).toHaveAttribute('aria-current', 'page')
})
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeAssetRow,
fakeSession,
flush,
type FakeSupabase,
@@ -22,6 +23,8 @@ const INITIAL = {
roles: [],
recovery: false,
urlFailure: null,
avatar: null,
avatarUrl: null,
}
let fake: FakeSupabase
@@ -97,6 +100,38 @@ describe('authStore', () => {
expect(fake.tables.profiles[0].first_name).toBe('Alice')
})
it('loads the avatar state and downloads the clean photo once', async () => {
fake.tables.assets.push(fakeAssetRow())
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await flush()
const s = useAuthStore.getState()
expect(s.avatar?.clean?.id).toBe('asset-1')
expect(s.avatarUrl).toMatch(/^blob:/)
expect(fake.storage.download).toHaveBeenCalledTimes(1)
await useAuthStore.getState().refreshAvatar()
expect(fake.storage.download).toHaveBeenCalledTimes(1)
fake.tables.assets.push(fakeAssetRow({ id: 'asset-2', object_key: 'profiles/user-1/asset-2/avatar.webp', created_at: '2026-10-13T12:00:00Z' }))
fake.tables.assets[0].status = 'deleted'
await useAuthStore.getState().refreshAvatar()
expect(fake.storage.download).toHaveBeenLastCalledWith('profiles/user-1/asset-2/avatar.webp')
})
it('clearAvatar drops the URL and the clean row; sign-out clears it too', async () => {
fake.tables.assets.push(fakeAssetRow())
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await flush()
useAuthStore.getState().clearAvatar()
expect(useAuthStore.getState().avatarUrl).toBeNull()
expect(useAuthStore.getState().avatar?.clean).toBeNull()
await useAuthStore.getState().refreshAvatar()
fake.emit('SIGNED_OUT', null)
expect(useAuthStore.getState()).toMatchObject({ avatar: null, avatarUrl: null })
})
it('signOut calls the client and resets the state', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())