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

report: add PSI.prepareLabData() #5804

Merged
merged 9 commits into from
Aug 8, 2018
Merged
Show file tree
Hide file tree
Changes from 5 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
76 changes: 76 additions & 0 deletions lighthouse-core/report/html/renderer/psi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @license
* Copyright 2018 Google Inc. 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';

/* globals self DOM PerformanceCategoryRenderer Util DetailsRenderer */

class PSI {
/**
* Returns all the elements that PSI needs to render the report
* We expose this helper method to minimize the 'public' API surface of the renderer
* and allow us to refactor without two-sided patches.
*
* const {scoreGaugeEl, perfCategoryEl, finalScreenshotDataUri} = PSI.prepareLabData(
* LHResultJsonString,
* document
* );
*
* @param {string} LHResultJsonString The stringified version of {LH.Result}
* @param {Document} document The host page's window.document
* @return {{scoreGaugeEl: Element, perfCategoryEl: Element, finalScreenshotDataUri: string|null}}
*/
static prepareLabData(LHResultJsonString, document) {
const lhResult = /** @type {LH.Result} */ JSON.parse(LHResultJsonString);
const dom = new DOM(document);

const reportLHR = Util.prepareReportResult(lhResult);
const perfCategory = reportLHR.reportCategories.find(cat => cat.id === 'performance');
if (!perfCategory) throw new Error(`No performance category. Can't make lab data section`);
if (!reportLHR.categoryGroups) throw new Error(`No category groups found.`);

const perfRenderer = new PerformanceCategoryRenderer(dom, new DetailsRenderer(dom));
const perfCategoryEl = perfRenderer.render(perfCategory, reportLHR.categoryGroups);

const scoreGaugeEl = dom.find('.lh-score__gauge', perfCategoryEl);
const scoreGaugeWrapper = dom.find('.lh-gauge__wrapper', scoreGaugeEl);
scoreGaugeWrapper.classList.add('lh-gauge__wrapper--huge');
// Remove Performance category title/description
dom.find('.lh-category-header', perfCategoryEl).remove();
// Remove navigation links
scoreGaugeWrapper.removeAttribute('href');
dom.find('.lh-permalink', perfCategoryEl).remove();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these remove()s are definitely the hackiest bits. Could we do with CSS or have a method for it on CategoryRenderer or something else?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

impl-wise it really comes down to avoiding these two lines, so yah we can easily avoid these .remove's.

  1. option: add extra arg to PerfCatRen.render() that avoids making the permamlink & catHeader elements in the first place. 1 more arg to .render() than the base class, but shrug.
  2. option: just like this._dom.isDevTools() we add a this._dom.isPSI() and drop it into PCR.render().
  3. the CSS solution (display:none) is possible and technically safe for screenreaders, but it feels a tad messy.
  4. what kinda method on CatRen are you thinking of?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

option: just like this._dom.isDevTools() we add a this._dom.isPSI() and drop it into PCR.render().

this has its downsides, but since we have precedent with isDevTools() it seems (to me) like the best option out of these (besides a .isPSI CSS class, but seems like you really don't like that :)

what kinda method on CatRen are you thinking of?

I was hoping if I suggested it vaguely enough you'd assume I meant something in particular and bring that back as a possible solution :)


const finalScreenshotDataUri = PSI.getFinalScreenshot(perfCategory);
return {scoreGaugeEl, perfCategoryEl, finalScreenshotDataUri};
}

/**
* @param {LH.ReportResult.Category} perfCategory
* @return {null|string}
*/
static getFinalScreenshot(perfCategory) {
const auditRef = perfCategory.auditRefs.find(audit => audit.id === 'final-screenshot');
if (!auditRef || !auditRef.result || auditRef.result.scoreDisplayMode === 'error') return null;
return auditRef.result.details.data;
}
}

if (typeof module !== 'undefined' && module.exports) {
module.exports = PSI;
} else {
self.PSI = PSI;
}
12 changes: 0 additions & 12 deletions lighthouse-core/report/html/renderer/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,18 +377,6 @@ class Util {
];
}

