import { camelCase } from 'change-case'; import { Node } from 'svg-parser'; // @ts-ignore - types doesn't exist for this lib. We should try to remove it since it's not maintained. import nativeCSS from 'css-to-object'; const CUSTOM_ATTRIBUTES = new Map(); CUSTOM_ATTRIBUTES.set('class', 'className'); function transformStyle(style: string) { const transformed = nativeCSS(style, { numbers: true, camelCase: true, }); return transformed; } export function transform(node: Node | string): Node | string { if (typeof node === 'string') { return node; } const attributeNames = Object.keys(node.attributes); const attributes = attributeNames.reduce((accumulator, attributeName) => { const attribute = node.attributes[attributeName]; if (attributeName.startsWith('data-')) { return { ...accumulator, [attributeName]: attribute, }; } if (attributeName === 'style' && typeof attribute === 'string') { return { ...accumulator, [attributeName]: transformStyle(attribute), }; } if (CUSTOM_ATTRIBUTES.has(attributeName)) { return { ...accumulator, [CUSTOM_ATTRIBUTES.get(attributeName)]: attribute, }; } return { ...accumulator, [camelCase(attributeName)]: attribute, }; }, {}); const children = node.children.map(transform); return { ...node, children, attributes, } as Node; }