Skip to content

Commit

Permalink
feat: 🎸 protect .putRaw from unknown pseudo-selectors
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jul 14, 2018
1 parent 69f4a76 commit d122cf5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/Installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ The `create()` function accepts an options object with the following keys:
- `pfx` — optional, string, prefix to add to all generated class and animation names, defaults to `_`.
- `h` — optional, hyperscript function of your virtual DOM library. Only necessary if you are using addons that require it.
- `sh` — optional, DOM style sheet element, useful when re-hydrating server rendered styles.
- `verbose` — optional, boolean, whether to be chatty in console in DEV mode.


```js
Expand Down
23 changes: 19 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,34 @@ exports.create = function (config) {
if (process.env.NODE_ENV !== 'production') {
renderer.sh.setAttribute('data-nano-css-dev', '');

// Test style sheet used in dev mode to test if .insetRule() would throw.
// Test style sheet used in DEV mode to test if .insetRule() would throw.
renderer.shTest = document.createElement('style');
renderer.shTest.setAttribute('data-nano-css-dev-tests', '');
document.head.appendChild(renderer.shTest);
}

renderer.putRaw = function (rawCssRule) {
// .insertRule() is faster than .appendChild(), that's why we use it in PROD.
// But CSS injected using .insertRule() is not displayed in Chrome Devtools,
// that's why we use .appendChild in DEV.
if (process.env.NODE_ENV === 'production') {
var sheet = renderer.sh.sheet;
sheet.insertRule(rawCssRule, sheet.cssRules.length);

// Unknown pseudo-selectors will throw, this try/catch swallows all errors.
try {
sheet.insertRule(rawCssRule, sheet.cssRules.length);
// eslint-disable-next-line no-empty
} catch (error) {}
} else {
// Test if .insertRule() works (does not throw).
renderer.shTest.sheet.insertRule(rawCssRule, renderer.shTest.sheet.cssRules.length);
// Test if .insertRule() works in dev mode. Unknown pseudo-selectors will throw when
// .insertRule() is used, but .appendChild() will not throw.
try {
renderer.shTest.sheet.insertRule(rawCssRule, renderer.shTest.sheet.cssRules.length);
} catch (error) {
if (config.verbose) {
console.error(error);
}
}

// Insert pretty-printed CSS for dev mode.
renderer.sh.appendChild(document.createTextNode(rawCssRule));
Expand Down

0 comments on commit d122cf5

Please sign in to comment.