Merge branch 'dev'

This commit is contained in:
Milan Paunovic
2024-10-26 18:40:10 +02:00
26 changed files with 1567 additions and 775 deletions

View File

@ -7,7 +7,7 @@ import {
DrawerItemList, DrawerItemList,
} from "@react-navigation/drawer"; } from "@react-navigation/drawer";
import { Button, View, Text, ButtonSize } from "react-native-ui-lib"; import { Button, View, Text, ButtonSize } from "react-native-ui-lib";
import { StyleSheet } from "react-native"; import { ImageBackground, StyleSheet } from "react-native";
import Feather from "@expo/vector-icons/Feather"; import Feather from "@expo/vector-icons/Feather";
import DrawerButton from "@/components/shared/DrawerButton"; import DrawerButton from "@/components/shared/DrawerButton";
import { import {
@ -43,7 +43,16 @@ export default function TabLayout() {
drawerContent={(props) => { drawerContent={(props) => {
return ( return (
<DrawerContentScrollView {...props} style={{ height: "100%" }}> <DrawerContentScrollView {...props} style={{ height: "100%" }}>
<View centerH centerV margin-30> <View centerV margin-30 row>
<ImageBackground
source={require("../../assets/images/splash.png")}
style={{
backgroundColor: "transparent",
height: 51.43,
aspectRatio: 1,
marginRight: 8,
}}
/>
<Text style={styles.title}>Welcome to Cally</Text> <Text style={styles.title}>Welcome to Cally</Text>
</View> </View>
<View <View
@ -203,7 +212,7 @@ const styles = StyleSheet.create({
label: { fontFamily: "Poppins_400Medium", fontSize: 15 }, label: { fontFamily: "Poppins_400Medium", fontSize: 15 },
title: { title: {
fontSize: 26.13, fontSize: 26.13,
fontFamily: 'Manrope_600SemiBold', fontFamily: "Manrope_600SemiBold",
color: "#262627" color: "#262627",
} },
}); });

View File

@ -4,6 +4,7 @@ const CalendarIcon: React.FC<SvgProps> = (props) => (
<Svg <Svg
width={props.width || 21} width={props.width || 21}
height={props.height || 21} height={props.height || 21}
viewBox="0 0 21 21"
fill="none" fill="none"
{...props} {...props}
> >

View File

@ -0,0 +1,20 @@
import * as React from "react"
import Svg, { SvgProps, Path } from "react-native-svg"
const ClockOIcon = (props: SvgProps) => (
<Svg
width={props.height || 22}
height={props.height || 22}
viewBox="0 0 22 22"
fill="none"
{...props}
>
<Path
stroke={props.color || "#919191"}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M11 5.444V11l1.667 2.778M21 11c0 5.523-4.477 10-10 10S1 16.523 1 11 5.477 1 11 1s10 4.477 10 10Z"
/>
</Svg>
)
export default ClockOIcon

View File

@ -0,0 +1,20 @@
import * as React from "react";
import Svg, { SvgProps, Path } from "react-native-svg";
const DropdownIcon = (props: SvgProps) => (
<Svg
width={props.width || 15}
height={props.height || 11}
fill="none"
viewBox="0 0 15 11"
{...props}
>
<Path
stroke={props.color || "#FD1775"}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={props.strokeWidth || 1.393}
d="M4.713 1.318h9.056m-9.056 4.18h9.056m-9.056 4.18h9.056M1.23 1.667h.697V.97H1.23v.696Zm0 4.18h.697V5.15H1.23v.696Zm0 4.18h.697V9.33H1.23v.696Z"
/>
</Svg>
);
export default DropdownIcon;

View File

@ -0,0 +1,18 @@
import * as React from "react"
import Svg, { SvgProps, Path } from "react-native-svg"
const RepeatIcon = (props: SvgProps) => (
<Svg
width={props.height || 13}
height={props.height || 13}
fill="none"
{...props}
>
<Path
stroke={props.color || "#858585"}
strokeLinecap="round"
strokeLinejoin="round"
d="M1.158 7.197a5.42 5.42 0 0 1 9.58-4.103m0 0V1.099m0 1.995v.037H8.705m3.21 2.71a5.42 5.42 0 0 1-9.444 4.263m0 .001v-.198h2.033m-2.033.198v1.835"
/>
</Svg>
)
export default RepeatIcon

View File

@ -1,104 +1,134 @@
import React, {memo} from 'react'; import React, { memo } from "react";
import {Button, Picker, PickerModes, SegmentedControl, Text, View} from "react-native-ui-lib"; import {
import {MaterialIcons} from "@expo/vector-icons"; Button,
import {modeMap, months} from './constants'; Picker,
import {StyleSheet} from "react-native"; PickerModes,
import {useAtom} from "jotai"; SegmentedControl,
import {modeAtom, selectedDateAtom} from "@/components/pages/calendar/atoms"; Text,
import {isSameDay} from "date-fns"; View,
} from "react-native-ui-lib";
import { MaterialIcons } from "@expo/vector-icons";
import { modeMap, months } from "./constants";
import { StyleSheet } from "react-native";
import { useAtom } from "jotai";
import { modeAtom, selectedDateAtom } from "@/components/pages/calendar/atoms";
import { isSameDay } from "date-fns";
import { useAuthContext } from "@/contexts/AuthContext";
export const CalendarHeader = memo(() => { export const CalendarHeader = memo(() => {
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom); const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom); const [mode, setMode] = useAtom(modeAtom);
const { profileData } = useAuthContext();
const handleSegmentChange = (index: number) => { const handleSegmentChange = (index: number) => {
const selectedMode = modeMap.get(index); const selectedMode = modeMap.get(index);
if (selectedMode) { if (selectedMode) {
setTimeout(() => { setTimeout(() => {
setMode(selectedMode as "day" | "week" | "month"); setMode(selectedMode as "day" | "week" | "month");
}, 150); }, 150);
} }
}; };
const handleMonthChange = (month: string) => { const handleMonthChange = (month: string) => {
const currentDay = selectedDate.getDate(); const currentDay = selectedDate.getDate();
const currentYear = selectedDate.getFullYear(); const currentYear = selectedDate.getFullYear();
const newMonthIndex = months.indexOf(month); const newMonthIndex = months.indexOf(month);
const updatedDate = new Date(currentYear, newMonthIndex, currentDay); const updatedDate = new Date(currentYear, newMonthIndex, currentDay);
setSelectedDate(updatedDate); setSelectedDate(updatedDate);
}; };
const isSelectedDateToday = isSameDay(selectedDate, new Date()) const isSelectedDateToday = isSameDay(selectedDate, new Date());
return ( return (
<View <View
style={{ style={{
flexDirection: "row", flexDirection: "row",
justifyContent: "space-between", justifyContent: "space-between",
alignItems: "center", alignItems: "center",
paddingHorizontal: 10, paddingHorizontal: 10,
paddingVertical: 8, paddingVertical: 8,
borderRadius: 20, borderRadius: 20,
borderBottomLeftRadius: 0, borderBottomLeftRadius: 0,
borderBottomRightRadius: 0, borderBottomRightRadius: 0,
backgroundColor: "white", backgroundColor: "white",
marginBottom: 10, marginBottom: 10,
}} }}
>
<View row centerV gap-3>
<Text style={{ fontFamily: "Manrope_500Medium", fontSize: 17 }}>
{selectedDate.getFullYear()}
</Text>
<Picker
value={months[selectedDate.getMonth()]}
placeholder={"Select Month"}
style={{ fontFamily: "Manrope_500Medium", fontSize: 17, width: 85 }}
mode={PickerModes.SINGLE}
onChange={(itemValue) => handleMonthChange(itemValue as string)}
trailingAccessory={<MaterialIcons name={"keyboard-arrow-down"} />}
topBarProps={{
title: selectedDate.getFullYear().toString(),
titleStyle: { fontFamily: "Manrope_500Medium", fontSize: 17 },
}}
> >
<View row centerV gap-3> {months.map((month) => (
<Text style={{fontFamily: "Manrope_500Medium", fontSize: 17}}> <Picker.Item key={month} label={month} value={month} />
{selectedDate.getFullYear()} ))}
</Text> </Picker>
<Picker </View>
value={months[selectedDate.getMonth()]}
placeholder={"Select Month"}
style={{fontFamily: "Manrope_500Medium", fontSize: 17}}
mode={PickerModes.SINGLE}
onChange={(itemValue) => handleMonthChange(itemValue as string)}
trailingAccessory={<MaterialIcons name={"keyboard-arrow-down"}/>}
topBarProps={{
title: selectedDate.getFullYear().toString(),
titleStyle: {fontFamily: "Manrope_500Medium", fontSize: 17},
}}
>
{months.map((month) => (
<Picker.Item key={month} label={month} value={month}/>
))}
</Picker>
</View>
<View row> <View row centerV>
{!isSelectedDateToday && ( {!isSelectedDateToday && (
<Button size={"small"} marginR-5 label={"Today"} onPress={() => { <Button
setSelectedDate(new Date()) size={"xSmall"}
setMode("day") marginR-0
}}/> avoidInnerPadding
)} padding-7
style={{
borderRadius: 5,
backgroundColor: "white",
borderWidth: 0.7,
borderColor: "#dadce0",
height: 30,
}}
labelStyle={{
fontSize: 12,
color: "black",
fontFamily: "Manrope_500Medium",
}}
label={new Date().toLocaleDateString("en-US", {
timeZone: profileData?.timeZone || "",
})}
onPress={() => {
setSelectedDate(new Date());
setMode("day");
console.log(profileData?.timeZone)
}}
/>
)}
<View> <View>
<SegmentedControl <SegmentedControl
segments={[{label: "D"}, {label: "W"}, {label: "M"}]} segments={[{ label: "D" }, { label: "W" }, { label: "M" }]}
backgroundColor="#ececec" backgroundColor="#ececec"
inactiveColor="#919191" inactiveColor="#919191"
activeBackgroundColor="#ea156c" activeBackgroundColor="#ea156c"
activeColor="white" activeColor="white"
outlineColor="white" outlineColor="white"
outlineWidth={3} outlineWidth={3}
segmentLabelStyle={styles.segmentslblStyle} segmentLabelStyle={styles.segmentslblStyle}
onChangeIndex={handleSegmentChange} onChangeIndex={handleSegmentChange}
initialIndex={mode === "day" ? 0 : mode === "week" ? 1 : 2} initialIndex={mode === "day" ? 0 : mode === "week" ? 1 : 2}
/> />
</View>
</View>
</View> </View>
) </View>
; </View>
);
}); });
const styles = StyleSheet.create({ const styles = StyleSheet.create({
segmentslblStyle: { segmentslblStyle: {
fontSize: 12, fontSize: 12,
fontFamily: "Manrope_600SemiBold", fontFamily: "Manrope_600SemiBold",
}, },
}); });

View File

@ -1,32 +1,33 @@
import React, {useCallback, useEffect, useMemo, useState} from 'react'; import React, { useCallback, useEffect, useMemo, useState } from "react";
import {Calendar} from "react-native-big-calendar"; import { Calendar } from "react-native-big-calendar";
import {ActivityIndicator, StyleSheet, View} from "react-native"; import { ActivityIndicator, StyleSheet, View } from "react-native";
import {useGetEvents} from "@/hooks/firebase/useGetEvents"; import { useGetEvents } from "@/hooks/firebase/useGetEvents";
import {useAtom, useSetAtom} from "jotai"; import { useAtom, useSetAtom } from "jotai";
import { import {
editVisibleAtom, editVisibleAtom,
eventForEditAtom, eventForEditAtom,
modeAtom, modeAtom,
selectedDateAtom, selectedDateAtom,
selectedNewEventDateAtom selectedNewEventDateAtom,
} from "@/components/pages/calendar/atoms"; } from "@/components/pages/calendar/atoms";
import {useAuthContext} from "@/contexts/AuthContext"; import { useAuthContext } from "@/contexts/AuthContext";
import {CalendarEvent} from "@/components/pages/calendar/interfaces"; import { CalendarEvent } from "@/components/pages/calendar/interfaces";
interface EventCalendarProps { interface EventCalendarProps {
calendarHeight: number; calendarHeight: number;
// WAS USED FOR SCROLLABLE CALENDARS, PERFORMANCE WAS NOT OPTIMAL // WAS USED FOR SCROLLABLE CALENDARS, PERFORMANCE WAS NOT OPTIMAL
calendarWidth: number; calendarWidth: number;
} }
const getTotalMinutes = () => { const getTotalMinutes = () => {
const date = new Date(); const date = new Date();
return Math.abs(date.getUTCHours() * 60 + date.getUTCMinutes() - 200); return Math.abs(date.getUTCHours() * 60 + date.getUTCMinutes() - 200);
} };
export const EventCalendar: React.FC<EventCalendarProps> = React.memo(({calendarHeight}) => { export const EventCalendar: React.FC<EventCalendarProps> = React.memo(
const {data: events, isLoading} = useGetEvents(); ({ calendarHeight }) => {
const {profileData} = useAuthContext(); const { data: events, isLoading } = useGetEvents();
const { profileData } = useAuthContext();
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom); const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom); const [mode, setMode] = useAtom(modeAtom);
@ -35,113 +36,128 @@ export const EventCalendar: React.FC<EventCalendarProps> = React.memo(({calendar
const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom); const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom);
const [isRendering, setIsRendering] = useState(true); const [isRendering, setIsRendering] = useState(true);
const [offsetMinutes, setOffsetMinutes] = useState(getTotalMinutes()) const [offsetMinutes, setOffsetMinutes] = useState(getTotalMinutes());
useEffect(() => { useEffect(() => {
if (events && mode) { if (events && mode) {
setIsRendering(true); setIsRendering(true);
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
setIsRendering(false); setIsRendering(false);
}, 300); }, 300);
return () => clearTimeout(timeout); return () => clearTimeout(timeout);
} }
}, [events, mode]); }, [events, mode]);
const handlePressEvent = useCallback((event: CalendarEvent) => { const handlePressEvent = useCallback(
(event: CalendarEvent) => {
if (mode === "day" || mode === "week") { if (mode === "day" || mode === "week") {
setEditVisible(true); setEditVisible(true);
console.log({event}) console.log({ event });
setEventForEdit(event); setEventForEdit(event);
} else { } else {
setMode("day") setMode("day");
setSelectedDate(event.start); setSelectedDate(event.start);
} }
}, [setEditVisible, setEventForEdit, mode]); },
[setEditVisible, setEventForEdit, mode]
const handlePressCell = useCallback(
(date: Date) => {
if (mode === "day" || mode === "week") {
setSelectedNewEndDate(date);
} else {
setMode("day")
setSelectedDate(date);
}
},
[mode, setSelectedNewEndDate, setSelectedDate]
); );
const handleSwipeEnd = useCallback((date: Date) => { const handlePressCell = useCallback(
(date: Date) => {
if (mode === "day" || mode === "week") {
setSelectedNewEndDate(date);
} else {
setMode("day");
setSelectedDate(date);
}
},
[mode, setSelectedNewEndDate, setSelectedDate]
);
const handleSwipeEnd = useCallback(
(date: Date) => {
setSelectedDate(date); setSelectedDate(date);
}, [setSelectedDate]); },
[setSelectedDate]
);
const memoizedEventCellStyle = useCallback( const memoizedEventCellStyle = useCallback(
(event: CalendarEvent) => ({backgroundColor: event.eventColor}), (event: CalendarEvent) => ({ backgroundColor: event.eventColor }),
[] []
); );
const memoizedWeekStartsOn = useMemo( const memoizedWeekStartsOn = useMemo(
() => (profileData?.firstDayOfWeek === "Mondays" ? 1 : 0), () => (profileData?.firstDayOfWeek === "Mondays" ? 1 : 0),
[profileData] [profileData]
); );
const memoizedHeaderContentStyle = useMemo( const memoizedHeaderContentStyle = useMemo(
() => (mode === "day" ? styles.dayModeHeader : {}), () => (mode === "day" ? styles.dayModeHeader : {}),
[mode] [mode]
); );
const memoizedEvents = useMemo(() => events ?? [], [events]); const memoizedEvents = useMemo(() => events ?? [], [events]);
useEffect(() => { useEffect(() => {
setOffsetMinutes(getTotalMinutes()) setOffsetMinutes(getTotalMinutes());
}, [events, mode]); }, [events, mode]);
if (isLoading || isRendering) { if (isLoading || isRendering) {
return ( return (
<View style={styles.loadingContainer}> <View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0000ff"/> <ActivityIndicator size="large" color="#0000ff" />
</View> </View>
); );
} }
return ( return (
<Calendar <Calendar
bodyContainerStyle={styles.calHeader} bodyContainerStyle={styles.calHeader}
swipeEnabled swipeEnabled
enableEnrichedEvents enableEnrichedEvents
mode={mode} mode={mode}
events={memoizedEvents} events={memoizedEvents}
eventCellStyle={memoizedEventCellStyle} eventCellStyle={memoizedEventCellStyle}
onPressEvent={handlePressEvent} onPressEvent={handlePressEvent}
weekStartsOn={memoizedWeekStartsOn} weekStartsOn={memoizedWeekStartsOn}
height={calendarHeight} height={calendarHeight}
activeDate={selectedDate} activeDate={selectedDate}
date={selectedDate} date={selectedDate}
onPressCell={handlePressCell} onPressCell={handlePressCell}
headerContentStyle={memoizedHeaderContentStyle} headerContentStyle={memoizedHeaderContentStyle}
onSwipeEnd={handleSwipeEnd} onSwipeEnd={handleSwipeEnd}
scrollOffsetMinutes={offsetMinutes} scrollOffsetMinutes={offsetMinutes}
/> />
); );
}); }
);
const styles = StyleSheet.create({ const styles = StyleSheet.create({
segmentslblStyle: { segmentslblStyle: {
fontSize: 12, fontSize: 12,
fontFamily: "Manrope_600SemiBold", fontFamily: "Manrope_600SemiBold",
}, },
calHeader: { calHeader: {
borderWidth: 0, borderWidth: 0,
}, },
dayModeHeader: { dayModeHeader: {
alignSelf: "flex-start", alignSelf: "flex-start",
justifyContent: "space-between", justifyContent: "space-between",
alignContent: "center", alignContent: "center",
width: 38, width: 38,
right: 42, right: 42,
}, height: 13,
loadingContainer: { },
flex: 1, loadingContainer: {
justifyContent: 'center', flex: 1,
alignItems: 'center', justifyContent: "center",
}, alignItems: "center",
},
dayHeader: {
backgroundColor: "#4184f2",
aspectRatio: 1,
borderRadius: 100,
alignItems: "center",
justifyContent: "center",
},
}); });

View File

@ -21,7 +21,7 @@ export const InnerCalendar = () => {
return ( return (
<> <>
<View <View
style={{flex: 1, backgroundColor: "#fff", borderRadius: 30, marginBottom: 60}} style={{flex: 1, backgroundColor: "#fff", borderRadius: 30, marginBottom: 60, overflow: "hidden"}}
ref={calendarContainerRef} ref={calendarContainerRef}
onLayout={onLayout} onLayout={onLayout}
> >

View File

@ -1,74 +1,145 @@
import {Text, View} from "react-native"; import { Text, View } from "react-native-ui-lib";
import React, {useEffect, useRef, useState} from "react"; import React, { useEffect, useRef, useState } from "react";
import {TextField, TextFieldRef} from "react-native-ui-lib"; import { TextField, TextFieldRef } from "react-native-ui-lib";
import {GroceryCategory, useGroceryContext,} from "@/contexts/GroceryContext"; import { GroceryCategory, useGroceryContext } from "@/contexts/GroceryContext";
import CategoryDropdown from "./CategoryDropdown"; import { Dropdown } from "react-native-element-dropdown";
import CloseXIcon from "@/assets/svgs/CloseXIcon";
import { StyleSheet } from "react-native";
import DropdownIcon from "@/assets/svgs/DropdownIcon";
interface IEditGrocery { interface IEditGrocery {
id?: string; id?: string;
title: string; title: string;
category: GroceryCategory; category: GroceryCategory;
setTitle: (value: string) => void; setTitle: (value: string) => void;
setCategory?: (category: GroceryCategory) => void; setCategory?: (category: GroceryCategory) => void;
setSubmit?: (value: boolean) => void; setSubmit?: (value: boolean) => void;
closeEdit?: (value: boolean) => void; closeEdit?: (value: boolean) => void;
handleEditSubmit?: Function handleEditSubmit?: Function;
} }
const EditGroceryItem = ({editGrocery}: { editGrocery: IEditGrocery }) => { const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
const {fuzzyMatchGroceryCategory} = useGroceryContext(); const { fuzzyMatchGroceryCategory } = useGroceryContext();
const inputRef = useRef<TextFieldRef>(null); const inputRef = useRef<TextFieldRef>(null);
const [category, setCategory] = useState<GroceryCategory>(GroceryCategory.None);
useEffect(() => { const groceryCategoryOptions = Object.values(GroceryCategory).map(
if (editGrocery.setCategory) (category) => ({
editGrocery.setCategory(fuzzyMatchGroceryCategory(editGrocery.title)); label: category,
}, [editGrocery.title]); value: category,
})
);
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
inputRef.current.focus(); // Focus on the TextField inputRef.current.focus(); // Focus on the TextField
}
console.log(editGrocery.category);
}, []);
return (
<View
style={{
backgroundColor: "white",
width: "100%",
borderRadius: 25,
paddingHorizontal: 13,
paddingVertical: 10,
marginTop: 0,
}}
>
<View row spread centerV>
<TextField
text70T
style={{}}
ref={inputRef}
placeholder="Grocery"
value={editGrocery.title}
onChangeText={(value) => {
editGrocery.setTitle(value);
}}
onSubmitEditing={() => {
if (editGrocery.setSubmit) {
editGrocery.setSubmit(true);
}
if (editGrocery.handleEditSubmit) {
editGrocery.handleEditSubmit({
id: editGrocery.id,
title: editGrocery.title,
category: editGrocery.category,
});
}
if (editGrocery.closeEdit) {
editGrocery.closeEdit(false);
}
}}
maxLength={25}
/>
<CloseXIcon
onPress={() => {
if (editGrocery.closeEdit) editGrocery.closeEdit(false);
}}
/>
</View>
<Dropdown
style={{marginTop: 15}}
data={groceryCategoryOptions}
placeholder="Select grocery category"
placeholderStyle={{ color: "#a2a2a2", fontFamily: "Manrope_500Medium", fontSize: 13.2 }}
labelField="label"
valueField="value"
value={
editGrocery.category == GroceryCategory.None
? null
: editGrocery.category
} }
}, []); iconColor="white"
activeColor={"#fd1775"}
return ( containerStyle={styles.dropdownStyle}
<View itemTextStyle={styles.itemText}
style={{ itemContainerStyle={styles.itemStyle}
backgroundColor: "white", selectedTextStyle={styles.selectedText}
width: "100%", renderLeftIcon={() => (
borderRadius: 25, <DropdownIcon style={{ marginRight: 8 }} color={editGrocery.category == GroceryCategory.None ? "#7b7b7b" : "#fd1775"} />
padding: 15, )}
marginTop: 10 renderItem={(item) => {
}} return (
> <View height={36.02} centerV>
<TextField <Text style={styles.itemText}>{item.label}</Text>
text70T </View>
style={{fontWeight: "400"}} );
ref={inputRef} }}
placeholder="Grocery" onChange={(item) => {
value={editGrocery.title} if (editGrocery.handleEditSubmit) {
onChangeText={(value) => { editGrocery.handleEditSubmit({
editGrocery.setTitle(value); id: editGrocery.id,
}} category: item.value,
onSubmitEditing={() => { });
if (editGrocery.setSubmit) { console.log("kategorija vo diropdown: " + item.value);
editGrocery.setSubmit(true); if (editGrocery.closeEdit) editGrocery.closeEdit(false);
} } else {
if (editGrocery.setCategory) { if (editGrocery.setCategory) {
editGrocery.setCategory(fuzzyMatchGroceryCategory(editGrocery.title)); editGrocery.setCategory(item.value);
} }
if (editGrocery.handleEditSubmit) { }
editGrocery.handleEditSubmit({id: editGrocery.id, title: editGrocery.title, category: editGrocery.category}); }}
} />
if (editGrocery.closeEdit) { </View>
editGrocery.closeEdit(false); );
}
}}
maxLength={25}
/>
<Text>{editGrocery.category}</Text>
</View>
);
}; };
const styles = StyleSheet.create({
itemText: {
fontFamily: "Manrope_400Regular",
fontSize: 15.42,
paddingLeft: 15,
},
selectedText: {
fontFamily: "Manrope_500Medium",
fontSize: 13.2,
color: "#fd1775",
},
dropdownStyle: { borderRadius: 6.61, height: 115.34, width: 187 },
itemStyle: { padding: 0, margin: 0 },
});
export default EditGroceryItem; export default EditGroceryItem;

