fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

31
node_modules/lighthouse/report/renderer/api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
/**
* @param {LH.Result} lhr
* @param {LH.Renderer.Options} opts
* @return {HTMLElement}
*/
export function renderReport(lhr: LH.Result, opts?: LH.Renderer.Options): HTMLElement;
/**
* @param {LH.ReportResult.Category} category
* @param {Parameters<CategoryRenderer['renderCategoryScore']>[2]=} options
* @return {DocumentFragment}
*/
export function renderCategoryScore(category: LH.ReportResult.Category, options?: [category: import("../types/report-result.js").default.Category, groupDefinitions: Record<string, import("../../types/lhr/lhr.js").default.ReportGroup>, options?: {
gatherMode: import("../../types/lhr/lhr.js").default.GatherMode;
omitLabel?: boolean | undefined;
onPageAnchorRendered?: ((link: HTMLAnchorElement) => void) | undefined;
} | undefined][2] | undefined): DocumentFragment;
/**
* @param {Blob} blob
* @param {string} filename
*/
export function saveFile(blob: Blob, filename: string): void;
/**
* @param {string} markdownText
* @return {Element}
*/
export function convertMarkdownCodeSnippets(markdownText: string): Element;
/**
* @return {DocumentFragment}
*/
export function createStylesElement(): DocumentFragment;
//# sourceMappingURL=api.d.ts.map

78
node_modules/lighthouse/report/renderer/api.js generated vendored Normal file
View File

@@ -0,0 +1,78 @@
/**
* @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.
*/
import {DOM} from '../renderer/dom.js';
import {ReportRenderer} from '../renderer/report-renderer.js';
import {ReportUIFeatures} from '../renderer/report-ui-features.js';
import {CategoryRenderer} from './category-renderer.js';
import {DetailsRenderer} from './details-renderer.js';
/**
* @param {LH.Result} lhr
* @param {LH.Renderer.Options} opts
* @return {HTMLElement}
*/
function renderReport(lhr, opts = {}) {
const rootEl = document.createElement('article');
rootEl.classList.add('lh-root', 'lh-vars');
const dom = new DOM(rootEl.ownerDocument, rootEl);
const renderer = new ReportRenderer(dom);
renderer.renderReport(lhr, rootEl, opts);
// Hook in JS features and page-level event listeners after the report
// is in the document.
const features = new ReportUIFeatures(dom, opts);
features.initFeatures(lhr);
return rootEl;
}
/**
* @param {LH.ReportResult.Category} category
* @param {Parameters<CategoryRenderer['renderCategoryScore']>[2]=} options
* @return {DocumentFragment}
*/
function renderCategoryScore(category, options) {
const dom = new DOM(document, document.documentElement);
const detailsRenderer = new DetailsRenderer(dom);
const categoryRenderer = new CategoryRenderer(dom, detailsRenderer);
return categoryRenderer.renderCategoryScore(category, {}, options);
}
/**
* @param {Blob} blob
* @param {string} filename
*/
function saveFile(blob, filename) {
const dom = new DOM(document, document.documentElement);
dom.saveFile(blob, filename);
}
/**
* @param {string} markdownText
* @return {Element}
*/
function convertMarkdownCodeSnippets(markdownText) {
const dom = new DOM(document, document.documentElement);
return dom.convertMarkdownCodeSnippets(markdownText);
}
/**
* @return {DocumentFragment}
*/
function createStylesElement() {
const dom = new DOM(document, document.documentElement);
return dom.createComponent('styles');
}
export {
renderReport,
renderCategoryScore,
saveFile,
convertMarkdownCodeSnippets,
createStylesElement,
};

View File

@@ -0,0 +1,176 @@
export class CategoryRenderer {
/**
* @param {DOM} dom
* @param {DetailsRenderer} detailsRenderer
*/
constructor(dom: DOM, detailsRenderer: DetailsRenderer);
/** @type {DOM} */
dom: DOM;
/** @type {DetailsRenderer} */
detailsRenderer: DetailsRenderer;
/**
* Display info per top-level clump. Define on class to avoid race with Util init.
*/
get _clumpTitles(): {
warning: string;
manual: string;
passed: string;
notApplicable: string;
};
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {Element}
*/
renderAudit(audit: LH.ReportResult.AuditRef): Element;
/**
* Populate an DOM tree with audit details. Used by renderAudit and renderOpportunity
* @param {LH.ReportResult.AuditRef} audit
* @param {DocumentFragment} component
* @return {!Element}
*/
populateAuditValues(audit: LH.ReportResult.AuditRef, component: DocumentFragment): Element;
/**
* Inject the final screenshot next to the score gauge of the first category (likely Performance)
* @param {HTMLElement} categoriesEl
* @param {LH.ReportResult['audits']} audits
* @param {Element} scoreScaleEl
*/
injectFinalScreenshot(categoriesEl: HTMLElement, audits: LH.ReportResult['audits'], scoreScaleEl: Element): null | undefined;
/**
* @return {Element}
*/
_createChevron(): Element;
/**
* @param {Element} element DOM node to populate with values.
* @param {number|null} score
* @param {string} scoreDisplayMode
* @return {!Element}
*/
_setRatingClass(element: Element, score: number | null, scoreDisplayMode: string): Element;
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {DocumentFragment}
*/
renderCategoryHeader(category: LH.ReportResult.Category, groupDefinitions: Record<string, LH.Result.ReportGroup>, options?: {
gatherMode: LH.Result.GatherMode;
} | undefined): DocumentFragment;
/**
* Renders the group container for a group of audits. Individual audit elements can be added
* directly to the returned element.
* @param {LH.Result.ReportGroup} group
* @return {[Element, Element | null]}
*/
renderAuditGroup(group: LH.Result.ReportGroup): [Element, Element | null];
/**
* Takes an array of auditRefs, groups them if requested, then returns an
* array of audit and audit-group elements.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Array<Element>}
*/
_renderGroupedAudits(auditRefs: Array<LH.ReportResult.AuditRef>, groupDefinitions: {
[x: string]: LH.Result.ReportGroup;
}): Array<Element>;
/**
* Take a set of audits, group them if they have groups, then render in a top-level
* clump that can't be expanded/collapsed.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Element}
*/
renderUnexpandableClump(auditRefs: Array<LH.ReportResult.AuditRef>, groupDefinitions: {
[x: string]: LH.Result.ReportGroup;
}): Element;
/**
* Take a set of audits and render in a top-level, expandable clump that starts
* in a collapsed state.
* @param {Exclude<TopLevelClumpId, 'failed'>} clumpId
* @param {{auditRefs: Array<LH.ReportResult.AuditRef>, description?: string}} clumpOpts
* @return {!Element}
*/
renderClump(clumpId: Exclude<TopLevelClumpId, 'failed'>, { auditRefs, description }: {
auditRefs: Array<LH.ReportResult.AuditRef>;
description?: string;
}): Element;
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode, omitLabel?: boolean, onPageAnchorRendered?: (link: HTMLAnchorElement) => void}=} options
* @return {DocumentFragment}
*/
renderCategoryScore(category: LH.ReportResult.Category, groupDefinitions: Record<string, LH.Result.ReportGroup>, options?: {
gatherMode: LH.Result.GatherMode;
omitLabel?: boolean | undefined;
onPageAnchorRendered?: ((link: HTMLAnchorElement) => void) | undefined;
} | undefined): DocumentFragment;
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {DocumentFragment}
*/
renderScoreGauge(category: LH.ReportResult.Category, groupDefinitions: Record<string, LH.Result.ReportGroup>): DocumentFragment;
/**
* @param {LH.ReportResult.Category} category
* @return {DocumentFragment}
*/
renderCategoryFraction(category: LH.ReportResult.Category): DocumentFragment;
/**
* Returns true if an LH category has any non-"notApplicable" audits.
* @param {LH.ReportResult.Category} category
* @return {boolean}
*/
hasApplicableAudits(category: LH.ReportResult.Category): boolean;
/**
* Define the score arc of the gauge
* Credit to xgad for the original technique: https://codepen.io/xgad/post/svg-radial-progress-meters
* @param {SVGCircleElement} arcElem
* @param {number} percent
*/
_setGaugeArc(arcElem: SVGCircleElement, percent: number): void;
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {boolean}
*/
_auditHasWarning(audit: LH.ReportResult.AuditRef): boolean;
/**
* Returns the id of the top-level clump to put this audit in.
* @param {LH.ReportResult.AuditRef} auditRef
* @return {TopLevelClumpId}
*/
_getClumpIdForAuditRef(auditRef: LH.ReportResult.AuditRef): TopLevelClumpId;
/**
* Renders a set of top level sections (clumps), under a status of failed, warning,
* manual, passed, or notApplicable. The result ends up something like:
*
* failed clump
* ├── audit 1 (w/o group)
* ├── audit 2 (w/o group)
* ├── audit group
* | ├── audit 3
* | └── audit 4
* └── audit group
* ├── audit 5
* └── audit 6
* other clump (e.g. 'manual')
* ├── audit 1
* ├── audit 2
* ├── …
* ⋮
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>=} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {Element}
*/
render(category: LH.ReportResult.Category, groupDefinitions?: {
[x: string]: LH.Result.ReportGroup;
} | undefined, options?: {
gatherMode: LH.Result.GatherMode;
} | undefined): Element;
}
export type DOM = import('./dom.js').DOM;
export type ReportRenderer = import('./report-renderer.js').ReportRenderer;
export type DetailsRenderer = import('./details-renderer.js').DetailsRenderer;
export type TopLevelClumpId = 'failed' | 'warning' | 'manual' | 'passed' | 'notApplicable';
//# sourceMappingURL=category-renderer.d.ts.map

View File

@@ -0,0 +1,580 @@
/**
* @license
* Copyright 2017 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.
*/
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./report-renderer.js').ReportRenderer} ReportRenderer */
/** @typedef {import('./details-renderer.js').DetailsRenderer} DetailsRenderer */
/** @typedef {'failed'|'warning'|'manual'|'passed'|'notApplicable'} TopLevelClumpId */
import {ReportUtils} from './report-utils.js';
import {Globals} from './report-globals.js';
export class CategoryRenderer {
/**
* @param {DOM} dom
* @param {DetailsRenderer} detailsRenderer
*/
constructor(dom, detailsRenderer) {
/** @type {DOM} */
this.dom = dom;
/** @type {DetailsRenderer} */
this.detailsRenderer = detailsRenderer;
}
/**
* Display info per top-level clump. Define on class to avoid race with Util init.
*/
get _clumpTitles() {
return {
warning: Globals.strings.warningAuditsGroupTitle,
manual: Globals.strings.manualAuditsGroupTitle,
passed: Globals.strings.passedAuditsGroupTitle,
notApplicable: Globals.strings.notApplicableAuditsGroupTitle,
};
}
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {Element}
*/
renderAudit(audit) {
const component = this.dom.createComponent('audit');
return this.populateAuditValues(audit, component);
}
/**
* Populate an DOM tree with audit details. Used by renderAudit and renderOpportunity
* @param {LH.ReportResult.AuditRef} audit
* @param {DocumentFragment} component
* @return {!Element}
*/
populateAuditValues(audit, component) {
const strings = Globals.strings;
const auditEl = this.dom.find('.lh-audit', component);
auditEl.id = audit.result.id;
const scoreDisplayMode = audit.result.scoreDisplayMode;
if (audit.result.displayValue) {
this.dom.find('.lh-audit__display-text', auditEl).textContent = audit.result.displayValue;
}
const titleEl = this.dom.find('.lh-audit__title', auditEl);
titleEl.append(this.dom.convertMarkdownCodeSnippets(audit.result.title));
const descEl = this.dom.find('.lh-audit__description', auditEl);
descEl.append(this.dom.convertMarkdownLinkSnippets(audit.result.description));
for (const relevantMetric of audit.relevantMetrics || []) {
const adornEl = this.dom.createChildOf(descEl, 'span', 'lh-audit__adorn');
adornEl.title = `Relevant to ${relevantMetric.result.title}`;
adornEl.textContent = relevantMetric.acronym || relevantMetric.id;
}
if (audit.stackPacks) {
audit.stackPacks.forEach(pack => {
const packElmImg = this.dom.createElement('img', 'lh-audit__stackpack__img');
packElmImg.src = pack.iconDataURL;
packElmImg.alt = pack.title;
const snippets = this.dom.convertMarkdownLinkSnippets(pack.description, {
alwaysAppendUtmSource: true,
});
const packElm = this.dom.createElement('div', 'lh-audit__stackpack');
packElm.append(packElmImg, snippets);
this.dom.find('.lh-audit__stackpacks', auditEl)
.append(packElm);
});
}
const header = this.dom.find('details', auditEl);
if (audit.result.details) {
const elem = this.detailsRenderer.render(audit.result.details);
if (elem) {
elem.classList.add('lh-details');
header.append(elem);
}
}
// Add chevron SVG to the end of the summary
this.dom.find('.lh-chevron-container', auditEl).append(this._createChevron());
this._setRatingClass(auditEl, audit.result.score, scoreDisplayMode);
if (audit.result.scoreDisplayMode === 'error') {
auditEl.classList.add(`lh-audit--error`);
const textEl = this.dom.find('.lh-audit__display-text', auditEl);
textEl.textContent = strings.errorLabel;
textEl.classList.add('lh-tooltip-boundary');
const tooltip = this.dom.createChildOf(textEl, 'div', 'lh-tooltip lh-tooltip--error');
tooltip.textContent = audit.result.errorMessage || strings.errorMissingAuditInfo;
} else if (audit.result.explanation) {
const explEl = this.dom.createChildOf(titleEl, 'div', 'lh-audit-explanation');
explEl.textContent = audit.result.explanation;
}
const warnings = audit.result.warnings;
if (!warnings || warnings.length === 0) return auditEl;
// Add list of warnings or singular warning
const summaryEl = this.dom.find('summary', header);
const warningsEl = this.dom.createChildOf(summaryEl, 'div', 'lh-warnings');
this.dom.createChildOf(warningsEl, 'span').textContent = strings.warningHeader;
if (warnings.length === 1) {
warningsEl.append(this.dom.createTextNode(warnings.join('')));
} else {
const warningsUl = this.dom.createChildOf(warningsEl, 'ul');
for (const warning of warnings) {
const item = this.dom.createChildOf(warningsUl, 'li');
item.textContent = warning;
}
}
return auditEl;
}
/**
* Inject the final screenshot next to the score gauge of the first category (likely Performance)
* @param {HTMLElement} categoriesEl
* @param {LH.ReportResult['audits']} audits
* @param {Element} scoreScaleEl
*/
injectFinalScreenshot(categoriesEl, audits, scoreScaleEl) {
const audit = audits['final-screenshot'];
if (!audit || audit.scoreDisplayMode === 'error') return null;
if (!audit.details || audit.details.type !== 'screenshot') return null;
const imgEl = this.dom.createElement('img', 'lh-final-ss-image');
const finalScreenshotDataUri = audit.details.data;
imgEl.src = finalScreenshotDataUri;
imgEl.alt = audit.title;
const firstCatHeaderEl = this.dom.find('.lh-category .lh-category-header', categoriesEl);
const leftColEl = this.dom.createElement('div', 'lh-category-headercol');
const separatorEl = this.dom.createElement('div',
'lh-category-headercol lh-category-headercol--separator');
const rightColEl = this.dom.createElement('div', 'lh-category-headercol');
leftColEl.append(...firstCatHeaderEl.childNodes);
leftColEl.append(scoreScaleEl);
rightColEl.append(imgEl);
firstCatHeaderEl.append(leftColEl, separatorEl, rightColEl);
firstCatHeaderEl.classList.add('lh-category-header__finalscreenshot');
}
/**
* @return {Element}
*/
_createChevron() {
const component = this.dom.createComponent('chevron');
const chevronEl = this.dom.find('svg.lh-chevron', component);
return chevronEl;
}
/**
* @param {Element} element DOM node to populate with values.
* @param {number|null} score
* @param {string} scoreDisplayMode
* @return {!Element}
*/
_setRatingClass(element, score, scoreDisplayMode) {
const rating = ReportUtils.calculateRating(score, scoreDisplayMode);
element.classList.add(`lh-audit--${scoreDisplayMode.toLowerCase()}`);
if (scoreDisplayMode !== 'informative') {
element.classList.add(`lh-audit--${rating}`);
}
return element;
}
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {DocumentFragment}
*/
renderCategoryHeader(category, groupDefinitions, options) {
const component = this.dom.createComponent('categoryHeader');
const gaugeContainerEl = this.dom.find('.lh-score__gauge', component);
const gaugeEl = this.renderCategoryScore(category, groupDefinitions, options);
gaugeContainerEl.append(gaugeEl);
if (category.description) {
const descEl = this.dom.convertMarkdownLinkSnippets(category.description);
this.dom.find('.lh-category-header__description', component).append(descEl);
}
return component;
}
/**
* Renders the group container for a group of audits. Individual audit elements can be added
* directly to the returned element.
* @param {LH.Result.ReportGroup} group
* @return {[Element, Element | null]}
*/
renderAuditGroup(group) {
const groupEl = this.dom.createElement('div', 'lh-audit-group');
const auditGroupHeader = this.dom.createElement('div', 'lh-audit-group__header');
this.dom.createChildOf(auditGroupHeader, 'span', 'lh-audit-group__title')
.textContent = group.title;
groupEl.append(auditGroupHeader);
let footerEl = null;
if (group.description) {
footerEl = this.dom.convertMarkdownLinkSnippets(group.description);
footerEl.classList.add('lh-audit-group__description', 'lh-audit-group__footer');
groupEl.append(footerEl);
}
return [groupEl, footerEl];
}
/**
* Takes an array of auditRefs, groups them if requested, then returns an
* array of audit and audit-group elements.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Array<Element>}
*/
_renderGroupedAudits(auditRefs, groupDefinitions) {
// Audits grouped by their group (or under notAGroup).
/** @type {Map<string, Array<LH.ReportResult.AuditRef>>} */
const grouped = new Map();
// Add audits without a group first so they will appear first.
const notAGroup = 'NotAGroup';
grouped.set(notAGroup, []);
for (const auditRef of auditRefs) {
const groupId = auditRef.group || notAGroup;
if (groupId === 'hidden') continue;
const groupAuditRefs = grouped.get(groupId) || [];
groupAuditRefs.push(auditRef);
grouped.set(groupId, groupAuditRefs);
}
/** @type {Array<Element>} */
const auditElements = [];
for (const [groupId, groupAuditRefs] of grouped) {
if (groupId === notAGroup) {
// Push not-grouped audits individually.
for (const auditRef of groupAuditRefs) {
auditElements.push(this.renderAudit(auditRef));
}
continue;
}
// Push grouped audits as a group.
const groupDef = groupDefinitions[groupId];
const [auditGroupElem, auditGroupFooterEl] = this.renderAuditGroup(groupDef);
for (const auditRef of groupAuditRefs) {
auditGroupElem.insertBefore(this.renderAudit(auditRef), auditGroupFooterEl);
}
auditGroupElem.classList.add(`lh-audit-group--${groupId}`);
auditElements.push(auditGroupElem);
}
return auditElements;
}
/**
* Take a set of audits, group them if they have groups, then render in a top-level
* clump that can't be expanded/collapsed.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Element}
*/
renderUnexpandableClump(auditRefs, groupDefinitions) {
const clumpElement = this.dom.createElement('div');
const elements = this._renderGroupedAudits(auditRefs, groupDefinitions);
elements.forEach(elem => clumpElement.append(elem));
return clumpElement;
}
/**
* Take a set of audits and render in a top-level, expandable clump that starts
* in a collapsed state.
* @param {Exclude<TopLevelClumpId, 'failed'>} clumpId
* @param {{auditRefs: Array<LH.ReportResult.AuditRef>, description?: string}} clumpOpts
* @return {!Element}
*/
renderClump(clumpId, {auditRefs, description}) {
const clumpComponent = this.dom.createComponent('clump');
const clumpElement = this.dom.find('.lh-clump', clumpComponent);
if (clumpId === 'warning') {
clumpElement.setAttribute('open', '');
}
const headerEl = this.dom.find('.lh-audit-group__header', clumpElement);
const title = this._clumpTitles[clumpId];
this.dom.find('.lh-audit-group__title', headerEl).textContent = title;
const itemCountEl = this.dom.find('.lh-audit-group__itemcount', clumpElement);
itemCountEl.textContent = `(${auditRefs.length})`;
// Add all audit results to the clump.
const auditElements = auditRefs.map(this.renderAudit.bind(this));
clumpElement.append(...auditElements);
const el = this.dom.find('.lh-audit-group', clumpComponent);
if (description) {
const descriptionEl = this.dom.convertMarkdownLinkSnippets(description);
descriptionEl.classList.add('lh-audit-group__description', 'lh-audit-group__footer');
el.append(descriptionEl);
}
this.dom.find('.lh-clump-toggletext--show', el).textContent = Globals.strings.show;
this.dom.find('.lh-clump-toggletext--hide', el).textContent = Globals.strings.hide;
clumpElement.classList.add(`lh-clump--${clumpId.toLowerCase()}`);
return el;
}
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode, omitLabel?: boolean, onPageAnchorRendered?: (link: HTMLAnchorElement) => void}=} options
* @return {DocumentFragment}
*/
renderCategoryScore(category, groupDefinitions, options) {
let categoryScore;
if (options && ReportUtils.shouldDisplayAsFraction(options.gatherMode)) {
categoryScore = this.renderCategoryFraction(category);
} else {
categoryScore = this.renderScoreGauge(category, groupDefinitions);
}
if (options?.omitLabel) {
const label = this.dom.find('.lh-gauge__label,.lh-fraction__label', categoryScore);
label.remove();
}
if (options?.onPageAnchorRendered) {
const anchor = this.dom.find('a', categoryScore);
options.onPageAnchorRendered(anchor);
}
return categoryScore;
}
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {DocumentFragment}
*/
renderScoreGauge(category, groupDefinitions) { // eslint-disable-line no-unused-vars
const tmpl = this.dom.createComponent('gauge');
const wrapper = this.dom.find('a.lh-gauge__wrapper', tmpl);
if (ReportUtils.isPluginCategory(category.id)) {
wrapper.classList.add('lh-gauge__wrapper--plugin');
}
// Cast `null` to 0
const numericScore = Number(category.score);
const gauge = this.dom.find('.lh-gauge', tmpl);
const gaugeArc = this.dom.find('circle.lh-gauge-arc', gauge);
if (gaugeArc) this._setGaugeArc(gaugeArc, numericScore);
const scoreOutOf100 = Math.round(numericScore * 100);
const percentageEl = this.dom.find('div.lh-gauge__percentage', tmpl);
percentageEl.textContent = scoreOutOf100.toString();
if (category.score === null) {
percentageEl.classList.add('lh-gauge--error');
percentageEl.textContent = '';
percentageEl.title = Globals.strings.errorLabel;
}
// Render a numerical score if the category has applicable audits, or no audits whatsoever.
if (category.auditRefs.length === 0 || this.hasApplicableAudits(category)) {
wrapper.classList.add(`lh-gauge__wrapper--${ReportUtils.calculateRating(category.score)}`);
} else {
wrapper.classList.add(`lh-gauge__wrapper--not-applicable`);
percentageEl.textContent = '-';
percentageEl.title = Globals.strings.notApplicableAuditsGroupTitle;
}
this.dom.find('.lh-gauge__label', tmpl).textContent = category.title;
return tmpl;
}
/**
* @param {LH.ReportResult.Category} category
* @return {DocumentFragment}
*/
renderCategoryFraction(category) {
const tmpl = this.dom.createComponent('fraction');
const wrapper = this.dom.find('a.lh-fraction__wrapper', tmpl);
const {numPassed, numPassableAudits, totalWeight} =
ReportUtils.calculateCategoryFraction(category);
const fraction = numPassed / numPassableAudits;
const content = this.dom.find('.lh-fraction__content', tmpl);
const text = this.dom.createElement('span');
text.textContent = `${numPassed}/${numPassableAudits}`;
content.append(text);
let rating = ReportUtils.calculateRating(fraction);
// If none of the available audits can affect the score, a rating isn't useful.
// The flow report should display the fraction with neutral icon and coloring in this case.
if (totalWeight === 0) {
rating = 'null';
}
wrapper.classList.add(`lh-fraction__wrapper--${rating}`);
this.dom.find('.lh-fraction__label', tmpl).textContent = category.title;
return tmpl;
}
/**
* Returns true if an LH category has any non-"notApplicable" audits.
* @param {LH.ReportResult.Category} category
* @return {boolean}
*/
hasApplicableAudits(category) {
return category.auditRefs.some(ref => ref.result.scoreDisplayMode !== 'notApplicable');
}
/**
* Define the score arc of the gauge
* Credit to xgad for the original technique: https://codepen.io/xgad/post/svg-radial-progress-meters
* @param {SVGCircleElement} arcElem
* @param {number} percent
*/
_setGaugeArc(arcElem, percent) {
const circumferencePx = 2 * Math.PI * Number(arcElem.getAttribute('r'));
// The rounded linecap of the stroke extends the arc past its start and end.
// First, we tweak the -90deg rotation to start exactly at the top of the circle.
const strokeWidthPx = Number(arcElem.getAttribute('stroke-width'));
const rotationalAdjustmentPercent = 0.25 * strokeWidthPx / circumferencePx;
arcElem.style.transform = `rotate(${-90 + rotationalAdjustmentPercent * 360}deg)`;
// Then, we terminate the line a little early as well.
let arcLengthPx = percent * circumferencePx - strokeWidthPx / 2;
// Special cases. No dot for 0, and full ring if 100
if (percent === 0) arcElem.style.opacity = '0';
if (percent === 1) arcLengthPx = circumferencePx;
arcElem.style.strokeDasharray = `${Math.max(arcLengthPx, 0)} ${circumferencePx}`;
}
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {boolean}
*/
_auditHasWarning(audit) {
return Boolean(audit.result.warnings?.length);
}
/**
* Returns the id of the top-level clump to put this audit in.
* @param {LH.ReportResult.AuditRef} auditRef
* @return {TopLevelClumpId}
*/
_getClumpIdForAuditRef(auditRef) {
const scoreDisplayMode = auditRef.result.scoreDisplayMode;
if (scoreDisplayMode === 'manual' || scoreDisplayMode === 'notApplicable') {
return scoreDisplayMode;
}
if (ReportUtils.showAsPassed(auditRef.result)) {
if (this._auditHasWarning(auditRef)) {
return 'warning';
} else {
return 'passed';
}
} else {
return 'failed';
}
}
/**
* Renders a set of top level sections (clumps), under a status of failed, warning,
* manual, passed, or notApplicable. The result ends up something like:
*
* failed clump
* ├── audit 1 (w/o group)
* ├── audit 2 (w/o group)
* ├── audit group
* | ├── audit 3
* | └── audit 4
* └── audit group
* ├── audit 5
* └── audit 6
* other clump (e.g. 'manual')
* ├── audit 1
* ├── audit 2
* ├── …
* ⋮
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>=} groupDefinitions
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {Element}
*/
render(category, groupDefinitions = {}, options) {
const element = this.dom.createElement('div', 'lh-category');
element.id = category.id;
element.append(this.renderCategoryHeader(category, groupDefinitions, options));
// Top level clumps for audits, in order they will appear in the report.
/** @type {Map<TopLevelClumpId, Array<LH.ReportResult.AuditRef>>} */
const clumps = new Map();
clumps.set('failed', []);
clumps.set('warning', []);
clumps.set('manual', []);
clumps.set('passed', []);
clumps.set('notApplicable', []);
// Sort audits into clumps.
for (const auditRef of category.auditRefs) {
const clumpId = this._getClumpIdForAuditRef(auditRef);
const clump = /** @type {Array<LH.ReportResult.AuditRef>} */ (clumps.get(clumpId)); // already defined
clump.push(auditRef);
clumps.set(clumpId, clump);
}
// Sort audits by weight.
for (const auditRefs of clumps.values()) {
auditRefs.sort((a, b) => {
return b.weight - a.weight;
});
}
// Render each clump.
for (const [clumpId, auditRefs] of clumps) {
if (auditRefs.length === 0) continue;
if (clumpId === 'failed') {
const clumpElem = this.renderUnexpandableClump(auditRefs, groupDefinitions);
clumpElem.classList.add(`lh-clump--failed`);
element.append(clumpElem);
continue;
}
const description = clumpId === 'manual' ? category.manualDescription : undefined;
const clumpElem = this.renderClump(clumpId, {auditRefs, description});
element.append(clumpElem);
}
return element;
}
}

View File

