UNPKG

@publidata/utils-svg

Version:

Collection of methods to handle svg files and src

83 lines (73 loc) 2.2 kB
import { hexify, getCSSColor } from "@publidata/utils-colors"; import { getFASvgFile, getSvgData, removeDoctype, removeXmlTag, retrieveViewboxData } from "../utils/helpers"; import { loadAndConvertSvgInImg } from "../loader/loadSvgIcons"; export const prepareSvgIconsForMultiflow = async (iconsWithColors = []) => { if (!iconsWithColors || !iconsWithColors.length) { throw new Error("Missing iconsWithColors"); } const rawSvgs = await Promise.all( iconsWithColors.map(({ icon }) => icon.includes("http") ? getSvgData(icon) : getFASvgFile(icon) ) ); return rawSvgs.map((svg, index) => { const cleaned = removeXmlTag(removeDoctype(svg)); const { icon, color } = iconsWithColors[index]; const isImage = icon.includes("http"); const viewbox = retrieveViewboxData(cleaned); if (isImage) { (viewbox.w *= 0.8), (viewbox.h *= 0.8); } return { svg: cleaned, color, bgColor: hexify(getCSSColor(color, 0.2)), viewbox, isImage }; }); }; /** Get loaded image object from svg * @param {object} loadedIcons - An object with iconKey as key and object as value (eg: {icon, colors, isImage}) * @return {promise} - an array of objects with iconKey, color and img */ export const prepareImgForMarkerMap = async ( loadedIcons, ) => { try { const rawSvgs = Object.values(loadedIcons).map(async item => { const { icon, color, isImage, iconKey, multiflowData } = item; let svgContent = ""; if (icon.includes("http")) { const svgFetched = await fetch( `${icon}${icon.includes("?") ? "&" : "?"}cacheblock=true` ); svgContent = await svgFetched.text(); } else if (icon.includes("fa-")) { svgContent = await getFASvgFile(icon); } else return null; const img = await loadAndConvertSvgInImg( svgContent, color, isImage, multiflowData ); return { icon, color, img, iconKey }; }); return await Promise.all(rawSvgs); } catch (error) { console.error("Error loading icons:", error); throw new Error("Failed to load icons"); } };