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 8 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
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,20 @@ class PerformanceCategoryRenderer extends CategoryRenderer {
/**
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>} groups
* @param {string=} environment
Copy link
Member

Choose a reason for hiding this comment

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

maybe be specific about what's accepted...I assume 'PSI'= works but that looks weird :)

* @return {Element}
* @override
*/
render(category, groups) {
render(category, groups, environment) {
const element = this.dom.createElement('div', 'lh-category');
this.createPermalinkSpan(element, category.id);
element.appendChild(this.renderCategoryHeader(category));
if (environment === 'PSI') {
const gaugeEl = this.dom.createElement('div', 'lh-score__gauge');
gaugeEl.appendChild(this.renderScoreGauge(category));
element.appendChild(gaugeEl);
} else {
this.createPermalinkSpan(element, category.id);
element.appendChild(this.renderCategoryHeader(category));
}

// Metrics
const metricAudits = category.auditRefs.filter(audit => audit.group === 'metrics');
Expand Down
74 changes: 74 additions & 0 deletions lighthouse-core/report/html/renderer/psi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @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));
// PSI environment string will assure the categoryHeader and permalink elements are excluded
Copy link
Member

Choose a reason for hiding this comment

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

ensure?

const perfCategoryEl = perfRenderer.render(perfCategory, reportLHR.categoryGroups, 'PSI');

const scoreGaugeEl = dom.find('.lh-score__gauge', perfCategoryEl);
const scoreGaugeWrapperEl = dom.find('.lh-gauge__wrapper', scoreGaugeEl);
scoreGaugeWrapperEl.classList.add('lh-gauge__wrapper--huge');
// Remove navigation link on gauge
scoreGaugeWrapperEl.removeAttribute('href');

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
119 changes: 119 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,119 @@
/**
* @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 URL = require('../../../../lib/url-shim');
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.URL = URL; // COMPAT: Needed for Node < 10
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.URL = undefined;
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.equal(result.scoreGaugeEl.querySelector('.lh-gauge__wrapper').href, '');
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 instanceof document.defaultView.Element);
assert.ok(result.perfCategoryEl.outerHTML.length > 50000, 'perfCategory HTML is populated');
assert.ok(!result.perfCategoryEl.outerHTML.includes('lh-permalink'),
'PSI\'s perfCategory HTML doesn\'t include a lh-permalink element');

assert.equal(typeof result.finalScreenshotDataUri, 'string');
assert.ok(result.finalScreenshotDataUri.startsWith('data:image/jpeg;base64,'));
});

it('throws if there is no perf category', () => {
Copy link
Member

Choose a reason for hiding this comment

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

same as above?

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