Skip to content

Commit

Permalink
feat: add useReducedMotion hook & export useIsomorphicLayout hook (#1886
Browse files Browse the repository at this point in the history
)
  • Loading branch information
joshuaellis committed Jul 13, 2022
1 parent 35da18b commit 3365cea
Show file tree
Hide file tree
Showing 20 changed files with 214 additions and 46 deletions.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
"@react-three/fiber": "^7.0.26",
"@testing-library/cypress": "^8.0.2",
"@testing-library/jest-dom": "^5.16.3",
"@testing-library/react": "^13.0.0",
"@testing-library/react": "^13.2.0",
"@types/jest": "^27.4.0",
"@types/lodash.clamp": "^4.0.6",
"@types/lodash.shuffle": "^4.2.6",
Expand Down
4 changes: 2 additions & 2 deletions packages/animated/src/withAnimated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
FluidValue,
addFluidObserver,
removeFluidObserver,
useLayoutEffect,
useIsomorphicLayoutEffect,
} from '@react-spring/shared'
import { ElementType } from '@react-spring/types'

Expand Down Expand Up @@ -66,7 +66,7 @@ export const withAnimated = (Component: any, host: HostConfig) => {
const observer = new PropsObserver(callback, deps)

const observerRef = useRef<PropsObserver>()
useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
observerRef.current = observer

// Observe the latest dependencies.
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/hooks/useChain.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { each, useLayoutEffect } from '@react-spring/shared'
import { each, useIsomorphicLayoutEffect } from '@react-spring/shared'
import { SpringRef } from '../SpringRef'
import { callProp } from '../helpers'

Expand All @@ -7,7 +7,7 @@ export function useChain(
timeSteps?: number[],
timeFrame = 1000
) {
useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (timeSteps) {
let prevDelay = 0
each(refs, (ref, i) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/hooks/useSprings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
usePrev,
useOnce,
useForceUpdate,
useLayoutEffect,
useIsomorphicLayoutEffect,
} from '@react-spring/shared'

import {
Expand Down Expand Up @@ -166,14 +166,14 @@ export function useSprings(

// New springs are created during render so users can pass them to
// their animated components, but new springs aren't cached until the
// commit phase (see the `useLayoutEffect` callback below).
// commit phase (see the `useIsomorphicLayoutEffect` callback below).
const springs = ctrls.current.map((ctrl, i) => getSprings(ctrl, updates[i]))

const context = useContext(SpringContext)
const prevContext = usePrev(context)
const hasContext = context !== prevContext && hasProps(context)

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
layoutId.current++

// Replace the cached controllers.
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/hooks/useTrail.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { each, is, useLayoutEffect } from '@react-spring/shared'
import { each, is, useIsomorphicLayoutEffect } from '@react-spring/shared'

import { Valid } from '../types/common'
import { PickAnimated, SpringValues, AsyncResult } from '../types'
Expand Down Expand Up @@ -62,7 +62,7 @@ export function useTrail(

const ref = passedRef ?? result[1]

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
each(ref.current, (ctrl, i) => {
const parent = ref.current[i + (reverse ? 1 : -1)]
if (parent) {
Expand Down
10 changes: 5 additions & 5 deletions packages/core/src/hooks/useTransition.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
useOnce,
usePrev,
each,
useLayoutEffect,
useIsomorphicLayoutEffect,
} from '@react-spring/shared'

import {
Expand Down Expand Up @@ -98,7 +98,7 @@ export function useTransition(
const usedTransitions = useRef<TransitionState[] | null>(null)
const prevTransitions = reset ? null : usedTransitions.current

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
usedTransitions.current = transitions
})

Expand Down Expand Up @@ -139,7 +139,7 @@ export function useTransition(

// Expired transitions that need clean up.
const expired = (reset && usedTransitions.current) || []
useLayoutEffect(() =>
useIsomorphicLayoutEffect(() =>
each(expired, ({ ctrl, item, key }) => {
detachRefs(ctrl, ref)
callProp(onDestroyed, item, key)
Expand Down Expand Up @@ -358,7 +358,7 @@ export function useTransition(
const hasContext = context !== prevContext && hasProps(context)

// Merge the context into each transition.
useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
if (hasContext) {
each(transitions, t => {
t.ctrl.start({ default: context })
Expand All @@ -378,7 +378,7 @@ export function useTransition(
}
})

useLayoutEffect(
useIsomorphicLayoutEffect(
() => {
/*
* if exitingTransitions.current has a size it means we're exiting before enter
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ export { SpringRef } from './SpringRef'
export { FrameValue } from './FrameValue'
export { Interpolation } from './Interpolation'
export { BailSignal } from './runAsync'
export { createInterpolator } from '@react-spring/shared'
export {
createInterpolator,
useIsomorphicLayoutEffect,
useReducedMotion,
} from '@react-spring/shared'
export { inferTo } from './helpers'

export * from './types'
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/src/hooks/useIsMounted.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useRef } from 'react'
import { useLayoutEffect } from './useLayoutEffect'
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'

export const useIsMounted = () => {
const isMounted = useRef(false)
useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
isMounted.current = true

return () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/shared/src/hooks/useIsomorphicLayoutEffect.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useLayoutEffect } from 'react'

export { useLayoutEffect as useIsomorphicLayoutEffect }
12 changes: 12 additions & 0 deletions packages/shared/src/hooks/useIsomorphicLayoutEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useEffect, useLayoutEffect } from 'react'

import { isSSR } from '../helpers'

/**
* Use this to read layout from the DOM and synchronously
* re-render if the isSSR returns true. Updates scheduled
* inside `useIsomorphicLayoutEffect` will be flushed
* synchronously in the browser, before the browser has
* a chance to paint.
*/
export const useIsomorphicLayoutEffect = isSSR() ? useEffect : useLayoutEffect
1 change: 0 additions & 1 deletion packages/shared/src/hooks/useLayoutEffect.native.ts

This file was deleted.

10 changes: 0 additions & 10 deletions packages/shared/src/hooks/useLayoutEffect.ts

This file was deleted.

40 changes: 40 additions & 0 deletions packages/shared/src/hooks/useReducedMotion.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useState } from 'react'
import { AccessibilityInfo } from 'react-native'

import { assign } from '../globals'

import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect.native'

/**
* Returns `boolean` or `null`, used to automatically
* set skipAnimations to the value of the user's
* `prefers-reduced-motion` query.
*
* The return value, post-effect, is the value of their prefered setting
*/
export const useReducedMotion = () => {
const [reducedMotion, setReducedMotion] = useState<boolean | null>(null)

useIsomorphicLayoutEffect(() => {
const handleMediaChange = (isReducedMotion: boolean) => {
setReducedMotion(isReducedMotion)

assign({
skipAnimation: isReducedMotion,
})
}

AccessibilityInfo.isReduceMotionEnabled().then(handleMediaChange)

const motionSubscription = AccessibilityInfo.addEventListener(
'reduceMotionChanged',
handleMediaChange
)

return () => {
motionSubscription.remove()
}
}, [])

return reducedMotion
}
91 changes: 91 additions & 0 deletions packages/shared/src/hooks/useReducedMotion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { act, renderHook } from '@testing-library/react'

import { useReducedMotion } from './useReducedMotion'

describe('useReducedMotion', () => {
let EVENTS: Record<string, MediaQueryHandler> = {}

const removeEventListenerMock = jest.fn()

type MediaQueryHandler = (mediaQuery: typeof mqDefaults) => void

const mqDefaults = {
matches: false,
onchange: null,
addEventListener: (name: string, handle: MediaQueryHandler) => {
EVENTS[name] = handle
},
removeEventListener: removeEventListenerMock,
}

afterEach(() => {
// reset events
EVENTS = {}

jest.clearAllMocks()
})

it('returns true if "Reduce motion" is enabled', async () => {
window.matchMedia = jest.fn().mockImplementation(query => {
return {
...mqDefaults,
matches: true,
media: query,
}
})

const { result } = renderHook(useReducedMotion)

expect(result.current).toBe(true)
})

it('returns false if "Reduce motion" is disabled', async () => {
window.matchMedia = jest.fn().mockImplementation(query => {
return {
...mqDefaults,
media: query,
}
})

const { result } = renderHook(useReducedMotion)

expect(result.current).toBe(false)
})

it('handles change of "prefers-reduce-motion" media query value', async () => {
window.matchMedia = jest.fn().mockImplementation(query => {
return {
...mqDefaults,
media: query,
}
})

const { result } = renderHook(useReducedMotion)

expect(result.current).toBe(false)

act(() => {
EVENTS.change({
...mqDefaults,
matches: true,
})
})

expect(result.current).toBe(true)
})

it('successfully removes listener on unmount', () => {
window.matchMedia = jest.fn().mockImplementation(query => {
return {
...mqDefaults,
media: query,
}
})

const { unmount } = renderHook(useReducedMotion)

unmount()

expect(removeEventListenerMock).toHaveBeenCalled()
})
})
37 changes: 37 additions & 0 deletions packages/shared/src/hooks/useReducedMotion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useState } from 'react'

import { assign } from '../globals'
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'

/**
* Returns `boolean` or `null`, used to automatically
* set skipAnimations to the value of the user's
* `prefers-reduced-motion` query.
*
* The return value, post-effect, is the value of their prefered setting
*/
export const useReducedMotion = () => {
const [reducedMotion, setReducedMotion] = useState<boolean | null>(null)

useIsomorphicLayoutEffect(() => {
const mql = window.matchMedia('(prefers-reduced-motion)')

const handleMediaChange = (e: MediaQueryListEvent | MediaQueryList) => {
setReducedMotion(e.matches)

assign({
skipAnimation: e.matches,
})
}

handleMediaChange(mql)

mql.addEventListener('change', handleMediaChange)

return () => {
mql.removeEventListener('change', handleMediaChange)
}
}, [])

return reducedMotion
}
3 changes: 2 additions & 1 deletion packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export * from './hooks/useForceUpdate'
export * from './hooks/useMemoOne'
export * from './hooks/useOnce'
export * from './hooks/usePrev'
export * from './hooks/useLayoutEffect'
export * from './hooks/useIsomorphicLayoutEffect'
export * from './hooks/useReducedMotion'

export * from './fluids'

Expand Down
Loading

1 comment on commit 3365cea

@vercel
Copy link

@vercel vercel bot commented on 3365cea Jul 13, 2022

Choose a reason for hiding this comment

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

Please sign in to comment.