Init commit. Rewrite of old project. Not done

This commit is contained in:
2024-10-15 15:53:05 -05:00
parent 9f193bbc01
commit 5549cbbe10
38 changed files with 957 additions and 407 deletions

View File

@ -1,37 +0,0 @@
import { StyleSheet } from 'react-native';
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
withRepeat,
withSequence,
} from 'react-native-reanimated';
import { ThemedText } from '@/components/ThemedText';
export function HelloWave() {
const rotationAnimation = useSharedValue(0);
rotationAnimation.value = withRepeat(
withSequence(withTiming(25, { duration: 150 }), withTiming(0, { duration: 150 })),
4 // Run the animation 4 times
);
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotationAnimation.value}deg` }],
}));
return (
<Animated.View style={animatedStyle}>
<ThemedText style={styles.text}>👋</ThemedText>
</Animated.View>
);
}
const styles = StyleSheet.create({
text: {
fontSize: 28,
lineHeight: 32,
marginTop: -6,
},
});

View File

@ -1,14 +0,0 @@
import { View, type ViewProps } from 'react-native';
import { useThemeColor } from '@/hooks/useThemeColor';
export type ThemedViewProps = ViewProps & {
lightColor?: string;
darkColor?: string;
};
export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) {
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
}

View File

@ -0,0 +1,153 @@
import React from "react";
import * as AppleAuthentication from "expo-apple-authentication";
import { StyleSheet, Alert } from "react-native";
import { ThemedView } from "@/components/theme/Theme";
import { useColorScheme } from "@/hooks/useColorScheme";
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import { saveUser, saveInitialData } from "@/components/services/SecureStore";
import type { InitialData, User } from "@/constants/Types";
const SignInScreen({onSignIn}: {onSignIn: () => void}) => {
const scheme = useColorScheme() ?? 'dark';
const handleAppleSignIn = async () => {
try {
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.EMAIL,
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
],
});
const projectId = Constants.expoConfig?.extra?.eas?.projectId;
if (!projectId) throw new Error('Project ID not found in eas.json');
const pushToken = await Notifications.getExpoPushTokenAsync({
projectId: projectId,
});
console.log(
credential.user, credential.email, credential.fullName?.givenName,
credential.fullName?.familyName, pushToken
);
const initialData = await
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/getUserByAppleId` +
`?appleId=${credential.user}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
},
});
console.log(initialData);
if (initialData.status === 404 || !initialData.ok) {
if (!credential.user || !credential.email ||
!credential.fullName?.givenName || !credential.fullName?.familyName ||
!pushToken || credential.email.length === 0) {
Alert.alert(
'Sign in error',
'Unable to create an account. ' +
'Remove App from Sign in with Apple & try again.',
);
throw new Error(
'Incomplete user data. This shouldn\'t happen & means that user has ' +
'previously signed in with Apple, but their user data did not ' +
'save in the database.'
);
}
const userResponse = await
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
},
body: JSON.stringify({
appleId: credential.user,
email: credential.email,
fullName:
`${credential.fullName?.givenName} ${credential.fullName?.familyName}`,
pushToken: pushToken,
}),
});
if (!userResponse.ok) {
const errorBody = await userResponse.text();
console.error(
'API error: No user returned: ',
userResponse.status, errorBody
);
throw new Error(`Failed to create user: ${userResponse.status} ${errorBody}`);
}
const user: User = await userResponse.json() as User;
await saveUser(user);
} else if (initialData.ok) {
const allData: InitialData = await initialData.json() as InitialData;
console.log('Existing user found! Saving data...');
if (allData.user.pushToken !== pushToken.data) {
const updatePushTokenResponse =
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/updatePushToken`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
},
body: JSON.stringify({
userId: allData.user.id,
pushToken: pushToken.data,
}),
});
if (!updatePushTokenResponse.ok) {
throw new Error(
`Failed to update push token: ${updatePushTokenResponse.status}`
);
}
} else {
console.log('Push token is up to date.');
}
allData.user.pushToken = pushToken.data;
await saveInitialData(allData);
}
onSignIn();
} catch (error) {
console.error('Error signing in:', error);
if (error.code === 'ERR_REQUEST_CANCELLED') {
Alert.alert('Sign in error', 'Sign in was cancelled.');
} else {
Alert.alert(
'Sign in error',
'An error occurred while signing in. Please try again or contact support.'
);
}
}
};
return (
<ThemedView style={styles.container}>
<AppleAuthentication.AppleAuthenticationButton
buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
buttonStyle={(scheme === 'light') ?
AppleAuthentication.AppleAuthenticationButtonStyle.BLACK :
AppleAuthentication.AppleAuthenticationButtonStyle.WHITE
}
cornerRadius={5}
style={styles.button}
onPress={handleAppleSignIn}
/>
</ThemedView>
);
};
export default SignInScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
width: 200,
height: 45,
},
});

