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
71 changes: 71 additions & 0 deletions packages/components/src/__tests__/Switch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,77 @@ describe('Switch', () => {
})
})

// MD3 track: 52 x 32 dp with a 2 dp outline. The thumb center sits 16 dp
// from the start edge when off and 36 dp when on, at every thumb size.
describe('thumb geometry', () => {
const BORDER = 2

function thumb() {
const style = getStyle(screen.getByTestId('switch-thumb'))
const transform = style.transform as { translateX?: number }[]
const translateX = transform.find(
(t) => t.translateX !== undefined,
)?.translateX
const size = style.width as number
const start = BORDER + (translateX as number)
return { size, start, center: start + size / 2, end: start + size }
}

it('centers the 16 dp off thumb 16 dp from the start edge', () => {
renderSettled(<Switch value={false} onValueChange={() => {}} />)
expect(thumb()).toMatchObject({ size: 16, center: 16 })
})

it('centers the 24 dp on thumb 36 dp from the start edge', () => {
renderSettled(<Switch value onValueChange={() => {}} />)
expect(thumb()).toMatchObject({ size: 24, center: 36 })
})

it('centers a 24 dp off thumb with an unselected icon at 16 dp', () => {
renderSettled(
<Switch
value={false}
onValueChange={() => {}}
unselectedIcon="close"
/>,
)
expect(thumb()).toMatchObject({ size: 24, center: 16 })
})

it.each([
['off', false, 16],
['on', true, 36],
])(
'grows the pressed %s thumb to 28 dp around its center',
(_, value, center) => {
const { flush } = renderSettled(
<Switch value={value} onValueChange={() => {}} />,
)
fireEvent(screen.getByRole('switch'), 'pressIn')
flush()
expect(thumb()).toMatchObject({ size: 28, center })
},
)

it('keeps the pressed on thumb inside the outline', () => {
const { flush } = renderSettled(<Switch value onValueChange={() => {}} />)
fireEvent(screen.getByRole('switch'), 'pressIn')
flush()
expect(thumb().end).toBe(52 - BORDER)
})

it('returns to the rest size on release', () => {
const { flush } = renderSettled(
<Switch value={false} onValueChange={() => {}} />,
)
fireEvent(screen.getByRole('switch'), 'pressIn')
flush()
fireEvent(screen.getByRole('switch'), 'pressOut')
flush()
expect(thumb()).toMatchObject({ size: 16, center: 16 })
})
})

