wealth/packages/island/src/tools/icon-sprite-plugin/icon-sprite-plugin.ts

58 lines
1.9 KiB
TypeScript

import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { optimize } from 'svgo';
import type { IconSpriteOptions } from './types';
const ROOT_SVG = /^<svg\b([^>]*)>([\s\S]*)<\/svg>$/;
const VIEW_BOX = /viewBox="([^"]+)"/;
/**
* Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped
* from each root, so the `<Icon>` that references a symbol sets them and a caller can change them.
*/
export function buildIconSprite({
iconsDir,
spriteFile,
namesFile,
}: IconSpriteOptions): string[] {
const files = readdirSync(iconsDir)
.filter((file) => file.endsWith('.svg'))
.sort();
const names = files.map((file) => basename(file, '.svg'));
const symbols = files.map((file, index) => {
const { data } = optimize(readFileSync(join(iconsDir, file), 'utf8'), {
multipass: true,
// svgo 4 keeps the viewBox by default.
plugins: ['preset-default'],
});
const [, attributes, body] = ROOT_SVG.exec(data) ?? [];
const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1];
if (body === undefined || !viewBox) {
throw new Error(`${file}: expected one root <svg> with a viewBox`);
}
return `<symbol id="${names[index]}" viewBox="${viewBox}">${body}</symbol>`;
});
// Next.js reads a static SVG's size on import, so the root carries one; `<use>` ignores it.
writeFileSync(
spriteFile,
`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">${symbols.join('')}</svg>\n`,
);
writeFileSync(
namesFile,
[
'// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`.',
'',
'export const ICON_NAMES = [',
...names.map((name) => ` '${name}',`),
'] as const;',
'',
'export type IconName = (typeof ICON_NAMES)[number];',
'',
].join('\n'),
);
return names;
}