Compare commits

...

20 Commits

Author SHA1 Message Date
35e340eed2 Allow users to update other statuses. Add column in statutes for that 2025-03-18 10:07:06 -05:00
dc43d3b20c Fixed the automatic updating of all statuses. 2025-03-17 12:58:04 -05:00
43e9e9790d Added sentry support 2025-03-17 09:35:27 -05:00
b9802f7b1f Clean up stuff 2025-03-13 14:01:11 -05:00
67179593cb Start fixing simple Android issues 2025-03-13 12:33:48 -05:00
ca9b56c5f1 Fix some text boxes 2025-03-13 11:56:19 -05:00
Gib
c503e4fb94 fix stuff 2025-03-12 14:13:19 -05:00
7e4978f0e0 idek 2025-03-11 17:00:25 -05:00
0c2e5f3ac7 Fix some android stuff 2025-03-11 16:47:40 -05:00
0cdfd1a0eb Just stopping now bc PC needs to reboot. 2025-03-11 14:40:34 -05:00
cfcf118275 More cleanup. More robust themed compononents 2025-03-11 11:33:46 -05:00
86d1df3558 Cleaned up auth. Ensured everything is necessary 2025-03-11 10:05:58 -05:00
Gib
6c0a275ee0 Moved logout button 2025-03-11 00:12:38 -05:00
Gib
f9655424db I got pfps working basicallly 2025-03-10 23:58:00 -05:00
50d3d69dbd Get started on stack navigation for settings page 2025-03-10 16:24:26 -05:00
6e41fd3ddf Clean up login page 2025-03-10 15:18:50 -05:00
f9fd5dafc5 All 3 auth methods work & update public profile table as well 2025-03-10 13:59:04 -05:00
07bf94d393 Sign in with Microsoft works on iOS 2025-03-07 15:05:58 -06:00
9f13d0357a Start trying to support Microsoft Azure Sign in 2025-03-06 16:55:13 -06:00
84cae666bf Apple sign in is mostly working. Did some other stuff too 2025-03-06 12:31:32 -06:00
30 changed files with 4304 additions and 1090 deletions

5
.gitignore vendored
View File

@ -29,6 +29,11 @@ yarn-error.*
.DS_Store
*.pem
# builds
*.ipa
ios/
android/
# Apple Secret
AuthKey_*.p8

View File

@ -1,24 +1,44 @@
{
"expo": {
"name": "Tech Tracker Expo",
"name": "Tech Tracker",
"slug": "tech-tracker-expo",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "com.techtracker",
"userInterfaceStyle": "automatic",
"splash": {
"image": "./assets/images/splash.png",
"resizeMode": "contain",
"backgroundColor": "#2e2f3d"
},
"newArchEnabled": true,
"ios": {
"usesAppleSignIn": true,
"supportsTablet": true,
"bundleIdentifier": "com.gibbyb.techtrackerexpo"
"bundleIdentifier": "com.gbrown.techtracker",
"config": {
"usesNonExemptEncryption": false
},
"infoPlist": {
"ITSAppUsesNonExemptEncryption": false,
"NSLocationWhenInUseUsageDescription": "This app uses your location in order to allow you to share your location in chat.",
"NSCameraUsageDescription": "This app uses your camera to take photos & send them in the chat."
}
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/adaptive-icon.png",
"backgroundColor": "#ffffff"
"backgroundColor": "#2e2f3d"
},
"package": "com.gibbyb.techtrackerexpo"
"permissions": [
"android.permission.ACCESS_COARSE_LOCATION",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.RECEIVE_BOOT_COMPLETED",
"android.permission.VIBRATE",
"android.permission.INTERNET"
],
"package": "com.gbrown.techtracker"
},
"web": {
"bundler": "metro",
@ -36,8 +56,27 @@
"backgroundColor": "#ffffff"
}
],
[
"expo-secure-store",
"expo-apple-authentication"
{
"faceIDPermission": "Allow $(PRODUCT_NAME) to access your FaceID biometric data."
}
],
"expo-apple-authentication",
[
"expo-location",
{
"locationAlwaysAndWhenInUsePermission": "Allow $(PRODUCT_NAME) to use your location."
}
],
[
"@sentry/react-native/expo",
{
"organization": "gib",
"project": "tech-tracker",
"url": "https://sentry.gbrown.org/"
}
]
],
"experiments": {
"typedRoutes": true
@ -51,8 +90,6 @@
"updates": {
"url": "https://u.expo.dev/7d872415-9160-4e06-ba95-4c3442e04b79"
},
"runtimeVersion": {
"policy": "appVersion"
}
"runtimeVersion": "1.0.0"
}
}

View File