@@ -0,0 +1,10 @@
/** @typedef {'3pFilter'|'audit'|'categoryHeader'|'chevron'|'clump'|'crc'|'crcChain'|'elementScreenshot'|'footer'|'fraction'|'gauge'|'gaugePwa'|'heading'|'metric'|'opportunity'|'opportunityHeader'|'scorescale'|'scoresWrapper'|'snippet'|'snippetContent'|'snippetHeader'|'snippetLine'|'styles'|'topbar'|'warningsToplevel'} ComponentName */
/**
* @param {DOM} dom
* @param {ComponentName} componentName
* @return {DocumentFragment}
*/
export function createComponent(dom: DOM, componentName: ComponentName): DocumentFragment;
export type DOM = import('./dom.js').DOM;
export type ComponentName = '3pFilter' | 'audit' | 'categoryHeader' | 'chevron' | 'clump' | 'crc' | 'crcChain' | 'elementScreenshot' | 'footer' | 'fraction' | 'gauge' | 'gaugePwa' | 'heading' | 'metric' | 'opportunity' | 'opportunityHeader' | 'scorescale' | 'scoresWrapper' | 'snippet' | 'snippetContent' | 'snippetHeader' | 'snippetLine' | 'styles' | 'topbar' | 'warningsToplevel';
//# sourceMappingURL=components.d.ts.map

711
node_modules/lighthouse/report/renderer/components.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,73 @@
export type DOM = import('./dom.js').DOM;
export type DetailsRenderer = import('./details-renderer.js').DetailsRenderer;
export type CRCSegment = {
node: LH.Audit.Details.SimpleCriticalRequestNode[string];
isLastChild: boolean;
hasChildren: boolean;
startTime: number;
transferSize: number;
treeMarkers: boolean[];
};
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./details-renderer.js').DetailsRenderer} DetailsRenderer */
/**
* @typedef CRCSegment
* @property {LH.Audit.Details.SimpleCriticalRequestNode[string]} node
* @property {boolean} isLastChild
* @property {boolean} hasChildren
* @property {number} startTime
* @property {number} transferSize
* @property {boolean[]} treeMarkers
*/
export class CriticalRequestChainRenderer {
/**
* Create render context for critical-request-chain tree display.
* @param {LH.Audit.Details.SimpleCriticalRequestNode} tree
* @return {{tree: LH.Audit.Details.SimpleCriticalRequestNode, startTime: number, transferSize: number}}
*/
static initTree(tree: LH.Audit.Details.SimpleCriticalRequestNode): {
tree: LH.Audit.Details.SimpleCriticalRequestNode;
startTime: number;
transferSize: number;
};
/**
* Helper to create context for each critical-request-chain node based on its
* parent. Calculates if this node is the last child, whether it has any
* children itself and what the tree looks like all the way back up to the root,
* so the tree markers can be drawn correctly.
* @param {LH.Audit.Details.SimpleCriticalRequestNode} parent
* @param {string} id
* @param {number} startTime
* @param {number} transferSize
* @param {Array<boolean>=} treeMarkers
* @param {boolean=} parentIsLastChild
* @return {CRCSegment}
*/
static createSegment(parent: LH.Audit.Details.SimpleCriticalRequestNode, id: string, startTime: number, transferSize: number, treeMarkers?: Array<boolean> | undefined, parentIsLastChild?: boolean | undefined): CRCSegment;
/**
* Creates the DOM for a tree segment.
* @param {DOM} dom
* @param {CRCSegment} segment
* @param {DetailsRenderer} detailsRenderer
* @return {Node}
*/
static createChainNode(dom: DOM, segment: CRCSegment, detailsRenderer: DetailsRenderer): Node;
/**
* Recursively builds a tree from segments.
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {CRCSegment} segment
* @param {Element} elem Parent element.
* @param {LH.Audit.Details.CriticalRequestChain} details
* @param {DetailsRenderer} detailsRenderer
*/
static buildTree(dom: DOM, tmpl: DocumentFragment, segment: CRCSegment, elem: Element, details: LH.Audit.Details.CriticalRequestChain, detailsRenderer: DetailsRenderer): void;
/**
* @param {DOM} dom
* @param {LH.Audit.Details.CriticalRequestChain} details
* @param {DetailsRenderer} detailsRenderer
* @return {Element}
*/
static render(dom: DOM, details: LH.Audit.Details.CriticalRequestChain, detailsRenderer: DetailsRenderer): Element;
}
//# sourceMappingURL=crc-details-renderer.d.ts.map

View File

@@ -0,0 +1,203 @@
/**
* @license
* Copyright 2017 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.
*/
/**
* @fileoverview This file contains helpers for constructing and rendering the
* critical request chains network tree.
*/
import {Globals} from './report-globals.js';
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./details-renderer.js').DetailsRenderer} DetailsRenderer */
/**
* @typedef CRCSegment
* @property {LH.Audit.Details.SimpleCriticalRequestNode[string]} node
* @property {boolean} isLastChild
* @property {boolean} hasChildren
* @property {number} startTime
* @property {number} transferSize
* @property {boolean[]} treeMarkers
*/
class CriticalRequestChainRenderer {
/**
* Create render context for critical-request-chain tree display.
* @param {LH.Audit.Details.SimpleCriticalRequestNode} tree
* @return {{tree: LH.Audit.Details.SimpleCriticalRequestNode, startTime: number, transferSize: number}}
*/
static initTree(tree) {
let startTime = 0;
const rootNodes = Object.keys(tree);
if (rootNodes.length > 0) {
const node = tree[rootNodes[0]];
startTime = node.request.startTime;
}
return {tree, startTime, transferSize: 0};
}
/**
* Helper to create context for each critical-request-chain node based on its
* parent. Calculates if this node is the last child, whether it has any
* children itself and what the tree looks like all the way back up to the root,
* so the tree markers can be drawn correctly.
* @param {LH.Audit.Details.SimpleCriticalRequestNode} parent
* @param {string} id
* @param {number} startTime
* @param {number} transferSize
* @param {Array<boolean>=} treeMarkers
* @param {boolean=} parentIsLastChild
* @return {CRCSegment}
*/
static createSegment(parent, id, startTime, transferSize, treeMarkers, parentIsLastChild) {
const node = parent[id];
const siblings = Object.keys(parent);
const isLastChild = siblings.indexOf(id) === (siblings.length - 1);
const hasChildren = !!node.children && Object.keys(node.children).length > 0;
// Copy the tree markers so that we don't change by reference.
const newTreeMarkers = Array.isArray(treeMarkers) ? treeMarkers.slice(0) : [];
// Add on the new entry.
if (typeof parentIsLastChild !== 'undefined') {
newTreeMarkers.push(!parentIsLastChild);
}
return {
node,
isLastChild,
hasChildren,
startTime,
transferSize: transferSize + node.request.transferSize,
treeMarkers: newTreeMarkers,
};
}
/**
* Creates the DOM for a tree segment.
* @param {DOM} dom
* @param {CRCSegment} segment
* @param {DetailsRenderer} detailsRenderer
* @return {Node}
*/
static createChainNode(dom, segment, detailsRenderer) {
const chainEl = dom.createComponent('crcChain');
// Hovering over request shows full URL.
dom.find('.lh-crc-node', chainEl).setAttribute('title', segment.node.request.url);
const treeMarkeEl = dom.find('.lh-crc-node__tree-marker', chainEl);
// Construct lines and add spacers for sub requests.
segment.treeMarkers.forEach(separator => {
const classSeparator = separator ?
'lh-tree-marker lh-vert' :
'lh-tree-marker';
treeMarkeEl.append(
dom.createElement('span', classSeparator),
dom.createElement('span', 'lh-tree-marker')
);
});
const classLastChild = segment.isLastChild ?
'lh-tree-marker lh-up-right' :
'lh-tree-marker lh-vert-right';
const classHasChildren = segment.hasChildren ?
'lh-tree-marker lh-horiz-down' :
'lh-tree-marker lh-right';
treeMarkeEl.append(
dom.createElement('span', classLastChild),
dom.createElement('span', 'lh-tree-marker lh-right'),
dom.createElement('span', classHasChildren)
);
// Fill in url, host, and request size information.
const url = segment.node.request.url;
const linkEl = detailsRenderer.renderTextURL(url);
const treevalEl = dom.find('.lh-crc-node__tree-value', chainEl);
treevalEl.append(linkEl);
if (!segment.hasChildren) {
const {startTime, endTime, transferSize} = segment.node.request;
const span = dom.createElement('span', 'lh-crc-node__chain-duration');
span.textContent =
' - ' + Globals.i18n.formatMilliseconds((endTime - startTime) * 1000) + ', ';
const span2 = dom.createElement('span', 'lh-crc-node__chain-duration');
span2.textContent = Globals.i18n.formatBytesToKiB(transferSize, 0.01);
treevalEl.append(span, span2);
}
return chainEl;
}
/**
* Recursively builds a tree from segments.
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {CRCSegment} segment
* @param {Element} elem Parent element.
* @param {LH.Audit.Details.CriticalRequestChain} details
* @param {DetailsRenderer} detailsRenderer
*/
static buildTree(dom, tmpl, segment, elem, details, detailsRenderer) {
elem.append(CRCRenderer.createChainNode(dom, segment, detailsRenderer));
if (segment.node.children) {
for (const key of Object.keys(segment.node.children)) {
const childSegment = CRCRenderer.createSegment(segment.node.children, key,
segment.startTime, segment.transferSize, segment.treeMarkers, segment.isLastChild);
CRCRenderer.buildTree(dom, tmpl, childSegment, elem, details, detailsRenderer);
}
}
}
/**
* @param {DOM} dom
* @param {LH.Audit.Details.CriticalRequestChain} details
* @param {DetailsRenderer} detailsRenderer
* @return {Element}
*/
static render(dom, details, detailsRenderer) {
const tmpl = dom.createComponent('crc');
const containerEl = dom.find('.lh-crc', tmpl);
// Fill in top summary.
dom.find('.lh-crc-initial-nav', tmpl).textContent = Globals.strings.crcInitialNavigation;
dom.find('.lh-crc__longest_duration_label', tmpl).textContent =
Globals.strings.crcLongestDurationLabel;
dom.find('.lh-crc__longest_duration', tmpl).textContent =
Globals.i18n.formatMilliseconds(details.longestChain.duration);
// Construct visual tree.
const root = CRCRenderer.initTree(details.chains);
for (const key of Object.keys(root.tree)) {
const segment = CRCRenderer.createSegment(root.tree, key, root.startTime, root.transferSize);
CRCRenderer.buildTree(dom, tmpl, segment, containerEl, details, detailsRenderer);
}
return dom.find('.lh-crc-container', tmpl);
}
}
// Alias b/c the name is really long.
const CRCRenderer = CriticalRequestChainRenderer;
export {
CriticalRequestChainRenderer,
};

View File

@@ -0,0 +1,161 @@
export class DetailsRenderer {
/**
* @param {DOM} dom
* @param {{fullPageScreenshot?: LH.Result.FullPageScreenshot, entities?: LH.Result.Entities}} [options]
*/
constructor(dom: DOM, options?: {
fullPageScreenshot?: import("../../types/lhr/lhr.js").default.FullPageScreenshot | undefined;
entities?: import("../../types/lhr/lhr.js").default.Entities | undefined;
} | undefined);
_dom: import("./dom.js").DOM;
_fullPageScreenshot: import("../../types/lhr/lhr.js").default.FullPageScreenshot | undefined;
_entities: import("../../types/lhr/lhr.js").default.Entities | undefined;
/**
* @param {AuditDetails} details
* @return {Element|null}
*/
render(details: AuditDetails): Element | null;
/**
* @param {{value: number, granularity?: number}} details
* @return {Element}
*/
_renderBytes(details: {
value: number;
granularity?: number | undefined;
}): Element;
/**
* @param {{value: number, granularity?: number, displayUnit?: string}} details
* @return {Element}
*/
_renderMilliseconds(details: {
value: number;
granularity?: number | undefined;
displayUnit?: string | undefined;
}): Element;
/**
* @param {string} text
* @return {HTMLElement}
*/
renderTextURL(text: string): HTMLElement;
/**
* @param {{text: string, url: string}} details
* @return {HTMLElement}
*/
_renderLink(details: {
text: string;
url: string;
}): HTMLElement;
/**
* @param {string} text
* @return {HTMLDivElement}
*/
_renderText(text: string): HTMLDivElement;
/**
* @param {{value: number, granularity?: number}} details
* @return {Element}
*/
_renderNumeric(details: {
value: number;
granularity?: number | undefined;
}): Element;
/**
* Create small thumbnail with scaled down image asset.
* @param {string} details
* @return {Element}
*/
_renderThumbnail(details: string): Element;
/**
* @param {string} type
* @param {*} value
*/
_renderUnknown(type: string, value: any): HTMLDetailsElement;
/**
* Render a details item value for embedding in a table. Renders the value
* based on the heading's valueType, unless the value itself has a `type`
* property to override it.
* @param {TableItemValue} value
* @param {LH.Audit.Details.TableColumnHeading} heading
* @return {Element|null}
*/
_renderTableValue(value: TableItemValue, heading: LH.Audit.Details.TableColumnHeading): Element | null;
/**
* Returns a new heading where the values are defined first by `heading.subItemsHeading`,
* and secondly by `heading`. If there is no subItemsHeading, returns null, which will
* be rendered as an empty column.
* @param {LH.Audit.Details.TableColumnHeading} heading
* @return {LH.Audit.Details.TableColumnHeading | null}
*/
_getDerivedSubItemsHeading(heading: LH.Audit.Details.TableColumnHeading): LH.Audit.Details.TableColumnHeading | null;
/**
* @param {TableItem} item
* @param {(LH.Audit.Details.TableColumnHeading | null)[]} headings
*/
_renderTableRow(item: TableItem, headings: (LH.Audit.Details.TableColumnHeading | null)[]): HTMLTableRowElement;
/**
* Renders one or more rows from a details table item. A single table item can
* expand into multiple rows, if there is a subItemsHeading.
* @param {TableItem} item
* @param {LH.Audit.Details.TableColumnHeading[]} headings
*/
_renderTableRowsFromItem(item: TableItem, headings: LH.Audit.Details.TableColumnHeading[]): DocumentFragment;
/**
* Adorn a table row element with entity chips based on [data-entity] attribute.
* @param {HTMLTableRowElement} rowEl
*/
_adornEntityGroupRow(rowEl: HTMLTableRowElement): void;
/**
* Renders an entity-grouped row.
* @param {TableItem} item
* @param {LH.Audit.Details.TableColumnHeading[]} headings
*/
_renderEntityGroupRow(item: TableItem, headings: LH.Audit.Details.TableColumnHeading[]): DocumentFragment;
/**
* Returns an array of entity-grouped TableItems to use as the top-level rows in
* an grouped table. Each table item returned represents a unique entity, with every
* applicable key that can be grouped as a property. Optionally, supported columns are
* summed by entity, and sorted by specified keys.
* @param {TableLike} details
* @return {TableItem[]}
*/
_getEntityGroupItems(details: TableLike): TableItem[];
/**
* @param {TableLike} details
* @return {Element}
*/
_renderTable(details: TableLike): Element;
/**
* @param {LH.FormattedIcu<LH.Audit.Details.List>} details
* @return {Element}
*/
_renderList(details: LH.FormattedIcu<LH.Audit.Details.List>): Element;
/**
* @param {LH.Audit.Details.NodeValue} item
* @return {Element}
*/
renderNode(item: LH.Audit.Details.NodeValue): Element;
/**
* @param {LH.Audit.Details.SourceLocationValue} item
* @return {Element|null}
* @protected
*/
protected renderSourceLocation(item: LH.Audit.Details.SourceLocationValue): Element | null;
/**
* @param {LH.Audit.Details.Filmstrip} details
* @return {Element}
*/
_renderFilmstrip(details: LH.Audit.Details.Filmstrip): Element;
/**
* @param {string} text
* @return {Element}
*/
_renderCode(text: string): Element;
}
export type DOM = import('./dom.js').DOM;
export type AuditDetails = LH.FormattedIcu<LH.Audit.Details>;
export type OpportunityTable = LH.FormattedIcu<LH.Audit.Details.Opportunity>;
export type Table = LH.FormattedIcu<LH.Audit.Details.Table>;
export type TableItem = LH.FormattedIcu<LH.Audit.Details.TableItem>;
export type TableItemValue = LH.FormattedIcu<LH.Audit.Details.ItemValue>;
export type TableColumnHeading = LH.FormattedIcu<LH.Audit.Details.TableColumnHeading>;
export type TableLike = LH.FormattedIcu<LH.Audit.Details.Table | LH.Audit.Details.Opportunity>;
//# sourceMappingURL=details-renderer.d.ts.map

View File

@@ -0,0 +1,677 @@
/**
* @license
* Copyright 2017 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.
*/
/** @typedef {import('./dom.js').DOM} DOM */
// Convenience types for localized AuditDetails.
/** @typedef {LH.FormattedIcu<LH.Audit.Details>} AuditDetails */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.Opportunity>} OpportunityTable */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.Table>} Table */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.TableItem>} TableItem */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.ItemValue>} TableItemValue */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.TableColumnHeading>} TableColumnHeading */
/** @typedef {LH.FormattedIcu<LH.Audit.Details.Table | LH.Audit.Details.Opportunity>} TableLike */
import {Util} from '../../shared/util.js';
import {CriticalRequestChainRenderer} from './crc-details-renderer.js';
import {ElementScreenshotRenderer} from './element-screenshot-renderer.js';
import {Globals} from './report-globals.js';
import {ReportUtils} from './report-utils.js';
const URL_PREFIXES = ['http://', 'https://', 'data:'];
const SUMMABLE_VALUETYPES = ['bytes', 'numeric', 'ms', 'timespanMs'];
export class DetailsRenderer {
/**
* @param {DOM} dom
* @param {{fullPageScreenshot?: LH.Result.FullPageScreenshot, entities?: LH.Result.Entities}} [options]
*/
constructor(dom, options = {}) {
this._dom = dom;
this._fullPageScreenshot = options.fullPageScreenshot;
this._entities = options.entities;
}
/**
* @param {AuditDetails} details
* @return {Element|null}
*/
render(details) {
switch (details.type) {
case 'filmstrip':
return this._renderFilmstrip(details);
case 'list':
return this._renderList(details);
case 'table':
case 'opportunity':
return this._renderTable(details);
case 'criticalrequestchain':
return CriticalRequestChainRenderer.render(this._dom, details, this);
// Internal-only details, not for rendering.
case 'screenshot':
case 'debugdata':
case 'treemap-data':
return null;
default: {
// @ts-expect-error - all detail types need to be handled above so tsc thinks this is unreachable.
// Call _renderUnknown() to be forward compatible with new, unexpected detail types.
return this._renderUnknown(details.type, details);
}
}
}
/**
* @param {{value: number, granularity?: number}} details
* @return {Element}
*/
_renderBytes(details) {
// TODO: handle displayUnit once we have something other than 'KiB'
const value = Globals.i18n.formatBytesToKiB(details.value, details.granularity || 0.1);
const textEl = this._renderText(value);
textEl.title = Globals.i18n.formatBytes(details.value);
return textEl;
}
/**
* @param {{value: number, granularity?: number, displayUnit?: string}} details
* @return {Element}
*/
_renderMilliseconds(details) {
let value;
if (details.displayUnit === 'duration') {
value = Globals.i18n.formatDuration(details.value);
} else {
value = Globals.i18n.formatMilliseconds(details.value, details.granularity || 10);
}
return this._renderText(value);
}
/**
* @param {string} text
* @return {HTMLElement}
*/
renderTextURL(text) {
const url = text;
let displayedPath;
let displayedHost;
let title;
try {
const parsed = Util.parseURL(url);
displayedPath = parsed.file === '/' ? parsed.origin : parsed.file;
displayedHost = parsed.file === '/' || parsed.hostname === '' ? '' : `(${parsed.hostname})`;
title = url;
} catch (e) {
displayedPath = url;
}
const element = this._dom.createElement('div', 'lh-text__url');
element.append(this._renderLink({text: displayedPath, url}));
if (displayedHost) {
const hostElem = this._renderText(displayedHost);
hostElem.classList.add('lh-text__url-host');
element.append(hostElem);
}
if (title) {
element.title = url;
// set the url on the element's dataset which we use to check 3rd party origins
element.dataset.url = url;
}
return element;
}
/**
* @param {{text: string, url: string}} details
* @return {HTMLElement}
*/
_renderLink(details) {
const a = this._dom.createElement('a');
this._dom.safelySetHref(a, details.url);
if (!a.href) {
// Fall back to just the link text if invalid or protocol not allowed.
const element = this._renderText(details.text);
element.classList.add('lh-link');
return element;
}
a.rel = 'noopener';
a.target = '_blank';
a.textContent = details.text;
a.classList.add('lh-link');
return a;
}
/**
* @param {string} text
* @return {HTMLDivElement}
*/
_renderText(text) {
const element = this._dom.createElement('div', 'lh-text');
element.textContent = text;
return element;
}
/**
* @param {{value: number, granularity?: number}} details
* @return {Element}
*/
_renderNumeric(details) {
const value = Globals.i18n.formatNumber(details.value, details.granularity || 0.1);
const element = this._dom.createElement('div', 'lh-numeric');
element.textContent = value;
return element;
}
/**
* Create small thumbnail with scaled down image asset.
* @param {string} details
* @return {Element}
*/
_renderThumbnail(details) {
const element = this._dom.createElement('img', 'lh-thumbnail');
const strValue = details;
element.src = strValue;
element.title = strValue;
element.alt = '';
return element;
}
/**
* @param {string} type
* @param {*} value
*/
_renderUnknown(type, value) {
// eslint-disable-next-line no-console
console.error(`Unknown details type: ${type}`, value);
const element = this._dom.createElement('details', 'lh-unknown');
this._dom.createChildOf(element, 'summary').textContent =
`We don't know how to render audit details of type \`${type}\`. ` +
'The Lighthouse version that collected this data is likely newer than the Lighthouse ' +
'version of the report renderer. Expand for the raw JSON.';
this._dom.createChildOf(element, 'pre').textContent = JSON.stringify(value, null, 2);
return element;
}
/**
* Render a details item value for embedding in a table. Renders the value
* based on the heading's valueType, unless the value itself has a `type`
* property to override it.
* @param {TableItemValue} value
* @param {LH.Audit.Details.TableColumnHeading} heading
* @return {Element|null}
*/
_renderTableValue(value, heading) {
if (value === undefined || value === null) {
return null;
}
// First deal with the possible object forms of value.
if (typeof value === 'object') {
// The value's type overrides the heading's for this column.
switch (value.type) {
case 'code': {
return this._renderCode(value.value);
}
case 'link': {
return this._renderLink(value);
}
case 'node': {
return this.renderNode(value);
}
case 'numeric': {
return this._renderNumeric(value);
}
case 'source-location': {
return this.renderSourceLocation(value);
}
case 'url': {
return this.renderTextURL(value.value);
}
default: {
return this._renderUnknown(value.type, value);
}
}
}
// Next, deal with primitives.
switch (heading.valueType) {
case 'bytes': {
const numValue = Number(value);
return this._renderBytes({value: numValue, granularity: heading.granularity});
}
case 'code': {
const strValue = String(value);
return this._renderCode(strValue);
}
case 'ms': {
const msValue = {
value: Number(value),
granularity: heading.granularity,
displayUnit: heading.displayUnit,
};
return this._renderMilliseconds(msValue);
}
case 'numeric': {
const numValue = Number(value);
return this._renderNumeric({value: numValue, granularity: heading.granularity});
}
case 'text': {
const strValue = String(value);
return this._renderText(strValue);
}
case 'thumbnail': {
const strValue = String(value);
return this._renderThumbnail(strValue);
}
case 'timespanMs': {
const numValue = Number(value);
return this._renderMilliseconds({value: numValue});
}
case 'url': {
const strValue = String(value);
if (URL_PREFIXES.some(prefix => strValue.startsWith(prefix))) {
return this.renderTextURL(strValue);
} else {
// Fall back to <pre> rendering if not actually a URL.
return this._renderCode(strValue);
}
}
default: {
return this._renderUnknown(heading.valueType, value);
}
}
}
/**
* Returns a new heading where the values are defined first by `heading.subItemsHeading`,
* and secondly by `heading`. If there is no subItemsHeading, returns null, which will
* be rendered as an empty column.
* @param {LH.Audit.Details.TableColumnHeading} heading
* @return {LH.Audit.Details.TableColumnHeading | null}
*/
_getDerivedSubItemsHeading(heading) {
if (!heading.subItemsHeading) return null;
return {
key: heading.subItemsHeading.key || '',
valueType: heading.subItemsHeading.valueType || heading.valueType,
granularity: heading.subItemsHeading.granularity || heading.granularity,
displayUnit: heading.subItemsHeading.displayUnit || heading.displayUnit,
label: '',
};
}
/**
* @param {TableItem} item
* @param {(LH.Audit.Details.TableColumnHeading | null)[]} headings
*/
_renderTableRow(item, headings) {
const rowElem = this._dom.createElement('tr');
for (const heading of headings) {
// Empty cell if no heading or heading key for this column.
if (!heading || !heading.key) {
this._dom.createChildOf(rowElem, 'td', 'lh-table-column--empty');
continue;
}
const value = item[heading.key];
let valueElement;
if (value !== undefined && value !== null) {
valueElement = this._renderTableValue(value, heading);
}
if (valueElement) {
const classes = `lh-table-column--${heading.valueType}`;
this._dom.createChildOf(rowElem, 'td', classes).append(valueElement);
} else {
// Empty cell is rendered for a column if:
// - the pair is null
// - the heading key is null
// - the value is undefined/null
this._dom.createChildOf(rowElem, 'td', 'lh-table-column--empty');
}
}
return rowElem;
}
/**
* Renders one or more rows from a details table item. A single table item can
* expand into multiple rows, if there is a subItemsHeading.
* @param {TableItem} item
* @param {LH.Audit.Details.TableColumnHeading[]} headings
*/
_renderTableRowsFromItem(item, headings) {
const fragment = this._dom.createFragment();
fragment.append(this._renderTableRow(item, headings));
if (!item.subItems) return fragment;
const subItemsHeadings = headings.map(this._getDerivedSubItemsHeading);
if (!subItemsHeadings.some(Boolean)) return fragment;
for (const subItem of item.subItems.items) {
const rowEl = this._renderTableRow(subItem, subItemsHeadings);
rowEl.classList.add('lh-sub-item-row');
fragment.append(rowEl);
}
return fragment;
}
/**
* Adorn a table row element with entity chips based on [data-entity] attribute.
* @param {HTMLTableRowElement} rowEl
*/
_adornEntityGroupRow(rowEl) {
const entityName = rowEl.dataset.entity;
if (!entityName) return;
const matchedEntity = this._entities?.find(e => e.name === entityName);
if (!matchedEntity) return;
const firstTdEl = this._dom.find('td', rowEl);
if (matchedEntity.category) {
const categoryChipEl = this._dom.createElement('span');
categoryChipEl.classList.add('lh-audit__adorn');
categoryChipEl.textContent = matchedEntity.category;
firstTdEl.append(' ', categoryChipEl);
}
if (matchedEntity.isFirstParty) {
const firstPartyChipEl = this._dom.createElement('span');
firstPartyChipEl.classList.add('lh-audit__adorn', 'lh-audit__adorn1p');
firstPartyChipEl.textContent = Globals.strings.firstPartyChipLabel;
firstTdEl.append(' ', firstPartyChipEl);
}
if (matchedEntity.homepage) {
const entityLinkEl = this._dom.createElement('a');
entityLinkEl.href = matchedEntity.homepage;
entityLinkEl.target = '_blank';
entityLinkEl.title = Globals.strings.openInANewTabTooltip;
entityLinkEl.classList.add('lh-report-icon--external');
firstTdEl.append(' ', entityLinkEl);
}
}
/**
* Renders an entity-grouped row.
* @param {TableItem} item
* @param {LH.Audit.Details.TableColumnHeading[]} headings
*/
_renderEntityGroupRow(item, headings) {
const entityColumnHeading = {...headings[0]};
// In subitem-situations (unused-javascript), ensure Entity name is not rendered as code, etc.
entityColumnHeading.valueType = 'text';
const groupedRowHeadings = [entityColumnHeading, ...headings.slice(1)];
const fragment = this._dom.createFragment();
fragment.append(this._renderTableRow(item, groupedRowHeadings));
this._dom.find('tr', fragment).classList.add('lh-row--group');
return fragment;
}
/**
* Returns an array of entity-grouped TableItems to use as the top-level rows in
* an grouped table. Each table item returned represents a unique entity, with every
* applicable key that can be grouped as a property. Optionally, supported columns are
* summed by entity, and sorted by specified keys.
* @param {TableLike} details
* @return {TableItem[]}
*/
_getEntityGroupItems(details) {
const {items, headings, sortedBy} = details;
// Exclude entity-grouped audits and results without entity classification.
// Eg. Third-party Summary comes entity-grouped.
if (!items.length || details.isEntityGrouped || !items.some(item => item.entity)) {
return [];
}
const skippedColumns = new Set(details.skipSumming || []);
/** @type {string[]} */
const summableColumns = [];
for (const heading of headings) {
if (!heading.key || skippedColumns.has(heading.key)) continue;
if (SUMMABLE_VALUETYPES.includes(heading.valueType)) {
summableColumns.push(heading.key);
}
}
// Grab the first column's key to group by entity
const firstColumnKey = headings[0].key;
if (!firstColumnKey) return [];
/** @type {Map<string | undefined, TableItem>} */
const byEntity = new Map();
for (const item of items) {
const entityName = typeof item.entity === 'string' ? item.entity : undefined;
const groupedItem = byEntity.get(entityName) || {
[firstColumnKey]: entityName || Globals.strings.unattributable,
entity: entityName,
};
for (const key of summableColumns) {
groupedItem[key] = Number(groupedItem[key] || 0) + Number(item[key] || 0);
}
byEntity.set(entityName, groupedItem);
}
const result = [...byEntity.values()];
if (sortedBy) {
result.sort(ReportUtils.getTableItemSortComparator(sortedBy));
}
return result;
}
/**
* @param {TableLike} details
* @return {Element}
*/
_renderTable(details) {
if (!details.items.length) return this._dom.createElement('span');
const tableElem = this._dom.createElement('table', 'lh-table');
const theadElem = this._dom.createChildOf(tableElem, 'thead');
const theadTrElem = this._dom.createChildOf(theadElem, 'tr');
for (const heading of details.headings) {
const valueType = heading.valueType || 'text';
const classes = `lh-table-column--${valueType}`;
const labelEl = this._dom.createElement('div', 'lh-text');
labelEl.textContent = heading.label;
this._dom.createChildOf(theadTrElem, 'th', classes).append(labelEl);
}
const entityItems = this._getEntityGroupItems(details);
const tbodyElem = this._dom.createChildOf(tableElem, 'tbody');
if (entityItems.length) {
for (const entityItem of entityItems) {
const entityName = typeof entityItem.entity === 'string' ? entityItem.entity : undefined;
const entityGroupFragment = this._renderEntityGroupRow(entityItem, details.headings);
// Render all the items that match the heading row
for (const item of details.items.filter((item) => item.entity === entityName)) {
entityGroupFragment.append(this._renderTableRowsFromItem(item, details.headings));
}
const rowEls = this._dom.findAll('tr', entityGroupFragment);
if (entityName && rowEls.length) {
rowEls.forEach(row => row.dataset.entity = entityName);
this._adornEntityGroupRow(rowEls[0]);
}
tbodyElem.append(entityGroupFragment);
}
} else {
let even = true;
for (const item of details.items) {
const rowsFragment = this._renderTableRowsFromItem(item, details.headings);
const rowEls = this._dom.findAll('tr', rowsFragment);
const firstRowEl = rowEls[0];
if (typeof item.entity === 'string') {
firstRowEl.dataset.entity = item.entity;
}
if (details.isEntityGrouped && item.entity) {
// If the audit is already grouped, consider first row as a heading row.
firstRowEl.classList.add('lh-row--group');
this._adornEntityGroupRow(firstRowEl);
} else {
for (const rowEl of rowEls) {
// For zebra styling (same shade for a row and its sub-rows).
rowEl.classList.add(even ? 'lh-row--even' : 'lh-row--odd');
}
}
even = !even;
tbodyElem.append(rowsFragment);
}
}
return tableElem;
}
/**
* @param {LH.FormattedIcu<LH.Audit.Details.List>} details
* @return {Element}
*/
_renderList(details) {
const listContainer = this._dom.createElement('div', 'lh-list');
details.items.forEach(item => {
const listItem = this.render(item);
if (!listItem) return;
listContainer.append(listItem);
});
return listContainer;
}
/**
* @param {LH.Audit.Details.NodeValue} item
* @return {Element}
*/
renderNode(item) {
const element = this._dom.createElement('span', 'lh-node');
if (item.nodeLabel) {
const nodeLabelEl = this._dom.createElement('div');
nodeLabelEl.textContent = item.nodeLabel;
element.append(nodeLabelEl);
}
if (item.snippet) {
const snippetEl = this._dom.createElement('div');
snippetEl.classList.add('lh-node__snippet');
snippetEl.textContent = item.snippet;
element.append(snippetEl);
}
if (item.selector) {
element.title = item.selector;
}
if (item.path) element.setAttribute('data-path', item.path);
if (item.selector) element.setAttribute('data-selector', item.selector);
if (item.snippet) element.setAttribute('data-snippet', item.snippet);
if (!this._fullPageScreenshot) return element;
const rect = item.lhId && this._fullPageScreenshot.nodes[item.lhId];
if (!rect || rect.width === 0 || rect.height === 0) return element;
const maxThumbnailSize = {width: 147, height: 100};
const elementScreenshot = ElementScreenshotRenderer.render(
this._dom,
this._fullPageScreenshot.screenshot,
rect,
maxThumbnailSize
);
if (elementScreenshot) element.prepend(elementScreenshot);
return element;
}
/**
* @param {LH.Audit.Details.SourceLocationValue} item
* @return {Element|null}
* @protected
*/
renderSourceLocation(item) {
if (!item.url) {
return null;
}
// Lines are shown as one-indexed.
const generatedLocation = `${item.url}:${item.line + 1}:${item.column}`;
let sourceMappedOriginalLocation;
if (item.original) {
const file = item.original.file || '<unmapped>';
sourceMappedOriginalLocation = `${file}:${item.original.line + 1}:${item.original.column}`;
}
// We render slightly differently based on presence of source map and provenance of URL.
let element;
if (item.urlProvider === 'network' && sourceMappedOriginalLocation) {
element = this._renderLink({
url: item.url,
text: sourceMappedOriginalLocation,
});
element.title = `maps to generated location ${generatedLocation}`;
} else if (item.urlProvider === 'network' && !sourceMappedOriginalLocation) {
element = this.renderTextURL(item.url);
this._dom.find('.lh-link', element).textContent += `:${item.line + 1}:${item.column}`;
} else if (item.urlProvider === 'comment' && sourceMappedOriginalLocation) {
element = this._renderText(`${sourceMappedOriginalLocation} (from source map)`);
element.title = `${generatedLocation} (from sourceURL)`;
} else if (item.urlProvider === 'comment' && !sourceMappedOriginalLocation) {
element = this._renderText(`${generatedLocation} (from sourceURL)`);
} else {
return null;
}
element.classList.add('lh-source-location');
element.setAttribute('data-source-url', item.url);
// DevTools expects zero-indexed lines.
element.setAttribute('data-source-line', String(item.line));
element.setAttribute('data-source-column', String(item.column));
return element;
}
/**
* @param {LH.Audit.Details.Filmstrip} details
* @return {Element}
*/
_renderFilmstrip(details) {
const filmstripEl = this._dom.createElement('div', 'lh-filmstrip');
for (const thumbnail of details.items) {
const frameEl = this._dom.createChildOf(filmstripEl, 'div', 'lh-filmstrip__frame');
const imgEl = this._dom.createChildOf(frameEl, 'img', 'lh-filmstrip__thumbnail');
imgEl.src = thumbnail.data;
imgEl.alt = `Screenshot`;
}
return filmstripEl;
}
/**
* @param {string} text
* @return {Element}
*/
_renderCode(text) {
const pre = this._dom.createElement('pre', 'lh-code');
pre.textContent = text;
return pre;
}
}

