phanpy/src/components/icon.jsx

109 wiersze
2.3 KiB
React

2024-01-03 01:49:48 +00:00
import moize from 'moize';
2023-12-23 10:05:30 +00:00
import { useEffect, useRef, useState } from 'preact/hooks';
2024-01-20 02:25:47 +00:00
import { ICONS } from './ICONS';
2022-12-10 09:14:48 +00:00
const SIZES = {
s: 12,
m: 16,
l: 20,
xl: 24,
xxl: 32,
};
2023-12-23 04:14:11 +00:00
const ICONDATA = {};
2024-01-03 01:49:48 +00:00
// Memoize the dangerouslySetInnerHTML of the SVGs
const SVGICon = moize(
2024-01-25 13:28:41 +00:00
function ({ width, height, body, rotate, flip }) {
2024-01-03 01:49:48 +00:00
return (
<svg
viewBox={`0 0 ${width} ${height}`}
dangerouslySetInnerHTML={{ __html: body }}
style={{
transform: `${rotate ? `rotate(${rotate})` : ''} ${
flip ? `scaleX(-1)` : ''
}`,
}}
/>
);
},
{
isShallowEqual: true,
maxSize: Object.keys(ICONS).length,
2024-01-25 16:28:03 +00:00
matchesArg: (cacheKeyArg, keyArg) =>
cacheKeyArg.icon === keyArg.icon && cacheKeyArg.body === keyArg.body,
2024-01-03 01:49:48 +00:00
},
);
2023-03-09 13:51:50 +00:00
function Icon({
icon,
size = 'm',
alt,
title,
class: className = '',
style = {},
}) {
2022-12-14 13:48:17 +00:00
if (!icon) return null;
2022-12-10 09:14:48 +00:00
const iconSize = SIZES[size];
let iconBlock = ICONS[icon];
2024-01-04 10:55:21 +00:00
if (!iconBlock) {
console.warn(`Icon ${icon} not found`);
return null;
}
let rotate, flip;
if (Array.isArray(iconBlock)) {
[iconBlock, rotate, flip] = iconBlock;
}
2023-12-23 04:14:11 +00:00
const [iconData, setIconData] = useState(ICONDATA[icon]);
2023-12-23 10:05:30 +00:00
const currentIcon = useRef(icon);
2023-12-23 04:14:11 +00:00
useEffect(() => {
2023-12-23 10:05:30 +00:00
if (iconData && currentIcon.current === icon) return;
2023-12-23 04:14:11 +00:00
(async () => {
const iconB = await iconBlock();
setIconData(iconB.default);
ICONDATA[icon] = iconB.default;
})();
2023-12-23 10:05:30 +00:00
currentIcon.current = icon;
}, [icon]);
2022-12-10 09:14:48 +00:00
return (
2023-09-29 13:02:09 +00:00
<span
2022-12-10 09:14:48 +00:00
class={`icon ${className}`}
title={title || alt}
style={{
width: `${iconSize}px`,
height: `${iconSize}px`,
2023-03-09 13:51:50 +00:00
...style,
2022-12-10 09:14:48 +00:00
}}
>
{iconData && (
2024-01-03 01:49:48 +00:00
// <svg
// width={iconSize}
// height={iconSize}
// viewBox={`0 0 ${iconData.width} ${iconData.height}`}
// dangerouslySetInnerHTML={{ __html: iconData.body }}
// style={{
// transform: `${rotate ? `rotate(${rotate})` : ''} ${
// flip ? `scaleX(-1)` : ''
// }`,
// }}
// />
<SVGICon
2024-01-25 13:28:41 +00:00
icon={icon}
2024-01-03 01:49:48 +00:00
width={iconData.width}
height={iconData.height}
body={iconData.body}
rotate={rotate}
flip={flip}
/>
)}
2023-09-29 13:02:09 +00:00
</span>
2022-12-10 09:14:48 +00:00
);
2022-12-16 05:27:04 +00:00
}
export default Icon;