-
-
Save mindplay-dk/47bc597dcbc28bea009b02c5a0c9010e to your computer and use it in GitHub Desktop.
CSS maker
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
type CSSDeclaration = Partial<CSSStyleDeclaration> & { [name: string]: any }; | |
const sheet = document.head.appendChild(document.createElement("style")).sheet as CSSStyleSheet; | |
const hyph = s => s.replace(/[A-Z]|^ms/g, '-$&').toLowerCase(); | |
const mx = (rule, media) => media ? `${media}{${rule}}` : rule; | |
const rx = (cn, prop, val) => `.${cn}{${hyph(prop)}:${val}}`; | |
const noAnd = s => s.replace(/&/g, ''); | |
function css(obj: CSSDeclaration) { | |
let className = 'x' + (sheet.rules.length).toString(36); | |
function parse(obj: CSSDeclaration, child: string, media: string) { | |
for (var key in obj) { | |
const val = obj[key]; | |
if (typeof val === 'object') { | |
const _media = /^@/.test(key) ? key : null; | |
const _child = _media ? child : child + ( | |
/^&/.test(key) ? key.substring(1) : " " + key | |
); | |
parse(val, _child, _media || media); | |
} else { | |
const rule = mx(rx(className + noAnd(child), key, val), media); | |
sheet.insertRule(rule, sheet.cssRules.length); | |
console.log(className, rule); | |
} | |
} | |
} | |
parse(obj, '', ''); | |
return className; | |
} | |
/// EXAMPLE: | |
document.getElementById("test").className = css({ | |
color: "red", | |
"h1": { | |
color: "blue", | |
"&:hover": { | |
color: "green" | |
} | |
}, | |
"@media screen and (min-width: 400px)": { | |
"h1": { | |
fontSize: "50px" | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment