Files

47 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2023-01-17 08:04:34 +01:00
import { basename } from 'path';
import { type INode, parseSync } from 'svgson';
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.
* @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(
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);
2023-01-17 08:04:34 +01:00
2025-02-10 14:13:52 +01:00
if (!(contents.children && contents.children.length)) {
throw new Error(`${name}.svg has no children!`);
}
2023-01-17 08:04:34 +01:00
2025-02-10 14:13:52 +01:00
if (hasDuplicatedChildren(contents.children)) {
throw new Error(`Duplicated children in ${name}.svg`);
}
2023-01-17 08:04:34 +01:00
2025-02-10 14:13:52 +01:00
if (renderUniqueKey) {
contents.children = contents.children.map((child) => {
child.attributes.key = generateHashedKey(child);
2023-01-17 08:04:34 +01:00
2025-02-10 14:13:52 +01:00
return child;
});
}
2023-01-17 08:04:34 +01:00
2025-02-10 14:13:52 +01:00
return { name, contents };
});
const svgsContents = await Promise.all(svgsContentPromises);
return svgsContents.reduce<Record<string, INode>>((icons, icon) => {
2025-02-10 14:13:52 +01:00
icons[icon.name] = icon.contents;
return icons;
}, {});
}