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

@ -0,0 +1,12 @@
import { Stack } from "expo-router";
export default function _Layout() {
return (
<Stack initialRouteName="index" screenOptions={{headerShown: false}}>
<Stack.Screen name="index"/>
<Stack.Screen name="addCategory" options={{presentation: "modal"}}/>
<Stack.Screen name="editCategory" options={{presentation: "modal"}}/>
<Stack.Screen name="category" options={{headerShown: false, animation: "slide_from_right"}}/>
</Stack>
);
}

View file

@ -0,0 +1,97 @@
import { router, useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";
import { SafeAreaView } from 'react-native-safe-area-context';
import { AutoDecimalInput, CustomColorPicker, NavigationButton, TypeSelectorSwitch } from "../../../components";
import { addCategory } from "../../../services/database";
import { useTheme } from "../../contexts/ThemeContext";
export default function Page() {
const {colors} = useTheme();
const parameters = useLocalSearchParams();
const [categoryName, setCategoryName] = useState<string>("");
const [categoryColor, setCategoryColor] = useState<string>('#' + Math.floor(Math.random()*16777215).toString(16));
const [selectedType, setSelectedType] = useState<string>("expense");
const [amount, setAmount] = useState(0);
return (
<SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: colors.backgroundColor}]}>
<Text style={[styles.headingTextStyle, {color: colors.primaryText}]}>Add Category</Text>
<View style={[styles.containerStyle, {backgroundColor: colors.containerColor}]}>
<View style={[styles.textInputViewStyle, {backgroundColor: colors.elementDefaultColor}]}>
<TextInput placeholder={"Enter Category Name..."} value={categoryName} placeholderTextColor={colors.secondaryText} style={[styles.textInputStyle, {color: colors.primaryText}]} onChangeText={(newName: string) => {
setCategoryName(newName);
}}/>
</View>
<View style={styles.budgetInput}>
<AutoDecimalInput label={"Allocated:"} onValueChange={(value) => {
setAmount(!Number.isNaN(Number.parseFloat(value)) ? Number.parseFloat(value) : 0);
}}/>
</View>
<TypeSelectorSwitch
currentSelected={selectedType}
handleButtonPress={(type) => {
setSelectedType(type);
}}
/>
<View>
<CustomColorPicker color={categoryColor} handleColorChange={(color) => {
setCategoryColor(color);
}}/>
</View>
<View style={styles.navigationButtonViewStyle}>
<NavigationButton text="Back" onPress={() => {
router.back();
}}/>
<NavigationButton text="Save" onPress={() => {
addCategory(categoryName, categoryColor, selectedType, amount);
router.back();
}}/>
</View>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
containerStyle: {
flex: 1,
margin: 10,
borderRadius: 10,
},
safeAreaViewStyle: {
flex: 1,
flexDirection: "column"
},
headingTextStyle: {
fontSize: 40,
fontWeight: "bold",
alignSelf: "center",
marginVertical: 10,
},
navigationButtonViewStyle: {
flexDirection: "row",
justifyContent: "center",
marginBottom: 10,
},
textInputViewStyle: {
borderRadius: 10,
paddingVertical: 10,
margin: 10,
},
textInputStyle: {
paddingHorizontal: 10,
fontSize: 25,
},
budgetInput: {
marginBottom: 10,
marginHorizontal: 10,
}
});

View file

@ -0,0 +1,131 @@
import { FontAwesome } from "@expo/vector-icons";
import { useRouter, useLocalSearchParams } from "expo-router";
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from "react-native";
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();
const {category_amount, category_color, category_name, category_type} = fetchCategoryInformation(category_guid.toString());
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: "/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}>
<FontAwesome style={styles.iconBack} name="arrow-left" size={35} color={colors.primaryText}/>
<Text style={[styles.backText, {color: colors.secondaryText}]}>Back</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.categoryEditTouchableOpacity, {backgroundColor: colors.elementDefaultColor}]}
onPress={handleEditCategory}>
<Text style={[styles.editButtonText, {color: colors.primaryText}]}>{category_name}</Text>
<FontAwesome style={styles.iconEdit} name="edit" size={35} color={colors.primaryText}/>
</TouchableOpacity>
<TextInputBar style={styles.searchBar} placeholder="Search..."/>
{isLoading ? (<LoadingSymbol/>) : (
<FlatList style={{marginHorizontal: 10}}
data={data}
renderItem = {({item}) => <ExpenseItem
color={item.category_color}
category={item.category_name}
title={item.expense_name}
date={item.expense_datetime}
value={item.expense_amount}
onPress={()=>router.push(`/expense/${item.expense_guid}`)}
/>}
keyExtractor={item => item.expense_guid}
ItemSeparatorComponent={() => {
return (<View style={styles.itemSeperator}/>);
}}
/>
)}
</SafeAreaView>
);
}
const fetchCategoryInformation = (guid: string) => {
const {data} = useFetch({sql: "SELECT * FROM category WHERE guid = ?", args: [guid]});
let category_name = "";
let category_color = "";
let category_amount = 0;
let category_type = "";
if (data && data[0]) {
if ("name" in data[0]) category_name = data[0].name as string;
if ("color" in data[0]) category_color = data[0].color as string;
if ("allocated_amount" in data[0]) category_amount = data[0].allocated_amount as number;
if ("type" in data[0]) category_type = data[0].type as string;
}
return {category_name, category_color, category_amount, category_type};
}
const styles = StyleSheet.create({
safeAreaView: {
flex: 1,
},
itemSeperator: {
margin: 5,
},
categoryEditTouchableOpacity: {
borderRadius: 10,
flexDirection: "row",
justifyContent: "space-around",
margin: 10,
},
editButtonText: {
fontSize: 30,
padding: 10,
fontWeight: "bold",
},
iconEdit: {
paddingVertical: 10,
paddingRight: 10,
},
searchBar: {
marginHorizontal: 10,
marginBottom:20,
},
iconBack: {
paddingLeft: 10,
paddingRight: 5,
},
backText: {
fontSize: 20,
padding: 5,
},
backContainer: {
flexDirection: "row",
justifyContent: "flex-start",
}
});