/**
* @param {LH.ReportResult} result
* @return {null|string}
*/
static getFinalScreenshot(result) {
const category = result.reportCategories.find(cat => cat.id === 'performance');
if (!category) return null;
const auditRef = category.auditRefs.find(audit => audit.id === 'final-screenshot');
if (!auditRef || !auditRef.result || auditRef.result.scoreDisplayMode === 'error') return null;
return auditRef.result.details.data;
}

/**
* @param {LH.Config.Settings} settings
* @return {{deviceEmulation: string, networkThrottling: string, cpuThrottling: string, summary: string}}
Expand Down
111 changes: 111 additions & 0 deletions lighthouse-core/test/report/html/renderer/psi-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* @license Copyright 2017 Google Inc. 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';

const assert = require('assert');
const fs = require('fs');
const jsdom = require('jsdom');

const PSI = require('../../../../report/html/renderer/psi.js');
const Util = require('../../../../report/html/renderer/util.js');
const DOM = require('../../../../report/html/renderer/dom.js');
const CategoryRenderer = require('../../../../report/html/renderer/category-renderer');
const DetailsRenderer = require('../../../../report/html/renderer/details-renderer');
const CriticalRequestChainRenderer =
require('../../../../report/html/renderer/crc-details-renderer');

const sampleResultsStr = fs.readFileSync(__dirname + '/../../../results/sample_v2.json', 'utf-8');
const sampleResults = JSON.parse(sampleResultsStr)
;
const TEMPLATE_FILE = fs.readFileSync(
__dirname + '/../../../../report/html/templates.html',
'utf8'
);

/* eslint-env jest */

describe('DOM', () => {
let document;
beforeAll(() => {
global.Util = Util;
global.DOM = DOM;
global.CategoryRenderer = CategoryRenderer;
global.DetailsRenderer = DetailsRenderer;

// Delayed so that CategoryRenderer is in global scope
const PerformanceCategoryRenderer =
require('../../../../report/html/renderer/performance-category-renderer');
global.PerformanceCategoryRenderer = PerformanceCategoryRenderer;
global.CriticalRequestChainRenderer = CriticalRequestChainRenderer;

document = jsdom.jsdom(TEMPLATE_FILE);
});

afterAll(() => {
global.Util = undefined;
global.DOM = undefined;
global.CategoryRenderer = undefined;
global.DetailsRenderer = undefined;
global.PerformanceCategoryRenderer = undefined;
global.CriticalRequestChainRenderer = undefined;
});

describe('psi prepareLabData helpers', () => {
describe('prepareLabData', () => {
it('reports expected data', () => {
const result = PSI.prepareLabData(sampleResultsStr, document);
assert.ok(result.scoreGaugeEl instanceof document.defaultView.Element);
assert.ok(result.perfCategoryEl instanceof document.defaultView.Element);
assert.equal(typeof result.finalScreenshotDataUri, 'string');

assert.ok(result.finalScreenshotDataUri.startsWith('data:image/jpeg;base64,'));
assert.ok(result.scoreGaugeEl.outerHTML.includes('<style>'), 'score gauge comes with CSS');
assert.ok(result.scoreGaugeEl.outerHTML.includes('<svg'), 'score gauge comes with SVG');
assert.ok(result.perfCategoryEl.outerHTML.length > 50000, 'perfCategory HTML is populated');
});

it('throws if there is no perf category', () => {
const lhrWithoutPerf = JSON.parse(sampleResultsStr);
delete lhrWithoutPerf.categories.performance;
const lhrWithoutPerfStr = JSON.stringify(lhrWithoutPerf);

assert.throws(() => {
PSI.prepareLabData(lhrWithoutPerfStr, document);
}, /no performance category/i);
});

it('throws if there is no category groups', () => {
const lhrWithoutGroups = JSON.parse(sampleResultsStr);
delete lhrWithoutGroups.categoryGroups;
const lhrWithoutGroupsStr = JSON.stringify(lhrWithoutGroups);

assert.throws(() => {
PSI.prepareLabData(lhrWithoutGroupsStr, document);
}, /no category groups/i);
});
});
});

describe('getFinalScreenshot', () => {
it('gets a datauri as a string', () => {
const cloneResults = Util.prepareReportResult(sampleResults);
const perfCategory = cloneResults.reportCategories.find(cat => cat.id === 'performance');
const datauri = PSI.getFinalScreenshot(perfCategory);
assert.equal(typeof datauri, 'string');
assert.ok(datauri.startsWith('data:image/jpeg;base64,'));
});

it('returns null if there is no final-screenshot audit', () => {
const clonedResults = JSON.parse(JSON.stringify(sampleResults));
delete clonedResults.audits['final-screenshot'];
const lhrNoFinalSS = Util.prepareReportResult(clonedResults);
const perfCategory = lhrNoFinalSS.reportCategories.find(cat => cat.id === 'performance');

const datauri = PSI.getFinalScreenshot(perfCategory);
assert.equal(datauri, null);
});
});
});
29 changes: 0 additions & 29 deletions lighthouse-core/test/report/html/renderer/util-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
const assert = require('assert');
const Util = require('../../../../report/html/renderer/util.js');

const sampleResults = require('../../../results/sample_v2.json');

const NBSP = '\xa0';

/* eslint-env jest */
Expand Down Expand Up @@ -166,31 +164,4 @@ describe('util helpers', () => {
Util.formatDisplayValue(displayValue);
assert.deepStrictEqual(displayValue, cloned, 'displayValue was mutated');
});

describe('getFinalScreenshot', () => {
it('gets a datauri as a string', () => {
const cloneResults = Util.prepareReportResult(sampleResults);
const datauri = Util.getFinalScreenshot(cloneResults);
assert.equal(typeof datauri, 'string');
assert.ok(datauri.startsWith('data:image/jpeg;base64,'));
});

it('returns null if there is no perf category', () => {
const clonedResults = JSON.parse(JSON.stringify(sampleResults));
delete clonedResults.categories.performance;
const lhrWithoutPerf = Util.prepareReportResult(clonedResults);

const datauri = Util.getFinalScreenshot(lhrWithoutPerf);
assert.equal(datauri, null);
});

it('returns null if there is no final-screenshot audit', () => {
const clonedResults = JSON.parse(JSON.stringify(sampleResults));
delete clonedResults.audits['final-screenshot'];
const lhrNoFinalSS = Util.prepareReportResult(clonedResults);

const datauri = Util.getFinalScreenshot(lhrNoFinalSS);
assert.equal(datauri, null);
});
});
});
3 changes: 3 additions & 0 deletions typings/html-renderer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import _PerformanceCategoryRenderer = require('../lighthouse-core/report/html/re
import _ReportRenderer = require('../lighthouse-core/report/html/renderer/report-renderer.js');
import _ReportUIFeatures = require('../lighthouse-core/report/html/renderer/report-ui-features.js');
import _Util = require('../lighthouse-core/report/html/renderer/util.js');
import _PSI = require('../lighthouse-core/report/html/renderer/psi.js');
import _FileNamer = require('../lighthouse-core/lib/file-namer.js');

declare global {
Expand All @@ -24,6 +25,7 @@ declare global {
var ReportRenderer: typeof _ReportRenderer;
var ReportUIFeatures: typeof _ReportUIFeatures;
var Util: typeof _Util;
var PSI: typeof _PSI;

interface Window {
CategoryRenderer: typeof _CategoryRenderer;
Expand All @@ -34,6 +36,7 @@ declare global {
ReportRenderer: typeof _ReportRenderer;
ReportUIFeatures: typeof _ReportUIFeatures;
Util: typeof _Util;
PSI: typeof _PSI;
}

module LH {
Expand Down