Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/afraid-buckets-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': minor
---

Add feature flag to control whether Spinner animations are synchronized
1 change: 1 addition & 0 deletions packages/react/src/FeatureFlags/DefaultFeatureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export const DefaultFeatureFlags = FeatureFlagScope.create({
primer_react_select_panel_fullscreen_on_narrow: false,
primer_react_select_panel_order_selected_at_top: false,
primer_react_select_panel_remove_active_descendant: false,
primer_react_spinner_synchronize_animations: false,
})
31 changes: 30 additions & 1 deletion packages/react/src/Spinner/Spinner.examples.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react'
import React, {useEffect, useState} from 'react'
import type {Meta} from '@storybook/react-vite'
import Spinner from './Spinner'
import {Button} from '..'
Expand Down Expand Up @@ -95,3 +95,32 @@ export const FullLifecycleVisibleLoadingText = () => {
</div>
)
}

export const SynchronizedSpinners = () => (
<>
<Spinner />
<Delay ms={250}>
<Spinner />
</Delay>
<Delay ms={750}>
<Spinner />
</Delay>
<Delay ms={1500}>
<Spinner />
</Delay>
<Delay ms={2350}>
<Spinner />
</Delay>
</>
)

function Delay({children, ms}: {children: React.ReactNode; ms: number}) {
const [show, setShow] = useState(false)

useEffect(() => {
const timeout = setTimeout(() => setShow(true), ms)
return () => clearTimeout(timeout)
}, [ms])

return show ? <>{children}</> : null
}
132 changes: 130 additions & 2 deletions packages/react/src/Spinner/Spinner.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import {clsx} from 'clsx'
import type React from 'react'
import {useState, useEffect} from 'react'
import {useCallback, useEffect, useRef, useState, useSyncExternalStore} from 'react'
import {VisuallyHidden} from '../VisuallyHidden'
import type {HTMLDataAttributes} from '../internal/internal-types'
import {useId} from '../hooks'
import classes from './Spinner.module.css'
import {clsx} from 'clsx'
import {useMedia} from '../hooks/useMedia'
import {useFeatureFlag} from '../FeatureFlags'

const sizeMap = {
small: '16px',
Expand Down Expand Up @@ -34,6 +36,8 @@ function Spinner({
delay = false,
...props
}: SpinnerProps) {
const syncAnimationsEnabled = useFeatureFlag('primer_react_spinner_synchronize_animations')
const animationRef = useSpinnerAnimation()
const size = sizeMap[sizeKey]
const hasHiddenLabel = srText !== null && ariaLabel === undefined
const labelId = useId()
Expand All @@ -58,6 +62,7 @@ function Spinner({
/* inline-flex removes the extra line height */
<span className={classes.Box}>
<svg
ref={syncAnimationsEnabled ? animationRef : undefined}
height={size}
width={size}
viewBox="0 0 16 16"
Expand Down Expand Up @@ -93,4 +98,127 @@ function Spinner({

Spinner.displayName = 'Spinner'

type Subscriber = () => void

type AnimationTimingValue = {
startTime: CSSNumberish | null
}

type AnimationTimingStore = {
subscribers: Set<Subscriber>
value: AnimationTimingValue
update(startTime: CSSNumberish): void
subscribe(subscriber: Subscriber): () => void
getSnapshot(): AnimationTimingValue
getServerSnapshot(): AnimationTimingValue
}

const animationTimingStore: AnimationTimingStore = {
subscribers: new Set<() => void>(),
value: {
startTime: null,
},
update(startTime) {
const value = {
startTime,
}
animationTimingStore.value = value
for (const subscriber of animationTimingStore.subscribers) {
subscriber()
}
},
subscribe(subscriber) {
animationTimingStore.subscribers.add(subscriber)
return () => {
animationTimingStore.subscribers.delete(subscriber)
}
},
getSnapshot() {
return animationTimingStore.value
},
getServerSnapshot() {
return animationTimingStore.value
},
}

/**
* A utility hook for reading a common `startTime` value so that all animations
* are in sync. This is a global value and is coordinated through `useSyncExternalStore`.
*/
function useAnimationTiming() {
return useSyncExternalStore(
animationTimingStore.subscribe,
animationTimingStore.getSnapshot,
animationTimingStore.getServerSnapshot,
)
}

/**
* Uses a technique from Spectrum to coordinate animations:
* @see https://github.com/adobe/react-spectrum/blob/ab5e6f3dba4235dafab9f81f8b5c506ce5f11230/packages/%40react-spectrum/s2/src/Skeleton.tsx#L21
*/
function useSpinnerAnimation() {
const ref = useRef<Animation | null>(null)
const noMotionPreference = useMedia('(prefers-reduced-motion: no-preference)', false)
const animationTiming = useAnimationTiming()
return useCallback(
(element: HTMLElement | SVGSVGElement | null) => {
if (!element) {
return
}

if (ref.current !== null) {
return
}

if (noMotionPreference) {
const cssAnimation = element.getAnimations().find((animation): animation is CSSAnimation => {
if (animation instanceof CSSAnimation) {
return animation.animationName.startsWith('Spinner') && animation.animationName.endsWith('rotate-keyframes')
}
return false
})
// If we can find a CSS Animation, pause it and we will use the Web
// Animations API to pick up from where it left off
cssAnimation?.pause()

ref.current = element.animate(
[
{
transform: 'rotate(0deg)',
},
{
transform: 'rotate(360deg)',
},
],
{
// var(--base-duration-1000)
duration: 1000,
// var(--base-easing-linear)
easing: 'cubic-bezier(0,0,1,1)',
iterations: Infinity,
},
)

// When the `startTime` value from `animationTimingStore` is `null` we
// are currently hydrating on the client. In this case, the first
// spinner to mount will set the `startTime` for all other spinners.
if (animationTiming.startTime === null) {
const startTime = cssAnimation?.startTime ?? 0

animationTimingStore.update(startTime)

// We use `startTime` to sync different animations. When all animations
// have the same startTime they will be in sync.
// @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/startTime#syncing_different_animations
ref.current.startTime = startTime
} else {
ref.current.startTime = animationTiming.startTime
}
}
},
[noMotionPreference, animationTiming],
)
}

export default Spinner
Loading