fix: auto-create CSS rules when selector or property is missing
updateCssValue now handles three cases: - Selector doesn't exist: creates the full block with property - Selector exists but property missing: adds property to block - Property exists: updates the value 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
681517db21
commit
668d950518
1 changed files with 23 additions and 11 deletions
|
|
@ -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 };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue