Major refactoring: navigation does not break anymore. the user can now navigate between the tabs without loosing context

This commit is contained in:
Jakob Stornig 2024-01-20 11:54:25 +01:00
parent 457b098883
commit 1beee68bff
23 changed files with 137 additions and 80 deletions

View file

@ -6,9 +6,12 @@ import { ExpenseItem, LoadingSymbol, TextInputBar } from "../../../components";
import useFetch from "../../../hooks/useFetch";
import { useTheme } from "../../contexts/ThemeContext";
import { SafeAreaView } from "react-native-safe-area-context";
import { useNavigation } from "expo-router/src/useNavigation";
import { useEffect } from "react";
export default function Page() {
const router = useRouter();
const navigation = useNavigation();
const {colors} = useTheme();
const {category_guid} = useLocalSearchParams();
@ -17,13 +20,21 @@ export default function Page() {
const {data, isLoading, reFetch} = useFetch({sql: "SELECT e.guid AS expense_guid, e.name AS expense_name, c.name AS category_name, e.datetime AS expense_datetime, e.amount AS expense_amount, c.color AS category_color FROM expense e JOIN category c ON e.category_guid = c.guid WHERE c.guid = ? ORDER BY expense_datetime desc;", args: [category_guid]});
const handleEditCategory = () => {
router.push({pathname: "/budget/editCategory", params: {category_guid: category_guid, category_color: category_color, category_amount: category_amount, category_name: category_name, category_type: category_type}});
router.push({pathname: "/editCategory", params: {category_guid: category_guid, category_color: category_color, category_amount: category_amount, category_name: category_name, category_type: category_type}});
}
const handleBackButton = () => {
router.back();
}
useEffect(() => {
console.log("useEffect called")
const unsubscribe = navigation.addListener("focus", () => {
reFetch();
})
return unsubscribe;
}, [navigation])
return (
<SafeAreaView style={[styles.safeAreaView, {backgroundColor: colors.containerColor}]}>
<TouchableOpacity style={styles.backContainer} onPress={handleBackButton}>
@ -40,7 +51,7 @@ export default function Page() {
<TextInputBar style={styles.searchBar} placeholder="Search..."/>
{isLoading ? (<LoadingSymbol/>) : (
<FlatList
<FlatList style={{marginHorizontal: 10}}
data={data}
renderItem = {({item}) => <ExpenseItem
color={item.category_color}
@ -48,9 +59,9 @@ export default function Page() {
title={item.expense_name}
date={item.expense_datetime}
value={item.expense_amount}
onPress={()=>router.push(`/home/expense/${item.guid}`)}
onPress={()=>router.push(`/expense/${item.expense_guid}`)}
/>}
keyExtractor={item => item.guid}
keyExtractor={item => item.expense_guid}
ItemSeparatorComponent={() => {
return (<View style={styles.itemSeperator}/>);
}}

View file

@ -1,5 +1,5 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { router } from 'expo-router';
import { router, useNavigation } from 'expo-router';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
@ -11,7 +11,7 @@ import { useTheme } from '../../contexts/ThemeContext';
export default function Page() {
const {colors} = useTheme()
const containerColor = colors.containerColor;
const navigation = useNavigation();
const [selectedPage, setSelectedPage] = useState("noPageLoaded");
useEffect(() => {
@ -27,9 +27,10 @@ export default function Page() {
const {data, isLoading, reFetch} = useFetch({sql: "SELECT c.guid AS category_guid, c.name AS category_name, c.color AS category_color, c.type AS category_type, SUM(e.amount) as total_expenses, c.allocated_amount as allocated_amount FROM category c LEFT JOIN expense e ON e.category_guid = c.guid WHERE c.type = ? GROUP BY c.guid", args: selectedPage === "expenses" ? ["expense"] : selectedPage === "savings" ? ["saving"] : []});
useEffect(() => {
reFetch();
reFetch()
}, [selectedPage]);
const handlePageSelection = (page: string) => {
if(page !== selectedPage) {
setSelectedPage(page);
@ -38,15 +39,16 @@ export default function Page() {
};
const handleCategoryPress = (item: {[column: string]: any;}) => {
router.push({pathname: "/(tabs)/budget/category", params: {category_guid: item.category_guid, category_name: item.category_name}})
router.push({pathname: "/category", params: {category_guid: item.category_guid, category_name: item.category_name}})
}
return (
<SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: containerColor}]}>
<View style={{flex: 1, marginHorizontal: 10}}>
<BudgetHeader selectedPage={selectedPage} handlePageSelection={handlePageSelection}/>
<Plus onPress={() => {
router.push({pathname: '/(tabs)/budget/addCategory'});
router.push({pathname: '/addCategory'});
}}/>
{isLoading ? (<LoadingSymbol/>) : (
@ -67,6 +69,7 @@ export default function Page() {
}}
/>
)}
</View>
</SafeAreaView>
);
}

View file

@ -24,9 +24,6 @@ export default function _Layout() {
title: "test",
headerShown: false,
}}/>
<Stack.Screen name="expense" options={{
headerShown: false,
}}/>
<Stack.Screen name="userSettings" options={{
animation: "slide_from_left",
title: "User Settings",

View file

@ -1,4 +1,4 @@
import React, { useMemo, useRef, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { NativeScrollEvent, NativeSyntheticEvent, StyleSheet, View } from 'react-native';
import { Calendar } from 'react-native-calendars';
import { FlatList, RefreshControl } from 'react-native-gesture-handler';
@ -10,6 +10,7 @@ import { useRouter } from "expo-router";
import { addExpense } from "../../../services/database";
import { SimpleDate } from '../../../util/SimpleDate';
import { useTheme } from '../../contexts/ThemeContext';
import { useNavigation } from 'expo-router';
interface MarkingProps {
@ -36,8 +37,7 @@ const constructMarkedDates = (data : {[column: string]: any}) => {
export default function Page() {
const { colors, theme } = useTheme()
const navigation = useNavigation();
const router = useRouter();
const [plusShow, setPlusShow] = useState(true);
const prevOffset = useRef(0);
@ -62,17 +62,24 @@ export default function Page() {
}
const {data, isLoading, reFetch} = useFetch({sql: "SELECT e.guid AS expense_guid, c.guid AS category_guid, e.name AS expense_name, c.name AS category_name, e.datetime AS expense_datetime, e.amount AS expense_amount, c.color AS category_color, c.type AS category_type FROM expense e JOIN category c ON e.category_guid = c.guid ORDER BY expense_datetime desc;", args: []});
const expenseDates = useMemo(()=>
constructMarkedDates(data)
, [data])
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
console.log("focus event triggered")
reFetch();
});
return unsubscribe;
}, [navigation]);
return (
<SafeAreaView edges={["left", "right", "top"]} style={[styles.safeAreaViewStyle, {backgroundColor: colors.containerColor}]}>
{plusShow && <Plus onPress={()=>{
router.push("/(tabs)/home/expense/new");
router.push("/expense/new");
// executeQuery({sql: "SELECT guid FROM category", args: []}).then((result) => {
// if("rows" in result[0]) {
@ -89,7 +96,7 @@ export default function Page() {
data={data}
ListHeaderComponent={
<>
<Welcome name="My Dude" image={profile} onPress={() => {router.push("/home/userSettings")}}/>
<Welcome name="My Dude" image={profile} onPress={() => {router.push("/userSettings")}}/>
<Calendar key={theme} maxDate={SimpleDate.now().format("YYYY-MM-DD")} style={{borderRadius: 20, padding:10}} theme={{
dayTextColor: colors.primaryText,
textDisabledColor: colors.secondaryText,
@ -107,8 +114,17 @@ export default function Page() {
<TextInputBar placeholder='Type to Search...' style={{marginBottom: 20}}></TextInputBar>
</>
}
renderItem = {({item}) => <ExpenseItem category={item.category_name} color={item.category_color} date={item.expense_datetime} title={item.expense_name} value={item.expense_amount} guid={item.expense_guid} onPress={(guid) => {router.push(`/(tabs)/home/expense/${guid}`)}}/>}
keyExtractor={item => item.expense_guid}
renderItem = {({item}) =>
<ExpenseItem
category={item.category_name}
color={item.category_color}
date={item.expense_datetime}
title={item.expense_name}
value={item.expense_amount}
guid={item.expense_guid}
onPress={(guid) => {router.push(`/expense/${guid}`)}}
/>}
keyExtractor={item => item.expense_guid }
ItemSeparatorComponent={() => {
return (<View style={styles.itemSeperatorStyle}/>);
}}

View file

@ -35,30 +35,25 @@ export default function Layout() {
return (
<Tabs sceneContainerStyle={styles.sceneContainer} screenOptions={screenOptions}>
<Tabs.Screen name="budget" options={
<Tabs.Screen name="(budget)" options={
{
tabBarLabel: "Budget",
tabBarIcon: ({size, color}) => (
<FontAwesome name="money" size={size} color={color}/>),
unmountOnBlur: true,
href: "(tabs)/budget"
}
}/>
<Tabs.Screen name="home" options={
<Tabs.Screen name="(home)" options={
{
tabBarLabel: "Home",
tabBarIcon: ({size, color}) => (
<FontAwesome name="home" size={size} color={color}/>),
unmountOnBlur: true,
href: "(tabs)/home/"
}
}/>
<Tabs.Screen name="stats/index" options={
<Tabs.Screen name="(stats)/index" options={
{
tabBarLabel: "Stats",
tabBarIcon: ({size, color}) => (
<FontAwesome name="bar-chart" size={size} color={color}/>),
unmountOnBlur: true,
}
}/>
</Tabs>

View file

@ -1,140 +0,0 @@
import { View, Text, Alert, StyleSheet } from 'react-native'
import React, { useEffect, useState } from 'react'
import { router, useLocalSearchParams, useRouter } from 'expo-router'
import useFetch from '../../../../hooks/useFetch';
import { Category, Expense } from '../../../../types/dbItems';
import { CategorySelectorModal, AutoDecimalInput, CategorySelector, TextInputBar, DateSelectorButton, RoundedButton } from '../../../../components';
import colors from '../../../../constants/colors';
import { addExpense, deleteExpense, executeQuery, updateExpense } from '../../../../services/database';
import { SimpleDate } from '../../../../util/SimpleDate';
import DateTimePicker from '@react-native-community/datetimepicker';
import { SIZES } from '../../../../constants/theme';
import { useTheme } from '../../../contexts/ThemeContext';
export default function Page() {
const router = useRouter();
const {colors} = useTheme();
const {expense} = useLocalSearchParams();
const {data, isEmptyResult} = useFetch({sql: "SELECT e.guid as e_guid, e.name as e_name, e.datetime as e_datetime, e.amount as e_amount, c.guid as c_guid, c.name as c_name, c.color as c_color FROM expense e INNER JOIN category c on e.category_guid = c.guid WHERE e.guid = ?", args: [expense]});
const [selectedExpense, setSelectedExpense] = useState<Expense|undefined>();
const [selectedCategory, setSelectedCategory] = useState<Category|undefined>();
const [formatedValue, setFormatedValue] = useState<string>("");
const [initialValue, setInitialValue] = useState<number>();
const [selectorModalVisible, setSelecorModalVisible] = useState<boolean>(false);
const [expenseName, setExpenseName] = useState<string>("");
const [datePickerShown, setDatePickerShown] = useState<boolean>(false);
const [selectedDate, setSelectedDate] = useState<Date>(new Date());
console.log(router.canGoBack())
useEffect(()=>{
const entry = data[0];
console.log(entry)
if(entry){
console.log(entry)
const extractedExpense: Expense = {name: entry["e_name"], amount: entry["e_amount"], dateTime: entry["e_datetime"], guid: entry["e_guid"]}
const extractedCategory: Category = {name: entry["c_name"], color: entry["c_color"], guid: entry["c_guid"]}
console.log(extractedCategory.color)
setSelectedExpense(extractedExpense);
setSelectedCategory(extractedCategory);
setInitialValue(extractedExpense.amount)
setExpenseName(extractedExpense.name ?? "")
setSelectedDate(extractedExpense.dateTime? new Date(extractedExpense.dateTime) : new Date());
}
}, [data])
const handleValueChange = (formatedValue: string) => {
setFormatedValue(formatedValue);
}
const handleCategorySelect = (category : Category) => {
setSelecorModalVisible(false);
setSelectedCategory(category);
}
const validateInput = ():boolean => {
if(formatedValue == "" || expenseName == "" || selectedCategory === undefined || selectedDate === null){
return false;
}
return true;
}
const submit = () => {
console.log(selectedExpense?.guid)
const insert = async () => {
await updateExpense(selectedExpense!.guid!, expenseName, selectedCategory!.guid!, new SimpleDate(selectedDate).format("YYYY-MM-DD"), Number(formatedValue))
}
if(validateInput()){
insert();
router.back();
}else {
Alert.alert("Invalid input", "One of the Props is not properly defined")
}
}
const handleDelete = () => {
const del = async () => {
await deleteExpense(selectedExpense!.guid!)
router.back();
}
del();
}
return (
<View style={styles.container}>
<CategorySelectorModal visible={selectorModalVisible} onRequestClose={()=>{setSelecorModalVisible(false)}} onCategoryTap={handleCategorySelect}></CategorySelectorModal>
<AutoDecimalInput onValueChange={handleValueChange} label='Amount' initialValue={initialValue}/>
<CategorySelector onPress={()=>{setSelecorModalVisible(true)}} selectedCategory={selectedCategory}/>
<TextInputBar placeholder='Name' onChangeText={(text)=>setExpenseName(text)} value={expenseName}/>
<DateSelectorButton selectedDate={selectedDate} onPress={()=>{setDatePickerShown(true)}}/>
{datePickerShown &&
<DateTimePicker
value={new Date()}
maximumDate={new Date()}
onChange={(event, date)=>{
setDatePickerShown(false);
if(date){
setSelectedDate(date);
}
}}
/>}
<RoundedButton color={colors.elementDefaultColor} style={{padding: 10, marginTop: 40}} onPress={handleDelete}>
<Text style={[styles.submitText, {color: colors.primaryText}]}>Delete Expense</Text>
</RoundedButton>
<RoundedButton color={colors.accentColor} style={styles.save} onPress={submit}>
<Text style={[styles.submitText, {color: colors.primaryText}]}>Save</Text>
</RoundedButton>
</View>
)
}
const styles = StyleSheet.create({
notFound: {
alignItems: "center",
justifyContent: "center"
},
notFoundMessageContainer: {
backgroundColor: "#e37b7b",
padding: 50,
},
save: {
padding: 10,
},
container: {
margin: SIZES.normal,
display: "flex",
gap: 10
},
submitText: {
fontSize: SIZES.large
}
})

View file

@ -1,40 +0,0 @@
import { StyleSheet, Text, View } from 'react-native'
import { Stack } from 'expo-router'
import React from 'react'
import { useTheme } from '../../../contexts/ThemeContext'
const _layout = () => {
const {colors} = useTheme();
return (
<Stack
initialRouteName="new"
screenOptions={{
contentStyle: {
backgroundColor:colors.containerColor,
},
headerStyle: {
backgroundColor: colors.containerColor
},
headerTintColor: colors.primaryText
}}>
<Stack.Screen name='new'
options={{
title: "New Expense"
}}
/>
<Stack.Screen name="[expense]"
options={{
headerBackButtonMenuEnabled: true,
headerBackVisible: true,
title: "edit Expense"
}}
getId={(params) => String(Date.now())}
/>
</Stack>
)
}
export default _layout
const styles = StyleSheet.create({})

View file

@ -1,93 +0,0 @@
import { View, Text, StyleSheet, Alert } from 'react-native'
import React, { useRef, useState } from 'react'
import { SIZES } from '../../../../constants/theme'
import { useTheme } from '../../../contexts/ThemeContext'
import { AutoDecimalInput, CategorySelector, CategorySelectorModal, DateSelectorButton, RoundedButton, TextInputBar } from '../../../../components'
import { Category } from '../../../../types/dbItems'
import DateTimePicker from '@react-native-community/datetimepicker';
import { addExpense } from '../../../../services/database'
import { SimpleDate } from '../../../../util/SimpleDate'
import { useRouter } from 'expo-router'
export default function AddItem() {
const {colors} = useTheme();
const router = useRouter();
const [formatedValue, setFormatedValue] = useState<string>("");
const [selectorModalVisible, setSelecorModalVisible] = useState<boolean>(false);
const [selectedCategory, setSelectedCategory] = useState<Category|undefined>()
const [expenseName, setExpenseName] = useState<string>("");
const [datePickerShown, setDatePickerShown] = useState<boolean>(false);
const [selectedDate, setSelectedDate] = useState<Date>(new Date())
const handleValueChange = (formatedValue: string) => {
setFormatedValue(formatedValue);
}
const handleCategorySelect = (category : Category) => {
setSelecorModalVisible(false);
setSelectedCategory(category);
}
const validateInput = ():boolean => {
if(formatedValue == "" || expenseName == "" || selectedCategory === undefined || selectedDate === null){
return false;
}
return true;
}
const submit = () => {
const insert = async () => {
await addExpense(expenseName, selectedCategory?.guid!, new SimpleDate(selectedDate).format("YYYY-MM-DD"), Number(formatedValue))
}
if(validateInput()){
insert();
router.back();
}else {
Alert.alert("Invalid input", "One of the Props is not properly defined")
}
}
return (
<View style={styles.container}>
<CategorySelectorModal visible={selectorModalVisible} onRequestClose={()=>{setSelecorModalVisible(false)}} onCategoryTap={handleCategorySelect}></CategorySelectorModal>
<AutoDecimalInput onValueChange={handleValueChange} label='Amount'/>
<CategorySelector onPress={()=>{setSelecorModalVisible(true)}} selectedCategory={selectedCategory}/>
<TextInputBar placeholder='Name' onChangeText={(text)=>setExpenseName(text)}/>
<DateSelectorButton selectedDate={selectedDate} onPress={()=>{setDatePickerShown(true)}}/>
{datePickerShown &&
<DateTimePicker
value={new Date()}
maximumDate={new Date()}
onChange={(event, date)=>{
setDatePickerShown(false);
if(date){
setSelectedDate(date);
}
}}
/>}
<RoundedButton color={colors.accentColor} style={styles.save} onPress={submit}>
<Text style={[styles.submitText, {color: colors.primaryText}]}>Save</Text>
</RoundedButton>
</View>
)
}
const styles = StyleSheet.create({
save: {
marginTop: 40,
padding: 10,
},
container: {
margin: SIZES.normal,
display: "flex",
gap: 10
},
submitText: {
fontSize: SIZES.large
}
})