UNPKG

design-react-kit

Version:

Componenti React per Bootstrap 5

67 lines 2.71 kB
import classNames from 'classnames'; import React, { useEffect, useState } from 'react'; import { EmptyIcon } from './EmptyIcon'; import { allIcons, isBundledIcon, loadIcon } from './assets/index'; export const iconsList = allIcons; let iconsCache = {}; /** * Preload a list of icons in cache * @param icons - the list of icons to preload * @returns true if the icons have been preloaded */ export async function preloadIcons(icons) { const preloadedIcons = await Promise.all(icons.map((icon) => loadIcon(icon))); preloadedIcons.forEach(({ component }, i) => { iconsCache[icons[i]] = (() => component); }); return true; } /** * Removes icons from cache * @param icon? - the icon to remove, or nothing to clear the whole cache * @returns an object containing the removed icons */ export const clearIconCache = (iconName) => { let deletedItems; if (iconName) { deletedItems = { [iconName]: iconsCache[iconName] }; delete iconsCache[iconName]; } else { deletedItems = { ...iconsCache }; iconsCache = {}; } return deletedItems; }; export const Icon = ({ color = '', size = '', icon = '', title = '', className, padding = false, onIconLoad, testId, ...attributes }) => { const [IconComponent, setCurrentIcon] = useState(iconsCache[icon]); const classes = classNames('icon', className, { [`icon-${color}`]: color, [`icon-${size}`]: size, 'icon-padded': padding }); useEffect(() => { if (isBundledIcon(icon) && !iconsCache[icon]) { loadIcon(icon).then(({ component }) => { iconsCache[icon] = (() => component); setCurrentIcon(iconsCache[icon]); onIconLoad?.(); }); } else { if (IconComponent !== iconsCache[icon]) { setCurrentIcon(iconsCache[icon]); } onIconLoad?.(); } }, [IconComponent, icon, onIconLoad]); if (!isBundledIcon(icon)) { // assume it's an image and let the browser do its job return (React.createElement("img", { src: icon, className: classes, alt: title, "data-testid": testId, ...attributes })); } if (!IconComponent) { return (React.createElement(EmptyIcon, { className: classes, role: title === '' ? undefined : 'img', "aria-hidden": title === '' ? true : false, title: title, ...attributes, "data-testid": testId })); } return (React.createElement(IconComponent, { className: classes, role: title === '' ? undefined : 'img', "aria-hidden": title === '' ? true : false, title: title, "data-testid": testId, ...attributes })); }; //# sourceMappingURL=Icon.js.map