View File

@ -1,13 +1,14 @@
import { Checkbox, Text, TouchableOpacity, View } from "react-native-ui-lib"; import {Checkbox, Text, TouchableOpacity, View} from "react-native-ui-lib";
import React, { useEffect, useState } from "react"; import React, {useEffect, useState} from "react";
import { AntDesign } from "@expo/vector-icons"; import {AntDesign} from "@expo/vector-icons";
import { GroceryCategory, useGroceryContext } from "@/contexts/GroceryContext"; import {GroceryCategory, useGroceryContext} from "@/contexts/GroceryContext";
import EditGroceryFrequency from "./EditGroceryFrequency"; import EditGroceryFrequency from "./EditGroceryFrequency";
import EditGroceryItem from "./EditGroceryItem"; import EditGroceryItem from "./EditGroceryItem";
import { ImageBackground, StyleSheet } from "react-native"; import {ImageBackground, StyleSheet} from "react-native";
import { IGrocery } from "@/hooks/firebase/types/groceryData"; import {IGrocery} from "@/hooks/firebase/types/groceryData";
import firestore from "@react-native-firebase/firestore"; import firestore from "@react-native-firebase/firestore";
import { UserProfile } from "@/hooks/firebase/types/profileTypes"; import {UserProfile} from "@/hooks/firebase/types/profileTypes";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
const GroceryItem = ({ const GroceryItem = ({
item, item,
@ -17,6 +18,8 @@ const GroceryItem = ({
handleItemApproved: (id: string, changes: Partial<IGrocery>) => void; handleItemApproved: (id: string, changes: Partial<IGrocery>) => void;
}) => { }) => {
const { updateGroceryItem } = useGroceryContext(); const { updateGroceryItem } = useGroceryContext();
const { profileData } = useAuthContext();
const isParent = profileData?.userType === ProfileType.PARENT;
const [openFreqEdit, setOpenFreqEdit] = useState<boolean>(false); const [openFreqEdit, setOpenFreqEdit] = useState<boolean>(false);
const [isEditingTitle, setIsEditingTitle] = useState<boolean>(false); const [isEditingTitle, setIsEditingTitle] = useState<boolean>(false);
@ -36,7 +39,7 @@ const GroceryItem = ({
useEffect(() => { useEffect(() => {
setNewTitle(item.title); setNewTitle(item.title);
console.log(item);
getItemCreator(item?.creatorId); getItemCreator(item?.creatorId);
}, []); }, []);
@ -53,14 +56,21 @@ const GroceryItem = ({
} }
}; };
const getInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`;
};
return ( return (
<View <View
key={item.id} key={item.id}
style={{ borderRadius: 17, marginVertical: 5 }} style={{
borderRadius: 17,
marginVertical: 5,
paddingHorizontal: isEditingTitle ? 0 : 13,
paddingVertical: isEditingTitle ? 0 : 10,
}}
backgroundColor="white" backgroundColor="white"
centerV centerV
paddingH-13
paddingV-10
> >
<View row spread> <View row spread>
<EditGroceryFrequency <EditGroceryFrequency
@ -73,56 +83,65 @@ const GroceryItem = ({
/> />
{!isEditingTitle ? ( {!isEditingTitle ? (
<View> <View>
<TouchableOpacity onPress={() => setIsEditingTitle(true)}> { isParent ? <TouchableOpacity onPress={() => setIsEditingTitle(true)}>
<Text text70T black style={styles.title}> <Text text70T black style={styles.title}>
{item.title} {item.title}
</Text> </Text>
</TouchableOpacity> </TouchableOpacity> :
<Text text70T black style={styles.title}>
{item.title}
</Text>
}
</View> </View>
) : ( ) : (
<EditGroceryItem <EditGroceryItem
editGrocery={{ editGrocery={{
id: item.id, id: item.id,
title: newTitle, title: newTitle,
category: category, category: item.category,
setTitle: setNewTitle, setTitle: setNewTitle,
setCategory: setCategory, setCategory: setCategory,
closeEdit: setIsEditingTitle, closeEdit: setIsEditingTitle,
handleEditSubmit: updateGroceryItem handleEditSubmit: updateGroceryItem,
}} }}
/> />
)} )}
{!item.approved ? ( {!item.approved ? (
<View row centerV marginB-10> <View row centerV marginB-10>
<AntDesign {isParent && <><AntDesign
name="check" name="check"
size={24} size={24}
style={{ style={{
color: item.approved ? "green" : "#aaaaaa", color: "green",
marginRight: 15, marginRight: 15,
}} }}
onPress={() => { onPress={() => {
handleItemApproved(item.id, { approved: true }); isParent ? handleItemApproved(item.id, { approved: true }) : null
}} }}
/> />
<AntDesign <AntDesign
name="close" name="close"
size={24} size={24}
style={{ color: item.approved ? "#aaaaaa" : "red" }} style={{ color: "red" }}
onPress={() => { onPress={() => {
handleItemApproved(item.id, { approved: false }); isParent ? handleItemApproved(item.id, { approved: false }) : null
}} }}
/> /> </>}
</View> </View>
) : ( ) : (
<Checkbox !isEditingTitle && (
value={item.bought} <Checkbox
containerStyle={styles.checkbox} value={item.bought}
hitSlop={20} containerStyle={[styles.checkbox, {borderRadius: 50}]}
onValueChange={() => style={styles.checked}
updateGroceryItem({ id: item.id, bought: !item.bought }) borderRadius={50}
} color="#fd1575"
/> hitSlop={20}
onValueChange={() =>
updateGroceryItem({ id: item.id, bought: !item.bought })
}
/>
)
)} )}
</View> </View>
{!item.approved && ( {!item.approved && (
@ -131,17 +150,43 @@ const GroceryItem = ({
<View height={0.7} backgroundColor="#e7e7e7" width={"98%"} /> <View height={0.7} backgroundColor="#e7e7e7" width={"98%"} />
</View> </View>
<View paddingL-0 paddingT-12 flexS row centerV> <View paddingL-0 paddingT-12 flexS row centerV>
<ImageBackground {profileData?.pfp ? <ImageBackground
style={{ source={require("../../../assets/images/child-picture.png")}
width: 22.36, style={{
aspectRatio: 1, height: 24.64,
borderRadius: 50, aspectRatio: 1,
backgroundColor: "red", borderRadius: 22,
marginRight: 10, overflow: "hidden",
overflow: 'hidden' }}
}} /> : <View
source={require('../../../assets/images/child-picture.png')} style={{
/> position: "relative",
width: 24.64,
aspectRatio: 1,
marginRight: 4
}}
>
<View
style={{
backgroundColor: "#ccc",
justifyContent: "center",
alignItems: "center",
borderRadius: 100, // Circular shape
width: "100%",
height: "100%",
}}
>
<Text
style={{
color: "#fff",
fontSize: 12,
fontWeight: "bold",
}}
>
{getInitials(itemCreator.firstName, itemCreator.lastName ?? "")}
</Text>
</View>
</View>}
<Text color="#858585" style={styles.authorTxt}> <Text color="#858585" style={styles.authorTxt}>
Requested by {itemCreator?.firstName} Requested by {itemCreator?.firstName}
</Text> </Text>
@ -166,6 +211,9 @@ const styles = StyleSheet.create({
fontFamily: "Manrope_500Medium", fontFamily: "Manrope_500Medium",
fontSize: 15, fontSize: 15,
}, },
checked: {
borderRadius: 50,
},
}); });
export default GroceryItem; export default GroceryItem;

View File

@ -30,8 +30,9 @@ const GroceryList = () => {
groceries?.filter((item) => item.approved !== true) groceries?.filter((item) => item.approved !== true)
); );
const [category, setCategory] = useState<GroceryCategory>( const [category, setCategory] = useState<GroceryCategory>(
GroceryCategory.Bakery GroceryCategory.None
); );
const [title, setTitle] = useState<string>(""); const [title, setTitle] = useState<string>("");
const [submit, setSubmitted] = useState<boolean>(false); const [submit, setSubmitted] = useState<boolean>(false);

View File

@ -1,250 +1,292 @@
import React, {useEffect, useRef, useState} from "react"; import React, { useEffect, useRef, useState } from "react";
import {StyleSheet, TouchableOpacity} from "react-native"; import { StyleSheet, TouchableOpacity } from "react-native";
import {ScrollView} from "react-native-gesture-handler"; import { ScrollView } from "react-native-gesture-handler";
import * as ImagePicker from "expo-image-picker"; import * as ImagePicker from "expo-image-picker";
import {Colors, Image, Picker, Text, TextField, View} from "react-native-ui-lib"; import {
Colors,
Image,
Picker,
Text,
TextField,
View,
} from "react-native-ui-lib";
import Ionicons from "@expo/vector-icons/Ionicons"; import Ionicons from "@expo/vector-icons/Ionicons";
import * as tz from "tzdata"; import * as tz from "tzdata";
import * as Localization from "expo-localization"; import * as Localization from "expo-localization";
import debounce from "debounce"; import debounce from "debounce";
import {useAuthContext} from "@/contexts/AuthContext"; import { useAuthContext } from "@/contexts/AuthContext";
import {useUpdateUserData} from "@/hooks/firebase/useUpdateUserData"; import { useUpdateUserData } from "@/hooks/firebase/useUpdateUserData";
import {useChangeProfilePicture} from "@/hooks/firebase/useChangeProfilePicture"; import { useChangeProfilePicture } from "@/hooks/firebase/useChangeProfilePicture";
import { colorMap } from "@/constants/colorMap";
const MyProfile = () => { const MyProfile = () => {
const {user, profileData} = useAuthContext(); const { user, profileData } = useAuthContext();
const [timeZone, setTimeZone] = useState<string>( const [timeZone, setTimeZone] = useState<string>(
profileData?.timeZone! ?? Localization.getCalendars()[0].timeZone profileData?.timeZone! ?? Localization.getCalendars()[0].timeZone
); );
const [lastName, setLastName] = useState<string>(profileData?.lastName || ""); const [lastName, setLastName] = useState<string>(profileData?.lastName || "");
const [firstName, setFirstName] = useState<string>( const [firstName, setFirstName] = useState<string>(
profileData?.firstName || "" profileData?.firstName || ""
); );
const [profileImage, setProfileImage] = useState<string | ImagePicker.ImagePickerAsset | null>(profileData?.pfp || null); const [profileImage, setProfileImage] = useState<
string | ImagePicker.ImagePickerAsset | null
>(profileData?.pfp || null);
const {mutateAsync: updateUserData} = useUpdateUserData(); const { mutateAsync: updateUserData } = useUpdateUserData();
const {mutateAsync: changeProfilePicture} = useChangeProfilePicture(); const { mutateAsync: changeProfilePicture } = useChangeProfilePicture();
const isFirstRender = useRef(true); const isFirstRender = useRef(true);
const handleUpdateUserData = async () => { const handleUpdateUserData = async () => {
await updateUserData({newUserData: {firstName, lastName, timeZone}}); await updateUserData({ newUserData: { firstName, lastName, timeZone } });
}; };
const debouncedUserDataUpdate = debounce(handleUpdateUserData, 500); const debouncedUserDataUpdate = debounce(handleUpdateUserData, 500);
useEffect(() => { useEffect(() => {
if (isFirstRender.current) { if (isFirstRender.current) {
isFirstRender.current = false; isFirstRender.current = false;
return; return;
} }
debouncedUserDataUpdate(); debouncedUserDataUpdate();
}, [timeZone, lastName, firstName, profileImage]); }, [timeZone, lastName, firstName, profileImage]);
useEffect(() => { useEffect(() => {
if (profileData) { if (profileData) {
setFirstName(profileData.firstName || ""); setFirstName(profileData.firstName || "");
setLastName(profileData.lastName || ""); setLastName(profileData.lastName || "");
// setProfileImage(profileData.pfp || null); // setProfileImage(profileData.pfp || null);
setTimeZone(profileData.timeZone || Localization.getCalendars()[0].timeZone!); setTimeZone(
} profileData.timeZone || Localization.getCalendars()[0].timeZone!
}, [profileData]); );
}
}, [profileData]);
const pickImage = async () => { const pickImage = async () => {
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); const permissionResult =
if (!permissionResult.granted) { await ImagePicker.requestMediaLibraryPermissionsAsync();
alert("Permission to access camera roll is required!"); if (!permissionResult.granted) {
return; alert("Permission to access camera roll is required!");
} return;
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.canceled) {
setProfileImage(result.assets[0].uri);
changeProfilePicture(result.assets[0])
}
};
const handleClearImage = async () => {
await updateUserData({newUserData: {pfp: null}});
setProfileImage(null)
} }
const pfpUri = profileImage && typeof profileImage === 'object' && 'uri' in profileImage ? profileImage.uri : profileImage; const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
return ( if (!result.canceled) {
<ScrollView style={{paddingBottom: 100, flex: 1}}> setProfileImage(result.assets[0].uri);
<View style={styles.card}> changeProfilePicture(result.assets[0]);
<Text style={styles.subTit}>Your Profile</Text> }
<View row spread paddingH-15 centerV marginV-15> };
<TouchableOpacity onPress={pickImage}>
<Image
key={pfpUri}
style={styles.pfp}
source={pfpUri ? {uri: pfpUri} : null}
/>
</TouchableOpacity>
<TouchableOpacity onPress={pickImage}> const handleClearImage = async () => {
<Text style={styles.photoSet} color="#50be0c" onPress={pickImage}> await updateUserData({ newUserData: { pfp: null } });
{profileData?.pfp ? "Change" : "Add"} Photo setProfileImage(null);
</Text> };
</TouchableOpacity>
{profileData?.pfp && ( const pfpUri =
<TouchableOpacity onPress={handleClearImage}> profileImage && typeof profileImage === "object" && "uri" in profileImage
<Text style={styles.photoSet}>Remove Photo</Text> ? profileImage.uri
</TouchableOpacity> : profileImage;
)}
</View>
<View paddingH-15>
<Text text80 marginT-10 marginB-7 style={styles.label}>
First name
</Text>
<TextField
text70
placeholder="First name"
style={styles.txtBox}
value={firstName}
onChangeText={async (value) => {
setFirstName(value);
}}
/>
<Text text80 marginT-10 marginB-7 style={styles.label}>
Last name
</Text>
<TextField
text70
placeholder="Last name"
style={styles.txtBox}
value={lastName}
onChangeText={async (value) => {
setLastName(value);
}}
/>
<Text text80 marginT-10 marginB-7 style={styles.label}>
Email address
</Text>
<TextField
editable={false}
text70
placeholder="Email address"
value={user?.email?.toString()}
style={styles.txtBox}
/>
</View>
</View>
<View style={styles.card}> return (
<Text style={styles.subTit}>Settings</Text> <ScrollView style={{ paddingBottom: 100, flex: 1 }}>
<Text style={styles.jakarta12}>Time Zone</Text> <View style={styles.card}>
<View style={styles.viewPicker}> <Text style={styles.subTit}>Your Profile</Text>
<Picker <View row spread paddingH-15 centerV marginV-15>
value={timeZone} <TouchableOpacity onPress={pickImage}>
onChange={(item) => setTimeZone(item as string)} {pfpUri ? (
showSearch <Image
floatingPlaceholder key={pfpUri}
style={styles.inViewPicker} style={styles.pfp}
trailingAccessory={ source={pfpUri ? { uri: pfpUri } : null}
<View />
style={{ ) : (
justifyContent: "center", <View
alignItems: "center", center
height: "100%", style={{
marginTop: -38, aspectRatio: 1,
paddingRight: 15, width: 65.54,
}} backgroundColor: profileData?.eventColor ?? colorMap.pink,
> borderRadius: 20,
<Ionicons }}
name={"chevron-down"} >
style={{alignSelf: "center"}} <Text style={styles.pfpTxt}>
size={20} {user?.email?.at(0)}
color={"#000000"} {user?.email?.at(1)}
/> </Text>
</View> </View>
} )}
> </TouchableOpacity>
{timeZoneItems}
</Picker> <TouchableOpacity onPress={pickImage}>
</View> <Text style={styles.photoSet} color="#50be0c" onPress={pickImage}>
</View> {profileData?.pfp ? "Change" : "Add"} Photo
</ScrollView> </Text>
); </TouchableOpacity>
{profileData?.pfp && (
<TouchableOpacity onPress={handleClearImage}>
<Text style={styles.photoSet}>Remove Photo</Text>
</TouchableOpacity>
)}
</View>
<View paddingH-15>
<Text text80 marginT-10 marginB-7 style={styles.label}>
First name
</Text>
<TextField
text70
placeholder="First name"
style={styles.txtBox}
value={firstName}
onChangeText={async (value) => {
setFirstName(value);
}}
/>
<Text text80 marginT-10 marginB-7 style={styles.label}>
Last name
</Text>
<TextField
text70
placeholder="Last name"
style={styles.txtBox}
value={lastName}
onChangeText={async (value) => {
setLastName(value);
}}
/>
<Text text80 marginT-10 marginB-7 style={styles.label}>
Email address
</Text>
<TextField
editable={false}
text70
placeholder="Email address"
value={user?.email?.toString()}
style={styles.txtBox}
/>
</View>
</View>
<View style={styles.card}>
<Text style={styles.subTit}>Settings</Text>
<Text style={styles.jakarta12}>Time Zone</Text>
<View style={styles.viewPicker}>
<Picker
value={timeZone}
onChange={(item) => setTimeZone(item as string)}
showSearch
floatingPlaceholder
style={styles.inViewPicker}
trailingAccessory={
<View
style={{
justifyContent: "center",
alignItems: "center",
height: "100%",
marginTop: -38,
paddingRight: 15,
}}
>
<Ionicons
name={"chevron-down"}
style={{ alignSelf: "center" }}
size={20}
color={"#000000"}
/>
</View>
}
>
{timeZoneItems}
</Picker>
</View>
</View>
</ScrollView>
);
}; };
const timeZoneItems = Object.keys(tz.zones) const timeZoneItems = Object.keys(tz.zones)
.sort() .sort()
.map((zone) => ( .map((zone) => (
<Picker.Item key={zone} label={zone.replace("/", " / ").replace("_", " ")} value={zone}/> <Picker.Item
)); key={zone}
label={zone.replace("/", " / ").replace("_", " ")}
value={zone}
/>
));
const styles = StyleSheet.create({ const styles = StyleSheet.create({
card: { card: {
marginVertical: 15, marginVertical: 15,
backgroundColor: "white", backgroundColor: "white",
width: "100%", width: "100%",
borderRadius: 12, borderRadius: 12,
paddingHorizontal: 20, paddingHorizontal: 20,
paddingVertical: 21, paddingVertical: 21,
}, },
pfp: { pfpTxt: {
aspectRatio: 1, fontFamily: "Manrope_500Medium",
width: 65.54, fontSize: 30,
backgroundColor: "gray", color: "white",
borderRadius: 20, },
}, pfp: {
txtBox: { aspectRatio: 1,
backgroundColor: "#fafafa", width: 65.54,
borderRadius: 50, backgroundColor: "gray",
borderWidth: 2, borderRadius: 20,
borderColor: "#cecece", },
padding: 15, txtBox: {
height: 45, backgroundColor: "#fafafa",
fontFamily: "PlusJakartaSans_500Medium", borderRadius: 50,
fontSize: 13, borderWidth: 2,
}, borderColor: "#cecece",
subTit: { padding: 15,
fontFamily: "Manrope_500Medium", height: 45,
fontSize: 15, fontFamily: "PlusJakartaSans_500Medium",
}, fontSize: 13,
label: { },
fontFamily: "PlusJakartaSans_500Medium", subTit: {
fontSize: 12, fontFamily: "Manrope_500Medium",
color: "#a1a1a1", fontSize: 15,
}, },
photoSet: { label: {
fontFamily: "PlusJakartaSans_500Medium", fontFamily: "PlusJakartaSans_500Medium",
fontSize: 13.07, fontSize: 12,
}, color: "#a1a1a1",
jakarta12: { },
paddingVertical: 10, photoSet: {
fontFamily: "PlusJakartaSans_500Medium", fontFamily: "PlusJakartaSans_500Medium",
fontSize: 12, fontSize: 13.07,
color: "#a1a1a1", },
}, jakarta12: {
viewPicker: { paddingVertical: 10,
borderRadius: 50, fontFamily: "PlusJakartaSans_500Medium",
backgroundColor: Colors.grey80, fontSize: 12,
marginBottom: 16, color: "#a1a1a1",
borderColor: Colors.grey50, },
borderWidth: 1, viewPicker: {
marginTop: 0, borderRadius: 50,
height: 40, backgroundColor: Colors.grey80,
zIndex: 10, marginBottom: 16,
}, borderColor: Colors.grey50,
inViewPicker: { borderWidth: 1,
borderRadius: 50, marginTop: 0,
paddingVertical: 12, height: 40,
paddingHorizontal: 16, zIndex: 10,
marginBottom: 16, },
marginTop: -20, inViewPicker: {
height: 40, borderRadius: 50,
zIndex: 10, paddingVertical: 12,
}, paddingHorizontal: 16,
marginBottom: 16,
marginTop: -20,
height: 40,
zIndex: 10,
},
}); });
export default MyProfile; export default MyProfile;

View File

@ -1,56 +1,61 @@
import {StyleSheet} from "react-native"; import { StyleSheet } from "react-native";
import React, {useState} from "react"; import React, { useState } from "react";
import {Button, ButtonSize, Text, View} from "react-native-ui-lib"; import { Button, ButtonSize, Text, View } from "react-native-ui-lib";
import {AntDesign} from "@expo/vector-icons"; import { AntDesign } from "@expo/vector-icons";
import LinearGradient from "react-native-linear-gradient"; import LinearGradient from "react-native-linear-gradient";
import AddChoreDialog from "./AddChoreDialog"; import AddChoreDialog from "./AddChoreDialog";
const AddChore = () => { const AddChore = () => {
const [isVisible, setIsVisible] = useState<boolean>(false); const [isVisible, setIsVisible] = useState<boolean>(false);
return ( return (
<LinearGradient <LinearGradient
colors={["#f9f8f700", "#f9f8f7", "#f9f8f700"]} colors={["#f9f8f700", "#f9f8f7", "#f9f8f700"]}
locations={[0, 0.5, 1]} locations={[0, 0.5, 1]}
style={styles.gradient} style={styles.gradient}
>
<View style={styles.buttonContainer}>
<Button
marginH-25
size={ButtonSize.large}
style={styles.button}
onPress={() => setIsVisible(!isVisible)}
> >
<View style={styles.buttonContainer}> <AntDesign name="plus" size={24} color="white" />
<Button <Text
marginH-25 white
size={ButtonSize.large} style={{ fontFamily: "Manrope_600SemiBold", fontSize: 15 }}
style={styles.button} marginL-10
onPress={() => setIsVisible(!isVisible)} >
> Create new to do
<AntDesign name="plus" size={24} color="white"/> </Text>
<Text white text60R marginL-10> </Button>
Create new to do </View>
</Text> {isVisible && <AddChoreDialog isVisible={isVisible} setIsVisible={setIsVisible} />}
</Button> </LinearGradient>
</View> );
<AddChoreDialog isVisible={isVisible} setIsVisible={setIsVisible}/>
</LinearGradient>
);
}; };
export default AddChore; export default AddChore;
const styles = StyleSheet.create({ const styles = StyleSheet.create({
gradient: { gradient: {
height: 150, height: 150,
position: "absolute", position: "absolute",
bottom: 0, bottom: 0,
width: "100%", width: "100%",
justifyContent: "center", justifyContent: "center",
alignItems: "center", alignItems: "center",
}, },
buttonContainer: { buttonContainer: {
width: "100%", width: "100%",
alignItems: "center", alignItems: "center",
}, },
button: { button: {
backgroundColor: "rgb(253, 23, 117)", backgroundColor: "rgb(253, 23, 117)",
paddingVertical: 15, paddingVertical: 15,
paddingHorizontal: 30, paddingHorizontal: 30,
borderRadius: 30, borderRadius: 30,
}, width: 335,
},
}); });

View File

@ -1,4 +1,4 @@
import {View, Text, Button, Switch, PickerModes} from "react-native-ui-lib"; import { View, Text, Button, Switch, PickerModes } from "react-native-ui-lib";
import React, { useRef, useState } from "react"; import React, { useRef, useState } from "react";
import PointsSlider from "@/components/shared/PointsSlider"; import PointsSlider from "@/components/shared/PointsSlider";
import { repeatOptions, useToDosContext } from "@/contexts/ToDosContext"; import { repeatOptions, useToDosContext } from "@/contexts/ToDosContext";
@ -15,7 +15,12 @@ import { Dimensions, StyleSheet } from "react-native";
import DropModalIcon from "@/assets/svgs/DropModalIcon"; import DropModalIcon from "@/assets/svgs/DropModalIcon";
import { IToDo } from "@/hooks/firebase/types/todoData"; import { IToDo } from "@/hooks/firebase/types/todoData";
import AssigneesDisplay from "@/components/shared/AssigneesDisplay"; import AssigneesDisplay from "@/components/shared/AssigneesDisplay";
import {useGetFamilyMembers} from "@/hooks/firebase/useGetFamilyMembers"; import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import CalendarIcon from "@/assets/svgs/CalendarIcon";
import ClockIcon from "@/assets/svgs/ClockIcon";
import ClockOIcon from "@/assets/svgs/ClockOIcon";
import ProfileIcon from "@/assets/svgs/ProfileIcon";
import RepeatFreq from "./RepeatFreq";
interface IAddChoreDialog { interface IAddChoreDialog {
isVisible: boolean; isVisible: boolean;
@ -30,7 +35,8 @@ const defaultTodo = {
date: new Date(), date: new Date(),
rotate: false, rotate: false,
repeatType: "Every week", repeatType: "Every week",
assignees: [] assignees: [],
repeatDays: []
}; };
const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => { const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
@ -38,11 +44,13 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
const [todo, setTodo] = useState<IToDo>( const [todo, setTodo] = useState<IToDo>(
addChoreDialogProps.selectedTodo ?? defaultTodo addChoreDialogProps.selectedTodo ?? defaultTodo
); );
const [selectedAssignees, setSelectedAssignees] = useState<string[]>(addChoreDialogProps?.selectedTodo?.assignees ?? []); const [selectedAssignees, setSelectedAssignees] = useState<string[]>(
addChoreDialogProps?.selectedTodo?.assignees ?? []
);
const { width, height } = Dimensions.get("screen"); const { width, height } = Dimensions.get("screen");
const [points, setPoints] = useState<number>(todo.points); const [points, setPoints] = useState<number>(todo.points);
const {data: members} = useGetFamilyMembers(); const { data: members } = useGetFamilyMembers();
const handleClose = () => { const handleClose = () => {
setTodo(defaultTodo); setTodo(defaultTodo);
@ -60,6 +68,25 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
} }
}; };
const handleRepeatDaysChange = (day: string, set: boolean) => {
if (set) {
const updatedTodo = {
...todo,
repeatDays: [...todo.repeatDays, day]
}
setTodo(updatedTodo);
} else {
const array = todo.repeatDays ?? [];
let index = array.indexOf(day);
array.splice(index, 1);
const updatedTodo = {
...todo,
repeatDays: array
}
setTodo(updatedTodo);
}
}
return ( return (
<Dialog <Dialog
bottom={true} bottom={true}
@ -100,13 +127,18 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
onPress={() => { onPress={() => {
try { try {
if (addChoreDialogProps.selectedTodo) { if (addChoreDialogProps.selectedTodo) {
updateToDo({ ...todo, points: points, assignees: selectedAssignees }); updateToDo({
...todo,
points: points,
assignees: selectedAssignees
});
} else { } else {
addToDo({ addToDo({
...todo, ...todo,
done: false, done: false,
points: points, points: points,
assignees: selectedAssignees assignees: selectedAssignees,
repeatDays: todo.repeatDays ?? []
}); });
} }
handleClose(); handleClose();
@ -133,11 +165,15 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
<View row marginB-10> <View row marginB-10>
{todo?.date && ( {todo?.date && (
<View row centerV> <View row centerV>
<Feather name="calendar" size={25} color="#919191" /> <CalendarIcon color="#919191" width={24} height={24} />
<DateTimePicker <DateTimePicker
value={todo.date} value={todo.date}
text70 text70
marginL-8 style={{
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
marginL-12
onChange={(date) => { onChange={(date) => {
setTodo((oldValue: IToDo) => ({ ...oldValue, date: date })); setTodo((oldValue: IToDo) => ({ ...oldValue, date: date }));
}} }}
@ -146,9 +182,9 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
)} )}
</View> </View>
<View row centerV> <View row centerV>
<AntDesign name="clockcircleo" size={24} color="#919191" /> <ClockOIcon />
<Picker <Picker
marginL-8 marginL-12
placeholder="Select Repeat Type" placeholder="Select Repeat Type"
value={todo?.repeatType} value={todo?.repeatType}
onChange={(value) => { onChange={(value) => {
@ -169,7 +205,11 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
} }
}} }}
topBarProps={{ title: "Repeat" }} topBarProps={{ title: "Repeat" }}
style={{ marginVertical: 5 }} style={{
marginVertical: 5,
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
> >
{repeatOptions.map((option) => ( {repeatOptions.map((option) => (
<Picker.Item <Picker.Item
@ -180,60 +220,67 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
))} ))}
</Picker> </Picker>
</View> </View>
{todo.repeatType == "Every week" && <RepeatFreq handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={todo.repeatDays ?? []}/>}
</View> </View>
<View style={styles.divider} /> <View style={styles.divider} />
<View marginH-30 marginB-10 row centerV> <View marginH-30 marginB-10 row centerV>
<Ionicons name="person-circle-outline" size={28} color="#919191" /> <ProfileIcon color="#919191" />
<Text text70R marginL-10> <Text style={styles.sub} marginL-10>
Assignees Assignees
</Text> </Text>
<View flex-1/> <View flex-1 />
<Picker <Picker
marginL-8 marginL-8
value={selectedAssignees} value={selectedAssignees}
onChange={(value) => { onChange={(value) => {
setSelectedAssignees([...selectedAssignees, ...value]); setSelectedAssignees([...selectedAssignees, ...value]);
}} }}
style={{ marginVertical: 5 }} style={{ marginVertical: 5 }}
mode={PickerModes.MULTI} mode={PickerModes.MULTI}
renderInput={() => renderInput={() => (
<Button <Button
size={ButtonSize.small} size={ButtonSize.small}
paddingH-8 paddingH-8
iconSource={() => ( iconSource={() => (
<Ionicons name="add-outline" size={20} color="#ea156c"/> <Ionicons name="add-outline" size={20} color="#ea156c" />
)} )}
style={{ style={{
marginLeft: "auto", marginLeft: "auto",
borderRadius: 8, borderRadius: 8,
backgroundColor: "#ffe8f1", backgroundColor: "#ffe8f1",
borderColor: "#ea156c", borderColor: "#ea156c",
borderWidth: 1, borderWidth: 1,
}} }}
color="#ea156c" color="#ea156c"
label="Assign" label="Assign"
labelStyle={{fontFamily: "Manrope_600SemiBold", fontSize: 14}} labelStyle={{ fontFamily: "Manrope_600SemiBold", fontSize: 14 }}
/> />
} )}
> >
{members?.map((member) => ( {members?.map((member) => (
<Picker.Item <Picker.Item
key={member.uid} key={member.uid}
label={member?.firstName + " " + member?.lastName} label={member?.firstName + " " + member?.lastName}
value={member?.uid!} value={member?.uid!}
/> />
))} ))}
</Picker> </Picker>
</View> </View>
<View row marginL-27 marginT-0> <View row marginL-27 marginT-0>
<AssigneesDisplay selectedAttendees={selectedAssignees} setSelectedAttendees={setSelectedAssignees}/> <AssigneesDisplay
selectedAttendees={selectedAssignees}
setSelectedAttendees={setSelectedAssignees}
/>
</View> </View>
<View row centerV style={styles.rotateSwitch}> <View row centerV style={styles.rotateSwitch}>
<Text text80>Take Turns</Text> <Text style={{ fontFamily: "PlusJakartaSans_500Medium", fontSize: 16 }}>
Take Turns
</Text>
<Switch <Switch
onColor={"#ea156c"} onColor={"#ea156c"}
value={todo.rotate} value={todo.rotate}
style={{ width: 43.06, height: 27.13 }}
marginL-10 marginL-10
onValueChange={(value) => onValueChange={(value) =>
setTodo((oldValue) => ({ ...oldValue, rotate: value })) setTodo((oldValue) => ({ ...oldValue, rotate: value }))
@ -243,7 +290,7 @@ const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
<View style={styles.divider} /> <View style={styles.divider} />
<View marginH-30 marginB-15 row centerV> <View marginH-30 marginB-15 row centerV>
<Ionicons name="gift-outline" size={25} color="#919191" /> <Ionicons name="gift-outline" size={25} color="#919191" />
<Text text70BL marginL-10> <Text style={styles.sub} marginL-10>
Reward Points Reward Points
</Text> </Text>
</View> </View>
@ -284,4 +331,8 @@ const styles = StyleSheet.create({
marginBottom: 10, marginBottom: 10,
marginTop: 25, marginTop: 25,
}, },
sub: {
fontFamily: "Manrope_600SemiBold",
fontSize: 18,
},
}); });

View File

@ -0,0 +1,59 @@
import { View, Text, TouchableOpacity, Picker } from "react-native-ui-lib";
import React, { useEffect, useState } from "react";
import {DAYS_OF_WEEK_ENUM} from "@/hooks/firebase/types/todoData";
const RepeatFreq = ({ repeatDays, handleRepeatDaysChange }: { repeatDays: string[], handleRepeatDaysChange: Function }) => {
const [weeks, setWeeks] = useState<number>(1);
const weekOptions: number[] = Array.from({ length: 52 }, (_, i) => i + 1);
useEffect(() => {}, [weeks]);
return (
<View row centerV spread marginR-30>
<RepeatOption value={DAYS_OF_WEEK_ENUM.MONDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.TUESDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.WEDNESDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.THURSDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.FRIDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.SATURDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
<RepeatOption value={DAYS_OF_WEEK_ENUM.SUNDAY} handleRepeatDaysChange={handleRepeatDaysChange} repeatDays={repeatDays}/>
</View>
);
};
export default RepeatFreq;
const RepeatOption = ({ value, handleRepeatDaysChange, repeatDays }: { value: string, handleRepeatDaysChange: Function, repeatDays: string[] }) => {
const [isSet, setisSet] = useState(repeatDays.includes(value));
const handleDayChange = () => {
handleRepeatDaysChange(value, !isSet)
setisSet(!isSet);
}
return (
<TouchableOpacity onPress={handleDayChange}>
<View
center
marginT-8
marginB-4
width={28}
height={28}
style={{
backgroundColor: isSet ? "#fd1575" : "white",
borderRadius: 100,
}}
>
<Text
style={{
fontFamily: !isSet ? "Manrope_400Regular" : "Manrope_700Bold",
color: isSet ? "white" : "gray",
}}
>
{value.at(0)}
</Text>
</View>
</TouchableOpacity>
);
};

View File

@ -1,11 +1,11 @@
import { import {
View, View,
Text, Text,
Checkbox, Checkbox,
TouchableOpacity, TouchableOpacity,
Dialog, Dialog,
Button, Button,
ButtonSize ButtonSize,
} from "react-native-ui-lib"; } from "react-native-ui-lib";
import React, { useState } from "react"; import React, { useState } from "react";
import { useToDosContext } from "@/contexts/ToDosContext"; import { useToDosContext } from "@/contexts/ToDosContext";
@ -15,10 +15,15 @@ import { IToDo } from "@/hooks/firebase/types/todoData";
import { ImageBackground } from "react-native"; import { ImageBackground } from "react-native";
import AddChoreDialog from "@/components/pages/todos/AddChoreDialog"; import AddChoreDialog from "@/components/pages/todos/AddChoreDialog";
import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers"; import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import RepeatIcon from "@/assets/svgs/RepeatIcon";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => { const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
const { updateToDo } = useToDosContext(); const { updateToDo } = useToDosContext();
const {data: members} = useGetFamilyMembers(); const { data: members } = useGetFamilyMembers();
const { profileData } = useAuthContext();
const isParent = profileData?.userType === ProfileType.PARENT;
const [visible, setVisible] = useState<boolean>(false); const [visible, setVisible] = useState<boolean>(false);
const [points, setPoints] = useState(props.item.points); const [points, setPoints] = useState(props.item.points);
const [pointsModalVisible, setPointsModalVisible] = useState<boolean>(false); const [pointsModalVisible, setPointsModalVisible] = useState<boolean>(false);
@ -33,11 +38,21 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
} }
}; };
const getInitials = (firstName: string, lastName: string) => { const getInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`; return `${firstName.charAt(0)}${lastName.charAt(0)}`;
}; };
const selectedMembers = members?.filter((x) =>
props?.item?.assignees?.includes(x?.uid!)
);
let isTodoEditable;
if (isParent) {
isTodoEditable = true
} else {
isTodoEditable = props.item.creatorId === profileData?.uid;
}
const selectedMembers = members?.filter((x) => props?.item?.assignees?.includes(x?.uid!));
return ( return (
<View <View
centerV centerV
@ -50,24 +65,36 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
opacity: props.item.done ? 0.3 : 1, opacity: props.item.done ? 0.3 : 1,
}} }}
> >
{visible && <AddChoreDialog isVisible={visible} setIsVisible={setVisible} selectedTodo={props.item}/>} {visible && (
<AddChoreDialog
isVisible={visible}
setIsVisible={setVisible}
selectedTodo={props.item}
/>
)}
<View paddingB-8 row spread> <View paddingB-8 row spread>
<Text <Text
text70 text70
style={{ style={{
textDecorationLine: props.item.done ? "line-through" : "none", textDecorationLine: props.item.done ? "line-through" : "none",
fontFamily: "Manrope_500Medium", fontFamily: "Manrope_500Medium",
fontSize: 15, fontSize: 15,
}} }}
onPress={() => { onPress={() => {
setVisible(true); isTodoEditable ? setVisible(true) : null
}} }}
> >
{props.item.title} {props.item.title}
</Text> </Text>
<Checkbox <Checkbox
value={props.item.done} value={props.item.done}
containerStyle={{borderWidth: 0.7, borderRadius: 50, borderColor: 'gray', height: 24.64, width: 24.64}} containerStyle={{
borderWidth: 0.7,
borderRadius: 50,
borderColor: "gray",
height: 24.64,
width: 24.64,
}}
color="#fd1575" color="#fd1575"
onValueChange={(value) => { onValueChange={(value) => {
updateToDo({ id: props.item.id, done: !props.item.done }); updateToDo({ id: props.item.id, done: !props.item.done });
@ -86,62 +113,99 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
/> />
</View> </View>
<View centerV centerH marginT-8 row spread> <View centerV centerH marginT-8 row spread>
{props.item.points && props.item.points > 0 ? ( <View row>
<TouchableOpacity {props.item.points && props.item.points > 0 ? (
onPress={() => { <TouchableOpacity
if (props.isSettings) { onPress={() => {
setPointsModalVisible(true); if (props.isSettings) {
} setPointsModalVisible(true);
}} }
> }}
<View centerV row gap-3> >
<Ionicons name="gift-outline" size={20} color="#46a80a" /> <View centerV row gap-3>
<Text color="#46a80a" style={{ fontSize: 12, fontFamily: "Manrope_500Medium" }}> <Ionicons name="gift-outline" size={20} color="#46a80a" />
{props.item.points} points <Text
color="#46a80a"
style={{ fontSize: 12, fontFamily: "Manrope_500Medium" }}
>
{props.item.points} points
</Text>
</View>
</TouchableOpacity>
) : (
<View />
)}
{!(props.item.repeatType == "None") && (
<View row centerV marginL-8>
<RepeatIcon style={{ marginRight: 4 }} />
<Text
style={{
fontSize: 12,
fontFamily: "Manrope_500Medium",
color: "#858585",
}}
>
{(() => {
switch (props.item.repeatType) {
case "Once a month":
return "Monthly";
case "Every week":
return "Weekly";
case "Once a year":
return "Yearly";
default:
return props.item.repeatType;
}
})()}
</Text> </Text>
</View> </View>
</TouchableOpacity> )}
) : ( </View>
<View /> <View row style={{ gap: 3 }}>
)} {selectedMembers?.map((member) => {
<View row style={{ gap: 3 }}> return member?.pfp ? (
{selectedMembers?.map((member) => { <ImageBackground
return member?.pfp ? ( source={{ uri: member.pfp }}
<ImageBackground style={{
source={require("../../../assets/images/child-picture.png")} height: 24.64,
style={{ aspectRatio: 1,
height: 24.64, borderRadius: 22,
aspectRatio: 1, overflow: "hidden",
borderRadius: 22, }}
overflow: "hidden", />
}} ) : (
/> <View
) : ( style={{
<View style={{ position: "relative",
position: 'relative', width: 24.64,
width: 24.64, aspectRatio: 1,
aspectRatio: 1 }}
}}> >
<View style={{ <View
backgroundColor: '#ccc', style={{
justifyContent: 'center', backgroundColor: "#ccc",
alignItems: 'center', justifyContent: "center",
borderRadius: 100, // Circular shape alignItems: "center",
width: '100%', borderRadius: 100, // Circular shape
height: '100%' width: "100%",
}}> height: "100%",
<Text style={{ }}
color: '#fff', >
fontSize: 12, <Text
fontWeight: 'bold' style={{
}}> color: "#fff",
{getInitials(member.firstName, member.lastName ?? "")} fontSize: 12,
</Text> fontWeight: "bold",
</View> }}
</View> >
)} {getInitials(member.firstName, member.lastName ?? "")}
)} </Text>
</View> </View>
</View>
);
})}
</View>
</View> </View>
<Dialog <Dialog
visible={pointsModalVisible} visible={pointsModalVisible}

View File

@ -2,7 +2,13 @@ import { View, Text, TouchableOpacity, Icon } from "react-native-ui-lib";
import React, { useState } from "react"; import React, { useState } from "react";
import { useToDosContext } from "@/contexts/ToDosContext"; import { useToDosContext } from "@/contexts/ToDosContext";
import ToDoItem from "./ToDoItem"; import ToDoItem from "./ToDoItem";
import { format, isToday, isTomorrow } from "date-fns"; import {
addDays,
format,
isToday,
isTomorrow,
isWithinInterval,
} from "date-fns";
import { AntDesign } from "@expo/vector-icons"; import { AntDesign } from "@expo/vector-icons";
import { IToDo } from "@/hooks/firebase/types/todoData"; import { IToDo } from "@/hooks/firebase/types/todoData";
@ -11,12 +17,26 @@ const groupToDosByDate = (toDos: IToDo[]) => {
return sortedTodos.reduce((groups, toDo) => { return sortedTodos.reduce((groups, toDo) => {
let dateKey; let dateKey;
const isNext7Days = (date: Date) => {
const today = new Date();
return isWithinInterval(date, { start: today, end: addDays(today, 7) });
};
const isNext30Days = (date: Date) => {
const today = new Date();
return isWithinInterval(date, { start: today, end: addDays(today, 30) });
};
if (toDo.date === null) { if (toDo.date === null) {
dateKey = "No Date"; dateKey = "No Date";
} else if (isToday(toDo.date)) { } else if (isToday(toDo.date)) {
dateKey = "Today • " + format(toDo.date, "EEE MMM dd"); dateKey = "Today";
} else if (isTomorrow(toDo.date)) { } else if (isTomorrow(toDo.date)) {
dateKey = "Tomorrow • " + format(toDo.date, "EEE MMM dd"); dateKey = "Tomorrow";
} else if (isNext7Days(toDo.date)) {
dateKey = "Next 7 Days";
} else if (isNext30Days(toDo.date)) {
dateKey = "Next 30 Days";
} else { } else {
dateKey = format(toDo.date, "EEE MMM dd"); dateKey = format(toDo.date, "EEE MMM dd");
} }
@ -110,12 +130,12 @@ const ToDosList = ({ isSettings }: { isSettings?: boolean }) => {
flexDirection: "row", flexDirection: "row",
justifyContent: "space-between", justifyContent: "space-between",
alignItems: "center", alignItems: "center",
paddingHorizontal: 20, paddingHorizontal: 0,
marginVertical: 8, marginBottom: 4,
marginTop: 15,
}} }}
> >
<Text <Text
text70
style={{ style={{
fontFamily: "Manrope_700Bold", fontFamily: "Manrope_700Bold",
fontSize: 15, fontSize: 15,

View File

@ -1,43 +1,70 @@
import {Image, Text, View} from "react-native-ui-lib"; import { Image, Text, View } from "react-native-ui-lib";
import React from "react"; import React from "react";
import {useAuthContext} from "@/contexts/AuthContext"; import { useAuthContext } from "@/contexts/AuthContext";
import { StyleSheet } from "react-native";
import { colorMap } from "@/constants/colorMap";
const HeaderTemplate = (props: { const HeaderTemplate = (props: {
message: string; message: string;
isWelcome: boolean; isWelcome: boolean;
children?: React.ReactNode; children?: React.ReactNode;
link?: React.ReactNode; link?: React.ReactNode;
}) => { }) => {
const {user, profileData} = useAuthContext(); const { user, profileData } = useAuthContext();
const headerHeight: number = 72; const headerHeight: number = 72;
return (
<View row centerV marginV-15> const styles = StyleSheet.create({
<Image pfp: {
source={{uri: profileData?.pfp}} height: headerHeight,
style={{ aspectRatio: 1,
height: headerHeight, borderRadius: 22,
aspectRatio: 1, overflow: "hidden",
borderRadius: 22, marginRight: 20,
overflow: "hidden", backgroundColor: profileData?.eventColor ?? colorMap.pink,
marginRight: 20, },
}} pfpTxt: {
/> fontFamily: "Manrope_500Medium",
<View gap-3> fontSize: 30,
{props.isWelcome && ( color: 'white',
<Text text70L style={{ },
fontSize: 19, });
fontFamily: "Manrope_400Regular"
}}>Welcome, {profileData?.firstName}!</Text> return (
)} <View row centerV marginV-15>
<Text text70B style={{fontSize: 18, fontFamily: "Manrope_600SemiBold"}}> {profileData?.pfp ? (
{props.message} <Image source={{ uri: profileData.pfp }} style={styles.pfp} />
</Text> ) : (
{props.children && <View>{props.children}</View>} <View style={styles.pfp} center>
{props.link && <View marginT-8>{props.link}</View>} <Text style={styles.pfpTxt}>
</View> {user?.email?.at(0)}
{user?.email?.at(1)}
</Text>
</View> </View>
); )}
<View gap-3>
{props.isWelcome && (
<Text
text70L
style={{
fontSize: 19,
fontFamily: "Manrope_400Regular",
}}
>
Welcome, {profileData?.firstName}!
</Text>
)}
<Text
text70B
style={{ fontSize: 18, fontFamily: "Manrope_600SemiBold" }}
>
{props.message}
</Text>
{props.children && <View>{props.children}</View>}
{props.link && <View marginT-8>{props.link}</View>}
</View>
</View>
);
}; };
export default HeaderTemplate; export default HeaderTemplate;

View File

@ -1,8 +1,6 @@
import { createContext, FC, ReactNode, useContext, useState } from "react"; import { createContext, FC, ReactNode, useContext, useState } from "react";
import {IToDo} from "@/hooks/firebase/types/todoData"; import {IToDo} from "@/hooks/firebase/types/todoData";
import {useGetGroceries} from "@/hooks/firebase/useGetGroceries";
import {useGetTodos} from "@/hooks/firebase/useGetTodos"; import {useGetTodos} from "@/hooks/firebase/useGetTodos";
import {useCreateGrocery} from "@/hooks/firebase/useCreateGrocery";
import {useCreateTodo} from "@/hooks/firebase/useCreateTodo"; import {useCreateTodo} from "@/hooks/firebase/useCreateTodo";
import {useUpdateTodo} from "@/hooks/firebase/useUpdateTodo"; import {useUpdateTodo} from "@/hooks/firebase/useUpdateTodo";

View File

@ -1,12 +1,32 @@
export interface IToDo { export interface IToDo {
id: string; id: string;
title: string; title: string;
done: boolean; done: boolean;
date: Date | null; date: Date | null;
points: number; points: number;
rotate: boolean; rotate: boolean;
repeatType: string; repeatType: string;
creatorId?: string, repeatDays?: string[];
familyId?: string, repeatWeeks?: number;
assignees?: string[]; // Optional list of assignees creatorId?: string;
familyId?: string;
assignees?: string[]; // Optional list of assignees
connectedTodoId?: string;
}
export const DAYS_OF_WEEK_ENUM = {
MONDAY: "Monday",
TUESDAY: "Tuesday",
WEDNESDAY: "Wednesday",
THURSDAY: "Thursday",
FRIDAY: "Friday",
SATURDAY: "Saturday",
SUNDAY: "Sunday"
}
export const REPEAT_TYPE = {
NONE: "None",
EVERY_WEEK: "Every week",
ONCE_A_MONTH: "Once a month",
ONCE_A_YEAR: "Once a year"
} }

View File

@ -30,9 +30,10 @@ export const useCreateEvent = () => {
return; return;
} }
} }
const newDoc = firestore().collection('Events').doc();
await firestore() await firestore()
.collection("Events") .collection("Events")
.add({...eventData, creatorId: currentUser?.uid, familyId: profileData?.familyId}); .add({...eventData, id: newDoc.id, creatorId: currentUser?.uid, familyId: profileData?.familyId});
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }

View File

@ -1,7 +1,17 @@
import { useMutation, useQueryClient } from "react-query"; import {useMutation, useQueryClient} from "react-query";
import firestore from "@react-native-firebase/firestore"; import firestore from "@react-native-firebase/firestore";
import { useAuthContext } from "@/contexts/AuthContext"; import {useAuthContext} from "@/contexts/AuthContext";
import { IToDo } from "@/hooks/firebase/types/todoData"; import {DAYS_OF_WEEK_ENUM, IToDo, REPEAT_TYPE} from "@/hooks/firebase/types/todoData";
import {addDays, addMonths, addWeeks, addYears, compareAsc, format, subDays} from "date-fns";
export const daysOfWeek = [
DAYS_OF_WEEK_ENUM.MONDAY,
DAYS_OF_WEEK_ENUM.TUESDAY,
DAYS_OF_WEEK_ENUM.WEDNESDAY,
DAYS_OF_WEEK_ENUM.THURSDAY,
DAYS_OF_WEEK_ENUM.FRIDAY,
DAYS_OF_WEEK_ENUM.SATURDAY,
DAYS_OF_WEEK_ENUM.SUNDAY];
export const useCreateTodo = () => { export const useCreateTodo = () => {
const { user: currentUser, profileData } = useAuthContext(); const { user: currentUser, profileData } = useAuthContext();
@ -11,10 +21,81 @@ export const useCreateTodo = () => {
mutationKey: ["createTodo"], mutationKey: ["createTodo"],
mutationFn: async (todoData: Partial<IToDo>) => { mutationFn: async (todoData: Partial<IToDo>) => {
try { try {
const newDoc = firestore().collection('Todos').doc(); if (todoData.repeatType === REPEAT_TYPE.NONE) {
await firestore() const newDoc = firestore().collection('Todos').doc();
.collection("Todos") let originalTodo = {...todoData, id: newDoc.id, familyId: profileData?.familyId, creatorId: currentUser?.uid}
.add({...todoData, id: newDoc.id, familyId: profileData?.familyId, creatorId: currentUser?.uid}) await firestore()
.collection("Todos")
.add(originalTodo);
} else {
// Create the one original to do
const newDoc = firestore().collection('Todos').doc();
let originalTodo = {...todoData, id: newDoc.id, familyId: profileData?.familyId, creatorId: currentUser?.uid, connectedTodoId: newDoc.id};
await firestore()
.collection("Todos")
.add(originalTodo);
const batch = firestore().batch();
if (todoData.repeatType === REPEAT_TYPE.EVERY_WEEK) {
let date = originalTodo.date;
let repeatDays = originalTodo.repeatDays;
const dates = [];
const originalDateDay = format(date, 'EEEE');
const originalNumber = daysOfWeek.indexOf(originalDateDay);
repeatDays?.forEach((day) => {
let number = daysOfWeek.indexOf(day);
let newDate;
if (originalNumber > number) {
let diff = originalNumber - number;
newDate = subDays(date, diff);
} else {
let diff = number - originalNumber;
newDate = addDays(date, diff);
}
dates.push(newDate);
});
// TODO: for the next 52 weeks
for (let i = 0; i < 4; i++) {
dates?.forEach((dateToAdd) => {
let newTodoDate = addWeeks(dateToAdd, i);
if (compareAsc(newTodoDate, originalTodo.date) !== 0) {
let docRef = firestore().collection("Todos").doc();
const newTodo = { ...originalTodo, id: docRef.id, date: newTodoDate, connectedTodoId: newDoc.id };
batch.set(docRef, newTodo);
}
})
}
} else if (todoData.repeatType === REPEAT_TYPE.ONCE_A_MONTH) {
// for the next 12 months
for (let i = 1; i < 12; i++) {
let date = originalTodo.date;
const nextMonth = addMonths(date, i);
let docRef = firestore().collection("Todos").doc();
const newTodo = { ...originalTodo, id: docRef.id, date: nextMonth, connectedTodoId: newDoc.id };
batch.set(docRef, newTodo);
}
} else if (todoData.repeatType === REPEAT_TYPE.ONCE_A_YEAR) {
// for the next 5 years
for (let i = 1; i < 5; i++) {
let date = originalTodo.date;
const nextMonth = addYears(date, i);
let docRef = firestore().collection("Todos").doc();
const newTodo = { ...originalTodo, id: docRef.id, date: nextMonth, connectedTodoId: newDoc.id };
batch.set(docRef, newTodo);
}
}
await batch.commit();
}
} catch (e) { } catch (e) {
console.error(e) console.error(e)
} }

View File

@ -1,7 +1,6 @@
import { useQuery } from "react-query"; import { useQuery } from "react-query";
import firestore from "@react-native-firebase/firestore"; import firestore from "@react-native-firebase/firestore";
import { useAuthContext } from "@/contexts/AuthContext"; import { useAuthContext } from "@/contexts/AuthContext";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";
import {IToDo} from "@/hooks/firebase/types/todoData"; import {IToDo} from "@/hooks/firebase/types/todoData";
export const useGetTodos = () => { export const useGetTodos = () => {
@ -23,6 +22,7 @@ export const useGetTodos = () => {
...data, ...data,
id: doc.id, id: doc.id,
date: data.date ? new Date(data.date.seconds * 1000) : null, date: data.date ? new Date(data.date.seconds * 1000) : null,
repeatDays: data.repeatDays ?? []
}; };
}) as IToDo[]; }) as IToDo[];
} }

View File

@ -1,18 +1,145 @@
import { useMutation, useQueryClient } from "react-query"; import { useMutation, useQueryClient } from "react-query";
import firestore from "@react-native-firebase/firestore"; import firestore from "@react-native-firebase/firestore";
import { IToDo } from "@/hooks/firebase/types/todoData"; import {IToDo, REPEAT_TYPE} from "@/hooks/firebase/types/todoData";
import {addDays, addMonths, addWeeks, addYears, compareAsc, format, subDays} from "date-fns";
import {daysOfWeek} from "@/hooks/firebase/useCreateTodo";
import {useAuthContext} from "@/contexts/AuthContext";
export const useUpdateTodo = () => { export const useUpdateTodo = () => {
const { user: currentUser, profileData } = useAuthContext();
const queryClients = useQueryClient() const queryClients = useQueryClient()
return useMutation({ return useMutation({
mutationKey: ["updateTodo"], mutationKey: ["updateTodo"],
mutationFn: async (todoData: Partial<IToDo>) => { mutationFn: async (todoData: Partial<IToDo>) => {
try { try {
await firestore() if (todoData.connectedTodoId) {
.collection("Todos") console.log("CONNECTED")
.doc(todoData.id) const snapshot = await firestore()
.update(todoData); .collection("Todos")
.where("connectedTodoId", "==", todoData.connectedTodoId)
.get();
const connectedTodos = snapshot.docs.map((doc) => {
const data = doc.data();
return {
...data,
id: doc.id,
date: data.date ? new Date(data.date.seconds * 1000) : null,
ref: doc.ref
};
}) as IToDo[];
console.log("CONNECTED TODO");
let filteredTodos = connectedTodos?.filter((item) => compareAsc(format(item.date, 'yyyy-MM-dd'), format(todoData.date, 'yyyy-MM-dd')) === 1 ||
compareAsc(format(item.date, 'yyyy-MM-dd'), format(todoData.date, 'yyyy-MM-dd')) === 0).sort((a,b) =>{
return b.date?.getSeconds() - a.date?.getSeconds();
});
let firstTodo = filteredTodos?.[0];
const batch = firestore().batch();
if (compareAsc(format(firstTodo?.date, 'yyyy-MM-dd'), format(todoData.date, 'yyyy-MM-dd')) !== 0 || firstTodo?.repeatType !== todoData.repeatType) {
console.log("DELETE");
filteredTodos?.forEach((item) => {
batch.delete(item.ref);
});
if (todoData.repeatType === REPEAT_TYPE.NONE) {
console.log("NONE");
const newDoc = firestore().collection('Todos').doc();
let originalTodo = {...todoData, id: newDoc.id, familyId: profileData?.familyId, creatorId: currentUser?.uid}
batch.set(newDoc, originalTodo);
} else if (todoData.repeatType === REPEAT_TYPE.EVERY_WEEK) {
console.log("EVERY WEEK");
let date = todoData?.date;
let repeatDays = todoData?.repeatDays;
const dates = [];
const originalDateDay = format(date, 'EEEE');
const originalNumber = daysOfWeek.indexOf(originalDateDay);
repeatDays?.forEach((day) => {
let number = daysOfWeek.indexOf(day);
let newDate;
if (originalNumber > number) {
let diff = originalNumber - number;
newDate = subDays(date, diff);
} else {
let diff = number - originalNumber;
newDate = addDays(date, diff);
}
dates.push(newDate);
});
let todosToAddCycles = 4;
if (firstTodo?.repeatType === REPEAT_TYPE.EVERY_WEEK) {
todosToAddCycles = filteredTodos?.length / firstTodo?.repeatDays?.length;
}
console.log(todosToAddCycles);
let newDoc = firestore().collection("Todos").doc();
const newTodo = { ...todoData, id: newDoc.id, date: todoData.date, connectedTodoId: newDoc?.id };
batch.set(newDoc, newTodo);
console.log(dates);
for (let i = 0; i < todosToAddCycles; i++) {
dates?.forEach((dateToAdd) => {
let newTodoDate = addWeeks(dateToAdd, i);
console.log("ENTER")
let docRef = firestore().collection("Todos").doc();
const newTodo = { ...todoData, id: docRef.id, date: newTodoDate, connectedTodoId: newDoc?.id };
batch.set(docRef, newTodo);
})
}
} else if (todoData.repeatType === REPEAT_TYPE.ONCE_A_MONTH) {
console.log("ONCE A MONTH");
// for the next 12 months
for (let i = 0; i < 12; i++) {
let date = todoData?.date;
const nextMonth = addMonths(date, i);
const newTodo = { ...todoData, date: nextMonth, connectedTodoId: firstTodo?.connectedTodoId };
let docRef = firestore().collection("Todos").doc();
batch.set(docRef, newTodo);
}
} else if (todoData.repeatType === REPEAT_TYPE.ONCE_A_YEAR) {
console.log("ONCE A YEAR");
// for the next 5 years
for (let i = 0; i < 5; i++) {
let date = todoData?.date;
const nextMonth = addYears(date, i);
const newTodo = { ...todoData, date: nextMonth, connectedTodoId: firstTodo?.connectedTodoId };
let docRef = firestore().collection("Todos").doc();
batch.set(docRef, newTodo);
}
}
await batch.commit();
} else if (firstTodo?.repeatDays !== todoData.repeatDays) {
console.log("UPDATE REPEAT DAYS");
await updateRepeatDaysTodos(batch, todoData, firstTodo, filteredTodos)
} else {
filteredTodos?.forEach((item) => {
console.log("UPDATE");
batch.update(item.ref, {...todoData, date: item.date});
})
await batch.commit();
}
} else {
console.log("REGULAR UPDATE");
console.log(todoData);
await firestore()
.collection("Todos")
.doc(todoData.id)
.update(todoData);
}
} catch (e) { } catch (e) {
console.error(e) console.error(e)
} }
@ -22,3 +149,58 @@ export const useUpdateTodo = () => {
} }
}) })
} }
const updateRepeatDaysTodos = async (batch: any, todoData: IToDo, firstTodo: IToDo, filteredTodos: IToDo[]) => {
const todosToAddCycles = filteredTodos?.length / firstTodo?.repeatDays?.length;
console.log(todosToAddCycles);
filteredTodos?.forEach((item) => {
batch.update(item.ref, {...todoData, date: item.date});
})
let newRepeatDays = todoData.repeatDays?.filter((element) => firstTodo?.repeatDays?.indexOf(element) === -1);
let removeRepeatDays = firstTodo?.repeatDays?.filter((element) => todoData?.repeatDays?.indexOf(element) === -1);
const dates = [];
let date = firstTodo?.date;
const originalDateDay = format(date, 'EEEE');
const originalNumber = daysOfWeek.indexOf(originalDateDay);
newRepeatDays?.forEach((day) => {
let number = daysOfWeek.indexOf(day);
let newDate;
if (originalNumber > number) {
let diff = originalNumber - number;
newDate = subDays(date, diff);
} else {
let diff = number - originalNumber;
newDate = addDays(date, diff);
}
dates.push(newDate);
});
for (let i = 0; i < todosToAddCycles; i++) {
dates?.forEach((dateToAdd) => {
let newTodoDate = addWeeks(dateToAdd, i);
if (compareAsc(newTodoDate, firstTodo?.date) !== 0) {
const newTodo = {...todoData, date: newTodoDate};
let docRef = firestore().collection("Todos").doc();
batch.set(docRef, newTodo);
}
})
}
removeRepeatDays?.forEach((removeDay) => {
filteredTodos?.forEach((item) => {
let todoDate = item.date;
const todoDateDay = format(todoDate, 'EEEE');
if (todoDateDay === removeDay) {
batch.delete(item.ref);
}
})
})
await batch.commit();
}

View File

@ -75,6 +75,7 @@
"react-native-app-auth": "^8.0.0", "react-native-app-auth": "^8.0.0",
"react-native-big-calendar": "^4.14.0", "react-native-big-calendar": "^4.14.0",
"react-native-calendars": "^1.1306.0", "react-native-calendars": "^1.1306.0",
"react-native-element-dropdown": "^2.12.2",
"react-native-gesture-handler": "~2.16.1", "react-native-gesture-handler": "~2.16.1",
"react-native-gifted-charts": "^1.4.41", "react-native-gifted-charts": "^1.4.41",
"react-native-keyboard-manager": "^6.5.16-0", "react-native-keyboard-manager": "^6.5.16-0",

View File

@ -8953,6 +8953,13 @@ react-native-calendars@^1.1306.0:
optionalDependencies: optionalDependencies:
moment "^2.29.4" moment "^2.29.4"
react-native-element-dropdown@^2.12.2:
version "2.12.2"
resolved "https://registry.yarnpkg.com/react-native-element-dropdown/-/react-native-element-dropdown-2.12.2.tgz#48d0c12b87591e2498c73bbde80e18374a4c262e"
integrity sha512-Tf8hfRuniYEXo+LGoVgIMoItKWuPLX6jbqlwAFgMbBhmWGTuV+g1OVOAx/ny16kgnwp+NhgJoWpxhVvr7HSmXA==
dependencies:
lodash "^4.17.21"
react-native-gesture-handler@~2.16.1: react-native-gesture-handler@~2.16.1:
version "2.16.2" version "2.16.2"
resolved "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.16.2.tgz" resolved "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.16.2.tgz"