Skip to content

Instantly share code, notes, and snippets.

@bingo347
Created February 27, 2017 08:30
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 bingo347/cb8e62606e206c00999f24b1e62db1be to your computer and use it in GitHub Desktop.
Save bingo347/cb8e62606e206c00999f24b1e62db1be to your computer and use it in GitHub Desktop.
'use strict';
var rules = {};
var sheet;
var nextIndex = 0;
void function initStyle() {
var el = document.createElement('style');
document.head.appendChild(el);
sheet = el.sheet;
}();
function insertRule(cssText, _index) {
var index = _index;
if(!index) {
index = nextIndex;
nextIndex++;
} else {
sheet.deleteRule(index);
}
sheet.insertRule(cssText, index);
return index;
}
function buildRuleBody(declarations) {
const body = Object.getOwnPropertyNames(declarations).map(property => {
const value = declarations[property];
if(value === null) {
return '';
}
return `${property}:${value};`;
}).join('');
return '{' + body + '}';
}
function updateRule(_selector, declarations) {
if(~_selector.indexOf(',')) {
_selector.split(',').forEach(s => updateRule(s, declarations));
return;
}
const selector = _selector.trim();
if(rules[selector]) {
let props = Object.getOwnPropertyNames(declarations);
for(let i = props.length; i--;) {
let property = props[i];
if(declarations[property] === null) {
delete rules[selector].declarations[property];
} else {
rules[selector].declarations[property] = declarations[property];
}
}
let body = buildRuleBody(rules[selector].declarations);
insertRule(selector + body, rules[selector].index);
return;
}
let body = buildRuleBody(declarations);
rules[selector] = {
declarations,
index: insertRule(selector + body)
};
}
function insertStyle(styleData) {
if(!Array.isArray(styleData)) { return; }
styleData.forEach(rule => {
if(rule.t !== 'r') {
insertRule(rule.b);
return;
}
rule.s.forEach(selector => updateRule(selector, rule.d));
});
}
function getCurrentStyle(selector) {
return rules[selector] ? rules[selector].declarations : {};
}
module.exports = {
updateRule,
insertStyle,
getCurrentStyle
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment