2021-03-23 19:26:50 +01:00
|
|
|
import { basename } from 'path';
|
|
|
|
|
import { parseSync } from 'svgson';
|
2022-08-10 09:10:53 +02:00
|
|
|
import { generateHashedKey, readSvg, hasDuplicatedChildren } from '../helpers.mjs';
|
2020-10-06 20:23:26 +02:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Build an object in the format: `{ <name>: <contents> }`.
|
|
|
|
|
* @param {string[]} svgFiles - A list of filenames.
|
|
|
|
|
* @param {Function} getSvg - A function that returns the contents of an SVG file given a filename.
|
|
|
|
|
* @returns {Object}
|
|
|
|
|
*/
|
2021-03-23 19:26:50 +01:00
|
|
|
export default (svgFiles, iconsDirectory, renderUniqueKey = false) =>
|
2020-10-06 20:23:26 +02:00
|
|
|
svgFiles
|
2022-11-07 22:29:19 +01:00
|
|
|
.map((svgFile) => {
|
2021-03-23 19:26:50 +01:00
|
|
|
const name = basename(svgFile, '.svg');
|
2020-10-06 20:23:26 +02:00
|
|
|
const svg = readSvg(svgFile, iconsDirectory);
|
2021-03-23 19:26:50 +01:00
|
|
|
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) {
|
2022-11-07 22:29:19 +01:00
|
|
|
contents.children = contents.children.map((child) => {
|
2021-03-23 19:26:50 +01:00
|
|
|
child.attributes.key = generateHashedKey(child);
|
|
|
|
|
|
|
|
|
|
return child;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-06 20:23:26 +02:00
|
|
|
return { name, contents };
|
|
|
|
|
})
|
|
|
|
|
.reduce((icons, icon) => {
|
|
|
|
|
icons[icon.name] = icon.contents;
|
|
|
|
|
return icons;
|
|
|
|
|
}, {});
|