@ -1,21 +1,20 @@
import { Image, StyleSheet, Platform } from 'react-native';
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
import { ThemedText, ThemedView } from '@/components/theme';
import StatusList from '@/components/status/StatusList';
const HomeScreen = () => {
return (
<ParallaxScrollView
headerImage={
<Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.reactLogo} />
}
<StatusList
headerTitle={
<ThemedText type='title' style={styles.headerTitle}>
<ThemedText style={styles.headerTitle}>
Tech Tracker
</ThemedText>
}
>
<ThemedView style={styles.titleContainer}></ThemedView>
</ParallaxScrollView>
headerImage={
<Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.techTrackerLogo} />
}
/>
);
};
export default HomeScreen;
@ -30,17 +29,17 @@ const styles = StyleSheet.create({
gap: 8,
marginBottom: 8,
},
reactLogo: {
techTrackerLogo: {
height: 70,
width: 72,
bottom: 10,
left: 40,
left: Platform.OS === 'ios' ? 40 : 20,
position: 'absolute',
},
headerTitle: {
position: 'absolute',
bottom: 20,
left: 75,
left: 80,
right: 0,
textAlign: 'center',
fontSize: 48,

View File

@ -1,46 +0,0 @@
import { StyleSheet, Image, Platform } from 'react-native';
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
import { ThemedText, ThemedView } from '@/components/theme';
import { IconSymbol } from '@/components/ui/IconSymbol';
import Logout_Button from '@/components/auth/Logout_Button';
const TabTwoScreen = () => {
return (
<ParallaxScrollView
headerImage={
<IconSymbol size={80} color='#808080' name='gear.circle' style={styles.headerImage} />
}
headerTitle={
<ThemedText type='title' style={styles.headerTitle}>
Settings
</ThemedText>
}
>
<Logout_Button />
</ParallaxScrollView>
);
};
export default TabTwoScreen;
const styles = StyleSheet.create({
headerImage: {
color: '#808080',
bottom: 6,
left: 38,
position: 'absolute',
},
headerTitle: {
position: 'absolute',
bottom: 20,
left: 16,
right: 0,
textAlign: 'center',
fontSize: 48,
lineHeight: 64,
fontWeight: 'bold',
},
titleContainer: {
flexDirection: 'row',
gap: 8,
},
});

View File

@ -0,0 +1,39 @@
import { Stack } from 'expo-router';
import { useColorScheme } from '@/hooks/useColorScheme';
import { Colors } from '@/constants/Colors';
export default function SettingsLayout() {
const scheme = useColorScheme() ?? 'dark';
return (
<Stack
screenOptions={{
headerStyle: {
backgroundColor: Colors[scheme].background,
},
headerTintColor: Colors[scheme].text,
headerTitleStyle: {
fontWeight: 'bold',
},
// This gives the iOS-style slide-in animation
animation: 'slide_from_right',
}}
>
<Stack.Screen
name="index"
options={{
title: "Settings",
headerShown: false,
}}
/>
<Stack.Screen
name="profile"
options={{
title: "Profile",
headerShown: true,
}}
/>
{/* Add more screens as needed */}
</Stack>
);
}

View File

@ -0,0 +1,91 @@
import { StyleSheet, TouchableOpacity } from 'react-native';
import { useRouter } from 'expo-router';
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
import { ThemedText, ThemedTextButton, ThemedView } from '@/components/theme';
import { IconSymbol } from '@/components/ui/IconSymbol';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const SettingsScreen = () => {
const scheme = useColorScheme() ?? 'dark';
const router = useRouter();
return (
<ParallaxScrollView
headerImage={
<IconSymbol size={80} color='#808080' name='gear.circle' style={styles.headerImage} />
}
headerTitle={
<ThemedText type='title' style={styles.headerTitle}>
Settings
</ThemedText>
}
>
<ThemedView style={styles.section}>
<TouchableOpacity
style={[styles.settingItem, {backgroundColor: Colors[scheme].card}]}
onPress={() => router.push('/settings/profile')}
>
<IconSymbol name="person.fill" size={24} color="#007AFF" style={styles.icon} />
<ThemedView style={styles.settingContent}>
<ThemedText style={styles.settingTitle}>Profile Settings</ThemedText>
<ThemedText style={styles.settingSubtitle}>Update profile information or sign out.</ThemedText>
</ThemedView>
<IconSymbol name="chevron.right" size={20} color="#C7C7CC" />
</TouchableOpacity>
</ThemedView>
<ThemedView style={styles.section}>
</ThemedView>
</ParallaxScrollView>
);
};
export default SettingsScreen;
const styles = StyleSheet.create({
headerImage: {
color: '#808080',
bottom: 6,
left: 38,
position: 'absolute',
},
headerTitle: {
position: 'absolute',
bottom: 20,
left: 16,
right: 0,
textAlign: 'center',
fontSize: 48,
lineHeight: 64,
fontWeight: 'bold',
},
section: {
marginVertical: 8,
borderRadius: 10,
overflow: 'hidden',
},
settingItem: {
flexDirection: 'row',
alignItems: 'center',
padding: 16,
marginBottom: 1,
},
icon: {
marginRight: 16,
},
settingContent: {
backgroundColor: 'transparent',
flex: 1,
},
settingTitle: {
fontSize: 17,
fontWeight: '500',
},
settingSubtitle: {
fontSize: 14,
opacity: 0.6,
marginTop: 4,
},
});

View File

@ -0,0 +1,224 @@
import React, { useState, useEffect, useRef } from 'react';
import {
StyleSheet,
Alert,
ActivityIndicator,
ScrollView,
} from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import ProfileAvatar from '@/components/auth/Profile_Avatar';
import LogoutButton from '@/components/auth/Logout_Button';
import { useFocusEffect } from '@react-navigation/native';
const ProfileScreen = () => {
const [loading, setLoading] = useState(true);
const [updating, setUpdating] = useState(false);
const [profile, setProfile] = useState({
full_name: '',
email: '',
avatar_url: null,
provider: ''
});
// Fetch profile when screen comes into focus
useFocusEffect(
React.useCallback(() => {
fetchUserProfile();
}, [])
);
const fetchUserProfile = async () => {
setLoading(true);
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
throw new Error('Not authenticated');
}
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('id', user.id)
.single();
if (error) throw error;
if (data) {
setProfile({
full_name: data.full_name || '',
email: data.email || '',
avatar_url: data.avatar_url,
provider: data.provider || ''
});
}
} catch (error) {
console.error('Error fetching profile:', error);
Alert.alert('Error', 'Failed to load profile information');
} finally {
setLoading(false);
}
};
const updateProfile = async () => {
setUpdating(true);
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('Not authenticated');
// Validate input
if (!profile.full_name.trim()) {
Alert.alert('Error', 'Please enter your full name');
return;
}
const updates = {
id: user.id,
full_name: profile.full_name.trim(),
updated_at: new Date(),
};
const { error } = await supabase
.from('profiles')
.upsert(updates);
if (error) throw error;
Alert.alert('Success', 'Profile updated successfully!');
} catch (error) {
Alert.alert('Error', error instanceof Error ? error.message : 'Failed to update profile');
} finally {
setUpdating(false);
}
};
const handleAvatarUpload = () => {
// Refresh profile data after avatar upload
fetchUserProfile();
};
if (loading) {
return (
<ThemedView style={styles.loadingContainer}>
<ActivityIndicator size="large" />
</ThemedView>
);
}
return (
<ScrollView
contentContainerStyle={styles.scrollContainer}
keyboardShouldPersistTaps='never'
>
<ThemedView style={styles.container}>
<ThemedView style={styles.avatarContainer}>
<ProfileAvatar
url={profile.avatar_url}
size={120}
onUpload={handleAvatarUpload}
disabled={updating}
/>
</ThemedView>
{profile.provider && (
<ThemedText style={styles.providerText}>
Signed in with {profile.provider.charAt(0).toUpperCase() + profile.provider.slice(1)}
</ThemedText>
)}
<ThemedView style={styles.formSection}>
<ThemedText type='title' style={styles.label}>Name</ThemedText>
<ThemedTextInput
value={profile.full_name}
onChangeText={(text) => setProfile(prev => ({ ...prev, full_name: text }))}
placeholder="Enter your full name"
style={styles.input}
fontSize={20}
height={55}
editable={!updating}
autoCapitalize='words'
textContentType='name'
maxLength={50}
returnKeyType='done'
secureTextEntry={false}
/>
</ThemedView>
<ThemedTextButton
text={updating ? 'Saving...' : 'Save Changes'}
onPress={updateProfile}
disabled={updating || !profile.full_name.trim()}
fontSize={18}
fontWeight='semibold'
width='90%'
style={styles.saveButton}
/>
<LogoutButton
fontSize={18}
fontWeight='semibold'
width='90%'
style={styles.logoutButton}
/>
</ThemedView>
</ScrollView>
);
};
export default ProfileScreen;
const styles = StyleSheet.create({
scrollContainer: {
flexGrow: 1,
},
container: {
flex: 1,
padding: 16,
alignItems: 'center',
},
avatarContainer: {
marginVertical: 20,
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
formSection: {
marginBottom: 20,
width: '100%',
alignItems: 'center',
},
label: {
marginBottom: 8,
fontSize: 18,
fontWeight: '500',
alignSelf: 'flex-start',
marginLeft: '5%',
},
input: {
paddingVertical: 12,
paddingHorizontal: 10,
borderRadius: 8,
marginBottom: 20,
},
disabledInput: {
opacity: 0.7,
},
saveButton: {
borderRadius: 8,
marginTop: 20,
marginBottom: 10,
alignItems: 'center',
},
logoutButton: {
marginTop: 10,
borderRadius: 8,
alignItems: 'center',
},
providerText: {
marginBottom: 20,
fontSize: 14,
opacity: 0.7,
}
});

View File

@ -1,6 +1,6 @@
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import { Stack, useNavigationContainerRef } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect, useState } from 'react';
@ -9,8 +9,24 @@ import { ThemedView } from '@/components/theme';
import { Session } from '@supabase/supabase-js';
import { useColorScheme } from '@/hooks/useColorScheme';
import { supabase } from '@/lib/supabase';
import LoginPage from '@/components/auth/Login';
import Account from '@/components/Account';
import Auth from '@/components/auth/Auth';
import PushNotificationManager from '@/services/PushNotificationManager';
import * as Sentry from '@sentry/react-native';
import { isRunningInExpoGo } from 'expo';
const navigationIntegration = Sentry.reactNavigationIntegration({
enableTimeToInitialDisplay: !isRunningInExpoGo(),
});
Sentry.init({
dsn: process.env.EXPO_PUBLIC_SENTRY_DSN,
debug: true,
tracesSampleRate: 1.0,
integrations: [
navigationIntegration,
],
enableNativeFramesTracking: !isRunningInExpoGo(),
});
// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
@ -18,6 +34,7 @@ SplashScreen.preventAutoHideAsync();
const RootLayout = () => {
const scheme = useColorScheme() ?? 'dark';
const [session, setSession] = useState<Session | null>(null);
const ref = useNavigationContainerRef();
const [loaded] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
@ -39,11 +56,18 @@ const RootLayout = () => {
}
}, [loaded]);
useEffect(() => {
if (ref?.current) {
navigationIntegration.registerNavigationContainer(ref);
}
}, [ref])
if (!loaded) {
return null;
}
return (
<PushNotificationManager>
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
{session && session.user ? (
<Stack>
@ -52,12 +76,13 @@ const RootLayout = () => {
</Stack>
) : (
<ThemedView style={{ flex: 1 }}>
<LoginPage />
<Auth />
</ThemedView>
)}
<StatusBar style='auto' />
</ThemeProvider>
</PushNotificationManager>
);
};
export default RootLayout;
export default Sentry.wrap(RootLayout);

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 B

View File

@ -1,120 +0,0 @@
import { useState, useEffect } from 'react';
import { supabase } from '../lib/supabase';
import { StyleSheet, View, Alert } from 'react-native';
import { Button, Input } from '@rneui/themed';
import { Session } from '@supabase/supabase-js';
export default function Account({ session }: { session: Session }) {
const [loading, setLoading] = useState(true);
const [username, setUsername] = useState('');
const [website, setWebsite] = useState('');
const [avatarUrl, setAvatarUrl] = useState('');
useEffect(() => {
if (session) getProfile();
}, [session]);
async function getProfile() {
try {
setLoading(true);
if (!session?.user) throw new Error('No user on the session!');
const { data, error, status } = await supabase
.from('profiles')
.select(`username, website, avatar_url`)
.eq('id', session?.user.id)
.single();
if (error && status !== 406) {
throw error;
}
if (data) {
setUsername(data.username);
setWebsite(data.website);
setAvatarUrl(data.avatar_url);
}
} catch (error) {
if (error instanceof Error) {
Alert.alert(error.message);
}
} finally {
setLoading(false);
}
}
async function updateProfile({
username,
website,
avatar_url,
}: {
username: string;
website: string;
avatar_url: string;
}) {
try {
setLoading(true);
if (!session?.user) throw new Error('No user on the session!');
const updates = {
id: session?.user.id,
username,
website,
avatar_url,
updated_at: new Date(),
};
const { error } = await supabase.from('profiles').upsert(updates);
if (error) {
throw error;
}
} catch (error) {
if (error instanceof Error) {
Alert.alert(error.message);
}
} finally {
setLoading(false);
}
}
return (
<View style={styles.container}>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Input label='Email' value={session?.user?.email} disabled />
</View>
<View style={styles.verticallySpaced}>
<Input label='Username' value={username || ''} onChangeText={(text) => setUsername(text)} />
</View>
<View style={styles.verticallySpaced}>
<Input label='Website' value={website || ''} onChangeText={(text) => setWebsite(text)} />
</View>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Button
title={loading ? 'Loading ...' : 'Update'}
onPress={() => updateProfile({ username, website, avatar_url: avatarUrl })}
disabled={loading}
/>
</View>
<View style={styles.verticallySpaced}>
<Button title='Sign Out' onPress={() => supabase.auth.signOut()} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginTop: 40,
padding: 12,
},
verticallySpaced: {
paddingTop: 4,
paddingBottom: 4,
alignSelf: 'stretch',
},
mt20: {
marginTop: 20,
},
});

