Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active July 15, 2022 03:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/47bc597dcbc28bea009b02c5a0c9010e to your computer and use it in GitHub Desktop.
Save mindplay-dk/47bc597dcbc28bea009b02c5a0c9010e to your computer and use it in GitHub Desktop.
CSS maker
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