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

@@ -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())