diff --git a/src/utils/css-parsing.js b/src/utils/css-parsing.js index 08edd4c..96e3c85 100644 --- a/src/utils/css-parsing.js +++ b/src/utils/css-parsing.js @@ -16,20 +16,32 @@ const extractCssValue = (css, selector, property) => { const updateCssValue = ({ css, selector, property, value, unit }) => { const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const formattedValue = unit === '' || unit === undefined ? value : `${value}${unit}`; - if (unit === '') { - const regex = new RegExp( - `(${escaped}\\s*{[^}]*${property}:\\s*)[^;]+`, - 'gi' - ); - return css.replace(regex, `$1${value}`); + // Check if selector exists + const selectorRegex = new RegExp(`${escaped}\\s*{([^}]*)}`, 'i'); + const selectorMatch = css.match(selectorRegex); + + if (!selectorMatch) { + // Selector doesn't exist, create it + return css + `\n${selector} {\n ${property}: ${formattedValue};\n}\n`; } - const regex = new RegExp( - `(${escaped}\\s*{[^}]*${property}:\\s*)[\\d.]+(px|rem|em|mm|cm|in)`, - 'gi' - ); - return css.replace(regex, `$1${value}${unit}`); + const blockContent = selectorMatch[1]; + + // Check if property exists in the block + const propertyRegex = new RegExp(`(${property}\\s*:\\s*)([^;]+)(;?)`, 'i'); + const propertyMatch = blockContent.match(propertyRegex); + + if (!propertyMatch) { + // Property doesn't exist, add it to the block + const newBlockContent = blockContent.trimEnd() + `\n ${property}: ${formattedValue};`; + return css.replace(selectorRegex, `${selector} {${newBlockContent}}`); + } + + // Property exists, replace the entire value + const newBlockContent = blockContent.replace(propertyRegex, `$1${formattedValue}$3`); + return css.replace(selectorRegex, `${selector} {${newBlockContent}}`); }; const cssParsingUtils = { extractCssBlock, extractCssValue, updateCssValue };