Skip to content

Commit

Permalink
core(fr): convert css-usage gatherer (#12460)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamraine authored and paulirish committed May 12, 2021
1 parent d7d398b commit 06334e1
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 16 deletions.
3 changes: 3 additions & 0 deletions lighthouse-core/fraggle-rock/config/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const artifacts = {
AppCacheManifest: '',
CacheContents: '',
ConsoleMessages: '',
CSSUsage: '',
Doctype: '',
DOMStats: '',
EmbeddedContent: '',
Expand Down Expand Up @@ -56,6 +57,7 @@ const defaultConfig = {
{id: artifacts.AppCacheManifest, gatherer: 'dobetterweb/appcache'},
{id: artifacts.CacheContents, gatherer: 'cache-contents'},
{id: artifacts.ConsoleMessages, gatherer: 'console-messages'},
{id: artifacts.CSSUsage, gatherer: 'css-usage'},
{id: artifacts.Doctype, gatherer: 'dobetterweb/doctype'},
{id: artifacts.DOMStats, gatherer: 'dobetterweb/domstats'},
{id: artifacts.EmbeddedContent, gatherer: 'seo/embedded-content'},
Expand Down Expand Up @@ -93,6 +95,7 @@ const defaultConfig = {
artifacts.AppCacheManifest,
artifacts.CacheContents,
artifacts.ConsoleMessages,
artifacts.CSSUsage,
artifacts.Doctype,
artifacts.DOMStats,
artifacts.EmbeddedContent,
Expand Down
41 changes: 26 additions & 15 deletions lighthouse-core/gather/gatherers/css-usage.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,46 @@
*/
'use strict';

const Gatherer = require('./gatherer.js');
const FRGatherer = require('../../fraggle-rock/gather/base-gatherer.js');

/**
* @fileoverview Tracks unused CSS rules.
*/
class CSSUsage extends Gatherer {
class CSSUsage extends FRGatherer {
/** @type {LH.Gatherer.GathererMeta} */
meta = {
// TODO(FR-COMPAT): Add support for timespan.
supportedModes: ['snapshot', 'navigation'],
};

/**
* @param {LH.Gatherer.PassContext} passContext
* @param {LH.Gatherer.FRTransitionalContext} context
* @return {Promise<LH.Artifacts['CSSUsage']>}
*/
async afterPass(passContext) {
const driver = passContext.driver;
async getArtifact(context) {
const session = context.driver.defaultSession;
const executionContext = context.driver.executionContext;

/** @type {Array<LH.Crdp.CSS.StyleSheetAddedEvent>} */
const stylesheets = [];
/** @param {LH.Crdp.CSS.StyleSheetAddedEvent} sheet */
const onStylesheetAdded = sheet => stylesheets.push(sheet);
driver.on('CSS.styleSheetAdded', onStylesheetAdded);
session.on('CSS.styleSheetAdded', onStylesheetAdded);

await session.sendCommand('DOM.enable');
await session.sendCommand('CSS.enable');
await session.sendCommand('CSS.startRuleUsageTracking');

// Force style to recompute.
// Doesn't appear to be necessary in newer versions of Chrome.
await executionContext.evaluateAsync('getComputedStyle(document.body)');

await driver.sendCommand('DOM.enable');
await driver.sendCommand('CSS.enable');
await driver.sendCommand('CSS.startRuleUsageTracking');
await driver.executionContext.evaluateAsync('getComputedStyle(document.body)');
driver.off('CSS.styleSheetAdded', onStylesheetAdded);
session.off('CSS.styleSheetAdded', onStylesheetAdded);

// Fetch style sheet content in parallel.
const promises = stylesheets.map(sheet => {
const styleSheetId = sheet.header.styleSheetId;
return driver.sendCommand('CSS.getStyleSheetText', {styleSheetId}).then(content => {
return session.sendCommand('CSS.getStyleSheetText', {styleSheetId}).then(content => {
return {
header: sheet.header,
content: content.text,
Expand All @@ -42,9 +53,9 @@ class CSSUsage extends Gatherer {
});
const styleSheetInfo = await Promise.all(promises);

const ruleUsageResponse = await driver.sendCommand('CSS.stopRuleUsageTracking');
await driver.sendCommand('CSS.disable');
await driver.sendCommand('DOM.disable');
const ruleUsageResponse = await session.sendCommand('CSS.stopRuleUsageTracking');
await session.sendCommand('CSS.disable');
await session.sendCommand('DOM.disable');

const dedupedStylesheets = new Map(styleSheetInfo.map(sheet => {
return [sheet.content, sheet];
Expand Down
112 changes: 112 additions & 0 deletions lighthouse-core/test/gather/gatherers/css-usage-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* @license Copyright 2021 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

/* eslint-env jest */

const CSSUsage = require('../../../gather/gatherers/css-usage.js');
const {createMockDriver} = require('../../fraggle-rock/gather/mock-driver.js');

describe('.getArtifact', () => {
it('gets CSS usage', async () => {
const driver = createMockDriver();
driver.defaultSession.on
.mockEvent('CSS.styleSheetAdded', {header: {styleSheetId: '1'}})
.mockEvent('CSS.styleSheetAdded', {header: {styleSheetId: '2'}});
driver.defaultSession.sendCommand
.mockResponse('DOM.enable')
.mockResponse('CSS.enable', undefined, 1) // Force events to emit
.mockResponse('CSS.startRuleUsageTracking')
.mockResponse('CSS.getStyleSheetText', {text: 'CSS text 1'})
.mockResponse('CSS.getStyleSheetText', {text: 'CSS text 2'})
.mockResponse('CSS.stopRuleUsageTracking', {
ruleUsage: [
{styleSheetId: '1', used: true},
{styleSheetId: '2', used: false},
],
})
.mockResponse('CSS.disable')
.mockResponse('DOM.disable');

/** @type {LH.Gatherer.FRTransitionalContext} */
const context = {
driver: driver.asDriver(),
url: 'https://example.com',
gatherMode: 'snapshot',
dependencies: {},
};
const gatherer = new CSSUsage();
const artifact = await gatherer.getArtifact(context);

expect(artifact).toEqual({
stylesheets: [
{
header: {styleSheetId: '1'},
content: 'CSS text 1',
},
{
header: {styleSheetId: '2'},
content: 'CSS text 2',
},
],
rules: [
{
styleSheetId: '1',
used: true,
},
{
styleSheetId: '2',
used: false,
},
],
});
});

it('dedupes stylesheets', async () => {
const driver = createMockDriver();
driver.defaultSession.on
.mockEvent('CSS.styleSheetAdded', {header: {styleSheetId: '1'}})
.mockEvent('CSS.styleSheetAdded', {header: {styleSheetId: '1'}});
driver.defaultSession.sendCommand
.mockResponse('DOM.enable')
.mockResponse('CSS.enable', undefined, 1) // Force events to emit
.mockResponse('CSS.startRuleUsageTracking')
.mockResponse('CSS.getStyleSheetText', {text: 'CSS text 1'})
.mockResponse('CSS.getStyleSheetText', {text: 'CSS text 1'})
.mockResponse('CSS.stopRuleUsageTracking', {
ruleUsage: [
{styleSheetId: '1', used: true},
],
})
.mockResponse('CSS.disable')
.mockResponse('DOM.disable');

/** @type {LH.Gatherer.FRTransitionalContext} */
const context = {
driver: driver.asDriver(),
url: 'https://example.com',
gatherMode: 'snapshot',
dependencies: {},
};
const gatherer = new CSSUsage();
const artifact = await gatherer.getArtifact(context);

expect(artifact).toEqual({
stylesheets: [
{
header: {styleSheetId: '1'},
content: 'CSS text 1',
},
],
rules: [
{
styleSheetId: '1',
used: true,
},
],
});
});
});
1 change: 0 additions & 1 deletion types/artifacts.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ declare global {
export interface Artifacts extends BaseArtifacts, GathererArtifacts {}

export type FRArtifacts = StrictOmit<Artifacts,
| 'CSSUsage'
| 'Fonts'
| 'FullPageScreenshot'
| 'HTTPRedirect'
Expand Down

0 comments on commit 06334e1

Please sign in to comment.