Merge branch 'dev' into tablet

This commit is contained in:
ivic00
2024-11-03 17:10:12 +01:00
102 changed files with 9637 additions and 2793 deletions

View File

@ -1,112 +1,127 @@
import {
View,
Text,
Button,
TextField,
TextFieldRef,
TouchableOpacity,
} from "react-native-ui-lib";
import React, { useEffect, useState, useRef } from "react";
import { Dialog } from "react-native-ui-lib";
import { PanningDirectionsEnum } from "react-native-ui-lib/src/incubator/panView";
import { Dimensions, Keyboard, StyleSheet } from "react-native";
import {Button, Dialog, TextField, TextFieldRef, TouchableOpacity, View,} from "react-native-ui-lib";
import React, {useEffect, useRef, useState} from "react";
import {PanningDirectionsEnum} from "react-native-ui-lib/src/incubator/panView";
import {Dimensions, Platform, StyleSheet} from "react-native";
import DropModalIcon from "@/assets/svgs/DropModalIcon";
import { useBrainDumpContext } from "@/contexts/DumpContext";
import {useBrainDumpContext} from "@/contexts/DumpContext";
import KeyboardManager from "react-native-keyboard-manager";
interface IAddBrainDumpProps {
isVisible: boolean;
setIsVisible: (value: boolean) => void;
isVisible: boolean;
setIsVisible: (value: boolean) => void;
}
const AddBrainDump = ({
addBrainDumpProps,
}: {
addBrainDumpProps: IAddBrainDumpProps;
addBrainDumpProps,
}: {
addBrainDumpProps: IAddBrainDumpProps;
}) => {
const { addBrainDump } = useBrainDumpContext();
const [dumpTitle, setDumpTitle] = useState<string>("");
const [dumpDesc, setDumpDesc] = useState<string>("");
const { width } = Dimensions.get("screen");
const {addBrainDump} = useBrainDumpContext();
const [dumpTitle, setDumpTitle] = useState<string>("");
const [dumpDesc, setDumpDesc] = useState<string>("");
const {width} = Dimensions.get("screen");
// Refs for the two TextFields
const descriptionRef = useRef<TextFieldRef>(null);
// Refs for the two TextFields
const descriptionRef = useRef<TextFieldRef>(null);
const titleRef = useRef<TextFieldRef>(null);
useEffect(() => {
setDumpDesc("");
setDumpTitle("");
}, [addBrainDumpProps.isVisible]);
useEffect(() => {
if (addBrainDumpProps.isVisible) {
setTimeout(() => {
titleRef?.current?.focus()
}, 500)
}
}, [addBrainDumpProps.isVisible]);
useEffect(() => {
setDumpDesc("");
setDumpTitle("");
}, [addBrainDumpProps.isVisible]);
if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(false);
}, []);
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => addBrainDumpProps.setIsVisible(false)}
containerStyle={styles.dialogContainer}
visible={addBrainDumpProps.isVisible}
>
<View row spread style={styles.topBtns} marginB-20>
<Button
color="#05a8b6"
label="Cancel"
style={styles.topBtn}
onPress={() => {
addBrainDumpProps.setIsVisible(false);
}}
/>
<TouchableOpacity onPress={() => addBrainDumpProps.setIsVisible(false)}>
<DropModalIcon style={{ marginTop: 15 }} />
</TouchableOpacity>
<Button
color="#05a8b6"
label="Save"
style={styles.topBtn}
onPress={() => {
addBrainDump({ id: 99, title: dumpTitle.trimEnd().trimStart(), description: dumpDesc.trimEnd().trimStart() });
addBrainDumpProps.setIsVisible(false);
}}
/>
</View>
<View marginH-20>
<TextField
value={dumpTitle}
autoFocus
placeholder="Set Title"
text60R
onChangeText={(text) => {
setDumpTitle(text);
}}
onSubmitEditing={() => {
// Move focus to the description field
descriptionRef.current?.focus();
}}
style={styles.title}
blurOnSubmit={false} // Keep the keyboard open when moving focus
returnKeyType="next"
/>
<View height={2} backgroundColor="#b3b3b3" width={"100%"} marginB-20 />
<TextField
ref={descriptionRef}
value={dumpDesc}
placeholder="Write Description"
text70
onChangeText={(text) => {
setDumpDesc(text);
}}
style={styles.description}
multiline
numberOfLines={4}
maxLength={255}
onEndEditing={() => {
descriptionRef.current?.blur();
}}
returnKeyType="done"
/>
</View>
</Dialog>
);
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => addBrainDumpProps.setIsVisible(false)}
containerStyle={styles.dialogContainer}
visible={addBrainDumpProps.isVisible}
>
<View row spread style={styles.topBtns} marginB-20>
<Button
color="#05a8b6"
label="Cancel"
style={styles.topBtn}
onPress={() => {
addBrainDumpProps.setIsVisible(false);
}}
/>
<TouchableOpacity onPress={() => addBrainDumpProps.setIsVisible(false)}>
<DropModalIcon style={{marginTop: 15}}/>
</TouchableOpacity>
<Button
color="#05a8b6"
label="Save"
style={styles.topBtn}
onPress={() => {
addBrainDump({
id: 99,
title: dumpTitle.trimEnd().trimStart(),
description: dumpDesc.trimEnd().trimStart(),
});
addBrainDumpProps.setIsVisible(false);
}}
/>
</View>
<View marginH-20>
<TextField
value={dumpTitle}
ref={titleRef}
placeholder="Set Title"
text60R
onChangeText={(text) => {
setDumpTitle(text);
}}
onSubmitEditing={() => {
// Move focus to the description field
descriptionRef.current?.focus();
}}
style={styles.title}
blurOnSubmit={false} // Keep the keyboard open when moving focus
returnKeyType="next"
/>
<View height={2} backgroundColor="#b3b3b3" width={"100%"} marginB-20/>
<TextField
ref={descriptionRef}
value={dumpDesc}
placeholder="Write Description"
text70
onChangeText={(text) => {
setDumpDesc(text);
}}
style={styles.description}
multiline
numberOfLines={4}
maxLength={255}
onEndEditing={() => {
descriptionRef.current?.blur();
}}
returnKeyType="done"
/>
</View>
</Dialog>
);
};
const styles = StyleSheet.create({
@ -130,7 +145,7 @@ const styles = StyleSheet.create({
description: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
textAlignVertical: 'top'
textAlignVertical: "top",
},
});

View File

@ -0,0 +1,82 @@
import React from "react";
import { Dialog, Button, Text, View } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
interface BrainDumpDialogProps {
visible: boolean;
title: string;
onDismiss: () => void;
onConfirm: () => void;
}
const BrainDumpDialog: React.FC<BrainDumpDialogProps> = ({
visible,
title,
onDismiss,
onConfirm,
}) => {
return (
<Dialog
visible={visible}
onDismiss={onDismiss}
containerStyle={styles.dialog}
>
<Text center style={styles.title}>
Delete Note
</Text>
<View center>
<Text style={styles.text} center>
Are you sure you want to delete the {"\n"}
<Text style={{ fontSize: 16, fontFamily: "PlusJakartaSans_700Bold" }}>
{title}
</Text>{" "}
Note?
</Text>
</View>
<View row right gap-8>
<Button
label="Cancel"
onPress={onDismiss}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={onConfirm}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</Dialog>
);
};
// Empty stylesheet for future styles
const styles = StyleSheet.create({
confirmBtn: {
backgroundColor: "#ea156d",
},
cancelBtn: {
backgroundColor: "white",
},
dialog: {
backgroundColor: "white",
paddingHorizontal: 25,
paddingTop: 35,
paddingBottom: 17,
borderRadius: 20,
},
title: {
fontFamily: "Manrope_600SemiBold",
fontSize: 22,
marginBottom: 20,
},
text: {
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
marginBottom: 25,
},
});
export default BrainDumpDialog;

View File

@ -1,123 +1,120 @@
import { Dimensions, ScrollView } from "react-native";
import React, { useState } from "react";
import { View, Text, Button } from "react-native-ui-lib";
import {Dimensions, ScrollView, StyleSheet} from "react-native";
import React, {useState} from "react";
import {Button, Text, TextField, View} from "react-native-ui-lib";
import DumpList from "./DumpList";
import HeaderTemplate from "@/components/shared/HeaderTemplate";
import { TextField } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
import { Feather, MaterialIcons } from "@expo/vector-icons";
import { TextInput } from "react-native-gesture-handler";
import {Feather, MaterialIcons} from "@expo/vector-icons";
import AddBrainDump from "./AddBrainDump";
import LinearGradient from "react-native-linear-gradient";
import PlusIcon from "@/assets/svgs/PlusIcon";
const BrainDumpPage = () => {
const [searchText, setSearchText] = useState<string>("");
const [isAddVisible, setIsAddVisible] = useState<boolean>(false);
const [searchText, setSearchText] = useState<string>("");
const [isAddVisible, setIsAddVisible] = useState<boolean>(false);
return (
<View height={"100%"}>
<View>
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
>
<View marginH-25>
<HeaderTemplate
message={"Welcome to your notes!"}
isWelcome={false}
children={
<Text
style={{ fontFamily: "Manrope_400Regular", fontSize: 14 }}
>
Drop your notes on-the-go here, and{"\n"}organize them later.
</Text>
}
/>
return (
<View height={"100%"}>
<View>
<View style={styles.searchField} centerV>
<TextField
value={searchText}
onChangeText={(value) => {
setSearchText(value);
}}
leadingAccessory={
<Feather
name="search"
size={24}
color="#9b9b9b"
style={{ paddingRight: 10 }}
/>
}
style={{
fontFamily: "Manrope_500Medium",
fontSize: 15,
}}
placeholder="Search notes..."
/>
</View>
<DumpList searchText={searchText} />
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
>
<View marginH-25>
<HeaderTemplate
message={"Welcome to your notes!"}
isWelcome={false}
children={
<Text
style={{fontFamily: "Manrope_400Regular", fontSize: 14}}
>
Drop your notes on-the-go here, and{"\n"}organize them later.
</Text>
}
/>
<View>
<View style={styles.searchField} centerV>
<TextField
value={searchText}
onChangeText={(value) => {
setSearchText(value);
}}
leadingAccessory={
<Feather
name="search"
size={24}
color="#9b9b9b"
style={{paddingRight: 10}}
/>
}
style={{
fontFamily: "Manrope_500Medium",
fontSize: 15,
}}
placeholder="Search notes..."
/>
</View>
<DumpList searchText={searchText}/>
</View>
</View>
</ScrollView>
</View>
</View>
</ScrollView>
</View>
<LinearGradient
colors={["#f2f2f2", "transparent"]}
start={{ x: 0.5, y: 1 }}
end={{ x: 0.5, y: 0 }}
style={{
position: "absolute",
bottom: 0,
height: 90,
width: Dimensions.get("screen").width,
}}
>
<Button
style={{
height: 40,
position: "relative",
marginLeft: "auto",
width: 20,
right: 20,
bottom: -10,
borderRadius: 30,
backgroundColor: "#fd1775",
}}
color="white"
enableShadow
onPress={() => {
setIsAddVisible(true);
}}
>
<View row centerV centerH>
<MaterialIcons name="add" size={22} color={"white"} />
<Text
white
style={{ fontSize: 16, fontFamily: "Manrope_600SemiBold" }}
<LinearGradient
colors={["#f9f8f700", "#f9f8f7"]}
locations={[0,1]}
style={{
position: "absolute",
bottom: 0,
height: 120,
width: Dimensions.get("screen").width,
justifyContent:'center',
alignItems:"center"
}}
>
New
</Text>
</View>
</Button>
</LinearGradient>
<AddBrainDump
addBrainDumpProps={{
isVisible: isAddVisible,
setIsVisible: setIsAddVisible,
}}
/>
</View>
);
<Button
style={{
height: 40,
position: "relative",
width: "90%",
bottom: -10,
borderRadius: 30,
backgroundColor: "#fd1775",
}}
color="white"
enableShadow
onPress={() => {
setIsAddVisible(true);
}}
>
<View row centerV centerH>
<PlusIcon />
<Text
white
style={{fontSize: 16, fontFamily: "Manrope_600SemiBold", marginLeft: 5}}
>
New
</Text>
</View>
</Button>
</LinearGradient>
<AddBrainDump
addBrainDumpProps={{
isVisible: isAddVisible,
setIsVisible: setIsAddVisible,
}}
/>
</View>
);
};
const styles = StyleSheet.create({
searchField: {
borderWidth: 0.7,
borderColor: "#9b9b9b",
borderRadius: 15,
height: 42,
paddingLeft: 10,
marginVertical: 20,
},
searchField: {
borderWidth: 0.7,
borderColor: "#9b9b9b",
borderRadius: 15,
height: 42,
paddingLeft: 10,
marginVertical: 20,
},
});
export default BrainDumpPage;

View File

@ -1,11 +1,11 @@
import React, { useEffect, useState } from "react";
import React, {useEffect, useRef, useState} from "react";
import {
Button,
Dialog,
View,
Text,
TextField,
TouchableOpacity,
TouchableOpacity, TextFieldRef,
} from "react-native-ui-lib";
import { Dimensions, StyleSheet } from "react-native";
import { PanningDirectionsEnum } from "react-native-ui-lib/src/incubator/panView";
@ -18,6 +18,7 @@ import NavCalendarIcon from "@/assets/svgs/NavCalendarIcon";
import NavToDosIcon from "@/assets/svgs/NavToDosIcon";
import RemindersIcon from "@/assets/svgs/RemindersIcon";
import MenuIcon from "@/assets/svgs/MenuIcon";
import BrainDumpDialog from "./BrainDumpDialog";
const MoveBrainDump = (props: {
item: IBrainDump;
@ -28,12 +29,35 @@ const MoveBrainDump = (props: {
const [description, setDescription] = useState<string>(
props.item.description
);
const [modalVisible, setModalVisible] = useState<boolean>(false);
const descriptionRef = useRef<TextFieldRef>(null)
const { width } = Dimensions.get("screen");
useEffect(() => {
updateBrainDumpItem(props.item.id, { description: description });
}, [description]);
useEffect(() => {
if (props.isVisible) {
setTimeout(() => {
descriptionRef?.current?.focus()
}, 500)
}
}, [props.isVisible]);
const showConfirmationDialog = () => {
setModalVisible(true);
};
const handleDeleteNote = () =>{
deleteBrainDump(props.item.id);
}
const hideConfirmationDialog = () => {
setModalVisible(false);
}
return (
<Dialog
bottom={true}
@ -81,8 +105,7 @@ const MoveBrainDump = (props: {
marginL-5
iconSource={() => <BinIcon />}
onPress={() => {
deleteBrainDump(props.item.id);
props.setIsVisible(false);
showConfirmationDialog();
}}
/>
</View>
@ -98,7 +121,6 @@ const MoveBrainDump = (props: {
<TextField
textAlignVertical="top"
multiline
autoFocus
fieldStyle={{
width: "94%",
}}
@ -109,6 +131,7 @@ const MoveBrainDump = (props: {
onChangeText={(value) => {
setDescription(value);
}}
ref={descriptionRef}
returnKeyType="default"
/>
</View>
@ -145,6 +168,7 @@ const MoveBrainDump = (props: {
</View>
</TouchableOpacity>
</View>
<BrainDumpDialog visible={modalVisible} title={props.item.title} onDismiss={hideConfirmationDialog} onConfirm={handleDeleteNote} />
</Dialog>
);
};
@ -191,10 +215,10 @@ const styles = StyleSheet.create({
fontSize: 22,
fontFamily: "Manrope_500Medium",
},
description:{
description: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
}
},
});
export default MoveBrainDump;

View File

@ -10,6 +10,7 @@ import CalendarIcon from "@/assets/svgs/CalendarIcon";
import NavToDosIcon from "@/assets/svgs/NavToDosIcon";
import {useSetAtom} from "jotai";
import {selectedNewEventDateAtom} from "@/components/pages/calendar/atoms";
import PlusIcon from "@/assets/svgs/PlusIcon";
export const AddEventDialog = () => {
const [show, setShow] = useState(false);
@ -50,8 +51,8 @@ export const AddEventDialog = () => {
onPress={() => setShow(true)}
>
<View row centerV centerH>
<MaterialIcons name="add" size={22} color={"white"}/>
<Text white style={{fontSize: 16, fontFamily: 'Manrope_600SemiBold'}}>
<PlusIcon />
<Text white style={{fontSize: 16, fontFamily: 'Manrope_600SemiBold', marginLeft: 5}}>
New
</Text>
</View>

View File

@ -1,104 +1,130 @@
import React, {memo} from 'react';
import {Button, Picker, PickerModes, SegmentedControl, Text, 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 React, { memo } from "react";
import {
Button,
Picker,
PickerModes,
SegmentedControl,
Text,
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 { format, isSameDay } from "date-fns";
import { useAuthContext } from "@/contexts/AuthContext";
export const CalendarHeader = memo(() => {
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom);
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom);
const { profileData } = useAuthContext();
const handleSegmentChange = (index: number) => {
const selectedMode = modeMap.get(index);
if (selectedMode) {
setTimeout(() => {
setMode(selectedMode as "day" | "week" | "month");
}, 150);
}
};
const handleSegmentChange = (index: number) => {
const selectedMode = modeMap.get(index);
if (selectedMode) {
setTimeout(() => {
setMode(selectedMode as "day" | "week" | "month");
}, 150);
}
};
const handleMonthChange = (month: string) => {
const currentDay = selectedDate.getDate();
const currentYear = selectedDate.getFullYear();
const newMonthIndex = months.indexOf(month);
const handleMonthChange = (month: string) => {
const currentDay = selectedDate.getDate();
const currentYear = selectedDate.getFullYear();
const newMonthIndex = months.indexOf(month);
const updatedDate = new Date(currentYear, newMonthIndex, currentDay);
setSelectedDate(updatedDate);
};
const updatedDate = new Date(currentYear, newMonthIndex, currentDay);
setSelectedDate(updatedDate);
};
const isSelectedDateToday = isSameDay(selectedDate, new Date())
const isSelectedDateToday = isSameDay(selectedDate, new Date());
return (
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 10,
paddingVertical: 8,
borderRadius: 20,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
backgroundColor: "white",
marginBottom: 10,
}}
return (
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 10,
paddingVertical: 8,
borderRadius: 20,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
backgroundColor: "white",
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>
<Text style={{fontFamily: "Manrope_500Medium", fontSize: 17}}>
{selectedDate.getFullYear()}
</Text>
<Picker
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>
{months.map((month) => (
<Picker.Item key={month} label={month} value={month} />
))}
</Picker>
</View>
<View row>
{!isSelectedDateToday && (
<Button size={"small"} marginR-5 label={"Today"} onPress={() => {
setSelectedDate(new Date())
setMode("day")
}}/>
)}
<View row centerV>
{!isSelectedDateToday && (
<Button
size={"xSmall"}
marginR-0
avoidInnerPadding
style={{
borderRadius: 50,
backgroundColor: "white",
borderWidth: 0.7,
borderColor: "#dadce0",
height: 30,
paddingHorizontal: 10,
}}
labelStyle={{
fontSize: 12,
color: "black",
fontFamily: "Manrope_500Medium",
}}
label={format(new Date(), "dd/MM/yyyy")}
onPress={() => {
setSelectedDate(new Date());
}}
/>
)}
<View>
<SegmentedControl
segments={[{label: "D"}, {label: "W"}, {label: "M"}]}
backgroundColor="#ececec"
inactiveColor="#919191"
activeBackgroundColor="#ea156c"
activeColor="white"
outlineColor="white"
outlineWidth={3}
segmentLabelStyle={styles.segmentslblStyle}
onChangeIndex={handleSegmentChange}
initialIndex={mode === "day" ? 0 : mode === "week" ? 1 : 2}
/>
</View>
</View>
<View>
<SegmentedControl
segments={[{ label: "D" }, { label: "W" }, { label: "M" }]}
backgroundColor="#ececec"
inactiveColor="#919191"
activeBackgroundColor="#ea156c"
activeColor="white"
outlineColor="white"
outlineWidth={3}
segmentLabelStyle={styles.segmentslblStyle}
onChangeIndex={handleSegmentChange}
initialIndex={mode === "day" ? 0 : mode === "week" ? 1 : 2}
/>
</View>
)
;
</View>
</View>
);
});
const styles = StyleSheet.create({
segmentslblStyle: {
fontSize: 12,
fontFamily: "Manrope_600SemiBold",
},
});
segmentslblStyle: {
fontSize: 12,
fontFamily: "Manrope_600SemiBold",
},
});

View File

@ -13,6 +13,7 @@ export default function CalendarPage() {
<HeaderTemplate
message={"Let's get your week started!"}
isWelcome
isCalendar={true}
/>
<InnerCalendar/>
</View>

View File

@ -1,90 +1,92 @@
import {Text, TouchableOpacity, View} from "react-native-ui-lib";
import React, {useState} from "react";
import {StyleSheet} from "react-native";
import {useSetAtom} from "jotai";
import {isFamilyViewAtom} from "@/components/pages/calendar/atoms";
import { Text, TouchableOpacity, View } from "react-native-ui-lib";
import React from "react";
import { StyleSheet } from "react-native";
import { useAtom } from "jotai";
import { isFamilyViewAtom } from "@/components/pages/calendar/atoms";
const CalendarViewSwitch = () => {
const [calView, setCalView] = useState<boolean>(false);
const viewSwitch = useSetAtom(isFamilyViewAtom)
const [isFamilyView, setIsFamilyView] = useAtom(isFamilyViewAtom);
return (
return (
<View
row
spread
style={{
position: "absolute",
bottom: 20,
left: 20,
borderRadius: 30,
backgroundColor: "white",
alignItems: "center",
justifyContent: "center",
// iOS shadow
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
// Android shadow (elevation)
elevation: 6,
}}
centerV
>
<TouchableOpacity
onPress={() => {
setIsFamilyView(true);
}}
>
<View
row
spread
style={{
position: "absolute",
bottom: 20,
left: 20,
borderRadius: 30,
backgroundColor: "white",
alignItems: "center",
justifyContent: "center",
// iOS shadow
shadowColor: "#000",
shadowOffset: {width: 0, height: 2},
shadowOpacity: 0.25,
shadowRadius: 3.84,
// Android shadow (elevation)
elevation: 6,
}}
centerV
centerV
centerH
height={40}
paddingH-15
style={isFamilyView ? styles.switchBtnActive : styles.switchBtn}
>
<TouchableOpacity
onPress={() => {
setCalView(true);
viewSwitch(true);
}}
>
<View
centerV
centerH
height={40}
paddingH-15
style={calView ? styles.switchBtnActive : styles.switchBtn}
>
<Text color={calView ? "white" : "#a1a1a1"} style={styles.switchTxt}>
Family View
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setCalView(false);
viewSwitch(false);
}}
>
<View
centerV
centerH
height={40}
paddingH-15
style={!calView ? styles.switchBtnActive : styles.switchBtn}
>
<Text color={!calView ? "white" : "#a1a1a1"} style={styles.switchTxt}>
My View
</Text>
</View>
</TouchableOpacity>
<Text
color={isFamilyView ? "white" : "#a1a1a1"}
style={styles.switchTxt}
>
Family View
</Text>
</View>
);
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setIsFamilyView(false);
}}
>
<View
centerV
centerH
height={40}
paddingH-15
style={!isFamilyView ? styles.switchBtnActive : styles.switchBtn}
>
<Text
color={!isFamilyView ? "white" : "#a1a1a1"}
style={styles.switchTxt}
>
My View
</Text>
</View>
</TouchableOpacity>
</View>
);
};
export default CalendarViewSwitch;
const styles = StyleSheet.create({
switchBtnActive: {
backgroundColor: "#a1a1a1",
borderRadius: 50,
},
switchBtn: {
backgroundColor: "white",
borderRadius: 50,
},
switchTxt: {
fontSize: 16,
fontFamily: 'Manrope_600SemiBold'
}
switchBtnActive: {
backgroundColor: "#a1a1a1",
borderRadius: 50,
},
switchBtn: {
backgroundColor: "white",
borderRadius: 50,
},
switchTxt: {
fontSize: 16,
fontFamily: "Manrope_600SemiBold",
},
});

View File

@ -0,0 +1,81 @@
import React from "react";
import { Dialog, Button, Text, View } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
interface DeleteEventDialogProps {
visible: boolean;
title: string;
onDismiss: () => void;
onConfirm: () => void;
}
const DeleteEventDialog: React.FC<DeleteEventDialogProps> = ({
visible,
title,
onDismiss,
onConfirm,
}) => {
return (
<Dialog
visible={visible}
onDismiss={onDismiss}
containerStyle={styles.dialog}
>
<Text center style={styles.title}>
Delete Event
</Text>
<View center>
<Text style={styles.text} center>
Are you sure you want to delete the event:{" "}
<Text style={{ fontSize: 16, fontFamily: "PlusJakartaSans_700Bold" }}>
{title}
</Text>{" "}
</Text>
</View>
<View row right gap-8>
<Button
label="Cancel"
onPress={onDismiss}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={onConfirm}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</Dialog>
);
};
// Empty stylesheet for future styles
const styles = StyleSheet.create({
confirmBtn: {
backgroundColor: "#ea156d",
},
cancelBtn: {
backgroundColor: "white",
},
dialog: {
backgroundColor: "white",
paddingHorizontal: 25,
paddingTop: 35,
paddingBottom: 17,
borderRadius: 20,
},
title: {
fontFamily: "Manrope_600SemiBold",
fontSize: 22,
marginBottom: 20,
},
text: {
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
marginBottom: 25,
},
});
export default DeleteEventDialog;

View File

@ -1,6 +1,6 @@
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import React, {useCallback, useEffect, useMemo, useState} from "react";
import {Calendar} from "react-native-big-calendar";
import {ActivityIndicator, StyleSheet, View} from "react-native";
import {ActivityIndicator, StyleSheet, View, ViewStyle} from "react-native";
import {useGetEvents} from "@/hooks/firebase/useGetEvents";
import {useAtom, useSetAtom} from "jotai";
import {
@ -8,10 +8,12 @@ import {
eventForEditAtom,
modeAtom,
selectedDateAtom,
selectedNewEventDateAtom
selectedNewEventDateAtom,
} from "@/components/pages/calendar/atoms";
import {useAuthContext} from "@/contexts/AuthContext";
import {CalendarEvent} from "@/components/pages/calendar/interfaces";
import {Text} from "react-native-ui-lib";
import {addDays, compareAsc, isWithinInterval, subDays} from "date-fns";
interface EventCalendarProps {
calendarHeight: number;
@ -22,107 +24,250 @@ interface EventCalendarProps {
const getTotalMinutes = () => {
const date = new Date();
return Math.abs(date.getUTCHours() * 60 + date.getUTCMinutes() - 200);
}
};
export const EventCalendar: React.FC<EventCalendarProps> = React.memo(({calendarHeight}) => {
const {data: events, isLoading} = useGetEvents();
const {profileData} = useAuthContext();
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom);
export const EventCalendar: React.FC<EventCalendarProps> = React.memo(
({calendarHeight}) => {
const {data: events, isLoading} = useGetEvents();
const {profileData} = useAuthContext();
const [selectedDate, setSelectedDate] = useAtom(selectedDateAtom);
const [mode, setMode] = useAtom(modeAtom);
const setEditVisible = useSetAtom(editVisibleAtom);
const setEventForEdit = useSetAtom(eventForEditAtom);
const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom);
const setEditVisible = useSetAtom(editVisibleAtom);
const setEventForEdit = useSetAtom(eventForEditAtom);
const setSelectedNewEndDate = useSetAtom(selectedNewEventDateAtom);
const [isRendering, setIsRendering] = useState(true);
const [offsetMinutes, setOffsetMinutes] = useState(getTotalMinutes())
const [offsetMinutes, setOffsetMinutes] = useState(getTotalMinutes());
useEffect(() => {
if (events && mode) {
setIsRendering(true);
const timeout = setTimeout(() => {
setIsRendering(false);
}, 300);
return () => clearTimeout(timeout);
}
}, [events, mode]);
const todaysDate = new Date();
const handlePressEvent = useCallback((event: CalendarEvent) => {
if (mode === "day" || mode === "week") {
setEditVisible(true);
console.log({event})
setEventForEdit(event);
} else {
setMode("day")
setSelectedDate(event.start);
}
}, [setEditVisible, setEventForEdit, mode]);
const handlePressEvent = useCallback(
(event: CalendarEvent) => {
if (mode === "day" || mode === "week") {
setEditVisible(true);
console.log({event});
setEventForEdit(event);
} else {
setMode("day");
setSelectedDate(event.start);
}
},
[setEditVisible, setEventForEdit, mode]
);
const handlePressCell = useCallback(
(date: Date) => {
if (mode === "day" || mode === "week") {
setSelectedNewEndDate(date);
} else {
setMode("day")
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]
);
const memoizedEventCellStyle = useCallback(
(event: CalendarEvent) => ({backgroundColor: event.eventColor}),
[]
);
const memoizedWeekStartsOn = useMemo(
() => (profileData?.firstDayOfWeek === "Mondays" ? 1 : 0),
[profileData]
);
console.log({memoizedWeekStartsOn, profileData: profileData?.firstDayOfWeek})
const isSameDate = useCallback((date1: Date, date2: Date) => {
return (
date1.getDate() === date2.getDate() &&
date1.getMonth() === date2.getMonth() &&
date1.getFullYear() === date2.getFullYear()
);
}, []);
const dayHeaderColor = useMemo(() => {
return isSameDate(todaysDate, selectedDate) ? "white" : "#4d4d4d";
}, [selectedDate, mode]);
const dateStyle = useMemo(() => {
if (mode === "week") return undefined;
return isSameDate(todaysDate, selectedDate) && mode === "day"
? styles.dayHeader
: styles.otherDayHeader;
}, [selectedDate, mode]);
const memoizedHeaderContentStyle = useMemo(() => {
if (mode === "day") {
return styles.dayModeHeader;
} else if (mode === "week") {
return styles.weekModeHeader;
} else if (mode === "month") {
return styles.monthModeHeader;
} else {
return {};
}
},
[mode, setSelectedNewEndDate, setSelectedDate]
);
}, [mode]);
const handleSwipeEnd = useCallback((date: Date) => {
setSelectedDate(date);
}, [setSelectedDate]);
const memoizedEventCellStyle = useCallback(
(event: CalendarEvent) => ({backgroundColor: event.eventColor}),
[]
);
const {enrichedEvents, filteredEvents} = useMemo(() => {
const startTime = Date.now(); // Start timer
const memoizedWeekStartsOn = useMemo(
() => (profileData?.firstDayOfWeek === "Mondays" ? 1 : 0),
[profileData]
);
const startOffset = mode === "month" ? 40 : mode === "week" ? 10 : 1;
const endOffset = mode === "month" ? 40 : mode === "week" ? 10 : 1;
const memoizedHeaderContentStyle = useMemo(
() => (mode === "day" ? styles.dayModeHeader : {}),
[mode]
);
const filteredEvents = events?.filter(event =>
event.start && event.end &&
isWithinInterval(event.start, {
start: subDays(selectedDate, startOffset),
end: addDays(selectedDate, endOffset)
}) &&
isWithinInterval(event.end, {
start: subDays(selectedDate, startOffset),
end: addDays(selectedDate, endOffset)
})
) ?? [];
const memoizedEvents = useMemo(() => events ?? [], [events]);
const enrichedEvents = filteredEvents.reduce((acc, event) => {
const dateKey = event.start.toISOString().split('T')[0];
acc[dateKey] = acc[dateKey] || [];
acc[dateKey].push({
...event,
overlapPosition: false,
overlapCount: 0
});
useEffect(() => {
setOffsetMinutes(getTotalMinutes())
}, [events, mode]);
acc[dateKey].sort((a, b) => compareAsc(a.start, b.start));
return acc;
}, {} as Record<string, CalendarEvent[]>);
const endTime = Date.now();
console.log("memoizedEvents computation time:", endTime - startTime, "ms");
return {enrichedEvents, filteredEvents};
}, [events, selectedDate, mode]);
const renderCustomDateForMonth = (date: Date) => {
const circleStyle = useMemo<ViewStyle>(
() => ({
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center",
borderRadius: 15,
}),
[]
);
const defaultStyle = useMemo<ViewStyle>(
() => ({
...circleStyle,
}),
[circleStyle]
);
const currentDateStyle = useMemo<ViewStyle>(
() => ({
...circleStyle,
backgroundColor: "#4184f2",
}),
[circleStyle]
);
const renderDate = useCallback(
(date: Date) => {
const isCurrentDate = isSameDate(todaysDate, date);
const appliedStyle = isCurrentDate ? currentDateStyle : defaultStyle;
return (
<View style={{alignItems: "center"}}>
<View style={appliedStyle}>
<Text style={{color: isCurrentDate ? "white" : "black"}}>
{date.getDate()}
</Text>
</View>
</View>
);
},
[todaysDate, currentDateStyle, defaultStyle] // dependencies
);
return renderDate(date);
};
useEffect(() => {
setOffsetMinutes(getTotalMinutes());
}, [events, mode]);
if (isLoading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0000ff"/>
</View>
);
}
// console.log(enrichedEvents, filteredEvents)
if (isLoading || isRendering) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#0000ff"/>
</View>
<Calendar
bodyContainerStyle={styles.calHeader}
swipeEnabled
mode={mode}
enableEnrichedEvents={true}
sortedMonthView
// enrichedEventsByDate={enrichedEvents}
events={filteredEvents}
// eventCellStyle={memoizedEventCellStyle}
onPressEvent={handlePressEvent}
weekStartsOn={memoizedWeekStartsOn}
height={calendarHeight}
activeDate={todaysDate}
date={selectedDate}
onPressCell={handlePressCell}
headerContentStyle={memoizedHeaderContentStyle}
onSwipeEnd={handleSwipeEnd}
scrollOffsetMinutes={offsetMinutes}
theme={{
palette: {
nowIndicator: profileData?.eventColor || "#fd1575",
gray: {
"100": "#e8eaed",
"200": "#e8eaed",
"500": "#b7b7b7",
"800": "#919191",
},
},
typography: {
fontFamily: "PlusJakartaSans_500Medium",
sm: {fontFamily: "Manrope_600SemiBold", fontSize: 15},
xl: {
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
},
moreLabel: {},
xs: {fontSize: 10},
},
}}
dayHeaderStyle={dateStyle}
dayHeaderHighlightColor={"white"}
showAdjacentMonths
hourStyle={styles.hourStyle}
ampm
// renderCustomDateForMonth={renderCustomDateForMonth}
/>
);
}
return (
<Calendar
bodyContainerStyle={styles.calHeader}
swipeEnabled
enableEnrichedEvents
mode={mode}
events={memoizedEvents}
eventCellStyle={memoizedEventCellStyle}
onPressEvent={handlePressEvent}
weekStartsOn={memoizedWeekStartsOn}
height={calendarHeight}
activeDate={selectedDate}
date={selectedDate}
onPressCell={handlePressCell}
headerContentStyle={memoizedHeaderContentStyle}
onSwipeEnd={handleSwipeEnd}
scrollOffsetMinutes={offsetMinutes}
/>
);
});
);
const styles = StyleSheet.create({
segmentslblStyle: {
@ -138,10 +283,33 @@ const styles = StyleSheet.create({
alignContent: "center",
width: 38,
right: 42,
height: 13,
},
weekModeHeader: {},
monthModeHeader: {},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
justifyContent: "center",
alignItems: "center",
},
});
dayHeader: {
backgroundColor: "#4184f2",
aspectRatio: 1,
borderRadius: 100,
alignItems: "center",
justifyContent: "center",
},
otherDayHeader: {
backgroundColor: "transparent",
color: "#919191",
aspectRatio: 1,
borderRadius: 100,
alignItems: "center",
justifyContent: "center",
},
hourStyle: {
color: "#5f6368",
fontSize: 12,
fontFamily: "Manrope_500Medium",
},
});

View File

@ -17,7 +17,7 @@ import {
import {ScrollView} from "react-native-gesture-handler";
import {useSafeAreaInsets} from "react-native-safe-area-context";
import {useEffect, useRef, useState} from "react";
import {AntDesign, Feather, Ionicons,} from "@expo/vector-icons";
import {AntDesign, Feather, Ionicons} from "@expo/vector-icons";
import {PickerMultiValue} from "react-native-ui-lib/src/components/picker/types";
import {useCreateEvent} from "@/hooks/firebase/useCreateEvent";
import {EventData} from "@/hooks/firebase/types/eventData";
@ -30,8 +30,11 @@ import MenuIcon from "@/assets/svgs/MenuIcon";
import CameraIcon from "@/assets/svgs/CameraIcon";
import AssigneesDisplay from "@/components/shared/AssigneesDisplay";
import {useAtom} from "jotai";
import {eventForEditAtom, selectedNewEventDateAtom} from "@/components/pages/calendar/atoms";
import {eventForEditAtom, selectedNewEventDateAtom,} from "@/components/pages/calendar/atoms";
import {useGetFamilyMembers} from "@/hooks/firebase/useGetFamilyMembers";
import BinIcon from "@/assets/svgs/BinIcon";
import DeleteEventDialog from "./DeleteEventDialog";
import {useDeleteEvent} from "@/hooks/firebase/useDeleteEvent";
const daysOfWeek = [
{label: "Monday", value: "monday"},
@ -46,24 +49,31 @@ const daysOfWeek = [
export const ManuallyAddEventModal = () => {
const insets = useSafeAreaInsets();
const [selectedNewEventDate, setSelectedNewEndDate] = useAtom(selectedNewEventDateAtom)
const [editEvent, setEditEvent] = useAtom(eventForEditAtom)
const [selectedNewEventDate, setSelectedNewEndDate] = useAtom(
selectedNewEventDateAtom
);
const [editEvent, setEditEvent] = useAtom(eventForEditAtom);
const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
const {mutateAsync: deleteEvent, isLoading: isDeleting} = useDeleteEvent()
const {show, close, initialDate} = {
show: !!selectedNewEventDate || !!editEvent,
close: () => {
setSelectedNewEndDate(undefined)
setEditEvent(undefined)
setDeleteModalVisible(false);
setSelectedNewEndDate(undefined);
setEditEvent(undefined);
},
initialDate: selectedNewEventDate || editEvent?.start
}
initialDate: selectedNewEventDate || editEvent?.start,
};
const detailsRef = useRef<TextFieldRef>(null)
const detailsRef = useRef<TextFieldRef>(null);
const [title, setTitle] = useState<string>(editEvent?.title || "");
const [details, setDetails] = useState<string>(editEvent?.notes || "");
const [isAllDay, setIsAllDay] = useState(editEvent?.allDay || false);
const [isPrivate, setIsPrivate] = useState<boolean>(editEvent?.private || false);
const [isPrivate, setIsPrivate] = useState<boolean>(
editEvent?.private || false
);
const [startTime, setStartTime] = useState(() => {
const date = initialDate ?? new Date();
date.setSeconds(0, 0);
@ -75,19 +85,27 @@ export const ManuallyAddEventModal = () => {
date.setSeconds(0, 0);
return date;
}
const date = (editEvent?.end ?? initialDate)
? addHours((editEvent?.end ?? initialDate!), 1)
: addHours(new Date(), 1);
const date =
editEvent?.end ?? initialDate
? addHours(editEvent?.end ?? initialDate!, 1)
: addHours(new Date(), 1);
date.setSeconds(0, 0);
return date;
});
const [startDate, setStartDate] = useState(initialDate ?? new Date());
const [endDate, setEndDate] = useState(editEvent?.end ?? initialDate ?? new Date());
const [selectedAttendees, setSelectedAttendees] = useState<string[]>(editEvent?.participants ?? []);
const [endDate, setEndDate] = useState(
editEvent?.end ?? initialDate ?? new Date()
);
const [selectedAttendees, setSelectedAttendees] = useState<string[]>(
editEvent?.participants ?? []
);
const [repeatInterval, setRepeatInterval] = useState<PickerMultiValue>([]);
const {mutateAsync: createEvent, isLoading, isError} = useCreateEvent();
const {mutateAsync: createEvent, isLoading: isAdding, isError} = useCreateEvent();
const {data: members} = useGetFamilyMembers(true);
const titleRef = useRef<TextFieldRef>(null)
const isLoading = isDeleting || isAdding
useEffect(() => {
setTitle(editEvent?.title || "");
@ -105,9 +123,10 @@ export const ManuallyAddEventModal = () => {
date.setSeconds(0, 0);
return date;
}
const date = (editEvent?.end ?? initialDate)
? addHours((editEvent?.end ?? initialDate!), 1)
: addHours(new Date(), 1);
const date =
editEvent?.end ?? initialDate
? addHours(editEvent?.end ?? initialDate!, 1)
: addHours(new Date(), 1);
date.setSeconds(0, 0);
return date;
});
@ -117,6 +136,14 @@ export const ManuallyAddEventModal = () => {
setRepeatInterval([]);
}, [editEvent, selectedNewEventDate]);
useEffect(() => {
if(show && !editEvent) {
setTimeout(() => {
titleRef?.current?.focus()
}, 500);
}
}, [selectedNewEventDate]);
if (!show) return null;
const formatDateTime = (date?: Date | string) => {
@ -128,6 +155,19 @@ export const ManuallyAddEventModal = () => {
});
};
const showDeleteEventModal = () => {
setDeleteModalVisible(true);
};
const handleDeleteEvent = async () => {
await deleteEvent({eventId: `${editEvent?.id}`})
close()
};
const hideDeleteEventModal = () => {
setDeleteModalVisible(false);
};
const combineDateAndTime = (date: Date, time: Date): Date => {
const combined = new Date(date);
combined.setHours(time.getHours());
@ -155,12 +195,13 @@ export const ManuallyAddEventModal = () => {
endDate: finalEndDate,
allDay: isAllDay,
attendees: selectedAttendees,
notes: details
notes: details,
};
if (editEvent?.id) eventData.id = editEvent?.id
if (editEvent?.id) eventData.id = editEvent?.id;
await createEvent(eventData);
setEditEvent(undefined);
close();
};
@ -205,7 +246,7 @@ export const ManuallyAddEventModal = () => {
onRequestClose={close}
transparent={false}
>
<LoaderScreen message={"Saving event..."} color={Colors.grey40}/>
<LoaderScreen message={isDeleting ? "Deleting event..." : "Saving event..."} color={Colors.grey40}/>
</Modal>
);
}
@ -227,6 +268,39 @@ export const ManuallyAddEventModal = () => {
paddingRight: insets.right, // Safe area inset for right
}}
>
{/*{editEvent ? (*/}
{/* <>*/}
{/* <View center paddingT-8>*/}
{/* <TouchableOpacity onPress={close}>*/}
{/* <DropModalIcon />*/}
{/* </TouchableOpacity>*/}
{/* </View>*/}
{/* <View row spread paddingH-10 paddingB-15>*/}
{/* <Button*/}
{/* color="#05a8b6"*/}
{/* style={styles.topBtn}*/}
{/* iconSource={() => <CloseXIcon />}*/}
{/* onPress={close}*/}
{/* />*/}
{/* <View row>*/}
{/* <Button*/}
{/* style={styles.topBtn}*/}
{/* marginR-10*/}
{/* iconSource={() => <PenIcon />}*/}
{/* onPress={handleSave}*/}
{/* />*/}
{/* <Button*/}
{/* style={styles.topBtn}*/}
{/* marginL-5*/}
{/* iconSource={() => <BinIcon />}*/}
{/* onPress={() => {*/}
{/* showDeleteEventModal();*/}
{/* }}*/}
{/* />*/}
{/* </View>*/}
{/* </View>*/}
{/* </>*/}
{/*) : (*/}
<View
style={{
flexDirection: "row",
@ -246,25 +320,39 @@ export const ManuallyAddEventModal = () => {
Cancel
</Text>
</TouchableOpacity>
<DropModalIcon onPress={close}/>
<TouchableOpacity onPress={handleSave}>
<Text
style={{
color: "#05a8b6",
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
}}
text70
>
Save
</Text>
</TouchableOpacity>
<View row center>
<DropModalIcon onPress={close}/>
</View>
<View flexS row gap-10>
<TouchableOpacity onPress={handleSave}>
<Text
style={{
color: "#05a8b6",
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
}}
text70
>
Save
</Text>
</TouchableOpacity>
{editEvent && (
<Button
style={styles.topBtn}
marginL-5
iconSource={() => <BinIcon/>}
onPress={showDeleteEventModal}
/>
)}
</View>
</View>
{/*)}*/}
<ScrollView style={{minHeight: "85%"}}>
<TextField
placeholder="Add event title"
ref={titleRef}
value={title}
autoFocus
onChangeText={(text) => {
setTitle(text);
}}
@ -307,7 +395,7 @@ export const ManuallyAddEventModal = () => {
onChange={(date) => {
setStartDate(date);
}}
maximumDate={endDate}
//maximumDate={endDate}
style={{
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
@ -317,8 +405,11 @@ export const ManuallyAddEventModal = () => {
</View>
<DateTimePicker
value={startTime}
onChange={(date) => setStartTime(date)}
maximumDate={endTime}
onChange={(time) => {
if (time <= endTime) {
setStartTime(time);
}
}}
minuteInterval={5}
dateTimeFormatter={(date, mode) =>
date.toLocaleTimeString("en-us", {
@ -355,7 +446,11 @@ export const ManuallyAddEventModal = () => {
</View>
<DateTimePicker
value={endTime}
onChange={(date) => setEndTime(date)}
onChange={(time) => {
if (time >= endTime) {
setEndTime(time);
}
}}
minimumDate={startTime}
minuteInterval={5}
dateTimeFormatter={(date, mode) =>
@ -388,10 +483,12 @@ export const ManuallyAddEventModal = () => {
<View flex-1/>
<Picker
value={selectedAttendees}
onChange={(value) => setSelectedAttendees(value as string[] ?? [])}
onChange={(value) =>
setSelectedAttendees((value as string[]) ?? [])
}
style={{marginLeft: "auto"}}
mode={PickerModes.MULTI}
renderInput={() =>
renderInput={() => (
<Button
size={ButtonSize.small}
paddingH-8
@ -407,9 +504,13 @@ export const ManuallyAddEventModal = () => {
}}
color="#ea156c"
label="Add"
labelStyle={{fontFamily: "Manrope_600SemiBold", fontSize: 14}}
labelStyle={{
fontFamily: "Manrope_600SemiBold",
fontSize: 14,
}}
/>
}>
)}
>
{members?.map((member) => (
<Picker.Item
key={member?.uid}
@ -421,8 +522,10 @@ export const ManuallyAddEventModal = () => {
</View>
<View marginL-35>
<AssigneesDisplay setSelectedAttendees={setSelectedAttendees}
selectedAttendees={selectedAttendees}/>
<AssigneesDisplay
setSelectedAttendees={setSelectedAttendees}
selectedAttendees={selectedAttendees}
/>
</View>
<View style={styles.divider}/>
@ -461,14 +564,15 @@ export const ManuallyAddEventModal = () => {
</View>
<View style={styles.divider}/>
<View marginH-30 marginB-0 row spread centerV>
<View row centerH>
<View row center>
<LockIcon/>
<Text
style={{
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
marginL-10
marginL-12
center
>
Mark as Private
</Text>
@ -500,14 +604,22 @@ export const ManuallyAddEventModal = () => {
</View>
</TouchableOpacity>
<TextField value={details} onChangeText={setDetails} ref={detailsRef} maxLength={2000} multiline
numberOfLines={10} marginT-10 style={{flex: 1, minHeight: 180}}/>
<TextField
value={details}
onChangeText={setDetails}
ref={detailsRef}
maxLength={2000}
multiline
numberOfLines={10}
marginT-10
style={{flex: 1, minHeight: 180}}
/>
</View>
</ScrollView>
<Button
disabled
marginH-30
marginB-15
marginB-30
label="Create event from image"
text70
style={{height: 47}}
@ -520,6 +632,14 @@ export const ManuallyAddEventModal = () => {
)}
/>
</View>
{editEvent && (
<DeleteEventDialog
visible={deleteModalVisible}
title={editEvent?.title}
onDismiss={hideDeleteEventModal}
onConfirm={handleDeleteEvent}
/>
)}
</Modal>
);
};

View File

@ -1,9 +1,12 @@
import { atom } from 'jotai';
import {CalendarEvent} from "@/components/pages/calendar/interfaces";
import { atom } from "jotai";
import { CalendarEvent } from "@/components/pages/calendar/interfaces";
export const editVisibleAtom = atom<boolean>(false);
export const eventForEditAtom = atom<CalendarEvent | undefined>(undefined);
export const isFamilyViewAtom = atom<boolean>(false);
export const modeAtom = atom<"week" | "month" | "day">("week");
export const selectedDateAtom = atom<Date>(new Date());
export const selectedNewEventDateAtom = atom<Date | undefined>(undefined);
export const selectedNewEventDateAtom = atom<Date | undefined>(undefined);
export const settingsPageIndex = atom<number>(0);
export const userSettingsView = atom<boolean>(true);
export const toDosPageIndex = atom<number>(0);

View File

@ -10,5 +10,7 @@ export interface CalendarEvent {
eventColor?: string; // Optional color to represent the event
participants?: string[]; // Optional list of participants or attendees
private?: boolean;
notes?: string
notes?: string,
overlapPosition?: number
overlapCount?: number
}

View File

@ -0,0 +1,157 @@
import {
Button,
Dialog,
TextField,
TextFieldRef,
TouchableOpacity,
View,
} from "react-native-ui-lib";
import React, { useEffect, useRef, useState } from "react";
import { PanningDirectionsEnum } from "react-native-ui-lib/src/incubator/panView";
import { Dimensions, Platform, StyleSheet } from "react-native";
import DropModalIcon from "@/assets/svgs/DropModalIcon";
import { useBrainDumpContext } from "@/contexts/DumpContext";
import KeyboardManager from "react-native-keyboard-manager";
import { useFeedbackContext } from "@/contexts/FeedbackContext";
interface IAddFeedbackProps {
isVisible: boolean;
setIsVisible: (value: boolean) => void;
}
const AddFeedback = ({
addFeedbackProps,
}: {
addFeedbackProps: IAddFeedbackProps;
}) => {
const { addFeedback } = useFeedbackContext();
const [feedback, setFeedback] = useState<string>("");
const [feedbackTitle, setFeedbackTitle] = useState<string>("");
const { width } = Dimensions.get("screen");
const descriptionRef = useRef<TextFieldRef>(null);
const titleRef = useRef<TextFieldRef>(null);
useEffect(() => {
setFeedback("");
}, [addFeedbackProps.isVisible]);
useEffect(() => {
if (addFeedbackProps.isVisible) {
setTimeout(() => {
titleRef?.current?.focus();
}, 500);
}
}, [addFeedbackProps.isVisible]);
useEffect(() => {
if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(false);
setFeedbackTitle("");
setFeedback("");
}, []);
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => addFeedbackProps.setIsVisible(false)}
containerStyle={styles.dialogContainer}
visible={addFeedbackProps.isVisible}
>
<View row spread style={styles.topBtns} marginB-20>
<Button
color="#05a8b6"
label="Cancel"
style={styles.topBtn}
onPress={() => {
addFeedbackProps.setIsVisible(false);
}}
/>
<TouchableOpacity onPress={() => addFeedbackProps.setIsVisible(false)}>
<DropModalIcon style={{ marginTop: 15 }} />
</TouchableOpacity>
<Button
color="#05a8b6"
label="Save"
style={styles.topBtn}
onPress={() => {
addFeedback({
id: 99,
title: feedbackTitle.trimEnd().trimStart(),
text: feedback.trimEnd().trimStart(),
});
addFeedbackProps.setIsVisible(false);
}}
/>
</View>
<View marginH-20>
<TextField
value={feedbackTitle}
ref={titleRef}
placeholder="Set Title"
text60R
onChangeText={(text) => {
setFeedbackTitle(text);
}}
onSubmitEditing={() => {
descriptionRef.current?.focus();
}}
style={styles.title}
blurOnSubmit={false}
returnKeyType="next"
/>
<View height={2} backgroundColor="#b3b3b3" width={"100%"} marginB-20 />
<TextField
ref={descriptionRef}
value={feedback}
placeholder="Write Description"
text70
onChangeText={(text) => {
setFeedback(text);
}}
style={styles.description}
multiline
numberOfLines={4}
maxLength={255}
onEndEditing={() => {
descriptionRef.current?.blur();
}}
returnKeyType="done"
/>
</View>
</Dialog>
);
};
const styles = StyleSheet.create({
dialogContainer: {
borderTopRightRadius: 15,
borderTopLeftRadius: 15,
backgroundColor: "white",
padding: 0,
paddingTop: 3,
margin: 0,
},
topBtns: {},
topBtn: {
backgroundColor: "white",
color: "#05a8b6",
},
title: {
fontSize: 22,
fontFamily: "Manrope_500Medium",
},
description: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
textAlignVertical: "top",
},
});
export default AddFeedback;

View File

@ -0,0 +1,196 @@
import React, { useEffect, useRef, useState } from "react";
import {
Button,
Dialog,
View,
Text,
TextField,
TouchableOpacity,
TextFieldRef,
} from "react-native-ui-lib";
import { Dimensions, StyleSheet } from "react-native";
import { PanningDirectionsEnum } from "react-native-ui-lib/src/incubator/panView";
import PenIcon from "@/assets/svgs/PenIcon";
import BinIcon from "@/assets/svgs/BinIcon";
import DropModalIcon from "@/assets/svgs/DropModalIcon";
import CloseXIcon from "@/assets/svgs/CloseXIcon";
import NavCalendarIcon from "@/assets/svgs/NavCalendarIcon";
import NavToDosIcon from "@/assets/svgs/NavToDosIcon";
import RemindersIcon from "@/assets/svgs/RemindersIcon";
import MenuIcon from "@/assets/svgs/MenuIcon";
import { IFeedback, useFeedbackContext } from "@/contexts/FeedbackContext";
import FeedbackDialog from "./FeedbackDialog";
const EditFeedback = (props: {
item: IFeedback;
isVisible: boolean;
setIsVisible: (value: boolean) => void;
}) => {
const { updateFeedback, deleteFeedback } = useFeedbackContext();
const [text, setText] = useState<string>(props.item.text);
const [modalVisible, setModalVisible] = useState<boolean>(false);
const textRef = useRef<TextFieldRef>(null);
const { width } = Dimensions.get("screen");
useEffect(() => {
setText(props.item.text);
}, []);
useEffect(() => {
if (props.isVisible) {
setTimeout(() => {
textRef?.current?.focus();
}, 500);
}
}, [props.isVisible]);
const showConfirmationDialog = () => {
setModalVisible(true);
};
const handleDeleteNote = () => {
deleteFeedback(props.item.id);
};
const hideConfirmationDialog = () => {
setModalVisible(false);
};
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => props.setIsVisible(false)}
containerStyle={{
borderRadius: 15,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
backgroundColor: "white",
width: "100%",
alignSelf: "stretch",
padding: 10,
paddingTop: 3,
margin: 0,
}}
visible={props.isVisible}
>
<View center paddingT-8>
<TouchableOpacity onPress={() => props.setIsVisible(false)}>
<DropModalIcon />
</TouchableOpacity>
</View>
<View row spread paddingH-10 paddingB-15>
<Button
color="#05a8b6"
style={styles.topBtn}
iconSource={() => <CloseXIcon />}
onPress={() => {
props.setIsVisible(false);
}}
/>
<View row>
<Button
style={styles.topBtn}
marginR-10
iconSource={() => <PenIcon />}
onPress={() => {
console.log("selview");
updateFeedback(props.item.id, { text: text });
props.setIsVisible(false);
}}
/>
<Button
style={styles.topBtn}
marginL-5
iconSource={() => <BinIcon />}
onPress={() => {
showConfirmationDialog();
}}
/>
</View>
</View>
<View centerH>
<Text style={styles.title}>{props.item.title} </Text>
</View>
<View style={styles.divider} />
<View row gap-5 paddingR-20>
<View paddingT-8 marginR-5>
<MenuIcon width={20} height={12} />
</View>
<TextField
textAlignVertical="top"
multiline
style={styles.description}
placeholder="Add description"
numberOfLines={3}
value={text}
onChangeText={(value) => {
setText(value);
}}
ref={textRef}
returnKeyType="done"
/>
</View>
<View style={styles.divider} />
<FeedbackDialog
visible={modalVisible}
title={props.item.title}
onDismiss={hideConfirmationDialog}
onConfirm={handleDeleteNote}
/>
</Dialog>
);
};
const styles = StyleSheet.create({
divider: { height: 1, backgroundColor: "#e4e4e4", marginVertical: 15 },
gradient: {
height: "25%",
position: "absolute",
bottom: 0,
width: "100%",
},
buttonContainer: {
position: "absolute",
bottom: 25,
width: "100%",
},
button: {
backgroundColor: "rgb(253, 23, 117)",
paddingVertical: 20,
},
topBtn: {
backgroundColor: "white",
color: "#05a8b6",
marginTop: -3,
},
rotateSwitch: {
marginLeft: 35,
marginBottom: 10,
marginTop: 25,
},
optionsReg: {
fontSize: 16,
fontFamily: "PlusJakartaSans_400Regular",
},
optionsBold: {
fontSize: 16,
fontFamily: "PlusJakartaSans_600SemiBold",
},
optionsIcon: {
marginRight: 10,
},
title: {
fontSize: 22,
fontFamily: "Manrope_500Medium",
},
description: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
},
});
export default EditFeedback;

View File

@ -0,0 +1,50 @@
import { View, Text } from "react-native-ui-lib";
import React, { useState } from "react";
import {
TouchableWithoutFeedback,
} from "react-native-gesture-handler";
import { IFeedback } from "@/contexts/FeedbackContext";
import EditFeedback from "./EditFeedback";
const Feedback = (props: { item: IFeedback }) => {
const [isVisible, setIsVisible] = useState<boolean>(false);
return (
<View>
<TouchableWithoutFeedback onPress={() => setIsVisible(true)}>
<View
backgroundColor="white"
marginV-5
paddingH-13
paddingV-10
style={{ borderRadius: 15, elevation: 2 }}
>
<Text
text70B
style={{ fontSize: 15, fontFamily: "Manrope_600SemiBold" }}
marginB-8
>
{props.item.title}
</Text>
<Text
text70
style={{
fontSize: 13,
fontFamily: "Manrope_400Regular",
color: "#5c5c5c",
}}
>
{props.item.text}
</Text>
</View>
</TouchableWithoutFeedback>
<EditFeedback
item={props.item}
isVisible={isVisible}
setIsVisible={setIsVisible}
/>
</View>
);
};
export default Feedback;

View File

@ -0,0 +1,81 @@
import React from "react";
import { Dialog, Button, Text, View } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
interface FeedbackDialogProps {
visible: boolean;
title: string;
onDismiss: () => void;
onConfirm: () => void;
}
const FeedbackDialog: React.FC<FeedbackDialogProps> = ({
visible,
title,
onDismiss,
onConfirm,
}) => {
return (
<Dialog
visible={visible}
onDismiss={onDismiss}
containerStyle={styles.dialog}
>
<Text center style={styles.title}>
Delete Note
</Text>
<View center>
<Text style={styles.text} center>
Are you sure you want to delete this feedback? {"\n\n"}
<Text style={{ fontSize: 16, fontFamily: "PlusJakartaSans_700Bold" }}>
{title}
</Text>
</Text>
</View>
<View row right gap-8>
<Button
label="Cancel"
onPress={onDismiss}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={onConfirm}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</Dialog>
);
};
// Empty stylesheet for future styles
const styles = StyleSheet.create({
confirmBtn: {
backgroundColor: "#ea156d",
},
cancelBtn: {
backgroundColor: "white",
},
dialog: {
backgroundColor: "white",
paddingHorizontal: 25,
paddingTop: 35,
paddingBottom: 17,
borderRadius: 20,
},
title: {
fontFamily: "Manrope_600SemiBold",
fontSize: 22,
marginBottom: 20,
},
text: {
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
marginBottom: 25,
},
});
export default FeedbackDialog;

View File

@ -0,0 +1,35 @@
import { View } from "react-native-ui-lib";
import React from "react";
import { FlatList } from "react-native";
import { useFeedbackContext } from "@/contexts/FeedbackContext";
import Feedback from "./Feedback";
const FeedbackList = (props: { searchText: string }) => {
const { feedbacks } = useFeedbackContext();
const filteredBrainDumps =
props.searchText.trim() === ""
? feedbacks
: feedbacks.filter(
(item) =>
item.title.toLowerCase().includes(props.searchText.toLowerCase()) ||
item.text
.toLowerCase()
.includes(props.searchText.toLowerCase())
);
return (
<View marginB-70>
<FlatList
style={{ zIndex: -1 }}
data={filteredBrainDumps}
keyExtractor={(item) => item.title}
renderItem={({ item }) => (
<Feedback key={item.title} item={item} />
)}
/>
</View>
);
};
export default FeedbackList;

View File

@ -0,0 +1,120 @@
import {Dimensions, ScrollView, StyleSheet} from "react-native";
import React, {useState} from "react";
import {Button, Text, TextField, View} from "react-native-ui-lib";
import HeaderTemplate from "@/components/shared/HeaderTemplate";
import {Feather, MaterialIcons} from "@expo/vector-icons";
import LinearGradient from "react-native-linear-gradient";
import PlusIcon from "@/assets/svgs/PlusIcon";
import AddFeedback from "./AddFeedback";
import FeedbackList from "./FeedbackList";
const FeedbackPage = () => {
const [searchText, setSearchText] = useState<string>("");
const [isAddVisible, setIsAddVisible] = useState<boolean>(false);
return (
<View height={"100%"}>
<View>
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
>
<View marginH-25>
<HeaderTemplate
message={"Welcome to your Feedback!"}
isWelcome={false}
children={
<Text
style={{fontFamily: "Manrope_400Regular", fontSize: 14}}
>
Drop your feedback here, and{"\n"}organize it later.
</Text>
}
/>
<View>
<View style={styles.searchField} centerV>
<TextField
value={searchText}
onChangeText={(value) => {
setSearchText(value);
}}
leadingAccessory={
<Feather
name="search"
size={24}
color="#9b9b9b"
style={{paddingRight: 10}}
/>
}
style={{
fontFamily: "Manrope_500Medium",
fontSize: 15,
}}
placeholder="Search your feedbacks..."
/>
</View>
<FeedbackList searchText={searchText}/>
</View>
</View>
</ScrollView>
</View>
<LinearGradient
colors={["#f9f8f700", "#f9f8f7"]}
locations={[0,1]}
style={{
position: "absolute",
bottom: 0,
height: 120,
width: Dimensions.get("screen").width,
justifyContent:'center',
alignItems:"center"
}}
>
<Button
style={{
height: 40,
position: "relative",
width: "90%",
bottom: -10,
borderRadius: 30,
backgroundColor: "#fd1775",
}}
color="white"
enableShadow
onPress={() => {
setIsAddVisible(true);
}}
>
<View row centerV centerH>
<PlusIcon />
<Text
white
style={{fontSize: 16, fontFamily: "Manrope_600SemiBold", marginLeft: 5}}
>
New
</Text>
</View>
</Button>
</LinearGradient>
<AddFeedback
addFeedbackProps={{
isVisible: isAddVisible,
setIsVisible: setIsAddVisible,
}}
/>
</View>
);
};
const styles = StyleSheet.create({
searchField: {
borderWidth: 0.7,
borderColor: "#9b9b9b",
borderRadius: 15,
height: 42,
paddingLeft: 10,
marginVertical: 20,
},
});
export default FeedbackPage;

View File

@ -1,96 +1,88 @@
import { StyleSheet } from "react-native";
import React, { useState } from "react";
import {
Button,
Colors,
Dialog,
Drawer,
Text,
View,
PanningProvider,
} from "react-native-ui-lib";
import { useGroceryContext } from "@/contexts/GroceryContext";
import { FontAwesome6 } from "@expo/vector-icons";
interface AddGroceryItemProps {
visible: boolean;
onClose: () => void;
}
const AddGroceryItem = () => {
const { isAddingGrocery, setIsAddingGrocery } = useGroceryContext();
const [visible, setVisible] = useState<boolean>(false);
import {Dimensions, StyleSheet} from "react-native";
import React from "react";
import {Button, View,} from "react-native-ui-lib";
import {useGroceryContext} from "@/contexts/GroceryContext";
import {FontAwesome6} from "@expo/vector-icons";
import PlusIcon from "@/assets/svgs/PlusIcon";
const handleShowDialog = () => {
setVisible(true);
};
const handleHideDialog = () => {
setVisible(false);
};
return (
<View
row
spread
paddingH-25
style={{
position: "absolute",
bottom: 20,
width: "100%",
height: 60,
}}
>
<View style={styles.btnContainer} row>
<Button
color="white"
backgroundColor="#fd1775"
label="Add item"
text70L
iconSource={() => <FontAwesome6 name="add" size={18} color="white" />}
style={styles.finishShopBtn}
labelStyle={styles.addBtnLbl}
enableShadow
onPress={() => {
setIsAddingGrocery(true);
}}
/>
</View>
</View>
);
const { width } = Dimensions.get("screen");
const AddGroceryItem = () => {
const {setIsAddingGrocery} = useGroceryContext();
return (
<View
row
spread
paddingH-20
style={{
position: "absolute",
bottom: 15,
width: "100%",
height: 53.26,
}}
>
<View style={styles.btnContainer} row>
<Button
color="white"
backgroundColor="#fd1775"
label="Add item"
text70L
iconSource={() => <PlusIcon />}
style={styles.finishShopBtn}
labelStyle={styles.addBtnLbl}
enableShadow
onPress={() => {
setIsAddingGrocery(true);
}}
/>
</View>
</View>
);
};
export default AddGroceryItem;
const styles = StyleSheet.create({
container: {
paddingVertical: 10,
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
},
inner: {
paddingHorizontal: 20,
display: "flex",
flexDirection: "column",
},
title: {
fontSize: 20,
fontWeight: "400",
textAlign: "center",
},
divider: {
width: "100%",
height: 1,
backgroundColor: "#E0E0E0",
marginVertical: 10,
},
btnContainer: {
width: "100%",
justifyContent: "center",
},
finishShopBtn: {
width: "100%",
},
shoppingBtn: {
flex: 1,
marginHorizontal: 3,
},
addBtnLbl: { fontFamily: "Manrope_500Medium", fontSize: 17, marginLeft: 5 },
container: {
paddingVertical: 10,
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
},
inner: {
paddingHorizontal: 20,
display: "flex",
flexDirection: "column",
},
title: {
fontSize: 20,
fontWeight: "400",
textAlign: "center",
},
divider: {
width: "100%",
height: 1,
backgroundColor: "#E0E0E0",
marginVertical: 10,
},
btnContainer: {
position:"absolute",
bottom: 30,
width: width,
padding: 20,
paddingBottom: 0,
justifyContent: "center",
alignItems:"center",
zIndex: 10,
},
finishShopBtn: {
width: "100%",
height: 53.26,
},
shoppingBtn: {
flex: 1,
marginHorizontal: 3,
},
addBtnLbl: {fontFamily: "Manrope_500Medium", fontSize: 17, marginLeft: 5},
});

View File

@ -1,11 +1,11 @@
import { Text, View } from "react-native-ui-lib";
import React, { useEffect, useRef, useState } from "react";
import { TextField, TextFieldRef } from "react-native-ui-lib";
import { Text, TextField, TextFieldRef, View } from "react-native-ui-lib";
import React, { useEffect, useRef } from "react";
import { GroceryCategory, useGroceryContext } from "@/contexts/GroceryContext";
import { Dropdown } from "react-native-element-dropdown";
import CloseXIcon from "@/assets/svgs/CloseXIcon";
import { StyleSheet } from "react-native";
import { findNodeHandle, StyleSheet, UIManager } from "react-native";
import DropdownIcon from "@/assets/svgs/DropdownIcon";
import { AntDesign } from "@expo/vector-icons";
interface IEditGrocery {
id?: string;
@ -14,13 +14,41 @@ interface IEditGrocery {
setTitle: (value: string) => void;
setCategory?: (category: GroceryCategory) => void;
setSubmit?: (value: boolean) => void;
closeEdit?: (value: boolean) => void;
closeEdit?: () => void;
handleEditSubmit?: Function;
}
const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
const EditGroceryItem = ({
editGrocery,
onInputFocus,
}: {
editGrocery: IEditGrocery;
onInputFocus: (y: number) => void;
}) => {
const { fuzzyMatchGroceryCategory } = useGroceryContext();
const inputRef = useRef<TextFieldRef>(null);
const containerRef = useRef(null);
const handleFocus = () => {
if (containerRef.current) {
const handle = findNodeHandle(containerRef.current);
if (handle) {
UIManager.measure(
handle,
(
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number
) => {
onInputFocus(pageY);
}
);
}
}
};
const groceryCategoryOptions = Object.values(GroceryCategory).map(
(category) => ({
@ -29,15 +57,35 @@ const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
})
);
const handleSubmit = () => {
inputRef?.current?.blur();
console.log("CALLLLLL");
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();
}
};
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus(); // Focus on the TextField
inputRef.current.focus();
}
console.log(editGrocery.category);
}, []);
return (
<View
ref={containerRef}
style={{
backgroundColor: "white",
width: "100%",
@ -50,48 +98,53 @@ const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
<View row spread centerV>
<TextField
text70T
style={{}}
ref={inputRef}
onFocus={handleFocus}
placeholder="Grocery"
value={editGrocery.title}
onSubmitEditing={handleSubmit}
numberOfLines={1}
returnKeyType="done"
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);
let groceryCategory = fuzzyMatchGroceryCategory(value);
if (editGrocery.setCategory) {
editGrocery.setCategory(groceryCategory);
}
}}
maxLength={25}
/>
<CloseXIcon
onPress={() => {
if (editGrocery.closeEdit) editGrocery.closeEdit(false);
}}
/>
<View row centerV>
<AntDesign
name="check"
size={24}
style={{
color: "green",
marginRight: 15,
}}
onPress={handleSubmit}
/>
<CloseXIcon
onPress={() => {
if (editGrocery.closeEdit) {
editGrocery.closeEdit();
}
}}
/>
</View>
</View>
<Dropdown
style={{marginTop: 15}}
style={{ marginTop: 15 }}
data={groceryCategoryOptions}
placeholder="Select grocery category"
placeholderStyle={{ color: "#a2a2a2", fontFamily: "Manrope_500Medium", fontSize: 13.2 }}
placeholderStyle={{
color: "#a2a2a2",
fontFamily: "Manrope_500Medium",
fontSize: 13.2,
}}
labelField="label"
valueField="value"
value={
editGrocery.category == GroceryCategory.None
? null
: editGrocery.category
}
value={editGrocery.category}
iconColor="white"
activeColor={"#fd1775"}
containerStyle={styles.dropdownStyle}
@ -99,7 +152,14 @@ const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
itemContainerStyle={styles.itemStyle}
selectedTextStyle={styles.selectedText}
renderLeftIcon={() => (
<DropdownIcon style={{ marginRight: 8 }} color={editGrocery.category == GroceryCategory.None ? "#7b7b7b" : "#fd1775"} />
<DropdownIcon
style={{ marginRight: 8 }}
color={
editGrocery.category == GroceryCategory.None
? "#7b7b7b"
: "#fd1775"
}
/>
)}
renderItem={(item) => {
return (
@ -114,8 +174,11 @@ const EditGroceryItem = ({ editGrocery }: { editGrocery: IEditGrocery }) => {
id: editGrocery.id,
category: item.value,
});
console.log("kategorija vo diropdown: " + item.value);
if (editGrocery.closeEdit) editGrocery.closeEdit(false);
if (editGrocery.closeEdit) editGrocery.closeEdit();
} else {
if (editGrocery.setCategory) {
editGrocery.setCategory(item.value);
}
}
}}
/>

View File

@ -8,24 +8,33 @@ import { ImageBackground, StyleSheet } from "react-native";
import { IGrocery } from "@/hooks/firebase/types/groceryData";
import firestore from "@react-native-firebase/firestore";
import { UserProfile } from "@/hooks/firebase/types/profileTypes";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
const GroceryItem = ({
item,
handleItemApproved,
onInputFocus,
}: {
item: IGrocery;
handleItemApproved: (id: string, changes: Partial<IGrocery>) => void;
onInputFocus: (y: number) => void;
}) => {
const { updateGroceryItem } = useGroceryContext();
const { profileData } = useAuthContext();
const isParent = profileData?.userType === ProfileType.PARENT;
const [openFreqEdit, setOpenFreqEdit] = useState<boolean>(false);
const [isEditingTitle, setIsEditingTitle] = useState<boolean>(false);
const [newTitle, setNewTitle] = useState<string>("");
const [newTitle, setNewTitle] = useState<string>(item.title ?? "");
const [category, setCategory] = useState<GroceryCategory>(
GroceryCategory.None
item.category ?? GroceryCategory.None
);
const [itemCreator, setItemCreator] = useState<UserProfile>(null);
const closeEdit = () => {
setIsEditingTitle(false);
};
const handleTitleChange = (newTitle: string) => {
updateGroceryItem({ id: item?.id, title: newTitle });
};
@ -35,7 +44,6 @@ const GroceryItem = ({
};
useEffect(() => {
setNewTitle(item.title);
console.log(item);
getItemCreator(item?.creatorId);
}, []);
@ -53,6 +61,10 @@ const GroceryItem = ({
}
};
const getInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`;
};
return (
<View
key={item.id}
@ -61,6 +73,8 @@ const GroceryItem = ({
marginVertical: 5,
paddingHorizontal: isEditingTitle ? 0 : 13,
paddingVertical: isEditingTitle ? 0 : 10,
height: 44.64,
backgroundColor: item.bought ? "#cbcbcb" : "white",
}}
backgroundColor="white"
centerV
@ -74,54 +88,83 @@ const GroceryItem = ({
setOpenFreqEdit(false);
}}
/>
{!isEditingTitle ? (
<View>
<TouchableOpacity onPress={() => setIsEditingTitle(true)}>
<Text text70T black style={styles.title}>
{item.title}
</Text>
</TouchableOpacity>
</View>
) : (
{isEditingTitle ? (
<EditGroceryItem
editGrocery={{
id: item.id,
title: newTitle,
category: item.category,
category: category,
setTitle: setNewTitle,
setCategory: setCategory,
closeEdit: setIsEditingTitle,
closeEdit: closeEdit,
handleEditSubmit: updateGroceryItem,
}}
onInputFocus={onInputFocus}
/>
) : (
<View>
{isParent ? (
<TouchableOpacity onPress={() => setIsEditingTitle(true)}>
<Text
text70T
black
style={[
styles.title,
{
textDecorationLine: item.bought ? "line-through" : "none",
},
]}
>
{item.title}
</Text>
</TouchableOpacity>
) : (
<Text
text70T
black
style={[styles.title, { color: item.bought ? "red" : "black" }]}
>
{item.title}
</Text>
)}
</View>
)}
{!item.approved ? (
<View row centerV marginB-10>
<AntDesign
name="check"
size={24}
style={{
color: item.approved ? "green" : "#aaaaaa",
marginRight: 15,
}}
onPress={() => {
handleItemApproved(item.id, { approved: true });
}}
/>
<AntDesign
name="close"
size={24}
style={{ color: item.approved ? "#aaaaaa" : "red" }}
onPress={() => {
handleItemApproved(item.id, { approved: false });
}}
/>
{isParent && (
<>
<AntDesign
name="check"
size={24}
style={{
color: "green",
marginRight: 15,
}}
onPress={
isParent
? () => handleItemApproved(item.id, { approved: true })
: null
}
/>
<AntDesign
name="close"
size={24}
style={{ color: "red" }}
onPress={
isParent
? () => handleItemApproved(item.id, { approved: false })
: null
}
/>
</>
)}
</View>
) : (
!isEditingTitle && (
!isEditingTitle &&
isParent && (
<Checkbox
value={item.bought}
containerStyle={[styles.checkbox, {borderRadius: 50}]}
containerStyle={[styles.checkbox, { borderRadius: 50 }]}
style={styles.checked}
borderRadius={50}
color="#fd1575"
@ -139,17 +182,49 @@ const GroceryItem = ({
<View height={0.7} backgroundColor="#e7e7e7" width={"98%"} />
</View>
<View paddingL-0 paddingT-12 flexS row centerV>
<ImageBackground
style={{
width: 22.36,
aspectRatio: 1,
borderRadius: 50,
backgroundColor: "red",
marginRight: 10,
overflow: "hidden",
}}
source={require("../../../assets/images/child-picture.png")}
/>
{profileData?.pfp ? (
<ImageBackground
source={require("../../../assets/images/child-picture.png")}
style={{
height: 24.64,
aspectRatio: 1,
borderRadius: 22,
overflow: "hidden",
}}
/>
) : (
<View
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",
}}
>
{itemCreator
? getInitials(itemCreator.firstName, itemCreator.lastName)
: ""}
</Text>
</View>
</View>
)}
<Text color="#858585" style={styles.authorTxt}>
Requested by {itemCreator?.firstName}
</Text>

View File

@ -1,298 +1,298 @@
import { FlatList, StyleSheet } from "react-native";
import React, { useEffect, useState } from "react";
import { Button, Text, TouchableOpacity, View } from "react-native-ui-lib";
import {FlatList, StyleSheet} from "react-native";
import React, {useEffect, useState} from "react";
import {Text, TouchableOpacity, View} from "react-native-ui-lib";
import GroceryItem from "./GroceryItem";
import {
GroceryCategory,
GroceryFrequency,
useGroceryContext,
} from "@/contexts/GroceryContext";
import {GroceryCategory, GroceryFrequency, useGroceryContext,} from "@/contexts/GroceryContext";
import HeaderTemplate from "@/components/shared/HeaderTemplate";
import { AntDesign, MaterialIcons } from "@expo/vector-icons";
import {AntDesign} from "@expo/vector-icons";
import EditGroceryItem from "./EditGroceryItem";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { IGrocery } from "@/hooks/firebase/types/groceryData";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import {IGrocery} from "@/hooks/firebase/types/groceryData";
import AddPersonIcon from "@/assets/svgs/AddPersonIcon";
const GroceryList = () => {
const {
groceries,
updateGroceryItem,
isAddingGrocery,
setIsAddingGrocery,
addGrocery,
} = useGroceryContext();
const { profileData } = useAuthContext();
const [approvedGroceries, setapprovedGroceries] = useState<IGrocery[]>(
groceries?.filter((item) => item.approved === true)
);
const [pendingGroceries, setPendingGroceries] = useState<IGrocery[]>(
groceries?.filter((item) => item.approved !== true)
);
const [category, setCategory] = useState<GroceryCategory>(
GroceryCategory.None
);
const [title, setTitle] = useState<string>("");
const [submit, setSubmitted] = useState<boolean>(false);
const GroceryList = ({onInputFocus}: {onInputFocus: (y: number) => void}) => {
const {
groceries,
updateGroceryItem,
isAddingGrocery,
setIsAddingGrocery,
addGrocery,
} = useGroceryContext();
const {profileData} = useAuthContext();
const [approvedGroceries, setapprovedGroceries] = useState<IGrocery[]>(
groceries?.filter((item) => item.approved)
);
const [pendingGroceries, setPendingGroceries] = useState<IGrocery[]>(
groceries?.filter((item) => !item.approved)
);
const [category, setCategory] = useState<GroceryCategory>(
GroceryCategory.None
);
const [pendingVisible, setPendingVisible] = useState<boolean>(true);
const [approvedVisible, setApprovedVisible] = useState<boolean>(true);
const [title, setTitle] = useState<string>("");
const [submit, setSubmitted] = useState<boolean>(false);
// Group approved groceries by category
const approvedGroceriesByCategory = approvedGroceries?.reduce(
(groups: any, item: IGrocery) => {
const category = item.category || "Uncategorized";
if (!groups[category]) {
groups[category] = [];
}
groups[category].push(item);
return groups;
},
{}
);
const [pendingVisible, setPendingVisible] = useState<boolean>(true);
const [approvedVisible, setApprovedVisible] = useState<boolean>(true);
useEffect(() => {
if (submit) {
if (title?.length > 2 && title?.length <= 25) {
addGrocery({
id: "",
title: title,
category: category,
approved: profileData?.userType === ProfileType.PARENT,
recurring: false,
frequency: GroceryFrequency.Never,
bought: false,
});
// Group approved groceries by category
const approvedGroceriesByCategory = approvedGroceries?.reduce(
(groups: any, item: IGrocery) => {
const category = item.category || "Uncategorized";
if (!groups[category]) {
groups[category] = [];
}
groups[category].push(item);
return groups;
},
{}
);
setIsAddingGrocery(false);
setSubmitted(false);
setTitle("");
}
}
}, [submit]);
useEffect(() => {
if (submit) {
if (title?.length > 2 && title?.length <= 25) {
addGrocery({
id: "",
title: title,
category: category,
approved: profileData?.userType === ProfileType.PARENT,
recurring: false,
frequency: GroceryFrequency.Never,
bought: false,
});
useEffect(() => {
/**/
}, [category]);
setIsAddingGrocery(false);
setSubmitted(false);
setTitle("");
}
}
}, [submit]);
useEffect(() => {
setapprovedGroceries(groceries?.filter((item) => item.approved === true));
setPendingGroceries(groceries?.filter((item) => item.approved !== true));
}, [groceries]);
useEffect(() => {
setapprovedGroceries(groceries?.filter((item) => item.approved));
setPendingGroceries(groceries?.filter((item) => !item.approved));
}, [groceries]);
return (
<View marginH-20 marginB-20>
<HeaderTemplate
message={"Welcome to your grocery list"}
isWelcome={false}
>
<View row centerV>
<View
backgroundColor="#e2eed8"
paddingH-15
paddingV-8
marginR-5
centerV
style={{ borderRadius: 50 }}
>
<Text text70BL color="#46a80a" style={styles.counterText}>
{approvedGroceries?.length} list{" "}
{approvedGroceries?.length === 1 ? (
<Text text70BL color="#46a80a" style={styles.counterText}>
item
</Text>
) : (
<Text text70BL color="#46a80a" style={styles.counterText}>
items
</Text>
)}
</Text>
</View>
<View
backgroundColor="#faead2"
padding-8
paddingH-12
marginR-15
style={{ borderRadius: 50 }}
>
<Text text70 style={styles.counterText} color="#e28800">
{pendingGroceries?.length} pending
</Text>
</View>
<TouchableOpacity>
<AddPersonIcon width={24}/>
</TouchableOpacity>
</View>
</HeaderTemplate>
{/* Pending Approval Section */}
<View row spread marginT-40 marginB-10 centerV>
<View row centerV>
<Text style={styles.subHeader}>Pending Approval</Text>
{pendingVisible && (
<AntDesign
name="down"
size={17}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setPendingVisible(false);
}}
/>
)}
{!pendingVisible && (
<AntDesign
name="right"
size={15}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setPendingVisible(true);
}}
/>
)}
</View>
<View
centerV
style={{
aspectRatio: 1,
width: 35,
backgroundColor: "#faead2",
borderRadius: 50,
}}
>
<Text style={styles.counterNr} center color="#e28800">
{pendingGroceries?.length.toString()}
</Text>
</View>
</View>
{pendingGroceries?.length > 0
? pendingVisible && (
<FlatList
data={pendingGroceries}
renderItem={({ item }) => (
<GroceryItem
item={item}
handleItemApproved={(id, changes) =>
updateGroceryItem({ ...changes, id: id })
}
/>
)}
keyExtractor={(item) => item.id.toString()}
/>
)
: pendingVisible && (
<Text style={styles.noItemTxt}>No items pending approval.</Text>
)}
{/* Approved Section */}
<View row spread marginT-40 marginB-0 centerV>
<View row centerV>
<Text style={styles.subHeader}>Shopping List</Text>
{approvedVisible && (
<AntDesign
name="down"
size={17}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setApprovedVisible(false);
}}
/>
)}
{!approvedVisible && (
<AntDesign
name="right"
size={15}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setApprovedVisible(true);
}}
/>
)}
</View>
<View
centerV
style={{
aspectRatio: 1,
width: 35,
backgroundColor: "#e2eed8",
borderRadius: 50,
}}
>
<Text style={styles.counterNr} center color="#46a80a">
{approvedGroceries?.length.toString()}
</Text>
</View>
</View>
{isAddingGrocery && (
<EditGroceryItem
editGrocery={{
title: title,
setCategory: setCategory,
category: category,
setTitle: setTitle,
setSubmit: setSubmitted,
}}
/>
)}
{/* Render Approved Groceries Grouped by Category */}
{approvedGroceries?.length > 0
? approvedVisible && (
<FlatList
data={Object.keys(approvedGroceriesByCategory)}
renderItem={({ item: category }) => (
<View key={category}>
{/* Render Category Header */}
<Text text80M style={{ marginTop: 10 }} color="#666">
{category}
</Text>
{/* Render Grocery Items for this Category */}
{approvedGroceriesByCategory[category].map(
(grocery: IGrocery) => (
<GroceryItem
key={grocery.id}
item={grocery}
handleItemApproved={(id, changes) =>
updateGroceryItem({ ...changes, id: id })
}
/>
)
)}
return (
<View marginH-20 marginB-45>
<HeaderTemplate
message={"Welcome to your grocery list"}
isWelcome={false}
isGroceries={true}
>
<View row centerV>
<View
backgroundColor="#e2eed8"
paddingH-15
paddingV-8
marginR-5
centerV
style={{borderRadius: 50}}
>
<Text text70BL color="#46a80a" style={styles.counterText}>
{approvedGroceries?.length} list{" "}
{approvedGroceries?.length === 1 ? (
<Text text70BL color="#46a80a" style={styles.counterText}>
item
</Text>
) : (
<Text text70BL color="#46a80a" style={styles.counterText}>
items
</Text>
)}
</Text>
</View>
<View
backgroundColor="#faead2"
padding-8
paddingH-12
marginR-15
style={{borderRadius: 50}}
>
<Text text70 style={styles.counterText} color="#e28800">
{pendingGroceries?.length} pending
</Text>
</View>
<TouchableOpacity>
<AddPersonIcon width={24}/>
</TouchableOpacity>
</View>
)}
keyExtractor={(category) => category}
/>
)
: approvedVisible && (
<Text style={styles.noItemTxt}>No approved items.</Text>
)}
</View>
);
</HeaderTemplate>
{/* Pending Approval Section */}
<View row spread marginT-40 marginB-10 centerV>
<View row centerV>
<Text style={styles.subHeader}>Pending Approval</Text>
{pendingVisible && (
<AntDesign
name="down"
size={17}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setPendingVisible(false);
}}
/>
)}
{!pendingVisible && (
<AntDesign
name="right"
size={15}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setPendingVisible(true);
}}
/>
)}
</View>
<View
centerV
style={{
aspectRatio: 1,
width: 35,
backgroundColor: "#faead2",
borderRadius: 50,
}}
>
<Text style={styles.counterNr} center color="#e28800">
{pendingGroceries?.length.toString()}
</Text>
</View>
</View>
{pendingGroceries?.length > 0
? pendingVisible && (
<FlatList
data={pendingGroceries}
renderItem={({item}) => (
<GroceryItem
item={item}
handleItemApproved={(id, changes) =>
updateGroceryItem({...changes, id: id})
}
onInputFocus={onInputFocus}
/>
)}
keyExtractor={(item) => item.id.toString()}
/>
)
: pendingVisible && (
<Text style={styles.noItemTxt}>No items pending approval.</Text>
)}
{/* Approved Section */}
<View row spread marginT-40 marginB-0 centerV>
<View row centerV>
<Text style={styles.subHeader}>Shopping List</Text>
{approvedVisible && (
<AntDesign
name="down"
size={17}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setApprovedVisible(false);
}}
/>
)}
{!approvedVisible && (
<AntDesign
name="right"
size={15}
style={styles.dropIcon}
color="#9f9f9f"
onPress={() => {
setApprovedVisible(true);
}}
/>
)}
</View>
<View
centerV
style={{
aspectRatio: 1,
width: 35,
backgroundColor: "#e2eed8",
borderRadius: 50,
}}
>
<Text style={styles.counterNr} center color="#46a80a">
{approvedGroceries?.length.toString()}
</Text>
</View>
</View>
{isAddingGrocery && (
<View style={{marginTop: 8}}>
<EditGroceryItem
editGrocery={{
title: title,
setCategory: setCategory,
category: category,
setTitle: setTitle,
setSubmit: setSubmitted,
closeEdit: () => setIsAddingGrocery(false)
}}
onInputFocus={onInputFocus}
/>
</View>
)}
{/* Render Approved Groceries Grouped by Category */}
{approvedGroceries?.length > 0
? approvedVisible && (
<FlatList
data={Object.keys(approvedGroceriesByCategory)}
renderItem={({item: category}) => (
<View key={category}>
{/* Render Category Header */}
<Text text80M style={{marginTop: 10}} color="#666">
{category}
</Text>
{/* Render Grocery Items for this Category */}
{approvedGroceriesByCategory[category].map(
(grocery: IGrocery) => (
<GroceryItem
key={grocery.id}
item={grocery}
handleItemApproved={(id, changes) =>
updateGroceryItem({...changes, id: id})
}
onInputFocus={onInputFocus}
/>
)
)}
</View>
)}
keyExtractor={(category) => category}
/>
)
: approvedVisible && (
<Text style={styles.noItemTxt}>No approved items.</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
dropIcon: {
marginHorizontal: 10,
},
noItemTxt: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
},
counterText: {
fontSize: 14,
fontFamily: "PlusJakartaSans_600SemiBold",
},
subHeader: {
fontSize: 15,
fontFamily: "Manrope_700Bold",
},
counterNr: {
fontFamily: "PlusJakartaSans_600SemiBold",
fontSize: 14
}
dropIcon: {
marginHorizontal: 10,
},
noItemTxt: {
fontFamily: "Manrope_400Regular",
fontSize: 14,
},
counterText: {
fontSize: 14,
fontFamily: "PlusJakartaSans_600SemiBold",
},
subHeader: {
fontSize: 15,
fontFamily: "Manrope_700Bold",
},
counterNr: {
fontFamily: "PlusJakartaSans_600SemiBold",
fontSize: 14
}
});
export default GroceryList;

View File

@ -1,38 +1,79 @@
import { Text, ScrollView } from "react-native";
import { Dimensions, ScrollView, Keyboard, Platform } from "react-native";
import { View } from "react-native-ui-lib";
import React, { useEffect, useRef } from "react";
import React, { useEffect, useRef, useState } from "react";
import AddGroceryItem from "./AddGroceryItem";
import GroceryList from "./GroceryList";
import { useGroceryContext } from "@/contexts/GroceryContext";
const GroceryWrapper = () => {
const { isAddingGrocery } = useGroceryContext();
const scrollViewRef = useRef<ScrollView>(null); // Reference to the ScrollView
const scrollViewRef = useRef<ScrollView>(null);
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const keyboardWillShowListener = Keyboard.addListener(
Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
(e) => {
setKeyboardHeight(e.endCoordinates.height);
}
);
const keyboardWillHideListener = Keyboard.addListener(
Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
() => {
setKeyboardHeight(0);
}
);
return () => {
keyboardWillShowListener.remove();
keyboardWillHideListener.remove();
};
}, []);
useEffect(() => {
if (isAddingGrocery && scrollViewRef.current) {
scrollViewRef.current.scrollTo({
y: 400, // Adjust this value to scroll a bit down (100 is an example)
y: 400,
animated: true,
});
}
}, [isAddingGrocery]);
const handleInputFocus = (y: number) => {
if (scrollViewRef.current) {
// Get the window height
const windowHeight = Dimensions.get('window').height;
// Calculate the space we want to leave at the top
const topSpacing = 20;
// Calculate the target scroll position:
// y (position of input) - topSpacing (space we want at top)
// if keyboard is shown, we need to account for its height
const scrollPosition = Math.max(0, y - topSpacing);
scrollViewRef.current.scrollTo({
y: scrollPosition,
animated: true,
});
}
};
return (
<View height={"100%"} paddingT-15 paddingH-15>
<View height={"100%"}>
<ScrollView
ref={scrollViewRef} // Assign the ref to the ScrollView
automaticallyAdjustKeyboardInsets={true}
>
<View marginB-70>
<GroceryList />
</View>
</ScrollView>
<>
<ScrollView
ref={scrollViewRef}
automaticallyAdjustKeyboardInsets={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
>
<View marginB-60>
<GroceryList onInputFocus={handleInputFocus} />
</View>
</ScrollView>
{!isAddingGrocery && <AddGroceryItem />}
</View>
</View>
</>
);
};
export default GroceryWrapper;
export default GroceryWrapper;

View File

@ -8,7 +8,7 @@ const Entry = () => {
const [tab, setTab] = useState<"register" | "login" | "reset-password">("login");
return (
<View>
<View style={{height:"100%"}}>
{tab === "register" && <SignUpPage setTab={setTab}/>}
{tab === "login" && <SignInPage setTab={setTab}/>}
{tab === "reset-password" && <ResetPasswordPage setTab={setTab}/>}

View File

@ -1,11 +1,9 @@
import {Button, ButtonSize, Text, TextField, View} from "react-native-ui-lib";
import {Button, Text, TextField, View} from "react-native-ui-lib";
import React, {useState} from "react";
import {useSignIn} from "@/hooks/firebase/useSignIn";
import {StyleSheet} from "react-native";
import {useResetPassword} from "@/hooks/firebase/useResetPassword";
import {isLoading} from "expo-font";
export const ResetPasswordPage = ({setTab}: { setTab: React.Dispatch<React.SetStateAction<"register" | "login" | "reset-password">> }) => {
export const ResetPasswordPage = () => {
const [email, setEmail] = useState<string>("");
const {mutateAsync: resetPassword, error, isError, isLoading} = useResetPassword();

View File

@ -1,170 +1,193 @@
import {Button, ButtonSize, Dialog, Text, TextField, View} from "react-native-ui-lib";
import React, {useState} from "react";
import {useSignIn} from "@/hooks/firebase/useSignIn";
import {StyleSheet} from "react-native";
import Toast from 'react-native-toast-message';
import {useLoginWithQrCode} from "@/hooks/firebase/useLoginWithQrCode";
import {Camera, CameraView} from 'expo-camera';
import {
Button,
ButtonSize,
Colors,
KeyboardAwareScrollView,
LoaderScreen,
Text,
TextField,
TextFieldRef,
View,
} from "react-native-ui-lib";
import React, { useRef, useState } from "react";
import { useSignIn } from "@/hooks/firebase/useSignIn";
import { KeyboardAvoidingView, Platform, StyleSheet } from "react-native";
import Toast from "react-native-toast-message";
import KeyboardManager from "react-native-keyboard-manager";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
const SignInPage = ({setTab}: {
setTab: React.Dispatch<React.SetStateAction<"register" | "login" | "reset-password">>
}) => {
const [email, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const [showCameraDialog, setShowCameraDialog] = useState<boolean>(false);
if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(true);
const {mutateAsync: signIn, error, isError} = useSignIn();
const {mutateAsync: signInWithQrCode} = useLoginWithQrCode()
const SignInPage = () => {
const [email, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const passwordRef = useRef<TextFieldRef>(null);
const handleSignIn = async () => {
await signIn({email, password});
if (!isError) {
Toast.show({
type: "success",
text1: "Login successful!"
});
} else {
Toast.show({
type: "error",
text1: "Error logging in",
text2: `${error}`
});
}
};
const { mutateAsync: signIn, error, isError, isLoading } = useSignIn();
const handleQrCodeScanned = async ({data}: { data: string }) => {
setShowCameraDialog(false);
try {
await signInWithQrCode({userId: data});
Toast.show({
type: "success",
text1: "Login successful with QR code!"
});
} catch (err) {
Toast.show({
type: "error",
text1: "Error logging in with QR code",
text2: `${err}`
});
}
};
const router = useRouter();
const getCameraPermissions = async (callback: () => void) => {
const {status} = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
if (status === 'granted') {
callback();
}
};
const handleSignIn = async () => {
await signIn({ email, password });
if (!isError) {
Toast.show({
type: "success",
text1: "Login successful!",
});
} else {
Toast.show({
type: "error",
text1: "Error logging in",
text2: `${error}`,
});
}
};
return (
<View padding-10 centerV height={"100%"}>
return (
<SafeAreaView style={{ flex: 1 }}>
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1 }}
enableOnAndroid
>
<View
style={{ flex: 1, padding: 21, paddingBottom: 45, paddingTop: "20%" }}
>
<View gap-13 width={"100%"} marginB-20>
<Text style={{ fontSize: 40, fontFamily: "Manrope_600SemiBold" }}>
Jump back into Cally
</Text>
<Text color={"#919191"} style={{ fontSize: 20 }}>
Please enter your details.
</Text>
</View>
<KeyboardAvoidingView
style={{ width: "100%" }}
contentContainerStyle={{ justifyContent: "center" }}
keyboardVerticalOffset={50}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<TextField
placeholder="Email"
value={email}
onChangeText={setEmail}
style={styles.textfield}
placeholder="Email"
keyboardType={"email-address"}
returnKeyType={"next"}
textContentType={"emailAddress"}
defaultValue={email}
onChangeText={setEmail}
style={styles.textfield}
autoComplete={"email"}
autoCorrect={false}
onSubmitEditing={() => {
// Move focus to the description field
passwordRef.current?.focus();
}}
/>
<TextField
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
style={styles.textfield}
ref={passwordRef}
placeholder="Password"
textContentType={"oneTimeCode"}
value={password}
onChangeText={setPassword}
secureTextEntry
style={styles.textfield}
autoCorrect={false}
/>
</KeyboardAvoidingView>
<View flexG />
<Button
label="Log in"
marginT-50
labelStyle={{
fontFamily: "PlusJakartaSans_600SemiBold",
fontSize: 16,
}}
onPress={handleSignIn}
style={{ marginBottom: 20, height: 50 }}
backgroundColor="#fd1775"
/>
{isError && (
<Text center style={{ marginBottom: 20 }}>{`${
error?.toString()?.split("]")?.[1]
}`}</Text>
)}
<View row centerH marginB-5 gap-5>
<Text style={styles.jakartaLight}>Don't have an account?</Text>
<Button
label="Login"
onPress={handleSignIn}
style={{marginBottom: 20}}
backgroundColor="#fd1775"
onPress={() => router.replace("/(unauth)/sign_up")}
label="Sign Up"
labelStyle={[
styles.jakartaMedium,
{ textDecorationLine: "none", color: "#fd1575" },
]}
link
size={ButtonSize.xSmall}
padding-0
margin-0
text70
left
color="#fd1775"
/>
<Button
label="Login with a QR Code"
onPress={() => {
getCameraPermissions(() => setShowCameraDialog(true));
}
}
style={{marginBottom: 20}}
backgroundColor="#fd1775"
</View>
{/*<View row centerH marginB-5 gap-5>*/}
{/* <Text text70>Forgot your password?</Text>*/}
{/* <Button*/}
{/* onPress={() => router.replace("/(unauth)/sign_up")}*/}
{/* label="Reset password"*/}
{/* labelStyle={[*/}
{/* styles.jakartaMedium,*/}
{/* {textDecorationLine: "none", color: "#fd1575"},*/}
{/* ]}*/}
{/* link*/}
{/* size={ButtonSize.xSmall}*/}
{/* padding-0*/}
{/* margin-0*/}
{/* text70*/}
{/* left*/}
{/* avoidInnerPadding*/}
{/* color="#fd1775"*/}
{/* />*/}
{/*</View>*/}
{isLoading && (
<LoaderScreen
overlay
message={"Signing in..."}
backgroundColor={Colors.white}
color={Colors.grey40}
/>
{isError && <Text center style={{marginBottom: 20}}>{`${error?.toString()?.split("]")?.[1]}`}</Text>}
<View row centerH marginB-5 gap-5>
<Text text70>
Don't have an account?
</Text>
<Button
onPress={() => setTab("register")}
label="Sign Up"
link
size={ButtonSize.xSmall}
padding-0
margin-0
text70
left
color="#fd1775"
/>
</View>
<View row centerH marginB-5 gap-5>
<Text text70>
Forgot your password?
</Text>
<Button
onPress={() => setTab("reset-password")}
label="Reset password"
link
size={ButtonSize.xSmall}
padding-0
margin-0
text70
left
color="#fd1775"
/>
</View>
{/* Camera Dialog */}
<Dialog
visible={showCameraDialog}
onDismiss={() => setShowCameraDialog(false)}
bottom
width="100%"
height="70%"
containerStyle={{padding: 0}}
>
{hasPermission === null ? (
<Text>Requesting camera permissions...</Text>
) : !hasPermission ? (
<Text>No access to camera</Text>
) : (
<CameraView
style={{flex: 1}}
onBarcodeScanned={handleQrCodeScanned}
barcodeScannerSettings={{
barcodeTypes: ["qr"],
}}
/>
)}
<Button
label="Cancel"
onPress={() => setShowCameraDialog(false)}
backgroundColor="#fd1775"
style={{margin: 10}}
/>
</Dialog>
)}
</View>
);
</KeyboardAwareScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
textfield: {
backgroundColor: "white",
marginVertical: 10,
padding: 30,
height: 45,
borderRadius: 50,
},
textfield: {
backgroundColor: "white",
marginVertical: 10,
padding: 30,
height: 45,
borderRadius: 50,
fontFamily: "PlusJakartaSans_300Light",
},
jakartaLight: {
fontFamily: "PlusJakartaSans_300Light",
fontSize: 16,
color: "#484848",
},
jakartaMedium: {
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
color: "#919191",
textDecorationLine: "underline",
},
});
export default SignInPage;

View File

@ -3,6 +3,9 @@ import {
Button,
ButtonSize,
Checkbox,
Colors,
KeyboardAwareScrollView,
LoaderScreen,
Text,
TextField,
TextFieldRef,
@ -10,17 +13,15 @@ import {
View,
} from "react-native-ui-lib";
import { useSignUp } from "@/hooks/firebase/useSignUp";
import { ProfileType } from "@/contexts/AuthContext";
import { StyleSheet } from "react-native";
import { KeyboardAvoidingView, Platform, StyleSheet } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import KeyboardManager from "react-native-keyboard-manager";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
const SignUpPage = ({
setTab,
}: {
setTab: React.Dispatch<
React.SetStateAction<"register" | "login" | "reset-password">
>;
}) => {
if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(true);
const SignUpPage = () => {
const [email, setEmail] = useState<string>("");
const [firstName, setFirstName] = useState<string>("");
const [lastName, setLastName] = useState<string>("");
@ -29,130 +30,212 @@ const SignUpPage = ({
const [isPasswordVisible, setIsPasswordVisible] = useState<boolean>(false);
const [allowFaceID, setAllowFaceID] = useState<boolean>(false);
const [acceptTerms, setAcceptTerms] = useState<boolean>(false);
const { mutateAsync: signUp } = useSignUp();
const { mutateAsync: signUp, isLoading } = useSignUp();
const lnameRef = useRef<TextFieldRef>(null);
const emailRef = useRef<TextFieldRef>(null);
const passwordRef = useRef<TextFieldRef>(null);
const router = useRouter();
const handleSignUp = async () => {
await signUp({ email, password, firstName, lastName });
router.replace("/(unauth)/cal_sync");
};
return (
<View padding-10 height={"100%"} flexG>
<Text text30 center>
Get started with Cally
</Text>
<Text center>Please enter your details.</Text>
<TextField
marginT-60
autoFocus
placeholder="First name"
value={firstName}
onChangeText={setFirstName}
style={styles.textfield}
onSubmitEditing={() => {lnameRef.current?.focus()}}
blurOnSubmit={false}
/>
<TextField
ref={lnameRef}
placeholder="Last name"
value={lastName}
onChangeText={setLastName}
style={styles.textfield}
onSubmitEditing={() => {emailRef.current?.focus()}}
blurOnSubmit={false}
/>
<TextField
ref={emailRef}
placeholder="Email"
value={email}
onChangeText={setEmail}
style={styles.textfield}
onSubmitEditing={() => {passwordRef.current?.focus()}}
blurOnSubmit={false}
/>
<TextField
ref={passwordRef}
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry={!isPasswordVisible}
style={styles.textfield}
trailingAccessory={
<TouchableOpacity
onPress={() => setIsPasswordVisible(!isPasswordVisible)}
>
<AntDesign
name={isPasswordVisible ? "eye" : "eyeo"}
size={24}
color="gray"
/>
</TouchableOpacity>
}
/>
<View gap-10 marginH-10>
<View row centerV>
<Checkbox
value={allowFaceID}
onValueChange={(value) => {
setAllowFaceID(value);
}}
/>
<Text text90R marginL-10>
Allow FaceID for login in future
</Text>
</View>
<View row centerV>
<Checkbox
value={acceptTerms}
onValueChange={(value) => setAcceptTerms(value)}
/>
<View row>
<Text text90R marginL-10>
I accept the
<SafeAreaView style={{ flex: 1 }}>
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1 }}
enableOnAndroid
>
<View
style={{ flex: 1, padding: 21, paddingBottom: 45, paddingTop: "20%" }}
>
<View gap-13 width={"100%"} marginB-20>
<Text style={{ fontSize: 40, fontFamily: "Manrope_600SemiBold" }}>
Get started with Cally
</Text>
<TouchableOpacity>
<Text text90 style={{ textDecorationLine: "underline" }}>
{" "}
terms and conditions
<Text color={"#919191"} style={{ fontSize: 20 }}>
Please enter your details.
</Text>
</View>
<KeyboardAvoidingView style={{ width: "100%" }}>
<TextField
marginT-30
autoFocus
placeholder="First name"
value={firstName}
onChangeText={setFirstName}
style={styles.textfield}
onSubmitEditing={() => {
lnameRef.current?.focus();
}}
blurOnSubmit={false}
accessibilityLabel="First name input"
accessibilityHint="Enter your first name"
accessible
returnKeyType="next"
textContentType="givenName"
importantForAccessibility="yes"
/>
<TextField
ref={lnameRef}
placeholder="Last name"
value={lastName}
onChangeText={setLastName}
style={styles.textfield}
onSubmitEditing={() => {
emailRef.current?.focus();
}}
blurOnSubmit={false}
accessibilityLabel="Last name input"
accessibilityHint="Enter your last name"
accessible
returnKeyType="next"
textContentType="familyName"
importantForAccessibility="yes"
/>
<TextField
placeholder="Email"
keyboardType={"email-address"}
returnKeyType={"next"}
textContentType={"emailAddress"}
defaultValue={email}
onChangeText={setEmail}
style={styles.textfield}
autoComplete={"email"}
autoCorrect={false}
ref={emailRef}
onSubmitEditing={() => {
passwordRef.current?.focus();
}}
/>
<View
centerV
style={[styles.textfield, { padding: 0, paddingHorizontal: 30 }]}
>
<TextField
ref={passwordRef}
placeholder="Password"
style={styles.jakartaLight}
value={password}
onChangeText={setPassword}
secureTextEntry={!isPasswordVisible}
trailingAccessory={
<TouchableOpacity
onPress={() => setIsPasswordVisible(!isPasswordVisible)}
>
<AntDesign
name={isPasswordVisible ? "eye" : "eyeo"}
size={24}
color="gray"
/>
</TouchableOpacity>
}
/>
</View>
</KeyboardAvoidingView>
<View gap-5 marginT-15>
<View row centerV>
<Checkbox
style={[styles.check]}
color="#919191"
value={allowFaceID}
onValueChange={(value) => {
setAllowFaceID(value);
}}
/>
<Text style={styles.jakartaLight} marginL-10>
Allow FaceID for login in future
</Text>
</TouchableOpacity>
<Text text90R> and </Text>
<TouchableOpacity>
<Text text90 style={{ textDecorationLine: "underline" }}>
{" "}
privacy policy
</View>
<View row centerV>
<Checkbox
style={styles.check}
color="#919191"
value={acceptTerms}
onValueChange={(value) => setAcceptTerms(value)}
/>
<View row style={{ flexWrap: "wrap", marginLeft: 10 }}>
<Text style={styles.jakartaLight}>I accept the</Text>
<TouchableOpacity>
<Text text90 style={styles.jakartaMedium}>
{" "}
terms and conditions
</Text>
</TouchableOpacity>
<Text style={styles.jakartaLight}> and </Text>
<TouchableOpacity>
<Text text90 style={styles.jakartaMedium}>
{" "}
privacy policy
</Text>
</TouchableOpacity>
</View>
</View>
</View>
<View flexG style={{ minHeight: 50 }} />
<View>
<Button
label="Register"
disabled={!acceptTerms}
labelStyle={{
fontFamily: "PlusJakartaSans_600SemiBold",
fontSize: 16,
}}
onPress={handleSignUp}
backgroundColor={"#fd1775"}
style={{ marginBottom: 0, height: 50 }}
/>
<View row centerH marginT-10 marginB-2 gap-5>
<Text
style={[
styles.jakartaLight,
{ fontSize: 16, color: "#484848" },
]}
center
>
Already have an account?
</Text>
</TouchableOpacity>
<Button
label="Log in"
labelStyle={[
styles.jakartaMedium,
{
fontSize: 16,
textDecorationLine: "none",
color: "#fd1775",
},
]}
flexS
margin-0
link
color="#fd1775"
size={ButtonSize.small}
text70
onPress={() => router.replace("/(unauth)/sign_in")}
/>
</View>
</View>
</View>
</View>
<View style={styles.bottomView}>
<Button
label="Register"
onPress={handleSignUp}
style={{ marginBottom: 10, backgroundColor: "#fd1775" }}
/>
<View row centerH marginT-10 marginB-5 gap-5>
<Text text70 center>
Already have an account?
</Text>
</KeyboardAwareScrollView>
<Button
label="Sign In"
flexS
margin-0
link
color="#fd1775"
size={ButtonSize.small}
text70
onPress={() => setTab("login")}
/>
</View>
</View>
</View>
{isLoading && (
<LoaderScreen
overlay
message={"Signing up..."}
backgroundColor={Colors.white}
color={Colors.grey40}
/>
)}
</SafeAreaView>
);
};
@ -161,11 +244,33 @@ export default SignUpPage;
const styles = StyleSheet.create({
textfield: {
backgroundColor: "white",
marginVertical: 10,
marginVertical: 8,
padding: 30,
height: 45,
height: 44,
borderRadius: 50,
fontFamily: "PlusJakartaSans_300Light",
fontSize: 13,
color: "#919191",
},
jakartaLight: {
fontFamily: "PlusJakartaSans_300Light",
fontSize: 13,
color: "#919191",
},
jakartaMedium: {
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 13,
color: "#919191",
textDecorationLine: "underline",
},
title: { fontFamily: "Manrope_600SemiBold", fontSize: 34, marginTop: 50 },
subtitle: { fontFamily: "PlusJakartaSans_400Regular", fontSize: 16 },
check: {
borderRadius: 3,
aspectRatio: 1,
width: 18,
color: "#919191",
borderColor: "#919191",
borderWidth: 1,
},
//mora da se izmeni kako treba
bottomView: { marginTop: 150 },
});

View File

@ -1,5 +1,5 @@
import {AntDesign, Ionicons} from "@expo/vector-icons";
import React, {useCallback, useEffect, useState} from "react";
import React, {useCallback, useState} from "react";
import {Button, Checkbox, Text, View} from "react-native-ui-lib";
import {ActivityIndicator, ScrollView, StyleSheet} from "react-native";
import {TouchableOpacity} from "react-native-gesture-handler";
@ -9,51 +9,49 @@ import debounce from "debounce";
import AppleIcon from "@/assets/svgs/AppleIcon";
import GoogleIcon from "@/assets/svgs/GoogleIcon";
import OutlookIcon from "@/assets/svgs/OutlookIcon";
import * as AuthSession from "expo-auth-session";
import * as Google from "expo-auth-session/providers/google";
import * as WebBrowser from "expo-web-browser";
import {UserProfile} from "@firebase/auth";
import {useFetchAndSaveGoogleEvents} from "@/hooks/useFetchAndSaveGoogleEvents";
import {useFetchAndSaveOutlookEvents} from "@/hooks/useFetchAndSaveOutlookEvents";
import {useFetchAndSaveAppleEvents} from "@/hooks/useFetchAndSaveAppleEvents";
import * as AppleAuthentication from 'expo-apple-authentication';
import ExpoLocalization from "expo-localization/src/ExpoLocalization";
import {colorMap} from "@/constants/colorMap";
import {useSetAtom} from "jotai";
import {settingsPageIndex} from "../calendar/atoms";
import CalendarSettingsDialog from "./calendar_components/CalendarSettingsDialog";
import {useClearTokens} from "@/hooks/firebase/useClearTokens";
import {useCalSync} from "@/hooks/useCalSync";
import Feather from "@expo/vector-icons/Feather";
const googleConfig = {
androidClientId:
"406146460310-2u67ab2nbhu23trp8auho1fq4om29fc0.apps.googleusercontent.com",
iosClientId:
"406146460310-2u67ab2nbhu23trp8auho1fq4om29fc0.apps.googleusercontent.com",
webClientId:
"406146460310-2u67ab2nbhu23trp8auho1fq4om29fc0.apps.googleusercontent.com",
scopes: [
"email",
"profile",
"https://www.googleapis.com/auth/calendar.events.owned",
],
};
const microsoftConfig = {
clientId: "13c79071-1066-40a9-9f71-b8c4b138b4af",
redirectUri: AuthSession.makeRedirectUri({path: "settings"}),
scopes: [
"openid",
"profile",
"email",
"offline_access",
"Calendars.ReadWrite",
"User.Read"
],
authorizationEndpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
tokenEndpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
};
const CalendarSettingsPage = (props: {
setSelectedPage: (page: number) => void;
}) => {
const CalendarSettingsPage = () => {
const {profileData} = useAuthContext();
const [firstDayOfWeek, setFirstDayOfWeek] = useState<string>(profileData?.firstDayOfWeek ?? ExpoLocalization.getCalendars()[0].firstWeekday === 1 ? "Mondays" : "Sundays");
const setPageIndex = useSetAtom(settingsPageIndex);
const [firstDayOfWeek, setFirstDayOfWeek] = useState<string>(
profileData?.firstDayOfWeek ??
ExpoLocalization.getCalendars()[0].firstWeekday === 1
? "Mondays"
: "Sundays"
);
const [isModalVisible, setModalVisible] = useState<boolean>(false);
const [selectedService, setSelectedService] = useState<
"google" | "outlook" | "apple"
>("google");
const [selectedEmail, setSelectedEmail] = useState<string>("");
const showConfirmationDialog = (
serviceName: "google" | "outlook" | "apple",
email: string
) => {
setSelectedService(serviceName);
setSelectedEmail(email);
setModalVisible(true);
};
const handleConfirm = async () => {
await clearToken({email: selectedEmail, provider: selectedService});
setModalVisible(false);
};
const handleCancel = () => {
setModalVisible(false);
};
const [selectedColor, setSelectedColor] = useState<string>(
profileData?.eventColor ?? colorMap.pink
@ -63,169 +61,22 @@ const CalendarSettingsPage = (props: {
);
const {mutateAsync: updateUserData} = useUpdateUserData();
const {mutateAsync: fetchAndSaveGoogleEvents, isLoading: isSyncingGoogle} = useFetchAndSaveGoogleEvents();
const {mutateAsync: fetchAndSaveOutlookEvents, isLoading: isSyncingOutlook} = useFetchAndSaveOutlookEvents();
const {mutateAsync: fetchAndSaveAppleEvents, isLoading: isSyncingApple} = useFetchAndSaveAppleEvents();
const {mutateAsync: clearToken} = useClearTokens();
WebBrowser.maybeCompleteAuthSession();
const [_, response, promptAsync] = Google.useAuthRequest(googleConfig);
useEffect(() => {
signInWithGoogle();
}, [response]);
const signInWithGoogle = async () => {
try {
if (response?.type === "success") {
const accessToken = response.authentication?.accessToken;
const userInfoResponse = await fetch(
"https://www.googleapis.com/oauth2/v3/userinfo",
{
headers: {Authorization: `Bearer ${accessToken}`},
}
);
const userInfo = await userInfoResponse.json();
const googleMail = userInfo.email;
let googleAccounts = profileData?.googleAccounts;
const updatedGoogleAccounts = googleAccounts ? {...googleAccounts, [googleMail]: accessToken} : {[googleMail]: accessToken};
await updateUserData({
newUserData: {googleAccounts: updatedGoogleAccounts},
});
await fetchAndSaveGoogleEvents({token: accessToken, email: googleMail})
}
} catch (error) {
console.error("Error during Google sign-in:", error);
}
};
const handleMicrosoftSignIn = async () => {
try {
console.log("Starting Microsoft sign-in...");
const authRequest = new AuthSession.AuthRequest({
clientId: microsoftConfig.clientId,
scopes: microsoftConfig.scopes,
redirectUri: microsoftConfig.redirectUri,
responseType: AuthSession.ResponseType.Code,
usePKCE: true, // Enable PKCE
});
console.log("Auth request created:", authRequest);
const authResult = await authRequest.promptAsync({
authorizationEndpoint: microsoftConfig.authorizationEndpoint,
});
console.log("Auth result:", authResult);
if (authResult.type === "success" && authResult.params?.code) {
const code = authResult.params.code;
console.log("Authorization code received:", code);
// Exchange authorization code for tokens
const tokenResponse = await fetch(microsoftConfig.tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `client_id=${
microsoftConfig.clientId
}&redirect_uri=${encodeURIComponent(
microsoftConfig.redirectUri
)}&grant_type=authorization_code&code=${code}&code_verifier=${
authRequest.codeVerifier
}&scope=${encodeURIComponent(
"https://graph.microsoft.com/Calendars.ReadWrite offline_access User.Read"
)}`,
});
console.log("Token response status:", tokenResponse.status);
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
console.error("Token exchange failed:", errorText);
return;
}
const tokenData = await tokenResponse.json();
console.log("Token data received:", tokenData);
if (tokenData?.access_token) {
console.log("Access token received, fetching user info...");
// Fetch user info from Microsoft Graph API to get the email
const userInfoResponse = await fetch("https://graph.microsoft.com/v1.0/me", {
headers: {
Authorization: `Bearer ${tokenData.access_token}`,
},
});
const userInfo = await userInfoResponse.json();
console.log("User info received:", userInfo);
if (userInfo.error) {
console.error("Error fetching user info:", userInfo.error);
} else {
const outlookMail = userInfo.mail || userInfo.userPrincipalName;
let microsoftAccounts = profileData?.microsoftAccounts;
const updatedMicrosoftAccounts = microsoftAccounts ? {...microsoftAccounts, [outlookMail]: tokenData.access_token} : {[outlookMail]: tokenData.access_token};
// Update user data with Microsoft token and email
await updateUserData({
newUserData: {microsoftAccounts: updatedMicrosoftAccounts},
});
await fetchAndSaveOutlookEvents(tokenData.access_token, outlookMail)
console.log("User data updated successfully.");
}
}
} else {
console.warn("Authentication was not successful:", authResult);
}
} catch (error) {
console.error("Error during Microsoft sign-in:", error);
}
};
const handleAppleSignIn = async () => {
try {
console.log("Starting Apple Sign-in...");
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.EMAIL,
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
],
});
console.log("Apple sign-in result:", credential);
const appleToken = credential.identityToken;
const appleMail = credential.email;
if (appleToken) {
console.log("Apple ID token received. Fetch user info if needed...");
await updateUserData({
newUserData: {appleToken, appleMail},
});
console.log("User data updated with Apple ID token.");
await fetchAndSaveAppleEvents({token: appleToken, email: appleMail!});
} else {
console.warn("Apple authentication was not successful or email was hidden.");
}
} catch (error) {
console.error("Error during Apple Sign-in:", error);
}
};
const {
isSyncingGoogle,
isSyncingOutlook,
isConnectedToGoogle,
isConnectedToMicrosoft,
isConnectedToApple,
handleAppleSignIn,
isSyncingApple,
handleMicrosoftSignIn,
fetchAndSaveOutlookEvents,
fetchAndSaveGoogleEvents,
handleStartGoogleSignIn,
fetchAndSaveAppleEvents
} = useCalSync()
const debouncedUpdateUserData = useCallback(
debounce(async (color: string) => {
@ -259,9 +110,9 @@ const CalendarSettingsPage = (props: {
);
const handleChangeFirstDayOfWeek = (firstDayOfWeek: string) => {
setFirstDayOfWeek(firstDayOfWeek === "Sundays" ? "Mondays" : "Sundays");
debouncedUpdateFirstDayOfWeek(firstDayOfWeek === "Sundays" ? "Mondays" : "Sundays");
}
setFirstDayOfWeek(firstDayOfWeek);
debouncedUpdateFirstDayOfWeek(firstDayOfWeek);
};
const handleChangeColor = (color: string) => {
setPreviousSelectedColor(selectedColor);
@ -269,80 +120,25 @@ const CalendarSettingsPage = (props: {
debouncedUpdateUserData(color);
};
const clearToken = async (provider: "google" | "outlook" | "apple", email: string) => {
const newUserData: Partial<UserProfile> = {};
if (provider === "google") {
let googleAccounts = profileData?.googleAccounts;
if (googleAccounts) {
googleAccounts[email] = null;
newUserData.googleAccounts = googleAccounts;
}
} else if (provider === "outlook") {
let microsoftAccounts = profileData?.microsoftAccounts;
if (microsoftAccounts) {
microsoftAccounts[email] = null;
newUserData.microsoftAccounts = microsoftAccounts;
}
} else if (provider === "apple") {
let appleAccounts = profileData?.appleAccounts;
if (appleAccounts) {
appleAccounts[email] = null;
newUserData.appleAccounts = appleAccounts;
}
}
await updateUserData({newUserData});
};
let isConnectedToGoogle = false;
if (profileData?.googleAccounts) {
Object.values(profileData?.googleAccounts).forEach((item) => {
if (item !== null) {
isConnectedToGoogle = true;
return;
}
});
}
let isConnectedToMicrosoft = false;
const microsoftAccounts = profileData?.microsoftAccounts;
if (microsoftAccounts) {
Object.values(profileData?.microsoftAccounts).forEach((item) => {
if (item !== null) {
isConnectedToMicrosoft = true;
return;
}
});
}
let isConnectedToApple = false;
if (profileData?.appleAccounts) {
Object.values(profileData?.appleAccounts).forEach((item) => {
if (item !== null) {
isConnectedToApple = true;
return;
}
});
}
return (
<ScrollView>
<TouchableOpacity onPress={() => setPageIndex(0)}>
<View row marginT-20 marginB-20 marginL-20 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{paddingBottom: 3}}
/>
<Text
style={{fontFamily: "Poppins_400Regular", fontSize: 14.71}}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<View marginH-30 marginB-30>
<TouchableOpacity onPress={() => props.setSelectedPage(0)}>
<View row marginT-20 marginB-35 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{paddingBottom: 3}}
/>
<Text
style={{fontFamily: "Poppins_400Regular", fontSize: 14.71}}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<Text style={styles.subTitle}>Calendar settings</Text>
<View style={styles.card}>
<Text style={styles.cardTitle} marginB-14>
@ -424,11 +220,11 @@ const CalendarSettingsPage = (props: {
</Text>
<Button
onPress={() => promptAsync()}
label={"Connect Google"}
onPress={() => handleStartGoogleSignIn()}
label={profileData?.googleAccounts ? "Connect another Google account" : "Connect Google account"}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
numberOfLines: 2,
}}
iconSource={() => (
<View marginR-15>
@ -439,52 +235,14 @@ const CalendarSettingsPage = (props: {
color="black"
text70BL
/>
{profileData?.googleAccounts ? Object.keys(profileData?.googleAccounts)?.map((googleMail) => {
const googleToken = profileData?.googleAccounts?.[googleMail];
return googleToken && <Button
key={googleMail}
onPress={() => clearToken("google", googleMail)}
label={`Disconnect ${googleMail}`}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
}}
iconSource={() => (
<View marginR-15>
<GoogleIcon/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
}) : null}
<Button
onPress={() => handleAppleSignIn()}
label={"Connect Apple"}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
}}
iconSource={() => (
<View marginR-15>
<AppleIcon/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
{profileData?.appleAccounts ? Object.keys(profileData?.appleAccounts)?.map((appleEmail) => {
const appleToken = profileData?.appleAccounts?.[appleEmail];
return appleToken && <Button
key={appleEmail}
onPress={() => clearToken("apple", appleEmail)}
label={`Disconnect ${appleEmail}`}
{!profileData?.appleAccounts && (
<Button
onPress={() => handleAppleSignIn()}
label={"Connect Apple"}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
numberOfLines: 2,
}}
iconSource={() => (
<View marginR-15>
@ -495,14 +253,14 @@ const CalendarSettingsPage = (props: {
color="black"
text70BL
/>
}) : null}
)}
<Button
onPress={() => handleMicrosoftSignIn()}
label={"Connect Outlook"}
label={profileData?.microsoftAccounts ? "Connect another Outlook account" : "Connect Outlook"}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
numberOfLines: 2,
}}
iconSource={() => (
<View marginR-15>
@ -513,147 +271,220 @@ const CalendarSettingsPage = (props: {
color="black"
text70BL
/>
{profileData?.microsoftAccounts ? Object.keys(profileData?.microsoftAccounts)?.map((microsoftEmail) => {
const microsoftToken = profileData?.microsoftAccounts?.[microsoftEmail];
return microsoftToken && <Button
key={microsoftEmail}
onPress={() => clearToken("outlook", microsoftEmail)}
label={`Disconnect ${microsoftEmail}`}
labelStyle={styles.addCalLbl}
labelProps={{
numberOfLines: 2
}}
iconSource={() => (
<View marginR-15>
<OutlookIcon/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
}) : null}
{(isConnectedToGoogle || isConnectedToMicrosoft || isConnectedToApple) && (
{(isConnectedToGoogle ||
isConnectedToMicrosoft ||
isConnectedToApple) && (
<>
<Text style={styles.subTitle} marginT-30 marginB-20>
Connected Calendars
</Text>
<View style={styles.noPaddingCard}>
<View style={[styles.noPaddingCard, {marginBottom: 100}]}>
<View style={{marginTop: 20}}>
{profileData?.googleAccounts && Object.keys(profileData?.googleAccounts)?.map((googleEmail) => {
const googleToken = profileData?.googleAccounts?.[googleEmail];
return googleToken && (
<TouchableOpacity
onPress={() => fetchAndSaveGoogleEvents({token: googleToken, email: googleEmail})}
>
<View row paddingR-20 center>
<Button
disabled={isSyncingGoogle}
onPress={() => fetchAndSaveGoogleEvents({token: googleToken, email: googleEmail})}
label={`Sync ${googleEmail}`}
labelStyle={styles.addCalLbl}
labelProps={{numberOfLines: 3}}
iconSource={() => (
<View marginR-15>
<GoogleIcon/>
{profileData?.googleAccounts &&
Object.keys(profileData?.googleAccounts)?.map(
(googleEmail) => {
const googleToken =
profileData?.googleAccounts?.[googleEmail]?.accessToken;
return (
googleToken && (
<View row paddingR-5 center>
<View
style={{
backgroundColor: "#ffffff",
marginBottom: 15,
paddingLeft: 15,
}}
color="black"
text70BL
row
centerV
width="100%"
spread
>
{isSyncingGoogle ? (
<View marginR-5>
<ActivityIndicator/>
</View>
) : (
<View marginR-5>
<Button
style={{backgroundColor: "#ffffff"}}
color="black"
onPress={() =>
fetchAndSaveGoogleEvents({
token: googleToken,
email: googleEmail,
})
}
iconSource={() => <Ionicons
name={"refresh"}
size={20}
color={"#000000"}
/>}
/>
</View>
)}
<View marginR-5>
<GoogleIcon/>
</View>
<Text style={styles.addCalLbl}>
{googleEmail}
</Text>
<Button
style={{backgroundColor: "#ffffff", marginRight: 5}}
color="black"
onPress={
() => showConfirmationDialog("google", googleEmail)
}
iconSource={() => <Feather name="x" size={24} />}
/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
</View>
)
);
}
)}
{isSyncingGoogle ? (
<ActivityIndicator/>
) : (
<Ionicons name={"refresh"} size={20} color={"#000000"}/>
)}
</View>
</TouchableOpacity>
)
})}
{profileData?.appleAccounts &&
Object.keys(profileData?.appleAccounts)?.map((appleEmail) => {
console.log(profileData?.appleAccounts)
{profileData?.appleAccounts && Object.keys(profileData?.appleAccounts)?.map((appleEmail) => {
const appleToken = profileData?.appleAccounts?.[appleEmail];
return appleToken && (
<TouchableOpacity
onPress={() => fetchAndSaveAppleEvents({
email: appleEmail,
token: appleToken
})}>
<View row paddingR-20 center>
<Button
disabled={isSyncingApple}
onPress={() => fetchAndSaveAppleEvents({
email: appleEmail,
token: appleToken
})}
label={`Sync ${appleEmail}`}
labelStyle={styles.addCalLbl}
labelProps={{numberOfLines: 3}}
iconSource={() => (
<View marginR-15>
const appleToken = profileData?.appleAccounts?.[appleEmail];
return (
appleToken && (
<View row paddingR-5 center>
<View
style={{
backgroundColor: "#ffffff",
marginBottom: 15,
paddingLeft: 15,
}}
color="black"
text70BL
row
centerV
width="100%"
spread
>
<View marginR-5>
<AppleIcon/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
{isSyncingApple ? (
<ActivityIndicator/>
) : (
<Ionicons name={"refresh"} size={20} color={"#000000"}/>
)}
</View>
</TouchableOpacity>
)
})}
<Text style={styles.addCalLbl}>
{appleEmail}
</Text>
{isSyncingApple ? (
<View marginR-5>
<ActivityIndicator/>
</View>
) : (
<View marginR-5>
<Button
style={{backgroundColor: "#ffffff"}}
color="black"
onPress={() =>
fetchAndSaveAppleEvents({
email: appleEmail,
token: appleToken,
})
}
iconSource={() => <Ionicons
name={"refresh"}
size={20}
color={"#000000"}
/>}
/>
</View>
)}
<Button
style={{backgroundColor: "#ffffff", marginRight: 5}}
color="black"
onPress={() => showConfirmationDialog("apple", appleEmail)}
iconSource={() => <Feather name="x" size={24} />}
/>
</View>
</View>
)
);
})}
{profileData?.microsoftAccounts && Object.keys(profileData?.microsoftAccounts)?.map((microsoftEmail) => {
const microsoftToken = profileData?.microsoftAccounts?.[microsoftEmail];
return microsoftToken && (
<TouchableOpacity
onPress={() => fetchAndSaveOutlookEvents({
token: microsoftToken,
email: microsoftEmail
})}
>
<View row paddingR-20 center>
<Button
disabled={isSyncingOutlook}
onPress={() => fetchAndSaveOutlookEvents({
token: microsoftToken,
email: microsoftEmail
})}
label={`Sync ${microsoftEmail}`}
labelStyle={styles.addCalLbl}
labelProps={{numberOfLines: 3}}
iconSource={() => (
<View marginR-15>
<OutlookIcon/>
{profileData?.microsoftAccounts &&
Object.keys(profileData?.microsoftAccounts)?.map(
(microsoftEmail) => {
const microsoftToken =
profileData?.microsoftAccounts?.[microsoftEmail];
return (
microsoftToken && (
<View row paddingR-5 center>
<View
style={{
backgroundColor: "#ffffff",
marginBottom: 15,
paddingLeft: 15,
}}
color="black"
text70BL
row
centerV
width="100%"
spread
>
{isSyncingOutlook ? (
<View marginR-5>
<ActivityIndicator/>
</View>
) : (
<View marginR-5>
<Button
style={{backgroundColor: "#ffffff"}}
color="black"
onPress={() =>
fetchAndSaveOutlookEvents({
token: microsoftToken,
email: microsoftEmail,
})
}
iconSource={() => <Ionicons
name={"refresh"}
size={20}
color={"#000000"}
/>}
/>
</View>
)}
<View marginR-5>
<OutlookIcon/>
</View>
<Text style={styles.addCalLbl}>
{microsoftEmail}
</Text>
<Button
style={{backgroundColor: "#ffffff", marginRight: 5}}
color="black"
onPress={
() => showConfirmationDialog("outlook", microsoftEmail)
}
iconSource={() => <Feather name="x" size={24} />}
/>
</View>
)}
style={styles.addCalBtn}
color="black"
text70BL
/>
{isSyncingOutlook ? (
<ActivityIndicator/>
) : (
<Ionicons name={"refresh"} size={20} color={"#000000"}/>
)}
</View>
</TouchableOpacity>
)
})}
</View>
)
);
}
)}
</View>
</View>
</>
)}
</View>
<CalendarSettingsDialog
visible={isModalVisible}
serviceName={selectedService}
email={selectedEmail}
onDismiss={handleCancel}
onConfirm={handleConfirm}
/>
</ScrollView>
);
};
@ -698,10 +529,10 @@ const styles = StyleSheet.create({
fontSize: 16,
fontFamily: "PlusJakartaSan_500Medium",
flexWrap: "wrap",
width: "75%",
width: "70%",
textAlign: "left",
lineHeight: 20,
overflow: "visible"
overflow: "hidden",
},
subTitle: {
fontFamily: "Manrope_600SemiBold",

View File

@ -4,30 +4,32 @@ import { Ionicons } from "@expo/vector-icons";
import { ToDosContextProvider } from "@/contexts/ToDosContext";
import ToDosList from "../todos/ToDosList";
import { ScrollView } from "react-native-gesture-handler";
import { settingsPageIndex } from "../calendar/atoms";
import { useAtom } from "jotai";
const ChoreRewardSettings = () => {
const [pageIndex, setPageIndex] = useAtom(settingsPageIndex);
const ChoreRewardSettings = (props: {
setSelectedPage: (page: number) => void;
}) => {
return (
<ToDosContextProvider>
<View marginT-10 marginH-20>
<TouchableOpacity onPress={() => setPageIndex(0)}>
<View row marginT-20 marginB-20 marginL-20 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{ paddingBottom: 3 }}
/>
<Text
style={{ fontFamily: "Poppins_400Regular", fontSize: 14.71 }}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<View marginH-20>
<ScrollView>
<TouchableOpacity onPress={() => props.setSelectedPage(0)}>
<View row marginT-20 marginB-35 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{ paddingBottom: 3 }}
/>
<Text
style={{ fontFamily: "Poppins_400Regular", fontSize: 14.71 }}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<Text text60R marginB-20>
Chore Reward Settings
</Text>

View File

@ -1,7 +1,7 @@
import {Button, Text, View} from "react-native-ui-lib";
import React, {useState} from "react";
import {StyleSheet} from "react-native";
import {Octicons} from "@expo/vector-icons";
import { Button, Text, View } from "react-native-ui-lib";
import React, { useState } from "react";
import {Linking, StyleSheet} from "react-native";
import { Octicons } from "@expo/vector-icons";
import CalendarSettingsPage from "./CalendarSettingsPage";
import ChoreRewardSettings from "./ChoreRewardSettings";
import UserSettings from "./UserSettings";
@ -9,120 +9,138 @@ import ProfileIcon from "@/assets/svgs/ProfileIcon";
import CalendarIcon from "@/assets/svgs/CalendarIcon";
import PrivacyPolicyIcon from "@/assets/svgs/PrivacyPolicyIcon";
import ArrowRightIcon from "@/assets/svgs/ArrowRightIcon";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { settingsPageIndex } from "../calendar/atoms";
import { useAtom } from "jotai";
const pageIndex = {
main: 0,
user: 1,
calendar: 2,
chore: 3,
policy: 4,
main: 0,
user: 1,
calendar: 2,
chore: 3,
policy: 4,
};
const SettingsPage = () => {
const {profileData} = useAuthContext()
const isntParent = profileData?.userType !== ProfileType.PARENT
const PRIVACY_POLICY_URL = 'https://callyapp.com';
const [selectedPage, setSelectedPage] = useState<number>(0);
return (
<View flexG>
{selectedPage == 0 && (
<View flexG centerH marginH-30 marginT-30>
<Button
disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<ProfileIcon style={{marginRight: 10}} color="#07b9c8"/>
<Text style={[styles.label, isntParent && styles.disabledText]}>
Manage My Profile
</Text>
<ArrowRightIcon style={{marginLeft: "auto"}}/>
</View>
}
onPress={() => setSelectedPage(pageIndex.user)}
/>
<Button
disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<CalendarIcon style={{marginRight: 10}}/>
<Text style={[styles.label, isntParent && styles.disabledText]}>
Calendar Settings
</Text>
<ArrowRightIcon style={{marginLeft: "auto"}}/>
</View>
}
onPress={() => {
setSelectedPage(pageIndex.calendar);
}}
/>
<Button
disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<Octicons
name="gear"
size={24}
color="#ff9900"
style={{marginRight: 10}}
/>
<Text style={[styles.label, isntParent && styles.disabledText]}>
To-Do Reward Settings
</Text>
<ArrowRightIcon style={{marginLeft: "auto"}}/>
</View>
}
onPress={() => setSelectedPage(pageIndex.chore)}
/>
<Button
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<PrivacyPolicyIcon style={{marginRight: 10}}/>
<Text style={styles.label}>
Cally Privacy Policy
</Text>
<ArrowRightIcon style={{marginLeft: "auto"}}/>
</View>
}
/>
</View>
)}
{selectedPage == pageIndex.calendar && (
<CalendarSettingsPage setSelectedPage={setSelectedPage}/>
)}
{selectedPage == pageIndex.chore && (
<ChoreRewardSettings setSelectedPage={setSelectedPage}/>
)}
{selectedPage == pageIndex.user && (
<UserSettings setSelectedPage={setSelectedPage}/>
)}
const SettingsPage = () => {
const { profileData } = useAuthContext();
const [pageIndex, setPageIndex] = useAtom(settingsPageIndex);
const isntParent = profileData?.userType !== ProfileType.PARENT;
const openPrivacyPolicy = async () => {
const supported = await Linking.canOpenURL(PRIVACY_POLICY_URL);
if (supported) {
await Linking.openURL(PRIVACY_POLICY_URL);
} else {
console.log("Don't know how to open this URL:", PRIVACY_POLICY_URL);
}
};
return (
<View flexG>
{pageIndex == 0 && (
<View flexG centerH marginH-30 marginT-30>
<Button
disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<ProfileIcon style={{ marginRight: 10 }} color="#07b9c8" />
<Text
style={[
styles.label,
isntParent ? styles.disabledText : { color: "#07b9c8" },
]}
>
Manage My Profile
</Text>
<ArrowRightIcon style={{ marginLeft: "auto" }} />
</View>
}
onPress={() => setPageIndex(1)}
/>
<Button
disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<CalendarIcon style={{ marginRight: 10 }} />
<Text
style={[
styles.label,
isntParent ? styles.disabledText : { color: "#FD1775" },
]}
>
Calendar Settings
</Text>
<ArrowRightIcon style={{ marginLeft: "auto" }} />
</View>
}
onPress={() => {
setPageIndex(2);
}}
/>
<Button
disabled
// disabled={isntParent}
backgroundColor="white"
style={styles.mainBtn}
children={
<View row centerV width={"100%"}>
<Octicons
name="gear"
size={24}
color="#ff9900"
style={{ marginRight: 10 }}
/>
<Text style={[styles.label, true ? styles.disabledText : {color: "#ff9900"}]}>
To-Do Reward Settings
</Text>
<ArrowRightIcon style={{ marginLeft: "auto" }} />
</View>
}
onPress={() => setPageIndex(3)}
/>
<Button
backgroundColor="white"
style={styles.mainBtn}
onPress={openPrivacyPolicy}
children={
<View row centerV width={"100%"}>
<PrivacyPolicyIcon style={{ marginRight: 10 }} />
<Text style={[styles.label]} color={"#6C645B"}>Cally Privacy Policy</Text>
<ArrowRightIcon style={{ marginLeft: "auto" }} />
</View>
}
/>
</View>
);
)}
{pageIndex == 2 && <CalendarSettingsPage />}
{pageIndex == 3 && <ChoreRewardSettings />}
{pageIndex == 1 && <UserSettings />}
</View>
);
};
export default SettingsPage;
const styles = StyleSheet.create({
mainBtn: {
width: 311,
justifyContent: "flex-start",
marginBottom: 20,
height: 57.61,
},
label: {
fontFamily: "Poppins_400Regular",
fontSize: 14.71,
textAlignVertical: "center",
},
disabledText: {
color: '#A9A9A9', // Example of a gray color for disabled text
},
});
mainBtn: {
width: 311,
justifyContent: "flex-start",
marginBottom: 20,
height: 57.61,
},
label: {
fontFamily: "Poppins_400Regular",
fontSize: 14.71,
textAlignVertical: "center",
},
disabledText: {
color: "#A9A9A9", // Example of a gray color for disabled text
},
});

View File

@ -1,99 +1,131 @@
import { Text, TouchableOpacity, View } from "react-native-ui-lib";
import React, { useState } from "react";
import { Ionicons } from "@expo/vector-icons";
import { ScrollView, StyleSheet } from "react-native";
import {FloatingButton, Text, TouchableOpacity, View,} from "react-native-ui-lib";
import React, {useState} from "react";
import {Ionicons} from "@expo/vector-icons";
import {ScrollView, StyleSheet} from "react-native";
import MyProfile from "./user_settings_views/MyProfile";
import MyGroup from "./user_settings_views/MyGroup";
import {useAtom, useSetAtom} from "jotai";
import {settingsPageIndex, userSettingsView} from "../calendar/atoms";
import PlusIcon from "@/assets/svgs/PlusIcon";
const UserSettings = (props: { setSelectedPage: (page: number) => void }) => {
const [selectedView, setSelectedView] = useState<boolean>(true);
return (
<View flexG>
<ScrollView style={{ paddingBottom: 20, minHeight: "100%" }}>
<TouchableOpacity onPress={() => props.setSelectedPage(0)}>
<View row marginT-20 marginB-35 centerV>
<Ionicons name="chevron-back" size={14} color="#979797" style={{paddingBottom: 3}} />
<Text
style={{ fontFamily: "Poppins_400Regular", fontSize: 14.71 }}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<View marginH-20 flexG style={{ minHeight: "90%" }}>
<Text text60R marginB-25>
User Management
</Text>
<View style={styles.buttonSwitch} spread row>
<TouchableOpacity
onPress={() => setSelectedView(true)}
centerV
centerH
style={selectedView == true ? styles.btnSelected : styles.btnNot}
>
<View>
<Text
style={styles.btnTxt}
color={selectedView ? "white" : "black"}
>
My Profile
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => setSelectedView(false)}
centerV
centerH
style={selectedView == false ? styles.btnSelected : styles.btnNot}
>
<View>
<Text
style={styles.btnTxt}
color={!selectedView ? "white" : "black"}
>
My Group
</Text>
</View>
</TouchableOpacity>
</View>
{selectedView && <MyProfile />}
{!selectedView && <MyGroup />}
</View>
</ScrollView>
const UserSettings = () => {
const setPageIndex = useSetAtom(settingsPageIndex);
const [userView, setUserView] = useAtom(userSettingsView);
const [onNewUserClick, setOnNewUserClick] = useState<(boolean)>(false);
{!selectedView && (
<View>
<Text>selview</Text>
return (
<View flexG>
<ScrollView style={{paddingBottom: 20, minHeight: "100%"}}>
<TouchableOpacity
onPress={() => {
setPageIndex(0);
setUserView(true);
}}
>
<View row marginT-20 marginB-20 marginL-20 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{paddingBottom: 3}}
/>
<Text
style={{fontFamily: "Poppins_400Regular", fontSize: 14.71}}
color="#979797"
>
Return to main settings
</Text>
</View>
</TouchableOpacity>
<View marginH-26 flexG style={{minHeight: "90%"}}>
<Text text60R marginB-25>
User Management
</Text>
<View style={styles.buttonSwitch} spread row>
<TouchableOpacity
onPress={() => setUserView(true)}
centerV
centerH
style={userView == true ? styles.btnSelected : styles.btnNot}
>
<View>
<Text
style={styles.btnTxt}
color={userView ? "white" : "black"}
>
My Profile
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => setUserView(false)}
centerV
centerH
style={userView == false ? styles.btnSelected : styles.btnNot}
>
<View>
<Text
style={styles.btnTxt}
color={!userView ? "white" : "black"}
>
My Group
</Text>
</View>
</TouchableOpacity>
</View>
{userView && <MyProfile/>}
{!userView && <MyGroup onNewUserClick={onNewUserClick} setOnNewUserClick={setOnNewUserClick}/>}
</View>
</ScrollView>
{!userView && (
<FloatingButton
fullWidth
hideBackgroundOverlay
visible
button={{
label: " Add a user device",
iconSource: () => <PlusIcon height={13} width={14}/>,
onPress: () => setOnNewUserClick(true),
style: styles.bottomButton,
labelStyle: {fontFamily: "Manrope_600SemiBold", fontSize: 15},
}}
/>
)}
</View>
)}
</View>
);
);
};
const styles = StyleSheet.create({
buttonSwitch: {
borderRadius: 50,
width: "100%",
backgroundColor: "#ebebeb",
height: 45,
},
btnSelected: {
backgroundColor: "#05a8b6",
height: "100%",
width: "50%",
borderRadius: 50,
},
btnTxt: {
fontFamily: "Manrope_500Medium",
fontSize: 15,
},
btnNot: {
height: "100%",
width: "50%",
borderRadius: 50,
},
title: { fontFamily: "Manrope_600SemiBold", fontSize: 18 },
bottomButton: {
position: "absolute",
bottom: 15,
marginHorizontal: 28,
width: 337,
backgroundColor: "#e8156c",
height: 53.26,
},
buttonSwitch: {
borderRadius: 50,
width: "100%",
backgroundColor: "#ebebeb",
height: 45,
},
btnSelected: {
backgroundColor: "#05a8b6",
height: "100%",
width: "50%",
borderRadius: 50,
},
btnTxt: {
fontFamily: "Manrope_500Medium",
fontSize: 15,
},
btnNot: {
height: "100%",
width: "50%",
borderRadius: 50,
},
title: {fontFamily: "Manrope_600SemiBold", fontSize: 18},
});
export default UserSettings;

View File

@ -0,0 +1,86 @@
import React from "react";
import { Dialog, Button, Text, View } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
interface ConfirmationDialogProps {
visible: boolean;
serviceName: "google" | "outlook" | "apple";
email: string;
onDismiss: () => void;
onConfirm: () => void;
}
const CalendarSettingsDialog: React.FC<ConfirmationDialogProps> = ({
visible,
serviceName,
email,
onDismiss,
onConfirm,
}) => {
return (
<Dialog
visible={visible}
onDismiss={onDismiss}
containerStyle={styles.dialog}
>
<Text center style={styles.title}>
Disconnect {serviceName}
</Text>
<View center>
<Text style={styles.text} center>
Are you sure you want to disconnect this {"\n"}
<Text style={{ fontSize: 16, fontFamily: "PlusJakartaSans_700Bold" }}>
{serviceName}
</Text>{" "}
calendar
{"\n"}
for {email}?
</Text>
</View>
<View row right gap-8>
<Button
label="Cancel"
onPress={onDismiss}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={onConfirm}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</Dialog>
);
};
// Empty stylesheet for future styles
const styles = StyleSheet.create({
confirmBtn: {
backgroundColor: "#ea156d",
},
cancelBtn: {
backgroundColor: "white",
},
dialog: {
backgroundColor: "white",
paddingHorizontal: 25,
paddingTop: 35,
paddingBottom: 17,
borderRadius: 20,
},
title: {
fontFamily: "Manrope_600SemiBold",
fontSize: 22,
marginBottom: 20,
},
text: {
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
marginBottom: 25,
},
});
export default CalendarSettingsDialog;

View File

@ -0,0 +1,128 @@
import React, { useState } from "react";
import { Dialog, Button, Text, View } from "react-native-ui-lib";
import { StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";
interface ConfirmationDialogProps {
visible: boolean;
onDismiss: () => void;
onFirstYes: () => void;
onConfirm: () => void;
}
const DeleteProfileDialogs: React.FC<ConfirmationDialogProps> = ({
visible,
onDismiss,
onFirstYes,
onConfirm,
}) => {
const [confirmationDialog, setConfirmationDialog] = useState<boolean>(false);
return (
<>
<Dialog
visible={visible}
onDismiss={onDismiss}
containerStyle={styles.dialog}
>
<View centerH>
<Feather name="alert-triangle" size={70} color="#FF5449" />
</View>
<Text center style={styles.title}>
Are you sure?
</Text>
<Text
style={{
fontSize: 18,
fontFamily: "PlusJakartaSans_700Bold",
color: "#979797",
marginBottom: 20,
}}
center
>
This action will permanently delete all your data, you won't be able
to recover it!
</Text>
<View centerV></View>
<View row right gap-8>
<Button
label="Cancel"
onPress={onDismiss}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={() => {
setTimeout(() => setConfirmationDialog(true), 300);
onFirstYes();
}}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</Dialog>
<Dialog
visible={confirmationDialog}
onDismiss={() => setConfirmationDialog(false)}
containerStyle={styles.dialog}
>
<View center paddingH-10 paddingT-15 paddingB-5>
<Text style={styles.title}>
We're sorry to see you go, are you really sure you want to delete
everything?
</Text>
<View row right gap-8 marginT-15>
<Button
label="Cancel"
onPress={() => {
setConfirmationDialog(false);
}}
style={styles.cancelBtn}
color="#999999"
labelStyle={{ fontFamily: "Poppins_500Medium", fontSize: 13.53 }}
/>
<Button
label="Yes"
onPress={() => {
onConfirm();
setConfirmationDialog(false);
}}
style={styles.confirmBtn}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium" }}
/>
</View>
</View>
</Dialog>
</>
);
};
// Empty stylesheet for future styles
const styles = StyleSheet.create({
confirmBtn: {
backgroundColor: "#FF5449",
},
cancelBtn: {
backgroundColor: "white",
},
dialog: {
backgroundColor: "white",
paddingHorizontal: 25,
paddingTop: 25,
paddingBottom: 17,
borderRadius: 20,
},
title: {
fontFamily: "Manrope_600SemiBold",
fontSize: 22,
marginBottom: 5,
},
text: {
fontFamily: "PlusJakartaSans_400Regular",
fontSize: 16,
marginBottom: 0,
},
});
export default DeleteProfileDialogs;

View File

@ -3,8 +3,7 @@ import {
Button,
Card,
Colors,
Dialog,
FloatingButton,
Dialog, Image,
KeyboardAwareScrollView,
PanningProvider,
Picker,
@ -15,10 +14,10 @@ import {
View,
} from "react-native-ui-lib";
import React, {useEffect, useRef, useState} from "react";
import {ScrollView, StyleSheet} from "react-native";
import {ImageBackground, Platform, StyleSheet} from "react-native";
import {PickerSingleValue} from "react-native-ui-lib/src/components/picker/types";
import {useCreateSubUser} from "@/hooks/firebase/useCreateSubUser";
import {ProfileType} from "@/contexts/AuthContext";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import {useGetFamilyMembers} from "@/hooks/firebase/useGetFamilyMembers";
import UserMenu from "@/components/pages/settings/user_settings_views/UserMenu";
import {uuidv4} from "@firebase/util";
@ -28,11 +27,18 @@ import CircledXIcon from "@/assets/svgs/CircledXIcon";
import ProfileIcon from "@/assets/svgs/ProfileIcon";
import NavToDosIcon from "@/assets/svgs/NavToDosIcon";
import Ionicons from "@expo/vector-icons/Ionicons";
import {PreviousNextView} from "react-native-keyboard-manager";
import KeyboardManager, {PreviousNextView,} from "react-native-keyboard-manager";
import {ScrollView} from "react-native-gesture-handler";
import {useUploadProfilePicture} from "@/hooks/useUploadProfilePicture";
import {ImagePickerAsset} from "expo-image-picker";
const MyGroup = () => {
type MyGroupProps = {
onNewUserClick: boolean;
setOnNewUserClick: React.Dispatch<React.SetStateAction<boolean>>;
};
const MyGroup: React.FC<MyGroupProps> = ({onNewUserClick, setOnNewUserClick}) => {
const [showAddUserDialog, setShowAddUserDialog] = useState(false);
const [showNewUserInfoDialog, setShowNewUserInfoDialog] = useState(false);
const [selectedStatus, setSelectedStatus] = useState<
string | PickerSingleValue
>(ProfileType.CHILD);
@ -40,13 +46,19 @@ const MyGroup = () => {
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [newUserId, setNewUserId] = useState("")
const lNameRef = useRef<TextFieldRef>(null);
const emailRef = useRef<TextFieldRef>(null);
const [showQRCodeDialog, setShowQRCodeDialog] = useState<string | boolean>(false);
const [showQRCodeDialog, setShowQRCodeDialog] = useState<string | boolean>(
false
);
const {mutateAsync: createSubUser, isLoading, isError} = useCreateSubUser();
const {data: familyMembers} = useGetFamilyMembers(true);
const {user} = useAuthContext();
const {pickImage, changeProfilePicture, handleClearImage, pfpUri, profileImageAsset} = useUploadProfilePicture(newUserId)
const parents =
familyMembers?.filter((x) => x.userType === ProfileType.PARENT) ?? [];
@ -67,10 +79,10 @@ const MyGroup = () => {
return;
}
if (selectedStatus !== ProfileType.FAMILY_DEVICE && !email) {
console.error("Email is required for non-family device users");
return;
}
// if (selectedStatus !== ProfileType.FAMILY_DEVICE && !email) {
// console.error("Email is required for non-family device users");
// return;
// }
if (email && !email.includes("@")) {
console.error("Invalid email address");
@ -87,28 +99,38 @@ const MyGroup = () => {
console.log(res);
if (!isError) {
setShowNewUserInfoDialog(false);
setOnNewUserClick(false);
if (res?.data?.userId) {
setTimeout(() => {
if (profileImageAsset) {
await changeProfilePicture(profileImageAsset)
setShowQRCodeDialog(res.data.userId);
}, 500);
} else {
setTimeout(() => {
setShowQRCodeDialog(res.data.userId);
}, 500);
}
handleClearImage()
}
}
};
useEffect(() => {
if (Platform.OS === "ios") KeyboardManager.setEnableAutoToolbar(true);
}, []);
useEffect(() => {
setFirstName("");
setLastName("");
setEmail("");
}, [])
}, []);
// @ts-ignore
return (
<View style={{flex: 1, minHeight: 500}}>
<View>
<ScrollView style={styles.card}>
<View marginB-70>
<ScrollView>
<View>
{!parents.length && !children.length && !caregivers.length && (
<Text text70 marginV-10>
{isLoading ? "Loading...." : "No user devices added"}
@ -116,8 +138,8 @@ const MyGroup = () => {
)}
{(!!parents.length || !!children.length) && (
<>
<Text style={styles.subTit} marginV-10>
<View style={styles.card}>
<Text style={styles.subTit} marginB-10>
Family
</Text>
{[...parents, ...children]?.map((member, index) => (
@ -128,39 +150,45 @@ const MyGroup = () => {
style={styles.familyCard}
row
centerV
padding-10
paddingT-10
>
<Avatar
source={{uri: "https://via.placeholder.com/60"}}
size={40}
backgroundColor={Colors.grey60}
/>
<View marginL-10>
<Text text70M>
{member.pfp ? (
<ImageBackground
style={styles.pfp}
borderRadius={10.56}
source={{uri: member.pfp || undefined}}
/>
) : (
<View
style={[styles.pfp, {backgroundColor: "#ea156d"}]}
/>
)}
<View row marginL-10 centerV>
<Text style={styles.name}>
{member.firstName} {member.lastName}
</Text>
<Text text90 grey40>
</View>
<View flexG/>
<View row centerV gap-10>
<Text style={styles.userType}>
{member.userType === ProfileType.PARENT
? "Admin (You)"
? `Admin${member.uid === user?.uid ? " (You)" : ""}`
: "Child"}
</Text>
<UserMenu
setShowQRCodeDialog={(val) => setShowQRCodeDialog(val)}
showQRCodeDialog={showQRCodeDialog === member?.uid}
userId={member?.uid!}
/>
</View>
<View flex-1/>
<UserMenu
setShowQRCodeDialog={(val) => setShowQRCodeDialog(val)}
showQRCodeDialog={showQRCodeDialog === member?.uid}
userId={member?.uid!}
/>
</Card>
))}
</>
</View>
)}
{!!caregivers.length && (
<>
<Text text70 marginB-10 marginT-15>
<View style={styles.card}>
<Text style={styles.subTit} marginB-10 marginT-15>
Caregivers
</Text>
{caregivers?.map((member) => (
@ -196,7 +224,7 @@ const MyGroup = () => {
/>
</Card>
))}
</>
</View>
)}
{!!familyDevices.length && (
@ -237,19 +265,8 @@ const MyGroup = () => {
))}
</>
)}
</ScrollView>
</View>
<FloatingButton
fullWidth
hideBackgroundOverlay
visible
button={{
label: "+ Add a user device",
onPress: () => setShowNewUserInfoDialog(true),
style: styles.bottomButton,
}}
/>
</View>
</ScrollView>
<Dialog
visible={showAddUserDialog}
@ -302,8 +319,8 @@ const MyGroup = () => {
<Dialog
panDirection={PanningProvider.Directions.DOWN}
visible={showNewUserInfoDialog}
onDismiss={() => setShowNewUserInfoDialog(false)}
visible={onNewUserClick}
onDismiss={() => setOnNewUserClick(false)}
>
<PreviousNextView>
<KeyboardAwareScrollView>
@ -312,31 +329,51 @@ const MyGroup = () => {
<Text style={{fontFamily: "Manrope_500Medium", fontSize: 16}}>
New User Information
</Text>
<TouchableOpacity onPress={() => {
setShowNewUserInfoDialog(false)
}}>
<TouchableOpacity
onPress={() => {
setOnNewUserClick(false);
}}
>
<CircledXIcon/>
</TouchableOpacity>
</View>
<View style={styles.divider} spread/>
<View row centerV gap-20 marginV-20>
<View
height={65.54}
width={65.54}
children={
<ProfileIcon color={"#d6d6d6"} width={37} height={37}/>
}
backgroundColor={Colors.grey60}
style={{borderRadius: 25}}
center
/>
<TouchableOpacity onPress={() => {
}}>
<Text color="#50be0c" style={styles.jakarta13} marginL-15>
Upload User Profile Photo
</Text>
</TouchableOpacity>
{pfpUri ? (
<Image
height={65.54}
width={65.54}
style={{borderRadius: 25}}
source={{uri: pfpUri}}
/>
) : (
<View
height={65.54}
width={65.54}
children={
<ProfileIcon color={"#d6d6d6"} width={37} height={37}/>
}
backgroundColor={Colors.grey60}
style={{borderRadius: 25}}
center
/>
)}
{pfpUri ? (
<TouchableOpacity onPress={handleClearImage}>
<Text color={Colors.red40} style={styles.jakarta13} marginL-15>
Clear user photo
</Text>
</TouchableOpacity>
) : (
<TouchableOpacity onPress={pickImage}>
<Text color="#50be0c" style={styles.jakarta13} marginL-15>
Upload User Profile Photo
</Text>
</TouchableOpacity>
)}
</View>
<Text style={styles.jakarta12}>Member Status</Text>
@ -349,21 +386,30 @@ const MyGroup = () => {
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
style={{
justifyContent: "center",
alignItems: "center",
height: "100%",
marginTop: -38,
paddingRight: 15,
}}
>
<Ionicons
name={"chevron-down"}
style={{alignSelf: "center"}}
size={20}
color={"#000000"}
/>
</View>
}
>
<Picker.Item label="Child" value={ProfileType.CHILD}/>
<Picker.Item label="Parent" value={ProfileType.PARENT}/>
<Picker.Item label="Caregiver" value={ProfileType.CAREGIVER}/>
<Picker.Item
label="Caregiver"
value={ProfileType.CAREGIVER}
/>
<Picker.Item
label="Family Device"
value={ProfileType.FAMILY_DEVICE}
@ -387,7 +433,7 @@ const MyGroup = () => {
onChangeText={setFirstName}
style={styles.inputField}
onSubmitEditing={() => {
lNameRef.current?.focus()
lNameRef.current?.focus();
}}
blurOnSubmit={false}
returnKeyType="next"
@ -404,11 +450,10 @@ const MyGroup = () => {
onChangeText={setLastName}
style={styles.inputField}
onSubmitEditing={() => {
emailRef.current?.focus()
emailRef.current?.focus();
}}
blurOnSubmit={false}
returnKeyType="next"
/>
</>
)}
@ -470,12 +515,14 @@ const styles = StyleSheet.create({
marginVertical: 15,
backgroundColor: "white",
width: "100%",
borderRadius: 15,
padding: 20,
borderRadius: 12,
paddingHorizontal: 21,
paddingVertical: 20,
},
bottomButton: {
position: "absolute",
bottom: 80,
bottom: 50,
backgroundColor: "#e8156c",
width: "100%",
},
familyCard: {
@ -556,6 +603,16 @@ const styles = StyleSheet.create({
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 13,
},
pfp: {aspectRatio: 1, width: 37.03, borderRadius: 10.56},
userType: {
fontFamily: "Manrope_500Medium",
fontSize: 12,
color: "#858585",
},
name: {
fontFamily: "Manrope_600SemiBold",
fontSize: 16,
},
});
export default MyGroup;

View File

@ -3,6 +3,7 @@ import { StyleSheet, TouchableOpacity } from "react-native";
import { ScrollView } from "react-native-gesture-handler";
import * as ImagePicker from "expo-image-picker";
import {
Button,
Colors,
Image,
Picker,
@ -18,6 +19,7 @@ import { useAuthContext } from "@/contexts/AuthContext";
import { useUpdateUserData } from "@/hooks/firebase/useUpdateUserData";
import { useChangeProfilePicture } from "@/hooks/firebase/useChangeProfilePicture";
import { colorMap } from "@/constants/colorMap";
import DeleteProfileDialogs from "../user_components/DeleteProfileDialogs";
const MyProfile = () => {
const { user, profileData } = useAuthContext();
@ -32,6 +34,15 @@ const MyProfile = () => {
string | ImagePicker.ImagePickerAsset | null
>(profileData?.pfp || null);
const [showDeleteDialog, setShowDeleteDialog] = useState<boolean>(false);
const handleHideDeleteDialog = () => {
setShowDeleteDialog(false);
};
const handleShowDeleteDialog = () => {
setShowDeleteDialog(true);
};
const { mutateAsync: updateUserData } = useUpdateUserData();
const { mutateAsync: changeProfilePicture } = useChangeProfilePicture();
const isFirstRender = useRef(true);
@ -48,13 +59,12 @@ const MyProfile = () => {
return;
}
debouncedUserDataUpdate();
}, [timeZone, lastName, firstName, profileImage]);
}, [timeZone, lastName, firstName]);
useEffect(() => {
if (profileData) {
setFirstName(profileData.firstName || "");
setLastName(profileData.lastName || "");
// setProfileImage(profileData.pfp || null);
setTimeZone(
profileData.timeZone || Localization.getCalendars()[0].timeZone!
);
@ -78,7 +88,7 @@ const MyProfile = () => {
if (!result.canceled) {
setProfileImage(result.assets[0].uri);
changeProfilePicture(result.assets[0]);
await changeProfilePicture(result.assets[0]);
}
};
@ -93,7 +103,7 @@ const MyProfile = () => {
: profileImage;
return (
<ScrollView style={{ paddingBottom: 100, flex: 1 }}>
<ScrollView style={{ paddingBottom: 20, flex: 1 }}>
<View style={styles.card}>
<Text style={styles.subTit}>Your Profile</Text>
<View row spread paddingH-15 centerV marginV-15>
@ -205,6 +215,22 @@ const MyProfile = () => {
</Picker>
</View>
</View>
<Button
size="large"
backgroundColor="#FF5449"
label="Delete Profile"
style={{ marginTop: 10 }}
labelStyle={{ fontFamily: "PlusJakartaSans_500Medium", fontSize: 15 }}
onPress={handleShowDeleteDialog}
/>
<DeleteProfileDialogs
onFirstYes={() => {
setShowDeleteDialog(false);
}}
visible={showDeleteDialog}
onDismiss={handleHideDeleteDialog}
onConfirm={() => {console.log('delete account here')}}
/>
</ScrollView>
);
};

View File

@ -32,7 +32,10 @@ const UserMenu = ({
panDirection={PanningDirectionsEnum.DOWN}
>
<Card padding-20 center>
<Text marginB-10>Scan this QR Code to Login:</Text>
<Text center marginB-10 style={{fontSize: 16, maxWidth: "80%"}}>Ask your family to download the app
and then scan the
QR Code to join the family group:
</Text>
<QRCode value={userId} size={150}/>
<Button
marginT-20

View File

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

View File

@ -1,317 +1,353 @@
import { View, Text, Button, Switch, PickerModes } from "react-native-ui-lib";
import React, { useRef, useState } from "react";
import PointsSlider from "@/components/shared/PointsSlider";
import { repeatOptions, useToDosContext } from "@/contexts/ToDosContext";
import { Feather, AntDesign, Ionicons } from "@expo/vector-icons";
import {
Dialog,
TextField,
DateTimePicker,
Picker,
ButtonSize,
Button,
ButtonSize,
DateTimePicker,
Dialog,
Picker,
PickerModes,
Switch,
Text,
TextField,
TextFieldRef,
View
} from "react-native-ui-lib";
import { PanningDirectionsEnum } from "react-native-ui-lib/src/incubator/panView";
import { Dimensions, StyleSheet } from "react-native";
import React, {useEffect, useRef, useState} from "react";
import PointsSlider from "@/components/shared/PointsSlider";
import {repeatOptions, useToDosContext} from "@/contexts/ToDosContext";
import {Ionicons} from "@expo/vector-icons";
import {PanningDirectionsEnum} from "react-native-ui-lib/src/incubator/panView";
import {Dimensions, KeyboardAvoidingView, StyleSheet} from "react-native";
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 { 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 {
isVisible: boolean;
setIsVisible: (value: boolean) => void;
selectedTodo?: IToDo;
isVisible: boolean;
setIsVisible: (value: boolean) => void;
selectedTodo?: IToDo;
}
const defaultTodo = {
id: "",
title: "",
points: 10,
date: new Date(),
rotate: false,
repeatType: "Every week",
assignees: [],
id: "",
title: "",
points: 10,
date: new Date(),
rotate: false,
repeatType: "Every week",
assignees: [],
repeatDays: []
};
const AddChoreDialog = (addChoreDialogProps: IAddChoreDialog) => {
const { addToDo, updateToDo } = useToDosContext();
const [todo, setTodo] = useState<IToDo>(
addChoreDialogProps.selectedTodo ?? defaultTodo
);
const [selectedAssignees, setSelectedAssignees] = useState<string[]>(
addChoreDialogProps?.selectedTodo?.assignees ?? []
);
const { width, height } = Dimensions.get("screen");
const [points, setPoints] = useState<number>(todo.points);
const {addToDo, updateToDo} = useToDosContext();
const [todo, setTodo] = useState<IToDo>(
addChoreDialogProps.selectedTodo ?? defaultTodo
);
const [selectedAssignees, setSelectedAssignees] = useState<string[]>(
addChoreDialogProps?.selectedTodo?.assignees ?? []
);
const {width} = Dimensions.get("screen");
const [points, setPoints] = useState<number>(todo.points);
const { data: members } = useGetFamilyMembers();
const titleRef = useRef<TextFieldRef>(null)
const handleClose = () => {
setTodo(defaultTodo);
setSelectedAssignees([]);
addChoreDialogProps.setIsVisible(false);
};
const {data: members} = useGetFamilyMembers();
const handleChange = (text: string) => {
const numericValue = parseInt(text, 10);
const handleClose = () => {
setTodo(defaultTodo);
setSelectedAssignees([]);
addChoreDialogProps.setIsVisible(false);
};
if (!isNaN(numericValue) && numericValue >= 0 && numericValue <= 100) {
setPoints(numericValue);
} else if (text === "") {
setPoints(0);
}
};
const handleChange = (text: string) => {
const numericValue = parseInt(text, 10);
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => handleClose}
containerStyle={{
borderRadius: 10,
backgroundColor: "white",
alignSelf: "stretch",
padding: 0,
paddingTop: 4,
margin: 0,
}}
visible={addChoreDialogProps.isVisible}
>
<View row spread>
<Button
color="#05a8b6"
style={styles.topBtn}
label="Cancel"
onPress={() => {
handleClose();
}}
/>
<View marginT-12>
<DropModalIcon
onPress={() => {
handleClose();
}}
/>
</View>
<Button
color="#05a8b6"
style={styles.topBtn}
label="Save"
onPress={() => {
try {
if (addChoreDialogProps.selectedTodo) {
updateToDo({
...todo,
points: points,
assignees: selectedAssignees,
});
} else {
addToDo({
...todo,
done: false,
points: points,
assignees: selectedAssignees,
});
}
handleClose();
} catch (error) {
console.error(error);
if (!isNaN(numericValue) && numericValue >= 0 && numericValue <= 100) {
setPoints(numericValue);
} else if (text === "") {
setPoints(0);
}
};
const handleRepeatDaysChange = (day: string, set: boolean) => {
if (set) {
const updatedTodo = {
...todo,
repeatDays: [...todo.repeatDays, day]
}
}}
/>
</View>
<TextField
placeholder="Add a To Do"
autoFocus
value={todo?.title}
onChangeText={(text) => {
setTodo((oldValue: IToDo) => ({ ...oldValue, title: text }));
}}
placeholderTextColor="#2d2d30"
text60R
marginT-15
marginL-30
/>
<View style={styles.divider} marginT-8 />
<View marginL-30 centerV>
<View row marginB-10>
{todo?.date && (
<View row centerV>
<CalendarIcon color="#919191" width={24} height={24} />
<DateTimePicker
value={todo.date}
text70
style={{
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
marginL-12
onChange={(date) => {
setTodo((oldValue: IToDo) => ({ ...oldValue, date: date }));
}}
/>
</View>
)}
</View>
<View row centerV>
<ClockOIcon />
<Picker
marginL-12
placeholder="Select Repeat Type"
value={todo?.repeatType}
onChange={(value) => {
if (value) {
if (value.toString() == "None") {
setTodo((oldValue) => ({
...oldValue,
date: null,
repeatType: "None",
}));
} else {
setTodo((oldValue) => ({
...oldValue,
date: new Date(),
repeatType: value.toString(),
}));
}
}
}}
topBarProps={{ title: "Repeat" }}
style={{
marginVertical: 5,
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
>
{repeatOptions.map((option) => (
<Picker.Item
key={option.value}
label={option.label}
value={option.value}
/>
))}
</Picker>
</View>
{todo.repeatType == "Every week" && <RepeatFreq/>}
</View>
<View style={styles.divider} />
setTodo(updatedTodo);
} else {
const array = todo.repeatDays ?? [];
let index = array.indexOf(day);
array.splice(index, 1);
const updatedTodo = {
...todo,
repeatDays: array
}
setTodo(updatedTodo);
}
}
<View marginH-30 marginB-10 row centerV>
<ProfileIcon color="#919191" />
<Text style={styles.sub} marginL-10>
Assignees
</Text>
<View flex-1 />
<Picker
marginL-8
value={selectedAssignees}
onChange={(value) => {
setSelectedAssignees([...selectedAssignees, ...value]);
}}
style={{ marginVertical: 5 }}
mode={PickerModes.MULTI}
renderInput={() => (
<Button
size={ButtonSize.small}
paddingH-8
iconSource={() => (
<Ionicons name="add-outline" size={20} color="#ea156c" />
)}
style={{
marginLeft: "auto",
borderRadius: 8,
backgroundColor: "#ffe8f1",
borderColor: "#ea156c",
borderWidth: 1,
}}
color="#ea156c"
label="Assign"
labelStyle={{ fontFamily: "Manrope_600SemiBold", fontSize: 14 }}
/>
)}
useEffect(() => {
setTimeout(() => {
titleRef?.current?.focus()
}, 500)
}, []);
return (
<Dialog
bottom={true}
height={"90%"}
width={width}
panDirection={PanningDirectionsEnum.DOWN}
onDismiss={() => handleClose}
containerStyle={{
borderRadius: 10,
backgroundColor: "white",
alignSelf: "stretch",
padding: 0,
paddingTop: 4,
margin: 0,
}}
visible={addChoreDialogProps.isVisible}
>
{members?.map((member) => (
<Picker.Item
key={member.uid}
label={member?.firstName + " " + member?.lastName}
value={member?.uid!}
/>
))}
</Picker>
</View>
<View row marginL-27 marginT-0>
<AssigneesDisplay
selectedAttendees={selectedAssignees}
setSelectedAttendees={setSelectedAssignees}
/>
</View>
<View row centerV style={styles.rotateSwitch}>
<Text style={{ fontFamily: "PlusJakartaSans_500Medium", fontSize: 16 }}>
Take Turns
</Text>
<Switch
onColor={"#ea156c"}
value={todo.rotate}
style={{ width: 43.06, height: 27.13 }}
marginL-10
onValueChange={(value) =>
setTodo((oldValue) => ({ ...oldValue, rotate: value }))
}
/>
</View>
<View style={styles.divider} />
<View marginH-30 marginB-15 row centerV>
<Ionicons name="gift-outline" size={25} color="#919191" />
<Text style={styles.sub} marginL-10>
Reward Points
</Text>
</View>
<PointsSlider
points={points}
setPoints={setPoints}
handleChange={handleChange}
/>
</Dialog>
);
<View row spread>
<Button
color="#05a8b6"
style={styles.topBtn}
label="Cancel"
onPress={() => {
handleClose();
}}
/>
<View marginT-12>
<DropModalIcon
onPress={() => {
handleClose();
}}
/>
</View>
<Button
color="#05a8b6"
style={styles.topBtn}
label="Save"
onPress={() => {
try {
if (addChoreDialogProps.selectedTodo) {
updateToDo({
...todo,
points: points,
assignees: selectedAssignees
});
} else {
addToDo({
...todo,
done: false,
points: points,
assignees: selectedAssignees,
repeatDays: todo.repeatDays ?? []
});
}
handleClose();
} catch (error) {
console.error(error);
}
}}
/>
</View>
<KeyboardAvoidingView>
<TextField
placeholder="Add a To Do"
value={todo?.title}
onChangeText={(text) => {
setTodo((oldValue: IToDo) => ({...oldValue, title: text}));
}}
placeholderTextColor="#2d2d30"
text60R
marginT-15
marginL-30
ref={titleRef}
/>
<View style={styles.divider} marginT-8/>
<View marginL-30 centerV>
<View row marginB-10>
{todo?.date && (
<View row centerV>
<CalendarIcon color="#919191" width={24} height={24}/>
<DateTimePicker
value={todo.date}
text70
style={{
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
marginL-12
onChange={(date) => {
setTodo((oldValue: IToDo) => ({...oldValue, date: date}));
}}
/>
</View>
)}
</View>
<View row centerV>
<ClockOIcon/>
<Picker
marginL-12
placeholder="Select Repeat Type"
value={todo?.repeatType}
onChange={(value) => {
if (value) {
if (value.toString() == "None") {
setTodo((oldValue) => ({
...oldValue,
date: null,
repeatType: "None",
}));
} else {
setTodo((oldValue) => ({
...oldValue,
date: new Date(),
repeatType: value.toString(),
}));
}
}
}}
topBarProps={{title: "Repeat"}}
style={{
marginVertical: 5,
fontFamily: "PlusJakartaSans_500Medium",
fontSize: 16,
}}
>
{repeatOptions.map((option) => (
<Picker.Item
key={option.value}
label={option.label}
value={option.value}
/>
))}
</Picker>
</View>
{todo.repeatType == "Every week" && <RepeatFreq handleRepeatDaysChange={handleRepeatDaysChange}
repeatDays={todo.repeatDays ?? []}/>}
</View>
<View style={styles.divider}/>
<View marginH-30 marginB-10 row centerV>
<ProfileIcon color="#919191"/>
<Text style={styles.sub} marginL-10>
Assignees
</Text>
<View flex-1/>
<Picker
marginL-8
value={selectedAssignees}
onChange={(value) => {
setSelectedAssignees(value);
}}
style={{marginVertical: 5}}
mode={PickerModes.MULTI}
renderInput={() => (
<Button
size={ButtonSize.small}
paddingH-8
iconSource={() => (
<Ionicons name="add-outline" size={20} color="#ea156c"/>
)}
style={{
marginLeft: "auto",
borderRadius: 8,
backgroundColor: "#ffe8f1",
borderColor: "#ea156c",
borderWidth: 1,
}}
color="#ea156c"
label="Assign"
labelStyle={{fontFamily: "Manrope_600SemiBold", fontSize: 14}}
/>
)}
>
{members?.map((member) => (
<Picker.Item
key={member.uid}
label={member?.firstName + " " + member?.lastName}
value={member?.uid!}
/>
))}
</Picker>
</View>
<View row marginL-27 marginT-0>
<AssigneesDisplay
selectedAttendees={selectedAssignees}
setSelectedAttendees={setSelectedAssignees}
/>
</View>
<View row centerV style={styles.rotateSwitch}>
<Text style={{fontFamily: "PlusJakartaSans_500Medium", fontSize: 16}}>
Take Turns
</Text>
<Switch
onColor={"#ea156c"}
value={todo.rotate}
style={{width: 43.06, height: 27.13}}
marginL-10
onValueChange={(value) =>
setTodo((oldValue) => ({...oldValue, rotate: value}))
}
/>
</View>
<View style={styles.divider}/>
<View marginH-30 marginB-15 row centerV>
<Ionicons name="gift-outline" size={25} color="#919191"/>
<Text style={styles.sub} marginL-10>
Reward Points
</Text>
</View>
<PointsSlider
points={points}
setPoints={setPoints}
handleChange={handleChange}
/>
</KeyboardAvoidingView>
</Dialog>
);
};
export default AddChoreDialog;
const styles = StyleSheet.create({
divider: { height: 1, backgroundColor: "#e4e4e4", marginVertical: 15 },
gradient: {
height: "25%",
position: "absolute",
bottom: 0,
width: "100%",
},
buttonContainer: {
position: "absolute",
bottom: 25,
width: "100%",
},
button: {
backgroundColor: "rgb(253, 23, 117)",
paddingVertical: 20,
},
topBtn: {
backgroundColor: "white",
color: "#05a8b6",
},
rotateSwitch: {
marginLeft: 35,
marginBottom: 10,
marginTop: 25,
},
sub: {
fontFamily: "Manrope_600SemiBold",
fontSize: 18,
},
divider: {height: 1, backgroundColor: "#e4e4e4", marginVertical: 15},
gradient: {
height: "25%",
position: "absolute",
bottom: 0,
width: "100%",
},
buttonContainer: {
position: "absolute",
bottom: 25,
width: "100%",
},
button: {
backgroundColor: "rgb(253, 23, 117)",
paddingVertical: 20,
},
topBtn: {
backgroundColor: "white",
color: "#05a8b6",
},
rotateSwitch: {
marginLeft: 35,
marginBottom: 10,
marginTop: 25,
},
sub: {
fontFamily: "Manrope_600SemiBold",
fontSize: 18,
},
});

View File

@ -1,7 +1,8 @@
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 = () => {
const RepeatFreq = ({ repeatDays, handleRepeatDaysChange }: { repeatDays: string[], handleRepeatDaysChange: Function }) => {
const [weeks, setWeeks] = useState<number>(1);
const weekOptions: number[] = Array.from({ length: 52 }, (_, i) => i + 1);
@ -9,23 +10,30 @@ const RepeatFreq = () => {
return (
<View row centerV spread marginR-30>
<RepeatOption value={"Monday"} />
<RepeatOption value={"Tuesday"} />
<RepeatOption value={"Wednesday"} />
<RepeatOption value={"Thirsday"} />
<RepeatOption value={"Friday"} />
<RepeatOption value={"Saturday"} />
<RepeatOption value={"Sunday"} />
<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 }: { value: string }) => {
const [isSet, setisSet] = useState(false);
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={() => setisSet(!isSet)}>
<TouchableOpacity onPress={handleDayChange}>
<View
center
marginT-8

View File

@ -1,25 +1,35 @@
import {
View,
Text,
Checkbox,
TouchableOpacity,
Dialog,
Button,
ButtonSize,
Checkbox,
} from "react-native-ui-lib";
import React, { useState } from "react";
import { useToDosContext } from "@/contexts/ToDosContext";
import { Ionicons } from "@expo/vector-icons";
import PointsSlider from "@/components/shared/PointsSlider";
import { IToDo } from "@/hooks/firebase/types/todoData";
import { ImageBackground } from "react-native";
import { ImageBackground, StyleSheet } from "react-native";
import AddChoreDialog from "@/components/pages/todos/AddChoreDialog";
import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import RepeatIcon from "@/assets/svgs/RepeatIcon";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { format } from "date-fns";
const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
const ToDoItem = (props: {
item: IToDo;
isSettings?: boolean;
is7Days?: boolean;
}) => {
const { updateToDo } = useToDosContext();
const { data: members } = useGetFamilyMembers();
const { profileData } = useAuthContext();
const isParent = profileData?.userType === ProfileType.PARENT;
const [visible, setVisible] = useState<boolean>(false);
const [points, setPoints] = useState(props.item.points);
const [pointsModalVisible, setPointsModalVisible] = useState<boolean>(false);
@ -41,16 +51,24 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
const selectedMembers = members?.filter((x) =>
props?.item?.assignees?.includes(x?.uid!)
);
let isTodoEditable;
if (isParent) {
isTodoEditable = true;
} else {
isTodoEditable = props.item.creatorId === profileData?.uid;
}
return (
<View
key={props.item.id}
centerV
paddingV-10
paddingH-13
marginV-10
style={{
borderRadius: 17,
backgroundColor: props.item.done ? "#e0e0e0" : "white",
opacity: props.item.done ? 0.3 : 1,
backgroundColor: "white",
}}
>
{visible && (
@ -66,23 +84,21 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
style={{
textDecorationLine: props.item.done ? "line-through" : "none",
fontFamily: "Manrope_500Medium",
color: props.item.done? "#a09f9f": "black",
fontSize: 15,
}}
onPress={() => {
setVisible(true);
isTodoEditable ? setVisible(true) : null;
}}
>
{props.item.title}
</Text>
<Checkbox
value={props.item.done}
containerStyle={{
borderWidth: 0.7,
borderRadius: 50,
borderColor: "gray",
height: 24.64,
width: 24.64,
}}
containerStyle={[styles.checkbox, { borderRadius: 50 }]}
style={styles.checked}
size={26.64}
borderRadius={50}
color="#fd1575"
onValueChange={(value) => {
updateToDo({ id: props.item.id, done: !props.item.done });
@ -146,9 +162,12 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
return props.item.repeatType;
}
})()}
{props.item.date &&
props.is7Days &&
" / " + format(props.item.date, "EEEE")}
</Text>
</View>
)}
)}
</View>
<View row style={{ gap: 3 }}>
{selectedMembers?.map((member) => {
@ -246,3 +265,17 @@ const ToDoItem = (props: { item: IToDo; isSettings?: boolean }) => {
};
export default ToDoItem;
const styles = StyleSheet.create({
checkbox: {
borderRadius: 50,
borderWidth: 0.7,
color: "#bfbfbf",
borderColor: "#bfbfbf",
width: 24.64,
aspectRatio: 1,
},
checked: {
borderRadius: 50,
},
});

View File

@ -14,40 +14,64 @@ import { IToDo } from "@/hooks/firebase/types/todoData";
const groupToDosByDate = (toDos: IToDo[]) => {
let sortedTodos = toDos.sort((a, b) => a.date - b.date);
return sortedTodos.reduce((groups, toDo) => {
let dateKey;
return sortedTodos.reduce(
(groups, toDo) => {
let dateKey;
let subDateKey;
const isNext7Days = (date: Date) => {
const today = new Date();
return isWithinInterval(date, { start: today, end: addDays(today, 7) });
};
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) });
};
const isNext30Days = (date: Date) => {
const today = new Date();
return isWithinInterval(date, {
start: today,
end: addDays(today, 30),
});
};
if (toDo.date === null) {
dateKey = "No Date";
} else if (isToday(toDo.date)) {
dateKey = "Today";
} else if (isTomorrow(toDo.date)) {
dateKey = "Tomorrow";
} else if (isNext7Days(toDo.date)) {
dateKey = "Next 7 Days";
} else if (isNext30Days(toDo.date)) {
dateKey = "Next 30 Days";
} else {
dateKey = format(toDo.date, "EEE MMM dd");
if (toDo.date === null) {
dateKey = "No Date";
} else if (isToday(toDo.date)) {
dateKey = "Today";
} else if (isTomorrow(toDo.date)) {
dateKey = "Tomorrow";
} else if (isNext7Days(toDo.date)) {
dateKey = "Next 7 Days";
} else if (isNext30Days(toDo.date)) {
dateKey = "Next 30 Days";
subDateKey = format(toDo.date, "MMM d");
} else {
return groups;
}
if (!groups[dateKey]) {
groups[dateKey] = {
items: [],
subgroups: {},
};
}
if (dateKey === "Next 30 Days" && subDateKey) {
if (!groups[dateKey].subgroups[subDateKey]) {
groups[dateKey].subgroups[subDateKey] = [];
}
groups[dateKey].subgroups[subDateKey].push(toDo);
} else {
groups[dateKey].items.push(toDo);
}
return groups;
},
{} as {
[key: string]: {
items: IToDo[];
subgroups: { [key: string]: IToDo[] };
};
}
if (!groups[dateKey]) {
groups[dateKey] = [];
}
groups[dateKey].push(toDo);
return groups;
}, {} as { [key: string]: IToDo[] });
);
};
const ToDosList = ({ isSettings }: { isSettings?: boolean }) => {
@ -67,11 +91,139 @@ const ToDosList = ({ isSettings }: { isSettings?: boolean }) => {
}));
};
const noDateToDos = groupedToDos["No Date"] || [];
const noDateToDos = groupedToDos["No Date"]?.items || [];
const datedToDos = Object.keys(groupedToDos).filter(
(key) => key !== "No Date"
);
const renderTodoGroup = (dateKey: string) => {
const isExpanded = expandedGroups[dateKey] || false;
if (dateKey === "Next 30 Days") {
const subgroups = Object.entries(groupedToDos[dateKey].subgroups).sort(
([dateA], [dateB]) => {
const dateAObj = new Date(dateA);
const dateBObj = new Date(dateB);
return dateAObj.getTime() - dateBObj.getTime();
}
);
return (
<View key={dateKey}>
<TouchableOpacity
onPress={() => toggleExpand(dateKey)}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 0,
marginBottom: 4,
marginTop: 15,
}}
>
<Text
style={{
fontFamily: "Manrope_700Bold",
fontSize: 15,
color: "#484848",
}}
>
{dateKey}
</Text>
<AntDesign
name={isExpanded ? "caretdown" : "caretright"}
size={24}
color="#fd1575"
/>
</TouchableOpacity>
{isExpanded &&
subgroups.map(([subDate, items]) => {
const sortedItems = [
...items.filter((toDo) => !toDo.done),
...items.filter((toDo) => toDo.done),
];
return (
<View key={subDate} marginT-15>
<View
style={{
marginBottom: 8,
}}
>
<Text
style={{
fontFamily: "Manrope_600SemiBold",
fontSize: 14,
color: "#919191",
}}
>
{subDate}
</Text>
</View>
{sortedItems.map((item) => (
<ToDoItem
isSettings={isSettings}
key={item.id}
item={item}
is7Days={false}
/>
))}
</View>
);
})}
</View>
);
}
const sortedToDos = [
...groupedToDos[dateKey].items.filter((toDo) => !toDo.done),
...groupedToDos[dateKey].items.filter((toDo) => toDo.done),
];
return (
<View key={dateKey}>
<TouchableOpacity
onPress={() => toggleExpand(dateKey)}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 0,
marginBottom: 4,
marginTop: 15,
}}
>
<Text
style={{
fontFamily: "Manrope_700Bold",
fontSize: 15,
color: "#484848",
}}
>
{dateKey}
</Text>
<AntDesign
name={isExpanded ? "caretdown" : "caretright"}
size={24}
color="#fd1575"
/>
</TouchableOpacity>
{isExpanded &&
sortedToDos.map((item) => (
<ToDoItem
isSettings={isSettings}
key={item.id}
item={item}
is7Days={dateKey === "Next 7 Days"}
/>
))}
</View>
);
};
return (
<View marginB-402>
{noDateToDos.length > 0 && (
@ -85,26 +237,14 @@ const ToDosList = ({ isSettings }: { isSettings?: boolean }) => {
>
Unscheduled
</Text>
{!expandNoDate && (
<AntDesign
name="caretright"
size={24}
color="#fd1575"
onPress={() => {
setExpandNoDate(!expandNoDate);
}}
/>
)}
{expandNoDate && (
<AntDesign
name="caretdown"
size={24}
color="#fd1575"
onPress={() => {
setExpandNoDate(!expandNoDate);
}}
/>
)}
<AntDesign
name={expandNoDate ? "caretdown" : "caretright"}
size={24}
color="#fd1575"
onPress={() => {
setExpandNoDate(!expandNoDate);
}}
/>
</View>
{expandNoDate &&
noDateToDos
@ -115,50 +255,7 @@ const ToDosList = ({ isSettings }: { isSettings?: boolean }) => {
</View>
)}
{datedToDos.map((dateKey) => {
const isExpanded = expandedGroups[dateKey] || false;
const sortedToDos = [
...groupedToDos[dateKey].filter((toDo) => !toDo.done),
...groupedToDos[dateKey].filter((toDo) => toDo.done),
];
return (
<View key={dateKey}>
<TouchableOpacity
onPress={() => toggleExpand(dateKey)}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 0,
marginBottom: 4,
marginTop: 15,
}}
>
<Text
style={{
fontFamily: "Manrope_700Bold",
fontSize: 15,
color: "#484848",
}}
>
{dateKey}
</Text>
{!isExpanded && (
<AntDesign name="caretright" size={24} color="#fd1575" />
)}
{isExpanded && (
<AntDesign name="caretdown" size={24} color="#fd1575" />
)}
</TouchableOpacity>
{isExpanded &&
sortedToDos.map((item) => (
<ToDoItem isSettings={isSettings} key={item.id} item={item} />
))}
</View>
);
})}
{datedToDos.map(renderTodoGroup)}
</View>
);
};

View File

@ -1,83 +1,90 @@
import {Button, Text, View} from "react-native-ui-lib";
import React, {useState} from "react";
import { Button, Text, View } from "react-native-ui-lib";
import React, { useState } from "react";
import HeaderTemplate from "@/components/shared/HeaderTemplate";
import AddChore from "./AddChore";
import ProgressCard from "./ProgressCard";
import ToDosList from "./ToDosList";
import {Dimensions, ScrollView, StyleSheet} from "react-native";
import {TouchableOpacity} from "react-native-gesture-handler";
import {ProfileType, useAuthContext} from "@/contexts/AuthContext";
import { Dimensions, ScrollView, StyleSheet } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import FamilyChoresProgress from "./family-chores/FamilyChoresProgress";
import UserChoresProgress from "./user-chores/UserChoresProgress";
import { useAtom } from "jotai";
import { toDosPageIndex } from "../calendar/atoms";
const ToDosPage = () => {
const [pageIndex, setPageIndex] = useState<number>(0);
const {profileData} = useAuthContext();
const {width, height} = Dimensions.get("screen");
const pageLink = (
<TouchableOpacity onPress={() => setPageIndex(1)}>
<Text color="#ea156d" style={{fontSize: 14}}>
View family progress
</Text>
</TouchableOpacity>
);
return (
<>
<View paddingH-25 backgroundColor="#f9f8f7" height={"100%"} width={width}>
{pageIndex == 0 && (
<View>
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
const { profileData } = useAuthContext();
const [pageIndex, setPageIndex] = useAtom(toDosPageIndex);
const { width, height } = Dimensions.get("screen");
const pageLink = (
<TouchableOpacity onPress={() => setPageIndex(1)}>
<Text color="#ea156d" style={{ fontSize: 14 }}>
View family progress
</Text>
</TouchableOpacity>
);
return (
<>
<ScrollView
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
>
<View
paddingH-25
height={"100%"}
width={width}
>
{pageIndex == 0 && (
<View>
<View>
<HeaderTemplate
message="Here are your To Do's"
isWelcome={true}
link={profileData?.userType == ProfileType.PARENT && pageLink}
isToDos={true}
/>
{profileData?.userType == ProfileType.CHILD && (
<View marginB-25>
<ProgressCard
children={
<Button
backgroundColor="transparent"
onPress={() => setPageIndex(2)}
>
<View>
<HeaderTemplate
message="Here are your To Do's"
isWelcome={true}
link={profileData?.userType == ProfileType.PARENT && pageLink}
/>
{profileData?.userType == ProfileType.CHILD && (
<View marginB-25>
<ProgressCard
children={
<Button
backgroundColor="transparent"
onPress={() => setPageIndex(2)}
>
<Text
style={{
textDecorationLine: "underline",
color: "#05a8b6",
}}
>
View your full progress report here
</Text>
</Button>
}
/>
</View>
)}
<ToDosList/>
</View>
</ScrollView>
</View>
<Text
style={{
textDecorationLine: "underline",
color: "#05a8b6",
}}
>
View your full progress report here
</Text>
</Button>
}
/>
</View>
)}
{pageIndex == 1 && <FamilyChoresProgress setPageIndex={setPageIndex}/>}
{pageIndex == 2 && <UserChoresProgress setPageIndex={setPageIndex}/>}
<ToDosList />
</View>
</View>
{
profileData?.userType == ProfileType.PARENT && <AddChore/>
}
</>
)
;
)}
{pageIndex == 1 && (
<FamilyChoresProgress setPageIndex={setPageIndex} />
)}
{pageIndex == 2 && <UserChoresProgress setPageIndex={setPageIndex} />}
</View>
</ScrollView>
<AddChore />
</>
);
};
const styles = StyleSheet.create({
linkBtn: {
backgroundColor: "transparent",
padding: 0,
},
linkBtn: {
backgroundColor: "transparent",
padding: 0,
},
});
export default ToDosPage;

View File

@ -3,6 +3,7 @@ import React from "react";
import { ImageBackground, StyleSheet } from "react-native";
import FamilyChart from "./FamilyChart";
import { TouchableOpacity } from "react-native-ui-lib/src/incubator";
import { Ionicons } from "@expo/vector-icons";
const FamilyChoresProgress = ({
setPageIndex,
@ -12,7 +13,20 @@ const FamilyChoresProgress = ({
return (
<View marginT-20 marginH-5>
<TouchableOpacity onPress={() => setPageIndex(0)}>
<Text style={{ fontFamily: "Manrope_200", fontSize: 12 }}>Back to ToDos</Text>
<View row marginT-4 marginB-10 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{ paddingBottom: 3 }}
/>
<Text
style={{ fontFamily: "Poppins_400Regular", fontSize: 14.71 }}
color="#979797"
>
Return to To Do's
</Text>
</View>
</TouchableOpacity>
<View centerH>
<Text style={{ fontFamily: "Manrope_700Bold", fontSize: 19 }}>

View File

@ -30,8 +30,21 @@ const UserChoresProgress = ({
showsHorizontalScrollIndicator={false}
>
<TouchableOpacity onPress={() => setPageIndex(0)}>
<Text style={{ fontSize: 14 }}>Back to ToDos</Text>
</TouchableOpacity>
<View row marginT-4 marginB-10 centerV>
<Ionicons
name="chevron-back"
size={14}
color="#979797"
style={{ paddingBottom: 3 }}
/>
<Text
style={{ fontFamily: "Poppins_400Regular", fontSize: 14.71 }}
color="#979797"
>
Return to To Do's
</Text>
</View>
</TouchableOpacity>
<View>
<Text style={{ fontFamily: "Manrope_700Bold", fontSize: 20 }}>
Your To Do's Progress Report

View File

@ -1,18 +1,37 @@
import { Image, Text, View } from "react-native-ui-lib";
import React from "react";
import { useAuthContext } from "@/contexts/AuthContext";
import React, { useEffect, useState } from "react";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { StyleSheet } from "react-native";
import { colorMap } from "@/constants/colorMap";
import { useAtom } from "jotai";
import { isFamilyViewAtom } from "../pages/calendar/atoms";
import { useGetChildrenByParentId } from "@/hooks/firebase/useGetChildrenByParentId";
import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import { UserProfile } from "@/hooks/firebase/types/profileTypes";
import { child } from "@react-native-firebase/storage";
import CachedImage from 'expo-cached-image'
const HeaderTemplate = (props: {
message: string;
isWelcome: boolean;
children?: React.ReactNode;
link?: React.ReactNode;
isCalendar?: boolean;
isToDos?: boolean;
isBrainDump?: boolean;
isGroceries?: boolean;
}) => {
const { user, profileData } = useAuthContext();
const headerHeight: number = 72;
const { data: members } = useGetFamilyMembers();
const [children, setChildren] = useState<UserProfile[]>([]);
const [isFamilyView] = useAtom(isFamilyViewAtom);
const headerHeight: number =
(props.isCalendar && 65.54) ||
(props.isToDos && 84) ||
(props.isGroceries && 72.09) ||
65.54;
const styles = StyleSheet.create({
pfp: {
@ -26,14 +45,71 @@ const HeaderTemplate = (props: {
pfpTxt: {
fontFamily: "Manrope_500Medium",
fontSize: 30,
color: 'white',
color: "white",
},
childrenPfpArr: {
width: 65.54,
position: "absolute",
bottom: -12.44,
left: (children.length > 3 && -9) || 0,
height: 27.32,
},
childrenPfp: {
aspectRatio: 1,
width: 27.32,
backgroundColor: "#fd1575",
borderRadius: 50,
position: "absolute",
borderWidth: 2,
borderColor: "#f2f2f2",
},
bottomMarg: {
marginBottom: isFamilyView ? 30 : 15,
},
});
useEffect(() => {
if (members) {
const childrenMembers = members.filter(
(member) => member.userType === ProfileType.CHILD
);
setChildren(childrenMembers);
}
}, []);
return (
<View row centerV marginV-15>
<View row centerV marginV-15 style={styles.bottomMarg}>
{profileData?.pfp ? (
<Image source={{ uri: profileData.pfp }} style={styles.pfp} />
<View>
<CachedImage source={{ uri: profileData.pfp, }} style={styles.pfp} cacheKey={profileData.pfp}/>
{isFamilyView && props.isCalendar && (
<View style={styles.childrenPfpArr} row>
{children?.slice(0, 3).map((child, index) => {
return child.pfp ? (
<Image
source={{ uri: child.pfp }}
style={[styles.childrenPfp, { left: index * 19 }]}
/>
) : (
<View
style={[styles.childrenPfp, { left: index * 19 }]}
center
>
<Text style={{ color: "white" }}>
{child?.firstName?.at(0)}
{child?.firstName?.at(1)}
</Text>
</View>
);
})}
{children?.length > 3 && (
<View style={[styles.childrenPfp, { left: 3 * 19 }]} center>
<Text style={{ color: "white", fontFamily: "Manrope_600SemiBold", fontSize: 12 }}>+{children.length - 3}</Text>
</View>
)}
</View>
)}
</View>
) : (
<View style={styles.pfp} center>
<Text style={styles.pfpTxt}>

View File

@ -6,7 +6,7 @@ import { View } from "react-native-ui-lib";
const RemoveAssigneeBtn = () => {
return (
<View style={styles.removeBtn} center>
<CloseXIcon />
<CloseXIcon width={9} height={9} strokeWidth={2} />
</View>
);
};