View File

@ -1,128 +0,0 @@
import React, { useState, useEffect } from 'react';
import { StyleSheet, Alert, Platform } from 'react-native';
import * as AppleAuthentication from 'expo-apple-authentication';
import { supabase } from '@/lib/supabase';
import { useColorScheme } from '@/hooks/useColorScheme';
type AppleSignInProps = {
onSignInStart?: () => void;
onSignInComplete?: () => void;
onSignInError?: (error: any) => void;
};
const AppleSignIn: React.FC<AppleSignInProps> = ({
onSignInStart,
onSignInComplete,
onSignInError,
}) => {
const scheme = useColorScheme() ?? 'dark';
const [isAppleAuthAvailable, setIsAppleAuthAvailable] = useState(false);
useEffect(() => {
if (Platform.OS === 'ios') {
AppleAuthentication.isAvailableAsync().then(setIsAppleAuthAvailable);
}
}, []);
const handleAppleSignIn = async () => {
try {
onSignInStart?.();
// Get credentials from Apple
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
if (!credential.email) {
throw new Error('Email is required for Apple Sign In');
}
// Extract user information
const { email, fullName, user: appleUserId } = credential;
// Create a name from the fullName object if available
let name = null;
if (fullName?.givenName || fullName?.familyName) {
name = `${fullName?.givenName || ''} ${fullName?.familyName || ''}`.trim();
}
// Create a deterministic password based on the Apple user ID
// This way the user can sign in again with the same password
const password = `Apple-${appleUserId.substring(0, 16)}`;
// First try to sign in (in case the user already exists)
const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
});
if (!signInError && signInData?.user) {
// User exists and signed in successfully
onSignInComplete?.();
return;
}
// If sign-in failed, create a new user
const { data: signUpData, error: signUpError } = await supabase.auth.signUp({
email,
password,
options: {
data: {
full_name: name,
},
},
});
if (signUpError) {
throw signUpError;
}
// User created successfully
onSignInComplete?.();
} catch (error) {
console.error('Apple sign in error:', error);
if (error.code === 'ERR_REQUEST_CANCELED') {
console.log('Sign in was canceled');
} else {
Alert.alert(
'Sign in error',
'An error occurred while signing in with Apple. Please try again.',
);
onSignInError?.(error);
}
}
};
// Only render on iOS and if Apple Authentication is available
if (Platform.OS !== 'ios' || !isAppleAuthAvailable) {
return null;
}
return (
<AppleAuthentication.AppleAuthenticationButton
buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
buttonStyle={
scheme === 'light'
? AppleAuthentication.AppleAuthenticationButtonStyle.BLACK
: AppleAuthentication.AppleAuthenticationButtonStyle.WHITE
}
cornerRadius={10}
style={styles.button}
onPress={handleAppleSignIn}
/>
);
};
const styles = StyleSheet.create({
button: {
width: 320,
height: 50,
marginVertical: 10,
},
});
export default AppleSignIn;

View File

