Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slider range #35

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
19 changes: 17 additions & 2 deletions App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable prettier/prettier */
import { CircleUser, CreditCard, Settings } from 'lucide-react-native';
import { useState } from 'react';
import React, { useState } from 'react';
import { Alert, ScrollView, Text, TouchableOpacity, View } from 'react-native';

import { Avatar, AvatarFallback, AvatarImage } from './components/Avatar';
Expand Down Expand Up @@ -32,6 +32,7 @@ import {
RadioGroupLabel,
} from './components/RadioGroup';
import { Skeleton } from './components/Skeleton';
import { Slider } from './components/Slider';
import { Switch } from './components/Switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './components/Tabs';
import { ToastProvider, ToastVariant, useToast } from './components/Toast';
Expand All @@ -41,6 +42,8 @@ export default function App() {
const [inputText, onChangeText] = useState('');
const [isEnabled, setIsEnabled] = useState(false);

const [sliderValue, setSliderValeu] = useState<number>(50);

return (
<ToastProvider position="top">
<ScrollView className="bg-background flex-1 py-16 px-10">
Expand Down Expand Up @@ -255,12 +258,24 @@ export default function App() {
<ExampleToast />
</View>
</View>
<View className="gap-2 mb-32">
<View className="gap-2 ">
<Text className="font-semibold text-xl text-primary">Progress</Text>
<View>
<Progress value={50} className="mb-2" />
</View>
</View>
<View className="gap-2 mb-32">
<Text className="font-semibold text-xl text-primary">Slider</Text>
<View>
<Slider
minimumValue={0}
maximumValue={100}
value={sliderValue}
onValueChange={v => setSliderValeu(v)}
// thumbVisible={false}
/>
</View>
</View>
</View>
</ScrollView>
</ToastProvider>
Expand Down
139 changes: 139 additions & 0 deletions components/Slider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import debounce from 'lodash.debounce';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Text, View } from 'react-native';
import {
Gesture,
GestureDetector,
GestureHandlerRootView,
} from 'react-native-gesture-handler';
import Animated, {
useAnimatedStyle,
useSharedValue,
} from 'react-native-reanimated';

import { cn } from '../lib/utils';

interface SliderProps {
minimumValue: number;
maximumValue: number;
value: number;
onValueChange?: (value: number) => void;
thumbVisible?: boolean;
}

const clamp = (value: number, min: number, max: number) =>
Math.max(min, Math.min(value, max));

function Slider({
value,
onValueChange,
minimumValue = 0,
maximumValue = 100,
thumbVisible = true,
}: SliderProps) {
const [sliderWidth, setSliderWidth] = useState(0);

const calcPosition = useCallback(
(v: number) =>
(sliderWidth * (v - minimumValue)) / (maximumValue - minimumValue),
[sliderWidth, minimumValue, maximumValue]
);

const translationX = useSharedValue(calcPosition(value));
const prevTranslationX = useSharedValue(0);
const isDragging = useSharedValue(false);

const debounceOnValueChange = useCallback(
debounce((value: number) => {
if (onValueChange) onValueChange(value);
}, 100),
[onValueChange]
);

useEffect(() => {
translationX.value = calcPosition(value);
return () => debounceOnValueChange.cancel();
}, [value, calcPosition, debounceOnValueChange]);

const panGesture = useMemo(
() =>
Gesture.Pan()
.minDistance(0)
.onStart(() => {
prevTranslationX.value = calcPosition(value);
isDragging.value = true;
})
.onUpdate(async event => {
const positionValue = prevTranslationX.value + event.translationX;
const clampedPosition = clamp(positionValue, 0, sliderWidth);
translationX.value = clampedPosition;
})
.onEnd(async () => {
isDragging.value = false;
const calcReturn =
((maximumValue - minimumValue) * translationX.value) / sliderWidth;
if (onValueChange) await debounceOnValueChange(calcReturn);
})
.runOnJS(true),
[calcPosition, sliderWidth, value, debounceOnValueChange]
);

const animatedStyles = useAnimatedStyle(
() => ({
transform: [{ translateX: translationX.value }],
}),
[translationX]
);
const sizeAnimatedStyles = useAnimatedStyle(
() => ({
width: translationX.value,
}),
[translationX]
);

return (
<>
<GestureHandlerRootView
style={{
height: 20,
paddingVertical: 18,
justifyContent: 'center',
}}
>
<View
onLayout={e => setSliderWidth(e.nativeEvent.layout.width)}
className={cn(
'mx-3 h-2 rounded-xl w-auto bg-foreground/20 justify-center'
)}
>
<Animated.View
style={sizeAnimatedStyles}
className={cn(
'h-2 rounded-l-xl bg-foreground absolute',
value === maximumValue ? 'rounded-r-xl' : null
)}
/>
<GestureDetector gesture={panGesture}>
<Animated.View
style={[animatedStyles]}
className={cn(
'h-6 w-6 -mx-3 rounded-full bg-background border border-foreground',
thumbVisible ? '' : ' bg-transparent border-transparent'
)}
/>
</GestureDetector>
</View>
</GestureHandlerRootView>
{/* Debugging info - remove or hide in production */}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the commented parts

{/* <View style={{ marginVertical: 40, backgroundColor: 'red' }}>
<Text>sliderWidth:{sliderWidth.toFixed(2)}</Text>
<Text>value:{value.toFixed(2)}</Text>
<Text>max:{maximumValue}</Text>
<Text>translationX.value:{translationX.value.toFixed(2)}</Text>
<Text>prevTranslationX.value:{prevTranslationX.value.toFixed(2)}</Text>
</View> */}
</>
);
}

export { Slider };
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"nativewind": "^4.0.1",
"react": "18.2.0",
"react-native": "0.73.6",
"react-native-gesture-handler": "~2.16.1",
"react-native-reanimated": "~3.6.2",
"react-native-svg": "^14.1.0",
"react-native-vector-icons": "^10.0.3",
Expand All @@ -30,7 +31,9 @@
},
"devDependencies": {
"@babel/core": "^7.23.9",
"@types/lodash.debounce": "^4.0.9",
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@types/lodash.debounce": "^4.0.9",
"@types/react": "~18.2.55",
"@types/react-native-vector-icons": "^6.4.18",
"eslint": "^8.56.0",
Expand Down