Files
EchoionWeb/frontend/src/components/Avatar.tsx
T
faumaray 9574aa8a23 making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:47:52 +03:00

73 lines
2.0 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { avatarColor } from '../lib/format';
// User avatar: tries the TeamSpeak avatar served at /avatar/<uid>, 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<ReturnType<typeof setTimeout> | 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 (
<img
className={'avatar avatar-img' + (className ? ` ${className}` : '')}
style={style}
src={src}
alt={name}
onError={() => {
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 (
<span
className={'avatar' + (className ? ` ${className}` : '')}
style={{ ...style, background: avatarColor(name || '?') }}
>
{(name || '?').charAt(0).toUpperCase()}
</span>
);
}