Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 94 additions & 13 deletions src/services/selectorPrinting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ class Specificity {
public tag = 0;
}

function compareSpecificity(a: Specificity, b: Specificity): number {
return (a.id - b.id) || (a.attr - b.attr) || (a.tag - b.tag);
}

export function toElement(node: nodes.SimpleSelector, parentElement?: Element | null): Element {
let result = new Element();
for (const child of node.getChildren()) {
Expand Down Expand Up @@ -388,12 +392,24 @@ export class SelectorPrinting {
return specificity;
};

// the specificity of the nesting selector `&` in the selector that is currently scored
let nestingSelectorSpecificity = new Specificity();

//https://www.w3.org/TR/selectors-3/#specificity
const calculateScore = (node: nodes.Node): Specificity => {
const specificity = new Specificity();

elementLoop: for (const element of node.getChildren()) {
switch (element.type) {
case nodes.NodeType.SelectorCombinator: {
// `&`, LESS allows several in one, e.g. `&-&`
const count = element.getText().split('&').length - 1;
specificity.id += count * nestingSelectorSpecificity.id;
specificity.attr += count * nestingSelectorSpecificity.attr;
specificity.tag += count * nestingSelectorSpecificity.tag;
continue elementLoop;
}

case nodes.NodeType.IdentifierSelector:
specificity.id++;
break;
Expand Down Expand Up @@ -530,7 +546,46 @@ export class SelectorPrinting {
return specificity;
};

const specificity = calculateScore(node);
// A nested rule is relative to its parent rule: the nesting selector `&`, explicit or implied, has the specificity
// of the most specific selector of the parent rule, like `:is()`. https://www.w3.org/TR/css-nesting-1/#nest-selector
const nestedScores = new Map<nodes.Node, Specificity>();
const calculateNestedScore = (node: nodes.Node): Specificity => {
let specificity = nestedScores.get(node);
if (specificity) {
return specificity;
}

const nestingParent = getNestingParent(node);
let mostSpecificParent = new Specificity();
if (nestingParent) {
for (const parentSelector of nestingParent.ruleSet.getSelectors().getChildren()) {
const parentSpecificity = calculateNestedScore(parentSelector);
if (compareSpecificity(parentSpecificity, mostSpecificParent) > 0) {
mostSpecificParent = parentSpecificity;
}
}
}

nestingSelectorSpecificity = mostSpecificParent;
specificity = calculateScore(node);

let hasNestingSelector = false;
node.accept(child => {
hasNestingSelector ||= child.type === nodes.NodeType.SelectorCombinator;
return !hasNestingSelector;
});
if (nestingParent?.implicit && !hasNestingSelector) {
// implied `& ` in front of the selector
specificity.id += mostSpecificParent.id;
specificity.attr += mostSpecificParent.attr;
specificity.tag += mostSpecificParent.tag;
}

nestedScores.set(node, specificity);
return specificity;
};

const specificity = calculateNestedScore(node);
return `[${l10n.t('Selector Specificity')}](https://developer.mozilla.org/docs/Web/CSS/Specificity): (${specificity.id}, ${specificity.attr}, ${specificity.tag})`;
}
}
Expand Down Expand Up @@ -602,26 +657,52 @@ function isNewSelectorContext(node: nodes.Node): boolean {
return false;
}

export function selectorToElement(node: nodes.Selector): Element | null {
if (node.matches('@at-root')) {
return null;
}
const root: Element = new RootElement();
const parentRuleSets: nodes.RuleSet[] = [];
const ruleSet = node.getParent();

function getParentRuleSet(ruleSet: nodes.Node | null): nodes.RuleSet | null {
if (ruleSet instanceof nodes.RuleSet) {
let parent = ruleSet.getParent(); // parent of the selector's ruleset
while (parent && !isNewSelectorContext(parent)) {
if (parent instanceof nodes.RuleSet) {
if (parent.getSelectors().matches('@at-root')) {
break;
}
parentRuleSets.push(<nodes.RuleSet>parent);
return parent.getSelectors().matches('@at-root') ? null : parent;
}
parent = parent.getParent();
}
}
return null;
}

/**
* The rule that `&` refers to in the given selector, and whether the selector is relative to it without an explicit `&`.
*/
function getNestingParent(selector: nodes.Node): { ruleSet: nodes.RuleSet; implicit: boolean } | null {
const ruleSet = selector.getParent();
if (!(ruleSet instanceof nodes.RuleSet)) {
return null;
}
// `@at-root .a, .b` and `@at-root { }` move rules to the root, but an explicit `&` still refers to the parent
let implicit = !ruleSet.getSelectors().getChild(0)?.getText().startsWith('@at-root');
for (let parent = ruleSet.getParent(); parent && !isNewSelectorContext(parent); parent = parent.getParent()) {
if (parent.type === nodes.NodeType.Scope) {
return null; // rules in `@scope` are relative to `:where(:scope)`, which adds nothing
}
if (parent instanceof nodes.RuleSet) {
if (!parent.getSelectors().matches('@at-root')) {
return { ruleSet: parent, implicit };
}
implicit = false;
}
}
return null;
}

export function selectorToElement(node: nodes.Selector): Element | null {
if (node.matches('@at-root')) {
return null;
}
const root: Element = new RootElement();
const parentRuleSets: nodes.RuleSet[] = [];
for (let parent = getParentRuleSet(node.getParent()); parent; parent = getParentRuleSet(parent)) {
parentRuleSets.push(parent);
}

const builder = new SelectorElementBuilder(root);

Expand Down
40 changes: 36 additions & 4 deletions src/test/css/hover.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { suite, test } from 'node:test';
import * as assert from 'node:assert';
import { Hover, TextDocument, getCSSLanguageService, getLESSLanguageService, getSCSSLanguageService } from '../../cssLanguageService.js';
import { Hover, MarkedString, TextDocument, getCSSLanguageService, getLESSLanguageService, getSCSSLanguageService } from '../../cssLanguageService.js';
import { HoverSettings } from '../../cssLanguageTypes.js';
import { BaselineImages } from '../../languageFacts/facts.js';

Expand Down Expand Up @@ -81,7 +81,7 @@ suite('CSS Hover', () => {
assertHover(
'div { d|iv {} }',
{
contents: [{ language: 'html', value: '<div>\n …\n <div>' }, '[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 0, 1)'],
contents: [{ language: 'html', value: '<div>\n …\n <div>' }, '[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 0, 2)'],
},
'css',
);
Expand All @@ -93,7 +93,7 @@ suite('CSS Hover', () => {
language: 'html',
value: '@media only screen\n<element class="foo">\n …\n <element class="bar">\n …\n <element class="bar">',
},
'[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 1, 0)',
'[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 3, 0)',
],
},
'css',
Expand Down Expand Up @@ -121,7 +121,7 @@ suite('CSS Hover', () => {
language: 'html',
value: '@scope .from → .to\n@media print\n@media only screen\n<element class="foo">\n …\n <element class="bar">\n …\n <element class="bar">',
},
'[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 1, 0)',
'[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): (0, 3, 0)',
],
},
'css',
Expand All @@ -130,6 +130,38 @@ suite('CSS Hover', () => {
});

suite('SCSS Hover', () => {
test('nested specificity', () => {
const assertSpecificity = (input: string, specificity: string, languageId = 'scss') => {
const document = TextDocument.create(`test://test/test.${languageId}`, languageId, 0, input.replace('|', ''));
const ls = languageId === 'less' ? getLESSLanguageService() : getSCSSLanguageService();
const hover = ls.doHover(document, document.positionAt(input.indexOf('|')), ls.parseStylesheet(document));
assert.strictEqual((<MarkedString[]>hover!.contents).at(-1), `[Selector Specificity](https://developer.mozilla.org/docs/Web/CSS/Specificity): ${specificity}`, input);
};
assertSpecificity('input { #id { |p { color: red; } } }', '(1, 0, 2)'); // #309
assertSpecificity('input #id |p { color: red; }', '(1, 0, 2)');
assertSpecificity('.a { > .|b {} }', '(0, 2, 0)');
assertSpecificity('.a { &:h|over {} }', '(0, 2, 0)');
assertSpecificity('.a { .b |& {} }', '(0, 2, 0)');
assertSpecificity('.a { & + |& {} }', '(0, 2, 0)'); // each `&` counts
assertSpecificity('.a { &-|b {} }', '(0, 1, 0)'); // suffix, still a single class
assertSpecificity('.a, #b { .|c {} }', '(1, 1, 0)'); // most specific parent selector
assertSpecificity('.a { :where(&) .|b {} }', '(0, 1, 0)'); // `&` follows the rules of the pseudo-class it's in
assertSpecificity('#x { :is(&, .c) .|d {} }', '(1, 1, 0)');
assertSpecificity('#x { .y { @media print { |p {} } } }', '(1, 1, 1)');
assertSpecificity('.a { @at-root { .|b {} } }', '(0, 1, 0)');
assertSpecificity('.a { @at-root (without: media) { .|b {} } }', '(0, 1, 0)');
assertSpecificity('.a { @at-root .|b {} }', '(0, 1, 0)');
assertSpecificity('.a { @at-root .b { .|c {} } }', '(0, 2, 0)');
assertSpecificity('.a { @at-root .b, .|c {} }', '(0, 1, 0)');
assertSpecificity('.a { @at-root .x |& {} }', '(0, 2, 0)'); // an explicit `&` still refers to the parent
assertSpecificity('.a { .b { @at-root .x & { .|c {} } } }', '(0, 4, 0)');
assertSpecificity('.a { @at-root { .b |& {} } }', '(0, 2, 0)');
assertSpecificity('.a { @mixin m { .|b {} } }', '(0, 1, 0)');
assertSpecificity('.a { @scope (.x) { .|b {} } }', '(0, 1, 0)'); // relative to `:where(:scope)`
assertSpecificity('@scope (.x) { .a { .|b {} } }', '(0, 2, 0)');
assertSpecificity('.a { &-|& {} }', '(0, 2, 0)', 'less');
});

test('@at-root', () => {
assertHover(
'.test { @|at-root { }',
Expand Down