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

Add table list formatter for HTML audits #1505

Merged
merged 7 commits into from
Jan 25, 2017
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
17 changes: 14 additions & 3 deletions lighthouse-cli/test/smokehouse/dobetterweb/dbw-expectations.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ module.exports = [
score: false,
extendedInfo: {
value: {
length: 11
results: {
length: 11
}
}
}
},
Expand Down Expand Up @@ -127,12 +129,21 @@ module.exports = [
value: {
// Note: This would normally be 7 but M56 defaults document-level
// listeners to passive. See https://www.chromestatus.com/features/5093566007214080
length: 4
results: {
length: 4
}
}
}
},
'uses-optimized-images': {
score: false
score: false,
extendedInfo: {
value: {
results: {
length: 1
}
}
}
},
'deprecations': {
score: false,
Expand Down
12 changes: 9 additions & 3 deletions lighthouse-core/audits/dobetterweb/uses-http2.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class UsesHTTP2Audit extends Audit {
return sameHost && notH2;
}).map(record => {
return {
label: record.protocol,
protocol: record.protocol,
url: record.url // .url is a getter and not copied over for the assign.
};
});
Expand All @@ -70,12 +70,18 @@ class UsesHTTP2Audit extends Audit {
displayValue = `${resources.length} request was not handled over h2`;
}

const createTable = Formatter.getByName(
Formatter.SUPPORTED_FORMATS.TABLE).createTable;

return UsesHTTP2Audit.generateAuditResult({
rawValue: resources.length === 0,
displayValue: displayValue,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
value: resources
formatter: Formatter.SUPPORTED_FORMATS.TABLE,
value: {
table: createTable({url: 'URL', protocol: 'Protocol'}, resources),
results: resources
}
}
});
}
Expand Down
29 changes: 23 additions & 6 deletions lighthouse-core/audits/dobetterweb/uses-optimized-images.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,21 +89,25 @@ class UsesOptimizedImages extends Audit {
const url = URL.getDisplayName(image.url);
const webpSavings = UsesOptimizedImages.computeSavings(image, 'webp');

let label = `${originalKb} KB total, webp savings: ${webpSavings.percent}%`;
if (webpSavings.bytes > WEBP_ALREADY_OPTIMIZED_THRESHOLD_IN_BYTES) {
hasAllEfficientImages = false;
}

let jpegSavings;
if (/(jpeg|bmp)/.test(image.mimeType)) {
const jpegSavings = UsesOptimizedImages.computeSavings(image, 'jpeg');
jpegSavings = UsesOptimizedImages.computeSavings(image, 'jpeg');
if (jpegSavings.bytes > 0) {
hasAllEfficientImages = false;
label += `, jpeg savings: ${jpegSavings.percent}%`;
}
}

totalWastedBytes += webpSavings.bytes;
results.push({url, label});
results.push({
url,
total: `${originalKb} KB`,
webpSavings: `${webpSavings ? webpSavings.percent + '%' : ''}`,
Copy link
Collaborator

Choose a reason for hiding this comment

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

don't need the check here for webpSavings

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

jpegSavings: `${jpegSavings ? jpegSavings.percent + '%' : ''}`
Copy link
Collaborator

Choose a reason for hiding this comment

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

either add a check for it to be positive here or move jpegSavings = ... inside the if above?

Copy link
Collaborator

Choose a reason for hiding this comment

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

probably also move these out of `` strings :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

});
return results;
}, []);

Expand All @@ -118,13 +122,26 @@ class UsesOptimizedImages extends Audit {
debugString = `Lighthouse was unable to decode some of your images: ${urls.join(', ')}`;
}

const createTable = Formatter.getByName(
Formatter.SUPPORTED_FORMATS.TABLE).createTable;

const table = createTable({
url: 'URL',
total: 'Original (KB)',
webpSavings: 'WebP savings',
jpegSavings: 'JPEG savings'
}, results);

