js/css.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-08-16 17:17:04 +00:00
const diversify = (prefix, now, ...rest) =>
now
2021-10-19 18:01:10 +00:00
? now.split(/, */g)
.map(current => current.replace(/\$/g, '.'))
.map(current => current[0] == "_"
? diversify(prefix+current.slice(1), ...rest)
: diversify(prefix+' '+current, ...rest)
).join(",")
2021-08-16 17:17:04 +00:00
: prefix
2021-08-16 17:31:52 +00:00
const keyToPropName = key => key.replace(/^[A-Z]/, a => "-"+a).replace(/[A-Z]/g, a => '-'+a.toLowerCase())
2022-02-08 12:14:20 +00:00
const buildValue = value =>
Array.isArray(value)
? value.map(e => Array.isArray(e) ? e.map(e => e.toString()).join(' ') : e.toString()).join(", ")
: value.toString()
const buildRule = (prop, value) => `${keyToPropName(prop)}: ${buildValue(value)}`
2021-08-16 17:17:04 +00:00
const walkStyles = (styles, trail=[], buffer=[]) => {
let inner
const position = buffer.push(undefined)-1
Object.entries(styles).forEach(([name, children]) => {
if (children.constructor.name === "Object") {
trail.push(name)
walkStyles(children, trail, buffer)
trail.pop()
} else {
inner ||= []
2022-02-08 12:14:20 +00:00
inner.push(buildRule(name, children))
2021-08-16 17:17:04 +00:00
}
})
if (inner) buffer[position] = (`${diversify("", ...trail)} {${inner.join("; ")}}`)
return buffer
}
2022-02-08 12:14:20 +00:00
export const style = rules => Object.entries(rules).map(buildRule)
export const css = styles => walkStyles(styles).filter(e=>e).join("\n")
2021-08-16 17:17:04 +00:00
2021-08-18 09:35:54 +00:00
const mkVar = name => {
const v = (def) => `var(--${name}, ${def})`
v.toString = () => `var(--${name})`
return v
}
export const variable = new Proxy(Window, {
get: (target, name, receiver) => mkVar(keyToPropName(name)),
apply: (target, object, [name, value]) => value
? `var(--${name})`
: `var(--${name}, value)`
2021-08-18 09:35:54 +00:00
})