react-native-paper icon indicating copy to clipboard operation
react-native-paper copied to clipboard

M3 styled switch

Open yuameshi opened this issue 3 years ago • 42 comments

Is your feature request related to a problem? Please describe.

get a m3 styled switch component

Describe the solution you'd like

just edit stylesheet

Additional context

Official document

Official document

Diff between M2 & M3

Expected style(M3)

Current style(M2)

yuameshi avatar Apr 02 '23 06:04 yuameshi

Made a version that switch state strictly follows value prop

(only tested on Android)

import { useCallback, useEffect, useState } from 'react'
import type { StyleProp, ViewStyle } from 'react-native'
import { Pressable, StyleSheet, View } from 'react-native'
import {
  Gesture,
  GestureDetector,
  GestureHandlerRootView,
} from 'react-native-gesture-handler'
import { Icon, useTheme } from 'react-native-paper'
import type { IconSource } from 'react-native-paper/lib/typescript/components/Icon'
import Animated, {
  Extrapolation,
  interpolate,
  interpolateColor,
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated'

export interface Props {
  value: boolean
  onPress?: () => void
  fluid?: boolean
  switchOnIcon?: IconSource // IconSource from 'react-native-paper/lib/typescript/components/Icon'
  switchOffIcon?: IconSource // IconSource from 'react-native-paper/lib/typescript/components/Icon'
  disabled?: boolean
  style?: StyleProp<ViewStyle>
}

const styles = StyleSheet.create({
  stateOuter: {
    justifyContent: 'center',
    height: 32,
    width: 52,
    alignItems: 'center',
    position: 'absolute',
  },
})

// https://github.com/callstack/react-native-paper/issues/3797#issuecomment-1859135794
export default function Switch({
  value,
  onPress,
  switchOnIcon,
  switchOffIcon,
  disabled,
  style,
}: Props) {
  const theme = useTheme()
  const position = useSharedValue(value ? 10 : -10)
  const handleHeight = useSharedValue(value ? 24 : 16)
  const handleWidth = useSharedValue(value ? 24 : 16)
  const [isPressed, setIsPressed] = useState(false)

  const syncButtonState = useCallback(() => {
    position.value = withTiming(value ? 10 : -10, { duration: 250 })
    handleHeight.value = withTiming(value ? 24 : 16, { duration: 100 })
    handleWidth.value = withTiming(value ? 24 : 16, { duration: 100 })
  }, [value])

  const callbackFunction = () => {
    onPress?.()
    syncButtonState()
  }

  const pan = Gesture.Pan()
    .activateAfterLongPress(100)
    .enabled(!disabled)
    .onTouchesUp(() => setIsPressed(false))
    .runOnJS(true)
    .hitSlop(disabled ? -30 : 0)
    .onStart(() => {
      setIsPressed(true)
      handleHeight.value = withTiming(28, { duration: 160 })
      handleWidth.value = withTiming(28, { duration: 160 })
    })
    .onChange((event) => {
      if (position.value + event.translationX / 10 < -10) {
        position.value = -10
        return
      }
      if (position.value + event.translationX / 10 > 10) {
        position.value = 10
        return
      }
      position.value += event.translationX / 10
    })
    .onEnd(() => {
      setIsPressed(false)
      if (position.value > 0) {
        position.value = withTiming(10)
        handleHeight.value = withTiming(24, { duration: 160 })
        handleWidth.value = withTiming(24, { duration: 160 })
        if (!value) runOnJS(callbackFunction)()
      } else if (position.value < 0) {
        position.value = withTiming(-10)
        handleHeight.value = withTiming(16, { duration: 160 })
        handleWidth.value = withTiming(16, { duration: 160 })
        if (value) runOnJS(callbackFunction)()
      }
    })
  // #endregion

  const handleStyle = useAnimatedStyle(() =>
    disabled
      ? {
          transform: [{ translateX: value ? 10 : -10 }],
          height: value ? 24 : 16,
          width: value ? 24 : 16,
          marginVertical: 'auto',
          minHeight: switchOffIcon ? 24 : 16,
          minWidth: switchOffIcon ? 24 : 16,
          opacity: value ? 1 : 0.36,
          backgroundColor: value ? theme.colors.surface : theme.colors.onSurface,
          borderRadius: 20,
          justifyContent: 'center',
          alignItems: 'center',
        }
      : {
          transform: [{ translateX: position.value }],
          opacity: 1,
          height: handleHeight.value,
          width: handleWidth.value,
          marginVertical: 'auto',
          minHeight: switchOffIcon ? 24 : 16,
          minWidth: switchOffIcon ? 24 : 16,
          backgroundColor: interpolateColor(
            position.value,
            [-10, 10],
            [theme.colors.outline, theme.colors.onPrimary],
          ),
          borderRadius: 20,
          justifyContent: 'center',
          alignItems: 'center',
        },
  )
  const trackStyle = useAnimatedStyle(() =>
    disabled
      ? {
          borderWidth: 2,
          borderRadius: 16,
          justifyContent: 'center',
          height: 32,
          width: 52,
          opacity: 0.12,
          backgroundColor: value ? theme.colors.onSurface : theme.colors.surfaceVariant,
          borderColor: theme.colors.onSurface,
        }
      : {
          alignItems: 'center',
          opacity: 1,
          backgroundColor: interpolateColor(
            position.value,
            [-10, 10],
            [theme.colors.surfaceVariant, theme.colors.primary],
          ),
          borderColor: interpolateColor(
            position.value,
            [-10, 10],
            [theme.colors.outline, theme.colors.primary],
          ),
          borderWidth: 2,
          borderRadius: 16,
          justifyContent: 'center',
          height: 32,
          width: 52,
        },
  )
  const handleOutlineStyle = useAnimatedStyle(() => ({
    height: 40,
    width: 40,
    borderRadius: 20,
    position: 'absolute',
    transform: [{ translateX: position.value }],
    backgroundColor: !isPressed
      ? 'transparent'
      : interpolateColor(
          position.value,
          [-10, 10],
          [theme.colors.onSurface, theme.colors.primary],
        ),
    alignItems: 'center',
    opacity: 0.18,
    justifyContent: 'center',
  }))
  const iconOnStyle = useAnimatedStyle(() => ({
    opacity: disabled
      ? 0.38
      : interpolate(position.value, [0, 10], [0, 1], Extrapolation.CLAMP),
    overflow: 'hidden',
    transform: [
      {
        scale: interpolate(position.value, [0, 10], [0, 1], Extrapolation.CLAMP),
      },
      {
        rotate: `${interpolate(
          position.value,
          [0, 10],
          [-90, 0],
          Extrapolation.CLAMP,
        )}deg`,
      },
    ],
  }))
  const iconOffStyle = useAnimatedStyle(() => ({
    position: 'absolute',
    opacity: disabled
      ? 0.38
      : interpolate(position.value, [-10, 0], [1, 0], Extrapolation.CLAMP),
    overflow: 'hidden',
    transform: [
      {
        scale: interpolate(position.value, [-10, 0], [1, 0], Extrapolation.CLAMP),
      },
      {
        rotate: `${interpolate(
          position.value,
          [-10, 0],
          [-90, 0],
          Extrapolation.CLAMP,
        )}deg`,
      },
    ],
    // width: interpolate(position.value, [5, 10], [0, 16]),
  }))

  useEffect(() => {
    syncButtonState()
  }, [value])

  return (
    <View style={[{ borderRadius: 20, backgroundColor: theme.colors.surface }, style]}>
      <View pointerEvents="none" style={styles.stateOuter}>
        <Animated.View style={handleOutlineStyle} key={3}></Animated.View>
      </View>
      <Animated.View style={trackStyle} key={1}>
        <GestureHandlerRootView>
          <GestureDetector gesture={pan}>
            <Pressable
              disabled={disabled}
              style={{
                justifyContent: 'center',
                height: 32,
                width: 52,
                alignItems: 'center',
              }}
              onPress={() => {
                setIsPressed(true)
                try {
                  callbackFunction()
                } finally {
                  setIsPressed(false)
                }
              }}
            ></Pressable>
          </GestureDetector>
        </GestureHandlerRootView>
      </Animated.View>
      <View pointerEvents="none" style={styles.stateOuter}>
        <Animated.View style={handleStyle} key={2}>
          {switchOnIcon ? (
            <Animated.View key={10} style={iconOnStyle}>
              <Icon
                source={switchOnIcon}
                size={16}
                color={
                  disabled ? theme.colors.onSurface : theme.colors.onPrimaryContainer
                }
              />
            </Animated.View>
          ) : null}
          {switchOffIcon ? (
            <Animated.View key={9} style={iconOffStyle}>
              <Icon source={switchOffIcon} size={16} color={theme.colors.surface} />
            </Animated.View>
          ) : null}
        </Animated.View>
      </View>
    </View>
  )
}

lgc2333 avatar Jun 22 '25 12:06 lgc2333

  • Fixed in https://github.com/callstack/react-native-paper/pull/4957

rollingmoai avatar May 29 '26 06:05 rollingmoai