|
| 1 | +/** |
| 2 | + * Process raw icon svg by removing any hardcoded |
| 3 | + * dimensions and colors and apply additional styles |
| 4 | + * so that they can adapt to the component settings. |
| 5 | + * @param input the raw svg string |
| 6 | + * @returns the processed svg string |
| 7 | + * |
| 8 | + * @example |
| 9 | + * ```ts |
| 10 | + * import { processIconSvg as i } from '@angularity/icons'; |
| 11 | + * export const iArrow = i`<svg width="24" height="24" fill="none" stroke="black"><path d="M12 5v14m7-7H5"/></svg>`; |
| 12 | + * ``` |
| 13 | + */ |
| 14 | +export async function processIconSvg( |
| 15 | + input: string | TemplateStringsArray, |
| 16 | +): Promise<string> { |
| 17 | + const raw = Array.isArray(input) ? input[0] : input; |
| 18 | + |
| 19 | + const { parse } = await import('node-html-parser').then((m) => m.default); |
| 20 | + |
| 21 | + const root = parse(raw); |
| 22 | + |
| 23 | + const svg = root.querySelector('svg'); |
| 24 | + if (!svg) throw new Error('SVG element not found'); |
| 25 | + svg.removeAttribute('width'); |
| 26 | + svg.removeAttribute('height'); |
| 27 | + svg.setAttribute('aria-hidden', 'true'); |
| 28 | + svg.setAttribute( |
| 29 | + 'style', |
| 30 | + 'width: var(--icon-size); height: var(--icon-size)', |
| 31 | + ); |
| 32 | + |
| 33 | + root.querySelectorAll('svg *').forEach((node) => { |
| 34 | + node.removeAttribute('stroke-width'); |
| 35 | + if (node.hasAttribute('stroke') && node.getAttribute('stroke') !== 'none') |
| 36 | + root.setAttribute('stroke', 'currentColor'); |
| 37 | + if (node.hasAttribute('fill') && node.getAttribute('fill') !== 'none') |
| 38 | + node.setAttribute('fill', 'currentColor'); |
| 39 | + if ( |
| 40 | + ['PATH'].includes(node.tagName) && |
| 41 | + !node.hasAttribute('fill') && |
| 42 | + !node.hasAttribute('stroke') |
| 43 | + ) |
| 44 | + node.setAttribute('fill', 'currentColor'); |
| 45 | + }); |
| 46 | + |
| 47 | + return root.outerHTML; |
| 48 | +} |
0 commit comments