Refactor CSS and add "style" function

This commit is contained in:
Talia 2022-02-08 13:14:20 +01:00
parent 7c6e231d09
commit 5512c955e5
2 changed files with 11 additions and 6 deletions

16
css.js
View file

@ -10,6 +10,13 @@ const diversify = (prefix, now, ...rest) =>
const keyToPropName = key => key.replace(/^[A-Z]/, a => "-"+a).replace(/[A-Z]/g, a => '-'+a.toLowerCase()) const keyToPropName = key => key.replace(/^[A-Z]/, a => "-"+a).replace(/[A-Z]/g, a => '-'+a.toLowerCase())
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)}`
const walkStyles = (styles, trail=[], buffer=[]) => { const walkStyles = (styles, trail=[], buffer=[]) => {
let inner let inner
const position = buffer.push(undefined)-1 const position = buffer.push(undefined)-1
@ -20,17 +27,16 @@ const walkStyles = (styles, trail=[], buffer=[]) => {
trail.pop() trail.pop()
} else { } else {
inner ||= [] inner ||= []
const rules = Array.isArray(children) inner.push(buildRule(name, children))
? children.map(e => Array.isArray(e) ? e.map(e => e.toString()).join(' ') : e.toString()).join(", ")
: children.toString()
inner.push(`${keyToPropName(name)}: ${rules}`)
} }
}) })
if (inner) buffer[position] = (`${diversify("", ...trail)} {${inner.join("; ")}}`) if (inner) buffer[position] = (`${diversify("", ...trail)} {${inner.join("; ")}}`)
return buffer return buffer
} }
export const css = (styles) => walkStyles(styles).filter(e=>e).join("\n") export const style = rules => Object.entries(rules).map(buildRule)
export const css = styles => walkStyles(styles).filter(e=>e).join("\n")
const mkVar = name => { const mkVar = name => {
const v = (def) => `var(--${name}, ${def})` const v = (def) => `var(--${name}, ${def})`

View file

@ -89,7 +89,6 @@ export const bind = transform => {
const update = (...data) => { const update = (...data) => {
const next = transform(...data) const next = transform(...data)
if (next) { if (next) {
console.log(element)
if (element) element.replaceWith(next) if (element) element.replaceWith(next)
element = inject(next) element = inject(next)
return element return element