stylelint icon indicating copy to clipboard operation
stylelint copied to clipboard

Fix `max-nesting-depth` false positives for the `&` selector with `ignoreRules: ["&"]`

Open e-kulikov opened this issue 1 year ago • 5 comments

What is the problem you're trying to solve?

In some cases it's worth using & nesting selector explicitly and as for me it shouldn't increase nesting count in the same logic as pseudo-classes.

The following rules are considered problems with max-nesting-depth: [1, { ignore: ["pseudo-classes"] }]

.button {
  color: green;

  &:hover,
  &:focus {
    color: blue;
  }

  &[disabled] { /* <-- level 1 */
    &, /* <-- nesting selector is considered as level 2 */
    &:hover,
    &:focus {
      color: grey;
    }
  }
}

What solution would you like to see?

Add nesting-selector as an available value for ignore option of the rule:

max-nesting-depth: [1, { ignore: ["pseudo-classes", "nesting-selector"] }]

e-kulikov avatar Jul 22 '24 13:07 e-kulikov

Thank you @e-kulikov for creating this issue.

I think this would be good to somehow support.

I am not sure about the exact implementation as ignore pseudo-classes only ignores rules when each selector is a pseudo class. https://github.com/stylelint/stylelint/tree/main/lib/rules/max-nesting-depth#ignore-pseudo-classes

&, /* not a pseudo class */
&:hover,
&:focus {
  color: grey;
}

So I think it needs to a new option to ignore any & and/or and pseudo classes.

romainmenke avatar Jul 22 '24 13:07 romainmenke

@e-kulikov Thanks for the report. When looking at this quickly, it seems like a bug for ignoreRules: ["&"] option of the max-nesting-depth rule. 🤔 See this demo.

{
  "rules": {
    "max-nesting-depth": [
      1,
      {
        "ignore": ["pseudo-classes"],
        "ignoreRules": ["&"]
      }
    ]
  }
}
a {
  color: red;

  & { color: blue; }

  b {
    color: gray;

    & { color: white; }

    &:hover { color: orange; }

    &, &:hover { color: purple; }
/*  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Expected nesting depth to be no more than 1 */
  }
}

ybiquitous avatar Jul 22 '24 14:07 ybiquitous

ignoreRules's description is

Ignore rules matching with the specified selectors.

Hence I've labeled the issue as ready to implement. Please consider contributing if you have time.

There are steps on how to fix a bug in a rule in the Developer guide.

Mouvedia avatar Jul 23 '24 00:07 Mouvedia

FYI.

https://github.com/stylelint/stylelint/blob/fcd3158268f21e605af6b34cebfb4f88378e5cbe/lib/rules/max-nesting-depth/README.md?plain=1#L418-L420

ybiquitous avatar Jul 25 '24 14:07 ybiquitous

This issue is older than one month. Please ask before opening a pull request, as it may no longer be relevant.

github-actions[bot] avatar Aug 26 '24 00:08 github-actions[bot]