import { Dimensions, ScrollView, Keyboard, Platform } from "react-native"; import { View } from "react-native-ui-lib"; import React, { useEffect, useRef, useState } from "react"; import AddGroceryItem from "./AddGroceryItem"; import GroceryList from "./GroceryList"; import { useGroceryContext } from "@/contexts/GroceryContext"; const GroceryWrapper = () => { const { isAddingGrocery } = useGroceryContext(); const scrollViewRef = useRef(null); const [keyboardHeight, setKeyboardHeight] = useState(0); useEffect(() => { const keyboardWillShowListener = Keyboard.addListener( Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow', (e) => { setKeyboardHeight(e.endCoordinates.height); } ); const keyboardWillHideListener = Keyboard.addListener( Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide', () => { setKeyboardHeight(0); } ); return () => { keyboardWillShowListener.remove(); keyboardWillHideListener.remove(); }; }, []); useEffect(() => { if (isAddingGrocery && scrollViewRef.current) { scrollViewRef.current.scrollTo({ y: 400, animated: true, }); } }, [isAddingGrocery]); const handleInputFocus = (y: number) => { if (scrollViewRef.current) { // Get the window height const windowHeight = Dimensions.get('window').height; // Calculate the space we want to leave at the top const topSpacing = 20; // Calculate the target scroll position: // y (position of input) - topSpacing (space we want at top) // if keyboard is shown, we need to account for its height const scrollPosition = Math.max(0, y - topSpacing); scrollViewRef.current.scrollTo({ y: scrollPosition, animated: true, }); } }; return ( <> {!isAddingGrocery && } ); }; export default GroceryWrapper;