Skip to content

Instantly share code, notes, and snippets.

@Raynos
Last active August 18, 2022 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Raynos/7223537 to your computer and use it in GitHub Desktop.
Save Raynos/7223537 to your computer and use it in GitHub Desktop.
/* stringify := (CSSON) => String
var accentColor = "some hex"
var pastelColor = "some hex"
var scaleColor = function (hex, scalar) {
// brighten if scalar positive, darken if scalar negative
}
var ulChildren = {
position: "absolute",
top: "-2000em"
}
var css = {
"ul.sf-menu": {
marginLeft: "10px",
"ul": { marginTop: "3px" },
"li": { background: "none" },
"li:hover ul, li.sfHover ul": { top: "35px" },
"li a": {
padding: "1px 10px",
color: scaleColor(accentColor, 2.5),
lineHeight: "35px"
},
"ul li": {
borderBottom: "1px solid " + scaleColor(accentColor, 1.85)
},
"ul li:last-child": {
borderBottom: "none"
},
"ul li a": {
background: scaleColor(accentColor, 2),
lineHeight: "normal",
fontSize: baseFontSize,
padding: "5px 10px",
color: scaleColor(accentColor, 0.8),
"&:hover": {
color: "#fff",
background: accentColor
}
},
"li li": {
background: pastelColor
},
".current_page_ancestor ul.children": ulChildren,
".current_page_item ul.children": ulChildren,
".current_page_parent ul.children": ulChildren
}
}
*/
function stringify(css, parentSelector) {
parentSelector = parentSelector || ""
var str = ""
Object.keys(css).forEach(function (key) {
var value = css[key]
// handle property
if (typeof value === "string") {
str += key + ": " + value + ";\n"
// handle selector
} else if (typeof value === "object") {
// handle obvouis bug where we mix properties & selectors
// we need to create two lists one for each and render them
// in a consistent order
var selector = parentSelector + " " + key
str += selector + "{ \n"
str += stringify(value, selector)
str += "}\n"
}
})
return str
}
var stringify = require("./stringify-css")
var md5 = require("md5")
var handled = {}
/* usage:
var css = { ... }
var elems = document.querySelector(".my-widget")
elems.forEach(function (elem) {
styleScoped(css, elem)
})
*/
module.exports = styleScoped
function styleScoped(css, elem) {
var id = md5(css);
elem.classList.add(id)
if (handled[id]) {
return
}
handled[id] = true
var cssString = prefixCss("." + id, stringify(css))
var style = document.createElement("style")
style.textContent = cssString
document.head.appendChild(style)
}
function prefixCss(selector, cssString) {
/* prefix every selector in the cssString with the selector */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment