Skip to content

Commit

Permalink
feat(utils): expose auditTitle and auditDocumentationLink
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickhulce committed Oct 21, 2019
1 parent 6eafeb6 commit 2bb88a6
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 42 deletions.
39 changes: 1 addition & 38 deletions packages/server/src/ui/components/markdown.jsx
Expand Up @@ -5,44 +5,7 @@
*/

import {h, Fragment} from 'preact';

/**
* Split a string on markdown links (e.g. [some link](https://...)) into
* segments of plain text that weren't part of a link (marked as
* `isLink === false`), and segments with text content and a URL that did make
* up a link (marked as `isLink === true`).
* @param {string} text
* @return {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>}
*/
function splitMarkdownLink(text) {
/** @type {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>} */
const segments = [];

const parts = text.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);
while (parts.length) {
// Shift off the same number of elements as the pre-split and capture groups.
const [preambleText, linkText, linkHref] = parts.splice(0, 3);

if (preambleText) {
// Skip empty text as it's an artifact of splitting, not meaningful.
segments.push({
isLink: false,
text: preambleText,
});
}

// Append link if there are any.
if (linkText && linkHref) {
segments.push({
isLink: true,
text: linkText,
linkHref,
});
}
}

return segments;
}
import {splitMarkdownLink} from '@lhci/utils/src/markdown.js';

/** @param {{text: string}} props */
export const Markdown = props => {
Expand Down
26 changes: 22 additions & 4 deletions packages/utils/src/assertions.js
Expand Up @@ -6,6 +6,7 @@
'use strict';

const _ = require('./lodash.js');
const {splitMarkdownLink} = require('./markdown.js');
const {computeRepresentativeRuns} = require('./representative-runs.js');

/** @typedef {keyof StrictOmit<LHCI.AssertCommand.AssertionOptions, 'aggregationMethod'>|'auditRan'} AssertionType */
Expand All @@ -21,6 +22,8 @@ const {computeRepresentativeRuns} = require('./representative-runs.js');
* @property {LHCI.AssertCommand.AssertionFailureLevel} [level]
* @property {string} [auditId]
* @property {string|undefined} [auditProperty]
* @property {string|undefined} [auditTitle]
* @property {string|undefined} [auditDocumentationLink]
*/

/** @typedef {StrictOmit<AssertionResult, 'url'>} AssertionResultNoURL */
Expand Down Expand Up @@ -338,8 +341,16 @@ function resolveAssertionOptionsAndLhrs(baseOptions, unfilteredLhrs) {
const auditsToAssert = [...new Set(Object.keys(assertions).map(_.kebabCase))].map(
assertionKey => {
const [auditId, ...rest] = assertionKey.split('.');
if (!rest.length) return {assertionKey, auditId};
return {assertionKey, auditId, auditProperty: rest};
const auditInstances = lhrs.map(lhr => lhr.audits[auditId]).filter(Boolean);
const failedAudit = auditInstances.find(audit => audit.score !== 1);
const audit = failedAudit || auditInstances[0] || {};
const auditTitle = audit.title;
const auditDocumentationLinkMatches = splitMarkdownLink(audit.description || '')
.map(segment => (segment.isLink ? segment.linkHref : ''))
.filter(link => link.includes('web.dev') || link.includes('developers.google.com/web'));
const [auditDocumentationLink] = auditDocumentationLinkMatches;
if (!rest.length) return {assertionKey, auditId, auditTitle, auditDocumentationLink};
return {assertionKey, auditId, auditTitle, auditDocumentationLink, auditProperty: rest};
}
);

Expand Down Expand Up @@ -374,7 +385,8 @@ function getAllFilteredAssertionResults(baseOptions, unfilteredLhrs) {
/** @type {AssertionResult[]} */
const results = [];

for (const {assertionKey, auditId, auditProperty} of auditsToAssert) {
for (const auditToAssert of auditsToAssert) {
const {assertionKey, auditId, auditProperty} = auditToAssert;
const [level, assertionOptions] = normalizeAssertion(assertions[assertionKey]);
if (level === 'off') continue;

Expand All @@ -390,7 +402,13 @@ function getAllFilteredAssertionResults(baseOptions, unfilteredLhrs) {
);

for (const result of assertionResults) {
results.push({...result, auditId, level, url});
const finalResult = {...result, auditId, level, url};
if (auditToAssert.auditTitle) finalResult.auditTitle = auditToAssert.auditTitle;
if (auditToAssert.auditDocumentationLink) {
finalResult.auditDocumentationLink = auditToAssert.auditDocumentationLink;
}

results.push(finalResult);
}
}

Expand Down
48 changes: 48 additions & 0 deletions packages/utils/src/markdown.js
@@ -0,0 +1,48 @@
/**
* @license Copyright 2019 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';

/**
* @see https://github.com/GoogleChrome/lighthouse/blob/2ff07d29a3e12a75cc844427c567330eb84d4249/lighthouse-core/report/html/renderer/util.js#L320-L347
*
* Split a string on markdown links (e.g. [some link](https://...)) into
* segments of plain text that weren't part of a link (marked as
* `isLink === false`), and segments with text content and a URL that did make
* up a link (marked as `isLink === true`).
* @param {string} text
* @return {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>}
*/
function splitMarkdownLink(text) {
/** @type {Array<{isLink: true, text: string, linkHref: string}|{isLink: false, text: string}>} */
const segments = [];

const parts = text.split(/\[([^\]]+?)\]\((https?:\/\/.*?)\)/g);
while (parts.length) {
// Shift off the same number of elements as the pre-split and capture groups.
const [preambleText, linkText, linkHref] = parts.splice(0, 3);

if (preambleText) {
// Skip empty text as it's an artifact of splitting, not meaningful.
segments.push({
isLink: false,
text: preambleText,
});
}

// Append link if there are any.
if (linkText && linkHref) {
segments.push({
isLink: true,
text: linkText,
linkHref,
});
}
}

return segments;
}

module.exports = {splitMarkdownLink};
50 changes: 50 additions & 0 deletions packages/utils/test/assertions.test.js
Expand Up @@ -186,6 +186,56 @@ describe('getAllAssertionResults', () => {
expect(results).toMatchObject([{actual: 0.8}]);
});

describe('title and documntation', () => {
it('should set auditTitle', () => {
const assertions = {
'first-contentful-paint': ['warn', {aggregationMethod: 'pessimistic'}],
};

// Make sure it pulls from failing audit
lhrs[0].audits['first-contentful-paint'].title = 'Passed';
lhrs[0].audits['first-contentful-paint'].score = 1;
lhrs[1].audits['first-contentful-paint'].title = 'First Contentful Paint';

const results = getAllAssertionResults({assertions}, lhrs);
expect(results).toMatchObject([{auditTitle: 'First Contentful Paint'}]);
});

it('should set auditDocumentationLink', () => {
const assertions = {
'first-contentful-paint': ['warn', {aggregationMethod: 'optimistic'}],
};

lhrs[0].audits['first-contentful-paint'].description = [
'First contentful paint is a really cool [metric](https://example.com/)',
'[Learn More](https://www.web.dev/first-contentful-paint).',
'There are other cool [metrics](https://example.com/) too.',
].join(' ');

const results = getAllAssertionResults({assertions}, lhrs);
expect(results).toMatchObject([
{auditDocumentationLink: 'https://www.web.dev/first-contentful-paint'},
]);
});

it('should not set auditDocumentationLink when no match', () => {
const assertions = {
'first-contentful-paint': ['warn', {aggregationMethod: 'optimistic'}],
};

lhrs[0].audits['first-contentful-paint'].description = [
'First contentful paint is a really cool [metric](https://example.com/)',
'[Learn More](https://non-documentation-link.com/first-contentful-paint).',
'There are other cool [metrics](https://example.com/) too.',
].join(' ');

const results = getAllAssertionResults({assertions}, lhrs);
expect(results).toHaveLength(1);
expect(results[0]).not.toHaveProperty('auditTitle');
expect(results[0]).not.toHaveProperty('auditDocumentationLink');
});
});

describe('aggregationMethod', () => {
it('should default to aggregationMethod optimistic', () => {
const assertions = {
Expand Down

0 comments on commit 2bb88a6

Please sign in to comment.