2023-01-17 08:04:34 +01:00
|
|
|
import { basename } from 'path';
|
2025-06-18 15:47:24 +02:00
|
|
|
import { type INode, parseSync } from 'svgson';
|
2024-06-28 11:24:37 +02:00
|
|
|
import { generateHashedKey, readSvg, hasDuplicatedChildren } from '@lucide/helpers';
|
2023-01-17 08:04:34 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Build an object in the format: `{ <name>: <contents> }`.
|
|
|
|
|
* @param {string[]} svgFiles - A list of filenames.
|
2025-06-18 15:47:24 +02:00
|
|
|
* @param {string} iconsDirectory - The directory where the icons are stored.
|
2023-01-17 08:04:34 +01:00
|
|
|
* @returns {Object}
|
|
|
|
|
*/
|
2025-02-10 14:13:52 +01:00
|
|
|
export default async function generateIconObject(
|
2025-06-18 15:47:24 +02:00
|
|
|
svgFiles: string[],
|
|
|
|
|
iconsDirectory: string,
|
2025-02-10 14:13:52 +01:00
|
|
|
renderUniqueKey = false,
|
|
|
|
|
) {
|
|
|
|
|
const svgsContentPromises = svgFiles.map(async (svgFile) => {
|
|
|
|
|
const name = basename(svgFile, '.svg');
|
|
|
|
|
const svg = await readSvg(svgFile, iconsDirectory);
|
|
|
|
|
const contents = parseSync(svg);
|
|
|
|
|
|
|
|
|
|
if (!(contents.children && contents.children.length)) {
|
|
|
|
|
throw new Error(`${name}.svg has no children!`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (hasDuplicatedChildren(contents.children)) {
|
|
|
|
|
throw new Error(`Duplicated children in ${name}.svg`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (renderUniqueKey) {
|
|
|
|
|
contents.children = contents.children.map((child) => {
|
|
|
|
|
child.attributes.key = generateHashedKey(child);
|
|
|
|
|
|
|
|
|
|
return child;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { name, contents };
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const svgsContents = await Promise.all(svgsContentPromises);
|
|
|
|
|
|
2025-06-18 15:47:24 +02:00
|
|
|
return svgsContents.reduce<Record<string, INode>>((icons, icon) => {
|
2025-02-10 14:13:52 +01:00
|
|
|
icons[icon.name] = icon.contents;
|
|
|
|
|
return icons;
|
|
|
|
|
}, {});
|
|
|
|
|
}
|