import * as path from 'path';
export function generateIconComponentCode(
componentName: string,
weightsObjectLiteral: string,
viewBox: string | null = null,
meta?: { collection: string; usageName: string },
): string {
// 注意:组件物理目录为 src/icons/{collection}/{Name}.svelte,所以 lib 是 ../../lib
const lines = [
``,
``,
meta
? ``
: ``,
'',
);
return lines.join('\n');
}
const BLACK_COLOR_VALUES = new Set([
'#000',
'#000000',
'#000000ff',
'black',
'rgb(0,0,0)',
'rgb(0, 0, 0)',
'rgba(0,0,0,1)',
'rgba(0, 0, 0, 1)'
]);
function normalizeColorAttributes(svgFragment: string): string {
const shouldReplace = (value: string) => {
const trimmed = value.trim();
if (
!trimmed ||
/^none$/i.test(trimmed) ||
/^currentColor$/i.test(trimmed) ||
/^url\(/i.test(trimmed) ||
/^var\(/i.test(trimmed)
) {
return false;
}
return BLACK_COLOR_VALUES.has(trimmed.toLowerCase());
};
const replaceAttr = (attr: string, quote: string, value: string, original: string) => {
if (!shouldReplace(value)) {
return original;
}
return `${attr}=${quote}currentColor${quote}`;
};
let normalized = svgFragment.replace(
/(fill|stroke)=("|\')([^"\']+)\2/gi,
(match, attr, quote, value) => replaceAttr(attr, quote, value, match)
);
normalized = normalized.replace(/style=("|\')([^"\']*)\1/gi, (match, quote, value) => {
const updated = value.replace(/(fill|stroke)\s*:\s*([^;]+)/gi, (_m, attr, val) => {
const trimmed = val.trim();
if (!shouldReplace(trimmed)) {
return `${attr}:${trimmed}`;
}
return `${attr}:currentColor`;
});
return updated === value ? match : `style=${quote}${updated}${quote}`;
});
return normalized;
}
const ATTRIBUTE_NAME_MAP: Record = {
'clip-rule': 'clipRule',
'fill-rule': 'fillRule',
'stroke-width': 'strokeWidth',
'stroke-linecap': 'strokeLinecap',
'stroke-linejoin': 'strokeLinejoin',
'stroke-miterlimit': 'strokeMiterlimit',
'stop-color': 'stopColor',
'stop-opacity': 'stopOpacity',
'color-interpolation-filters': 'colorInterpolationFilters',
'flood-color': 'floodColor',
'flood-opacity': 'floodOpacity'
};
function normalizeAttributeNames(svgFragment: string): string {
return svgFragment.replace(/(\s)([a-zA-Z_:][a-zA-Z0-9_.:-]*)=/g, (match, prefix, attr) => {
const lowerAttr = attr.toLowerCase();
if (ATTRIBUTE_NAME_MAP[lowerAttr]) {
return `${prefix}${ATTRIBUTE_NAME_MAP[lowerAttr]}=`;
}
return match;
});
}
function toStyleProp(prop: string): string {
const mapped = ATTRIBUTE_NAME_MAP[prop.toLowerCase()];
if (mapped) return mapped;
return prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());
}
function convertStyleAttributes(svgFragment: string): string {
return svgFragment.replace(/style=("([^"]*)"|'([^']*)')/gi, (_match, _full, doubleQuote, singleQuote) => {
const styleContent = (doubleQuote ?? singleQuote ?? '').trim();
if (!styleContent) {
return `style=""`;
}
const declarations = styleContent
.split(/;(?![^(]*\))/g)
.map((part) => part.trim())
.filter(Boolean)
.map((declaration) => {
const [rawProp, ...rawValueParts] = declaration.split(':');
if (!rawProp || rawValueParts.length === 0) return null;
const valueRaw = rawValueParts.join(':').trim();
if (!valueRaw) return null;
const propName = toStyleProp(rawProp.trim());
const numericMatch = /^[-+]?\d*\.?\d+$/.test(valueRaw);
if (numericMatch) {
const numericValue = Number(valueRaw);
return `${propName}: ${numericValue}`;
}
return `${propName}: "${valueRaw.replace(/"/g, '\\"')}"`;
})
.filter((item): item is string => Boolean(item));
if (declarations.length === 0) {
return `style=""`;
}
return `style="${declarations.join('; ')}"`;
});
}
function removeXmlnsAttributes(svgFragment: string): string {
return svgFragment.replace(/\s+xmlns(:[a-zA-Z0-9_-]+)?=("([^"]*)"|'([^']*)')/gi, '');
}
export function extractViewBox(svg: string): string | null {
const viewBoxMatch = svg.match(/viewBox=["']([^"']+)["']/i);
if (viewBoxMatch) {
return viewBoxMatch[1];
}
// 如果没有 viewBox,尝试从 width 和 height 推断
const widthMatch = svg.match(/width=["'](\d+)["']/i);
const heightMatch = svg.match(/height=["'](\d+)["']/i);
if (widthMatch && heightMatch) {
return `0 0 ${widthMatch[1]} ${heightMatch[1]}`;
}
return null;
}
export function wrapSvgAsSvelte(svgByWeight: Record, componentName: string): { weightsLiteral: string; viewBox: string | null } {
let extractedViewBox: string | null = null;
const entries = Object.entries(svgByWeight).map(([w, svg]) => {
// 提取 viewBox(使用第一个找到的 viewBox,假设所有权重使用相同的 viewBox)
if (!extractedViewBox) {
extractedViewBox = extractViewBox(svg);
}
// strip xml/doctype and outer , keep inner nodes for IconBase
let cleaned = svg
.replace(/<\?xml[^>]*>/gi, '')
.replace(/]*>/gi, '')
.trim();
// extract inner of first
const svgMatch = cleaned.match(/