return UsesOptimizedImages.generateAuditResult({
displayValue,
debugString,
rawValue: hasAllEfficientImages && totalWastedBytes < TOTAL_WASTED_BYTES_THRESHOLD,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
value: results
formatter: Formatter.SUPPORTED_FORMATS.TABLE,
value: {
results,
table
}
}
});
}
Expand Down
14 changes: 12 additions & 2 deletions lighthouse-core/audits/dobetterweb/uses-passive-event-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,21 @@ class PassiveEventsAudit extends Audit {

const groupedResults = EventHelpers.groupCodeSnippetsByLocation(results);

const createTable = Formatter.getByName(
Formatter.SUPPORTED_FORMATS.TABLE).createTable;

const table = createTable({
url: 'URL', lineCol: 'Line/Col', type: 'Type', code: 'Snippet'
}, groupedResults);

return PassiveEventsAudit.generateAuditResult({
rawValue: groupedResults.length === 0,
extendedInfo: {
formatter: Formatter.SUPPORTED_FORMATS.URLLIST,
value: groupedResults
formatter: Formatter.SUPPORTED_FORMATS.TABLE,
value: {
results: groupedResults,
Copy link
Collaborator

Choose a reason for hiding this comment

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

no changes needed to the mapping?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

nope. The table formatter will pull from thegroupedResults object as needed, based on the keys used in the first arg to createTable({url: 'URL', lineCol: 'Line/Col', type: 'Type', code: 'Snippet'}).

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ah so the extra info was already in there and was being ignored by URLLIST?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yea.

table
}
},
debugString
});
Expand Down
1 change: 1 addition & 0 deletions lighthouse-core/formatters/formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class Formatter {
urllist: require('./url-list'),
null: require('./null-formatter'),
speedline: require('./speedline-formatter'),
table: require('./table'),
userTimings: require('./user-timings')
};
}
Expand Down
68 changes: 68 additions & 0 deletions lighthouse-core/formatters/partials/table.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<style>
.table_list {
margin-top: 8px;
border: 1px solid #EBEBEB;
Copy link
Collaborator

Choose a reason for hiding this comment

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

do we care about alphabetizing our rules?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There's a PR that alphabetizing selectors was brought up (can't find it now), but we deemed it unrealistic without tooling.

Copy link
Collaborator

Choose a reason for hiding this comment

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

a-ok by me!

max-width: 100%;
}
.table_list th,
.table_list td {
overflow: auto;
}
.table_list th {
background-color: #eee;
padding: 15px 10px;
}
.table_list td {
padding: 10px;
}
.table_list th:first-of-type,
.table_list td:first-of-type {
min-width: 40%;
white-space: nowrap;
}
.table_list tr:nth-child(even) {
background-color: #fafafa;
}
.table_list tr:hover {
background-color: #fafafa;
}
.table_list code {
white-space: pre;
font-family: monospace;
}

.table_list.multicolumn {
display: flex;
flex-direction: column;
}
.table_list.multicolumn tr {
display: flex;
}
.table_list.multicolumn th,
.table_list.multicolumn td {
flex: 1;
}
</style>

