refactor: more concise

This commit is contained in:
zernonia 2023-10-21 16:53:31 +08:00
parent fd42e6766f
commit db766086e2

View File

@ -20,35 +20,32 @@ export const transformCssVars: Transformer = async ({
return sourceFile return sourceFile
type ElementNode = typeof template.ast type ElementNode = typeof template.ast
type ElementNodeChildren = ElementNode['children'] type TemplateNode = ElementNode['children'][number]
const parseChildren = (children: ElementNodeChildren) => { const parseNode = (node: ElementNode | TemplateNode) => {
for (const child of children) { if ('props' in node) {
if ('children' in child) for (const prop of node.props) {
parseChildren(child.children as ElementNodeChildren) // for component
if ('props' in child) {
for (const prop of child.props) {
if ('arg' in prop && prop.arg && 'content' in prop.exp! && prop.exp) { if ('arg' in prop && prop.arg && 'content' in prop.exp! && prop.exp) {
if ('content' in prop.arg && prop.arg?.content === 'class') { if ('content' in prop.arg && prop.arg?.content === 'class') {
const s = new MagicString(prop.exp.content) const s = new MagicString(prop.exp.content)
s.replace(/'(.*?)'/g, (substring) => { s.replace(/'(.*?)'/g, (substring) => {
return applyColorMapping(substring, return `'${applyColorMapping(substring, baseColor.inlineColors)}'`
baseColor.inlineColors,
)
}) })
sourceFile.replaceText([prop.exp.loc.start.offset, prop.exp.loc.end.offset], s.toString()) sourceFile.replaceText([prop.exp.loc.start.offset, prop.exp.loc.end.offset], s.toString())
} }
} }
} }
} }
if ('children' in node) {
for (const child of node.children)
parseNode(child as TemplateNode)
} }
} }
walk(template?.ast, { walk(template?.ast, {
enter(node: ElementNode) { enter(node: ElementNode) {
if (node.children) parseNode(node)
parseChildren(node.children)
}, },
}) })
@ -129,5 +126,5 @@ export function applyColorMapping(
} }
const combined = `${lightMode.join(' ').replace(/\'/g, '')} ${darkMode.join(' ').trim()}`.trim() const combined = `${lightMode.join(' ').replace(/\'/g, '')} ${darkMode.join(' ').trim()}`.trim()
return `'${combined}'` return `${combined}`
} }