postcss / postcss-nested

PostCSS plugin to unwrap nested rules like how Sass does it.
MIT License
1.16k stars 66 forks source link

Ability to use reference (&) not only in rules #36

Closed komlev closed 8 years ago

komlev commented 8 years ago

I've been playing with postcss for some time and noticed that you can not use pattern which works in sass like this:

@mixin control() {
  $c: &; //GET THE REFERENCE
  &_state {
    &_active {}
    &_hover {}
    &_focus {}
    &_disabled {
      cursor: default !important;
    }
  }
  &:hover:not(#{$c}_state_disabled) {
    @extend #{$c}_state_hover;//USE IT IN DEEP NESTING LIKE THAT
  }
  &:focus:not(#{$c}_state_disabled) {
    @extend #{$c}_state_focus;//USE IT IN DEEP NESTING LIKE THAT
  }
  &:active:not(#{$c}_state_disabled) {
    @extend #{$c}_state_active;//USE IT IN DEEP NESTING LIKE THAT
  }
}

@mixin button() {
  @include control();
  cursor: pointer;
}

//LATER YOU OVERRIDE STATE IN IMPLEMENTATION OF THE MIXIN
.action-button {
  $c: &; //HERE I CAN GET REFERENCE ON CURRENT SELECTOR
  @include button();

  #{$c}_state //AND USER IT ANYTHERE FROM NOW ON
  {
    &_hover {
      background-color: #123;
      border-color: #234;
    }

    &_disabled {
      opacity: 0.5;
      color: #777;
    }

    &_focus {
      @extend #{$c}_state_hover; //IN DEEP NESTING TOO
    }
  }
}

In postcss-nested I can not use reference operator in variables or in at-rules.

ai commented 8 years ago

It is useful thing. But I think replacing & in any declaration is too dangerous.

Maybe you should write a separated plugin postcss-current-selector for this case. It will be much safer and will use power of PostCSS modularity (like UNIX way).

I will add your plugin to postcss-nested docs. Also do not worry about plugin development. This plugin will be very small and I will help you on any question (you can ask here or in Gitter chat).

What do you think about separated plugin?

komlev commented 8 years ago

Sure, good stuff. I'll do that.

komlev commented 8 years ago

Made this simple pugin for getting current selector in declaration https://github.com/komlev/postcss-current-selector

ai commented 8 years ago

@komlev awesome, I mentioned it in docs bf93fe1