128
node_modules/lighthouse/report/renderer/dom.d.ts generated vendored Normal file
View File

@@ -0,0 +1,128 @@
export class DOM {
/**
* @param {Document} document
* @param {HTMLElement} rootEl
*/
constructor(document: Document, rootEl: HTMLElement);
/** @type {Document} */
_document: Document;
/** @type {string} */
_lighthouseChannel: string;
/** @type {Map<string, DocumentFragment>} */
_componentCache: Map<string, DocumentFragment>;
/** @type {HTMLElement} */
rootEl: HTMLElement;
/**
* @template {string} T
* @param {T} name
* @param {string=} className
* @return {HTMLElementByTagName[T]}
*/
createElement<T extends string>(name: T, className?: string | undefined): HTMLElementByTagName[T];
/**
* @param {string} namespaceURI
* @param {string} name
* @param {string=} className
* @return {Element}
*/
createElementNS(namespaceURI: string, name: string, className?: string | undefined): Element;
/**
* @return {!DocumentFragment}
*/
createFragment(): DocumentFragment;
/**
* @param {string} data
* @return {!Node}
*/
createTextNode(data: string): Node;
/**
* @template {string} T
* @param {Element} parentElem
* @param {T} elementName
* @param {string=} className
* @return {HTMLElementByTagName[T]}
*/
createChildOf<T_1 extends string>(parentElem: Element, elementName: T_1, className?: string | undefined): HTMLElementByTagName[T_1];
/**
* @param {import('./components.js').ComponentName} componentName
* @return {!DocumentFragment} A clone of the cached component.
*/
createComponent(componentName: import('./components.js').ComponentName): DocumentFragment;
clearComponentCache(): void;
/**
* @param {string} text
* @param {{alwaysAppendUtmSource?: boolean}} opts
* @return {Element}
*/
convertMarkdownLinkSnippets(text: string, opts?: {
alwaysAppendUtmSource?: boolean;
}): Element;
/**
* Set link href, but safely, preventing `javascript:` protocol, etc.
* @see https://github.com/google/safevalues/
* @param {HTMLAnchorElement} elem
* @param {string} url
*/
safelySetHref(elem: HTMLAnchorElement, url: string): void;
/**
* Only create blob URLs for JSON & HTML
* @param {HTMLAnchorElement} elem
* @param {Blob} blob
*/
safelySetBlobHref(elem: HTMLAnchorElement, blob: Blob): void;
/**
* @param {string} markdownText
* @return {Element}
*/
convertMarkdownCodeSnippets(markdownText: string): Element;
/**
* The channel to use for UTM data when rendering links to the documentation.
* @param {string} lighthouseChannel
*/
setLighthouseChannel(lighthouseChannel: string): void;
/**
* ONLY use if `dom.rootEl` isn't sufficient for your needs. `dom.rootEl` is preferred
* for all scoping, because a document can have multiple reports within it.
* @return {Document}
*/
document(): Document;
/**
* TODO(paulirish): import and conditionally apply the DevTools frontend subclasses instead of this
* @return {boolean}
*/
isDevTools(): boolean;
/**
* Guaranteed context.querySelector. Always returns an element or throws if
* nothing matches query.
* @template {string} T
* @param {T} query
* @param {ParentNode} context
* @return {ParseSelector<T>}
*/
find<T_2 extends string>(query: T_2, context: ParentNode): import("typed-query-selector/parser").ParseSelector<T_2, Element>;
/**
* Helper for context.querySelectorAll. Returns an Array instead of a NodeList.
* @template {string} T
* @param {T} query
* @param {ParentNode} context
*/
findAll<T_3 extends string>(query: T_3, context: ParentNode): import("../../types/internal/query-selector.js").QuerySelectorParse<T_3>[];
/**
* Fires a custom DOM event on target.
* @param {string} name Name of the event.
* @param {Node=} target DOM node to fire the event on.
* @param {*=} detail Custom data to include.
*/
fireEventOn(name: string, target?: Node | undefined, detail?: any | undefined): void;
/**
* Downloads a file (blob) using a[download].
* @param {Blob|File} blob The file to save.
* @param {string} filename
*/
saveFile(blob: Blob | File, filename: string): void;
}
export type HTMLElementByTagName = HTMLElementTagNameMap & {
[id: string]: HTMLElement;
};
export type ParseSelector<T extends string> = import('typed-query-selector/parser').ParseSelector<T, Element>;
//# sourceMappingURL=dom.d.ts.map

310
node_modules/lighthouse/report/renderer/dom.js generated vendored Normal file
View File

@@ -0,0 +1,310 @@
/**
* @license
* Copyright 2017 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.
*/
/* eslint-env browser */
/** @typedef {HTMLElementTagNameMap & {[id: string]: HTMLElement}} HTMLElementByTagName */
/** @template {string} T @typedef {import('typed-query-selector/parser').ParseSelector<T, Element>} ParseSelector */
import {Util} from '../../shared/util.js';
import {createComponent} from './components.js';
export class DOM {
/**
* @param {Document} document
* @param {HTMLElement} rootEl
*/
constructor(document, rootEl) {
/** @type {Document} */
this._document = document;
/** @type {string} */
this._lighthouseChannel = 'unknown';
/** @type {Map<string, DocumentFragment>} */
this._componentCache = new Map();
/** @type {HTMLElement} */
// For legacy Report API users, this'll be undefined, but set in renderReport
this.rootEl = rootEl;
}
/**
* @template {string} T
* @param {T} name
* @param {string=} className
* @return {HTMLElementByTagName[T]}
*/
createElement(name, className) {
const element = this._document.createElement(name);
if (className) {
for (const token of className.split(/\s+/)) {
if (token) element.classList.add(token);
}
}
return element;
}
/**
* @param {string} namespaceURI
* @param {string} name
* @param {string=} className
* @return {Element}
*/
createElementNS(namespaceURI, name, className) {
const element = this._document.createElementNS(namespaceURI, name);
if (className) {
for (const token of className.split(/\s+/)) {
if (token) element.classList.add(token);
}
}
return element;
}
/**
* @return {!DocumentFragment}
*/
createFragment() {
return this._document.createDocumentFragment();
}
/**
* @param {string} data
* @return {!Node}
*/
createTextNode(data) {
return this._document.createTextNode(data);
}
/**
* @template {string} T
* @param {Element} parentElem
* @param {T} elementName
* @param {string=} className
* @return {HTMLElementByTagName[T]}
*/
createChildOf(parentElem, elementName, className) {
const element = this.createElement(elementName, className);
parentElem.append(element);
return element;
}
/**
* @param {import('./components.js').ComponentName} componentName
* @return {!DocumentFragment} A clone of the cached component.
*/
createComponent(componentName) {
let component = this._componentCache.get(componentName);
if (component) {
const cloned = /** @type {DocumentFragment} */ (component.cloneNode(true));
// Prevent duplicate styles in the DOM. After a template has been stamped
// for the first time, remove the clone's styles so they're not re-added.
this.findAll('style', cloned).forEach(style => style.remove());
return cloned;
}
component = createComponent(this, componentName);
this._componentCache.set(componentName, component);
const cloned = /** @type {DocumentFragment} */ (component.cloneNode(true));
return cloned;
}
clearComponentCache() {
this._componentCache.clear();
}
/**
* @param {string} text
* @param {{alwaysAppendUtmSource?: boolean}} opts
* @return {Element}
*/
convertMarkdownLinkSnippets(text, opts = {}) {
const element = this.createElement('span');
for (const segment of Util.splitMarkdownLink(text)) {
const processedSegment = segment.text.includes('`') ?
this.convertMarkdownCodeSnippets(segment.text) :
segment.text;
if (!segment.isLink) {
// Plain text segment.
element.append(processedSegment);
continue;
}
// Otherwise, append any links found.
const url = new URL(segment.linkHref);
const DOCS_ORIGINS = ['https://developers.google.com', 'https://web.dev', 'https://developer.chrome.com'];
if (DOCS_ORIGINS.includes(url.origin) || opts.alwaysAppendUtmSource) {
url.searchParams.set('utm_source', 'lighthouse');
url.searchParams.set('utm_medium', this._lighthouseChannel);
}
const a = this.createElement('a');
a.rel = 'noopener';
a.target = '_blank';
a.append(processedSegment);
this.safelySetHref(a, url.href);
element.append(a);
}
return element;
}
/**
* Set link href, but safely, preventing `javascript:` protocol, etc.
* @see https://github.com/google/safevalues/
* @param {HTMLAnchorElement} elem
* @param {string} url
*/
safelySetHref(elem, url) {
// Defaults to '' to fix proto roundtrip issue. See https://github.com/GoogleChrome/lighthouse/issues/12868
url = url || '';
// In-page anchor links are safe.
if (url.startsWith('#')) {
elem.href = url;
return;
}
const allowedProtocols = ['https:', 'http:'];
let parsed;
try {
parsed = new URL(url);
} catch (_) {}
if (parsed && allowedProtocols.includes(parsed.protocol)) {
elem.href = parsed.href;
}
}
/**
* Only create blob URLs for JSON & HTML
* @param {HTMLAnchorElement} elem
* @param {Blob} blob
*/
safelySetBlobHref(elem, blob) {
if (blob.type !== 'text/html' && blob.type !== 'application/json') {
throw new Error('Unsupported blob type');
}
const href = URL.createObjectURL(blob);
elem.href = href;
}
/**
* @param {string} markdownText
* @return {Element}
*/
convertMarkdownCodeSnippets(markdownText) {
const element = this.createElement('span');
for (const segment of Util.splitMarkdownCodeSpans(markdownText)) {
if (segment.isCode) {
const pre = this.createElement('code');
pre.textContent = segment.text;
element.append(pre);
} else {
element.append(this._document.createTextNode(segment.text));
}
}
return element;
}
/**
* The channel to use for UTM data when rendering links to the documentation.
* @param {string} lighthouseChannel
*/
setLighthouseChannel(lighthouseChannel) {
this._lighthouseChannel = lighthouseChannel;
}
/**
* ONLY use if `dom.rootEl` isn't sufficient for your needs. `dom.rootEl` is preferred
* for all scoping, because a document can have multiple reports within it.
* @return {Document}
*/
document() {
return this._document;
}
/**
* TODO(paulirish): import and conditionally apply the DevTools frontend subclasses instead of this
* @return {boolean}
*/
isDevTools() {
return !!this._document.querySelector('.lh-devtools');
}
/**
* Guaranteed context.querySelector. Always returns an element or throws if
* nothing matches query.
* @template {string} T
* @param {T} query
* @param {ParentNode} context
* @return {ParseSelector<T>}
*/
find(query, context) {
const result = context.querySelector(query);
if (result === null) {
throw new Error(`query ${query} not found`);
}
// Because we control the report layout and templates, use the simpler
// `typed-query-selector` types that don't require differentiating between
// e.g. HTMLAnchorElement and SVGAElement. See https://github.com/GoogleChrome/lighthouse/issues/12011
return /** @type {ParseSelector<T>} */ (result);
}
/**
* Helper for context.querySelectorAll. Returns an Array instead of a NodeList.
* @template {string} T
* @param {T} query
* @param {ParentNode} context
*/
findAll(query, context) {
const elements = Array.from(context.querySelectorAll(query));
return elements;
}
/**
* Fires a custom DOM event on target.
* @param {string} name Name of the event.
* @param {Node=} target DOM node to fire the event on.
* @param {*=} detail Custom data to include.
*/
fireEventOn(name, target = this._document, detail) {
const event = new CustomEvent(name, detail ? {detail} : undefined);
target.dispatchEvent(event);
}
/**
* Downloads a file (blob) using a[download].
* @param {Blob|File} blob The file to save.
* @param {string} filename
*/
saveFile(blob, filename) {
const a = this.createElement('a');
a.download = filename;
this.safelySetBlobHref(a, blob);
this._document.body.append(a); // Firefox requires anchor to be in the DOM.
a.click();
// cleanup.
this._document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(a.href), 500);
}
}

View File

@@ -0,0 +1,70 @@
/**
* @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.
*/
/** @typedef {import('./dom.js').DOM} DOM */
export class DropDownMenu {
/**
* @param {DOM} dom
*/
constructor(dom: DOM);
/** @type {DOM} */
_dom: DOM;
/** @type {HTMLElement} */
_toggleEl: HTMLElement;
/** @type {HTMLElement} */
_menuEl: HTMLElement;
/**
* Keydown handler for the document.
* @param {KeyboardEvent} e
*/
onDocumentKeyDown(e: KeyboardEvent): void;
/**
* Click handler for tools button.
* @param {Event} e
*/
onToggleClick(e: Event): void;
/**
* Handler for tool button.
* @param {KeyboardEvent} e
*/
onToggleKeydown(e: KeyboardEvent): void;
/**
* Focus out handler for the drop down menu.
* @param {FocusEvent} e
*/
onMenuFocusOut(e: FocusEvent): void;
/**
* Handler for tool DropDown.
* @param {KeyboardEvent} e
*/
onMenuKeydown(e: KeyboardEvent): void;
/**
* @param {?HTMLElement=} startEl
* @return {HTMLElement}
*/
_getNextMenuItem(startEl?: (HTMLElement | null) | undefined): HTMLElement;
/**
* @param {Array<Node>} allNodes
* @param {?HTMLElement=} startNode
* @return {HTMLElement}
*/
_getNextSelectableNode(allNodes: Array<Node>, startNode?: (HTMLElement | null) | undefined): HTMLElement;
/**
* @param {?HTMLElement=} startEl
* @return {HTMLElement}
*/
_getPreviousMenuItem(startEl?: (HTMLElement | null) | undefined): HTMLElement;
/**
* @param {function(MouseEvent): any} menuClickHandler
*/
setup(menuClickHandler: (arg0: MouseEvent) => any): void;
close(): void;
/**
* @param {HTMLElement} firstFocusElement
*/
open(firstFocusElement: HTMLElement): void;
}
export type DOM = import('./dom.js').DOM;
//# sourceMappingURL=drop-down-menu.d.ts.map

View File

@@ -0,0 +1,214 @@
/**
* @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.
*/
/* eslint-env browser */
/** @typedef {import('./dom.js').DOM} DOM */
export class DropDownMenu {
/**
* @param {DOM} dom
*/
constructor(dom) {
/** @type {DOM} */
this._dom = dom;
/** @type {HTMLElement} */
this._toggleEl; // eslint-disable-line no-unused-expressions
/** @type {HTMLElement} */
this._menuEl; // eslint-disable-line no-unused-expressions
this.onDocumentKeyDown = this.onDocumentKeyDown.bind(this);
this.onToggleClick = this.onToggleClick.bind(this);
this.onToggleKeydown = this.onToggleKeydown.bind(this);
this.onMenuFocusOut = this.onMenuFocusOut.bind(this);
this.onMenuKeydown = this.onMenuKeydown.bind(this);
this._getNextMenuItem = this._getNextMenuItem.bind(this);
this._getNextSelectableNode = this._getNextSelectableNode.bind(this);
this._getPreviousMenuItem = this._getPreviousMenuItem.bind(this);
}
/**
* @param {function(MouseEvent): any} menuClickHandler
*/
setup(menuClickHandler) {
this._toggleEl = this._dom.find('.lh-topbar button.lh-tools__button', this._dom.rootEl);
this._toggleEl.addEventListener('click', this.onToggleClick);
this._toggleEl.addEventListener('keydown', this.onToggleKeydown);
this._menuEl = this._dom.find('.lh-topbar div.lh-tools__dropdown', this._dom.rootEl);
this._menuEl.addEventListener('keydown', this.onMenuKeydown);
this._menuEl.addEventListener('click', menuClickHandler);
}
close() {
this._toggleEl.classList.remove('lh-active');
this._toggleEl.setAttribute('aria-expanded', 'false');
if (this._menuEl.contains(this._dom.document().activeElement)) {
// Refocus on the tools button if the drop down last had focus
this._toggleEl.focus();
}
this._menuEl.removeEventListener('focusout', this.onMenuFocusOut);
this._dom.document().removeEventListener('keydown', this.onDocumentKeyDown);
}
/**
* @param {HTMLElement} firstFocusElement
*/
open(firstFocusElement) {
if (this._toggleEl.classList.contains('lh-active')) {
// If the drop down is already open focus on the element
firstFocusElement.focus();
} else {
// Wait for drop down transition to complete so options are focusable.
this._menuEl.addEventListener('transitionend', () => {
firstFocusElement.focus();
}, {once: true});
}
this._toggleEl.classList.add('lh-active');
this._toggleEl.setAttribute('aria-expanded', 'true');
this._menuEl.addEventListener('focusout', this.onMenuFocusOut);
this._dom.document().addEventListener('keydown', this.onDocumentKeyDown);
}
/**
* Click handler for tools button.
* @param {Event} e
*/
onToggleClick(e) {
e.preventDefault();
e.stopImmediatePropagation();
if (this._toggleEl.classList.contains('lh-active')) {
this.close();
} else {
this.open(this._getNextMenuItem());
}
}
/**
* Handler for tool button.
* @param {KeyboardEvent} e
*/
onToggleKeydown(e) {
switch (e.code) {
case 'ArrowUp':
e.preventDefault();
this.open(this._getPreviousMenuItem());
break;
case 'ArrowDown':
case 'Enter':
case ' ':
e.preventDefault();
this.open(this._getNextMenuItem());
break;
default:
// no op
}
}
/**
* Handler for tool DropDown.
* @param {KeyboardEvent} e
*/
onMenuKeydown(e) {
const el = /** @type {?HTMLElement} */ (e.target);
switch (e.code) {
case 'ArrowUp':
e.preventDefault();
this._getPreviousMenuItem(el).focus();
break;
case 'ArrowDown':
e.preventDefault();
this._getNextMenuItem(el).focus();
break;
case 'Home':
e.preventDefault();
this._getNextMenuItem().focus();
break;
case 'End':
e.preventDefault();
this._getPreviousMenuItem().focus();
break;
default:
// no op
}
}
/**
* Keydown handler for the document.
* @param {KeyboardEvent} e
*/
onDocumentKeyDown(e) {
if (e.keyCode === 27) { // ESC
this.close();
}
}
/**
* Focus out handler for the drop down menu.
* @param {FocusEvent} e
*/
onMenuFocusOut(e) {
const focusedEl = /** @type {?HTMLElement} */ (e.relatedTarget);
if (!this._menuEl.contains(focusedEl)) {
this.close();
}
}
/**
* @param {Array<Node>} allNodes
* @param {?HTMLElement=} startNode
* @return {HTMLElement}
*/
_getNextSelectableNode(allNodes, startNode) {
const nodes = allNodes.filter(/** @return {node is HTMLElement} */ (node) => {
if (!(node instanceof HTMLElement)) {
return false;
}
// 'Save as Gist' option may be disabled.
if (node.hasAttribute('disabled')) {
return false;
}
// 'Save as Gist' option may have display none.
if (window.getComputedStyle(node).display === 'none') {
return false;
}
return true;
});
let nextIndex = startNode ? (nodes.indexOf(startNode) + 1) : 0;
if (nextIndex >= nodes.length) {
nextIndex = 0;
}
return nodes[nextIndex];
}
/**
* @param {?HTMLElement=} startEl
* @return {HTMLElement}
*/
_getNextMenuItem(startEl) {
const nodes = Array.from(this._menuEl.childNodes);
return this._getNextSelectableNode(nodes, startEl);
}
/**
* @param {?HTMLElement=} startEl
* @return {HTMLElement}
*/
_getPreviousMenuItem(startEl) {
const nodes = Array.from(this._menuEl.childNodes).reverse();
return this._getNextSelectableNode(nodes, startEl);
}
}

View File

@@ -0,0 +1,79 @@
export class ElementScreenshotRenderer {
/**
* Given the location of an element and the sizes of the preview and screenshot,
* compute the absolute positions (in screenshot coordinate scale) of the screenshot content
* and the highlighted rect around the element.
* @param {Rect} elementRectSC
* @param {Size} elementPreviewSizeSC
* @param {Size} screenshotSize
*/
static getScreenshotPositions(elementRectSC: Rect, elementPreviewSizeSC: Size, screenshotSize: Size): {
screenshot: {
left: number;
top: number;
};
clip: {
left: number;
top: number;
};
};
/**
* Render a clipPath SVG element to assist marking the element's rect.
* The elementRect and previewSize are in screenshot coordinate scale.
* @param {DOM} dom
* @param {HTMLElement} maskEl
* @param {{left: number, top: number}} positionClip
* @param {Rect} elementRect
* @param {Size} elementPreviewSize
*/
static renderClipPathInScreenshot(dom: DOM, maskEl: HTMLElement, positionClip: {
left: number;
top: number;
}, elementRect: Rect, elementPreviewSize: Size): void;
/**
* Called by report renderer. Defines a css variable used by any element screenshots
* in the provided report element.
* Allows for multiple Lighthouse reports to be rendered on the page, each with their
* own full page screenshot.
* @param {HTMLElement} el
* @param {LH.Result.FullPageScreenshot['screenshot']} screenshot
*/
static installFullPageScreenshot(el: HTMLElement, screenshot: LH.Result.FullPageScreenshot['screenshot']): void;
/**
* Installs the lightbox elements and wires up click listeners to all .lh-element-screenshot elements.
* @param {InstallOverlayFeatureParams} opts
*/
static installOverlayFeature(opts: InstallOverlayFeatureParams): void;
/**
* Given the size of the element in the screenshot and the total available size of our preview container,
* compute the factor by which we need to zoom out to view the entire element with context.
* @param {Rect} elementRectSC
* @param {Size} renderContainerSizeDC
* @return {number}
*/
static _computeZoomFactor(elementRectSC: Rect, renderContainerSizeDC: Size): number;
/**
* Renders an element with surrounding context from the full page screenshot.
* Used to render both the thumbnail preview in details tables and the full-page screenshot in the lightbox.
* Returns null if element rect is outside screenshot bounds.
* @param {DOM} dom
* @param {LH.Result.FullPageScreenshot['screenshot']} screenshot
* @param {Rect} elementRectSC Region of screenshot to highlight.
* @param {Size} maxRenderSizeDC e.g. maxThumbnailSize or maxLightboxSize.
* @return {Element|null}
*/
static render(dom: DOM, screenshot: LH.Result.FullPageScreenshot['screenshot'], elementRectSC: Rect, maxRenderSizeDC: Size): Element | null;
}
export type DOM = import('./dom.js').DOM;
export type Rect = LH.Audit.Details.Rect;
export type Size = {
width: number;
height: number;
};
export type InstallOverlayFeatureParams = {
dom: DOM;
rootEl: Element;
overlayContainerEl: Element;
fullPageScreenshot: LH.Result.FullPageScreenshot;
};
//# sourceMappingURL=element-screenshot-renderer.d.ts.map

