about summary refs log tree commit diff
path: root/src/lib/custom-animations/PressableScale.tsx
blob: 68315a978316d225bbd29c41787cd3cc0365a900 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import React from 'react'
import {Pressable, PressableProps} from 'react-native'
import Animated, {
  cancelAnimation,
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated'

import {isTouchDevice} from '#/lib/browser'
import {isNative} from '#/platform/detection'

const DEFAULT_TARGET_SCALE = isNative || isTouchDevice ? 0.98 : 1

export function PressableScale({
  targetScale = DEFAULT_TARGET_SCALE,
  children,
  ...rest
}: {targetScale?: number} & Exclude<
  PressableProps,
  'onPressIn' | 'onPressOut'
>) {
  const scale = useSharedValue(1)

  const style = useAnimatedStyle(() => ({
    transform: [{scale: scale.value}],
  }))

  return (
    <Pressable
      accessibilityRole="button"
      onPressIn={e => {
        'worklet'
        if (rest.onPressIn) {
          runOnJS(rest.onPressIn)(e)
        }
        cancelAnimation(scale)
        scale.value = withTiming(targetScale, {duration: 100})
      }}
      onPressOut={e => {
        'worklet'
        if (rest.onPressOut) {
          runOnJS(rest.onPressOut)(e)
        }
        cancelAnimation(scale)
        scale.value = withTiming(1, {duration: 100})
      }}
      {...rest}>
      <Animated.View style={style}>{children as React.ReactNode}</Animated.View>
    </Pressable>
  )
}