-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
cumulative-layout-shift.js
246 lines (217 loc) · 10 KB
/
cumulative-layout-shift.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {makeComputedArtifact} from '../computed-artifact.js';
import {ProcessedTrace} from '../processed-trace.js';
import * as RectHelpers from '../../lib/rect-helpers.js';
import * as TraceEngine from '../../lib/trace-engine.js';
import {Sentry} from '../../lib/sentry.js';
/** @typedef {{ts: number, isMainFrame: boolean, weightedScore: number, impactedNodes?: LH.Artifacts.TraceImpactedNode[], event: LH.TraceEvent}} LayoutShiftEvent */
const RECENT_INPUT_WINDOW = 500;
class CumulativeLayoutShift {
/**
* Returns all LayoutShift events that had no recent input.
* Only a `weightedScore` per event is returned. For non-main-frame events, this is
* the only score that matters. For main-frame events, `weighted_score_delta === score`.
* @see https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/layout/layout_shift_tracker.cc;l=492-495;drc=de3b3a8a8839269c6b44403fa38a13a1ed12fed5
* @param {LH.Artifacts.ProcessedTrace} processedTrace
* @return {Array<LayoutShiftEvent>}
*/
static getLayoutShiftEvents(processedTrace) {
const layoutShiftEvents = [];
// Chromium will set `had_recent_input` if there was recent user input, which
// skips shift events from contributing to CLS. This flag is also set when
// Lighthouse changes the emulation size. This results in the first few shift
// events having `had_recent_input` set, so ignore it for those events.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=1094974.
let mustRespectHadRecentInput = false;
// Even if emulation was applied before navigating, Chrome will issue a viewport
// change event after a navigation starts which is treated as an interaction when
// deciding the `had_recent_input` flag. Anything within 500ms of this event should
// always be counted for CLS regardless of the `had_recent_input` flag.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=1302667
let viewportChangeTs = processedTrace.timestamps.timeOrigin;
const firstViewportEvent = processedTrace.frameEvents.find(event => event.name === 'viewport');
if (firstViewportEvent) {
viewportChangeTs = firstViewportEvent.ts;
}
for (const event of processedTrace.frameTreeEvents) {
if (event.name !== 'LayoutShift' ||
!event.args.data ||
event.args.data.is_main_frame === undefined) {
continue;
}
// For all-frames CLS calculation, we rely on `weighted_score_delta`
// All layout shift events should have this since M90: https://crbug.com/1173139
if (event.args.data.weighted_score_delta === undefined) {
throw new Error('CLS missing weighted_score_delta');
}
if (event.args.data.had_recent_input) {
const timing = (event.ts - viewportChangeTs) / 1000;
if (timing > RECENT_INPUT_WINDOW || mustRespectHadRecentInput) continue;
} else {
mustRespectHadRecentInput = true;
}
layoutShiftEvents.push({
ts: event.ts,
isMainFrame: event.args.data.is_main_frame,
weightedScore: event.args.data.weighted_score_delta,
impactedNodes: event.args.data.impacted_nodes,
event,
});
}
return layoutShiftEvents;
}
/**
* Each layout shift event has a 'score' which is the amount added to the CLS as a result of the given shift(s).
* We calculate the score per element by taking the 'score' of each layout shift event and
* distributing it between all the nodes that were shifted, proportianal to the impact region of
* each shifted element.
*
* @param {LayoutShiftEvent[]} layoutShiftEvents
* @return {Map<number, number>}
*/
static getImpactByNodeId(layoutShiftEvents) {
/** @type {Map<number, number>} */
const impactByNodeId = new Map();
for (const event of layoutShiftEvents) {
if (!event.impactedNodes) continue;
let totalAreaOfImpact = 0;
/** @type {Map<number, number>} */
const pixelsMovedPerNode = new Map();
for (const node of event.impactedNodes) {
if (!node.node_id || !node.old_rect || !node.new_rect) continue;
const oldRect = RectHelpers.traceRectToLHRect(node.old_rect);
const newRect = RectHelpers.traceRectToLHRect(node.new_rect);
const areaOfImpact = RectHelpers.getRectArea(oldRect) +
RectHelpers.getRectArea(newRect) -
RectHelpers.getRectOverlapArea(oldRect, newRect);
pixelsMovedPerNode.set(node.node_id, areaOfImpact);
totalAreaOfImpact += areaOfImpact;
}
for (const [nodeId, pixelsMoved] of pixelsMovedPerNode.entries()) {
let clsContribution = impactByNodeId.get(nodeId) || 0;
clsContribution += (pixelsMoved / totalAreaOfImpact) * event.weightedScore;
impactByNodeId.set(nodeId, clsContribution);
}
}
return impactByNodeId;
}
/**
* Calculates cumulative layout shifts per cluster (session) of LayoutShift
* events -- where a new cluster is created when there's a gap of more than
* 1000ms since the last LayoutShift event or the cluster is greater than
* 5000ms long -- and returns the max LayoutShift score found.
* @param {Array<LayoutShiftEvent>} layoutShiftEvents
* @return {number}
*/
static calculate(layoutShiftEvents) {
const gapMicroseconds = 1_000_000;
const limitMicroseconds = 5_000_000;
let maxScore = 0;
let currentClusterScore = 0;
let firstTs = Number.NEGATIVE_INFINITY;
let prevTs = Number.NEGATIVE_INFINITY;
for (const event of layoutShiftEvents) {
if (event.ts - firstTs > limitMicroseconds || event.ts - prevTs > gapMicroseconds) {
firstTs = event.ts;
currentClusterScore = 0;
}
prevTs = event.ts;
currentClusterScore += event.weightedScore;
maxScore = Math.max(maxScore, currentClusterScore);
}
return maxScore;
}
/**
* @param {LayoutShiftEvent[]} allFrameShiftEvents
* @param {LayoutShiftEvent[]} mainFrameShiftEvents
*/
static async computeWithSharedTraceEngine(allFrameShiftEvents, mainFrameShiftEvents) {
/** @param {LH.TraceEvent[]} events */
const run = async (events) => {
const processor = new TraceEngine.TraceProcessor({
LayoutShifts: TraceEngine.TraceHandlers.LayoutShifts,
Screenshots: TraceEngine.TraceHandlers.Screenshots,
});
// eslint-disable-next-line max-len
await processor.parse(/** @type {import('@paulirish/trace_engine').Types.TraceEvents.TraceEventData[]} */ (
events
));
if (!processor.traceParsedData) {
throw new Error('null trace engine result');
}
return processor.traceParsedData.LayoutShifts.sessionMaxScore;
};
const cumulativeLayoutShift = await run(allFrameShiftEvents.map(e => e.event));
const cumulativeLayoutShiftMainFrame = await run(mainFrameShiftEvents.map(e => e.event));
return {cumulativeLayoutShift, cumulativeLayoutShiftMainFrame};
}
/**
* @param {LH.Trace} trace
* @param {LH.Artifacts.ComputedContext} context
* @return {Promise<{cumulativeLayoutShift: number, cumulativeLayoutShiftMainFrame: number, impactByNodeId: Map<number, number>, newEngineResult?: {cumulativeLayoutShift: number, cumulativeLayoutShiftMainFrame: number}, newEngineResultDiffered: boolean}>}
*/
static async compute_(trace, context) {
const processedTrace = await ProcessedTrace.request(trace, context);
const allFrameShiftEvents =
CumulativeLayoutShift.getLayoutShiftEvents(processedTrace);
const impactByNodeId = CumulativeLayoutShift.getImpactByNodeId(allFrameShiftEvents);
const mainFrameShiftEvents = allFrameShiftEvents.filter(e => e.isMainFrame);
const cumulativeLayoutShift = CumulativeLayoutShift.calculate(allFrameShiftEvents);
const cumulativeLayoutShiftMainFrame = CumulativeLayoutShift.calculate(mainFrameShiftEvents);
// Run with the new trace engine, and only throw an error if we are running our unit tests.
// Otherwise, simply report any differences or errors to Sentry.
// TODO: TraceEngine always drops `had_recent_input` events, but Lighthouse is more lenient.
// See comment in `getLayoutShiftEvents`. We need to upstream this.
let newEngineResult;
let newEngineResultDiffered = false;
let tryNewTraceEngine = true;
if (allFrameShiftEvents.some(e => e.event.args.data?.had_recent_input)) {
tryNewTraceEngine = false;
}
if (tryNewTraceEngine) {
try {
newEngineResult =
await this.computeWithSharedTraceEngine(allFrameShiftEvents, mainFrameShiftEvents);
newEngineResultDiffered =
newEngineResult.cumulativeLayoutShift !== cumulativeLayoutShift ||
newEngineResult.cumulativeLayoutShiftMainFrame !== cumulativeLayoutShiftMainFrame;
if (newEngineResultDiffered) {
newEngineResultDiffered = true;
const expected = JSON.stringify({cumulativeLayoutShift, cumulativeLayoutShiftMainFrame});
const got = JSON.stringify(newEngineResult);
throw new Error(`new trace engine differed. expected: ${expected}, got: ${got}`);
}
} catch (err) {
console.error(err);
newEngineResultDiffered = true;
const error = new Error('Error when using new trace engine', {cause: err});
// @ts-expect-error Check for running from tests.
if (global.expect) {
throw error;
} else {
Sentry.captureException(error, {
tags: {computed: 'new-trace-engine'},
level: 'error',
extra: {
// Not sure if Sentry handles `cause`, so just in case add the info in a second place.
errorMsg: err.toString(),
},
});
}
}
}
return {
cumulativeLayoutShift,
cumulativeLayoutShiftMainFrame,
impactByNodeId,
newEngineResult,
newEngineResultDiffered,
};
}
}
const CumulativeLayoutShiftComputed = makeComputedArtifact(CumulativeLayoutShift, null);
export {CumulativeLayoutShiftComputed as CumulativeLayoutShift};