View File

@@ -0,0 +1,287 @@
/**
* @license Copyright 2020 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.
*/
/**
* @fileoverview These functions define {Rect}s and {Size}s using two different coordinate spaces:
* 1. Screenshot coords (SC suffix): where 0,0 is the top left of the screenshot image
* 2. Display coords (DC suffix): that match the CSS pixel coordinate space of the LH report's page.
*/
import {Globals} from './report-globals.js';
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {LH.Audit.Details.Rect} Rect */
/** @typedef {{width: number, height: number}} Size */
/**
* @typedef InstallOverlayFeatureParams
* @property {DOM} dom
* @property {Element} rootEl
* @property {Element} overlayContainerEl
* @property {LH.Result.FullPageScreenshot} fullPageScreenshot
*/
/**
* @param {LH.Result.FullPageScreenshot['screenshot']} screenshot
* @param {LH.Audit.Details.Rect} rect
* @return {boolean}
*/
function screenshotOverlapsRect(screenshot, rect) {
return rect.left <= screenshot.width &&
0 <= rect.right &&
rect.top <= screenshot.height &&
0 <= rect.bottom;
}
/**
* @param {number} value
* @param {number} min
* @param {number} max
*/
function clamp(value, min, max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
/**
* @param {Rect} rect
*/
function getElementRectCenterPoint(rect) {
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
}
export class ElementScreenshotRenderer {
/**
* Given the location of an element and the sizes of the preview and screenshot,
* compute the absolute positions (in screenshot coordinate scale) of the screenshot content
* and the highlighted rect around the element.
* @param {Rect} elementRectSC
* @param {Size} elementPreviewSizeSC
* @param {Size} screenshotSize
*/
static getScreenshotPositions(elementRectSC, elementPreviewSizeSC, screenshotSize) {
const elementRectCenter = getElementRectCenterPoint(elementRectSC);
// Try to center clipped region.
const screenshotLeftVisibleEdge = clamp(
elementRectCenter.x - elementPreviewSizeSC.width / 2,
0, screenshotSize.width - elementPreviewSizeSC.width
);
const screenshotTopVisisbleEdge = clamp(
elementRectCenter.y - elementPreviewSizeSC.height / 2,
0, screenshotSize.height - elementPreviewSizeSC.height
);
return {
screenshot: {
left: screenshotLeftVisibleEdge,
top: screenshotTopVisisbleEdge,
},
clip: {
left: elementRectSC.left - screenshotLeftVisibleEdge,
top: elementRectSC.top - screenshotTopVisisbleEdge,
},
};
}
/**
* Render a clipPath SVG element to assist marking the element's rect.
* The elementRect and previewSize are in screenshot coordinate scale.
* @param {DOM} dom
* @param {HTMLElement} maskEl
* @param {{left: number, top: number}} positionClip
* @param {Rect} elementRect
* @param {Size} elementPreviewSize
*/
static renderClipPathInScreenshot(dom, maskEl, positionClip, elementRect, elementPreviewSize) {
const clipPathEl = dom.find('clipPath', maskEl);
const clipId = `clip-${Globals.getUniqueSuffix()}`;
clipPathEl.id = clipId;
maskEl.style.clipPath = `url(#${clipId})`;
// Normalize values between 0-1.
const top = positionClip.top / elementPreviewSize.height;
const bottom = top + elementRect.height / elementPreviewSize.height;
const left = positionClip.left / elementPreviewSize.width;
const right = left + elementRect.width / elementPreviewSize.width;
const polygonsPoints = [
`0,0 1,0 1,${top} 0,${top}`,
`0,${bottom} 1,${bottom} 1,1 0,1`,
`0,${top} ${left},${top} ${left},${bottom} 0,${bottom}`,
`${right},${top} 1,${top} 1,${bottom} ${right},${bottom}`,
];
for (const points of polygonsPoints) {
const pointEl = dom.createElementNS('http://www.w3.org/2000/svg', 'polygon');
pointEl.setAttribute('points', points);
clipPathEl.append(pointEl);
}
}
/**
* Called by report renderer. Defines a css variable used by any element screenshots
* in the provided report element.
* Allows for multiple Lighthouse reports to be rendered on the page, each with their
* own full page screenshot.
* @param {HTMLElement} el
* @param {LH.Result.FullPageScreenshot['screenshot']} screenshot
*/
static installFullPageScreenshot(el, screenshot) {
el.style.setProperty('--element-screenshot-url', `url('${screenshot.data}')`);
}
/**
* Installs the lightbox elements and wires up click listeners to all .lh-element-screenshot elements.
* @param {InstallOverlayFeatureParams} opts
*/
static installOverlayFeature(opts) {
const {dom, rootEl, overlayContainerEl, fullPageScreenshot} = opts;
const screenshotOverlayClass = 'lh-screenshot-overlay--enabled';
// Don't install the feature more than once.
if (rootEl.classList.contains(screenshotOverlayClass)) return;
rootEl.classList.add(screenshotOverlayClass);
// Add a single listener to the provided element to handle all clicks within (event delegation).
rootEl.addEventListener('click', e => {
const target = /** @type {?HTMLElement} */ (e.target);
if (!target) return;
// Only activate the overlay for clicks on the screenshot *preview* of an element, not the full-size too.
const el = /** @type {?HTMLElement} */ (target.closest('.lh-node > .lh-element-screenshot'));
if (!el) return;
const overlay = dom.createElement('div', 'lh-element-screenshot__overlay');
overlayContainerEl.append(overlay);
// The newly-added overlay has the dimensions we need.
const maxLightboxSize = {
width: overlay.clientWidth * 0.95,
height: overlay.clientHeight * 0.80,
};
const elementRectSC = {
width: Number(el.dataset['rectWidth']),
height: Number(el.dataset['rectHeight']),
left: Number(el.dataset['rectLeft']),
right: Number(el.dataset['rectLeft']) + Number(el.dataset['rectWidth']),
top: Number(el.dataset['rectTop']),
bottom: Number(el.dataset['rectTop']) + Number(el.dataset['rectHeight']),
};
const screenshotElement = ElementScreenshotRenderer.render(
dom,
fullPageScreenshot.screenshot,
elementRectSC,
maxLightboxSize
);
// This would be unexpected here.
// When `screenshotElement` is `null`, there is also no thumbnail element for the user to have clicked to make it this far.
if (!screenshotElement) {
overlay.remove();
return;
}
overlay.append(screenshotElement);
overlay.addEventListener('click', () => overlay.remove());
});
}
/**
* Given the size of the element in the screenshot and the total available size of our preview container,
* compute the factor by which we need to zoom out to view the entire element with context.
* @param {Rect} elementRectSC
* @param {Size} renderContainerSizeDC
* @return {number}
*/
static _computeZoomFactor(elementRectSC, renderContainerSizeDC) {
const targetClipToViewportRatio = 0.75;
const zoomRatioXY = {
x: renderContainerSizeDC.width / elementRectSC.width,
y: renderContainerSizeDC.height / elementRectSC.height,
};
const zoomFactor = targetClipToViewportRatio * Math.min(zoomRatioXY.x, zoomRatioXY.y);
return Math.min(1, zoomFactor);
}
/**
* Renders an element with surrounding context from the full page screenshot.
* Used to render both the thumbnail preview in details tables and the full-page screenshot in the lightbox.
* Returns null if element rect is outside screenshot bounds.
* @param {DOM} dom
* @param {LH.Result.FullPageScreenshot['screenshot']} screenshot
* @param {Rect} elementRectSC Region of screenshot to highlight.
* @param {Size} maxRenderSizeDC e.g. maxThumbnailSize or maxLightboxSize.
* @return {Element|null}
*/
static render(dom, screenshot, elementRectSC, maxRenderSizeDC) {
if (!screenshotOverlapsRect(screenshot, elementRectSC)) {
return null;
}
const tmpl = dom.createComponent('elementScreenshot');
const containerEl = dom.find('div.lh-element-screenshot', tmpl);
containerEl.dataset['rectWidth'] = elementRectSC.width.toString();
containerEl.dataset['rectHeight'] = elementRectSC.height.toString();
containerEl.dataset['rectLeft'] = elementRectSC.left.toString();
containerEl.dataset['rectTop'] = elementRectSC.top.toString();
// Zoom out when highlighted region takes up most of the viewport.
// This provides more context for where on the page this element is.
const zoomFactor = this._computeZoomFactor(elementRectSC, maxRenderSizeDC);
const elementPreviewSizeSC = {
width: maxRenderSizeDC.width / zoomFactor,
height: maxRenderSizeDC.height / zoomFactor,
};
elementPreviewSizeSC.width = Math.min(screenshot.width, elementPreviewSizeSC.width);
elementPreviewSizeSC.height = Math.min(screenshot.height, elementPreviewSizeSC.height);
/* This preview size is either the size of the thumbnail or size of the Lightbox */
const elementPreviewSizeDC = {
width: elementPreviewSizeSC.width * zoomFactor,
height: elementPreviewSizeSC.height * zoomFactor,
};
const positions = ElementScreenshotRenderer.getScreenshotPositions(
elementRectSC,
elementPreviewSizeSC,
{width: screenshot.width, height: screenshot.height}
);
const imageEl = dom.find('div.lh-element-screenshot__image', containerEl);
imageEl.style.width = elementPreviewSizeDC.width + 'px';
imageEl.style.height = elementPreviewSizeDC.height + 'px';
imageEl.style.backgroundPositionY = -(positions.screenshot.top * zoomFactor) + 'px';
imageEl.style.backgroundPositionX = -(positions.screenshot.left * zoomFactor) + 'px';
imageEl.style.backgroundSize =
`${screenshot.width * zoomFactor}px ${screenshot.height * zoomFactor}px`;
const markerEl = dom.find('div.lh-element-screenshot__element-marker', containerEl);
markerEl.style.width = elementRectSC.width * zoomFactor + 'px';
markerEl.style.height = elementRectSC.height * zoomFactor + 'px';
markerEl.style.left = positions.clip.left * zoomFactor + 'px';
markerEl.style.top = positions.clip.top * zoomFactor + 'px';
const maskEl = dom.find('div.lh-element-screenshot__mask', containerEl);
maskEl.style.width = elementPreviewSizeDC.width + 'px';
maskEl.style.height = elementPreviewSizeDC.height + 'px';
ElementScreenshotRenderer.renderClipPathInScreenshot(
dom,
maskEl,
positions.clip,
elementRectSC,
elementPreviewSizeSC
);
return containerEl;
}
}

View File

@@ -0,0 +1,13 @@
/**
* @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.
*/
/** @typedef {import('./dom.js').DOM} DOM */
/**
* @param {DOM} dom
* @param {boolean} [force]
*/
export function toggleDarkTheme(dom: DOM, force?: boolean | undefined): void;
export type DOM = import('./dom.js').DOM;
//# sourceMappingURL=features-util.d.ts.map

View File

@@ -0,0 +1,25 @@
/**
* @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.
*/
/* eslint-env browser */
/** @typedef {import('./dom.js').DOM} DOM */
/**
* @param {DOM} dom
* @param {boolean} [force]
*/
export function toggleDarkTheme(dom, force) {
const el = dom.rootEl;
// This seems unnecessary, but in DevTools, passing "undefined" as the second
// parameter acts like passing "false".
// https://github.com/ChromeDevTools/devtools-frontend/blob/dd6a6d4153647c2a4203c327c595692c5e0a4256/front_end/dom_extension/DOMExtension.js#L809-L819
if (typeof force === 'undefined') {
el.classList.toggle('lh-dark');
} else {
el.classList.toggle('lh-dark', force);
}
}

View File

@@ -0,0 +1,100 @@
export class I18nFormatter {
/**
* @param {LH.Locale} locale
*/
constructor(locale: LH.Locale);
_locale: "en-US" | "en" | "en-AU" | "en-GB" | "en-IE" | "en-SG" | "en-ZA" | "en-IN" | "ar-XB" | "ar" | "bg" | "ca" | "cs" | "da" | "de" | "el" | "en-XL" | "es" | "es-419" | "es-AR" | "es-BO" | "es-BR" | "es-BZ" | "es-CL" | "es-CO" | "es-CR" | "es-CU" | "es-DO" | "es-EC" | "es-GT" | "es-HN" | "es-MX" | "es-NI" | "es-PA" | "es-PE" | "es-PR" | "es-PY" | "es-SV" | "es-US" | "es-UY" | "es-VE" | "fi" | "fil" | "fr" | "he" | "hi" | "hr" | "hu" | "gsw" | "id" | "in" | "it" | "iw" | "ja" | "ko" | "lt" | "lv" | "mo" | "nl" | "nb" | "no" | "pl" | "pt" | "pt-PT" | "ro" | "ru" | "sk" | "sl" | "sr" | "sr-Latn" | "sv" | "ta" | "te" | "th" | "tl" | "tr" | "uk" | "vi" | "zh" | "zh-HK" | "zh-TW";
_cachedNumberFormatters: Map<any, any>;
/**
* @param {number} number
* @param {number|undefined} granularity
* @param {Intl.NumberFormatOptions=} opts
* @return {string}
*/
_formatNumberWithGranularity(number: number, granularity: number | undefined, opts?: Intl.NumberFormatOptions | undefined): string;
/**
* Format number.
* @param {number} number
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed as described
* by the Intl defaults: tinyurl.com/7s67w5x7
* @return {string}
*/
formatNumber(number: number, granularity?: number | undefined): string;
/**
* Format integer.
* Just like {@link formatNumber} but uses a granularity of 1, rounding to the nearest
* whole number.
* @param {number} number
* @return {string}
*/
formatInteger(number: number): string;
/**
* Format percent.
* @param {number} number 01
* @return {string}
*/
formatPercent(number: number): string;
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesToKiB(size: number, granularity?: number | undefined): string;
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesToMiB(size: number, granularity?: number | undefined): string;
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytes(size: number, granularity?: number | undefined): string;
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesWithBestUnit(size: number, granularity?: number | undefined): string;
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatKbps(size: number, granularity?: number | undefined): string;
/**
* @param {number} ms
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatMilliseconds(ms: number, granularity?: number | undefined): string;
/**
* @param {number} ms
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatSeconds(ms: number, granularity?: number | undefined): string;
/**
* Format time.
* @param {string} date
* @return {string}
*/
formatDateTime(date: string): string;
/**
* Converts a time in milliseconds into a duration string, i.e. `1d 2h 13m 52s`
* @param {number} timeInMilliseconds
* @return {string}
*/
formatDuration(timeInMilliseconds: number): string;
}
//# sourceMappingURL=i18n-formatter.d.ts.map

View File

@@ -0,0 +1,263 @@
/**
* @license Copyright 2020 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.
*/
// Not named `NBSP` because that creates a duplicate identifier (util.js).
const NBSP2 = '\xa0';
const KiB = 1024;
const MiB = KiB * KiB;
export class I18nFormatter {
/**
* @param {LH.Locale} locale
*/
constructor(locale) {
// When testing, use a locale with more exciting numeric formatting.
if (locale === 'en-XA') locale = 'de';
this._locale = locale;
this._cachedNumberFormatters = new Map();
}
/**
* @param {number} number
* @param {number|undefined} granularity
* @param {Intl.NumberFormatOptions=} opts
* @return {string}
*/
_formatNumberWithGranularity(number, granularity, opts = {}) {
if (granularity !== undefined) {
const log10 = -Math.log10(granularity);
if (!Number.isInteger(log10)) {
console.warn(`granularity of ${granularity} is invalid. Using 1 instead`);
granularity = 1;
}
if (granularity < 1) {
opts = {...opts};
opts.minimumFractionDigits = opts.maximumFractionDigits = Math.ceil(log10);
}
number = Math.round(number / granularity) * granularity;
// Avoid displaying a negative value that rounds to zero as "0".
if (Object.is(number, -0)) number = 0;
} else if (Math.abs(number) < 0.0005) {
// Also avoids "-0".
number = 0;
}
let formatter;
// eslint-disable-next-line max-len
const cacheKey = [
opts.minimumFractionDigits,
opts.maximumFractionDigits,
opts.style,
opts.unit,
opts.unitDisplay,
this._locale,
].join('');
formatter = this._cachedNumberFormatters.get(cacheKey);
if (!formatter) {
formatter = new Intl.NumberFormat(this._locale, opts);
this._cachedNumberFormatters.set(cacheKey, formatter);
}
return formatter.format(number).replace(' ', NBSP2);
}
/**
* Format number.
* @param {number} number
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed as described
* by the Intl defaults: tinyurl.com/7s67w5x7
* @return {string}
*/
formatNumber(number, granularity) {
return this._formatNumberWithGranularity(number, granularity);
}
/**
* Format integer.
* Just like {@link formatNumber} but uses a granularity of 1, rounding to the nearest
* whole number.
* @param {number} number
* @return {string}
*/
formatInteger(number) {
return this._formatNumberWithGranularity(number, 1);
}
/**
* Format percent.
* @param {number} number 01
* @return {string}
*/
formatPercent(number) {
return new Intl.NumberFormat(this._locale, {style: 'percent'}).format(number);
}
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesToKiB(size, granularity = undefined) {
return this._formatNumberWithGranularity(size / KiB, granularity) + `${NBSP2}KiB`;
}
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesToMiB(size, granularity = undefined) {
return this._formatNumberWithGranularity(size / MiB, granularity) + `${NBSP2}MiB`;
}
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytes(size, granularity = 1) {
return this._formatNumberWithGranularity(size, granularity, {
style: 'unit',
unit: 'byte',
unitDisplay: 'long',
});
}
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatBytesWithBestUnit(size, granularity = undefined) {
if (size >= MiB) return this.formatBytesToMiB(size, granularity);
if (size >= KiB) return this.formatBytesToKiB(size, granularity);
return this._formatNumberWithGranularity(size, granularity, {
style: 'unit',
unit: 'byte',
unitDisplay: 'narrow',
});
}
/**
* @param {number} size
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatKbps(size, granularity = undefined) {
return this._formatNumberWithGranularity(size, granularity, {
style: 'unit',
unit: 'kilobit-per-second',
unitDisplay: 'short',
});
}
/**
* @param {number} ms
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatMilliseconds(ms, granularity = undefined) {
return this._formatNumberWithGranularity(ms, granularity, {
style: 'unit',
unit: 'millisecond',
unitDisplay: 'short',
});
}
/**
* @param {number} ms
* @param {number=} granularity Controls how coarse the displayed value is.
* If undefined, the number will be displayed in full.
* @return {string}
*/
formatSeconds(ms, granularity = undefined) {
return this._formatNumberWithGranularity(ms / 1000, granularity, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
});
}
/**
* Format time.
* @param {string} date
* @return {string}
*/
formatDateTime(date) {
/** @type {Intl.DateTimeFormatOptions} */
const options = {
month: 'short', day: 'numeric', year: 'numeric',
hour: 'numeric', minute: 'numeric', timeZoneName: 'short',
};
// Force UTC if runtime timezone could not be detected.
// See https://github.com/GoogleChrome/lighthouse/issues/1056
// and https://github.com/GoogleChrome/lighthouse/pull/9822
let formatter;
try {
formatter = new Intl.DateTimeFormat(this._locale, options);
} catch (err) {
options.timeZone = 'UTC';
formatter = new Intl.DateTimeFormat(this._locale, options);
}
return formatter.format(new Date(date));
}
/**
* Converts a time in milliseconds into a duration string, i.e. `1d 2h 13m 52s`
* @param {number} timeInMilliseconds
* @return {string}
*/
formatDuration(timeInMilliseconds) {
// There is a proposal for a Intl.DurationFormat.
// https://github.com/tc39/proposal-intl-duration-format
// Until then, we do things a bit more manually.
let timeInSeconds = timeInMilliseconds / 1000;
if (Math.round(timeInSeconds) === 0) {
return 'None';
}
/** @type {Array<string>} */
const parts = [];
/** @type {Record<string, number>} */
const unitToSecondsPer = {
day: 60 * 60 * 24,
hour: 60 * 60,
minute: 60,
second: 1,
};
Object.keys(unitToSecondsPer).forEach(unit => {
const secondsPerUnit = unitToSecondsPer[unit];
const numberOfUnits = Math.floor(timeInSeconds / secondsPerUnit);
if (numberOfUnits > 0) {
timeInSeconds -= numberOfUnits * secondsPerUnit;
const part = this._formatNumberWithGranularity(numberOfUnits, 1, {
style: 'unit',
unit,
unitDisplay: 'narrow',
});
parts.push(part);
}
});
return parts.join(' ');
}
}

47
node_modules/lighthouse/report/renderer/logger.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
* @license
* Copyright 2017 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.
*/
/**
* Logs messages via a UI butter.
*/
export class Logger {
/**
* @param {HTMLElement} element - expected to have id #lh-log
*/
constructor(element: HTMLElement);
el: HTMLElement;
_id: number | undefined;
/**
* Shows a butter bar.
* @param {string} msg The message to show.
* @param {boolean=} autoHide True to hide the message after a duration.
* Default is true.
*/
log(msg: string, autoHide?: boolean | undefined): void;
/**
* @param {string} msg
*/
warn(msg: string): void;
/**
* @param {string} msg
*/
error(msg: string): void;
/**
* Explicitly hides the butter bar.
*/
hide(): void;
}
//# sourceMappingURL=logger.d.ts.map

108
node_modules/lighthouse/report/renderer/logger.js generated vendored Normal file
View File

@@ -0,0 +1,108 @@
/**
* @license
* Copyright 2017 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.
*/
/**
* Logs messages via a UI butter.
*/
export class Logger {
/**
* @param {HTMLElement} element - expected to have id #lh-log
*/
constructor(element) {
this.el = element;
const styleEl = document.createElement('style');
styleEl.textContent = /* css */ `
#lh-log {
position: fixed;
background-color: #323232;
color: #fff;
min-height: 48px;
min-width: 288px;
padding: 16px 24px;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
border-radius: 2px;
margin: 12px;
font-size: 14px;
cursor: default;
transition: transform 0.3s, opacity 0.3s;
transform: translateY(100px);
opacity: 0;
bottom: 0;
left: 0;
z-index: 3;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
#lh-log.lh-show {
opacity: 1;
transform: translateY(0);
}
`;
if (!this.el.parentNode) throw new Error('element needs to be in the DOM');
this.el.parentNode.insertBefore(styleEl, this.el);
this._id = undefined;
}
/**
* Shows a butter bar.
* @param {string} msg The message to show.
* @param {boolean=} autoHide True to hide the message after a duration.
* Default is true.
*/
log(msg, autoHide = true) {
this._id && clearTimeout(this._id);
this.el.textContent = msg;
this.el.classList.add('lh-show');
if (autoHide) {
this._id = setTimeout(() => {
this.el.classList.remove('lh-show');
}, 7000);
}
}
/**
* @param {string} msg
*/
warn(msg) {
this.log('Warning: ' + msg);
}
/**
* @param {string} msg
*/
error(msg) {
this.log(msg);
// Rethrow to make sure it's auditable as an error, but in a setTimeout so page
// recovers gracefully and user can try loading a report again.
setTimeout(() => {
throw new Error(msg);
}, 0);
}
/**
* Explicitly hides the butter bar.
*/
hide() {
this._id && clearTimeout(this._id);
this.el.classList.remove('lh-show');
}
}

19
node_modules/lighthouse/report/renderer/open-tab.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/**
* Opens a new tab to the online viewer and sends the local page's JSON results
* to the online viewer using URL.fragment
* @param {LH.Result} lhr
* @protected
*/
export function openViewer(lhr: LH.Result): Promise<void>;
/**
* Same as openViewer, but uses postMessage.
* @param {LH.Result} lhr
* @protected
*/
export function openViewerAndSendData(lhr: LH.Result): Promise<void>;
/**
* Opens a new tab to the treemap app and sends the JSON results using URL.fragment
* @param {LH.Result} json
*/
export function openTreemap(json: LH.Result): void;
//# sourceMappingURL=open-tab.d.ts.map

143
node_modules/lighthouse/report/renderer/open-tab.js generated vendored Normal file
View File

@@ -0,0 +1,143 @@
/**
* @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.
*/
import {TextEncoding} from './text-encoding.js';
/* eslint-env browser */
function getAppsOrigin() {
const isVercel = window.location.host.endsWith('.vercel.app');
const isDev = new URLSearchParams(window.location.search).has('dev');
if (isVercel) return `https://${window.location.host}/gh-pages`;
if (isDev) return 'http://localhost:7333';
return 'https://googlechrome.github.io/lighthouse';
}
/**
* The popup's window.name is keyed by version+url+fetchTime, so we reuse/select tabs correctly.
* @param {LH.Result} json
* @protected
*/
function computeWindowNameSuffix(json) {
// @ts-expect-error - If this is a v2 LHR, use old `generatedTime`.
const fallbackFetchTime = /** @type {string} */ (json.generatedTime);
const fetchTime = json.fetchTime || fallbackFetchTime;
return `${json.lighthouseVersion}-${json.finalDisplayedUrl}-${fetchTime}`;
}
/**
* Opens a new tab to an external page and sends data using postMessage.
* @param {{lhr: LH.Result} | LH.Treemap.Options} data
* @param {string} url
* @param {string} windowName
* @protected
*/
function openTabAndSendData(data, url, windowName) {
const origin = new URL(url).origin;
// Chrome doesn't allow us to immediately postMessage to a popup right
// after it's created. Normally, we could also listen for the popup window's
// load event, however it is cross-domain and won't fire. Instead, listen
// for a message from the target app saying "I'm open".
window.addEventListener('message', function msgHandler(messageEvent) {
if (messageEvent.origin !== origin) {
return;
}
if (popup && messageEvent.data.opened) {
popup.postMessage(data, origin);
window.removeEventListener('message', msgHandler);
}
});
const popup = window.open(url, windowName);
}
/**
* Opens a new tab to an external page and sends data via base64 encoded url params.
* @param {{lhr: LH.Result} | LH.Treemap.Options} data
* @param {string} url_
* @param {string} windowName
* @protected
*/
async function openTabWithUrlData(data, url_, windowName) {
const url = new URL(url_);
const gzip = Boolean(window.CompressionStream);
url.hash = await TextEncoding.toBase64(JSON.stringify(data), {
gzip,
});
if (gzip) url.searchParams.set('gzip', '1');
window.open(url.toString(), windowName);
}
/**
* Opens a new tab to the online viewer and sends the local page's JSON results
* to the online viewer using URL.fragment
* @param {LH.Result} lhr
* @protected
*/
async function openViewer(lhr) {
const windowName = 'viewer-' + computeWindowNameSuffix(lhr);
const url = getAppsOrigin() + '/viewer/';
await openTabWithUrlData({lhr}, url, windowName);
}
/**
* Same as openViewer, but uses postMessage.
* @param {LH.Result} lhr
* @protected
*/
async function openViewerAndSendData(lhr) {
const windowName = 'viewer-' + computeWindowNameSuffix(lhr);
const url = getAppsOrigin() + '/viewer/';
openTabAndSendData({lhr}, url, windowName);
}
/**
* Opens a new tab to the treemap app and sends the JSON results using URL.fragment
* @param {LH.Result} json
*/
function openTreemap(json) {
const treemapData = json.audits['script-treemap-data'].details;
if (!treemapData) {
throw new Error('no script treemap data found');
}
/** @type {LH.Treemap.Options} */
const treemapOptions = {
lhr: {
mainDocumentUrl: json.mainDocumentUrl,
finalUrl: json.finalUrl,
finalDisplayedUrl: json.finalDisplayedUrl,
audits: {
'script-treemap-data': json.audits['script-treemap-data'],
},
configSettings: {
locale: json.configSettings.locale,
},
},
};
const url = getAppsOrigin() + '/treemap/';
const windowName = 'treemap-' + computeWindowNameSuffix(json);
openTabWithUrlData(treemapOptions, url, windowName);
}
export {
openViewer,
openViewerAndSendData,
openTreemap,
};

View File

