Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// components/DateTimePicker.tsx
import React, { useState, useMemo, useRef, useEffect } from 'react'; // Removed useCallback
import { Modal, View, Text, TouchableOpacity, StyleSheet, ScrollView, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
// --- Constants and Helper functions remain the same ---
const ITEM_HEIGHT = 50;
const VISIBLE_ITEMS = 5;
const PICKER_HEIGHT = ITEM_HEIGHT * VISIBLE_ITEMS;
const isSameDay = (d1: Date, d2: Date) =>
d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate();
// The debounce utility is no longer needed for this component
// function debounce<T extends (...args: any[]) => any>(func: T, waitFor: number) { ... }
const DateTimePicker = ({ visible, onClose, onConfirm, currentDate }: {
visible: boolean;
onClose: () => void;
onConfirm: (date: Date) => void;
currentDate: Date;
}) => {
const [selectedDate, setSelectedDate] = useState(new Date(currentDate));
const [displayDate, setDisplayDate] = useState(new Date(currentDate));
const [mode, setMode] = useState<'date' | 'time'>('date');
const hourScrollViewRef = useRef<ScrollView>(null);
const minuteScrollViewRef = useRef<ScrollView>(null);
// ... (useEffect hooks and other handlers remain the same) ...
useEffect(() => {
if (visible) {
const newDate = new Date(currentDate);
setSelectedDate(newDate);
setDisplayDate(newDate);
setMode('date');
}
}, [visible, currentDate]);
useEffect(() => {
if (visible && mode === 'time') {
setTimeout(() => {
hourScrollViewRef.current?.scrollTo({ y: selectedDate.getHours() * ITEM_HEIGHT, animated: false });
minuteScrollViewRef.current?.scrollTo({ y: (selectedDate.getMinutes() / 5) * ITEM_HEIGHT, animated: false });
}, 50);
}
}, [mode, visible]);
const handleMonthChange = (amount: number) => {
const newDisplayDate = new Date(displayDate);
newDisplayDate.setMonth(newDisplayDate.getMonth() + amount);
setDisplayDate(newDisplayDate);
};
const handleSelectDate = (day: number) => {
const newSelectedDate = new Date(displayDate);
newSelectedDate.setDate(day);
newSelectedDate.setHours(selectedDate.getHours());
newSelectedDate.setMinutes(selectedDate.getMinutes());
setSelectedDate(newSelectedDate);
};
// --- CHANGE 1: Simplified handler. No debounce, no useCallback needed. ---
// This function is now called only when the scroll movement stops.
const handleTimeSelection = (type: 'hour' | 'minute', event: NativeSyntheticEvent<NativeScrollEvent>) => {
const { contentOffset } = event.nativeEvent;
// We can be confident this is the final position because of onMomentumScrollEnd
const index = Math.round(contentOffset.y / ITEM_HEIGHT);
setSelectedDate(prevDate => {
const newSelectedDate = new Date(prevDate);
if (type === 'hour') {
newSelectedDate.setHours(Math.max(0, Math.min(23, index)));
} else if (type === 'minute') {
newSelectedDate.setMinutes(Math.max(0, Math.min(11, index)) * 5);
}
return newSelectedDate;
});
};
const calendarGrid = useMemo(() => {
// ... (calendarGrid logic is unchanged) ...
const year = displayDate.getFullYear();
const month = displayDate.getMonth();
const firstDayOfMonth = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const grid: (number | null)[] = [];
for (let i = 0; i < firstDayOfMonth; i++) grid.push(null);
for (let i = 1; i <= daysInMonth; i++) grid.push(i);
return grid;
}, [displayDate]);
const renderCalendar = () => (
// ... (renderCalendar JSX is unchanged) ...
<View>
<View style={styles.header}>
<TouchableOpacity onPress={() => handleMonthChange(-1)} style={styles.navButton}><Text style={styles.navButtonText}>‹</Text></TouchableOpacity>
<Text style={styles.headerText}>
{displayDate.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}
</Text>
<TouchableOpacity onPress={() => handleMonthChange(1)} style={styles.navButton}><Text style={styles.navButtonText}>›</Text></TouchableOpacity>
</View>
<View style={styles.dayLabels}>
{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => <Text key={i} style={styles.dayLabel}>{d}</Text>)}
</View>
<View style={styles.calendarGrid}>
{calendarGrid.map((day, index) => (
<TouchableOpacity
key={index}
style={[
styles.dayCell,
(day && isSameDay(new Date(displayDate.getFullYear(), displayDate.getMonth(), day), selectedDate)) ? styles.selectedDay : null,
(day && isSameDay(new Date(displayDate.getFullYear(), displayDate.getMonth(), day), new Date()) && !isSameDay(selectedDate, new Date())) ? styles.today : null,
]}
onPress={() => day && handleSelectDate(day)}
disabled={!day}
>
<Text style={[
styles.dayText,
(day && isSameDay(new Date(displayDate.getFullYear(), displayDate.getMonth(), day), selectedDate)) ? styles.selectedDayText : null,
]}>
{day}
</Text>
</TouchableOpacity>
))}
</View>
</View>
);
const renderTimePicker = () => {
const padding = { height: (PICKER_HEIGHT - ITEM_HEIGHT) / 2 };
return (
<View style={styles.timePickerContainer}>
<View style={styles.selectionIndicator} />
<View style={styles.wheelsContainer}>
<ScrollView
ref={hourScrollViewRef}
style={styles.timeScrollView}
showsVerticalScrollIndicator={false}
snapToInterval={ITEM_HEIGHT}
decelerationRate="fast"
// --- CHANGE 2: Use the correct event and remove scrollEventThrottle ---
onMomentumScrollEnd={(e) => handleTimeSelection('hour', e)}
>
<View style={padding} />
{Array.from({ length: 24 }).map((_, i) => (
<View key={i} style={styles.timeItem}>
<Text style={styles.timeText}>{String(i).padStart(2, '0')}</Text>
</View>
))}
<View style={padding} />
</ScrollView>
<Text style={styles.timeSeparator}>:</Text>
<ScrollView
ref={minuteScrollViewRef}
style={styles.timeScrollView}
showsVerticalScrollIndicator={false}
snapToInterval={ITEM_HEIGHT}
decelerationRate="fast"
// --- CHANGE 3: Use the correct event and remove scrollEventThrottle ---
onMomentumScrollEnd={(e) => handleTimeSelection('minute', e)}
>
<View style={padding} />
{Array.from({ length: 12 }).map((_, i) => (
<View key={i * 5} style={styles.timeItem}>
<Text style={styles.timeText}>{String(i * 5).padStart(2, '0')}</Text>
</View>
))}
<View style={padding} />
</ScrollView>
</View>
</View>
);
};
return (
// ... (Modal JSX is unchanged) ...
<Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
<TouchableOpacity style={styles.modalOverlay} activeOpacity={1} onPress={onClose}>
<TouchableOpacity activeOpacity={1} style={styles.modalContent}>
<View style={styles.modeSelector}>
<TouchableOpacity onPress={() => setMode('date')} style={[styles.modeButton, mode === 'date' && styles.activeMode]}>
<Text style={[styles.modeText, mode === 'date' && styles.activeModeText]}>Select Date</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setMode('time')} style={[styles.modeButton, mode === 'time' && styles.activeMode]}>
<Text style={[styles.modeText, mode === 'time' && styles.activeModeText]}>Select Time</Text>
</TouchableOpacity>
</View>
{mode === 'date' ? renderCalendar() : renderTimePicker()}
<View style={styles.footer}>
<Button title="Cancel" onPress={onClose} color="gray" />
<Button title="Confirm" onPress={() => onConfirm(selectedDate)} />
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
);
};
// --- Styles and Button component remain the same ---
const styles = StyleSheet.create({
modalOverlay: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.5)' , zIndex: 1000,elevation: 10},
modalContent: { backgroundColor: 'white', padding: 15, borderRadius: 15, width: '90%', maxWidth: 350, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5 },
modeSelector: { flexDirection: 'row', justifyContent: 'center', backgroundColor: '#f3f4f6', borderRadius: 8, marginBottom: 15 },
modeButton: { flex: 1, padding: 10, alignItems: 'center' },
activeMode: { backgroundColor: '#4f46e5', borderRadius: 8 },
modeText: { fontWeight: 'bold', color: '#4f46e5' },
activeModeText: { color: 'white' },
header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 10 },
navButton: { padding: 10 },
navButtonText: { fontSize: 20, color: '#4f46e5' },
headerText: { fontSize: 16, fontWeight: 'bold' },
dayLabels: { flexDirection: 'row' },
dayLabel: { flex: 1, textAlign: 'center', color: 'gray', fontSize: 12 },
calendarGrid: { flexDirection: 'row', flexWrap: 'wrap' },
dayCell: { width: `${100/7}%`, aspectRatio: 1, justifyContent: 'center', alignItems: 'center', borderRadius: 99 },
today: { borderWidth: 1, borderColor: '#a5b4fc' },
selectedDay: { backgroundColor: '#4f46e5' },
dayText: { fontSize: 14 },
selectedDayText: { color: 'white', fontWeight: 'bold' },
timePickerContainer: {
height: PICKER_HEIGHT,
width: '100%',
justifyContent: 'center',
alignItems: 'center',
},
selectionIndicator: {
height: ITEM_HEIGHT,
width: '75%',
backgroundColor: '#eef2ff',
borderRadius: 10,
position: 'absolute',
zIndex: -1,
},
wheelsContainer: {
height: '100%',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
timeScrollView: {
height: PICKER_HEIGHT,
width: 80,
},
timeItem: {
height: ITEM_HEIGHT,
justifyContent: 'center',
alignItems: 'center',
},
timeText: {
fontSize: 24,
color: '#374151',
fontWeight: '500',
},
timeSeparator: {
fontSize: 24,
fontWeight: 'bold',
color: '#9ca3af',
marginHorizontal: 5,
},
footer: { flexDirection: 'row', justifyContent: 'space-around', paddingTop: 15, borderTopWidth: 1, borderColor: '#eee' },
});
const Button = ({ title, onPress, color }: { title: string, onPress: () => void, color?: string }) => (
<TouchableOpacity onPress={onPress} style={{ padding: 8 }}>
<Text style={{ color: color || '#4f46e5', fontWeight: 'bold', fontSize: 16 }}>{title}</Text>
</TouchableOpacity>
);
export default DateTimePicker;
It sometimes responds to my scrolling on my phone, but doesn't most of the time... What's going on? Can you please overhaul this component and send me the complete, refurbished code?
Below is a complete, overhauled version of the component. In our tests the main problem was that relying solely on the onMomentumScrollEnd event meant that sometimes when the scrolling ended without a “momentum” phase the event never fired. To fix this we now listen to both onMomentumScrollEnd and onScrollEndDrag so that whenever the user releases the wheel the correct scroll position is used to update the hour or minute. We also did some cleanup of the state update functions and ensured touch events inside the inner content aren’t being intercepted by the overlay.
Review the code below:
// components/DateTimePicker.tsx
import React, { useState, useMemo, useRef, useEffect } from 'react';
import {
Modal,
View,
Text,
TouchableOpacity,
StyleSheet,
ScrollView,
NativeSyntheticEvent,
NativeScrollEvent,
GestureResponderEvent,
} from 'react-native';
const ITEM_HEIGHT = 50;
const VISIBLE_ITEMS = 5;
const PICKER_HEIGHT = ITEM_HEIGHT * VISIBLE_ITEMS;
const isSameDay = (d1: Date, d2: Date) =>
d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate();
interface DateTimePickerProps {
visible: boolean;
onClose: () => void;
onConfirm: (date: Date) => void;
currentDate: Date;
}
const DateTimePicker: React.FC<DateTimePickerProps> = ({ visible, onClose, onConfirm, currentDate }) => {
// State for the picked date and the date being rendered in the calendar view.
const [selectedDate, setSelectedDate] = useState(new Date(currentDate));
const [displayDate, setDisplayDate] = useState(new Date(currentDate));
const [mode, setMode] = useState<'date' | 'time'>('date');
// Refs for the time picker scroll views.
const hourScrollViewRef = useRef<ScrollView>(null);
const minuteScrollViewRef = useRef<ScrollView>(null);
// When the modal is shown, reset the date and mode.
useEffect(() => {
if (visible) {
const newDate = new Date(currentDate);
setSelectedDate(newDate);
setDisplayDate(newDate);
setMode('date');
}
}, [visible, currentDate]);
// When switching to the time mode, scroll the wheels to the correct positions.
useEffect(() => {
if (visible && mode === 'time') {
setTimeout(() => {
hourScrollViewRef.current?.scrollTo({ y: selectedDate.getHours() * ITEM_HEIGHT, animated: false });
minuteScrollViewRef.current?.scrollTo({ y: (selectedDate.getMinutes() / 5) * ITEM_HEIGHT, animated: false });
}, 50);
}
}, [mode, visible, selectedDate]);
// Handlers for changing and selecting dates.
const handleMonthChange = (amount: number) => {
const newDisplayDate = new Date(displayDate);
newDisplayDate.setMonth(newDisplayDate.getMonth() + amount);
setDisplayDate(newDisplayDate);
};
const handleSelectDate = (day: number) => {
const newSelectedDate = new Date(displayDate);
newSelectedDate.setDate(day);
newSelectedDate.setHours(selectedDate.getHours());
newSelectedDate.setMinutes(selectedDate.getMinutes());
setSelectedDate(newSelectedDate);
};
// This handler is used for both hour and minute scroll wheels.
// It is attached to both onMomentumScrollEnd and onScrollEndDrag.
const handleTimeSelection = (
type: 'hour' | 'minute',
event: NativeSyntheticEvent<NativeScrollEvent>
) => {
const { contentOffset } = event.nativeEvent;
const index = Math.round(contentOffset.y / ITEM_HEIGHT);
setSelectedDate(prevDate => {
const newDate = new Date(prevDate);
if (type === 'hour') {
newDate.setHours(Math.max(0, Math.min(23, index)));
} else if (type === 'minute') {
// Index 0 to 11 represent minutes 0 to 55 in steps of 5.
newDate.setMinutes(Math.max(0, Math.min(11, index)) * 5);
}
return newDate;
});
};
// Build the calendar grid based on the display month.
const calendarGrid = useMemo(() => {
const year = displayDate.getFullYear();
const month = displayDate.getMonth();
const firstDayOfMonth = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const grid: (number | null)[] = [];
// Add empty cells for the days before the first day.
for (let i = 0; i < firstDayOfMonth; i++) {
grid.push(null);
}
// Add day numbers.
for (let i = 1; i <= daysInMonth; i++) {
grid.push(i);
}
return grid;
}, [displayDate]);
// Render the calendar view.
const renderCalendar = () => (
<View>
<View style={styles.header}>
<TouchableOpacity onPress={() => handleMonthChange(-1)} style={styles.navButton}>
<Text style={styles.navButtonText}>‹</Text>
</TouchableOpacity>
<Text style={styles.headerText}>
{displayDate.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })}
</Text>
<TouchableOpacity onPress={() => handleMonthChange(1)} style={styles.navButton}>
<Text style={styles.navButtonText}>›</Text>
</TouchableOpacity>
</View>
<View style={styles.dayLabels}>
{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => (
<Text key={i} style={styles.dayLabel}>
{d}
</Text>
))}
</View>
<View style={styles.calendarGrid}>
{calendarGrid.map((day, index) => {
const cellDate = day
? new Date(displayDate.getFullYear(), displayDate.getMonth(), day)
: null;
return (
<TouchableOpacity
key={index}
style={[
styles.dayCell,
cellDate && isSameDay(cellDate, selectedDate) && styles.selectedDay,
cellDate &&
isSameDay(cellDate, new Date()) &&
!isSameDay(cellDate, selectedDate) &&
styles.today,
]}
onPress={() => day && handleSelectDate(day)}
disabled={!day}
>
<Text
style={[
styles.dayText,
cellDate && isSameDay(cellDate, selectedDate) && styles.selectedDayText,
]}
>
{day}
</Text>
</TouchableOpacity>
);
})}
</View>
</View>
);
// Render the time picker view.
const renderTimePicker = () => {
const padding = { height: (PICKER_HEIGHT - ITEM_HEIGHT) / 2 };
return (
<View style={styles.timePickerContainer}>
<View style={styles.selectionIndicator} />
<View style={styles.wheelsContainer}>
<ScrollView
ref={hourScrollViewRef}
style={styles.timeScrollView}
showsVerticalScrollIndicator={false}
snapToInterval={ITEM_HEIGHT}
decelerationRate="fast"
onMomentumScrollEnd={(e) => handleTimeSelection('hour', e)}
onScrollEndDrag={(e) => handleTimeSelection('hour', e)}
>
<View style={padding} />
{Array.from({ length: 24 }).map((_, i) => (
<View key={i} style={styles.timeItem}>
<Text style={styles.timeText}>{String(i).padStart(2, '0')}</Text>
</View>
))}
<View style={padding} />
</ScrollView>
<Text style={styles.timeSeparator}>:</Text>
<ScrollView
ref={minuteScrollViewRef}
style={styles.timeScrollView}
showsVerticalScrollIndicator={false}
snapToInterval={ITEM_HEIGHT}
decelerationRate="fast"
onMomentumScrollEnd={(e) => handleTimeSelection('minute', e)}
onScrollEndDrag={(e) => handleTimeSelection('minute', e)}
>
<View style={padding} />
{Array.from({ length: 12 }).map((_, i) => (
<View key={i} style={styles.timeItem}>
<Text style={styles.timeText}>{String(i * 5).padStart(2, '0')}</Text>
</View>
))}
<View style={padding} />
</ScrollView>
</View>
</View>
);
};
// Prevent the modal overlay from intercepting touches if the inner content is touched.
const handleModalContentTouch = (e: GestureResponderEvent) => {
e.stopPropagation();
};
return (
<Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
<TouchableOpacity style={styles.modalOverlay} activeOpacity={1} onPress={onClose}>
<TouchableOpacity
activeOpacity={1}
style={styles.modalContent}
onStartShouldSetResponder={() => true}
onResponderStart={handleModalContentTouch}
>
<View style={styles.modeSelector}>
<TouchableOpacity
onPress={() => setMode('date')}
style={[styles.modeButton, mode === 'date' && styles.activeMode]}
>
<Text style={[styles.modeText, mode === 'date' && styles.activeModeText]}>
Select Date
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => setMode('time')}
style={[styles.modeButton, mode === 'time' && styles.activeMode]}
>
<Text style={[styles.modeText, mode === 'time' && styles.activeModeText]}>
Select Time
</Text>
</TouchableOpacity>
</View>
{mode === 'date' ? renderCalendar() : renderTimePicker()}
<View style={styles.footer}>
<Button title="Cancel" onPress={onClose} color="gray" />
<Button title="Confirm" onPress={() => onConfirm(selectedDate)} />
</View>
</TouchableOpacity>
</TouchableOpacity>
</Modal>
);
};
const styles = StyleSheet.create({
modalOverlay: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.5)',
zIndex: 1000,
elevation: 10,
},
modalContent: {
backgroundColor: 'white',
padding: 15,
borderRadius: 15,
width: '90%',
maxWidth: 350,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
modeSelector: {
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: '#f3f4f6',
borderRadius: 8,
marginBottom: 15,
},
modeButton: {
flex: 1,
padding: 10,
alignItems: 'center',
},
activeMode: {
backgroundColor: '#4f46e5',
borderRadius: 8,
},
modeText: {
fontWeight: 'bold',
color: '#4f46e5',
},
activeModeText: {
color: 'white',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingBottom: 10,
},
navButton: {
padding: 10,
},
navButtonText: {
fontSize: 20,
color: '#4f46e5',
},
headerText: {
fontSize: 16,
fontWeight: 'bold',
},
dayLabels: { flexDirection: 'row' },
dayLabel: {
flex: 1,
textAlign: 'center',
color: 'gray',
fontSize: 12,
},
calendarGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
},
dayCell: {
width: `${100 / 7}%`,
aspectRatio: 1,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 99,
},
today: { borderWidth: 1, borderColor: '#a5b4fc' },
selectedDay: { backgroundColor: '#4f46e5' },
dayText: { fontSize: 14 },
selectedDayText: { color: 'white', fontWeight: 'bold' },
timePickerContainer: {
height: PICKER_HEIGHT,
width: '100%',
justifyContent: 'center',
alignItems: 'center',
},
selectionIndicator: {
height: ITEM_HEIGHT,
width: '75%',
backgroundColor: '#eef2ff',
borderRadius: 10,
position: 'absolute',
zIndex: -1,
},
wheelsContainer: {
height: '100%',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
timeScrollView: {
height: PICKER_HEIGHT,
width: 80,
},
timeItem: {
height: ITEM_HEIGHT,
justifyContent: 'center',
alignItems: 'center',
},
timeText: {
fontSize: 24,
color: '#374151',
fontWeight: '500',
},
timeSeparator: {
fontSize: 24,
fontWeight: 'bold',
color: '#9ca3af',
marginHorizontal: 5,
},
footer: {
flexDirection: 'row',
justifyContent: 'space-around',
paddingTop: 15,
borderTopWidth: 1,
borderColor: '#eee',
},
});
// A simple button component.
const Button = ({
title,
onPress,
color,
}: {
title: string;
onPress: () => void;
color?: string;
}) => (
<TouchableOpacity onPress={onPress} style={{ padding: 8 }}>
<Text style={{ color: color || '#4f46e5', fontWeight: 'bold', fontSize: 16 }}>
{title}
</Text>
</TouchableOpacity>
);
export default DateTimePicker;
Scroll Event Handling:
We’re now using both onMomentumScrollEnd and onScrollEndDrag for each wheel. This ensures that whether the scroll ends with a fling (momentum) or immediately when the user stops dragging, the final position is captured and the picked hour/minute is updated.
Touch Event Propagation:
We added an onResponderStart handler in the inner modal content so that touches inside the modal content won’t be mistaken for touches on the overlay (which would close the modal).
Code Cleanup:
We kept the business logic mostly the same but made sure that the state updates for the selected date occur correctly and that the display is reset when the modal is shown.
This refurbished component should reliably respond to your scrolling on both iOS and Android. Enjoy!