Last active
August 29, 2015 14:11
-
-
Save hayes/ae55bbcd5206c0795902 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var document = require('dom-lite').document | |
var specificity = require('specificity') | |
var cssauron = require('cssauron') | |
var css = require('cssauron')({ | |
tag: 'tagName', | |
contents: 'innerText', | |
id: 'id', | |
class: 'className', | |
parent: 'parentNode', | |
children: 'childNodes', | |
attr: 'getAttribute(attr)' | |
}) | |
var div = document.createElement('div') | |
var a = document.createElement('a') | |
var rules = [] | |
addRule('a', { | |
width: 100, | |
color: 'red' | |
}) | |
addRule('div > a', { | |
color: 'blue' | |
}) | |
addRule('div', { | |
color: 'green' | |
}) | |
div.appendChild(a) | |
console.log(getComputedStyle(a)) | |
console.log(getComputedStyle(div)) | |
function getComputedStyle(el) { | |
var matched = [] | |
for(var i = 0, l = rules.length; i < l; ++i) { | |
if(rules[i].selector(el)) matched.push(rules[i].styles) | |
} | |
return matched.reduce(function(out, rule) { | |
var keys = Object.keys(rule) | |
for(var i = 0, l = keys.length; i < l; ++i) { | |
out[keys[i]] = rule[keys[i]] | |
} | |
return out | |
}, {}) | |
} | |
function addRule(rule, styles) { | |
if(~rule.indexOf(',')) { | |
return rule.split(',').map(function(rule) { | |
addRule(rule, styles) | |
}) | |
} | |
rules.push({ | |
selector: css(rule.toUpperCase()), | |
styles: styles, | |
raw: rule, | |
spec: specificity.calculate(rule)[0].specificity.split(',') | |
}) | |
rules.sort(sort) | |
} | |
function sort(lhs, rhs) { | |
for(var i = 0; i < 4; ++i) { | |
if(lhs.spec[i] === rhs.spec[i]) continue | |
return lhs.spec[i] > rhs.spec[i] ? 1 : -1 | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment