import { useEffect, useRef, useState } from 'react'; import { avatarColor } from '../lib/format'; // User avatar: tries the TeamSpeak avatar served at /avatar/, falling // back to the initial-letter-on-gradient avatar when the image is missing. // `uid` is the stable TeamSpeak unique id. // // The server fetches avatars from TeamSpeak lazily (it must first sync the // client's avatar hash, then download the file), so the first few requests can // 404 while that completes. We retry a handful of times with a growing delay, // bypassing the browser's negative cache with a ?v=N buster, before giving up // and showing initials. const RETRY_DELAYS_MS = [2500, 4000, 6000, 9000]; export function Avatar(props: { name: string; uid?: string | null; size?: number; className?: string; }) { const { name, uid, size, className } = props; const [attempt, setAttempt] = useState(0); const [failed, setFailed] = useState(false); const timer = useRef | null>(null); // Reset retry state whenever the target uid changes. useEffect(() => { setAttempt(0); setFailed(false); return () => { if (timer.current) clearTimeout(timer.current); }; }, [uid]); const style: React.CSSProperties = size ? { width: `${size}px`, height: `${size}px` } : {}; if (uid && !failed) { const src = `/avatar/${encodeURIComponent(uid)}` + (attempt > 0 ? `?v=${attempt}` : ''); return ( {name} { if (attempt < RETRY_DELAYS_MS.length) { const delay = RETRY_DELAYS_MS[attempt]; if (timer.current) clearTimeout(timer.current); timer.current = setTimeout( () => setAttempt((a) => a + 1), delay ); } else { setFailed(true); } }} /> ); } return ( {(name || '?').charAt(0).toUpperCase()} ); }