@ -0,0 +1,96 @@
import React, { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import * as AppleAuthentication from 'expo-apple-authentication';
import { useColorScheme } from '@/hooks/useColorScheme';
import { ThemedView } from '@/components/theme';
import { StyleSheet, Platform, Alert } from 'react-native';
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
import type { updateUser } from '@/constants/Types';
const AppleSignInButton = () => {
const scheme = useColorScheme() ?? 'dark';
const signInWithApple = async () => {
try {
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
//const projectId = Constants.expoConfig?.extra?.projectId;
//if (!projectId) throw new Error('No projectId found in expo.config.json');
//const pushToken = await Notifications.getExpoPushTokenAsync({
//projectId,
//});
if (credential.identityToken) {
const email = credential.email;
const full_name =
credential.fullName && credential.fullName.givenName && credential.fullName.familyName
? `${credential.fullName.givenName} ${credential.fullName.familyName}`
: null;
const {
error,
data: { user, session },
} = await supabase.auth.signInWithIdToken({
provider: 'apple',
token: credential.identityToken,
});
console.log(JSON.stringify({ error, user }, null, 2));
if (!error && session) {
if (email) {
const data: updateUser = {
id: session?.user.id,
updated_at: new Date(),
email,
full_name: full_name ?? '',
provider: 'apple',
};
const { error: updateError } = await supabase.auth.updateUser({ data });
if (updateError) Alert.alert('Error updating auth info:', updateError.message);
const { error: updateProfileError } = await supabase
.from('profiles')
.upsert({
id: session?.user.id ?? '',
updated_at: new Date(),
email: email ?? '',
full_name: full_name ?? '',
provider: 'apple',
});
if (updateProfileError)
Alert.alert('Error updating profile:', updateProfileError.message);
}
}
} else {
throw new Error('No identityToken.');
}
} catch (e: any) {
if (e.code === 'ERR_REQUEST_CANCELED') {
// handle that the user canceled the sign-in flow
console.log('User canceled sign-in flow');
} else {
// handle other errors
console.log('Error signing in with Apple:', e);
}
}
};
if (Platform.OS !== 'ios') return <ThemedView />;
else
return (
<AppleAuthentication.AppleAuthenticationButton
buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
buttonStyle={
scheme === 'light'
? AppleAuthentication.AppleAuthenticationButtonStyle.BLACK
: AppleAuthentication.AppleAuthenticationButtonStyle.WHITE
}
cornerRadius={5}
style={{ width: '85%', height: 64 }}
onPress={signInWithApple}
/>
);
};
export default AppleSignInButton;

View File

@ -2,7 +2,10 @@ import React, { useState, useEffect } from 'react';
import { Alert, StyleSheet, AppState, Image, Platform } from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import AppleSignIn from '@/components/auth/AppleSignIn';
import AppleSignInButton from '@/components/auth/AppleSignIniOS';
import AzureSignIn from './AzureSignIn';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
// Tells Supabase Auth to continuously refresh the session automatically if
// the app is in the foreground. When this is added, you will continue to receive
@ -18,7 +21,10 @@ if (Platform.OS !== 'web') {
});
}
const LoginPage = () => {
const Auth = () => {
const scheme = useColorScheme() ?? 'dark';
const [full_name, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
@ -49,8 +55,14 @@ const LoginPage = () => {
data: { session },
error,
} = await supabase.auth.signUp({
email: email,
password: password,
email,
password,
options: {
data: {
full_name,
provider: 'email',
}
}
});
if (error) Alert.alert(error.message);
else if (!session) Alert.alert('Please check your inbox for email verification!');
@ -66,17 +78,33 @@ const LoginPage = () => {
</ThemedText>
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<ThemedTextInput
height={60}
fontSize={24}
onChangeText={(text) => setFullName(text)}
value={full_name}
secureTextEntry={false}
autoCapitalize='words'
placeholder='Full Name'
/>
</ThemedView>
<ThemedView style={[styles.verticallySpaced]}>
<ThemedTextInput
height={60}
fontSize={24}
onChangeText={(text) => setEmail(text)}
value={email}
secureTextEntry={false}
autoCapitalize='none'
placeholder='email@address.com'
/>
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<ThemedTextInput
height={60}
fontSize={24}
onChangeText={(text) => setPassword(text)}
value={password}
@ -85,37 +113,53 @@ const LoginPage = () => {
/>
</ThemedView>
<ThemedView style={[styles.verticallySpaced, styles.mt20]}>
<ThemedView style={styles.verticallySpaced}>
<ThemedView style={styles.horizontallySpaced}>
<ThemedTextButton
text='Sign in'
disabled={loading}
onPress={() => signInWithEmail()}
fontSize={24}
fontSize={28}
fontWeight='semibold'
width='50%'
/>
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<ThemedTextButton
text='Sign up'
disabled={loading}
onPress={() => signUpWithEmail()}
fontSize={24}
fontSize={28}
fontWeight='semibold'
width='50%'
/>
</ThemedView>
</ThemedView>
{/* Apple Sign In - Only shows on iOS */}
<ThemedView style={[styles.verticallySpaced, styles.mt20]}>
<AppleSignIn
onSignInStart={() => setLoading(true)}
onSignInComplete={() => setLoading(false)}
onSignInError={() => setLoading(false)}
/>
{ Platform.OS === 'ios' && (
<ThemedView style={styles.divider}>
<ThemedView style={[styles.dividerLine, { backgroundColor: Colors[scheme].text }]} />
<ThemedText type='subtitle' style={styles.dividerText}>or</ThemedText>
<ThemedView style={[styles.dividerLine, { backgroundColor: Colors[scheme].text }]} />
</ThemedView>
)}
<ThemedView style={styles.verticallySpaced}>
<AppleSignInButton />
</ThemedView>
<ThemedView style={styles.divider}>
<ThemedView style={[styles.dividerLine, { backgroundColor: Colors[scheme].text }]} />
<ThemedText type='subtitle' style={styles.dividerText}>or</ThemedText>
<ThemedView style={[styles.dividerLine, { backgroundColor: Colors[scheme].text }]} />
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<AzureSignIn />
</ThemedView>
</ThemedView>
);
};
export default LoginPage;
export default Auth;
const styles = StyleSheet.create({
container: {
@ -127,6 +171,14 @@ const styles = StyleSheet.create({
paddingBottom: 4,
alignItems: 'center',
},
horizontallySpaced: {
flexDirection: 'row',
paddingLeft: 4,
paddingRight: 4,
alignItems: 'center',
justifyContent: 'center',
width: '90%',
},
mt20: {
marginTop: 20,
},
@ -152,11 +204,18 @@ const styles = StyleSheet.create({
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
marginVertical: 20,
marginVertical: 5,
width: '80%',
alignSelf: 'center',
},
dividerText: {
marginHorizontal: 10,
fontSize: 16,
marginHorizontal: 15,
fontSize: 14,
opacity: 0.7,
},
dividerLine: {
flex: 1,
height: 1,
opacity: 0.3,
}
});

View File

@ -0,0 +1,149 @@
import React, { useState } from 'react';
import { Image, StyleSheet, Alert } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
import * as AuthSession from 'expo-auth-session';
import * as QueryParams from 'expo-auth-session/build/QueryParams';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedButton, ThemedText } from '@/components/theme';
import { Colors } from '@/constants/Colors';
import type { updateUser } from '@/constants/Types';
WebBrowser.maybeCompleteAuthSession();
// Configuration for Azure AD
const tenantId = process.env.EXPO_PUBLIC_AZURE_TENANT_ID;
const clientId = process.env.EXPO_PUBLIC_AZURE_CLIENT_ID;
// Create MSAL auth request
const redirectUri = Linking.createURL('auth/callback');
const discovery = {
authorizationEndpoint: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize`,
tokenEndpoint: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
};
const AzureSignIn = () => {
const [loading, setLoading] = useState(false);
const signInWithAzure = async () => {
try {
setLoading(true);
// Create the MSAL auth request
const request = new AuthSession.AuthRequest({
clientId: clientId!,
scopes: ['openid', 'profile', 'email', 'offline_access', 'User.Read'],
redirectUri,
usePKCE: true,
responseType: AuthSession.ResponseType.Code,
});
// Generate the auth URL with PKCE & open in browser
const authUrl = await request.makeAuthUrlAsync(discovery);
const result = await WebBrowser.openAuthSessionAsync(authUrl, redirectUri, {
showInRecents: true,
});
if (result.type === 'success' && result.url) {
// Parse the URL to get the authorization code
const { params, errorCode } = QueryParams.getQueryParams(result.url);
if (errorCode || params.error) {
const errorMessage = params.error_description || params.error || errorCode;
throw new Error(`Error during authentication: ${errorMessage}`);
}
if (!params.code) {
throw new Error('No authorization code received');
}
// Exchange the code for tokens
const tokenResult = await AuthSession.exchangeCodeAsync(
{
clientId: clientId!,
code: params.code,
redirectUri,
extraParams: {
code_verifier: request.codeVerifier || '',
},
},
discovery,
);
if (!tokenResult.idToken) {
throw new Error('No ID token received');
}
// Now use the ID token to sign in with Supabase
const { data, error } = await supabase.auth.signInWithIdToken({
provider: 'azure',
token: tokenResult.idToken,
});
console.log(JSON.stringify({ data, error }, null, 2));
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('*')
.eq('id', data.user?.id)
.single();
if (profileError) {
console.error('Supabase profile error:', profileError);
throw profileError;
}
console.log(JSON.stringify({ profile, error: profileError }, null, 2));
if (profile?.provider !== 'azure') {
const { error: updateProfileError } = await supabase
.from('profiles')
.upsert({
id: data.session?.user.id ?? '',
provider: 'azure',
updated_at: new Date(),
});
if (updateProfileError) {
console.error('Supabase profile error:', updateProfileError);
Alert.alert('Error updating profile:', updateProfileError.message);
}
}
if (error) {
console.error('Supabase sign-in error:', error);
throw error;
}
console.log('Successfully signed in with Azure via Supabase');
return data;
} else {
console.log('Authentication was canceled or failed');
}
} catch (error: any) {
console.error('Error signing in with Azure:', error);
Alert.alert('Sign In Error', error.message || 'An error occurred during sign in');
} finally {
setLoading(false);
}
};
return (
<ThemedButton disabled={loading} onPress={signInWithAzure}>
<Image source={require('@/assets/images/Microsoft_Logo.png')} style={styles.microsoftLogo} />
<ThemedText
type='custom'
fontWeight='semibold'
fontSize={26}
lightColor={Colors.dark.text}
darkColor={Colors.light.text}
>
{loading ? 'Signing in...' : 'Sign in with Microsoft'}
</ThemedText>
</ThemedButton>
);
};
export default AzureSignIn;
const styles = StyleSheet.create({
microsoftLogo: {
height: 30,
width: 30,
marginRight: 10,
},
});

View File

@ -1,8 +1,30 @@
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import { Alert, StyleSheet, AppState } from 'react-native';
import { ThemedTextButton } from '@/components/theme';
import { Alert, StyleSheet } from 'react-native';
import React from 'react';
import { TextStyle, PressableProps, DimensionValue } from 'react-native';
const Logout_Button = () => {
// Extend ThemedButton props (which already extends PressableProps)
type ThemedTextButtonProps = Omit<PressableProps, 'children'> & {
width?: DimensionValue;
height?: DimensionValue;
fontSize?: number;
fontWeight?: 'normal' | 'semibold' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
textStyle?: TextStyle;
containerStyle?: object;
buttonStyle?: object;
};
const Logout_Button: React.FC<ThemedTextButtonProps> = ({
width,
height,
fontSize = 16,
fontWeight = 'normal',
textStyle,
containerStyle,
buttonStyle,
...restProps
}) => {
const signOut = async () => {
const { error } = await supabase.auth.signOut();
if (error) Alert.alert(error.message);
@ -10,14 +32,18 @@ const Logout_Button = () => {
return (
<ThemedTextButton
width={120}
height={60}
text='Logout'
fontSize={16}
width={width}
height={height}
textColor='white'
backgroundColor='red'
fontSize={fontSize}
fontWeight={fontWeight}
containerStyle={containerStyle}
buttonStyle={buttonStyle}
onPress={() => signOut()}
{...restProps}
/>
);
};
export default Logout_Button;
const styles = StyleSheet.create({});

View File

@ -0,0 +1,184 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { StyleSheet, Alert, Image, TouchableOpacity, ActivityIndicator } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
import { ThemedView, ThemedText } from '../theme';
import { IconSymbol } from '@/components/ui/IconSymbol';
interface AvatarProps {
size?: number;
url: string | null;
onUpload?: (filePath: string) => void;
disabled?: boolean;
}
export default function ProfileAvatar({
url,
size = 120,
onUpload,
disabled = false
}: AvatarProps) {
const [uploading, setUploading] = useState(false);
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
useEffect(() => {
if (url) downloadImage(url);
}, [url]);
async function downloadImage(path: string) {
try {
const { data, error } = await supabase.storage.from('avatars').download(path);
if (error) throw error;
const fr = new FileReader();
fr.readAsDataURL(data);
fr.onload = () => {
setAvatarUrl(fr.result as string);
};
} catch (error) {
console.log('Error downloading image: ', error instanceof Error ? error.message : error);
}
}
async function uploadAvatar() {
if (disabled || uploading) return;
try {
setUploading(true);
// Get current user
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('User not authenticated');
// Request permission if needed
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (!permissionResult.granted) {
Alert.alert('Permission Required', 'Please allow access to your photo library to upload an avatar.');
return;
}
// Launch image picker
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsMultipleSelection: false,
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
exif: false,
});
if (result.canceled || !result.assets || result.assets.length === 0) {
return;
}
const image = result.assets[0];
// Compress and resize the image
const compressedImage = await manipulateAsync(
image.uri,
[{ resize: { width: 300, height: 300 } }],
{ compress: 0.7, format: SaveFormat.JPEG }
);
// Get file info to check size
const fileInfo = await FileSystem.getInfoAsync(compressedImage.uri);
// Convert to array buffer for upload
const arraybuffer = await fetch(compressedImage.uri).then((res) => res.arrayBuffer());
// Generate unique filename
const fileExt = compressedImage.uri.split('.').pop()?.toLowerCase() ?? 'jpg';
const fileName = `${user.id}_${Date.now()}.${fileExt}`;
// Upload to Supabase Storage
const { data, error: uploadError } = await supabase.storage
.from('avatars')
.upload(fileName, arraybuffer, {
contentType: `image/${fileExt}`,
upsert: true,
});
if (uploadError) throw uploadError;
// Update user profile with new avatar URL
const { error: updateError } = await supabase
.from('profiles')
.update({
avatar_url: data.path,
updated_at: new Date()
})
.eq('id', user.id);
if (updateError) throw updateError;
// Set the new avatar URL
setAvatarUrl(compressedImage.uri);
// Call the onUpload callback if provided
if (onUpload) onUpload(data.path);
Alert.alert('Success', 'Avatar updated successfully!');
} catch (error) {
Alert.alert('Error uploading avatar', error instanceof Error ? error.message : 'An unknown error occurred');
} finally {
setUploading(false);
}
}
return (
<TouchableOpacity
onPress={uploadAvatar}
style={[styles.avatarContainer, { opacity: disabled ? 0.7 : 1 }]}
disabled={disabled || uploading}
>
{avatarUrl ? (
<Image
source={{ uri: avatarUrl }}
style={[styles.avatar, { width: size, height: size, borderRadius: size / 2 }]}
/>
) : (
<ThemedView style={[styles.avatarPlaceholder, { width: size, height: size, borderRadius: size / 2 }]}>
<IconSymbol name="person.fill" size={size / 2.5} color="#999" />
</ThemedView>
)}
{uploading ? (
<ActivityIndicator style={styles.uploadingIndicator} size="small" color="#007AFF" />
) : (
disabled ? (
<ThemedView />
) : (
<ThemedText style={styles.changePhotoText}>
Change Photo
</ThemedText>
)
)}
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
avatarContainer: {
alignItems: 'center',
},
avatar: {
backgroundColor: '#E1E1E1',
},
avatarPlaceholder: {
backgroundColor: '#E1E1E1',
justifyContent: 'center',
alignItems: 'center',
},
changePhotoText: {
marginTop: 8,
color: '#007AFF',
fontSize: 16,
},
uploadingIndicator: {
marginTop: 8,
}
});

View File

@ -55,6 +55,8 @@ const ParallaxScrollView = ({
scrollEventThrottle={16}
scrollIndicatorInsets={{ bottom }}
contentContainerStyle={{ paddingBottom: bottom }}
keyboardShouldPersistTaps='handled'
keyboardDismissMode='interactive'
>
<Animated.View
style={[

View File

@ -0,0 +1,217 @@
import React, { useState } from 'react';
import {
StyleSheet,
Modal,
TouchableWithoutFeedback,
KeyboardAvoidingView,
Platform,
View,
ActivityIndicator,
Alert
} from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextInput, ThemedTextButton } from '@/components/theme';
import ProfileAvatar from '@/components/auth/Profile_Avatar';
interface StatusCardProps {
visible: boolean;
user: {
user_id: string;
status: string;
profiles: {
full_name: string;
avatar_url: string | null;
};
};
onClose: () => void;
onUpdate: () => void;
}
export default function StatusCard({ visible, user, onClose, onUpdate }: StatusCardProps) {
const [newStatus, setNewStatus] = useState('');
const [updating, setUpdating] = useState(false);
const handleUpdateStatus = async () => {
if (!newStatus.trim() || newStatus.trim().length < 3) {
Alert.alert('Invalid Status', 'Status must be at least 3 characters long.');
return;
}
setUpdating(true);
try {
const { data: { user: currentUser } } = await supabase.auth.getUser();
if (!currentUser) throw new Error('Not authenticated');
// Insert new status
const { error } = await supabase
.from('statuses')
.insert({
user_id: user.user_id,
status: newStatus.trim()
});
if (error) throw error;
setNewStatus('');
onUpdate();
} catch (error) {
Alert.alert('Error', error instanceof Error ? error.message : 'Failed to update status');
console.error('Status update error:', error);
} finally {
setUpdating(false);
}
};
const handleCancel = () => {
setNewStatus('');
onClose();
};
return (
<Modal
animationType="slide"
transparent={true}
visible={visible}
onRequestClose={onClose}
>
<TouchableWithoutFeedback onPress={onClose}>
<View style={styles.modalOverlay} />
</TouchableWithoutFeedback>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.keyboardAvoidingView}
>
<ThemedView style={styles.modalContent}>
<View style={styles.handle} />
<View style={styles.userInfoContainer}>
<ProfileAvatar
url={user.profiles.avatar_url}
size={75}
disabled={true}
/>
<ThemedText style={styles.userName}>
{user.profiles.full_name}
</ThemedText>
<ThemedText style={styles.currentStatus}>
{user.status}
</ThemedText>
</View>
<ThemedView style={styles.inputContainer}>
<ThemedText style={styles.inputLabel}>New Status</ThemedText>
<ThemedTextInput
value={newStatus}
onChangeText={setNewStatus}
placeholder="What's happening?"
fontSize={18}
maxLength={80}
width='95%'
height={80}
multiline
style={styles.input}
editable={!updating}
onSubmitEditing={handleUpdateStatus}
returnKeyType='send'
/>
<ThemedText style={styles.charCount}>
{newStatus.length}/80
</ThemedText>
</ThemedView>
<ThemedTextButton
text={updating ? 'Updating...' : 'Update Status'}
onPress={handleUpdateStatus}
disabled={updating || newStatus.trim().length < 3}
fontSize={18}
fontWeight='semibold'
width='100%'
style={styles.updateButton}
/>
<ThemedTextButton
text='Cancel'
onPress={handleCancel}
backgroundColor='red'
disabled={updating}
textColor='white'
width='100%'
fontSize={18}
fontWeight='500'
/>
</ThemedView>
</KeyboardAvoidingView>
</Modal>
);
}
const styles = StyleSheet.create({
modalOverlay: {
flex: 1,
},
keyboardAvoidingView: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
modalContent: {
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
padding: 20,
paddingBottom: Platform.OS === 'ios' ? 40 : 20,
},
handle: {
width: 40,
height: 5,
borderRadius: 3,
backgroundColor: '#ccc',
alignSelf: 'center',
marginBottom: 20,
},
userInfoContainer: {
alignItems: 'center',
marginBottom: 20,
},
userName: {
fontSize: 20,
fontWeight: '600',
marginTop: 10,
},
currentStatus: {
fontSize: 18,
marginTop: 5,
opacity: 0.7,
},
inputContainer: {
marginBottom: 10,
alignItems: 'center',
padding: 10,
},
inputLabel: {
fontSize: 18,
fontWeight: '500',
marginBottom: 8,
alignSelf: 'flex-start',
marginLeft: '5%',
},
input: {
paddingVertical: 12,
paddingHorizontal: 10,
minHeight: 100,
textAlignVertical: 'top',
},
charCount: {
fontSize: 12,
alignSelf: 'flex-end',
marginTop: 5,
opacity: 0.6,
},
updateButton: {
borderRadius: 8,
marginBottom: 15,
},
});

View File

@ -0,0 +1,709 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
Animated,
StyleSheet,
FlatList,
TouchableOpacity,
RefreshControl,
ActivityIndicator,
AppState,
AppStateStatus,
Platform,
} from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText } from '@/components/theme';
import { formatDistanceToNow } from 'date-fns';
import StatusCard from './StatusCard';
import ProfileAvatar from '@/components/auth/Profile_Avatar';
import { useIsFocused } from '@react-navigation/native';
import { RealtimeChannel } from '@supabase/supabase-js';
import { UserStatus } from '@/constants/Types';
import debounce from 'lodash/debounce';
import NetInfo from '@react-native-community/netinfo';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useBottomTabOverflow } from '@/components/ui/TabBarBackground';
const HEADER_HEIGHT = 150;
const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
type StatusListProps = {
headerImage?: React.ReactNode;
headerTitle?: React.ReactNode;
};
const StatusList = ({headerImage, headerTitle}: StatusListProps) => {
const scheme = useColorScheme() ?? 'dark';
const bottom = useBottomTabOverflow();
const [statuses, setStatuses] = useState<UserStatus[]>([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [selectedUser, setSelectedUser] = useState<UserStatus | null>(null);
const [showStatusCard, setShowStatusCard] = useState(false);
const [recentlyUpdatedIds, setRecentlyUpdatedIds] = useState<Set<string>>(new Set());
const [isConnected, setIsConnected] = useState(true);
const [lastFetchTime, setLastFetchTime] = useState<Date | null>(null);
const fadeAnimation = useRef(new Animated.Value(0)).current;
const isFocused = useIsFocused();
const subscriptionRef = useRef<RealtimeChannel | null>(null);
const appStateRef = useRef(AppState.currentState);
const pendingUpdatesRef = useRef<Set<string>>(new Set());
// Parallax animation setup
const scrollY = useRef(new Animated.Value(0)).current;
const headerTranslateY = scrollY.interpolate({
inputRange: [0, HEADER_HEIGHT],
outputRange: [0, -HEADER_HEIGHT/2],
extrapolate: 'clamp',
});
const headerScale = scrollY.interpolate({
inputRange: [-HEADER_HEIGHT, 0, HEADER_HEIGHT],
outputRange: [2, 1, 1],
extrapolate: 'clamp',
});
// Debounced version of the status update handler
const debouncedHandleStatusUpdates = useRef(
debounce(() => {
if (pendingUpdatesRef.current.size > 0) {
const statusesToFetch = Array.from(pendingUpdatesRef.current);
pendingUpdatesRef.current.clear();
// Fetch all pending status updates in a single query
fetchMultipleStatuses(statusesToFetch);
}
}, 500)
).current;
// Fetch multiple statuses at once
const fetchMultipleStatuses = async (statusIds: string[]) => {
if (statusIds.length === 0) return;
try {
const { data, error } = await supabase
.from('statuses')
.select(`
id,
user_id,
status,
created_at,
profiles:profiles(full_name, avatar_url)
`)
.in('id', statusIds);
if (error) throw error;
if (data && data.length > 0) {
// Transform the data
const transformedData = data.map(item => ({
...item,
profiles: Array.isArray(item.profiles) ? item.profiles[0] : item.profiles
}));
// Update statuses
setStatuses(prevStatuses => {
const newStatuses = [...prevStatuses];
const updatedIds = new Set<string>();
// Process each new status
transformedData.forEach(newStatus => {
const existingIndex = newStatuses.findIndex(s => s.user_id === newStatus.user_id);
if (existingIndex !== -1) {
// If the new status is more recent, replace the existing one
if (new Date(newStatus.created_at) > new Date(newStatuses[existingIndex].created_at)) {
newStatuses[existingIndex] = newStatus;
updatedIds.add(newStatus.id);
}
} else {
// If this is a new user, add to the array
newStatuses.push(newStatus);
updatedIds.add(newStatus.id);
}
});
// Sort by most recent
newStatuses.sort((a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
// Mark updated statuses for highlighting
if (updatedIds.size > 0) {
setRecentlyUpdatedIds(prev => {
const newSet = new Set(prev);
updatedIds.forEach(id => newSet.add(id));
// Schedule removal of highlights
setTimeout(() => {
setRecentlyUpdatedIds(current => {
const updatedSet = new Set(current);
updatedIds.forEach(id => updatedSet.delete(id));
return updatedSet;
});
}, 3000);
return newSet;
});
// Animate the fade-in
Animated.sequence([
Animated.timing(fadeAnimation, {
toValue: 1,
duration: 300,
useNativeDriver: true,
}),
Animated.timing(fadeAnimation, {
toValue: 0,
duration: 300,
delay: 2000,
useNativeDriver: true,
}),
]).start();
}
return newStatuses;
});
}
} catch (error) {
console.error('Error fetching multiple statuses:', error);
}
};
// Fetch statuses with time filtering
const fetchStatuses = useCallback(async (forceRefresh = false) => {
try {
if (!isConnected) {
console.log('Skipping fetch - device is offline');
setLoading(false);
setRefreshing(false);
return;
}
// Get current time
const now = new Date();
setLastFetchTime(now);
// Calculate time filter - only get statuses from the last week
// unless it's a force refresh
let query = supabase
.from('statuses')
.select(`
id,
user_id,
status,
created_at,
profiles:profiles(full_name, avatar_url)
`)
.order('created_at', { ascending: false });
if (!forceRefresh) {
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
query = query.gte('created_at', oneWeekAgo.toISOString());
}
const { data, error } = await query;
if (error) throw error;
if (data) {
// Transform the data to match our expected type
const transformedData = data.map(item => ({
...item,
profiles: Array.isArray(item.profiles) ? item.profiles[0] : item.profiles
}));
// Get unique users with their latest status
const userMap = new Map();
transformedData.forEach(status => {
if (!userMap.has(status.user_id) ||
new Date(status.created_at) > new Date(userMap.get(status.user_id).created_at)) {
userMap.set(status.user_id, status);
}
});
// Convert map to array and sort by most recent
const latestUserStatuses = Array.from(userMap.values());
latestUserStatuses.sort((a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
setStatuses(latestUserStatuses);
}
} catch (error) {
console.error('Error fetching statuses:', error);
} finally {
setLoading(false);
setRefreshing(false);
}
}, [isConnected]);
// Handle individual status update
const handleNewStatus = useCallback((statusId: string) => {
// Add to pending updates
pendingUpdatesRef.current.add(statusId);
// Trigger the debounced handler
debouncedHandleStatusUpdates();
}, [debouncedHandleStatusUpdates]);
// Set up network connectivity listener
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsConnected(state.isConnected ?? false);
// If we're coming back online and we have a last fetch time
// that's more than 1 minute old, refresh the data
if (state.isConnected && lastFetchTime) {
const now = new Date();
const timeDiff = now.getTime() - lastFetchTime.getTime();
if (timeDiff > 60000) { // 1 minute
fetchStatuses();
}
}
});
return () => {
unsubscribe();
};
}, [fetchStatuses, lastFetchTime]);
// Set up AppState listener for background/foreground transitions
useEffect(() => {
const handleAppStateChange = (nextAppState: AppStateStatus) => {
if (
appStateRef.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('App has come to the foreground!');
// Refresh data if we've been in the background for a while
if (lastFetchTime) {
const now = new Date();
const timeDiff = now.getTime() - lastFetchTime.getTime();
if (timeDiff > 60000) { // 1 minute
fetchStatuses();
}
}
// Reconnect to realtime if needed
if (!subscriptionRef.current && isFocused) {
setupRealtimeSubscription();
}
}
appStateRef.current = nextAppState;
};
const subscription = AppState.addEventListener('change', handleAppStateChange);
return () => {
subscription.remove();
};
}, [fetchStatuses, isFocused, lastFetchTime]);
const setupRealtimeSubscription = useCallback(() => {
console.log('Setting up realtime subscription');
const subscription = supabase
.channel('status_changes')
.on('postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'statuses',
},
(payload) => {
console.log('New status received:', payload);
// Get the complete data immediately instead of just the ID
const newStatus = payload.new;
// Fetch the complete status with profile data
fetchStatusWithProfile(newStatus.id);
}
)
.subscribe((status) => {
console.log('Realtime subscription status:', status);
});
subscriptionRef.current = subscription;
return subscription;
}, []);
// Add this new function to fetch a single status with profile data
const fetchStatusWithProfile = async (statusId: string) => {
try {
console.log('Fetching status with profile:', statusId);
const { data, error } = await supabase
.from('statuses')
.select(`
id,
user_id,
status,
created_at,
profiles:profiles(full_name, avatar_url)
`)
.eq('id', statusId)
.single();
if (error) throw error;
if (data) {
// Transform the data
const transformedStatus = {
...data,
profiles: Array.isArray(data.profiles) ? data.profiles[0] : data.profiles
};
console.log('Received transformed status:', transformedStatus);
// Update statuses immediately without debouncing
setStatuses(prevStatuses => {
const newStatuses = [...prevStatuses];
const existingIndex = newStatuses.findIndex(s => s.user_id === transformedStatus.user_id);
if (existingIndex !== -1) {
// If the new status is more recent, replace the existing one
if (new Date(transformedStatus.created_at) > new Date(newStatuses[existingIndex].created_at)) {
newStatuses[existingIndex] = transformedStatus;
// Mark as recently updated
setRecentlyUpdatedIds(prev => {
const newSet = new Set(prev);
newSet.add(transformedStatus.id);
return newSet;
});
// Schedule removal of highlight
setTimeout(() => {
setRecentlyUpdatedIds(current => {
const updatedSet = new Set(current);
updatedSet.delete(transformedStatus.id);
return updatedSet;
});
}, 3000);
}
} else {
// If this is a new user, add to the array
newStatuses.push(transformedStatus);
// Mark as recently updated
setRecentlyUpdatedIds(prev => {
const newSet = new Set(prev);
newSet.add(transformedStatus.id);
return newSet;
});
// Schedule removal of highlight
setTimeout(() => {
setRecentlyUpdatedIds(current => {
const updatedSet = new Set(current);
updatedSet.delete(transformedStatus.id);
return updatedSet;
});
}, 3000);
}
// Sort by most recent
newStatuses.sort((a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
);
return newStatuses;
});
// Animate the fade-in
Animated.sequence([
Animated.timing(fadeAnimation, {
toValue: 1,
duration: 300,
useNativeDriver: true,
}),
Animated.timing(fadeAnimation, {
toValue: 0,
duration: 300,
delay: 2000,
useNativeDriver: true,
}),
]).start();
}
} catch (error) {
console.error('Error fetching status with profile:', error);
}
};
// Set up real-time subscription when component is focused
useEffect(() => {
let subscription: RealtimeChannel | null = null;
if (isFocused && isConnected) {
fetchStatuses();
subscription = setupRealtimeSubscription();
console.log('Subscription established: ', subscription);
// Clean up subscription when component unmounts or loses focus
return () => {
if (subscription) {
console.log('Removing subscription channel: ', subscription);
supabase.removeChannel(subscription);
subscriptionRef.current = null;
}
};
}
}, [isFocused, isConnected, fetchStatuses, setupRealtimeSubscription]);
// Handle refresh
const onRefresh = useCallback(() => {
setRefreshing(true);
fetchStatuses(true); // Force refresh to get all statuses
}, [fetchStatuses]);
const handleUserSelect = useCallback((user: UserStatus) => {
setSelectedUser(user);
setShowStatusCard(true);
}, []);
const handleStatusUpdate = useCallback(() => {
setShowStatusCard(false);
// No need to manually fetch statuses here since the real-time subscription will handle it
}, []);
const formatDate = useCallback((dateString: string) => {
const date = new Date(dateString);
return {
time: date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
date: date.toLocaleDateString([], { month: 'short', day: 'numeric' }),
relative: formatDistanceToNow(date, { addSuffix: true })
};
}, []);
// Memoize the list item renderer for better performance
const renderItem = useCallback(({ item }: { item: UserStatus }) => {
const formattedDate = formatDate(item.created_at);
return (
<TouchableOpacity
style={[
styles.statusItem,
recentlyUpdatedIds.has(item.id) && styles.recentlyUpdated,
{backgroundColor: Colors[scheme].card},
]}
onPress={() => handleUserSelect(item)}
activeOpacity={0.7}
>
<ThemedView style={styles.contentContainer}>
<ThemedView style={styles.topRow}>
<ThemedView style={styles.userContainer}>
<ThemedView style={styles.avatarContainer}>
<ProfileAvatar
url={item.profiles.avatar_url}
size={30}
disabled={true}
/>
</ThemedView>
<ThemedText
type='custom'
fontSize={24}
fontWeight='bold'
>
{item.profiles.full_name}
</ThemedText>
</ThemedView>
</ThemedView>
<ThemedView style={styles.bottomRow}>
<ThemedText type='custom' fontSize={18} style={styles.statusText}>
{item.status}
</ThemedText>
</ThemedView>
</ThemedView>
<ThemedView style={styles.timeContainer}>
<ThemedText type='custom' fontSize={20} fontWeight='semibold'>
{formattedDate.time}
</ThemedText>
<ThemedText type='custom' fontSize={20} fontWeight='500'>
{formattedDate.date}
</ThemedText>
</ThemedView>
</TouchableOpacity>
);
}, [formatDate, handleUserSelect, recentlyUpdatedIds]);
// Render the header component
const renderHeader = () => (
<Animated.View
style={[
styles.header,
{
backgroundColor: Colors[scheme].accent,
transform: [
{ translateY: headerTranslateY },
{ scale: headerScale }
]
}
]}
>
{headerImage}
{headerTitle}
</Animated.View>
);
// Empty list component
const ListEmptyComponent = useCallback(() => (
<ThemedView style={styles.emptyContainer}>
<ThemedText style={styles.emptyText}>
{isConnected ? 'No statuses available' : 'You are offline'}
</ThemedText>
</ThemedView>
), [isConnected]);
if (loading) {
return (
<ThemedView style={styles.loadingContainer}>
<ActivityIndicator size="large" />
</ThemedView>
);
}
return (
<ThemedView style={styles.container}>
{!isConnected && (
<ThemedView style={styles.offlineBar}>
<ThemedText style={styles.offlineText}>You are offline</ThemedText>
</ThemedView>
)}
{renderHeader()}
<AnimatedFlatList
data={statuses}
keyExtractor={(item) => item.id}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
enabled={isConnected}
/>
}
renderItem={renderItem}
ListEmptyComponent={ListEmptyComponent}
initialNumToRender={10}
maxToRenderPerBatch={10}
windowSize={10}
removeClippedSubviews={Platform.OS !== 'web'}
getItemLayout={(data, index) => (
{length: 120, offset: 120 * index, index}
)}
contentContainerStyle={{
paddingTop: HEADER_HEIGHT, // Add padding to account for the header
paddingBottom: bottom,
paddingHorizontal: 16,
}}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
{ useNativeDriver: true }
)}
scrollEventThrottle={16}
/>
{selectedUser && (
<StatusCard
visible={showStatusCard}
user={selectedUser}
onClose={() => setShowStatusCard(false)}
onUpdate={handleStatusUpdate}
/>
)}
</ThemedView>
);
};
export default React.memo(StatusList);
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: HEADER_HEIGHT,
position: 'absolute',
top: 0,
left: 0,
right: 0,
zIndex: 10,
overflow: 'hidden',
},
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
statusItem: {
flexDirection: 'row',
padding: 16,
borderRadius: 12,
marginHorizontal: 8,
marginVertical: 8,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2,
height: 120, // Fixed height for getItemLayout optimization
},
recentlyUpdated: {
backgroundColor: 'rgba(100, 200, 255, 0.1)',
borderLeftWidth: 3,
borderLeftColor: '#4C9EFF',
},
userContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'transparent',
},
avatarContainer: {
marginRight: 4,
backgroundColor: 'transparent',
},
contentContainer: {
flex: 1,
justifyContent: 'space-between',
backgroundColor: 'transparent',
},
topRow: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'transparent',
},
timeContainer: {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
},
bottomRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'transparent',
},
statusText: {
flex: 1,
marginLeft: 8,
marginRight: 4,
},
emptyContainer: {
padding: 20,
alignItems: 'center',
},
emptyText: {
fontSize: 16,
opacity: 0.6,
},
offlineBar: {
backgroundColor: '#FF3B30',
padding: 8,
alignItems: 'center',
},
offlineText: {
color: 'white',
fontWeight: 'bold',
},
});

View File

@ -1,5 +1,5 @@
import React from 'react';
import { StyleSheet, Pressable, PressableProps } from 'react-native';
import { StyleSheet, Pressable, PressableProps, DimensionValue } from 'react-native';
import ThemedView from '@/components/theme/default/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
@ -8,36 +8,36 @@ const DEFAULT_WIDTH = 320;
const DEFAULT_HEIGHT = 68;
type ThemedButtonProps = PressableProps & {
width?: number;
height?: number;
width?: DimensionValue;
height?: DimensionValue;
backgroundColor?: string;
containerStyle?: object;
buttonStyle?: object;
};
const ThemedButton: React.FC<ThemedButtonProps> = ({
width,
height,
width = DEFAULT_WIDTH,
height = DEFAULT_HEIGHT,
backgroundColor = Colors[useColorScheme() ?? 'dark'].text,
children,
containerStyle,
buttonStyle,
style,
...restProps // This now includes onPress automatically
}) => {
const scheme = useColorScheme() ?? 'dark';
return (
<ThemedView
style={[
styles.buttonContainer,
{
width: width ?? DEFAULT_WIDTH,
height: height ?? DEFAULT_HEIGHT,
width,
height,
},
containerStyle,
]}
>
<Pressable
style={[styles.button, { backgroundColor: Colors[scheme].text }, buttonStyle, style]}
style={[styles.button, { backgroundColor }, buttonStyle, style]}
{...restProps} // This passes onPress and all other Pressable props
>
{children}

View File

@ -1,34 +1,38 @@
import React from 'react';
import { TextStyle, PressableProps } from 'react-native';
import { TextStyle, PressableProps, DimensionValue } from 'react-native';
import ThemedButton from '@/components/theme/buttons/ThemedButton';
import ThemedText from '@/components/theme/default/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const DEFAULT_FONT_SIZE = 16;
// Extend ThemedButton props (which already extends PressableProps)
type ThemedTextButtonProps = Omit<PressableProps, 'children'> & {
width?: number;
height?: number;
width?: DimensionValue;
height?: DimensionValue;
text: string;
fontSize?: number;
fontWeight?: 'normal' | 'semibold' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
textStyle?: TextStyle;
containerStyle?: object;
buttonStyle?: object;
textColor?: string;
backgroundColor?: string;
};
const ThemedTextButton: React.FC<ThemedTextButtonProps> = ({
width,
height,
text,
fontSize,
fontSize = 16,
fontWeight = 'normal',
textStyle,
containerStyle,
buttonStyle,
textColor = Colors[useColorScheme() ?? 'dark'].background,
backgroundColor = Colors[useColorScheme() ?? 'dark'].text,
...restProps // This includes onPress and all other Pressable props
}) => {
const scheme = useColorScheme() ?? 'dark';
if (fontWeight === 'semibold') fontWeight = '600';
return (
<ThemedButton
@ -36,13 +40,16 @@ const ThemedTextButton: React.FC<ThemedTextButtonProps> = ({
height={height}
containerStyle={containerStyle}
buttonStyle={buttonStyle}
backgroundColor={backgroundColor}
{...restProps}
>
<ThemedText
style={[
{
color: Colors[scheme].background,
fontSize: fontSize ?? DEFAULT_FONT_SIZE,
color: textColor,
fontSize,
lineHeight: fontSize * 1.5,
fontWeight,
},
textStyle,
]}

View File

@ -7,23 +7,29 @@ export type ThemedViewProps = ViewProps & {
darkColor?: string;
};
export type ThemedTextProps = TextProps & {
fontSize?: number;
fontWeight?: 'normal' | 'semibold' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
lightColor?: string;
darkColor?: string;
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
type?: 'custom' | 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
};
const ThemedText = ({
fontSize = 16,
fontWeight = 'normal',
style,
lightColor,
darkColor,
type = 'default',
type='default',
...rest
}: ThemedTextProps) => {
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
if (fontWeight === 'semibold') fontWeight = '600';
return (
<Text
style={[
{ color },
type === 'custom' ? { fontSize, lineHeight: fontSize * 1.5, fontWeight } : undefined,
type === 'default' ? styles.default : undefined,
type === 'title' ? styles.title : undefined,
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,

View File

@ -4,9 +4,6 @@ import ThemedView from '@/components/theme/default/ThemedView';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const DEFAULT_WIDTH = 320;
const DEFAULT_HEIGHT = 50;
type ThemedTextInputProps = TextInputProps & {
width?: DimensionValue;
height?: DimensionValue;
@ -15,8 +12,8 @@ type ThemedTextInputProps = TextInputProps & {
};
const ThemedTextInput: React.FC<ThemedTextInputProps> = ({
width = DEFAULT_WIDTH,
height = DEFAULT_HEIGHT,
width='90%',
height=50,
fontSize = 16,
containerStyle,
style,
@ -29,9 +26,9 @@ const ThemedTextInput: React.FC<ThemedTextInputProps> = ({
style={[
styles.inputContainer,
{
borderColor: Colors[scheme].accent,
width,
height,
borderColor: Colors[scheme].accent,
},
containerStyle,
]}
@ -64,7 +61,6 @@ const styles = StyleSheet.create({
input: {
width: '100%',
height: '100%',
borderRadius: 8,
paddingHorizontal: 15,
},
});

View File

@ -13,6 +13,9 @@ const MAPPING = {
'paperplane.fill': 'send',
'chevron.left.forwardslash.chevron.right': 'code',
'chevron.right': 'chevron-right',
'gear.circle' : 'settings',
'gearshape.fill' : 'settings',
'person.fill' : 'person'
} as Partial<
Record<
import('expo-symbols').SymbolViewProps['name'],

27
constants/Types.ts Normal file
View File

@ -0,0 +1,27 @@
export type updateUser = {
id?: string;
updated_at?: Date;
email?: string;
full_name?: string;
avatar_url?: string;
provider?: string;
};
export type UserStatus = {
id: string;
user_id: string;
status: string;
created_at: string;
profiles: {
full_name: string;
avatar_url: string | null;
};
};
export type NotificationMessage = {
sound?: string;
title: string;
body: string;
data?: any;
};

7
metro.config.js Normal file
View File

@ -0,0 +1,7 @@
// This replaces `const { getDefaultConfig } = require('expo/metro-config');`
const { getSentryExpoConfig } = require('@sentry/react-native/metro');
// This replaces `const config = getDefaultConfig(__dirname);`
const config = getSentryExpoConfig(__dirname);
module.exports = config;

2717
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,8 +6,8 @@
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo start --android",
"ios": "expo start --ios",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web",
"test": "jest --watchAll",
"lint": "expo lint",
@ -18,45 +18,63 @@
"preset": "jest-expo"
},
"dependencies": {
"@azure/msal-browser": "^4.5.1",
"@azure/msal-react": "^3.0.5",
"@expo/metro-runtime": "~4.0.1",
"@expo/ngrok": "4.1.0",
"@expo/vector-icons": "^14.0.2",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-native-community/netinfo": "11.4.1",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/native": "^7.0.14",
"@supabase/supabase-js": "^2.48.1",
"aes-js": "^3.1.2",
"expo": "~52.0.28",
"date-fns": "^4.1.0",
"expo": "~52.0.38",
"expo-apple-authentication": "~7.1.3",
"expo-auth-session": "~6.0.3",
"expo-blur": "~14.0.3",
"expo-constants": "~17.0.5",
"expo-dev-client": "~5.0.10",
"expo-constants": "~17.0.7",
"expo-dev-client": "~5.0.12",
"expo-device": "~7.0.2",
"expo-font": "~13.0.3",
"expo-haptics": "~14.0.1",
"expo-image": "~2.0.6",
"expo-image-manipulator": "~13.0.6",
"expo-image-picker": "~16.0.6",
"expo-insights": "~0.8.2",
"expo-linking": "~7.0.5",
"expo-router": "~4.0.17",
"expo-location": "~18.0.7",
"expo-notifications": "~0.29.13",
"expo-router": "~4.0.19",
"expo-secure-store": "~14.0.1",
"expo-splash-screen": "~0.29.21",
"expo-status-bar": "~2.0.1",
"expo-symbols": "~0.2.1",
"expo-system-ui": "~4.0.7",
"expo-updates": "~0.26.13",
"expo-updates": "~0.27.3",
"expo-web-browser": "~14.0.2",
"jsonwebtoken": "^9.0.2",
"jwt-decode": "^4.0.0",
"lodash": "^4.17.21",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-native": "0.76.6",
"react-native": "0.76.7",
"react-native-gesture-handler": "~2.20.2",
"react-native-get-random-values": "^1.11.0",
"react-native-reanimated": "~3.16.1",
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-svg": "15.8.0",
"react-native-svg-transformer": "^1.5.0",
"react-native-web": "~0.19.13",
"react-native-webview": "13.12.5"
"react-native-webview": "13.12.5",
"@sentry/react-native": "~6.3.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@types/jest": "^29.5.12",
"@types/lodash": "^4.17.16",
"@types/react": "~18.3.12",
"@types/react-test-renderer": "^18.3.0",
"jest": "^29.2.1",

105
scripts/supabase_schema.sql Normal file
View File

@ -0,0 +1,105 @@
-- Create a table for public profiles
create table profiles (
id uuid references auth.users on delete cascade not null primary key,
updated_at timestamp with time zone,
email text,
full_name text,
avatar_url text,
provider text,
constraint full_name_length check (char_length(full_name) >= 3 and char_length(full_name) <= 50)
);
-- Set up Row Level Security (RLS)
-- See https://supabase.com/docs/guides/auth/row-level-security for more details.
alter table profiles
enable row level security;
create policy "Public profiles are viewable by everyone." on profiles
for select using (true);
create policy "Users can insert their own profile." on profiles
for insert with check ((select auth.uid()) = id);
create policy "Users can update own profile." on profiles
for update using ((select auth.uid()) = id);
-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth.
-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details.
create function public.handle_new_user()
returns trigger
set search_path = ''
as $$
begin
insert into public.profiles (id, email, full_name, avatar_url, provider, updated_at)
values (
new.id,
new.email,
new.raw_user_meta_data->>'full_name',
new.raw_user_meta_data->>'avatar_url'
new.raw_user_meta_data->>'provider',
now()
);
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on auth.users
for each row execute procedure public.handle_new_user();
-- Set up Storage!
insert into storage.buckets (id, name)
values ('avatars', 'avatars');
-- Set up access controls for storage.
-- See https://supabase.com/docs/guides/storage#policy-examples for more details.
create policy "Avatar images are publicly accessible." on storage.objects
for select using (bucket_id = 'avatars');
create policy "Anyone can upload an avatar." on storage.objects
for insert with check (bucket_id = 'avatars');
-- Create a table for public statuses
CREATE TABLE statuses (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
user_id uuid REFERENCES auth.users ON DELETE CASCADE NOT NULL,
updated_by_id uuid REFERENCES auth.users ON DELETE SET NULL DEFAULT auth.uid(),
created_at timestamp with time zone DEFAULT now() NOT NULL,
status text NOT NULL,
CONSTRAINT status_length CHECK (char_length(status) >= 3 AND char_length(status) <= 80),
CONSTRAINT statuses_user_id_fkey FOREIGN KEY (user_id) REFERENCES profiles(id) ON DELETE CASCADE
);
-- Set up Row Level Security (RLS)
ALTER TABLE statuses
ENABLE ROW LEVEL SECURITY;
-- Policies
CREATE POLICY "Public statuses are viewable by everyone." ON statuses
FOR SELECT USING (true);
CREATE POLICY "Users can insert statuses for any user." ON statuses
FOR INSERT WITH CHECK (auth.role() = 'authenticated');
-- Function to add first status
CREATE FUNCTION public.handle_first_status()
RETURNS TRIGGER
SET search_path = ''
AS $$
BEGIN
INSERT INTO public.statuses (user_id, updated_by_id, status)
VALUES (
NEW.id,
NEW.id,
'Just joined!'
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Create a separate trigger for the status
CREATE TRIGGER on_auth_user_created_add_status
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE PROCEDURE public.handle_first_status();
alter publication supabase_realtime add table statuses;

View File

@ -0,0 +1,118 @@
import React, { useState, useEffect, useRef } from 'react';
import { Alert, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import { NotificationMessage } from '@/constants/Types';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
export const sendPushNotification = async (
expoPushToken: string | null,
notification: NotificationMessage,
) => {
if (!expoPushToken) {
Alert.alert('Error', 'No push token found.');
return;
}
const message = {
to: expoPushToken,
sound: notification.sound ?? 'default',
title: notification.title,
body: notification.body,
data: notification.data ?? {},
};
try {
const response = 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 result = await response.json();
} catch (error) {
console.error('Error sending push notification:', error);
Alert.alert('Error', 'Failed to send push notification.');
}
};
const handleRegistrationError = (errorMessage: string) => {
alert(errorMessage);
throw new Error(errorMessage);
};
async function registerForPushNotificationsAsync() {
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) {
console.warn('No project id found');
alert('Project ID not found');
return;
}
token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
} else {
alert('Must use physical device for Push Notifications');
}
return token;
}
const PushNotificationManager = ({ children }: { children: React.ReactNode }) => {
const [expoPushToken, setExpoPushToken] = useState<string | undefined>('');
const [notification, setNotification] = useState<Notifications.Notification | undefined>(
undefined,
);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();
useEffect(() => {
registerForPushNotificationsAsync().then((token) => setExpoPushToken(token));
notificationListener.current = Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => {
console.log(response);
// Handle notification response here
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current!);
Notifications.removeNotificationSubscription(responseListener.current!);
};
}, []);
return <>{children}</>;
};
export default PushNotificationManager;