@@ -0,0 +1,56 @@
export class PerformanceCategoryRenderer extends CategoryRenderer {
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {!Element}
*/
_renderMetric(audit: LH.ReportResult.AuditRef): Element;
/**
* @param {LH.ReportResult.AuditRef} audit
* @param {number} scale
* @return {!Element}
*/
_renderOpportunity(audit: LH.ReportResult.AuditRef, scale: number): Element;
/**
* Get an audit's wastedMs to sort the opportunity by, and scale the sparkline width
* Opportunities with an error won't have a details object, so MIN_VALUE is returned to keep any
* erroring opportunities last in sort order.
* @param {LH.ReportResult.AuditRef} audit
* @return {number}
*/
_getWastedMs(audit: LH.ReportResult.AuditRef): number;
/**
* Get a link to the interactive scoring calculator with the metric values.
* @param {LH.ReportResult.AuditRef[]} auditRefs
* @return {string}
*/
_getScoringCalculatorHref(auditRefs: LH.ReportResult.AuditRef[]): string;
/**
* For performance, audits with no group should be a diagnostic or opportunity.
* The audit details type will determine which of the two groups an audit is in.
*
* @param {LH.ReportResult.AuditRef} audit
* @return {'load-opportunity'|'diagnostic'|null}
*/
_classifyPerformanceAudit(audit: LH.ReportResult.AuditRef): 'load-opportunity' | 'diagnostic' | null;
/**
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>} groups
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {Element}
* @override
*/
override render(category: LH.ReportResult.Category, groups: {
[x: string]: LH.Result.ReportGroup;
}, options?: {
gatherMode: LH.Result.GatherMode;
} | undefined): Element;
/**
* Render the control to filter the audits by metric. The filtering is done at runtime by CSS only
* @param {LH.ReportResult.AuditRef[]} filterableMetrics
* @param {HTMLDivElement} categoryEl
*/
renderMetricAuditFilter(filterableMetrics: LH.ReportResult.AuditRef[], categoryEl: HTMLDivElement): void;
}
export type DOM = import('./dom.js').DOM;
import { CategoryRenderer } from './category-renderer.js';
//# sourceMappingURL=performance-category-renderer.d.ts.map

View File

@@ -0,0 +1,396 @@
/**
* @license
* Copyright 2018 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.
*/
/** @typedef {import('./dom.js').DOM} DOM */
import {CategoryRenderer} from './category-renderer.js';
import {ReportUtils} from './report-utils.js';
import {Globals} from './report-globals.js';
export class PerformanceCategoryRenderer extends CategoryRenderer {
/**
* @param {LH.ReportResult.AuditRef} audit
* @return {!Element}
*/
_renderMetric(audit) {
const tmpl = this.dom.createComponent('metric');
const element = this.dom.find('.lh-metric', tmpl);
element.id = audit.result.id;
const rating = ReportUtils.calculateRating(audit.result.score, audit.result.scoreDisplayMode);
element.classList.add(`lh-metric--${rating}`);
const titleEl = this.dom.find('.lh-metric__title', tmpl);
titleEl.textContent = audit.result.title;
const valueEl = this.dom.find('.lh-metric__value', tmpl);
valueEl.textContent = audit.result.displayValue || '';
const descriptionEl = this.dom.find('.lh-metric__description', tmpl);
descriptionEl.append(this.dom.convertMarkdownLinkSnippets(audit.result.description));
if (audit.result.scoreDisplayMode === 'error') {
descriptionEl.textContent = '';
valueEl.textContent = 'Error!';
const tooltip = this.dom.createChildOf(descriptionEl, 'span');
tooltip.textContent = audit.result.errorMessage || 'Report error: no metric information';
} else if (audit.result.scoreDisplayMode === 'notApplicable') {
valueEl.textContent = '--';
}
return element;
}
/**
* @param {LH.ReportResult.AuditRef} audit
* @param {number} scale
* @return {!Element}
*/
_renderOpportunity(audit, scale) {
const oppTmpl = this.dom.createComponent('opportunity');
const element = this.populateAuditValues(audit, oppTmpl);
element.id = audit.result.id;
if (!audit.result.details || audit.result.scoreDisplayMode === 'error') {
return element;
}
const details = audit.result.details;
if (details.overallSavingsMs === undefined) {
return element;
}
// Overwrite the displayValue with opportunity's wastedMs
// TODO: normalize this to one tagName.
const displayEl =
this.dom.find('span.lh-audit__display-text, div.lh-audit__display-text', element);
const sparklineWidthPct = `${details.overallSavingsMs / scale * 100}%`;
this.dom.find('div.lh-sparkline__bar', element).style.width = sparklineWidthPct;
displayEl.textContent = Globals.i18n.formatSeconds(details.overallSavingsMs, 0.01);
// Set [title] tooltips
if (audit.result.displayValue) {
const displayValue = audit.result.displayValue;
this.dom.find('div.lh-load-opportunity__sparkline', element).title = displayValue;
displayEl.title = displayValue;
}
return element;
}
/**
* Get an audit's wastedMs to sort the opportunity by, and scale the sparkline width
* Opportunities with an error won't have a details object, so MIN_VALUE is returned to keep any
* erroring opportunities last in sort order.
* @param {LH.ReportResult.AuditRef} audit
* @return {number}
*/
_getWastedMs(audit) {
if (audit.result.details) {
const details = audit.result.details;
if (typeof details.overallSavingsMs !== 'number') {
throw new Error('non-opportunity details passed to _getWastedMs');
}
return details.overallSavingsMs;
} else {
return Number.MIN_VALUE;
}
}
/**
* Get a link to the interactive scoring calculator with the metric values.
* @param {LH.ReportResult.AuditRef[]} auditRefs
* @return {string}
*/
_getScoringCalculatorHref(auditRefs) {
// TODO: filter by !!acronym when dropping renderer support of v7 LHRs.
const metrics = auditRefs.filter(audit => audit.group === 'metrics');
const tti = auditRefs.find(audit => audit.id === 'interactive');
const fci = auditRefs.find(audit => audit.id === 'first-cpu-idle');
const fmp = auditRefs.find(audit => audit.id === 'first-meaningful-paint');
if (tti) metrics.push(tti);
if (fci) metrics.push(fci);
if (fmp) metrics.push(fmp);
/**
* Clamp figure to 2 decimal places
* @param {number} val
* @return {number}
*/
const clampTo2Decimals = val => Math.round(val * 100) / 100;
const metricPairs = metrics.map(audit => {
let value;
if (typeof audit.result.numericValue === 'number') {
value = audit.id === 'cumulative-layout-shift' ?
clampTo2Decimals(audit.result.numericValue) :
Math.round(audit.result.numericValue);
value = value.toString();
} else {
value = 'null';
}
return [audit.acronym || audit.id, value];
});
const paramPairs = [...metricPairs];
if (Globals.reportJson) {
paramPairs.push(['device', Globals.reportJson.configSettings.formFactor]);
paramPairs.push(['version', Globals.reportJson.lighthouseVersion]);
}
const params = new URLSearchParams(paramPairs);
const url = new URL('https://googlechrome.github.io/lighthouse/scorecalc/');
url.hash = params.toString();
return url.href;
}
/**
* For performance, audits with no group should be a diagnostic or opportunity.
* The audit details type will determine which of the two groups an audit is in.
*
* @param {LH.ReportResult.AuditRef} audit
* @return {'load-opportunity'|'diagnostic'|null}
*/
_classifyPerformanceAudit(audit) {
if (audit.group) return null;
if (audit.result.details?.overallSavingsMs !== undefined) {
return 'load-opportunity';
}
return 'diagnostic';
}
/**
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>} groups
* @param {{gatherMode: LH.Result.GatherMode}=} options
* @return {Element}
* @override
*/
render(category, groups, options) {
const strings = Globals.strings;
const element = this.dom.createElement('div', 'lh-category');
element.id = category.id;
element.append(this.renderCategoryHeader(category, groups, options));
// Metrics.
const metricAudits = category.auditRefs.filter(audit => audit.group === 'metrics');
if (metricAudits.length) {
const [metricsGroupEl, metricsFooterEl] = this.renderAuditGroup(groups.metrics);
// Metric descriptions toggle.
const checkboxEl = this.dom.createElement('input', 'lh-metrics-toggle__input');
const checkboxId = `lh-metrics-toggle${Globals.getUniqueSuffix()}`;
checkboxEl.setAttribute('aria-label', 'Toggle the display of metric descriptions');
checkboxEl.type = 'checkbox';
checkboxEl.id = checkboxId;
metricsGroupEl.prepend(checkboxEl);
const metricHeaderEl = this.dom.find('.lh-audit-group__header', metricsGroupEl);
const labelEl = this.dom.createChildOf(metricHeaderEl, 'label', 'lh-metrics-toggle__label');
labelEl.htmlFor = checkboxId;
const showEl = this.dom.createChildOf(labelEl, 'span', 'lh-metrics-toggle__labeltext--show');
const hideEl = this.dom.createChildOf(labelEl, 'span', 'lh-metrics-toggle__labeltext--hide');
showEl.textContent = Globals.strings.expandView;
hideEl.textContent = Globals.strings.collapseView;
const metricsBoxesEl = this.dom.createElement('div', 'lh-metrics-container');
metricsGroupEl.insertBefore(metricsBoxesEl, metricsFooterEl);
metricAudits.forEach(item => {
metricsBoxesEl.append(this._renderMetric(item));
});
// Only add the disclaimer with the score calculator link if the category was rendered with a score gauge.
if (element.querySelector('.lh-gauge__wrapper')) {
const descriptionEl = this.dom.find('.lh-category-header__description', element);
const estValuesEl = this.dom.createChildOf(descriptionEl, 'div', 'lh-metrics__disclaimer');
const disclaimerEl = this.dom.convertMarkdownLinkSnippets(strings.varianceDisclaimer);
estValuesEl.append(disclaimerEl);
// Add link to score calculator.
const calculatorLink = this.dom.createChildOf(estValuesEl, 'a', 'lh-calclink');
calculatorLink.target = '_blank';
calculatorLink.textContent = strings.calculatorLink;
this.dom.safelySetHref(calculatorLink, this._getScoringCalculatorHref(category.auditRefs));
}
metricsGroupEl.classList.add('lh-audit-group--metrics');
element.append(metricsGroupEl);
}
// Filmstrip
const timelineEl = this.dom.createChildOf(element, 'div', 'lh-filmstrip-container');
const thumbnailAudit = category.auditRefs.find(audit => audit.id === 'screenshot-thumbnails');
const thumbnailResult = thumbnailAudit?.result;
if (thumbnailResult?.details) {
timelineEl.id = thumbnailResult.id;
const filmstripEl = this.detailsRenderer.render(thumbnailResult.details);
filmstripEl && timelineEl.append(filmstripEl);
}
// Opportunities
const opportunityAudits = category.auditRefs
.filter(audit => this._classifyPerformanceAudit(audit) === 'load-opportunity')
.filter(audit => !ReportUtils.showAsPassed(audit.result))
.sort((auditA, auditB) => this._getWastedMs(auditB) - this._getWastedMs(auditA));
const filterableMetrics = metricAudits.filter(a => !!a.relevantAudits);
// TODO: only add if there are opportunities & diagnostics rendered.
if (filterableMetrics.length) {
this.renderMetricAuditFilter(filterableMetrics, element);
}
if (opportunityAudits.length) {
// Scale the sparklines relative to savings, minimum 2s to not overstate small savings
const minimumScale = 2000;
const wastedMsValues = opportunityAudits.map(audit => this._getWastedMs(audit));
const maxWaste = Math.max(...wastedMsValues);
const scale = Math.max(Math.ceil(maxWaste / 1000) * 1000, minimumScale);
const [groupEl, footerEl] = this.renderAuditGroup(groups['load-opportunities']);
const tmpl = this.dom.createComponent('opportunityHeader');
this.dom.find('.lh-load-opportunity__col--one', tmpl).textContent =
strings.opportunityResourceColumnLabel;
this.dom.find('.lh-load-opportunity__col--two', tmpl).textContent =
strings.opportunitySavingsColumnLabel;
const headerEl = this.dom.find('.lh-load-opportunity__header', tmpl);
groupEl.insertBefore(headerEl, footerEl);
opportunityAudits.forEach(item =>
groupEl.insertBefore(this._renderOpportunity(item, scale), footerEl));
groupEl.classList.add('lh-audit-group--load-opportunities');
element.append(groupEl);
}
// Diagnostics
const diagnosticAudits = category.auditRefs
.filter(audit => this._classifyPerformanceAudit(audit) === 'diagnostic')
.filter(audit => !ReportUtils.showAsPassed(audit.result))
.sort((a, b) => {
const scoreA = a.result.scoreDisplayMode === 'informative' ? 100 : Number(a.result.score);
const scoreB = b.result.scoreDisplayMode === 'informative' ? 100 : Number(b.result.score);
return scoreA - scoreB;
});
if (diagnosticAudits.length) {
const [groupEl, footerEl] = this.renderAuditGroup(groups['diagnostics']);
diagnosticAudits.forEach(item => groupEl.insertBefore(this.renderAudit(item), footerEl));
groupEl.classList.add('lh-audit-group--diagnostics');
element.append(groupEl);
}
// Passed audits
const passedAudits = category.auditRefs
.filter(audit =>
this._classifyPerformanceAudit(audit) && ReportUtils.showAsPassed(audit.result));
if (!passedAudits.length) return element;
const clumpOpts = {
auditRefs: passedAudits,
groupDefinitions: groups,
};
const passedElem = this.renderClump('passed', clumpOpts);
element.append(passedElem);
// Budgets
/** @type {Array<Element>} */
const budgetTableEls = [];
['performance-budget', 'timing-budget'].forEach((id) => {
const audit = category.auditRefs.find(audit => audit.id === id);
if (audit?.result.details) {
const table = this.detailsRenderer.render(audit.result.details);
if (table) {
table.id = id;
table.classList.add('lh-details', 'lh-details--budget', 'lh-audit');
budgetTableEls.push(table);
}
}
});
if (budgetTableEls.length > 0) {
const [groupEl, footerEl] = this.renderAuditGroup(groups.budgets);
budgetTableEls.forEach(table => groupEl.insertBefore(table, footerEl));
groupEl.classList.add('lh-audit-group--budgets');
element.append(groupEl);
}
return element;
}
/**
* Render the control to filter the audits by metric. The filtering is done at runtime by CSS only
* @param {LH.ReportResult.AuditRef[]} filterableMetrics
* @param {HTMLDivElement} categoryEl
*/
renderMetricAuditFilter(filterableMetrics, categoryEl) {
const metricFilterEl = this.dom.createElement('div', 'lh-metricfilter');
const textEl = this.dom.createChildOf(metricFilterEl, 'span', 'lh-metricfilter__text');
textEl.textContent = Globals.strings.showRelevantAudits;
const filterChoices = /** @type {LH.ReportResult.AuditRef[]} */ ([
({acronym: 'All'}),
...filterableMetrics,
]);
// Form labels need to reference unique IDs, but multiple reports rendered in the same DOM (eg PSI)
// would mean ID conflict. To address this, we 'scope' these radio inputs with a unique suffix.
const uniqSuffix = Globals.getUniqueSuffix();
for (const metric of filterChoices) {
const elemId = `metric-${metric.acronym}-${uniqSuffix}`;
const radioEl = this.dom.createChildOf(metricFilterEl, 'input', 'lh-metricfilter__radio');
radioEl.type = 'radio';
radioEl.name = `metricsfilter-${uniqSuffix}`;
radioEl.id = elemId;
const labelEl = this.dom.createChildOf(metricFilterEl, 'label', 'lh-metricfilter__label');
labelEl.htmlFor = elemId;
labelEl.title = metric.result?.title;
labelEl.textContent = metric.acronym || metric.id;
if (metric.acronym === 'All') {
radioEl.checked = true;
labelEl.classList.add('lh-metricfilter__label--active');
}
categoryEl.append(metricFilterEl);
// Toggle class/hidden state based on filter choice.
radioEl.addEventListener('input', _ => {
for (const elem of categoryEl.querySelectorAll('label.lh-metricfilter__label')) {
elem.classList.toggle('lh-metricfilter__label--active', elem.htmlFor === elemId);
}
categoryEl.classList.toggle('lh-category--filtered', metric.acronym !== 'All');
for (const perfAuditEl of categoryEl.querySelectorAll('div.lh-audit')) {
if (metric.acronym === 'All') {
perfAuditEl.hidden = false;
continue;
}
perfAuditEl.hidden = true;
if (metric.relevantAudits && metric.relevantAudits.includes(perfAuditEl.id)) {
perfAuditEl.hidden = false;
}
}
// Hide groups/clumps if all child audits are also hidden.
const groupEls = categoryEl.querySelectorAll('div.lh-audit-group, details.lh-audit-group');
for (const groupEl of groupEls) {
groupEl.hidden = false;
const childEls = Array.from(groupEl.querySelectorAll('div.lh-audit'));
const areAllHidden = !!childEls.length && childEls.every(auditEl => auditEl.hidden);
groupEl.hidden = areAllHidden;
}
});
}
}
}

View File

@@ -0,0 +1,55 @@
export class PwaCategoryRenderer extends CategoryRenderer {
/**
* Alters SVG id references so multiple instances of an SVG element can coexist
* in a single page. If `svgRoot` has a `<defs>` block, gives all elements defined
* in it unique ids, then updates id references (`<use xlink:href="...">`,
* `fill="url(#...)"`) to the altered ids in all descendents of `svgRoot`.
* @param {SVGElement} svgRoot
*/
static _makeSvgReferencesUnique(svgRoot: SVGElement): void;
/**
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>} [groupDefinitions]
* @return {Element}
*/
render(category: LH.ReportResult.Category, groupDefinitions?: {
[x: string]: import("../../types/lhr/lhr.js").default.ReportGroup;
} | undefined): Element;
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {DocumentFragment}
*/
renderCategoryScore(category: LH.ReportResult.Category, groupDefinitions: Record<string, LH.Result.ReportGroup>): DocumentFragment;
/**
* Returns the group IDs found in auditRefs.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @return {!Set<string>}
*/
_getGroupIds(auditRefs: Array<LH.ReportResult.AuditRef>): Set<string>;
/**
* Returns the group IDs whose audits are all considered passing.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @return {Set<string>}
*/
_getPassingGroupIds(auditRefs: Array<LH.ReportResult.AuditRef>): Set<string>;
/**
* Returns a tooltip string summarizing group pass rates.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {string}
*/
_getGaugeTooltip(auditRefs: Array<LH.ReportResult.AuditRef>, groupDefinitions: Record<string, LH.Result.ReportGroup>): string;
/**
* Render non-manual audits in groups, giving a badge to any group that has
* all passing audits.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Element}
*/
_renderAudits(auditRefs: Array<LH.ReportResult.AuditRef>, groupDefinitions: {
[x: string]: LH.Result.ReportGroup;
}): Element;
}
import { CategoryRenderer } from './category-renderer.js';
//# sourceMappingURL=pwa-category-renderer.d.ts.map

View File

@@ -0,0 +1,186 @@
/**
* @license
* Copyright 2018 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.
*/
import {CategoryRenderer} from './category-renderer.js';
import {ReportUtils} from './report-utils.js';
import {Globals} from './report-globals.js';
export class PwaCategoryRenderer extends CategoryRenderer {
/**
* @param {LH.ReportResult.Category} category
* @param {Object<string, LH.Result.ReportGroup>} [groupDefinitions]
* @return {Element}
*/
render(category, groupDefinitions = {}) {
const categoryElem = this.dom.createElement('div', 'lh-category');
categoryElem.id = category.id;
categoryElem.append(this.renderCategoryHeader(category, groupDefinitions));
const auditRefs = category.auditRefs;
// Regular audits aren't split up into pass/fail/notApplicable clumps, they're
// all put in a top-level clump that isn't expandable/collapsible.
const regularAuditRefs = auditRefs.filter(ref => ref.result.scoreDisplayMode !== 'manual');
const auditsElem = this._renderAudits(regularAuditRefs, groupDefinitions);
categoryElem.append(auditsElem);
// Manual audits are still in a manual clump.
const manualAuditRefs = auditRefs.filter(ref => ref.result.scoreDisplayMode === 'manual');
const manualElem = this.renderClump('manual',
{auditRefs: manualAuditRefs, description: category.manualDescription});
categoryElem.append(manualElem);
return categoryElem;
}
/**
* @param {LH.ReportResult.Category} category
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {DocumentFragment}
*/
renderCategoryScore(category, groupDefinitions) {
// Defer to parent-gauge style if category error.
if (category.score === null) {
return super.renderScoreGauge(category, groupDefinitions);
}
const tmpl = this.dom.createComponent('gaugePwa');
const wrapper = this.dom.find('a.lh-gauge--pwa__wrapper', tmpl);
// Correct IDs in case multiple instances end up in the page.
const svgRoot = tmpl.querySelector('svg');
if (!svgRoot) throw new Error('no SVG element found in PWA score gauge template');
PwaCategoryRenderer._makeSvgReferencesUnique(svgRoot);
const allGroups = this._getGroupIds(category.auditRefs);
const passingGroupIds = this._getPassingGroupIds(category.auditRefs);
if (passingGroupIds.size === allGroups.size) {
wrapper.classList.add('lh-badged--all');
} else {
for (const passingGroupId of passingGroupIds) {
wrapper.classList.add(`lh-badged--${passingGroupId}`);
}
}
this.dom.find('.lh-gauge__label', tmpl).textContent = category.title;
wrapper.title = this._getGaugeTooltip(category.auditRefs, groupDefinitions);
return tmpl;
}
/**
* Returns the group IDs found in auditRefs.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @return {!Set<string>}
*/
_getGroupIds(auditRefs) {
const groupIds = auditRefs.map(ref => ref.group).filter(/** @return {g is string} */ g => !!g);
return new Set(groupIds);
}
/**
* Returns the group IDs whose audits are all considered passing.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @return {Set<string>}
*/
_getPassingGroupIds(auditRefs) {
const uniqueGroupIds = this._getGroupIds(auditRefs);
// Remove any that have a failing audit.
for (const auditRef of auditRefs) {
if (!ReportUtils.showAsPassed(auditRef.result) && auditRef.group) {
uniqueGroupIds.delete(auditRef.group);
}
}
return uniqueGroupIds;
}
/**
* Returns a tooltip string summarizing group pass rates.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Record<string, LH.Result.ReportGroup>} groupDefinitions
* @return {string}
*/
_getGaugeTooltip(auditRefs, groupDefinitions) {
const groupIds = this._getGroupIds(auditRefs);
const tips = [];
for (const groupId of groupIds) {
const groupAuditRefs = auditRefs.filter(ref => ref.group === groupId);
const auditCount = groupAuditRefs.length;
const passedCount = groupAuditRefs.filter(ref => ReportUtils.showAsPassed(ref.result)).length;
const title = groupDefinitions[groupId].title;
tips.push(`${title}: ${passedCount}/${auditCount}`);
}
return tips.join(', ');
}
/**
* Render non-manual audits in groups, giving a badge to any group that has
* all passing audits.
* @param {Array<LH.ReportResult.AuditRef>} auditRefs
* @param {Object<string, LH.Result.ReportGroup>} groupDefinitions
* @return {Element}
*/
_renderAudits(auditRefs, groupDefinitions) {
const auditsElem = this.renderUnexpandableClump(auditRefs, groupDefinitions);
// Add a 'badged' class to group if all audits in that group pass.
const passsingGroupIds = this._getPassingGroupIds(auditRefs);
for (const groupId of passsingGroupIds) {
const groupElem = this.dom.find(`.lh-audit-group--${groupId}`, auditsElem);
groupElem.classList.add('lh-badged');
}
return auditsElem;
}
/**
* Alters SVG id references so multiple instances of an SVG element can coexist
* in a single page. If `svgRoot` has a `<defs>` block, gives all elements defined
* in it unique ids, then updates id references (`<use xlink:href="...">`,
* `fill="url(#...)"`) to the altered ids in all descendents of `svgRoot`.
* @param {SVGElement} svgRoot
*/
static _makeSvgReferencesUnique(svgRoot) {
const defsEl = svgRoot.querySelector('defs');
if (!defsEl) return;
const idSuffix = Globals.getUniqueSuffix();
const elementsToUpdate = defsEl.querySelectorAll('[id]');
for (const el of elementsToUpdate) {
const oldId = el.id;
const newId = `${oldId}-${idSuffix}`;
el.id = newId;
// Update all <use>s.
const useEls = svgRoot.querySelectorAll(`use[href="#${oldId}"]`);
for (const useEl of useEls) {
useEl.setAttribute('href', `#${newId}`);
}
// Update all fill="url(#...)"s.
const fillEls = svgRoot.querySelectorAll(`[fill="url(#${oldId})"]`);
for (const fillEl of fillEls) {
fillEl.setAttribute('fill', `url(#${newId})`);
}
}
}
}

View File

@@ -0,0 +1,21 @@
export type I18nFormatter = import('./i18n-formatter').I18nFormatter;
export class Globals {
/** @type {I18nFormatter} */
static i18n: I18nFormatter;
/** @type {typeof UIStrings} */
static strings: typeof UIStrings;
/** @type {LH.ReportResult | null} */
static reportJson: LH.ReportResult | null;
/**
* @param {{providedStrings: Record<string, string>; i18n: I18nFormatter; reportJson: LH.ReportResult | null}} options
*/
static apply(options: {
providedStrings: Record<string, string>;
i18n: I18nFormatter;
reportJson: LH.ReportResult | null;
}): void;
static getUniqueSuffix(): number;
static resetUniqueSuffix(): void;
}
import { UIStrings } from './report-utils.js';
//# sourceMappingURL=report-globals.d.ts.map

View File

@@ -0,0 +1,49 @@
/**
* @license Copyright 2023 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.
*/
import {UIStrings} from './report-utils.js';
/** @typedef {import('./i18n-formatter').I18nFormatter} I18nFormatter */
let svgSuffix = 0;
class Globals {
/** @type {I18nFormatter} */
// @ts-expect-error: Set in report renderer.
static i18n = null;
/** @type {typeof UIStrings} */
// @ts-expect-error: Set in report renderer.
static strings = {};
/** @type {LH.ReportResult | null} */
static reportJson = null;
/**
* @param {{providedStrings: Record<string, string>; i18n: I18nFormatter; reportJson: LH.ReportResult | null}} options
*/
static apply(options) {
Globals.strings = {
// Set missing renderer strings to default (english) values.
...UIStrings,
...options.providedStrings,
};
Globals.i18n = options.i18n;
Globals.reportJson = options.reportJson;
}
static getUniqueSuffix() {
return svgSuffix++;
}
static resetUniqueSuffix() {
svgSuffix = 0;
}
}
export {
Globals,
};

View File

@@ -0,0 +1,57 @@
export class ReportRenderer {
/**
* @param {DOM} dom
*/
constructor(dom: DOM);
/** @type {DOM} */
_dom: DOM;
/** @type {LH.Renderer.Options} */
_opts: LH.Renderer.Options;
/**
* @param {LH.Result} lhr
* @param {HTMLElement?} rootEl Report root element containing the report
* @param {LH.Renderer.Options=} opts
* @return {!Element}
*/
renderReport(lhr: LH.Result, rootEl: HTMLElement | null, opts?: LH.Renderer.Options | undefined): Element;
/**
* @param {LH.ReportResult} report
* @return {DocumentFragment}
*/
_renderReportTopbar(report: LH.ReportResult): DocumentFragment;
/**
* @return {DocumentFragment}
*/
_renderReportHeader(): DocumentFragment;
/**
* @param {LH.ReportResult} report
* @return {DocumentFragment}
*/
_renderReportFooter(report: LH.ReportResult): DocumentFragment;
/**
* @param {LH.ReportResult} report
* @param {DocumentFragment} footer
*/
_renderMetaBlock(report: LH.ReportResult, footer: DocumentFragment): void;
/**
* Returns a div with a list of top-level warnings, or an empty div if no warnings.
* @param {LH.ReportResult} report
* @return {Node}
*/
_renderReportWarnings(report: LH.ReportResult): Node;
/**
* @param {LH.ReportResult} report
* @param {CategoryRenderer} categoryRenderer
* @param {Record<string, CategoryRenderer>} specificCategoryRenderers
* @return {!DocumentFragment[]}
*/
_renderScoreGauges(report: LH.ReportResult, categoryRenderer: CategoryRenderer, specificCategoryRenderers: Record<string, CategoryRenderer>): DocumentFragment[];
/**
* @param {LH.ReportResult} report
* @return {!DocumentFragment}
*/
_renderReport(report: LH.ReportResult): DocumentFragment;
}
export type DOM = import('./dom.js').DOM;
import { CategoryRenderer } from './category-renderer.js';
//# sourceMappingURL=report-renderer.d.ts.map

View File

