diff --git a/README.md b/README.md index c41a50f..39eae5c 100644 --- a/README.md +++ b/README.md @@ -111,5 +111,49 @@ Default: `&` Ancestor selector base symbol +### replaceValues + +Type `boolean` +Default: `false` + +If this is true then this plugin will look through your declaration values for the placeholder symbol and replace them with the desired selector. + +i.e. + +```css +.foo { + background-color: red; + + &:hover { + background-color: blue; + + &::before { + content: '^&'; + } + } +} +``` + +``` +.foo { + background-color: red; +} + +.foo:hover { + background-color: blue; +} + +.foo:hover::before { + content: '.foo' +} +``` + +### pseudoClasses + +Type `boolean` +Default: `false` + +If this is true then pseudo classes (`&:hover`, `&:focus`) are included in the parent chain + ## Todo's - Add warning when nestingLevel >= parentsStack.length diff --git a/index.js b/index.js index 0383923..e9b58ff 100644 --- a/index.js +++ b/index.js @@ -4,7 +4,9 @@ var postcss = require('postcss'), module.exports = postcss.plugin('postcss-nested-ancestors', function (opts) { opts = assign({ - placeholder: '^&' + placeholder: '^&', + replaceValues: false, + pseudoClasses: false }, opts); // Advanced options @@ -34,6 +36,8 @@ module.exports = postcss.plugin('postcss-nested-ancestors', function (opts) { function getParentSelectorAtLevel(nestingLevel) { nestingLevel = nestingLevel || 1; + if (opts.pseudoClasses) nestingLevel -= 1; + // @TODO add warning when nestingLevel >= parentsStack.length return parentsStack.filter( function (rule, index) { @@ -85,6 +89,18 @@ module.exports = postcss.plugin('postcss-nested-ancestors', function (opts) { // Replace parents placeholders in rule selector rule.selectors = rule.selectors.map(replacePlaceholders); + if (opts.replaceValues) { + rule.nodes.forEach(function (ruleNode) { + if (ruleNode.type === 'decl') { + if (ruleNode.value.indexOf(opts.placeholder) >= 0) { + ruleNode.value = replacePlaceholders( + ruleNode.value + ); + } + } + }); + } + // Process child rules process(rule); } diff --git a/test.js b/test.js index 5a0a739..c356465 100644 --- a/test.js +++ b/test.js @@ -43,6 +43,24 @@ test('Prepend 2 ancestors in double selector', t => { ); }); +test('Replace declaration values if replaceValues is true', t => { + return run( t, + '.a{ background: red; &:hover {&::before { content: "^&"; }}}', + '.a{ background: red; &:hover {&::before { content: ".a"; }}}', + { replaceValues: true } + ); +}); + +test('Take into account pseudo classes if pseudoClasses is true', t => { + return run( t, + '.a{ background: red; &:hover {&::before ' + + '{ content: "^&"; }}}', + '.a{ background: red; &:hover {&::before ' + + '{ content: ".a:hover"; }}}', + { replaceValues: true, pseudoClasses: true } + ); +}); + test('Replace ancestors at different nesting levels', t => { return run( t, '.a{ &:hover{ ^&-b{} } .c{ .d{ ^&-e{} } } .z{} }',