View file

@ -0,0 +1,97 @@
import { router, useLocalSearchParams } from "expo-router";
import { useState } from "react";
import { SafeAreaView, StyleSheet, Text, TextInput, View } from "react-native";
import { AutoDecimalInput, CustomColorPicker, NavigationButton, TypeSelectorSwitch } from "../../../components";
import { updateCategory } from "../../../services/database";
import { useTheme } from "../../contexts/ThemeContext";
const addCategory = () => {
const {colors} = useTheme();
const {category_guid, category_amount, category_color, category_name, category_type} = useLocalSearchParams();
const [categoryName, setCategoryName] = useState(category_name.toString());
const [categoryColor, setCategoryColor] = useState(category_color.toString());
const [selectedType, setSelectedType] = useState(category_type.toString());
const [amount, setAmount] = useState(Number.parseFloat(category_amount.toString()));
return (
<SafeAreaView style={[styles.safeAreaViewStyle, {backgroundColor: colors.backgroundColor}]}>
<Text style={[styles.headingTextStyle, {color: colors.primaryText}]}>Edit Category</Text>
<View style={[styles.containerStyle, {backgroundColor: colors.containerColor}]}>
<View style={[styles.textInputViewStyle, {backgroundColor: colors.elementDefaultColor}]}>
<TextInput placeholder={"Enter Category Name..."} value={categoryName} placeholderTextColor={colors.secondaryText} style={[styles.textInputStyle, {color: colors.primaryText}]} onChangeText={(newName: string) => {
setCategoryName(newName);
}}/>
</View>
<View style={styles.budgetInput}>
<AutoDecimalInput label={"Allocated:"} onValueChange={(value) => {
setAmount(!Number.isNaN(Number.parseFloat(value)) ? Number.parseFloat(value) : 0);
}}/>
</View>
<TypeSelectorSwitch
currentSelected={selectedType}
handleButtonPress={(type) => {
setSelectedType(type);
}}
/>
<View>
<CustomColorPicker color={categoryColor} handleColorChange={(color) => {
setCategoryColor(color);
}}/>
</View>
<View style={styles.navigationButtonViewStyle}>
<NavigationButton text="Back" onPress={() => {
router.back();
}}/>
<NavigationButton text="Save" onPress={() => {
updateCategory(category_guid.toString(), categoryName, categoryColor, selectedType, amount);
router.back();
}}/>
</View>
</View>
</SafeAreaView>
);
}
export default addCategory;
const styles = StyleSheet.create({
containerStyle: {
flex: 1,
margin: 10,
borderRadius: 10,
},
safeAreaViewStyle: {
flex: 1,
flexDirection: "column"
},
headingTextStyle: {
fontSize: 40,
fontWeight: "bold",
alignSelf: "center",
marginVertical: 10,
},
navigationButtonViewStyle: {
flexDirection: "row",
justifyContent: "center",
marginBottom: 10,
},
textInputViewStyle: {
borderRadius: 10,
paddingVertical: 10,
margin: 10,
},
textInputStyle: {
paddingHorizontal: 10,
fontSize: 25,
},
budgetInput: {
marginBottom: 10,
marginHorizontal: 10,
}
});

View file

@ -0,0 +1,84 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { router, useNavigation } from 'expo-router';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
import { SafeAreaView } from 'react-native-safe-area-context';
import { BudgetHeader, CategoryItem, LoadingSymbol, Plus } from '../../../components';
import useFetch from '../../../hooks/useFetch';
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(() => {
AsyncStorage.getItem("currentBudgetPage").then((page) => {
if(page === "expenses" || page === "savings") {
setSelectedPage(page);
}
}).catch((error) => {
console.log("Error fetching previous page from Async Storage:", error);
})
}, []);
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()
}, [selectedPage]);
const handlePageSelection = (page: string) => {
if(page !== selectedPage) {
setSelectedPage(page);
AsyncStorage.setItem("currentBudgetPage", page);
}
};
const handleCategoryPress = (item: {[column: string]: any;}) => {
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: '/addCategory'});
}}/>
{isLoading ? (<LoadingSymbol/>) : (
<FlatList
data={data}
renderItem = {({item}) => <CategoryItem
category={item.category_name}
allocated_amount={item.allocated_amount ?? 0}
color={item.category_color}
category_guid={item.category_guid}
total_expenses={item.total_expenses ?? 0}
onPress={() => {
handleCategoryPress(item);
}}/>}
keyExtractor={item => item.category_guid}
ItemSeparatorComponent={() => {
return (<View style={styles.itemSeperatorStyle}/>);
}}
/>
)}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeAreaViewStyle: {
flex: 1,
},
itemSeperatorStyle: {
marginVertical: 5,
},
});