Skip to content

Instantly share code, notes, and snippets.

@adi518
Created July 14, 2020 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adi518/3b50dcaf8fa0c3f853a85d7389b1cd93 to your computer and use it in GitHub Desktop.
Save adi518/3b50dcaf8fa0c3f853a85d7389b1cd93 to your computer and use it in GitHub Desktop.
var postcss = require('postcss');
var objectAssign = require('object-assign');
var classRepeat = require('class-repeat');
var isPresent = require('is-present');
var hasClass = require('has-class-selector');
require('string.prototype.repeat');
let opts;
function specifyByClassRepeat(root) {
root.walkRules(function(node) {
if (isPresent(node.selectors)) {
node.selectors = node.selectors.map(function(selector) {
return hasClass(selector) ? classRepeat(selector, opts) : selector;
});
}
return node;
});
}
function specifyById(root) {
opts.id = opts.id[0] !== '#' ? '#' + opts.id : opts.id;
root.walkRules(function(rule) {
var isInsideKeyframes =
rule.parent.type === 'atrule' &&
(rule.parent.name === 'keyframes' ||
rule.parent.name === '-webkit-keyframes' ||
rule.parent.name === 'webkit-keyframes');
if (!isInsideKeyframes) {
increaseSpecifityOfRule(rule, opts);
}
});
}
function increaseSpecifityOfRule(rule, opts) {
rule.selectors = rule.selectors.map(function(selector) {
if (
selector.includes(':root') ||
selector === 'html' ||
selector === 'body'
) {
return selector;
}
if (opts.withoutCssLoaderPrefix) {
return `:global(${opts.id.repeat(opts.repeat)}) ${selector}`;
}
return `${opts.id.repeat(opts.repeat)} ${selector}`;
});
}
const postcssIncreaseSpecificity = postcss.plugin(
'postcss-increase-specificity',
function(options) {
const defaults = {
repeat: 2,
};
opts = objectAssign({}, defaults, options);
let specifyBy = opts.id ? specifyById : specifyByClassRepeat;
return specifyBy;
}
);
module.exports = postcssIncreaseSpecificity;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment