Skip to content
This repository has been archived by the owner on Feb 21, 2024. It is now read-only.

Commit

Permalink
feat(lib): initial development
Browse files Browse the repository at this point in the history
  • Loading branch information
kcmr committed Apr 22, 2019
1 parent a59b393 commit 2ba8f2b
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
16 changes: 16 additions & 0 deletions develop/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const fs = require('fs');
const path = require('path');
const postcss = require('postcss');
const plugin = require('../lib');

const fixturePath = path.join(process.cwd(), 'tests', 'fixtures');
const read = (file) => fs.readFileSync(path.join(fixturePath, file), 'utf-8');
const input = read('develop.css');

postcss()
.use(plugin)
.process(input, { from: undefined, to: undefined })
.then((result) => {
console.log(result.css);
})
.catch(console.error);
27 changes: 27 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

const postcss = require('postcss');

module.exports = postcss.plugin('postcss-selector-scope', (options = {}) => {
options = Object.assign({
not: '.style-scope',
exclude: [':root']
}, options);

const excluded = (options.exclude || []).join('|');
const included = new RegExp(`^(?!${excluded})\\S+`);

const scope = (pattern) => (str) => {
const result = str.match(pattern) ? `${str}:not(${options.not})` : str;

return result;
};

const transform = (pattern) => (selector) => selector.split(' ').map(scope(pattern)).join(' ');

return (root) => {
root.walkRules((rule) => {
rule.selectors = rule.selectors.map(transform(included));
});
};
});
46 changes: 46 additions & 0 deletions tests/fixtures/develop.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* excluded */
:root {
--some-var: red;
}

/* tags */
a,
b,
strong,
html,
body,
body .class,
.class div {
color: red;
}

/* classes and IDs */
.foo,
#bar,
#id .class,
.class #id {
color: red;
}

/* pseudo and not */
div::after,
div:after {
content: "";
}

a:hover,
::selection,
:focus {
outline: 1px solid blue;
}

.any:not(.selected) {
color: red;
}

/* attributes */
[class*="any"],
[class^="any-"],
[class*=" any"] {
color: red;
}

0 comments on commit 2ba8f2b

Please sign in to comment.