Skip to content

Commit

Permalink
tests(full-page-screenshot): add node verification and debug tool (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
connorjclark authored Mar 8, 2024
1 parent ab9be18 commit 62bcd98
Show file tree
Hide file tree
Showing 6 changed files with 485 additions and 6 deletions.
59 changes: 59 additions & 0 deletions cli/test/fixtures/screenshot-nodes.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!--
* 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.
-->

<head>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<style>
p {
background-color: white;
}

div {
width: 150px;
}
div,span,img {
margin: 10px;
padding: 5px;
}
/* Want a LCP, but not any image or text visible! */
img {
opacity: 0.001;
}
span {
display: inline-block;
}

[id*='red'],span[id*='red'] {
background-color: #8a4343;
}
[id*='green'],span[id*='green'] {
background-color: #427f36;
}
</style>
</head>

<body>
<p id="textEl"></p>

<script>
const params = new URLSearchParams(document.location.search);
if (params.has('grow')) {
textEl.style.backgroundColor = 'lightgrey';
let padding = 1;
setInterval(() => {
if (padding > 300) return;

textEl.style.paddingTop = padding + 'px';
padding += 1;
}, 50);
}
</script>

<div id="el-1-red" role="treeitem"></div>
<div id="red">
<span id="green"><img id="el-2-green" src="launcher-icon-4x.png" width="50" height="50"></span>
</div>
</body>
11 changes: 7 additions & 4 deletions core/gather/gatherers/full-page-screenshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import {waitForNetworkIdle} from '../driver/wait-for-condition.js';
// JPEG quality setting
// Exploration and examples of reports using different quality settings: https://docs.google.com/document/d/1ZSffucIca9XDW2eEwfoevrk-OTl7WQFeMf0CgeJAA8M/edit#
// Note: this analysis was done for JPEG, but now we use WEBP.
const FULL_PAGE_SCREENSHOT_QUALITY = 30;
const FULL_PAGE_SCREENSHOT_QUALITY = process.env.LH_FPS_TEST ? 100 : 30;
// webp currently cant do lossless encoding, so to help tests switch to png
// Remove when this is resolved: https://bugs.chromium.org/p/chromium/issues/detail?id=1469183
const FULL_PAGE_SCREENSHOT_FORMAT = process.env.LH_FPS_TEST ? 'png' : 'webp';

// https://developers.google.com/speed/webp/faq#what_is_the_maximum_size_a_webp_image_can_be
const MAX_WEBP_SIZE = 16383;
Expand Down Expand Up @@ -121,10 +124,10 @@ class FullPageScreenshot extends BaseGatherer {
*/
async _takeScreenshot(context) {
const result = await context.driver.defaultSession.sendCommand('Page.captureScreenshot', {
format: 'webp',
format: FULL_PAGE_SCREENSHOT_FORMAT,
quality: FULL_PAGE_SCREENSHOT_QUALITY,
});
const data = 'data:image/webp;base64,' + result.data;
const data = `data:image/${FULL_PAGE_SCREENSHOT_FORMAT};base64,` + result.data;

const screenshotAreaSize =
await context.driver.executionContext.evaluate(getScreenshotAreaSize, {
Expand Down Expand Up @@ -159,7 +162,7 @@ class FullPageScreenshot extends BaseGatherer {
for (const [node, id] of lhIdToElements.entries()) {
// @ts-expect-error - getBoundingClientRect put into scope via stringification
const rect = getBoundingClientRect(node);
nodes[id] = rect;
nodes[id] = {id: node.id, ...rect};
}

return nodes;
Expand Down
95 changes: 95 additions & 0 deletions core/scripts/full-page-screenshot-debug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* @license Copyright 2023 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

// To open result in chrome:
// node core/scripts/full-page-screenshot-debug.js latest-run/lhr.report.json | xargs "$CHROME_PATH"

import * as fs from 'fs';

import esMain from 'es-main';
import * as puppeteer from 'puppeteer-core';
import {getChromePath} from 'chrome-launcher';

import {LH_ROOT} from '../../shared/root.js';

/**
* @param {LH.Result} lhr
* @return {Promise<string>}
*/
async function getDebugImage(lhr) {
if (!lhr.fullPageScreenshot) {
return '';
}

const browser = await puppeteer.launch({
headless: true,
executablePath: getChromePath(),
ignoreDefaultArgs: ['--enable-automation'],
});
const page = await browser.newPage();

const debugDataUrl = await page.evaluate(async (fullPageScreenshot) => {
const img = await new Promise((resolve, reject) => {
// eslint-disable-next-line no-undef
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = fullPageScreenshot.screenshot.data;
});

// eslint-disable-next-line no-undef
const canvasEl = document.createElement('canvas');
canvasEl.width = img.width;
canvasEl.height = img.height;
const ctx = canvasEl.getContext('2d');
if (!ctx) return '';

ctx.drawImage(img, 0, 0);
for (const [lhId, node] of Object.entries(fullPageScreenshot.nodes)) {
if (!node.width && !node.height) continue;

ctx.strokeStyle = '#D3E156';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rect(node.left, node.top, node.width, node.height);
ctx.stroke();

const txt = node.id || lhId;
const txtWidth = Math.min(ctx.measureText(txt).width, node.width);
const txtHeight = 10;
const txtTop = node.top - 3;
const txtLeft = node.left;
ctx.fillStyle = '#FFFFFF88';
ctx.fillRect(txtLeft, txtTop, txtWidth, txtHeight);
ctx.fillStyle = '#000000';
ctx.lineWidth = 1;
ctx.textBaseline = 'top';
ctx.fillText(txt, txtLeft, txtTop);
}

return canvasEl.toDataURL();
}, lhr.fullPageScreenshot);

await browser.close();

if (!debugDataUrl.startsWith('data:image/')) {
throw new Error('invalid data url');
}

return debugDataUrl;
}

if (esMain(import.meta)) {
const lhr = JSON.parse(fs.readFileSync(process.argv[2], 'utf-8'));
const imageUrl = await getDebugImage(lhr);
const [type, base64Data] = imageUrl.split(',');
const ext = type.replace('data:image/', '');
const dest = `${LH_ROOT}/.tmp/fps-debug.${ext}`;
fs.writeFileSync(dest, base64Data, 'base64');
console.log(dest);
}

export {getDebugImage};
Loading

0 comments on commit 62bcd98

Please sign in to comment.