From 40fabe91bed64be640e3a667438a0e83b78fd62e Mon Sep 17 00:00:00 2001 From: Asman Umbetov Date: Mon, 18 Mar 2024 23:18:40 +0300 Subject: [PATCH] fix(#209) fixes issue with parsing of nested variables --- addon/src/parsers/postcss.parser.ts | 50 +++++++++++------------------ 1 file changed, 19 insertions(+), 31 deletions(-) diff --git a/addon/src/parsers/postcss.parser.ts b/addon/src/parsers/postcss.parser.ts index 836d94d..17be0fb 100644 --- a/addon/src/parsers/postcss.parser.ts +++ b/addon/src/parsers/postcss.parser.ts @@ -33,8 +33,8 @@ export async function parseCssFiles( injectionStyles + `:root { ${nodes.declarations - .map((declaration) => declaration.toString()) - .join(";")} + .map((declaration) => declaration.toString()) + .join(";")} }`; } @@ -83,15 +83,15 @@ function determineCategories( to: !nextCommentIsInAnotherFile && nextComment?.prev() ? { - column: nextComment.prev()?.source?.end?.column || 0, - line: nextComment.prev()?.source?.end?.line || 0, - } + column: nextComment.prev()?.source?.end?.column || 0, + line: nextComment.prev()?.source?.end?.line || 0, + } : !nextCommentIsInAnotherFile && nextComment - ? { + ? { column: nextComment.source?.start?.column || 0, line: nextComment.source?.start?.line || 0, } - : undefined, + : undefined, }; const source = comment.source?.input.from || ""; @@ -184,36 +184,24 @@ function determineTokenValue( ): string { rawValue = rawValue.replace(/!default/g, "").replace(/!global/g, ""); - const cssVars = "(var\\(([a-zA-Z0-9-_]+)\\))"; - const scssVars = "(\\$([a-zA-Z0-9-_]+))"; - const lessVars = "(\\@([a-zA-Z0-9-_]+))"; - - const vars = [!preserveCSSVars && cssVars, scssVars, lessVars].filter( - Boolean - ) as string[]; - - const referencedVariableResult = new RegExp(`^(${vars.join("|")})$`).exec( - rawValue - ); - - const referencedVariable = - referencedVariableResult?.[3] || - referencedVariableResult?.[5] || - referencedVariableResult?.[7]; - - if (referencedVariable) { - const value = + const regex = /\bvar\(([^)]+)\)|(\$[a-zA-Z0-9-_]+|@[a-zA-Z0-9-_]+)/g; + let match; + let replacedString = rawValue; + while ((match = regex.exec(rawValue)) !== null) { + const variableMatch = match[0]; + const variableName = variableMatch.replace(/\(|\)|var\(|@|\$/g, ""); + const replacement = declarations.find( (declaration) => - declaration.prop === referencedVariable || - declaration.prop === `$${referencedVariable}` || - declaration.prop === `@${referencedVariable}` + declaration.prop === variableName || + declaration.prop === `$${variableName}` || + declaration.prop === `@${variableName}` )?.value || ""; - return determineTokenValue(value, declarations, preserveCSSVars); + replacedString = replacedString.replace(variableMatch, replacement); } - return rawValue; + return replacedString; } async function getNodes(files: File[]): Promise<{