View File

@ -1,7 +1,6 @@
import * as React from 'react';
import renderer from 'react-test-renderer';
import { ThemedText } from '../ThemedText';
import { ThemedText } from '@/components/Theme';
it(`renders correctly`, () => {
const tree = renderer.create(<ThemedText>Snapshot test!</ThemedText>).toJSON();

View File

@ -1,5 +1,4 @@
// You can explore the built-in icon families and icons on the web at https://icons.expo.fyi/
import Ionicons from '@expo/vector-icons/Ionicons';
import { type IconProps } from '@expo/vector-icons/build/createIconSet';
import { type ComponentProps } from 'react';

View File

@ -0,0 +1,95 @@
import * as SecureStore from "expo-secure-store";
import type {
Countdown,
InitialData,
Relationship,
RelationshipData,
User,
} from "@/constants/Types";
export const saveUser = async (user: User) => {
try {
await SecureStore.setItemAsync('user', JSON.stringify(user));
} catch (error) {
console.error('Error saving user to SecureStore:', error);
}
};
export const getUser = async () => {
try {
const user = await SecureStore.getItemAsync('user');
return user ? JSON.parse(user) as User : null;
} catch (error) {
console.error('Error getting user from SecureStore:', error);
return null;
}
};
export const savePartner = async (partner: User) => {
try {
await SecureStore.setItemAsync('partner', JSON.stringify(partner));
} catch (error) {
console.error('Error saving partner to SecureStore:', error);
}
};
export const getPartner = async () => {
try {
const partner = await SecureStore.getItemAsync('partner');
return partner ? JSON.parse(partner) as User : null;
} catch (error) {
console.error('Error getting partner from SecureStore:', error);
return null;
}
};
export const saveRelationship = async (relationship: Relationship) => {
try {
await SecureStore.setItemAsync('relationship', JSON.stringify(relationship));
} catch (error) {
console.error('Error saving relationship to SecureStore:', error);
}
};
export const getRelationship = async () => {
try {
const relationship = await SecureStore.getItemAsync('relationship');
return relationship ? JSON.parse(relationship) as Relationship : null;
} catch (error) {
console.error('Error getting relationship from SecureStore:', error);
return null;
}
};
export const saveCountdown = async (countdown: Countdown) => {
try {
await SecureStore.setItemAsync('countdown', JSON.stringify(countdown));
} catch (error) {
console.error('Error saving countdown to SecureStore:', error);
}
};
export const getCountdown = async () => {
try {
const countdown = await SecureStore.getItemAsync('countdown');
return countdown ? JSON.parse(countdown) as Countdown : null;
} catch (error) {
console.error('Error getting countdown from SecureStore:', error);
return null;
}
};
export const saveRelationshipData = async (relationshipData: RelationshipData) => {
try {
await SecureStore.setItemAsync('partner', JSON.stringify(relationshipData.Partner));
await SecureStore.setItemAsync('relationship', JSON.stringify(relationshipData.relationship));
} catch (error) {
console.error('Error saving partner & relationship to SecureStore:', error);
}
};
export const saveInitialData = async (initialData: InitialData) => {
try {
await SecureStore.setItemAsync('user', JSON.stringify(initialData.user));
await SecureStore.setItemAsync(
'relationship', JSON.stringify(initialData.relationshipData.relationship)
);
await SecureStore.setItemAsync(
'partner', JSON.stringify(initialData.relationshipData.Partner)
);
await SecureStore.setItemAsync('countdown', JSON.stringify(initialData.countdown));
} catch (error) {
console.error('Error saving initial data to SecureStore:', error);
}
};

View File

@ -0,0 +1,107 @@
import React, { useState, useEffect, useRef } from 'react';
import { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import type { NotificationMessage } from '@/constants/Types';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});
export const sendPushNotification = async(expoPushToken: string, notification: NotificationMessage) => {
const message = {
to: expoPushToken,
sound: notification.sound ?? 'default',
title: notification.title,
body: notification.body,
data: notification.data ?? {},
};
await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
};
const handleRegistrationError = (errorMessage: string) => {
alert(errorMessage);
throw new Error(errorMessage);
};
const registerforPushNotificationsAsync = async () => {
let token;
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
const projectId = Constants.expoConfig?.extra?.eas?.projectId;
if (!projectId) {
alert('Project ID not found in eas.json');
return;
}
token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
} else {
alert('Must use physical device for Push Notifications');
}
return token;
};
export const PushNotificationManager = ({children}: {children: React.ReactNode}) => {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] =
useState<Notifications.Notification | undefined>(undefined);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();
useEffect(() => {
registerforPushNotificationsAsync()
.then(token => setExpoPushToken(token ?? ''))
.catch((error: any) => {
setExpoPushToken('');
console.error(error);
});
notificationListener.current = Notifications.addNotificationReceivedListener(
notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(
response => {
console.log(response);
// Handle notification response here
});
return () => {
notificationListener.current &&
Notifications.removeNotificationSubscription(notificationListener.current);
responseListener.current &&
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return ( <> {children} </> );
};

View File

@ -1,13 +1,22 @@
import { View, type ViewProps } from 'react-native';
import { Text, type TextProps, StyleSheet } from 'react-native';
import { useThemeColor } from '@/hooks/useThemeColor';
export type ThemedViewProps = ViewProps & {
lightColor?: string;
darkColor?: string;
};
export type ThemedTextProps = TextProps & {
lightColor?: string;
darkColor?: string;
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
};
export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) {
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
}
export function ThemedText({
style,
lightColor,

View File

@ -0,0 +1,55 @@
import { StyleSheet, Pressable } from "react-native";
import { ThemedView } from "@/components/theme/Theme";
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const DEFAULT_WIDTH = 320;
const DEFAULT_HEIGHT = 68;
type Props = {
width?: number;
height?: number;
onPress?: () => void;
};
const Button = ({ width, height, children, onPress }: Props & React.ComponentProps<typeof Pressable>) => {
const scheme = useColorScheme() ?? 'dark';
return (
<ThemedView
style={[
styles.buttonContainer,
{
width: (width ?? DEFAULT_WIDTH),
height: (height ?? DEFAULT_HEIGHT),
},
]}
>
<Pressable
style={[
styles.button,
{backgroundColor: Colors[scheme].text}
]}
onPress={onPress}
>
{children}
</Pressable>
</ThemedView>
);
};
export default Button;
const styles = StyleSheet.create({
buttonContainer: {
alignItems: 'center',
justifyContent: 'center',
padding: 3,
},
button: {
borderRadius: 10,
width: '100%',
height: '100%',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
});

View File

@ -0,0 +1,37 @@
import Button from '@/components/theme/buttons/DefaultButton';
import { ThemedText } from "@/components/theme/Theme";
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const DEFAULT_FONT_SIZE = 16;
type Props = {
width?: number;
height?: number;
text: string;
fontSize?: number;
onPress?: () => void;
};
const TextButton = ({ width, height, text, fontSize, onPress }: Props ) => {
const scheme = useColorScheme() ?? 'dark';
return (
<Button
width={width}
height={height}
onPress={onPress}
>
<ThemedText
style={[
{
color: Colors[scheme].text,
fontSize: fontSize ?? DEFAULT_FONT_SIZE
}
]}
>
{text}
</ThemedText>
</Button>
);
};
export default TextButton;