Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(browser): Set artificial zero-value CLS measurement to report no layout shift #12989

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="content">
Some content
Copy link
Member Author

@Lms24 Lms24 Jul 19, 2024

Choose a reason for hiding this comment

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

There needs to be something visible on the page because we (rightfully) only send CLS measurements if FCP was also recorded.

</div>
</body>
</html>
Copy link
Member Author

@Lms24 Lms24 Jul 22, 2024

Choose a reason for hiding this comment

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

Note: We have 3 more integration tests covering >0 CLS values which all still pass. So I don't think that this change somehow causes actual layout shift values to be ignored.

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect } from '@playwright/test';
import type { Event } from '@sentry/types';

import { sentryTest } from '../../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest, shouldSkipTracingTest } from '../../../../utils/helpers';

sentryTest.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 800, height: 1200 });
});

sentryTest('captures 0 CLS if the browser supports reporting CLS', async ({ getLocalTestPath, page, browserName }) => {
if (shouldSkipTracingTest() || browserName !== 'chromium') {
sentryTest.skip();
}

const url = await getLocalTestPath({ testDir: __dirname });
const transactionEvent = await getFirstSentryEnvelopeRequest<Event>(page, url);

expect(transactionEvent.measurements).toBeDefined();
expect(transactionEvent.measurements?.cls?.value).toBe(0);

// but no source entry (no source if there is no layout shift)
expect(transactionEvent.contexts?.trace?.data?.['cls.source.1']).toBeUndefined();
});

sentryTest(
"doesn't capture 0 CLS if the browser doesn't support reporting CLS",
async ({ getLocalTestPath, page, browserName }) => {
if (shouldSkipTracingTest() || browserName === 'chromium') {
sentryTest.skip();
}

const url = await getLocalTestPath({ testDir: __dirname });
const transactionEvent = await getFirstSentryEnvelopeRequest<Event>(page, `${url}#no-cls`);

expect(transactionEvent.measurements).toBeDefined();
expect(transactionEvent.measurements?.cls).toBeUndefined();

expect(transactionEvent.contexts?.trace?.data?.['cls.source.1']).toBeUndefined();
},
);
28 changes: 28 additions & 0 deletions packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ export { startTrackingINP, registerInpInteractionListener } from './inp';

/** Starts tracking the Cumulative Layout Shift on the current page. */
function _trackCLS(): () => void {
trySetZeroClsValue();

return addClsInstrumentationHandler(({ metric }) => {
const entry = metric.entries[metric.entries.length - 1];
if (!entry) {
Expand All @@ -227,6 +229,32 @@ function _trackCLS(): () => void {
}, true);
}

/**
* Why does this function exist? A very good question!
*
* The `PerformanceObserver` emits `LayoutShift` entries whenever a layout shift occurs.
* If none occurs (which is great!), the observer will never emit any entries. Makes sense so far!
*
* This is problematic for the Sentry product though. We can't differentiate between a CLS of 0 and not having received
* CLS data at all. So in both cases, we'd show users that the CLS score simply is not available. When in fact, it can
* be 0, which is a very good score. This function is a workaround to emit a CLS of 0 right at the start of
* listening to CLS events. This way, we can differentiate between a CLS of 0 and no CLS at all. If a layout shift
* occurs later, the real CLS value will be emitted and the 0 value will be ignored.
* We also only send this artificial 0 value if the browser supports reporting the `layout-shift` entry type.
*/
function trySetZeroClsValue(): void {
try {
const canReportLayoutShift = PerformanceObserver.supportedEntryTypes.includes('layout-shift');
if (canReportLayoutShift) {
DEBUG_BUILD && logger.log('[Measurements] Adding CLS 0');
_measurements['cls'] = { value: 0, unit: '' };
// TODO: Do we have to set _clsEntry here as well? If so, what attribution should we give it?
}
} catch {
// catching and ignoring access errors for bundle size reduction
}
}

/** Starts tracking the Largest Contentful Paint on the current page. */
function _trackLCP(): () => void {
return addLcpInstrumentationHandler(({ metric }) => {
Expand Down
Loading