@metamask/design-system-react
Version:
Design system react ui components
79 lines • 3.04 kB
JavaScript
function $importDefault(module) {
if (module?.__esModule) {
return module.default;
}
return module;
}
import $jazzicon from "@metamask/jazzicon";
const jazzicon = $importDefault($jazzicon);
import { KnownCaipNamespace } from "@metamask/utils";
import $React, { useEffect, useRef } from "react";
const React = $importDefault($React);
import { twMerge } from "../../../utils/tw-merge.mjs";
import { generateSeedEthereum, generateSeedNonEthereum, getCaipNamespaceFromAddress } from "./Jazzicon.utilities.mjs";
/**
* Cache for storing generated SVG elements by `address:diameter` so
* we don't regenerate them repeatedly.
*/
const iconCache = {};
export const Jazzicon = ({ address, size = 32, className, ...props }) => {
const containerRef = useRef(null);
useEffect(() => {
let isCancelled = false;
const generateJazzicon = async () => {
if (!containerRef.current) {
return;
}
// Clear any existing content
while (containerRef.current.firstChild) {
containerRef.current.removeChild(containerRef.current.firstChild);
}
// Check the cache
const cacheKey = `${address.toLowerCase()}:${size}`;
if (iconCache[cacheKey]) {
// If cached, just append a clone
if (!isCancelled) {
const clone = iconCache[cacheKey].cloneNode(true);
containerRef.current.appendChild(clone);
}
return;
}
// Determine the CAIP namespace
const namespace = await getCaipNamespaceFromAddress(address);
if (isCancelled) {
return;
}
// Pick seeding strategy based on namespace
let seed;
if (namespace === KnownCaipNamespace.Eip155) {
seed = generateSeedEthereum(address);
}
else {
seed = generateSeedNonEthereum(address);
}
// Create Jazzicon
const newIcon = jazzicon(size, seed);
// Cache it
iconCache[cacheKey] = newIcon;
// Append a fresh clone
if (!isCancelled && containerRef.current) {
containerRef.current.appendChild(newIcon.cloneNode(true));
}
};
generateJazzicon().catch(() => {
// Silently ignore errors during async generation
});
// Cleanup
return () => {
isCancelled = true;
if (containerRef.current) {
while (containerRef.current.firstChild) {
containerRef.current.removeChild(containerRef.current.firstChild);
}
}
};
}, [address, size]);
return (React.createElement("div", { ref: containerRef, className: twMerge('flex [&>div]:!rounded-none', className), ...props }));
};
Jazzicon.displayName = 'Jazzicon';
//# sourceMappingURL=Jazzicon.mjs.map