@@ -0,0 +1,349 @@
/**
* @license
* Copyright 2017 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.
*
* Dummy text for ensuring report robustness: </script> pre$`post %%LIGHTHOUSE_JSON%%
* (this is handled by terser)
*/
/** @typedef {import('./dom.js').DOM} DOM */
import {CategoryRenderer} from './category-renderer.js';
import {DetailsRenderer} from './details-renderer.js';
import {ElementScreenshotRenderer} from './element-screenshot-renderer.js';
import {I18nFormatter} from './i18n-formatter.js';
import {PerformanceCategoryRenderer} from './performance-category-renderer.js';
import {PwaCategoryRenderer} from './pwa-category-renderer.js';
import {ReportUtils} from './report-utils.js';
import {Globals} from './report-globals.js';
export class ReportRenderer {
/**
* @param {DOM} dom
*/
constructor(dom) {
/** @type {DOM} */
this._dom = dom;
/** @type {LH.Renderer.Options} */
this._opts = {};
}
/**
* @param {LH.Result} lhr
* @param {HTMLElement?} rootEl Report root element containing the report
* @param {LH.Renderer.Options=} opts
* @return {!Element}
*/
renderReport(lhr, rootEl, opts) {
// Allow legacy report rendering API
if (!this._dom.rootEl && rootEl) {
console.warn('Please adopt the new report API in renderer/api.js.');
const closestRoot = rootEl.closest('.lh-root');
if (closestRoot) {
this._dom.rootEl = /** @type {HTMLElement} */ (closestRoot);
} else {
rootEl.classList.add('lh-root', 'lh-vars');
this._dom.rootEl = rootEl;
}
} else if (this._dom.rootEl && rootEl) {
// Handle legacy flow-report case
this._dom.rootEl = rootEl;
}
if (opts) {
this._opts = opts;
}
this._dom.setLighthouseChannel(lhr.configSettings.channel || 'unknown');
const report = ReportUtils.prepareReportResult(lhr);
this._dom.rootEl.textContent = ''; // Remove previous report.
this._dom.rootEl.append(this._renderReport(report));
return this._dom.rootEl;
}
/**
* @param {LH.ReportResult} report
* @return {DocumentFragment}
*/
_renderReportTopbar(report) {
const el = this._dom.createComponent('topbar');
const metadataUrl = this._dom.find('a.lh-topbar__url', el);
metadataUrl.textContent = report.finalDisplayedUrl;
metadataUrl.title = report.finalDisplayedUrl;
this._dom.safelySetHref(metadataUrl, report.finalDisplayedUrl);
return el;
}
/**
* @return {DocumentFragment}
*/
_renderReportHeader() {
const el = this._dom.createComponent('heading');
const domFragment = this._dom.createComponent('scoresWrapper');
const placeholder = this._dom.find('.lh-scores-wrapper-placeholder', el);
placeholder.replaceWith(domFragment);
return el;
}
/**
* @param {LH.ReportResult} report
* @return {DocumentFragment}
*/
_renderReportFooter(report) {
const footer = this._dom.createComponent('footer');
this._renderMetaBlock(report, footer);
this._dom.find('.lh-footer__version_issue', footer).textContent = Globals.strings.footerIssue;
this._dom.find('.lh-footer__version', footer).textContent = report.lighthouseVersion;
return footer;
}
/**
* @param {LH.ReportResult} report
* @param {DocumentFragment} footer
*/
_renderMetaBlock(report, footer) {
const envValues = ReportUtils.getEmulationDescriptions(report.configSettings || {});
const match = report.userAgent.match(/(\w*Chrome\/[\d.]+)/); // \w* to include 'HeadlessChrome'
const chromeVer = Array.isArray(match)
? match[1].replace('/', ' ').replace('Chrome', 'Chromium')
: 'Chromium';
const channel = report.configSettings.channel;
const benchmarkIndex = report.environment.benchmarkIndex.toFixed(0);
const axeVersion = report.environment.credits?.['axe-core'];
const devicesTooltipTextLines = [
`${Globals.strings.runtimeSettingsBenchmark}: ${benchmarkIndex}`,
`${Globals.strings.runtimeSettingsCPUThrottling}: ${envValues.cpuThrottling}`,
];
if (envValues.screenEmulation) {
devicesTooltipTextLines.push(
`${Globals.strings.runtimeSettingsScreenEmulation}: ${envValues.screenEmulation}`);
}
if (axeVersion) {
devicesTooltipTextLines.push(`${Globals.strings.runtimeSettingsAxeVersion}: ${axeVersion}`);
}
// [CSS icon class, textContent, tooltipText]
const metaItems = [
['date',
`Captured at ${Globals.i18n.formatDateTime(report.fetchTime)}`],
['devices',
`${envValues.deviceEmulation} with Lighthouse ${report.lighthouseVersion}`,
devicesTooltipTextLines.join('\n')],
['samples-one',
Globals.strings.runtimeSingleLoad,
Globals.strings.runtimeSingleLoadTooltip],
['stopwatch',
Globals.strings.runtimeAnalysisWindow],
['networkspeed',
`${envValues.summary}`,
`${Globals.strings.runtimeSettingsNetworkThrottling}: ${envValues.networkThrottling}`],
['chrome',
`Using ${chromeVer}` + (channel ? ` with ${channel}` : ''),
`${Globals.strings.runtimeSettingsUANetwork}: "${report.environment.networkUserAgent}"`],
];
const metaItemsEl = this._dom.find('.lh-meta__items', footer);
for (const [iconname, text, tooltip] of metaItems) {
const itemEl = this._dom.createChildOf(metaItemsEl, 'li', 'lh-meta__item');
itemEl.textContent = text;
if (tooltip) {
itemEl.classList.add('lh-tooltip-boundary');
const tooltipEl = this._dom.createChildOf(itemEl, 'div', 'lh-tooltip');
tooltipEl.textContent = tooltip;
}
itemEl.classList.add('lh-report-icon', `lh-report-icon--${iconname}`);
}
}
/**
* Returns a div with a list of top-level warnings, or an empty div if no warnings.
* @param {LH.ReportResult} report
* @return {Node}
*/
_renderReportWarnings(report) {
if (!report.runWarnings || report.runWarnings.length === 0) {
return this._dom.createElement('div');
}
const container = this._dom.createComponent('warningsToplevel');
const message = this._dom.find('.lh-warnings__msg', container);
message.textContent = Globals.strings.toplevelWarningsMessage;
const warnings = [];
for (const warningString of report.runWarnings) {
const warning = this._dom.createElement('li');
warning.append(this._dom.convertMarkdownLinkSnippets(warningString));
warnings.push(warning);
}
this._dom.find('ul', container).append(...warnings);
return container;
}
/**
* @param {LH.ReportResult} report
* @param {CategoryRenderer} categoryRenderer
* @param {Record<string, CategoryRenderer>} specificCategoryRenderers
* @return {!DocumentFragment[]}
*/
_renderScoreGauges(report, categoryRenderer, specificCategoryRenderers) {
// Group gauges in this order: default, pwa, plugins.
const defaultGauges = [];
const customGauges = []; // PWA.
const pluginGauges = [];
for (const category of Object.values(report.categories)) {
const renderer = specificCategoryRenderers[category.id] || categoryRenderer;
const categoryGauge = renderer.renderCategoryScore(
category,
report.categoryGroups || {},
{gatherMode: report.gatherMode}
);
const gaugeWrapperEl = this._dom.find('a.lh-gauge__wrapper, a.lh-fraction__wrapper',
categoryGauge);
if (gaugeWrapperEl) {
this._dom.safelySetHref(gaugeWrapperEl, `#${category.id}`);
// Handle navigation clicks by scrolling to target without changing the page's URL.
// Why? Some report embedding clients have their own routing and updating the location.hash
// can introduce problems. Others may have an unpredictable `<base>` URL which ensures
// navigation to `${baseURL}#categoryid` will be unintended.
gaugeWrapperEl.addEventListener('click', e => {
if (!gaugeWrapperEl.matches('[href^="#"]')) return;
const selector = gaugeWrapperEl.getAttribute('href');
const reportRoot = this._dom.rootEl;
if (!selector || !reportRoot) return;
const destEl = this._dom.find(selector, reportRoot);
e.preventDefault();
destEl.scrollIntoView();
});
this._opts.onPageAnchorRendered?.(gaugeWrapperEl);
}
if (ReportUtils.isPluginCategory(category.id)) {
pluginGauges.push(categoryGauge);
} else if (renderer.renderCategoryScore === categoryRenderer.renderCategoryScore) {
// The renderer for default categories is just the default CategoryRenderer.
// If the functions are equal, then renderer is an instance of CategoryRenderer.
// For example, the PWA category uses PwaCategoryRenderer, which overrides
// CategoryRenderer.renderCategoryScore, so it would fail this check and be placed
// in the customGauges bucket.
defaultGauges.push(categoryGauge);
} else {
customGauges.push(categoryGauge);
}
}
return [...defaultGauges, ...customGauges, ...pluginGauges];
}
/**
* @param {LH.ReportResult} report
* @return {!DocumentFragment}
*/
_renderReport(report) {
Globals.apply({
providedStrings: report.i18n.rendererFormattedStrings,
i18n: new I18nFormatter(report.configSettings.locale),
reportJson: report,
});
const detailsRenderer = new DetailsRenderer(this._dom, {
fullPageScreenshot: report.fullPageScreenshot ?? undefined,
entities: report.entities,
});
const categoryRenderer = new CategoryRenderer(this._dom, detailsRenderer);
/** @type {Record<string, CategoryRenderer>} */
const specificCategoryRenderers = {
performance: new PerformanceCategoryRenderer(this._dom, detailsRenderer),
pwa: new PwaCategoryRenderer(this._dom, detailsRenderer),
};
const headerContainer = this._dom.createElement('div');
headerContainer.append(this._renderReportHeader());
const reportContainer = this._dom.createElement('div', 'lh-container');
const reportSection = this._dom.createElement('div', 'lh-report');
reportSection.append(this._renderReportWarnings(report));
let scoreHeader;
const isSoloCategory = Object.keys(report.categories).length === 1;
if (!isSoloCategory) {
scoreHeader = this._dom.createElement('div', 'lh-scores-header');
} else {
headerContainer.classList.add('lh-header--solo-category');
}
const scoreScale = this._dom.createElement('div');
scoreScale.classList.add('lh-scorescale-wrap');
scoreScale.append(this._dom.createComponent('scorescale'));
if (scoreHeader) {
const scoresContainer = this._dom.find('.lh-scores-container', headerContainer);
scoreHeader.append(
...this._renderScoreGauges(report, categoryRenderer, specificCategoryRenderers));
scoresContainer.append(scoreHeader, scoreScale);
const stickyHeader = this._dom.createElement('div', 'lh-sticky-header');
stickyHeader.append(
...this._renderScoreGauges(report, categoryRenderer, specificCategoryRenderers));
reportContainer.append(stickyHeader);
}
const categories = this._dom.createElement('div', 'lh-categories');
reportSection.append(categories);
const categoryOptions = {gatherMode: report.gatherMode};
for (const category of Object.values(report.categories)) {
const renderer = specificCategoryRenderers[category.id] || categoryRenderer;
// .lh-category-wrapper is full-width and provides horizontal rules between categories.
// .lh-category within has the max-width: var(--report-content-max-width);
const wrapper = renderer.dom.createChildOf(categories, 'div', 'lh-category-wrapper');
wrapper.append(renderer.render(
category,
report.categoryGroups,
categoryOptions
));
}
categoryRenderer.injectFinalScreenshot(categories, report.audits, scoreScale);
const reportFragment = this._dom.createFragment();
if (!this._opts.omitGlobalStyles) {
reportFragment.append(this._dom.createComponent('styles'));
}
if (!this._opts.omitTopbar) {
reportFragment.append(this._renderReportTopbar(report));
}
reportFragment.append(reportContainer);
reportSection.append(this._renderReportFooter(report));
reportContainer.append(headerContainer, reportSection);
if (report.fullPageScreenshot) {
ElementScreenshotRenderer.installFullPageScreenshot(
this._dom.rootEl, report.fullPageScreenshot.screenshot);
}
return reportFragment;
}
}

View File

@@ -0,0 +1,71 @@
export class ReportUIFeatures {
/**
* @param {DOM} dom
* @param {LH.Renderer.Options} opts
*/
constructor(dom: DOM, opts?: LH.Renderer.Options);
/** @type {LH.Result} */
json: LH.Result;
/** @type {DOM} */
_dom: DOM;
_opts: import("../types/report-renderer.js").default.Options;
_topbar: TopbarFeatures | null;
/**
* Handle media query change events.
* @param {MediaQueryList|MediaQueryListEvent} mql
*/
onMediaQueryChange(mql: MediaQueryList | MediaQueryListEvent): void;
/**
* Adds tools button, print, and other functionality to the report. The method
* should be called whenever the report needs to be re-rendered.
* @param {LH.Result} lhr
*/
initFeatures(lhr: LH.Result): void;
_fullPageScreenshot: import("../../types/lhr/lhr.js").default.FullPageScreenshot | undefined;
/**
* @param {{text: string, icon?: string, onClick: () => void}} opts
*/
addButton(opts: {
text: string;
icon?: string;
onClick: () => void;
}): HTMLButtonElement | undefined;
resetUIState(): void;
/**
* Returns the html that recreates this report.
* @return {string}
*/
getReportHtml(): string;
/**
* Save json as a gist. Unimplemented in base UI features.
*/
saveAsGist(): void;
_enableFireworks(): void;
_setupMediaQueryListeners(): void;
/**
* Resets the state of page before capturing the page for export.
* When the user opens the exported HTML page, certain UI elements should
* be in their closed state (not opened) and the templates should be unstamped.
*/
_resetUIState(): void;
_setupThirdPartyFilter(): void;
/**
* @param {Element} rootEl
*/
_setupElementScreenshotOverlay(rootEl: Element): void;
/**
* From a table with URL entries, finds the rows containing third-party URLs
* and returns them.
* @param {HTMLElement[]} rowEls
* @param {string} finalDisplayedUrl
* @return {Array<HTMLElement>}
*/
_getThirdPartyRows(rowEls: HTMLElement[], finalDisplayedUrl: string): Array<HTMLElement>;
/**
* @param {Blob|File} blob
*/
_saveFile(blob: Blob | File): void;
}
export type DOM = import('./dom').DOM;
import { TopbarFeatures } from './topbar-features.js';
//# sourceMappingURL=report-ui-features.d.ts.map

View File

@@ -0,0 +1,373 @@
/**
* @license
* Copyright 2017 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.
*/
/**
* @fileoverview Adds tools button, print, and other dynamic functionality to
* the report.
*/
/** @typedef {import('./dom').DOM} DOM */
import {ElementScreenshotRenderer} from './element-screenshot-renderer.js';
import {toggleDarkTheme} from './features-util.js';
import {openTreemap} from './open-tab.js';
import {TopbarFeatures} from './topbar-features.js';
import {Util} from '../../shared/util.js';
import {getLhrFilenamePrefix} from '../generator/file-namer.js';
import {Globals} from './report-globals.js';
/**
* @param {HTMLTableElement} tableEl
* @return {Array<HTMLElement>}
*/
function getTableRows(tableEl) {
return Array.from(tableEl.tBodies[0].rows);
}
export class ReportUIFeatures {
/**
* @param {DOM} dom
* @param {LH.Renderer.Options} opts
*/
constructor(dom, opts = {}) {
/** @type {LH.Result} */
this.json; // eslint-disable-line no-unused-expressions
/** @type {DOM} */
this._dom = dom;
this._opts = opts;
this._topbar = opts.omitTopbar ? null : new TopbarFeatures(this, dom);
this.onMediaQueryChange = this.onMediaQueryChange.bind(this);
}
/**
* Adds tools button, print, and other functionality to the report. The method
* should be called whenever the report needs to be re-rendered.
* @param {LH.Result} lhr
*/
initFeatures(lhr) {
this.json = lhr;
this._fullPageScreenshot = Util.getFullPageScreenshot(lhr);
if (this._topbar) {
this._topbar.enable(lhr);
this._topbar.resetUIState();
}
this._setupMediaQueryListeners();
this._setupThirdPartyFilter();
this._setupElementScreenshotOverlay(this._dom.rootEl);
// Do not query the system preferences for DevTools - DevTools should only apply dark theme
// if dark is selected in the settings panel.
// TODO: set `disableDarkMode` in devtools and delete this special case.
const disableDarkMode = this._dom.isDevTools() ||
this._opts.disableDarkMode || this._opts.disableAutoDarkModeAndFireworks;
if (!disableDarkMode && window.matchMedia('(prefers-color-scheme: dark)').matches) {
toggleDarkTheme(this._dom, true);
}
// Fireworks!
// To get fireworks you need 100 scores in all core categories, except PWA (because going the PWA route is discretionary).
const fireworksRequiredCategoryIds = ['performance', 'accessibility', 'best-practices', 'seo'];
const scoresAll100 = fireworksRequiredCategoryIds.every(id => {
const cat = lhr.categories[id];
return cat && cat.score === 1;
});
const disableFireworks =
this._opts.disableFireworks || this._opts.disableAutoDarkModeAndFireworks;
if (scoresAll100 && !disableFireworks) {
this._enableFireworks();
// If dark mode is allowed, force it on because it looks so much better.
if (!disableDarkMode) toggleDarkTheme(this._dom, true);
}
// Show the metric descriptions by default when there is an error.
const hasMetricError = lhr.categories.performance && lhr.categories.performance.auditRefs
.some(audit => Boolean(audit.group === 'metrics' && lhr.audits[audit.id].errorMessage));
if (hasMetricError) {
const toggleInputEl = this._dom.find('input.lh-metrics-toggle__input', this._dom.rootEl);
toggleInputEl.checked = true;
}
const showTreemapApp =
this.json.audits['script-treemap-data'] && this.json.audits['script-treemap-data'].details;
if (showTreemapApp) {
this.addButton({
text: Globals.strings.viewTreemapLabel,
icon: 'treemap',
onClick: () => openTreemap(this.json),
});
}
if (this._opts.onViewTrace) {
this.addButton({
text: lhr.configSettings.throttlingMethod === 'simulate' ?
Globals.strings.viewOriginalTraceLabel :
Globals.strings.viewTraceLabel,
onClick: () => this._opts.onViewTrace?.(),
});
}
if (this._opts.getStandaloneReportHTML) {
this._dom.find('a[data-action="save-html"]', this._dom.rootEl).classList.remove('lh-hidden');
}
// Fill in all i18n data.
for (const node of this._dom.findAll('[data-i18n]', this._dom.rootEl)) {
// These strings are guaranteed to (at least) have a default English string in UIStrings,
// so this cannot be undefined as long as `report-ui-features.data-i18n` test passes.
const i18nKey = node.getAttribute('data-i18n');
const i18nAttr = /** @type {keyof typeof Globals.strings} */ (i18nKey);
node.textContent = Globals.strings[i18nAttr];
}
}
/**
* @param {{text: string, icon?: string, onClick: () => void}} opts
*/
addButton(opts) {
// Use qSA directly to as we don't want to throw (if this element is missing).
const metricsEl = this._dom.rootEl.querySelector('.lh-audit-group--metrics');
if (!metricsEl) return;
let buttonsEl = metricsEl.querySelector('.lh-buttons');
if (!buttonsEl) buttonsEl = this._dom.createChildOf(metricsEl, 'div', 'lh-buttons');
const classes = [
'lh-button',
];
if (opts.icon) {
classes.push('lh-report-icon');
classes.push(`lh-report-icon--${opts.icon}`);
}
const buttonEl = this._dom.createChildOf(buttonsEl, 'button', classes.join(' '));
buttonEl.textContent = opts.text;
buttonEl.addEventListener('click', opts.onClick);
return buttonEl;
}
resetUIState() {
if (this._topbar) {
this._topbar.resetUIState();
}
}
/**
* Returns the html that recreates this report.
* @return {string}
*/
getReportHtml() {
if (!this._opts.getStandaloneReportHTML) {
throw new Error('`getStandaloneReportHTML` is not set');
}
this.resetUIState();
return this._opts.getStandaloneReportHTML();
}
/**
* Save json as a gist. Unimplemented in base UI features.
*/
saveAsGist() {
// TODO ?
throw new Error('Cannot save as gist from base report');
}
_enableFireworks() {
const scoresContainer = this._dom.find('.lh-scores-container', this._dom.rootEl);
scoresContainer.classList.add('lh-score100');
}
_setupMediaQueryListeners() {
const mediaQuery = self.matchMedia('(max-width: 500px)');
mediaQuery.addListener(this.onMediaQueryChange);
// Ensure the handler is called on init
this.onMediaQueryChange(mediaQuery);
}
/**
* Resets the state of page before capturing the page for export.
* When the user opens the exported HTML page, certain UI elements should
* be in their closed state (not opened) and the templates should be unstamped.
*/
_resetUIState() {
if (this._topbar) {
this._topbar.resetUIState();
}
}
/**
* Handle media query change events.
* @param {MediaQueryList|MediaQueryListEvent} mql
*/
onMediaQueryChange(mql) {
this._dom.rootEl.classList.toggle('lh-narrow', mql.matches);
}
_setupThirdPartyFilter() {
// Some audits should not display the third party filter option.
const thirdPartyFilterAuditExclusions = [
// These audits deal explicitly with third party resources.
'uses-rel-preconnect',
'third-party-facades',
];
// Some audits should hide third party by default.
const thirdPartyFilterAuditHideByDefault = [
// Only first party resources are actionable.
'legacy-javascript',
];
// Get all tables with a text url column.
const tables = Array.from(this._dom.rootEl.querySelectorAll('table.lh-table'));
const tablesWithUrls = tables
.filter(el =>
el.querySelector('td.lh-table-column--url, td.lh-table-column--source-location'))
.filter(el => {
const containingAudit = el.closest('.lh-audit');
if (!containingAudit) throw new Error('.lh-table not within audit');
return !thirdPartyFilterAuditExclusions.includes(containingAudit.id);
});
tablesWithUrls.forEach((tableEl) => {
const rowEls = getTableRows(tableEl);
const nonSubItemRows = rowEls.filter(rowEl => !rowEl.classList.contains('lh-sub-item-row'));
const thirdPartyRowEls = this._getThirdPartyRows(nonSubItemRows,
Util.getFinalDisplayedUrl(this.json));
// Entity-grouped tables don't have zebra lines.
const hasZebraStyle = rowEls.some(rowEl => rowEl.classList.contains('lh-row--even'));
// create input box
const filterTemplate = this._dom.createComponent('3pFilter');
const filterInput = this._dom.find('input', filterTemplate);
filterInput.addEventListener('change', e => {
const shouldHideThirdParty = e.target instanceof HTMLInputElement && !e.target.checked;
let even = true;
let rowEl = nonSubItemRows[0];
while (rowEl) {
const shouldHide = shouldHideThirdParty && thirdPartyRowEls.includes(rowEl);
// Iterate subsequent associated sub item rows.
do {
rowEl.classList.toggle('lh-row--hidden', shouldHide);
if (hasZebraStyle) {
// Adjust for zebra styling.
rowEl.classList.toggle('lh-row--even', !shouldHide && even);
rowEl.classList.toggle('lh-row--odd', !shouldHide && !even);
}
rowEl = /** @type {HTMLElement} */ (rowEl.nextElementSibling);
} while (rowEl && rowEl.classList.contains('lh-sub-item-row'));
if (!shouldHide) even = !even;
}
});
// thirdPartyRowEls contains both heading and item rows.
// Filter out heading rows to get third party resource count.
const thirdPartyResourceCount = thirdPartyRowEls.filter(
rowEl => !rowEl.classList.contains('lh-row--group')).length;
this._dom.find('.lh-3p-filter-count', filterTemplate).textContent =
`${thirdPartyResourceCount}`;
this._dom.find('.lh-3p-ui-string', filterTemplate).textContent =
Globals.strings.thirdPartyResourcesLabel;
const allThirdParty = thirdPartyRowEls.length === nonSubItemRows.length;
const allFirstParty = !thirdPartyRowEls.length;
// If all or none of the rows are 3rd party, hide the control.
if (allThirdParty || allFirstParty) {
this._dom.find('div.lh-3p-filter', filterTemplate).hidden = true;
}
// Add checkbox to the DOM.
if (!tableEl.parentNode) return; // Keep tsc happy.
tableEl.parentNode.insertBefore(filterTemplate, tableEl);
// Hide third-party rows for some audits by default.
const containingAudit = tableEl.closest('.lh-audit');
if (!containingAudit) throw new Error('.lh-table not within audit');
if (thirdPartyFilterAuditHideByDefault.includes(containingAudit.id) && !allThirdParty) {
filterInput.click();
}
});
}
/**
* @param {Element} rootEl
*/
_setupElementScreenshotOverlay(rootEl) {
if (!this._fullPageScreenshot) return;
ElementScreenshotRenderer.installOverlayFeature({
dom: this._dom,
rootEl: rootEl,
overlayContainerEl: rootEl,
fullPageScreenshot: this._fullPageScreenshot,
});
}
/**
* From a table with URL entries, finds the rows containing third-party URLs
* and returns them.
* @param {HTMLElement[]} rowEls
* @param {string} finalDisplayedUrl
* @return {Array<HTMLElement>}
*/
_getThirdPartyRows(rowEls, finalDisplayedUrl) {
const finalDisplayedUrlRootDomain = Util.getRootDomain(finalDisplayedUrl);
const firstPartyEntityName = this.json.entities?.find(e => e.isFirstParty === true)?.name;
/** @type {Array<HTMLElement>} */
const thirdPartyRowEls = [];
for (const rowEl of rowEls) {
if (firstPartyEntityName) {
// We rely on entity-classification for new LHRs that support it.
if (!rowEl.dataset.entity || rowEl.dataset.entity === firstPartyEntityName) continue;
} else {
// Without 10.0's entity classification, fallback to the older root domain-based filtering.
const urlItem = rowEl.querySelector('div.lh-text__url');
if (!urlItem) continue;
const datasetUrl = urlItem.dataset.url;
if (!datasetUrl) continue;
const isThirdParty = Util.getRootDomain(datasetUrl) !== finalDisplayedUrlRootDomain;
if (!isThirdParty) continue;
}
thirdPartyRowEls.push(rowEl);
}
return thirdPartyRowEls;
}
/**
* @param {Blob|File} blob
*/
_saveFile(blob) {
const ext = blob.type.match('json') ? '.json' : '.html';
const filename = getLhrFilenamePrefix({
finalDisplayedUrl: Util.getFinalDisplayedUrl(this.json),
fetchTime: this.json.fetchTime,
}) + ext;
if (this._opts.onSaveFileOverride) {
this._opts.onSaveFileOverride(blob, filename);
} else {
this._dom.saveFile(blob, filename);
}
}
}

View File

@@ -0,0 +1,138 @@
export class ReportUtils {
/**
* Returns a new LHR that's reshaped for slightly better ergonomics within the report rendereer.
* Also, sets up the localized UI strings used within renderer and makes changes to old LHRs to be
* compatible with current renderer.
* The LHR passed in is not mutated.
* TODO(team): we all agree the LHR shape change is technical debt we should fix
* @param {LH.Result} lhr
* @return {LH.ReportResult}
*/
static prepareReportResult(lhr: LH.Result): LH.ReportResult;
/**
* Given an audit's details, identify and return a URL locator function that
* can be called later with an `item` to extract the URL of it.
* @param {LH.FormattedIcu<LH.Audit.Details.TableColumnHeading[]>} headings
* @return {((item: LH.FormattedIcu<LH.Audit.Details.TableItem>) => string|undefined)=}
*/
static getUrlLocatorFn(headings: LH.FormattedIcu<LH.Audit.Details.TableColumnHeading[]>): ((item: LH.FormattedIcu<LH.Audit.Details.TableItem>) => string | undefined) | undefined;
/**
* Mark TableItems/OpportunityItems with entity names.
* @param {LH.Result.Entities} entities
* @param {LH.FormattedIcu<LH.Audit.Details.Opportunity|LH.Audit.Details.Table>} details
*/
static classifyEntities(entities: LH.Result.Entities, details: LH.FormattedIcu<LH.Audit.Details.Opportunity | LH.Audit.Details.Table>): void;
/**
* Returns a comparator created from the supplied list of keys
* @param {Array<string>} sortedBy
* @return {((a: LH.Audit.Details.TableItem, b: LH.Audit.Details.TableItem) => number)}
*/
static getTableItemSortComparator(sortedBy: Array<string>): (a: LH.Audit.Details.TableItem, b: LH.Audit.Details.TableItem) => number;
/**
* @param {LH.Result['configSettings']} settings
* @return {!{deviceEmulation: string, screenEmulation?: string, networkThrottling: string, cpuThrottling: string, summary: string}}
*/
static getEmulationDescriptions(settings: LH.Result['configSettings']): {
deviceEmulation: string;
screenEmulation?: string | undefined;
networkThrottling: string;
cpuThrottling: string;
summary: string;
};
/**
* Used to determine if the "passed" for the purposes of showing up in the "failed" or "passed"
* sections of the report.
*
* @param {{score: (number|null), scoreDisplayMode: string}} audit
* @return {boolean}
*/
static showAsPassed(audit: {
score: (number | null);
scoreDisplayMode: string;
}): boolean;
/**
* Convert a score to a rating label.
* TODO: Return `'error'` for `score === null && !scoreDisplayMode`.
*
* @param {number|null} score
* @param {string=} scoreDisplayMode
* @return {string}
*/
static calculateRating(score: number | null, scoreDisplayMode?: string | undefined): string;
/**
* @param {LH.ReportResult.Category} category
*/
static calculateCategoryFraction(category: LH.ReportResult.Category): {
numPassed: number;
numPassableAudits: number;
numInformative: number;
totalWeight: number;
};
/**
* @param {string} categoryId
*/
static isPluginCategory(categoryId: string): boolean;
/**
* @param {LH.Result.GatherMode} gatherMode
*/
static shouldDisplayAsFraction(gatherMode: LH.Result.GatherMode): boolean;
}
export namespace UIStrings {
const varianceDisclaimer: string;
const calculatorLink: string;
const showRelevantAudits: string;
const opportunityResourceColumnLabel: string;
const opportunitySavingsColumnLabel: string;
const errorMissingAuditInfo: string;
const errorLabel: string;
const warningHeader: string;
const warningAuditsGroupTitle: string;
const passedAuditsGroupTitle: string;
const notApplicableAuditsGroupTitle: string;
const manualAuditsGroupTitle: string;
const toplevelWarningsMessage: string;
const crcInitialNavigation: string;
const crcLongestDurationLabel: string;
const snippetExpandButtonLabel: string;
const snippetCollapseButtonLabel: string;
const lsPerformanceCategoryDescription: string;
const labDataTitle: string;
const thirdPartyResourcesLabel: string;
const viewTreemapLabel: string;
const viewTraceLabel: string;
const viewOriginalTraceLabel: string;
const dropdownPrintSummary: string;
const dropdownPrintExpanded: string;
const dropdownCopyJSON: string;
const dropdownSaveHTML: string;
const dropdownSaveJSON: string;
const dropdownViewer: string;
const dropdownSaveGist: string;
const dropdownDarkTheme: string;
const runtimeSettingsDevice: string;
const runtimeSettingsNetworkThrottling: string;
const runtimeSettingsCPUThrottling: string;
const runtimeSettingsUANetwork: string;
const runtimeSettingsBenchmark: string;
const runtimeSettingsAxeVersion: string;
const runtimeSettingsScreenEmulation: string;
const footerIssue: string;
const runtimeNoEmulation: string;
const runtimeMobileEmulation: string;
const runtimeDesktopEmulation: string;
const runtimeUnknown: string;
const runtimeSingleLoad: string;
const runtimeAnalysisWindow: string;
const runtimeSingleLoadTooltip: string;
const throttlingProvided: string;
const show: string;
const hide: string;
const expandView: string;
const collapseView: string;
const runtimeSlow4g: string;
const runtimeCustom: string;
const firstPartyChipLabel: string;
const openInANewTabTooltip: string;
const unattributable: string;
}
//# sourceMappingURL=report-utils.d.ts.map

