phanpy/src/components/avatar.jsx

89 lines
2.3 KiB
React
Raw Normal View History

2022-12-10 09:14:48 +00:00
import './avatar.css';
2023-03-13 02:10:21 +00:00
import { useRef } from 'preact/hooks';
2022-12-10 09:14:48 +00:00
const SIZES = {
s: 16,
m: 20,
l: 24,
xl: 32,
xxl: 50,
xxxl: 64,
2022-12-10 09:14:48 +00:00
};
const alphaCache = {};
function Avatar({ url, size, alt = '', ...props }) {
2022-12-10 09:14:48 +00:00
size = SIZES[size] || size || SIZES.m;
2023-03-13 02:10:21 +00:00
const avatarRef = useRef();
2023-03-21 07:52:26 +00:00
const isMissing = /missing\.png$/.test(url);
2022-12-10 09:14:48 +00:00
return (
<span
2023-03-13 02:10:21 +00:00
ref={avatarRef}
class={`avatar ${alphaCache[url] ? 'has-alpha' : ''}`}
2022-12-10 09:14:48 +00:00
style={{
width: size,
height: size,
}}
title={alt}
{...props}
2022-12-10 09:14:48 +00:00
>
{!!url && (
2023-03-13 02:10:21 +00:00
<img
src={url}
width={size}
height={size}
alt={alt}
loading="lazy"
2023-03-21 07:52:26 +00:00
crossOrigin={
alphaCache[url] === undefined && !isMissing
? 'anonymous'
: undefined
}
onError={(e) => {
if (e.target.crossOrigin) {
e.target.crossOrigin = null;
e.target.src = url;
}
}}
2023-03-13 02:10:21 +00:00
onLoad={(e) => {
2023-03-13 08:22:41 +00:00
if (avatarRef.current) avatarRef.current.dataset.loaded = true;
if (alphaCache[url] !== undefined) return;
2023-03-21 07:52:26 +00:00
if (isMissing) return;
try {
// Check if image has alpha channel
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = e.target.width;
canvas.height = e.target.height;
ctx.drawImage(e.target, 0, 0);
const allPixels = ctx.getImageData(
0,
0,
canvas.width,
canvas.height,
);
2023-03-15 07:48:26 +00:00
// At least 10% of pixels have alpha <= 128
const hasAlpha =
allPixels.data.filter((pixel, i) => i % 4 === 3 && pixel <= 128)
.length /
(allPixels.data.length / 4) >
0.1;
if (hasAlpha) {
2023-03-14 09:32:06 +00:00
// console.log('hasAlpha', hasAlpha, allPixels.data);
avatarRef.current.classList.add('has-alpha');
}
alphaCache[url] = hasAlpha;
} catch (e) {
2023-03-21 14:45:35 +00:00
// Silent fail
alphaCache[url] = false;
}
2023-03-13 02:10:21 +00:00
}}
/>
2022-12-10 09:14:48 +00:00
)}
</span>
);
2022-12-16 05:27:04 +00:00
}
export default Avatar;