Skip to content

Commit

Permalink
Include all configuration in the <style /> element
Browse files Browse the repository at this point in the history
This fixes a bug in the prefixIds plugin.  It assumed that the <style />
element will have a single text fragment underneath.

So this works:
<style>
<!-- Leading comment ignored -->
.class1 {}
...
.classN {}
</style>

The above parses so that node.children[0] is a "text" node with all the
CSS classes where "node" is the style element.

And this fails:
<style>
<!-- Ignored comment -->
.class1 {}
<!-- comment -->
.class2 {}
</style>

This fails because only node.children[0] is processed and node.children
looks something like:
[
.class1 (type = "text")
comment (type = "comment")
.class2 (type = "text")
]
  • Loading branch information
john-neptune committed Jan 9, 2023
1 parent aa5d667 commit 4e3007c
Showing 1 changed file with 44 additions and 42 deletions.
86 changes: 44 additions & 42 deletions plugins/prefixIds.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,55 +101,57 @@ exports.fn = (_root, params, info) => {
}

// parse styles
let cssText = '';
if (
node.children[0].type === 'text' ||
node.children[0].type === 'cdata'
) {
cssText = node.children[0].value;
}
/**
* @type {null | csstree.CssNode}
*/
let cssAst = null;
try {
cssAst = csstree.parse(cssText, {
parseValue: true,
parseCustomProperty: false,
});
} catch {
return;
}

csstree.walk(cssAst, (node) => {
// #ID, .class selectors
node.children.forEach(child => {
let cssText = '';
if (
(prefixIds && node.type === 'IdSelector') ||
(prefixClassNames && node.type === 'ClassSelector')
child.type === 'text' ||
child.type === 'cdata'
) {
node.name = prefixId(prefix, node.name);
cssText = child.value;
}
/**
* @type {null | csstree.CssNode}
*/
let cssAst = null;
try {
cssAst = csstree.parse(cssText, {
parseValue: true,
parseCustomProperty: false,
});
} catch {
return;
}
// url(...) references
// csstree v2 changed this type
if (node.type === 'Url' && toAny(node.value).length > 0) {
const prefixed = prefixReference(
prefix,
unquote(toAny(node.value))
);
if (prefixed != null) {
toAny(node).value = prefixed;

csstree.walk(cssAst, (node) => {
// #ID, .class selectors
if (
(prefixIds && node.type === 'IdSelector') ||
(prefixClassNames && node.type === 'ClassSelector')
) {
node.name = prefixId(prefix, node.name);
return;
}
// url(...) references
// csstree v2 changed this type
if (node.type === 'Url' && toAny(node.value).length > 0) {
const prefixed = prefixReference(
prefix,
unquote(toAny(node.value))
);
if (prefixed != null) {
toAny(node).value = prefixed;
}
}
});

// update styles
if (
child.type === 'text' ||
child.type === 'cdata'
) {
child.value = csstree.generate(cssAst);
}
});

// update styles
if (
node.children[0].type === 'text' ||
node.children[0].type === 'cdata'
) {
node.children[0].value = csstree.generate(cssAst);
}
return;
}

Expand Down

0 comments on commit 4e3007c

Please sign in to comment.