Unverified Commit 07048186 authored by rauno's avatar rauno Committed by GitHub

[dev-overlay] Ignore animations on page load (#76834)

The current animation strategy for our Dev Tools surface does not work. 



https://github.com/user-attachments/assets/a0ca5459-9d5a-4d90-af00-b071d43581e0

On page load, several animations can be observed:
- Width growth from `0` → `auto`
- Issue count translates and fades, along with the plural `s` suffix
- A subtle scale bounce effect plays

All these animations are state transitions, and thus we should ignore
them completely on page load or on high-frequency updates where
animating is undesirable, e.g. sometimes `issueCount` will receive
updates faster than the animation can run.

This PR implements checks to guard the animations from being executed on
page load, _and only_ during state transitions.

To review, it is worth checking out the
[/animation-test](https://github.com/vercel/next.js/blob/a6e6fe635b712020d4ea2d027040d838eb5941c6/test/development/app-dir/hydration-error-count/app/animation-test/page.tsx)
fixture I've set up in this PR.

After these changes, the experience is as follows—no animations on page
load, but only on subsequent low-frequency updates (count change, or
collapse of the surface):



https://github.com/user-attachments/assets/7b2d5e0d-64ec-4165-b5e2-85489bd00a2c



_Note: I am not using Storybook for a page load reference, the apps
under `test/development/app-dir/*` are more reliable._
parent 0abd8771
...@@ -269,7 +269,7 @@ function DevToolsPopover({ ...@@ -269,7 +269,7 @@ function DevToolsPopover({
// Reset the toast component's default positions. // Reset the toast component's default positions.
bottom: 'initial', bottom: 'initial',
left: 'initial', left: 'initial',
[vertical]: '10px', [vertical]: '20px',
[horizontal]: '20px', [horizontal]: '20px',
} as CSSProperties } as CSSProperties
} }
......
import { forwardRef, useEffect, useRef, useState } from 'react' import { forwardRef, useEffect, useMemo, useRef, useState } from 'react'
import { css } from '../../../../utils/css' import { css } from '../../../../utils/css'
import mergeRefs from '../../../utils/merge-refs' import mergeRefs from '../../../utils/merge-refs'
import { useMinimumLoadingTimeMultiple } from './use-minimum-loading-time-multiple' import { useMinimumLoadingTimeMultiple } from './use-minimum-loading-time-multiple'
...@@ -16,48 +16,6 @@ const SIZE = '2.25rem' // 36px in 16px base ...@@ -16,48 +16,6 @@ const SIZE = '2.25rem' // 36px in 16px base
const SIZE_PX = 36 const SIZE_PX = 36
const SHORT_DURATION_MS = 150 const SHORT_DURATION_MS = 150
/**
* A hook that creates an animated state based on changes to a dependency.
* When the dependency changes and passes the shouldSkip check, it triggers
* an animation state that lasts for the specified duration.
*
* @param dep The dependency to watch for changes
* @param config Configuration object containing:
* - shouldSkip: Function to determine if animation should be skipped
* - animationDuration: Duration of the animation in milliseconds
* @returns Boolean indicating if animation is currently active
*/
const useAnimated = <T,>(
dep: T,
config: { shouldSkip: (dep: T) => boolean; animationDuration: number }
) => {
const { shouldSkip: _shouldSkip, animationDuration } = config
const shouldSkipRef = useRef(_shouldSkip) // ensure stable reference in case it's not
const [animatedDep, setAnimatedDep] = useState(false)
const isInitialRef = useRef(true)
useEffect(() => {
if (isInitialRef.current) {
isInitialRef.current = false
return
}
if (shouldSkipRef.current(dep)) {
return
}
setAnimatedDep(true)
const timeoutId = setTimeout(() => {
setAnimatedDep(false)
}, animationDuration)
return () => clearTimeout(timeoutId)
}, [dep, animationDuration])
return animatedDep
}
export const NextLogo = forwardRef(function NextLogo( export const NextLogo = forwardRef(function NextLogo(
{ {
disabled, disabled,
...@@ -73,26 +31,32 @@ export const NextLogo = forwardRef(function NextLogo( ...@@ -73,26 +31,32 @@ export const NextLogo = forwardRef(function NextLogo(
) { ) {
const hasError = issueCount > 0 const hasError = issueCount > 0
const [isErrorExpanded, setIsErrorExpanded] = useState(hasError) const [isErrorExpanded, setIsErrorExpanded] = useState(hasError)
const newErrorDetected = useAnimated(issueCount, {
shouldSkip: (count) => count === 0,
animationDuration: SHORT_DURATION_MS,
})
const [dismissed, setDismissed] = useState(false) const [dismissed, setDismissed] = useState(false)
const newErrorDetected = useUpdateAnimation(issueCount, SHORT_DURATION_MS)
const triggerRef = useRef<HTMLButtonElement | null>(null) const triggerRef = useRef<HTMLButtonElement | null>(null)
const ref = useRef<HTMLDivElement | null>(null) const ref = useRef<HTMLDivElement | null>(null)
const width = useMeasureWidth(ref) const [measuredWidth, pristine] = useMeasureWidth(ref)
const isLoading = useMinimumLoadingTimeMultiple( const isLoading = useMinimumLoadingTimeMultiple(
isDevBuilding || isDevRendering isDevBuilding || isDevRendering
) )
const isExpanded = isErrorExpanded || disabled
const style = useMemo(() => {
let width: number | string = SIZE
// Animates the badge, if expanded
if (measuredWidth > SIZE_PX) width = measuredWidth
// No animations on page load, assume the intrinsic width immediately
if (pristine && hasError) width = 'auto'
// Default state, collapsed
return { width }
}, [measuredWidth, pristine, hasError])
useEffect(() => { useEffect(() => {
setIsErrorExpanded(hasError) setIsErrorExpanded(hasError)
}, [hasError]) }, [hasError])
const isExpanded = isErrorExpanded || disabled
return ( return (
<div <div
data-next-badge-root data-next-badge-root
...@@ -332,7 +296,9 @@ export const NextLogo = forwardRef(function NextLogo( ...@@ -332,7 +296,9 @@ export const NextLogo = forwardRef(function NextLogo(
[data-issues-count-plural] { [data-issues-count-plural] {
display: inline-block; display: inline-block;
animation: fadeIn 300ms var(--timing) forwards; &[data-animate='true'] {
animation: fadeIn 300ms var(--timing) forwards;
}
} }
.path0 { .path0 {
...@@ -426,9 +392,7 @@ export const NextLogo = forwardRef(function NextLogo( ...@@ -426,9 +392,7 @@ export const NextLogo = forwardRef(function NextLogo(
data-error={hasError} data-error={hasError}
data-error-expanded={isExpanded} data-error-expanded={isExpanded}
data-animate={newErrorDetected} data-animate={newErrorDetected}
style={{ style={style}
width: hasError && width > SIZE_PX ? width : SIZE,
}}
> >
<div ref={ref}> <div ref={ref}>
{/* Children */} {/* Children */}
...@@ -466,7 +430,13 @@ export const NextLogo = forwardRef(function NextLogo( ...@@ -466,7 +430,13 @@ export const NextLogo = forwardRef(function NextLogo(
<div> <div>
Issue Issue
{issueCount > 1 && ( {issueCount > 1 && (
<span aria-hidden data-issues-count-plural> <span
aria-hidden
data-issues-count-plural
// This only needs to animate once the count changes from 1 -> 2,
// otherwise it should stay static between re-renders.
data-animate={newErrorDetected && issueCount === 2}
>
s s
</span> </span>
)} )}
...@@ -518,8 +488,11 @@ function AnimateCount({ ...@@ -518,8 +488,11 @@ function AnimateCount({
) )
} }
function useMeasureWidth(ref: React.RefObject<HTMLDivElement | null>) { function useMeasureWidth(
ref: React.RefObject<HTMLDivElement | null>
): [number, boolean] {
const [width, setWidth] = useState<number>(0) const [width, setWidth] = useState<number>(0)
const [pristine, setPristine] = useState(true)
useEffect(() => { useEffect(() => {
const el = ref.current const el = ref.current
...@@ -530,14 +503,52 @@ function useMeasureWidth(ref: React.RefObject<HTMLDivElement | null>) { ...@@ -530,14 +503,52 @@ function useMeasureWidth(ref: React.RefObject<HTMLDivElement | null>) {
const observer = new ResizeObserver(() => { const observer = new ResizeObserver(() => {
const { width: w } = el.getBoundingClientRect() const { width: w } = el.getBoundingClientRect()
setWidth(w) setWidth((prevWidth) => {
if (prevWidth !== 0) {
setPristine(false)
}
return w
})
}) })
observer.observe(el) observer.observe(el)
return () => observer.disconnect() return () => observer.disconnect()
}, [ref]) }, [ref])
return width return [width, pristine]
}
function useUpdateAnimation(issueCount: number, animationDurationMs = 0) {
const lastUpdatedTimeStamp = useRef<number | null>(null)
const [animate, setAnimate] = useState(false)
useEffect(() => {
if (issueCount > 0) {
const deltaMs = lastUpdatedTimeStamp.current
? Date.now() - lastUpdatedTimeStamp.current
: -1
lastUpdatedTimeStamp.current = Date.now()
// We don't animate if `issueCount` changes too quickly
if (deltaMs <= animationDurationMs) {
return
}
setAnimate(true)
// It is important to use a CSS transitioned state, not a CSS keyframed animation
// because if the issue count increases faster than the animation duration, it
// will abruptly stop and not transition smoothly back to its original state.
const timeoutId = window.setTimeout(() => {
setAnimate(false)
}, animationDurationMs)
return () => {
clearTimeout(timeoutId)
}
}
}, [issueCount, animationDurationMs])
return animate
} }
function NextMark({ function NextMark({
......
'use client'
import { useEffect } from 'react'
/**
* This page is to verify that the Dev Tools surface animates as expected and without jank:
*
* 1. When the page loads with "1 Issue" present,
* no animations should trigger (count change, width growth, etc.).
* The surface should assume its intrinsic position immediately,
* while still animating when collapsed from (×).
*
* 2. When multiple errors come in with little delay inbetween them,
* the count _should not_ animate when it changes because it will
* look janky when the `deltaMs` between changes is less than the `animationDurationMs`.
*
* 3. When another error comes in, and `deltaMs` is greater, the surface should
* subtly bounce and animate the count.
*/
// Play with this between `1` and `2`
// to make sure the surface doesn't animate the plural form (s)
const ERROR_COUNT = 2
export default function Page() {
const clx = typeof window === 'undefined' ? 'server' : 'client'
useEffect(() => {
setTimeout(() => {
throw new Error('runtime error')
}, 2000)
}, [])
return <p className={clx}>{ERROR_COUNT >= 2 && <p>hey</p>}</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment