Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core(font-size): use order from protocol as implicit specificity #13501

Merged
merged 4 commits into from
Nov 29, 2022
Merged
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
61 changes: 9 additions & 52 deletions core/gather/gatherers/seo/font-size.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,38 +34,6 @@ function hasFontSizeDeclaration(style) {
return !!style && !!style.cssProperties.find(({name}) => name === FONT_SIZE_PROPERTY_NAME);
}

/**
* Computes the CSS specificity of a given selector, i.e. #id > .class > div
* TODO: Handle pseudo selectors (:not(), :where, :nth-child) and attribute selectors
* LIMITATION: !important is not respected
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
* @see https://www.smashingmagazine.com/2010/04/css-specificity-and-inheritance/
* @see https://drafts.csswg.org/selectors-4/#specificity-rules
*
* @param {string} selector
* @return {number}
*/
function computeSelectorSpecificity(selector) {
// Remove universal selector and separator characters, then split.
const tokens = selector.replace(/[*\s+>~]/g, ' ').split(' ');

let numIDs = 0;
let numClasses = 0;
let numTypes = 0;

for (const token of tokens) {
const ids = token.match(/(\b|^)#[a-z0-9_-]+/gi) || [];
const classes = token.match(/(\b|^)\.[a-z0-9_-]+/gi) || [];
const types = token.match(/^[a-z]+/i) ? [1] : [];
numIDs += ids.length;
numClasses += classes.length;
numTypes += types.length;
}

return Math.min(9, numIDs) * 100 + Math.min(9, numClasses) * 10 + Math.min(9, numTypes);
}

/**
* Finds the most specific directly matched CSS font-size rule from the list.
*
Expand All @@ -74,31 +42,21 @@ function computeSelectorSpecificity(selector) {
* @return {NodeFontData['cssRule']|undefined}
*/
function findMostSpecificMatchedCSSRule(matchedCSSRules = [], isDeclarationOfInterest) {
let maxSpecificity = -Infinity;
/** @type {LH.Crdp.CSS.CSSRule|undefined} */
let maxSpecificityRule;

for (const {rule, matchingSelectors} of matchedCSSRules) {
if (isDeclarationOfInterest(rule.style)) {
const specificities = matchingSelectors.map(idx =>
computeSelectorSpecificity(rule.selectorList.selectors[idx].text)
);
const specificity = Math.max(...specificities);
// Use greater OR EQUAL so that the last rule wins in the event of a tie
if (specificity >= maxSpecificity) {
maxSpecificity = specificity;
maxSpecificityRule = rule;
}
let mostSpecificRule;
for (let i = matchedCSSRules.length - 1; i >= 0; i--) {
if (isDeclarationOfInterest(matchedCSSRules[i].rule.style)) {
mostSpecificRule = matchedCSSRules[i].rule;
break;
}
}

if (maxSpecificityRule) {
if (mostSpecificRule) {
return {
type: 'Regular',
...maxSpecificityRule.style,
...mostSpecificRule.style,
parentRule: {
origin: maxSpecificityRule.origin,
selectors: maxSpecificityRule.selectorList.selectors,
origin: mostSpecificRule.origin,
selectors: mostSpecificRule.selectorList.selectors,
},
};
}
Expand Down Expand Up @@ -376,7 +334,6 @@ class FontSize extends FRGatherer {

export default FontSize;
export {
computeSelectorSpecificity,
getEffectiveFontRule,
findMostSpecificMatchedCSSRule,
};
77 changes: 11 additions & 66 deletions core/test/gather/gatherers/seo/font-size-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

import assert from 'assert/strict';

import FontSizeGather, {
computeSelectorSpecificity, getEffectiveFontRule,
} from '../../../../gather/gatherers/seo/font-size.js';
import FontSizeGather, {getEffectiveFontRule} from '../../../../gather/gatherers/seo/font-size.js';

let fontSizeGather;

Expand Down Expand Up @@ -178,59 +176,6 @@ describe('Font size gatherer', () => {
});
});

describe('#computeSelectorSpecificity', () => {
const compute = computeSelectorSpecificity;

it('should handle basic selectors', () => {
expect(compute('h1')).toEqual(1);
expect(compute('h1 > p > span')).toEqual(3);
});

it('should handle class selectors', () => {
expect(compute('h1.foo')).toEqual(11);
expect(compute('.foo')).toEqual(10);
expect(compute('h1 > p.other.yeah > span')).toEqual(23);
});

it('should handle ID selectors', () => {
expect(compute('h1#awesome.foo')).toEqual(111);
expect(compute('#awesome.foo')).toEqual(110);
expect(compute('#awesome')).toEqual(100);
expect(compute('h1 > p.other > span#the-text')).toEqual(113);
});

it('should ignore the univeral selector', () => {
expect(compute('.foo')).toEqual(10);
expect(compute('* .foo')).toEqual(10);
expect(compute('.foo *')).toEqual(10);
});

// Examples https://drafts.csswg.org/selectors-3/#specificity
it('should handle l3 spec selectors', () => {
expect(compute('*')).toEqual(0);
expect(compute('LI')).toEqual(1);
expect(compute('UL LI')).toEqual(2);
expect(compute('UL OL+LI')).toEqual(3);
// expect(compute('H1 + *[REL=up]')).toEqual(11); // TODO: Handle attribute selectors
expect(compute('UL OL LI.red')).toEqual(13);
expect(compute('LI.red.level')).toEqual(21);
expect(compute('#x34y')).toEqual(100);
// expect(compute('#s12:not(FOO)')).toEqual(101); // TODO: Handle pseudo selectors
});

// Examples from https://drafts.csswg.org/selectors-4/#specificity-rules
it('should handle l4 spec selectors', () => {
expect(compute(':is(em, #foo)')).toEqual(100);
// expect(compute('.qux:where(em, #foo#bar#baz)')).toEqual(10); // TODO: Handle pseudo selectors
// expect(compute(':nth-child(even of li, .item)')).toEqual(20); // TODO: Handle pseudo selectors
// expect(compute(':not(em, strong#foo)')).toEqual(101); // TODO: Handle pseudo selectors
});

it('should cap the craziness', () => {
expect(compute('h1.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p')).toEqual(91);
});
});

describe('#getEffectiveFontRule', () => {
const createProps = props => Object.entries(props).map(([name, value]) => ({name, value}));
const createStyle = ({properties, id}) => ({
Expand Down Expand Up @@ -366,29 +311,29 @@ describe('Font size gatherer', () => {
style: createStyle({id: 1, properties: {'font-size': '1em'}}),
});

// Two matching selectors where 2nd is the global most specific, ID + class
// Just ID
const fontRuleB = createRule({
origin: 'regular',
selectors: ['html body *', '#main.foo'],
style: createStyle({id: 2, properties: {'font-size': '2em'}}),
selectors: ['#main'],
style: createStyle({id: 2, properties: {'font-size': '3em'}}),
});

// Just ID
// Two matching selectors where 2nd is the global most specific, ID + class
const fontRuleC = createRule({
origin: 'regular',
selectors: ['#main'],
style: createStyle({id: 3, properties: {'font-size': '3em'}}),
selectors: ['html body *', '#main.foo'],
style: createStyle({id: 3, properties: {'font-size': '2em'}}),
});

const matchedCSSRules = [
{rule: fontRuleA, matchingSelectors: [0]},
{rule: fontRuleB, matchingSelectors: [0, 1]},
{rule: fontRuleC, matchingSelectors: [0]},
{rule: fontRuleB, matchingSelectors: [0]},
{rule: fontRuleC, matchingSelectors: [0, 1]},
];

const result = getEffectiveFontRule({matchedCSSRules});
// fontRuleB should have one for ID + class
expect(result.styleSheetId).toEqual(2);
// fontRuleC should have one for ID + class
expect(result.styleSheetId).toEqual(3);
});

it('should break ties with last one declared', () => {
Expand Down