480
node_modules/lighthouse/report/renderer/report-utils.js generated vendored Normal file
View File

@@ -0,0 +1,480 @@
/**
* @license Copyright 2023 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.
*/
import {Util} from '../../shared/util.js';
import {Globals} from './report-globals.js';
import {upgradeLhrForCompatibility} from '../../core/lib/lighthouse-compatibility.js';
const RATINGS = Util.RATINGS;
class ReportUtils {
/**
* Returns a new LHR that's reshaped for slightly better ergonomics within the report rendereer.
* Also, sets up the localized UI strings used within renderer and makes changes to old LHRs to be
* compatible with current renderer.
* The LHR passed in is not mutated.
* TODO(team): we all agree the LHR shape change is technical debt we should fix
* @param {LH.Result} lhr
* @return {LH.ReportResult}
*/
static prepareReportResult(lhr) {
// If any mutations happen to the report within the renderers, we want the original object untouched
const clone = /** @type {LH.ReportResult} */ (JSON.parse(JSON.stringify(lhr)));
upgradeLhrForCompatibility(clone);
for (const audit of Object.values(clone.audits)) {
// Attach table/opportunity items with entity information.
if (audit.details) {
if (audit.details.type === 'opportunity' || audit.details.type === 'table') {
if (!audit.details.isEntityGrouped && clone.entities) {
ReportUtils.classifyEntities(clone.entities, audit.details);
}
}
}
}
// For convenience, smoosh all AuditResults into their auditRef (which has just weight & group)
if (typeof clone.categories !== 'object') throw new Error('No categories provided.');
/** @type {Map<string, Array<LH.ReportResult.AuditRef>>} */
const relevantAuditToMetricsMap = new Map();
for (const category of Object.values(clone.categories)) {
// Make basic lookup table for relevantAudits
category.auditRefs.forEach(metricRef => {
if (!metricRef.relevantAudits) return;
metricRef.relevantAudits.forEach(auditId => {
const arr = relevantAuditToMetricsMap.get(auditId) || [];
arr.push(metricRef);
relevantAuditToMetricsMap.set(auditId, arr);
});
});
category.auditRefs.forEach(auditRef => {
const result = clone.audits[auditRef.id];
auditRef.result = result;
// Attach any relevantMetric auditRefs
if (relevantAuditToMetricsMap.has(auditRef.id)) {
auditRef.relevantMetrics = relevantAuditToMetricsMap.get(auditRef.id);
}
// attach the stackpacks to the auditRef object
if (clone.stackPacks) {
clone.stackPacks.forEach(pack => {
if (pack.descriptions[auditRef.id]) {
auditRef.stackPacks = auditRef.stackPacks || [];
auditRef.stackPacks.push({
title: pack.title,
iconDataURL: pack.iconDataURL,
description: pack.descriptions[auditRef.id],
});
}
});
}
});
}
return clone;
}
/**
* Given an audit's details, identify and return a URL locator function that
* can be called later with an `item` to extract the URL of it.
* @param {LH.FormattedIcu<LH.Audit.Details.TableColumnHeading[]>} headings
* @return {((item: LH.FormattedIcu<LH.Audit.Details.TableItem>) => string|undefined)=}
*/
static getUrlLocatorFn(headings) {
// The most common type, valueType=url.
const urlKey = headings.find(heading => heading.valueType === 'url')?.key;
if (urlKey && typeof urlKey === 'string') {
// Return a function that extracts item.url.
return (item) => {
const url = item[urlKey];
if (typeof url === 'string') return url;
};
}
// The second common type, valueType=source-location.
const srcLocationKey = headings.find(heading => heading.valueType === 'source-location')?.key;
if (srcLocationKey) {
// Return a function that extracts item.source.url.
return (item) => {
const sourceLocation = item[srcLocationKey];
if (typeof sourceLocation === 'object' && sourceLocation.type === 'source-location') {
return sourceLocation.url;
}
};
}
// More specific tests go here, as we need to identify URLs in more audits.
}
/**
* Mark TableItems/OpportunityItems with entity names.
* @param {LH.Result.Entities} entities
* @param {LH.FormattedIcu<LH.Audit.Details.Opportunity|LH.Audit.Details.Table>} details
*/
static classifyEntities(entities, details) {
// If details.items are already marked with entity attribute during an audit, nothing to do here.
const {items, headings} = details;
if (!items.length || items.some(item => item.entity)) return;
// Identify a URL-locator function that we could call against each item to get its URL.
const urlLocatorFn = ReportUtils.getUrlLocatorFn(headings);
if (!urlLocatorFn) return;
for (const item of items) {
const url = urlLocatorFn(item);
if (!url) continue;
let origin = '';
try {
// Non-URLs can appear in valueType: url columns, like 'Unattributable'
origin = Util.parseURL(url).origin;
} catch {}
if (!origin) continue;
const entity = entities.find(e => e.origins.includes(origin));
if (entity) item.entity = entity.name;
}
}
/**
* Returns a comparator created from the supplied list of keys
* @param {Array<string>} sortedBy
* @return {((a: LH.Audit.Details.TableItem, b: LH.Audit.Details.TableItem) => number)}
*/
static getTableItemSortComparator(sortedBy) {
return (a, b) => {
for (const key of sortedBy) {
const aVal = a[key];
const bVal = b[key];
if (typeof aVal !== typeof bVal || !['number', 'string'].includes(typeof aVal)) {
console.warn(`Warning: Attempting to sort unsupported value type: ${key}.`);
}
if (typeof aVal === 'number' && typeof bVal === 'number' && aVal !== bVal) {
return bVal - aVal;
}
if (typeof aVal === 'string' && typeof bVal === 'string' && aVal !== bVal) {
return aVal.localeCompare(bVal);
}
}
return 0;
};
}
/**
* @param {LH.Result['configSettings']} settings
* @return {!{deviceEmulation: string, screenEmulation?: string, networkThrottling: string, cpuThrottling: string, summary: string}}
*/
static getEmulationDescriptions(settings) {
let cpuThrottling;
let networkThrottling;
let summary;
const throttling = settings.throttling;
const i18n = Globals.i18n;
const strings = Globals.strings;
switch (settings.throttlingMethod) {
case 'provided':
summary = networkThrottling = cpuThrottling = strings.throttlingProvided;
break;
case 'devtools': {
const {cpuSlowdownMultiplier, requestLatencyMs} = throttling;
// eslint-disable-next-line max-len
cpuThrottling = `${i18n.formatNumber(cpuSlowdownMultiplier)}x slowdown (DevTools)`;
networkThrottling = `${i18n.formatMilliseconds(requestLatencyMs)} HTTP RTT, ` +
`${i18n.formatKbps(throttling.downloadThroughputKbps)} down, ` +
`${i18n.formatKbps(throttling.uploadThroughputKbps)} up (DevTools)`;
const isSlow4G = () => {
return requestLatencyMs === 150 * 3.75 &&
throttling.downloadThroughputKbps === 1.6 * 1024 * 0.9 &&
throttling.uploadThroughputKbps === 750 * 0.9;
};
summary = isSlow4G() ? strings.runtimeSlow4g : strings.runtimeCustom;
break;
}
case 'simulate': {
const {cpuSlowdownMultiplier, rttMs, throughputKbps} = throttling;
// eslint-disable-next-line max-len
cpuThrottling = `${i18n.formatNumber(cpuSlowdownMultiplier)}x slowdown (Simulated)`;
networkThrottling = `${i18n.formatMilliseconds(rttMs)} TCP RTT, ` +
`${i18n.formatKbps(throughputKbps)} throughput (Simulated)`;
const isSlow4G = () => {
return rttMs === 150 && throughputKbps === 1.6 * 1024;
};
summary = isSlow4G() ?
strings.runtimeSlow4g : strings.runtimeCustom;
break;
}
default:
summary = cpuThrottling = networkThrottling = strings.runtimeUnknown;
}
// devtools-entry.js always sets `screenEmulation.disabled` when using mobile emulation,
// because we handle the emulation outside of Lighthouse. Since the screen truly is emulated
// as a mobile device, ignore `.disabled` in devtools and just check the form factor
const isScreenEmulationDisabled = settings.channel === 'devtools' ?
false :
settings.screenEmulation.disabled;
const isScreenEmulationMobile = settings.channel === 'devtools' ?
settings.formFactor === 'mobile' :
settings.screenEmulation.mobile;
let deviceEmulation = strings.runtimeMobileEmulation;
if (isScreenEmulationDisabled) {
deviceEmulation = strings.runtimeNoEmulation;
} else if (!isScreenEmulationMobile) {
deviceEmulation = strings.runtimeDesktopEmulation;
}
const screenEmulation = isScreenEmulationDisabled ?
undefined :
// eslint-disable-next-line max-len
`${settings.screenEmulation.width}x${settings.screenEmulation.height}, DPR ${settings.screenEmulation.deviceScaleFactor}`;
return {
deviceEmulation,
screenEmulation,
cpuThrottling,
networkThrottling,
summary,
};
}
/**
* Used to determine if the "passed" for the purposes of showing up in the "failed" or "passed"
* sections of the report.
*
* @param {{score: (number|null), scoreDisplayMode: string}} audit
* @return {boolean}
*/
static showAsPassed(audit) {
switch (audit.scoreDisplayMode) {
case 'manual':
case 'notApplicable':
return true;
case 'error':
case 'informative':
return false;
case 'numeric':
case 'binary':
default:
return Number(audit.score) >= RATINGS.PASS.minScore;
}
}
/**
* Convert a score to a rating label.
* TODO: Return `'error'` for `score === null && !scoreDisplayMode`.
*
* @param {number|null} score
* @param {string=} scoreDisplayMode
* @return {string}
*/
static calculateRating(score, scoreDisplayMode) {
// Handle edge cases first, manual and not applicable receive 'pass', errored audits receive 'error'
if (scoreDisplayMode === 'manual' || scoreDisplayMode === 'notApplicable') {
return RATINGS.PASS.label;
} else if (scoreDisplayMode === 'error') {
return RATINGS.ERROR.label;
} else if (score === null) {
return RATINGS.FAIL.label;
}
// At this point, we're rating a standard binary/numeric audit
let rating = RATINGS.FAIL.label;
if (score >= RATINGS.PASS.minScore) {
rating = RATINGS.PASS.label;
} else if (score >= RATINGS.AVERAGE.minScore) {
rating = RATINGS.AVERAGE.label;
}
return rating;
}
/**
* @param {LH.ReportResult.Category} category
*/
static calculateCategoryFraction(category) {
let numPassableAudits = 0;
let numPassed = 0;
let numInformative = 0;
let totalWeight = 0;
for (const auditRef of category.auditRefs) {
const auditPassed = ReportUtils.showAsPassed(auditRef.result);
// Don't count the audit if it's manual, N/A, or isn't displayed.
if (auditRef.group === 'hidden' ||
auditRef.result.scoreDisplayMode === 'manual' ||
auditRef.result.scoreDisplayMode === 'notApplicable') {
continue;
} else if (auditRef.result.scoreDisplayMode === 'informative') {
if (!auditPassed) {
++numInformative;
}
continue;
}
++numPassableAudits;
totalWeight += auditRef.weight;
if (auditPassed) numPassed++;
}
return {numPassed, numPassableAudits, numInformative, totalWeight};
}
/**
* @param {string} categoryId
*/
static isPluginCategory(categoryId) {
return categoryId.startsWith('lighthouse-plugin-');
}
/**
* @param {LH.Result.GatherMode} gatherMode
*/
static shouldDisplayAsFraction(gatherMode) {
return gatherMode === 'timespan' || gatherMode === 'snapshot';
}
}
/**
* Report-renderer-specific strings.
*/
const UIStrings = {
/** Disclaimer shown to users below the metric values (First Contentful Paint, Time to Interactive, etc) to warn them that the numbers they see will likely change slightly the next time they run Lighthouse. */
varianceDisclaimer: 'Values are estimated and may vary. The [performance score is calculated](https://developer.chrome.com/docs/lighthouse/performance/performance-scoring/) directly from these metrics.',
/** Text link pointing to an interactive calculator that explains Lighthouse scoring. The link text should be fairly short. */
calculatorLink: 'See calculator.',
/** Label preceding a radio control for filtering the list of audits. The radio choices are various performance metrics (FCP, LCP, TBT), and if chosen, the audits in the report are hidden if they are not relevant to the selected metric. */
showRelevantAudits: 'Show audits relevant to:',
/** Column heading label for the listing of opportunity audits. Each audit title represents an opportunity. There are only 2 columns, so no strict character limit. */
opportunityResourceColumnLabel: 'Opportunity',
/** Column heading label for the estimated page load savings of opportunity audits. Estimated Savings is the total amount of time (in seconds) that Lighthouse computed could be reduced from the total page load time, if the suggested action is taken. There are only 2 columns, so no strict character limit. */
opportunitySavingsColumnLabel: 'Estimated Savings',
/** An error string displayed next to a particular audit when it has errored, but not provided any specific error message. */
errorMissingAuditInfo: 'Report error: no audit information',
/** A label, shown next to an audit title or metric title, indicating that there was an error computing it. The user can hover on the label to reveal a tooltip with the extended error message. Translation should be short (< 20 characters). */
errorLabel: 'Error!',
/** This label is shown above a bulleted list of warnings. It is shown directly below an audit that produced warnings. Warnings describe situations the user should be aware of, as Lighthouse was unable to complete all the work required on this audit. For example, The 'Unable to decode image (biglogo.jpg)' warning may show up below an image encoding audit. */
warningHeader: 'Warnings: ',
/** Section heading shown above a list of passed audits that contain warnings. Audits under this section do not negatively impact the score, but Lighthouse has generated some potentially actionable suggestions that should be reviewed. This section is expanded by default and displays after the failing audits. */
warningAuditsGroupTitle: 'Passed audits but with warnings',
/** Section heading shown above a list of audits that are passing. 'Passed' here refers to a passing grade. This section is collapsed by default, as the user should be focusing on the failed audits instead. Users can click this heading to reveal the list. */
passedAuditsGroupTitle: 'Passed audits',
/** Section heading shown above a list of audits that do not apply to the page. For example, if an audit is 'Are images optimized?', but the page has no images on it, the audit will be marked as not applicable. This is neither passing or failing. This section is collapsed by default, as the user should be focusing on the failed audits instead. Users can click this heading to reveal the list. */
notApplicableAuditsGroupTitle: 'Not applicable',
/** Section heading shown above a list of audits that were not computed by Lighthouse. They serve as a list of suggestions for the user to go and manually check. For example, Lighthouse can't automate testing cross-browser compatibility, so that is listed within this section, so the user is reminded to test it themselves. This section is collapsed by default, as the user should be focusing on the failed audits instead. Users can click this heading to reveal the list. */
manualAuditsGroupTitle: 'Additional items to manually check',
/** Label shown preceding any important warnings that may have invalidated the entire report. For example, if the user has Chrome extensions installed, they may add enough performance overhead that Lighthouse's performance metrics are unreliable. If shown, this will be displayed at the top of the report UI. */
toplevelWarningsMessage: 'There were issues affecting this run of Lighthouse:',
/** String of text shown in a graphical representation of the flow of network requests for the web page. This label represents the initial network request that fetches an HTML page. This navigation may be redirected (eg. Initial navigation to http://example.com redirects to https://www.example.com). */
crcInitialNavigation: 'Initial Navigation',
/** Label of value shown in the summary of critical request chains. Refers to the total amount of time (milliseconds) of the longest critical path chain/sequence of network requests. Example value: 2310 ms */
crcLongestDurationLabel: 'Maximum critical path latency:',
/** Label for button that shows all lines of the snippet when clicked */
snippetExpandButtonLabel: 'Expand snippet',
/** Label for button that only shows a few lines of the snippet when clicked */
snippetCollapseButtonLabel: 'Collapse snippet',
/** Explanation shown to users below performance results to inform them that the test was done with a 4G network connection and to warn them that the numbers they see will likely change slightly the next time they run Lighthouse. 'Lighthouse' becomes link text to additional documentation. */
lsPerformanceCategoryDescription: '[Lighthouse](https://developers.google.com/web/tools/lighthouse/) analysis of the current page on an emulated mobile network. Values are estimated and may vary.',
/** Title of the lab data section of the Performance category. Within this section are various speed metrics which quantify the pageload performance into values presented in seconds and milliseconds. "Lab" is an abbreviated form of "laboratory", and refers to the fact that the data is from a controlled test of a website, not measurements from real users visiting that site. */
labDataTitle: 'Lab Data',
/** This label is for a checkbox above a table of items loaded by a web page. The checkbox is used to show or hide third-party (or "3rd-party") resources in the table, where "third-party resources" refers to items loaded by a web page from URLs that aren't controlled by the owner of the web page. */
thirdPartyResourcesLabel: 'Show 3rd-party resources',
/** This label is for a button that opens a new tab to a webapp called "Treemap", which is a nested visual representation of a heierarchy of data related to the reports (script bytes and coverage, resource breakdown, etc.) */
viewTreemapLabel: 'View Treemap',
/** This label is for a button that will show the user a trace of the page. */
viewTraceLabel: 'View Trace',
/** This label is for a button that will show the user a trace of the page. */
viewOriginalTraceLabel: 'View Original Trace',
/** Option in a dropdown menu that opens a small, summary report in a print dialog. */
dropdownPrintSummary: 'Print Summary',
/** Option in a dropdown menu that opens a full Lighthouse report in a print dialog. */
dropdownPrintExpanded: 'Print Expanded',
/** Option in a dropdown menu that copies the Lighthouse JSON object to the system clipboard. */
dropdownCopyJSON: 'Copy JSON',
/** Option in a dropdown menu that saves the Lighthouse report HTML locally to the system as a '.html' file. */
dropdownSaveHTML: 'Save as HTML',
/** Option in a dropdown menu that saves the Lighthouse JSON object to the local system as a '.json' file. */
dropdownSaveJSON: 'Save as JSON',
/** Option in a dropdown menu that opens the current report in the Lighthouse Viewer Application. */
dropdownViewer: 'Open in Viewer',
/** Option in a dropdown menu that saves the current report as a new GitHub Gist. */
dropdownSaveGist: 'Save as Gist',
/** Option in a dropdown menu that toggles the themeing of the report between Light(default) and Dark themes. */
dropdownDarkTheme: 'Toggle Dark Theme',
/** Label for a row in a table that describes the kind of device that was emulated for the Lighthouse run. Example values for row elements: 'No Emulation', 'Emulated Desktop', etc. */
runtimeSettingsDevice: 'Device',
/** Label for a row in a table that describes the network throttling conditions that were used during a Lighthouse run, if any. */
runtimeSettingsNetworkThrottling: 'Network throttling',
/** Label for a row in a table that describes the CPU throttling conditions that were used during a Lighthouse run, if any.*/
runtimeSettingsCPUThrottling: 'CPU throttling',
/** Label for a row in a table that shows the User Agent that was used to send out all network requests during the Lighthouse run. */
runtimeSettingsUANetwork: 'User agent (network)',
/** Label for a row in a table that shows the estimated CPU power of the machine running Lighthouse. Example row values: 532, 1492, 783. */
runtimeSettingsBenchmark: 'Unthrottled CPU/Memory Power',
/** Label for a row in a table that shows the version of the Axe library used. Example row values: 2.1.0, 3.2.3 */
runtimeSettingsAxeVersion: 'Axe version',
/** Label for a row in a table that shows the screen resolution and DPR that was emulated for the Lighthouse run. Example values: '800x600, DPR: 3' */
runtimeSettingsScreenEmulation: 'Screen emulation',
/** Label for button to create an issue against the Lighthouse GitHub project. */
footerIssue: 'File an issue',
/** Descriptive explanation for emulation setting when no device emulation is set. */
runtimeNoEmulation: 'No emulation',
/** Descriptive explanation for emulation setting when emulating a Moto G Power mobile device. */
runtimeMobileEmulation: 'Emulated Moto G Power',
/** Descriptive explanation for emulation setting when emulating a generic desktop form factor, as opposed to a mobile-device like form factor. */
runtimeDesktopEmulation: 'Emulated Desktop',
/** Descriptive explanation for a runtime setting that is set to an unknown value. */
runtimeUnknown: 'Unknown',
/** Descriptive label that this analysis run was from a single pageload of a browser (not a summary of hundreds of loads) */
runtimeSingleLoad: 'Single page load',
/** Descriptive label that this analysis only considers the initial load of the page, and no interaction beyond when the page had "fully loaded" */
runtimeAnalysisWindow: 'Initial page load',
/** Descriptive explanation that this analysis run was from a single pageload of a browser, whereas field data often summarizes hundreds+ of page loads */
runtimeSingleLoadTooltip: 'This data is taken from a single page load, as opposed to field data summarizing many sessions.', // eslint-disable-line max-len
/** Descriptive explanation for environment throttling that was provided by the runtime environment instead of provided by Lighthouse throttling. */
throttlingProvided: 'Provided by environment',
/** Label for an interactive control that will reveal or hide a group of content. This control toggles between the text 'Show' and 'Hide'. */
show: 'Show',
/** Label for an interactive control that will reveal or hide a group of content. This control toggles between the text 'Show' and 'Hide'. */
hide: 'Hide',
/** Label for an interactive control that will reveal or hide a group of content. This control toggles between the text 'Expand view' and 'Collapse view'. */
expandView: 'Expand view',
/** Label for an interactive control that will reveal or hide a group of content. This control toggles between the text 'Expand view' and 'Collapse view'. */
collapseView: 'Collapse view',
/** Label indicating that Lighthouse throttled the page to emulate a slow 4G network connection. */
runtimeSlow4g: 'Slow 4G throttling',
/** Label indicating that Lighthouse throttled the page using custom throttling settings. */
runtimeCustom: 'Custom throttling',
/** This label is for a decorative chip that is included in a table row. The label indicates that the entity/company name in the row belongs to the first-party (or "1st-party"). First-party label is used to identify resources that are directly controlled by the owner of the web page. */
firstPartyChipLabel: '1st party',
/** Descriptive explanation in a tooltip form for a link to be opened in a new tab of the browser. */
openInANewTabTooltip: 'Open in a new tab',
/** Generic category name for all resources that could not be attributed to a 1st or 3rd party entity. */
unattributable: 'Unattributable',
};
export {
ReportUtils,
UIStrings,
};

View File

@@ -0,0 +1,85 @@
/**
* Render snippet of text with line numbers and annotations.
* By default we only show a few lines around each annotation and the user
* can click "Expand snippet" to show more.
* Content lines with annotations are highlighted.
*/
export class SnippetRenderer {
/**
* @param {DOM} dom
* @param {LH.Audit.Details.SnippetValue} details
* @param {DetailsRenderer} detailsRenderer
* @param {function} toggleExpandedFn
* @return {DocumentFragment}
*/
static renderHeader(dom: DOM, details: LH.Audit.Details.SnippetValue, detailsRenderer: DetailsRenderer, toggleExpandedFn: Function): DocumentFragment;
/**
* Renders a line (text content, message, or placeholder) as a DOM element.
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LineDetails} lineDetails
* @return {Element}
*/
static renderSnippetLine(dom: DOM, tmpl: DocumentFragment, { content, lineNumber, truncated, contentType, visibility }: LineDetails): Element;
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {{message: string}} message
* @return {Element}
*/
static renderMessage(dom: DOM, tmpl: DocumentFragment, message: {
message: string;
}): Element;
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LineVisibility} visibility
* @return {Element}
*/
static renderOmittedLinesPlaceholder(dom: DOM, tmpl: DocumentFragment, visibility: LineVisibility): Element;
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LH.Audit.Details.SnippetValue} details
* @return {DocumentFragment}
*/
static renderSnippetContent(dom: DOM, tmpl: DocumentFragment, details: LH.Audit.Details.SnippetValue): DocumentFragment;
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LH.Audit.Details.SnippetValue} details
* @return {DocumentFragment}
*/
static renderSnippetLines(dom: DOM, tmpl: DocumentFragment, details: LH.Audit.Details.SnippetValue): DocumentFragment;
/**
* @param {DOM} dom
* @param {LH.Audit.Details.SnippetValue} details
* @param {DetailsRenderer} detailsRenderer
* @return {!Element}
*/
static render(dom: DOM, details: LH.Audit.Details.SnippetValue, detailsRenderer: DetailsRenderer): Element;
}
export type DetailsRenderer = import('./details-renderer').DetailsRenderer;
export type DOM = import('./dom').DOM;
export type LineDetails = {
content: string;
lineNumber: string | number;
contentType: LineContentType;
truncated?: boolean;
visibility?: LineVisibility;
};
type LineVisibility = number;
declare namespace LineVisibility {
const ALWAYS: number;
const WHEN_COLLAPSED: number;
const WHEN_EXPANDED: number;
}
type LineContentType = number;
declare namespace LineContentType {
const CONTENT_NORMAL: number;
const CONTENT_HIGHLIGHTED: number;
const PLACEHOLDER: number;
const MESSAGE: number;
}
export {};
//# sourceMappingURL=snippet-renderer.d.ts.map

View File