describe('overrides', () => {
it('applies containerColor to the track background', () => {
renderWithTheme(<Switch containerColor="#FF0000" />)
Expand Down
16 changes: 9 additions & 7 deletions packages/components/src/__tests__/renderSettled.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import { Portal } from '../portal/Portal'
import { PortalHost } from '../portal/PortalHost'
import { Switch } from '../switch'

// 52 track - 2 * 4 padding - 24 on-thumb.
const THUMB_TRANSLATE_X = 20
// The thumb lays out inside the 2 dp outline and sits by its center: 16 dp
// from the start edge when off (16 dp thumb), 36 dp when on (24 dp thumb).
const THUMB_OFF_X = 16 - 16 / 2 - 2
const THUMB_ON_X = 36 - 24 / 2 - 2

const entrance = (
<Motion.View
Expand Down Expand Up @@ -61,17 +63,17 @@ describe('renderSettled', () => {
describe('progress-driven transitions', () => {
it('is already settled at mount, like renderWithTheme', () => {
renderSettled(<Switch onValueChange={jest.fn()} value />)
expect(thumbTranslateX()).toBe(THUMB_TRANSLATE_X)
expect(thumbTranslateX()).toBe(THUMB_ON_X)
})

it('settles after a prop change, without an explicit flush', () => {
const { rerender } = renderSettled(
<Switch onValueChange={jest.fn()} value={false} />,
)
expect(thumbTranslateX()).toBe(0)
expect(thumbTranslateX()).toBe(THUMB_OFF_X)

rerender(<Switch onValueChange={jest.fn()} value />)
expect(thumbTranslateX()).toBe(THUMB_TRANSLATE_X)
expect(thumbTranslateX()).toBe(THUMB_ON_X)
})

it('settles after an interaction, once flushed', () => {
Expand All @@ -81,7 +83,7 @@ describe('renderSettled', () => {
// more pass on top.
fireEvent.press(screen.getByRole('switch'))
flush()
expect(thumbTranslateX()).toBe(THUMB_TRANSLATE_X)
expect(thumbTranslateX()).toBe(THUMB_ON_X)
})

it('flushes what is mounted, not the element first passed in', () => {
Expand All @@ -93,7 +95,7 @@ describe('renderSettled', () => {
// A flush that re-rendered the original element would revert the switch
// to its off position here.
view.flush()
expect(thumbTranslateX()).toBe(THUMB_TRANSLATE_X)
expect(thumbTranslateX()).toBe(THUMB_ON_X)
})
})
})
139 changes: 49 additions & 90 deletions packages/components/src/switch/Switch.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import { useIconResolver, useTheme } from '@rootnative/core'
import {
resolveTransition,
useAnimation,
useColorTransition,
useInterpolatedStyle,
useMotionValue,
useNamedTransitions,
useShouldReduceMotion,
} from '@rootnative/inertia'
import {
Animated,
interpolate,
useAnimatedStyle,
} from '@rootnative/inertia/reanimated'
import { Animated, useAnimatedStyle } from '@rootnative/inertia/reanimated'
import {
isRTLDirection,
renderIcon,
resolveColorFromStyle,
resolveLogical,
} from '@rootnative/utils'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useCallback, useMemo, useState } from 'react'
import { Platform, View } from 'react-native'
import { AnimatedPressable } from '../internal/AnimatedPressable'
import { composeHandlers } from '../internal/composeHandlers'
Expand All @@ -40,15 +33,16 @@ import {
SWITCH_THUMB_PRESSED_SIZE,
SWITCH_TRACK_BORDER_WIDTH,
SWITCH_TRACK_HEIGHT,
SWITCH_TRACK_PADDING,
SWITCH_TRACK_WIDTH,
createStyles,
getResolvedColors,
} from './styles'
import type { SwitchProps } from './types'

const THUMB_TRANSLATE_X =
SWITCH_TRACK_WIDTH - SWITCH_TRACK_PADDING * 2 - SWITCH_THUMB_ON_SIZE
// MD3 places the thumb by its center, 16 dp from the start edge when off and
// 36 dp when on, so each size (16, 24, pressed 28) keeps the same center.
const THUMB_CENTER_OFF = SWITCH_TRACK_HEIGHT / 2
const THUMB_TRAVEL = SWITCH_TRACK_WIDTH - SWITCH_TRACK_HEIGHT

const ICON_SIZE = 16

Expand All @@ -73,9 +67,6 @@ export function Switch({
const isSelected = isControlled ? Boolean(value) : selfValue
const isPassive = isPassiveControl(isControlled, onValueChange, isDisabled)
const hasUnselectedIcon = Boolean(unselectedIcon)
const offThumbSize = hasUnselectedIcon
? SWITCH_THUMB_ON_SIZE
: SWITCH_THUMB_OFF_SIZE

const theme = useTheme()
const iconResolver = useIconResolver()
Expand All @@ -94,54 +85,48 @@ export function Switch({
)

// Toggle progress — the theme's fast-spatial spring (Expressive bounce,
// 0.6 damping ratio), driving thumb travel and size per Compose's Switch.
// 0.6 damping ratio), driving the thumb travel per Compose's Switch.
const progress = useBooleanProgress(isSelected, 'spring-fast-spatial')

// The thumb rests at the start edge (`marginStart`) and `translateX` is a
// physical offset, so in RTL it has to travel toward negative x or the
// thumb leaves the track on the right.
// The thumb rests at the start edge and `translateX` is a physical offset,
// so in RTL it has to travel toward negative x or the thumb leaves the
// track on the right.
const travelSign = isRTLDirection() ? -1 : 1
const thumbTravel = travelSign * THUMB_TRANSLATE_X

const {
style: haloOpacityStyle,
handlers: layerHandlers,
focusRingStyle: animatedFocusRingStyle,
} = useHaloLayer(isDisabled)

// Thumb press-grow per Expressive Switch: the grow to 28dp is a *snap*
// (Compose uses SnapSpec while pressed) and the release springs back on
// fast-spatial. Direction-dependent, so it can't ride the gesture layer's
// single pressed transition — a dedicated progress with hand-rolled
// handlers instead. Reduced motion already snaps by construction.
const pressed = useMotionValue(0)
const namedTransitions = useNamedTransitions()
const shouldReduceMotion = useShouldReduceMotion()
const [isPressed, setIsPressed] = useState(false)
const pressGrowHandlers = useMemo(
() => ({
onPressIn: () => {
pressed.value = 1
},
onPressOut: () => {
const spring = namedTransitions['spring-fast-spatial']
pressed.value =
shouldReduceMotion || !spring
? 0
: (resolveTransition(spring, 0) as never)
},
onPressIn: () => setIsPressed(true),
onPressOut: () => setIsPressed(false),
}),
[pressed, namedTransitions, shouldReduceMotion],
[],
)
const handlers = useMemo(
() => composePressHandlers(layerHandlers, pressGrowHandlers),
[layerHandlers, pressGrowHandlers],
)

// A press has no matching release once the component disables mid-press —
// pin the grow back to rest so re-enabling doesn't resume mid-grow.
useEffect(() => {
if (isDisabled) pressed.value = 0
}, [isDisabled, pressed])
// drop it so re-enabling doesn't resume at the pressed size.
if (isDisabled && isPressed) setIsPressed(false)

// One size spring toward one target, as in Compose's Switch. A separate
// press spring would add its undershoot to the toggle's and double the
// size dip at the end of a toggle off.
const restThumbSize =
isSelected || hasUnselectedIcon
? SWITCH_THUMB_ON_SIZE
: SWITCH_THUMB_OFF_SIZE
const thumbSize = useAnimation(
isPressed && !isDisabled ? SWITCH_THUMB_PRESSED_SIZE : restThumbSize,
'spring-fast-spatial',
)

const trackColorStyle = useColorTransition(progress, [
offColors.trackColor,
Expand All @@ -158,49 +143,38 @@ export function Switch({
onColors.thumbColor,
])

// Interop escape hatch: the thumb morph reads the toggle spring and the
// press-grow progress together — position, size, and radius in one
// progress-driven worklet.
// Interop escape hatch: the thumb reads the toggle progress and its size
// spring together. It is placed by its center, so a size change grows it
// in both directions. It lays out inside the track border, so the offset
// from the outer start edge loses the border width.
const animatedThumbStyle = useAnimatedStyle(() => {
'worklet'
const baseSize = interpolate(
progress.value,
[0, 1],
[offThumbSize, SWITCH_THUMB_ON_SIZE],
)
const size = interpolate(
pressed.value,
[0, 1],
[baseSize, SWITCH_THUMB_PRESSED_SIZE],
)
const size = thumbSize.value
const center = THUMB_CENTER_OFF + progress.value * THUMB_TRAVEL
return {
width: size,
height: size,
borderRadius: size / 2,
transform: [
{
translateX: interpolate(progress.value, [0, 1], [0, thumbTravel]),
translateX:
travelSign * (center - size / 2 - SWITCH_TRACK_BORDER_WIDTH),
},
],
}
})

// Halo center should track the thumb's center. The static `start` is
// calibrated for the off position; `translateX` adds (a) the toggle
// progress shift and (b) any thumb-grow shift on press (the thumb's start
// edge is fixed, so its center moves toward the end by half the size
// delta). Both follow `thumbTravel`'s sign, so the halo mirrors in RTL too.
// The inset is an inline style, so it goes through `resolveLogical`.
// The halo sits on the thumb's center, so only the toggle progress moves
// it. The inset is an inline style, so it goes through `resolveLogical`.
const haloPositionStyle = useMemo(
() =>
resolveLogical(
'start',
SWITCH_TRACK_PADDING -
SWITCH_TRACK_BORDER_WIDTH +
offThumbSize / 2 -
THUMB_CENTER_OFF -
SWITCH_TRACK_BORDER_WIDTH -
SWITCH_STATE_LAYER_SIZE / 2,
),
[offThumbSize],
[],
)

// The halo color crossfades with the toggle progress (same as the thumb).
Expand All @@ -209,28 +183,13 @@ export function Switch({
onColors.thumbColor,
])

const animatedHaloStyle = useAnimatedStyle(() => {
'worklet'
const baseSize = interpolate(
progress.value,
[0, 1],
[offThumbSize, SWITCH_THUMB_ON_SIZE],
)
const size = interpolate(
pressed.value,
[0, 1],
[baseSize, SWITCH_THUMB_PRESSED_SIZE],
)
return {
transform: [
{
translateX:
progress.value * thumbTravel +
(travelSign * (size - offThumbSize)) / 2,
},
],
}
})
// `extend`, not the default clamp, keeps the halo on the thumb through the
// spring's overshoot.
const animatedHaloStyle = useInterpolatedStyle(
progress,
{ translateX: [0, travelSign * THUMB_TRAVEL] },
{ extrapolate: 'extend' },
)

// The two icons cross-fade on one progress value: the selected icon follows
// it, the unselected icon runs the inverted range.
Expand Down
2 changes: 0 additions & 2 deletions packages/components/src/switch/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { StyleSheet } from 'react-native'

export const SWITCH_TRACK_WIDTH = 52
export const SWITCH_TRACK_HEIGHT = 32
export const SWITCH_TRACK_PADDING = 4
export const SWITCH_TRACK_BORDER_WIDTH = 2
export const SWITCH_THUMB_ON_SIZE = 24
export const SWITCH_THUMB_OFF_SIZE = 16
Expand Down Expand Up @@ -163,7 +162,6 @@ export function createStyles(
top: (SWITCH_TRACK_HEIGHT - SWITCH_STATE_LAYER_SIZE) / 2,
},
thumbBase: {
marginStart: SWITCH_TRACK_PADDING - SWITCH_TRACK_BORDER_WIDTH,
alignItems: 'center' as const,
justifyContent: 'center' as const,
},
Expand Down
Loading