threepointone / glam

crazy good css in your js
506 stars 19 forks source link

Fragments with nested selectors #30

Open emmatown opened 7 years ago

emmatown commented 7 years ago

Currently if you have a nested selector inside of a fragment it throws.

This is because this

fragment`
  transform: scale(1.5);
  &:hover {
    transform: scale(2);
  }
`

turns into this

fragment('frag-wjjar5', [], function () {
    return ['.frag-wjjar5 { -webkit-transform: scale(1.5); -ms-transform: scale(1.5); transform: scale(1.5); }', '.frag-wjjar5:hover { -webkit-transform: scale(2); -ms-transform: scale(2); transform: scale(2); }'];
  }))

which has two rules and fragment throws if there's more than one rule.

I think this could be solved in two ways.

  1. make fragments insert classes and when they are applied append the class to the string that's returned(I think this would break the cascade?)
  2. split a rule where there's an @apply and make all the fragment selectors & then replace them in css with the selector so e.g.
const frag = fragment`
  &:hover { color: green; }
`
const cls = css`
  color: blue;
  @apply ${frag};
  background-color: green;
`

would turn into

const frag = fragment(/* stuff */); // returns '&:hover { color: green }'
const cls = css('css-hash', [frag], function inlineCss (frag) {
  return [`.css-hash { color: blue; }`, frag, `.css-hash { background-color: green; }`]
})

and it would insert this

.css-hash { color:blue; }
.css-hash:hover { color: green; }
.css-hash { background-color: green; }

I'd be happy to implement this, I just want to know which way would better(I'm guessing the second) or if there's a better way.

threepointone commented 7 years ago

Yeah I couldn't get the parser to work with nested fragments, and specifically disallowed it to push this lib out there. Would be nice to solve. Kye might have some thoughts on this too.