{{#if table.rows}}
<details class="subitem__details">
<summary class="subitem__detail">More information</summary>
<table class="table_list {{#if_not_eq table.headings.length 2}}multicolumn{{/if_not_eq}}"
cellspacing="0">
<thead>
<tr>
{{#each table.headings}}<th>{{this}}</th>{{/each}}
</tr>
</thead>
<tbody>
{{#each table.rows}}
<tr>
{{#each cols}}
<td>{{ sanitize this}}</td>
{{/each}}
</tr>
{{/each}}
</tbody>
</table>
</details>
{{/if}}
95 changes: 95 additions & 0 deletions lighthouse-core/formatters/table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* @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 Formatter = require('./formatter');
const path = require('path');
const fs = require('fs');
const html = fs.readFileSync(path.join(__dirname, 'partials/table.html'), 'utf8');

class Table extends Formatter {
static getFormatter(type) {
switch (type) {
case 'pretty':
return result => {
if (!result) {
return '';
}
if (!result.table || !Array.isArray(result.table.headings) ||
!Array.isArray(result.table.rows)) {
return '';
}

let output = '';
result.table.rows.forEach(row => {
output += ' ';
row.cols.forEach(col => {
// Omit code snippet cols.
if (col.startsWith('`') && col.endsWith('`')) {
return;
}
output += `${col} `;
});
output += '\n';
});
return output;
};

case 'html':
// Returns a handlebars string to be used by the Report.
return html;

default:
throw new Error('Unknown formatter type');
}
}

/**
* Preps a formatted table (headings/col vals) for output.
* @param {!Object<string, string>} headings for the table. The order of this
Copy link
Member

Choose a reason for hiding this comment

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

nit: can just do !Object<string> (since all object keys are strings)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

* object's key/value will be the order of the table's headings.
* @param {!Array<*>} results Audit results.
Copy link
Member

Choose a reason for hiding this comment

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

looks like you maybe expect this to be !Array<!Object>?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

* @return {!{headings: string, rows: [{cols: [*]}]}} headings
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: no ! needed, headings is Array<string> isn't it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

thanks. done.

*/
static createTable(headings, results) {
const headingKeys = Object.keys(headings);

const rows = results.map(result => {
const cols = headingKeys.map(key => {
switch (key) {
case 'code':
// Wrap code snippets in markdown ticks.
Copy link
Member

Choose a reason for hiding this comment

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

worth documenting these special keys in jsdoc?

Copy link
Contributor Author

@ebidel ebidel Jan 24, 2017

Choose a reason for hiding this comment

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

done. added to the function description. If we ad more one-offs, that'll be easy to doc more.

return '`' + result[key].trim() + '`';
case 'lineCol':
// Create a combined line/col numbers for the lineCol key.
return `${result.line}:${result.col}`;
default:
return result[key];
}
});

return {cols};
});

headings = headingKeys.map(key => headings[key]);

return {headings, rows};
}
}

module.exports = Table;
4 changes: 2 additions & 2 deletions lighthouse-core/report/report-generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class ReportGenerator {
// !value
Handlebars.registerHelper('not', value => !value);

// value == value2?
// value !== value2
Handlebars.registerHelper('if_not_eq', function(lhs, rhs, options) {
if (lhs !== rhs) {
// eslint-disable-next-line no-invalid-this
Expand Down Expand Up @@ -139,7 +139,7 @@ class ReportGenerator {
// Ignore fatal errors from marked js.
}

// The input str has been santized and transformed. Mark it as safe so
// The input str has been sanitized and transformed. Mark it as safe so
// handlebars renders the text as HTML.
return new Handlebars.SafeString(str);
});
Expand Down
8 changes: 7 additions & 1 deletion lighthouse-core/test/audits/dobetterweb/uses-http2-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ describe('Resources are fetched over http/2', () => {
});
assert.equal(auditResult.rawValue, false);
assert.ok(auditResult.displayValue.match('4 requests were not'));
assert.equal(auditResult.extendedInfo.value.length, 4);
assert.equal(auditResult.extendedInfo.value.results.length, 4);

assert.equal(auditResult.extendedInfo.value.table.headings.length,
auditResult.extendedInfo.value.table.rows[0].cols.length,
'number table headings matches number data columns');
assert.deepEqual(auditResult.extendedInfo.value.table.headings,
['URL', 'Protocol'], 'table headings are correct and in order');
});

it('displayValue is correct when only one resource fails', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ describe('Page uses optimized images', () => {
});

assert.equal(auditResult.rawValue, false);
assert.equal(auditResult.extendedInfo.value.table.headings.length,
auditResult.extendedInfo.value.table.rows[0].cols.length,
'number table headings matches number data columns');
assert.deepEqual(auditResult.extendedInfo.value.table.headings,
['URL', 'Original (KB)', 'WebP savings', 'JPEG savings'],
'table headings are correct and in order');
});

it('fails when one png image is highly unoptimized', () => {
Expand Down Expand Up @@ -103,7 +109,7 @@ describe('Page uses optimized images', () => {
OptimizedImages: [image],
});

const actualUrl = auditResult.extendedInfo.value[0].url;
const actualUrl = auditResult.extendedInfo.value.results[0].url;
assert.ok(actualUrl.length < image.url.length, `${actualUrl} >= ${image.url}`);
});

Expand Down
Loading