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,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"
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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.',
|
||||
}
|
||||
@@ -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.',
|
||||
}
|
||||
@@ -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())
|
||||
|
||||
Reference in new issue
Block a user