cxs-css / cxs

fast af css-in-js in 0.7kb
MIT License
1.19k stars 68 forks source link

Add a custom rules parser #45

Closed lukebrooker closed 7 years ago

lukebrooker commented 7 years ago

For my specific use case, this allows atomic/lite style to add things like prefixing at a lower level. As adding these as a wrapper around CXS creates either multiple class names/rules for a single rule or (in the case of arrays) a broken style.

Examples

Prefixed Keys

import cxs from 'cxs'
import prefixer from 'inline-style-prefixer/static'

const prefixed = prefixer({
  alignItems: 'center'
})
const cx = cxs(prefixed)

In this example cx will equal webkit-box-align-center ms-flex-align-center align-items-center instead of just align-items-center.

Prefixed Values

import cxs from 'cxs'
import prefixer from 'inline-style-prefixer/static'

const prefixed = prefixer({
  display: 'flex'
})
const cx = cxs(prefixed)

In this example the cxs.getCss() would include a broken rule:

._19uyyw8 {
    display: -webkit-box,-moz-box,-ms-flexbox,-webkit-flex,flex;
}

Proposed Solution

My proposed solution is to add to the existing options object and allow adding a custom rule parser at a lower level so prefixes can be added without affecting class names.

The adapted tests in this PR hopefully illustrate how it can be used.

Example

 const prefixRules = ({ selector, key, val }) => {
   const declarations = prefixer({ [key]: val })
   const createRule = (rules, key, value, i) =>
     `${rules}${i > 0 ? ';' : ''}${hyphenate(key)}:${value}`
   const declarationsStr = Object.keys(declarations).reduce((rules, key, i) => {
     const value = declarations[key]
     if (Array.isArray(value)) {
       return value.reduce((acc, val, i) => (
         createRule(acc, key, val, i)
       ), '')
     }
     return createRule(rules, key, val, i)
   }, '')
   return `${selector}{${declarationsStr}}`
 }

cxs.setOptions({ customRuleParser: prefixRules })
souporserious commented 7 years ago

Any status on this? Would love to see this functionality.

jxnblk commented 7 years ago

Thanks for this. Sorry I left this sitting for so long, but closing for now since I think it's fallen out of sync since it was opened