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

✨ [RUMF-777] implement Cumulative Layout Shift #628

Merged
merged 6 commits into from
Nov 24, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
22 changes: 19 additions & 3 deletions packages/rum/src/browser/performanceCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,26 @@ export interface RumFirstInputTiming {
processingStart: number
}

export interface RumLayoutShiftTiming {
entryType: 'layout-shift'
value: number
hadRecentInput: boolean
}

export type RumPerformanceEntry =
| RumPerformanceResourceTiming
| RumPerformanceLongTaskTiming
| RumPerformancePaintTiming
| RumPerformanceNavigationTiming
| RumLargestContentfulPaintTiming
| RumFirstInputTiming
| RumLayoutShiftTiming

function supportPerformanceObject() {
return window.performance !== undefined && 'getEntries' in performance
}

function supportPerformanceTimingEvent(entryType: string) {
export function supportPerformanceTimingEvent(entryType: string) {
return (
(window as BrowserWindow).PerformanceObserver &&
PerformanceObserver.supportedEntryTypes !== undefined &&
Expand All @@ -100,7 +107,15 @@ export function startPerformanceCollection(lifeCycle: LifeCycle, configuration:
const observer = new PerformanceObserver(
monitor((entries) => handlePerformanceEntries(lifeCycle, configuration, entries.getEntries()))
)
const entryTypes = ['resource', 'navigation', 'longtask', 'paint', 'largest-contentful-paint', 'first-input']
const entryTypes = [
'resource',
'navigation',
'longtask',
'paint',
'largest-contentful-paint',
'first-input',
'layout-shift',
]

observer.observe({ entryTypes })

Expand Down Expand Up @@ -267,7 +282,8 @@ function handlePerformanceEntries(lifeCycle: LifeCycle, configuration: Configura
entry.entryType === 'paint' ||
entry.entryType === 'longtask' ||
entry.entryType === 'largest-contentful-paint' ||
entry.entryType === 'first-input'
entry.entryType === 'first-input' ||
entry.entryType === 'layout-shift'
) {
handleRumPerformanceEntry(lifeCycle, configuration, entry as RumPerformanceEntry)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -885,4 +885,66 @@ describe('rum view measures', () => {
expect(getHandledCount()).toEqual(3)
})
})

describe('cumulativeLayoutShift', () => {
let isLayoutShiftSupported: boolean
beforeEach(() => {
if (!('PerformanceObserver' in window) || !('supportedEntryTypes' in PerformanceObserver)) {
pending('No PerformanceObserver support')
}
isLayoutShiftSupported = true
spyOnProperty(PerformanceObserver, 'supportedEntryTypes', 'get').and.callFake(() => {
return isLayoutShiftSupported ? ['layout-shift'] : []
})
})

it('should be initialized to 0', () => {
setupBuilder.build()
expect(getHandledCount()).toEqual(1)
expect(getViewEvent(0).cumulativeLayoutShift).toBe(0)
})

it('should be initialized to undefined if layout-shift is not supported', () => {
isLayoutShiftSupported = false
setupBuilder.build()
expect(getHandledCount()).toEqual(1)
expect(getViewEvent(0).cumulativeLayoutShift).toBe(undefined)
})

it('should accmulate layout shift values', () => {
const { lifeCycle, clock } = setupBuilder.withFakeClock().build()

lifeCycle.notify(LifeCycleEventType.PERFORMANCE_ENTRY_COLLECTED, {
entryType: 'layout-shift',
hadRecentInput: false,
value: 0.1,
})

lifeCycle.notify(LifeCycleEventType.PERFORMANCE_ENTRY_COLLECTED, {
entryType: 'layout-shift',
hadRecentInput: false,
value: 0.2,
})

clock.tick(THROTTLE_VIEW_UPDATE_PERIOD)

expect(getHandledCount()).toEqual(2)
expect(getViewEvent(1).cumulativeLayoutShift).toBe(0.1 + 0.2)
})

it('should ignore entries with recent input', () => {
const { lifeCycle, clock } = setupBuilder.withFakeClock().build()

lifeCycle.notify(LifeCycleEventType.PERFORMANCE_ENTRY_COLLECTED, {
entryType: 'layout-shift',
hadRecentInput: true,
value: 0.1,
})

clock.tick(THROTTLE_VIEW_UPDATE_PERIOD)

expect(getHandledCount()).toEqual(1)
expect(getViewEvent(0).cumulativeLayoutShift).toBe(0)
})
})
})
46 changes: 45 additions & 1 deletion packages/rum/src/domain/rumEventsCollection/view/trackViews.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { addEventListener, DOM_EVENT, generateUUID, monitor, ONE_MINUTE, throttle } from '@datadog/browser-core'
import { addEventListener, DOM_EVENT, generateUUID, monitor, noop, ONE_MINUTE, throttle } from '@datadog/browser-core'

import { supportPerformanceTimingEvent } from '../../../browser/performanceCollection'
import { LifeCycle, LifeCycleEventType } from '../../lifeCycle'
import { EventCounts, trackEventCounts } from '../../trackEventCounts'
import { waitIdlePageActivity } from '../../trackPageActivities'
Expand All @@ -16,6 +17,7 @@ export interface View {
duration: number
loadingTime?: number | undefined
loadingType: ViewLoadingType
cumulativeLayoutShift?: number
}

export interface ViewCreatedEvent {
Expand Down Expand Up @@ -105,6 +107,7 @@ function newView(
}
let timings: Timings = {}
let documentVersion = 0
let cumulativeLayoutShift: number | undefined
let loadingTime: number | undefined
let endTime: number | undefined
let location: Location = { ...initialLocation }
Expand Down Expand Up @@ -132,12 +135,24 @@ function newView(

const { stop: stopActivityLoadingTimeTracking } = trackActivityLoadingTime(lifeCycle, setActivityLoadingTime)

let stopCLSTracking: () => void
if (isLayoutShiftSupported()) {
cumulativeLayoutShift = 0
;({ stop: stopCLSTracking } = trackLayoutShift(lifeCycle, (layoutShift) => {
cumulativeLayoutShift! += layoutShift
scheduleViewUpdate()
}))
} else {
stopCLSTracking = noop
}

// Initial view update
triggerViewUpdate()

function triggerViewUpdate() {
documentVersion += 1
lifeCycle.notify(LifeCycleEventType.VIEW_UPDATED, {
cumulativeLayoutShift,
documentVersion,
eventCounts,
id,
Expand All @@ -157,6 +172,7 @@ function newView(
endTime = performance.now()
stopEventCountsTracking()
stopActivityLoadingTimeTracking()
stopCLSTracking()
},
isDifferentView(otherLocation: Location) {
return (
Expand Down Expand Up @@ -250,3 +266,31 @@ function trackActivityLoadingTime(lifeCycle: LifeCycle, callback: (loadingTimeVa

return { stop: stopWaitIdlePageActivity }
}

/**
* Track layout shifts (LS) occuring during the Views. This yields multiple values that can be
* added up to compute the cumulated layout shift (CLS).
*
* See isLayoutShiftSupported to check for browser support.
*
* Documentation: https://web.dev/cls/
* Reference implementation: https://github.com/GoogleChrome/web-vitals/blob/master/src/getCLS.ts
*/
function trackLayoutShift(lifeCycle: LifeCycle, callback: (layoutShift: number) => void) {
const { unsubscribe: stop } = lifeCycle.subscribe(LifeCycleEventType.PERFORMANCE_ENTRY_COLLECTED, (entry) => {
if (entry.entryType === 'layout-shift' && !entry.hadRecentInput) {
callback(entry.value)
}
})

return {
stop,
}
}

/**
* Check whether `layout-shift` is supported by the browser.
*/
function isLayoutShiftSupported() {
return supportPerformanceTimingEvent('layout-shift')
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ describe('viewCollection V2', () => {
it('should create view from view update', () => {
const { lifeCycle, rawRumEventsV2 } = setupBuilder.build()
const view = {
cumulativeLayoutShift: 1,
documentVersion: 3,
duration: 100,
eventCounts: {
Expand Down Expand Up @@ -136,6 +137,7 @@ describe('viewCollection V2', () => {
action: {
count: 10,
},
cumulativeLayoutShift: 1,
domComplete: 10 * 1e6,
domContentLoaded: 10 * 1e6,
domInteractive: 10 * 1e6,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ function processViewUpdateV2(view: View) {
action: {
count: view.eventCounts.userActionCount,
},
cumulativeLayoutShift: view.cumulativeLayoutShift,
domComplete: msToNs(view.timings.domComplete),
domContentLoaded: msToNs(view.timings.domContentLoaded),
domInteractive: msToNs(view.timings.domInteractive),
Expand Down
1 change: 1 addition & 0 deletions packages/rum/src/typesV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export interface RumViewEventV2 {
loadingType: ViewLoadingType
firstContentfulPaint?: number
firstInputDelay?: number
cumulativeLayoutShift?: number
largestContentfulPaint?: number
domInteractive?: number
domContentLoaded?: number
Expand Down