Files
cally/components/pages/grocery/GroceryWrapper.tsx
2024-10-30 23:44:37 +01:00

79 lines
2.2 KiB
TypeScript

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<ScrollView>(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 (
<>
<ScrollView
ref={scrollViewRef}
automaticallyAdjustKeyboardInsets={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
>
<View marginB-60>
<GroceryList onInputFocus={handleInputFocus} />
</View>
</ScrollView>
{!isAddingGrocery && <AddGroceryItem />}
</>
);
};
export default GroceryWrapper;