@@ -0,0 +1,355 @@
/**
* @license Copyright 2019 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.
*/
/** @typedef {import('./details-renderer').DetailsRenderer} DetailsRenderer */
/** @typedef {import('./dom').DOM} DOM */
import {Util} from '../../shared/util.js';
import {Globals} from './report-globals.js';
/** @enum {number} */
const LineVisibility = {
/** Show regardless of whether the snippet is collapsed or expanded */
ALWAYS: 0,
WHEN_COLLAPSED: 1,
WHEN_EXPANDED: 2,
};
/** @enum {number} */
const LineContentType = {
/** A line of content */
CONTENT_NORMAL: 0,
/** A line of content that's emphasized by setting the CSS background color */
CONTENT_HIGHLIGHTED: 1,
/** Use when some lines are hidden, shows the "..." placeholder */
PLACEHOLDER: 2,
/** A message about a line of content or the snippet in general */
MESSAGE: 3,
};
/** @typedef {{
content: string;
lineNumber: string | number;
contentType: LineContentType;
truncated?: boolean;
visibility?: LineVisibility;
}} LineDetails */
const classNamesByContentType = {
[LineContentType.CONTENT_NORMAL]: ['lh-snippet__line--content'],
[LineContentType.CONTENT_HIGHLIGHTED]: [
'lh-snippet__line--content',
'lh-snippet__line--content-highlighted',
],
[LineContentType.PLACEHOLDER]: ['lh-snippet__line--placeholder'],
[LineContentType.MESSAGE]: ['lh-snippet__line--message'],
};
/**
* @param {LH.Audit.Details.SnippetValue['lines']} lines
* @param {number} lineNumber
* @return {{line?: LH.Audit.Details.SnippetValue['lines'][0], previousLine?: LH.Audit.Details.SnippetValue['lines'][0]}}
*/
function getLineAndPreviousLine(lines, lineNumber) {
return {
line: lines.find(l => l.lineNumber === lineNumber),
previousLine: lines.find(l => l.lineNumber === lineNumber - 1),
};
}
/**
* @param {LH.Audit.Details.SnippetValue["lineMessages"]} messages
* @param {number} lineNumber
*/
function getMessagesForLineNumber(messages, lineNumber) {
return messages.filter(h => h.lineNumber === lineNumber);
}
/**
* @param {LH.Audit.Details.SnippetValue} details
* @return {LH.Audit.Details.SnippetValue['lines']}
*/
function getLinesWhenCollapsed(details) {
const SURROUNDING_LINES_TO_SHOW_WHEN_COLLAPSED = 2;
return Util.filterRelevantLines(
details.lines,
details.lineMessages,
SURROUNDING_LINES_TO_SHOW_WHEN_COLLAPSED
);
}
/**
* Render snippet of text with line numbers and annotations.
* By default we only show a few lines around each annotation and the user
* can click "Expand snippet" to show more.
* Content lines with annotations are highlighted.
*/
export class SnippetRenderer {
/**
* @param {DOM} dom
* @param {LH.Audit.Details.SnippetValue} details
* @param {DetailsRenderer} detailsRenderer
* @param {function} toggleExpandedFn
* @return {DocumentFragment}
*/
static renderHeader(dom, details, detailsRenderer, toggleExpandedFn) {
const linesWhenCollapsed = getLinesWhenCollapsed(details);
const canExpand = linesWhenCollapsed.length < details.lines.length;
const header = dom.createComponent('snippetHeader');
dom.find('.lh-snippet__title', header).textContent = details.title;
const {
snippetCollapseButtonLabel,
snippetExpandButtonLabel,
} = Globals.strings;
dom.find(
'.lh-snippet__btn-label-collapse',
header
).textContent = snippetCollapseButtonLabel;
dom.find(
'.lh-snippet__btn-label-expand',
header
).textContent = snippetExpandButtonLabel;
const toggleExpandButton = dom.find('.lh-snippet__toggle-expand', header);
// If we're already showing all the available lines of the snippet, we don't need an
// expand/collapse button and can remove it from the DOM.
// If we leave the button in though, wire up the click listener to toggle visibility!
if (!canExpand) {
toggleExpandButton.remove();
} else {
toggleExpandButton.addEventListener('click', () => toggleExpandedFn());
}
// We only show the source node of the snippet in DevTools because then the user can
// access the full element detail. Just being able to see the outer HTML isn't very useful.
if (details.node && dom.isDevTools()) {
const nodeContainer = dom.find('.lh-snippet__node', header);
nodeContainer.append(detailsRenderer.renderNode(details.node));
}
return header;
}
/**
* Renders a line (text content, message, or placeholder) as a DOM element.
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LineDetails} lineDetails
* @return {Element}
*/
static renderSnippetLine(
dom,
tmpl,
{content, lineNumber, truncated, contentType, visibility}
) {
const clonedTemplate = dom.createComponent('snippetLine');
const contentLine = dom.find('.lh-snippet__line', clonedTemplate);
const {classList} = contentLine;
classNamesByContentType[contentType].forEach(typeClass =>
classList.add(typeClass)
);
if (visibility === LineVisibility.WHEN_COLLAPSED) {
classList.add('lh-snippet__show-if-collapsed');
} else if (visibility === LineVisibility.WHEN_EXPANDED) {
classList.add('lh-snippet__show-if-expanded');
}
const lineContent = content + (truncated ? '…' : '');
const lineContentEl = dom.find('.lh-snippet__line code', contentLine);
if (contentType === LineContentType.MESSAGE) {
lineContentEl.append(dom.convertMarkdownLinkSnippets(lineContent));
} else {
lineContentEl.textContent = lineContent;
}
dom.find(
'.lh-snippet__line-number',
contentLine
).textContent = lineNumber.toString();
return contentLine;
}
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {{message: string}} message
* @return {Element}
*/
static renderMessage(dom, tmpl, message) {
return SnippetRenderer.renderSnippetLine(dom, tmpl, {
lineNumber: ' ',
content: message.message,
contentType: LineContentType.MESSAGE,
});
}
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LineVisibility} visibility
* @return {Element}
*/
static renderOmittedLinesPlaceholder(dom, tmpl, visibility) {
return SnippetRenderer.renderSnippetLine(dom, tmpl, {
lineNumber: '…',
content: '',
visibility,
contentType: LineContentType.PLACEHOLDER,
});
}
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LH.Audit.Details.SnippetValue} details
* @return {DocumentFragment}
*/
static renderSnippetContent(dom, tmpl, details) {
const template = dom.createComponent('snippetContent');
const snippetEl = dom.find('.lh-snippet__snippet-inner', template);
// First render messages that don't belong to specific lines
details.generalMessages.forEach(m =>
snippetEl.append(SnippetRenderer.renderMessage(dom, tmpl, m))
);
// Then render the lines and their messages, as well as placeholders where lines are omitted
snippetEl.append(SnippetRenderer.renderSnippetLines(dom, tmpl, details));
return template;
}
/**
* @param {DOM} dom
* @param {DocumentFragment} tmpl
* @param {LH.Audit.Details.SnippetValue} details
* @return {DocumentFragment}
*/
static renderSnippetLines(dom, tmpl, details) {
const {lineMessages, generalMessages, lineCount, lines} = details;
const linesWhenCollapsed = getLinesWhenCollapsed(details);
const hasOnlyGeneralMessages =
generalMessages.length > 0 && lineMessages.length === 0;
const lineContainer = dom.createFragment();
// When a line is not shown in the collapsed state we try to see if we also need an
// omitted lines placeholder for the expanded state, rather than rendering two separate
// placeholders.
let hasPendingOmittedLinesPlaceholderForCollapsedState = false;
for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
const {line, previousLine} = getLineAndPreviousLine(lines, lineNumber);
const {
line: lineWhenCollapsed,
previousLine: previousLineWhenCollapsed,
} = getLineAndPreviousLine(linesWhenCollapsed, lineNumber);
const showLineWhenCollapsed = !!lineWhenCollapsed;
const showPreviousLineWhenCollapsed = !!previousLineWhenCollapsed;
// If we went from showing lines in the collapsed state to not showing them
// we need to render a placeholder
if (showPreviousLineWhenCollapsed && !showLineWhenCollapsed) {
hasPendingOmittedLinesPlaceholderForCollapsedState = true;
}
// If we are back to lines being visible in the collapsed and the placeholder
// hasn't been rendered yet then render it now
if (
showLineWhenCollapsed &&
hasPendingOmittedLinesPlaceholderForCollapsedState
) {
lineContainer.append(
SnippetRenderer.renderOmittedLinesPlaceholder(
dom,
tmpl,
LineVisibility.WHEN_COLLAPSED
)
);
hasPendingOmittedLinesPlaceholderForCollapsedState = false;
}
// Render omitted lines placeholder if we have not already rendered one for this gap
const isFirstOmittedLineWhenExpanded = !line && !!previousLine;
const isFirstLineOverallAndIsOmittedWhenExpanded =
!line && lineNumber === 1;
if (
isFirstOmittedLineWhenExpanded ||
isFirstLineOverallAndIsOmittedWhenExpanded
) {
// In the collapsed state we don't show omitted lines placeholders around
// the edges of the snippet
const hasRenderedAllLinesVisibleWhenCollapsed = !linesWhenCollapsed.some(
l => l.lineNumber > lineNumber
);
const onlyShowWhenExpanded =
hasRenderedAllLinesVisibleWhenCollapsed || lineNumber === 1;
lineContainer.append(
SnippetRenderer.renderOmittedLinesPlaceholder(
dom,
tmpl,
onlyShowWhenExpanded
? LineVisibility.WHEN_EXPANDED
: LineVisibility.ALWAYS
)
);
hasPendingOmittedLinesPlaceholderForCollapsedState = false;
}
if (!line) {
// Can't render the line if we don't know its content (instead we've rendered a placeholder)
continue;
}
// Now render the line and any messages
const messages = getMessagesForLineNumber(lineMessages, lineNumber);
const highlightLine = messages.length > 0 || hasOnlyGeneralMessages;
const contentLineDetails = Object.assign({}, line, {
contentType: highlightLine
? LineContentType.CONTENT_HIGHLIGHTED
: LineContentType.CONTENT_NORMAL,
visibility: lineWhenCollapsed
? LineVisibility.ALWAYS
: LineVisibility.WHEN_EXPANDED,
});
lineContainer.append(
SnippetRenderer.renderSnippetLine(dom, tmpl, contentLineDetails)
);
messages.forEach(message => {
lineContainer.append(SnippetRenderer.renderMessage(dom, tmpl, message));
});
}
return lineContainer;
}
/**
* @param {DOM} dom
* @param {LH.Audit.Details.SnippetValue} details
* @param {DetailsRenderer} detailsRenderer
* @return {!Element}
*/
static render(dom, details, detailsRenderer) {
const tmpl = dom.createComponent('snippet');
const snippetEl = dom.find('.lh-snippet', tmpl);
const header = SnippetRenderer.renderHeader(
dom,
details,
detailsRenderer,
() => snippetEl.classList.toggle('lh-snippet--expanded')
);
const content = SnippetRenderer.renderSnippetContent(dom, tmpl, details);
snippetEl.append(header, content);
return snippetEl;
}
}

View File

@@ -0,0 +1,31 @@
/**
* @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.
*/
/**
* @fileoverview Creates a <select> element, filled with all supported locales
*/
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./report-ui-features').ReportUIFeatures} ReportUIFeatures */
export class SwapLocaleFeature {
/**
* @param {ReportUIFeatures} reportUIFeatures
* @param {DOM} dom
* @param {{onLocaleSelected: (localeModuleName: LH.Locale) => Promise<void>}} callbacks
* Specifiy the URL where the i18n module script can be found, and the URLS for the locale JSON files.
*/
constructor(reportUIFeatures: ReportUIFeatures, dom: DOM, callbacks: {
onLocaleSelected: (localeModuleName: LH.Locale) => Promise<void>;
});
_reportUIFeatures: import("./report-ui-features").ReportUIFeatures;
_dom: import("./dom.js").DOM;
_localeSelectedCallback: (localeModuleName: LH.Locale) => Promise<void>;
/**
* @param {Array<LH.Locale>} locales
*/
enable(locales: Array<LH.Locale>): void;
}
export type DOM = import('./dom.js').DOM;
export type ReportUIFeatures = import('./report-ui-features').ReportUIFeatures;
//# sourceMappingURL=swap-locale-feature.d.ts.map

View File

@@ -0,0 +1,76 @@
/**
* @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.
*/
/**
* @fileoverview Creates a <select> element, filled with all supported locales
*/
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./report-ui-features').ReportUIFeatures} ReportUIFeatures */
export class SwapLocaleFeature {
/**
* @param {ReportUIFeatures} reportUIFeatures
* @param {DOM} dom
* @param {{onLocaleSelected: (localeModuleName: LH.Locale) => Promise<void>}} callbacks
* Specifiy the URL where the i18n module script can be found, and the URLS for the locale JSON files.
*/
constructor(reportUIFeatures, dom, callbacks) {
this._reportUIFeatures = reportUIFeatures;
this._dom = dom;
this._localeSelectedCallback = callbacks.onLocaleSelected;
}
/**
* @param {Array<LH.Locale>} locales
*/
enable(locales) {
if (!this._reportUIFeatures.json.i18n.icuMessagePaths) {
throw new Error('missing icuMessagePaths');
}
this._dom.find('.lh-tools-locale', this._dom.rootEl).classList.remove('lh-hidden');
const currentLocale = this._reportUIFeatures.json.configSettings.locale;
const containerEl = this._dom.find('.lh-tools-locale__selector-wrapper', this._dom.rootEl);
containerEl.removeAttribute('aria-hidden');
const selectEl = this._dom.createChildOf(containerEl, 'select', 'lh-locale-selector');
selectEl.name = 'lh-locale-list';
selectEl.setAttribute('role', 'menuitem');
const toggleEl = this._dom.find('.lh-tool-locale__button', this._dom.rootEl);
toggleEl.addEventListener('click', () => {
toggleEl.classList.toggle('lh-active');
});
for (const locale of locales) {
const optionEl = this._dom.createChildOf(selectEl, 'option', '');
optionEl.value = locale;
if (locale === currentLocale) optionEl.selected = true;
if (window.Intl && Intl.DisplayNames) {
const currentLocaleDisplay = new Intl.DisplayNames([currentLocale], {type: 'language'});
const optionLocaleDisplay = new Intl.DisplayNames([locale], {type: 'language'});
const optionLocaleName = optionLocaleDisplay.of(locale);
const currentLocaleName = currentLocaleDisplay.of(locale) || locale;
if (optionLocaleName && optionLocaleName !== currentLocaleName) {
optionEl.textContent = `${optionLocaleName} ${currentLocaleName}`;
} else {
optionEl.textContent = currentLocaleName;
}
} else {
optionEl.textContent = locale;
}
}
selectEl.addEventListener('change', () => {
const locale = /** @type {LH.Locale} */ (selectEl.value);
this._localeSelectedCallback(locale);
});
}
}

View File

@@ -0,0 +1,26 @@
export namespace TextEncoding {
export { toBase64 };
export { fromBase64 };
}
/**
* Takes an UTF-8 string and returns a base64 encoded string.
* If gzip is true, the UTF-8 bytes are gzipped before base64'd, using
* CompressionStream (currently only in Chrome), falling back to pako
* (which is only used to encode in our Node tests).
* @param {string} string
* @param {{gzip: boolean}} options
* @return {Promise<string>}
*/
declare function toBase64(string: string, options: {
gzip: boolean;
}): Promise<string>;
/**
* @param {string} encoded
* @param {{gzip: boolean}} options
* @return {string}
*/
declare function fromBase64(encoded: string, options: {
gzip: boolean;
}): string;
export {};
//# sourceMappingURL=text-encoding.d.ts.map

View File

@@ -0,0 +1,73 @@
/**
* @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.
*/
/* global CompressionStream */
const btoa_ = typeof btoa !== 'undefined' ?
btoa :
/** @param {string} str */
(str) => Buffer.from(str).toString('base64');
const atob_ = typeof atob !== 'undefined' ?
atob :
/** @param {string} str */
(str) => Buffer.from(str, 'base64').toString();
/**
* Takes an UTF-8 string and returns a base64 encoded string.
* If gzip is true, the UTF-8 bytes are gzipped before base64'd, using
* CompressionStream (currently only in Chrome), falling back to pako
* (which is only used to encode in our Node tests).
* @param {string} string
* @param {{gzip: boolean}} options
* @return {Promise<string>}
*/
async function toBase64(string, options) {
let bytes = new TextEncoder().encode(string);
if (options.gzip) {
if (typeof CompressionStream !== 'undefined') {
const cs = new CompressionStream('gzip');
const writer = cs.writable.getWriter();
writer.write(bytes);
writer.close();
const compAb = await new Response(cs.readable).arrayBuffer();
bytes = new Uint8Array(compAb);
} else {
/** @type {import('pako')=} */
const pako = window.pako;
bytes = pako.gzip(string);
}
}
let binaryString = '';
// This is ~25% faster than building the string one character at a time.
// https://jsbench.me/2gkoxazvjl
const chunkSize = 5000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binaryString += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa_(binaryString);
}
/**
* @param {string} encoded
* @param {{gzip: boolean}} options
* @return {string}
*/
function fromBase64(encoded, options) {
const binaryString = atob_(encoded);
const bytes = Uint8Array.from(binaryString, c => c.charCodeAt(0));
if (options.gzip) {
/** @type {import('pako')=} */
const pako = window.pako;
return pako.ungzip(bytes, {to: 'string'});
} else {
return new TextDecoder().decode(bytes);
}
}
export const TextEncoding = {toBase64, fromBase64};

View File

@@ -0,0 +1,82 @@
export class TopbarFeatures {
/**
* @param {ReportUIFeatures} reportUIFeatures
* @param {DOM} dom
*/
constructor(reportUIFeatures: ReportUIFeatures, dom: DOM);
/** @type {LH.Result} */
lhr: LH.Result;
_reportUIFeatures: import("./report-ui-features").ReportUIFeatures;
_dom: import("./dom.js").DOM;
_dropDownMenu: DropDownMenu;
_copyAttempt: boolean;
/** @type {HTMLElement} */
topbarEl: HTMLElement;
/** @type {HTMLElement} */
categoriesEl: HTMLElement;
/** @type {HTMLElement?} */
stickyHeaderEl: HTMLElement | null;
/** @type {HTMLElement} */
highlightEl: HTMLElement;
/**
* Handler for tool button.
* @param {Event} e
*/
onDropDownMenuClick(e: Event): void;
/**
* Keyup handler for the document.
* @param {KeyboardEvent} e
*/
onKeyUp(e: KeyboardEvent): void;
/**
* Handle copy events.
* @param {ClipboardEvent} e
*/
onCopy(e: ClipboardEvent): void;
/**
* Collapses all audit `<details>`.
* open a `<details>` element.
*/
collapseAllDetails(): void;
/**
* @param {LH.Result} lhr
*/
enable(lhr: LH.Result): void;
/**
* Copies the report JSON to the clipboard (if supported by the browser).
*/
onCopyButtonClick(): void;
/**
* Expands all audit `<details>`.
* Ideally, a print stylesheet could take care of this, but CSS has no way to
* open a `<details>` element.
*/
expandAllDetails(): void;
_print(): void;
/**
* Resets the state of page before capturing the page for export.
* When the user opens the exported HTML page, certain UI elements should
* be in their closed state (not opened) and the templates should be unstamped.
*/
resetUIState(): void;
/**
* Finds the first scrollable ancestor of `element`. Falls back to the document.
* @param {Element} element
* @return {Element | Document}
*/
_getScrollParent(element: Element): Element | Document;
/**
* Sets up listeners to collapse audit `<details>` when the user closes the
* print dialog, all `<details>` are collapsed.
*/
_setUpCollapseDetailsAfterPrinting(): void;
_setupStickyHeader(): void;
/**
* Toggle visibility and update highlighter position
*/
_updateStickyHeader(): void;
}
export type DOM = import('./dom.js').DOM;
export type ReportUIFeatures = import('./report-ui-features').ReportUIFeatures;
import { DropDownMenu } from './drop-down-menu.js';
//# sourceMappingURL=topbar-features.d.ts.map

View File

@@ -0,0 +1,319 @@
/**
* @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.
*/
/* eslint-env browser */
/** @typedef {import('./dom.js').DOM} DOM */
/** @typedef {import('./report-ui-features').ReportUIFeatures} ReportUIFeatures */
import {DropDownMenu} from './drop-down-menu.js';
import {toggleDarkTheme} from './features-util.js';
import {openViewer, openViewerAndSendData} from './open-tab.js';
export class TopbarFeatures {
/**
* @param {ReportUIFeatures} reportUIFeatures
* @param {DOM} dom
*/
constructor(reportUIFeatures, dom) {
/** @type {LH.Result} */
this.lhr; // eslint-disable-line no-unused-expressions
this._reportUIFeatures = reportUIFeatures;
this._dom = dom;
this._dropDownMenu = new DropDownMenu(this._dom);
this._copyAttempt = false;
/** @type {HTMLElement} */
this.topbarEl; // eslint-disable-line no-unused-expressions
/** @type {HTMLElement} */
this.categoriesEl; // eslint-disable-line no-unused-expressions
/** @type {HTMLElement?} */
this.stickyHeaderEl; // eslint-disable-line no-unused-expressions
/** @type {HTMLElement} */
this.highlightEl; // eslint-disable-line no-unused-expressions
this.onDropDownMenuClick = this.onDropDownMenuClick.bind(this);
this.onKeyUp = this.onKeyUp.bind(this);
this.onCopy = this.onCopy.bind(this);
this.collapseAllDetails = this.collapseAllDetails.bind(this);
}
/**
* @param {LH.Result} lhr
*/
enable(lhr) {
this.lhr = lhr;
this._dom.rootEl.addEventListener('keyup', this.onKeyUp);
this._dom.document().addEventListener('copy', this.onCopy);
this._dropDownMenu.setup(this.onDropDownMenuClick);
this._setUpCollapseDetailsAfterPrinting();
const topbarLogo = this._dom.find('.lh-topbar__logo', this._dom.rootEl);
topbarLogo.addEventListener('click', () => toggleDarkTheme(this._dom));
this._setupStickyHeader();
}
/**
* Handler for tool button.
* @param {Event} e
*/
onDropDownMenuClick(e) {
e.preventDefault();
const el = /** @type {?Element} */ (e.target);
if (!el || !el.hasAttribute('data-action')) {
return;
}
switch (el.getAttribute('data-action')) {
case 'copy':
this.onCopyButtonClick();
break;
case 'print-summary':
this.collapseAllDetails();
this._print();
break;
case 'print-expanded':
this.expandAllDetails();
this._print();
break;
case 'save-json': {
const jsonStr = JSON.stringify(this.lhr, null, 2);
this._reportUIFeatures._saveFile(new Blob([jsonStr], {type: 'application/json'}));
break;
}
case 'save-html': {
const htmlStr = this._reportUIFeatures.getReportHtml();
try {
this._reportUIFeatures._saveFile(new Blob([htmlStr], {type: 'text/html'}));
} catch (e) {
this._dom.fireEventOn('lh-log', this._dom.document(), {
cmd: 'error', msg: 'Could not export as HTML. ' + e.message,
});
}
break;
}
case 'open-viewer': {
// DevTools cannot send data with postMessage, and we only want to use the URL fragment
// approach for viewer when needed, so check the environment and choose accordingly.
if (this._dom.isDevTools()) {
openViewer(this.lhr);
} else {
openViewerAndSendData(this.lhr);
}
break;
}
case 'save-gist': {
this._reportUIFeatures.saveAsGist();
break;
}
case 'toggle-dark': {
toggleDarkTheme(this._dom);
break;
}
}
this._dropDownMenu.close();
}
/**
* Handle copy events.
* @param {ClipboardEvent} e
*/
onCopy(e) {
// Only handle copy button presses (e.g. ignore the user copying page text).
if (this._copyAttempt && e.clipboardData) {
// We want to write our own data to the clipboard, not the user's text selection.
e.preventDefault();
e.clipboardData.setData('text/plain', JSON.stringify(this.lhr, null, 2));
this._dom.fireEventOn('lh-log', this._dom.document(), {
cmd: 'log', msg: 'Report JSON copied to clipboard',
});
}
this._copyAttempt = false;
}
/**
* Copies the report JSON to the clipboard (if supported by the browser).
*/
onCopyButtonClick() {
this._dom.fireEventOn('lh-analytics', this._dom.document(), {
cmd: 'send',
fields: {hitType: 'event', eventCategory: 'report', eventAction: 'copy'},
});
try {
if (this._dom.document().queryCommandSupported('copy')) {
this._copyAttempt = true;
// Note: In Safari 10.0.1, execCommand('copy') returns true if there's
// a valid text selection on the page. See http://caniuse.com/#feat=clipboard.
if (!this._dom.document().execCommand('copy')) {
this._copyAttempt = false; // Prevent event handler from seeing this as a copy attempt.
this._dom.fireEventOn('lh-log', this._dom.document(), {
cmd: 'warn', msg: 'Your browser does not support copy to clipboard.',
});
}
}
} catch (e) {
this._copyAttempt = false;
this._dom.fireEventOn('lh-log', this._dom.document(), {cmd: 'log', msg: e.message});
}
}
/**
* Keyup handler for the document.
* @param {KeyboardEvent} e
*/
onKeyUp(e) {
// Ctrl+P - Expands audit details when user prints via keyboard shortcut.
if ((e.ctrlKey || e.metaKey) && e.keyCode === 80) {
this._dropDownMenu.close();
}
}
/**
* Expands all audit `<details>`.
* Ideally, a print stylesheet could take care of this, but CSS has no way to
* open a `<details>` element.
*/
expandAllDetails() {
const details = this._dom.findAll('.lh-categories details', this._dom.rootEl);
details.map(detail => detail.open = true);
}
/**
* Collapses all audit `<details>`.
* open a `<details>` element.
*/
collapseAllDetails() {
const details = this._dom.findAll('.lh-categories details', this._dom.rootEl);
details.map(detail => detail.open = false);
}
_print() {
if (this._reportUIFeatures._opts.onPrintOverride) {
this._reportUIFeatures._opts.onPrintOverride(this._dom.rootEl);
} else {
self.print();
}
}
/**
* Resets the state of page before capturing the page for export.
* When the user opens the exported HTML page, certain UI elements should
* be in their closed state (not opened) and the templates should be unstamped.
*/
resetUIState() {
this._dropDownMenu.close();
}
/**
* Finds the first scrollable ancestor of `element`. Falls back to the document.
* @param {Element} element
* @return {Element | Document}
*/
_getScrollParent(element) {
const {overflowY} = window.getComputedStyle(element);
const isScrollable = overflowY !== 'visible' && overflowY !== 'hidden';
if (isScrollable) {
return element;
}
if (element.parentElement) {
return this._getScrollParent(element.parentElement);
}
return document;
}
/**
* Sets up listeners to collapse audit `<details>` when the user closes the
* print dialog, all `<details>` are collapsed.
*/
_setUpCollapseDetailsAfterPrinting() {
// FF and IE implement these old events.
const supportsOldPrintEvents = 'onbeforeprint' in self;
if (supportsOldPrintEvents) {
self.addEventListener('afterprint', this.collapseAllDetails);
} else {
// Note: FF implements both window.onbeforeprint and media listeners. However,
// it doesn't matchMedia doesn't fire when matching 'print'.
self.matchMedia('print').addListener(mql => {
if (mql.matches) {
this.expandAllDetails();
} else {
this.collapseAllDetails();
}
});
}
}
_setupStickyHeader() {
// Cache these elements to avoid qSA on each onscroll.
this.topbarEl = this._dom.find('div.lh-topbar', this._dom.rootEl);
this.categoriesEl = this._dom.find('div.lh-categories', this._dom.rootEl);
// Defer behind rAF to avoid forcing layout.
window.requestAnimationFrame(() => window.requestAnimationFrame(() => {
// Only present in the DOM if it'll be used (>=2 categories)
try {
this.stickyHeaderEl = this._dom.find('div.lh-sticky-header', this._dom.rootEl);
} catch {
return;
}
// Highlighter will be absolutely positioned at first gauge, then transformed on scroll.
this.highlightEl = this._dom.createChildOf(this.stickyHeaderEl, 'div', 'lh-highlighter');
// Update sticky header visibility and highlight when page scrolls/resizes.
const scrollParent = this._getScrollParent(
this._dom.find('.lh-container', this._dom.rootEl));
// The 'scroll' handler must be should be on {Element | Document}...
scrollParent.addEventListener('scroll', () => this._updateStickyHeader());
// However resizeObserver needs an element, *not* the document.
const resizeTarget = scrollParent instanceof window.Document
? document.documentElement
: scrollParent;
new window.ResizeObserver(() => this._updateStickyHeader()).observe(resizeTarget);
}));
}
/**
* Toggle visibility and update highlighter position
*/
_updateStickyHeader() {
if (!this.stickyHeaderEl) return;
// Show sticky header when the main 5 gauges clear the topbar.
const topbarBottom = this.topbarEl.getBoundingClientRect().bottom;
const categoriesTop = this.categoriesEl.getBoundingClientRect().top;
const showStickyHeader = topbarBottom >= categoriesTop;
// Highlight mini gauge when section is in view.
// In view = the last category that starts above the middle of the window.
const categoryEls = Array.from(this._dom.rootEl.querySelectorAll('.lh-category'));
const categoriesAboveTheMiddle =
categoryEls.filter(el => el.getBoundingClientRect().top - window.innerHeight / 2 < 0);
const highlightIndex =
categoriesAboveTheMiddle.length > 0 ? categoriesAboveTheMiddle.length - 1 : 0;
// Category order matches gauge order in sticky header.
const gaugeWrapperEls =
this.stickyHeaderEl.querySelectorAll('.lh-gauge__wrapper, .lh-fraction__wrapper');
const gaugeToHighlight = gaugeWrapperEls[highlightIndex];
const origin = gaugeWrapperEls[0].getBoundingClientRect().left;
const offset = gaugeToHighlight.getBoundingClientRect().left - origin;
// Mutate at end to avoid layout thrashing.
this.highlightEl.style.transform = `translate(${offset}px)`;
this.stickyHeaderEl.classList.toggle('lh-sticky-header--visible', showStickyHeader);
}
}