Compare commits
22 Commits
06471f688a
...
main
Author | SHA1 | Date | |
---|---|---|---|
35e340eed2 | |||
dc43d3b20c | |||
43e9e9790d | |||
b9802f7b1f | |||
67179593cb | |||
ca9b56c5f1 | |||
c503e4fb94 | |||
7e4978f0e0 | |||
0c2e5f3ac7 | |||
0cdfd1a0eb | |||
cfcf118275 | |||
86d1df3558 | |||
6c0a275ee0 | |||
f9655424db | |||
50d3d69dbd | |||
6e41fd3ddf | |||
f9fd5dafc5 | |||
07bf94d393 | |||
9f13d0357a | |||
84cae666bf | |||
708c0553f5 | |||
c62926b8f2 |
8
.gitignore
vendored
8
.gitignore
vendored
@ -29,6 +29,14 @@ yarn-error.*
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
*.pem
|
*.pem
|
||||||
|
|
||||||
|
# builds
|
||||||
|
*.ipa
|
||||||
|
ios/
|
||||||
|
android/
|
||||||
|
|
||||||
|
# Apple Secret
|
||||||
|
AuthKey_*.p8
|
||||||
|
|
||||||
# local env files
|
# local env files
|
||||||
.env
|
.env
|
||||||
.env*.local
|
.env*.local
|
||||||
|
@ -4,5 +4,6 @@
|
|||||||
"useTabs": false,
|
"useTabs": false,
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"jsxSingleQuote": true,
|
"jsxSingleQuote": true,
|
||||||
"trailingComma": "all"
|
"trailingComma": "all",
|
||||||
|
"semi": true
|
||||||
}
|
}
|
||||||
|
55
app.json
55
app.json
@ -1,23 +1,44 @@
|
|||||||
{
|
{
|
||||||
"expo": {
|
"expo": {
|
||||||
"name": "Tech Tracker Expo",
|
"name": "Tech Tracker",
|
||||||
"slug": "tech-tracker-expo",
|
"slug": "tech-tracker-expo",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"icon": "./assets/images/icon.png",
|
"icon": "./assets/images/icon.png",
|
||||||
"scheme": "com.techtracker",
|
"scheme": "com.techtracker",
|
||||||
"userInterfaceStyle": "automatic",
|
"userInterfaceStyle": "automatic",
|
||||||
|
"splash": {
|
||||||
|
"image": "./assets/images/splash.png",
|
||||||
|
"resizeMode": "contain",
|
||||||
|
"backgroundColor": "#2e2f3d"
|
||||||
|
},
|
||||||
"newArchEnabled": true,
|
"newArchEnabled": true,
|
||||||
"ios": {
|
"ios": {
|
||||||
|
"usesAppleSignIn": true,
|
||||||
"supportsTablet": 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": {
|
"android": {
|
||||||
"adaptiveIcon": {
|
"adaptiveIcon": {
|
||||||
"foregroundImage": "./assets/images/adaptive-icon.png",
|
"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": {
|
"web": {
|
||||||
"bundler": "metro",
|
"bundler": "metro",
|
||||||
@ -35,7 +56,27 @@
|
|||||||
"backgroundColor": "#ffffff"
|
"backgroundColor": "#ffffff"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"expo-secure-store"
|
[
|
||||||
|
"expo-secure-store",
|
||||||
|
{
|
||||||
|
"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": {
|
"experiments": {
|
||||||
"typedRoutes": true
|
"typedRoutes": true
|
||||||
@ -49,8 +90,6 @@
|
|||||||
"updates": {
|
"updates": {
|
||||||
"url": "https://u.expo.dev/7d872415-9160-4e06-ba95-4c3442e04b79"
|
"url": "https://u.expo.dev/7d872415-9160-4e06-ba95-4c3442e04b79"
|
||||||
},
|
},
|
||||||
"runtimeVersion": {
|
"runtimeVersion": "1.0.0"
|
||||||
"policy": "appVersion"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -37,16 +37,14 @@ const TabLayout = () => {
|
|||||||
name='index'
|
name='index'
|
||||||
options={{
|
options={{
|
||||||
title: 'Home',
|
title: 'Home',
|
||||||
tabBarIcon: ({ color }) =>
|
tabBarIcon: ({ color }) => <IconSymbol size={28} name='house.fill' color={color} />,
|
||||||
<IconSymbol size={28} name='house.fill' color={color} />,
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tabs.Screen
|
<Tabs.Screen
|
||||||
name='settings'
|
name='settings'
|
||||||
options={{
|
options={{
|
||||||
title: 'Settings',
|
title: 'Settings',
|
||||||
tabBarIcon: ({ color }) =>
|
tabBarIcon: ({ color }) => <IconSymbol size={28} name='gearshape.fill' color={color} />,
|
||||||
<IconSymbol size={28} name='gearshape.fill' color={color} />,
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
@ -1,24 +1,20 @@
|
|||||||
import { Image, StyleSheet, Platform } from 'react-native';
|
import { Image, StyleSheet, Platform } from 'react-native';
|
||||||
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
|
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
|
||||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
import { ThemedText, ThemedView } from '@/components/theme';
|
||||||
|
import StatusList from '@/components/status/StatusList';
|
||||||
|
|
||||||
const HomeScreen = () => {
|
const HomeScreen = () => {
|
||||||
return (
|
return (
|
||||||
<ParallaxScrollView
|
<StatusList
|
||||||
headerImage={
|
headerTitle={
|
||||||
<Image
|
<ThemedText style={styles.headerTitle}>
|
||||||
source={require('@/assets/images/tech_tracker_logo.png')}
|
Tech Tracker
|
||||||
style={styles.reactLogo}
|
</ThemedText>
|
||||||
/>
|
}
|
||||||
}
|
headerImage={
|
||||||
headerTitle={
|
<Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.techTrackerLogo} />
|
||||||
<ThemedText type='title' style={styles.headerTitle}>Tech Tracker</ThemedText>
|
}
|
||||||
}
|
/>
|
||||||
>
|
|
||||||
<ThemedView style={styles.titleContainer}>
|
|
||||||
|
|
||||||
</ThemedView>
|
|
||||||
</ParallaxScrollView>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export default HomeScreen;
|
export default HomeScreen;
|
||||||
@ -33,17 +29,17 @@ const styles = StyleSheet.create({
|
|||||||
gap: 8,
|
gap: 8,
|
||||||
marginBottom: 8,
|
marginBottom: 8,
|
||||||
},
|
},
|
||||||
reactLogo: {
|
techTrackerLogo: {
|
||||||
height: 70,
|
height: 70,
|
||||||
width: 72,
|
width: 72,
|
||||||
bottom: 10,
|
bottom: 10,
|
||||||
left: 40,
|
left: Platform.OS === 'ios' ? 40 : 20,
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
},
|
},
|
||||||
headerTitle: {
|
headerTitle: {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
bottom: 20,
|
bottom: 20,
|
||||||
left: 75,
|
left: 80,
|
||||||
right: 0,
|
right: 0,
|
||||||
textAlign: 'center',
|
textAlign: 'center',
|
||||||
fontSize: 48,
|
fontSize: 48,
|
||||||
|
@ -1,46 +0,0 @@
|
|||||||
import { StyleSheet, Image, Platform } from 'react-native';
|
|
||||||
import { Collapsible } from '@/components/default/Collapsible';
|
|
||||||
import { ExternalLink } from '@/components/default/ExternalLink';
|
|
||||||
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
|
|
||||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
|
||||||
import { IconSymbol } from '@/components/ui/IconSymbol';
|
|
||||||
|
|
||||||
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>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
</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,
|
|
||||||
},
|
|
||||||
});
|
|
39
app/(tabs)/settings/_layout.tsx
Normal file
39
app/(tabs)/settings/_layout.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
91
app/(tabs)/settings/index.tsx
Normal file
91
app/(tabs)/settings/index.tsx
Normal 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,
|
||||||
|
},
|
||||||
|
});
|
224
app/(tabs)/settings/profile.tsx
Normal file
224
app/(tabs)/settings/profile.tsx
Normal 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,
|
||||||
|
}
|
||||||
|
});
|
@ -1,7 +1,6 @@
|
|||||||
import { Link, Stack } from 'expo-router';
|
import { Link, Stack } from 'expo-router';
|
||||||
import { StyleSheet } from 'react-native';
|
import { StyleSheet } from 'react-native';
|
||||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
import { ThemedText, ThemedView, ThemedTextButton } from '@/components/theme';
|
||||||
import TextButton from '@/components/theme/buttons/TextButton';
|
|
||||||
|
|
||||||
const NotFoundScreen = () => {
|
const NotFoundScreen = () => {
|
||||||
return (
|
return (
|
||||||
@ -10,7 +9,7 @@ const NotFoundScreen = () => {
|
|||||||
<ThemedView style={styles.container}>
|
<ThemedView style={styles.container}>
|
||||||
<ThemedText type='title'>This screen doesn't exist.</ThemedText>
|
<ThemedText type='title'>This screen doesn't exist.</ThemedText>
|
||||||
<Link href='/'>
|
<Link href='/'>
|
||||||
<TextButton width={200} height={45} text='Go to home screen' fontSize={24} />
|
<ThemedTextButton width={200} height={45} text='Go to home screen' fontSize={24} />
|
||||||
</Link>
|
</Link>
|
||||||
</ThemedView>
|
</ThemedView>
|
||||||
</>
|
</>
|
||||||
|
@ -1,39 +1,88 @@
|
|||||||
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
|
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
|
||||||
import { useFonts } from 'expo-font';
|
import { useFonts } from 'expo-font';
|
||||||
import { Stack } from 'expo-router';
|
import { Stack, useNavigationContainerRef } from 'expo-router';
|
||||||
import * as SplashScreen from 'expo-splash-screen';
|
import * as SplashScreen from 'expo-splash-screen';
|
||||||
import { StatusBar } from 'expo-status-bar';
|
import { StatusBar } from 'expo-status-bar';
|
||||||
import { useEffect } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import 'react-native-reanimated';
|
import 'react-native-reanimated';
|
||||||
|
import { ThemedView } from '@/components/theme';
|
||||||
|
import { Session } from '@supabase/supabase-js';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
import { supabase } from '@/lib/supabase';
|
||||||
|
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.
|
// Prevent the splash screen from auto-hiding before asset loading is complete.
|
||||||
SplashScreen.preventAutoHideAsync();
|
SplashScreen.preventAutoHideAsync();
|
||||||
|
|
||||||
const RootLayout = () => {
|
const RootLayout = () => {
|
||||||
const scheme = useColorScheme() ?? 'dark';
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
const [session, setSession] = useState<Session | null>(null);
|
||||||
|
const ref = useNavigationContainerRef();
|
||||||
|
|
||||||
const [loaded] = useFonts({
|
const [loaded] = useFonts({
|
||||||
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
|
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
supabase.auth.getSession().then(({ data: { session } }) => {
|
||||||
|
setSession(session);
|
||||||
|
});
|
||||||
|
|
||||||
|
supabase.auth.onAuthStateChange((_event, session) => {
|
||||||
|
setSession(session);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loaded) {
|
if (loaded) {
|
||||||
SplashScreen.hideAsync();
|
SplashScreen.hideAsync();
|
||||||
}
|
}
|
||||||
}, [loaded]);
|
}, [loaded]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ref?.current) {
|
||||||
|
navigationIntegration.registerNavigationContainer(ref);
|
||||||
|
}
|
||||||
|
}, [ref])
|
||||||
|
|
||||||
if (!loaded) {
|
if (!loaded) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
|
<PushNotificationManager>
|
||||||
<Stack>
|
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
|
||||||
<Stack.Screen name='(tabs)' options={{ headerShown: false }} />
|
{session && session.user ? (
|
||||||
<Stack.Screen name='+not-found' />
|
<Stack>
|
||||||
</Stack>
|
<Stack.Screen name='(tabs)' options={{ headerShown: false }} />
|
||||||
<StatusBar style='auto' />
|
<Stack.Screen name='+not-found' />
|
||||||
</ThemeProvider>
|
</Stack>
|
||||||
|
) : (
|
||||||
|
<ThemedView style={{ flex: 1 }}>
|
||||||
|
<Auth />
|
||||||
|
</ThemedView>
|
||||||
|
)}
|
||||||
|
<StatusBar style='auto' />
|
||||||
|
</ThemeProvider>
|
||||||
|
</PushNotificationManager>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
export default RootLayout;
|
|
||||||
|
export default Sentry.wrap(RootLayout);
|
||||||
|
BIN
assets/images/Microsoft_Logo.png
Normal file
BIN
assets/images/Microsoft_Logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 430 B |
@ -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,
|
|
||||||
},
|
|
||||||
})
|
|
@ -1,95 +0,0 @@
|
|||||||
import React, { useState } from 'react'
|
|
||||||
import { Alert, StyleSheet, View, AppState } from 'react-native'
|
|
||||||
import { supabase } from '../lib/supabase'
|
|
||||||
import { Button, Input } from '@rneui/themed'
|
|
||||||
|
|
||||||
// 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
|
|
||||||
// `onAuthStateChange` events with the `TOKEN_REFRESHED` or `SIGNED_OUT` event
|
|
||||||
// if the user's session is terminated. This should only be registered once.
|
|
||||||
AppState.addEventListener('change', (state) => {
|
|
||||||
if (state === 'active') {
|
|
||||||
supabase.auth.startAutoRefresh()
|
|
||||||
} else {
|
|
||||||
supabase.auth.stopAutoRefresh()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
export default function Auth() {
|
|
||||||
const [email, setEmail] = useState('')
|
|
||||||
const [password, setPassword] = useState('')
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
|
|
||||||
async function signInWithEmail() {
|
|
||||||
setLoading(true)
|
|
||||||
const { error } = await supabase.auth.signInWithPassword({
|
|
||||||
email: email,
|
|
||||||
password: password,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (error) Alert.alert(error.message)
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function signUpWithEmail() {
|
|
||||||
setLoading(true)
|
|
||||||
const {
|
|
||||||
data: { session },
|
|
||||||
error,
|
|
||||||
} = await supabase.auth.signUp({
|
|
||||||
email: email,
|
|
||||||
password: password,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (error) Alert.alert(error.message)
|
|
||||||
if (!session) Alert.alert('Please check your inbox for email verification!')
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<View style={styles.container}>
|
|
||||||
<View style={[styles.verticallySpaced, styles.mt20]}>
|
|
||||||
<Input
|
|
||||||
label="Email"
|
|
||||||
leftIcon={{ type: 'font-awesome', name: 'envelope' }}
|
|
||||||
onChangeText={(text) => setEmail(text)}
|
|
||||||
value={email}
|
|
||||||
placeholder="email@address.com"
|
|
||||||
autoCapitalize={'none'}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
<View style={styles.verticallySpaced}>
|
|
||||||
<Input
|
|
||||||
label="Password"
|
|
||||||
leftIcon={{ type: 'font-awesome', name: 'lock' }}
|
|
||||||
onChangeText={(text) => setPassword(text)}
|
|
||||||
value={password}
|
|
||||||
secureTextEntry={true}
|
|
||||||
placeholder="Password"
|
|
||||||
autoCapitalize={'none'}
|
|
||||||
/>
|
|
||||||
</View>
|
|
||||||
<View style={[styles.verticallySpaced, styles.mt20]}>
|
|
||||||
<Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />
|
|
||||||
</View>
|
|
||||||
<View style={styles.verticallySpaced}>
|
|
||||||
<Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />
|
|
||||||
</View>
|
|
||||||
</View>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
|
||||||
container: {
|
|
||||||
marginTop: 40,
|
|
||||||
padding: 12,
|
|
||||||
},
|
|
||||||
verticallySpaced: {
|
|
||||||
paddingTop: 4,
|
|
||||||
paddingBottom: 4,
|
|
||||||
alignSelf: 'stretch',
|
|
||||||
},
|
|
||||||
mt20: {
|
|
||||||
marginTop: 20,
|
|
||||||
},
|
|
||||||
})
|
|
96
components/auth/AppleSignIniOS.tsx
Normal file
96
components/auth/AppleSignIniOS.tsx
Normal 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;
|
221
components/auth/Auth.tsx
Normal file
221
components/auth/Auth.tsx
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
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 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
|
||||||
|
// `onAuthStateChange` events with the `TOKEN_REFRESHED` or `SIGNED_OUT` event
|
||||||
|
// if the user's session is terminated. This should only be registered once.
|
||||||
|
if (Platform.OS !== 'web') {
|
||||||
|
AppState.addEventListener('change', (state) => {
|
||||||
|
if (state === 'active') {
|
||||||
|
supabase.auth.startAutoRefresh();
|
||||||
|
} else {
|
||||||
|
supabase.auth.stopAutoRefresh();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const Auth = () => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
|
||||||
|
const [full_name, setFullName] = useState('');
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
// Set up auto-refreshing for web
|
||||||
|
useEffect(() => {
|
||||||
|
if (Platform.OS === 'web') {
|
||||||
|
supabase.auth.startAutoRefresh();
|
||||||
|
return () => {
|
||||||
|
supabase.auth.stopAutoRefresh();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const signInWithEmail = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
const { error } = await supabase.auth.signInWithPassword({
|
||||||
|
email: email,
|
||||||
|
password: password,
|
||||||
|
});
|
||||||
|
if (error) Alert.alert(error.message);
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const signUpWithEmail = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
const {
|
||||||
|
data: { session },
|
||||||
|
error,
|
||||||
|
} = await supabase.auth.signUp({
|
||||||
|
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!');
|
||||||
|
setLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedView style={styles.container}>
|
||||||
|
<ThemedView style={styles.titleContainer}>
|
||||||
|
<Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.reactLogo} />
|
||||||
|
<ThemedText type='title' style={styles.headerTitle}>
|
||||||
|
Tech Tracker
|
||||||
|
</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}
|
||||||
|
secureTextEntry={true}
|
||||||
|
placeholder='Password'
|
||||||
|
/>
|
||||||
|
</ThemedView>
|
||||||
|
|
||||||
|
<ThemedView style={styles.verticallySpaced}>
|
||||||
|
<ThemedView style={styles.horizontallySpaced}>
|
||||||
|
<ThemedTextButton
|
||||||
|
text='Sign in'
|
||||||
|
disabled={loading}
|
||||||
|
onPress={() => signInWithEmail()}
|
||||||
|
fontSize={28}
|
||||||
|
fontWeight='semibold'
|
||||||
|
width='50%'
|
||||||
|
/>
|
||||||
|
<ThemedTextButton
|
||||||
|
text='Sign up'
|
||||||
|
disabled={loading}
|
||||||
|
onPress={() => signUpWithEmail()}
|
||||||
|
fontSize={28}
|
||||||
|
fontWeight='semibold'
|
||||||
|
width='50%'
|
||||||
|
/>
|
||||||
|
</ThemedView>
|
||||||
|
</ThemedView>
|
||||||
|
|
||||||
|
{ 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 Auth;
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
padding: 12,
|
||||||
|
height: '100%',
|
||||||
|
},
|
||||||
|
verticallySpaced: {
|
||||||
|
paddingTop: 4,
|
||||||
|
paddingBottom: 4,
|
||||||
|
alignItems: 'center',
|
||||||
|
},
|
||||||
|
horizontallySpaced: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
paddingLeft: 4,
|
||||||
|
paddingRight: 4,
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
width: '90%',
|
||||||
|
},
|
||||||
|
mt20: {
|
||||||
|
marginTop: 20,
|
||||||
|
},
|
||||||
|
reactLogo: {
|
||||||
|
height: 70,
|
||||||
|
width: 72,
|
||||||
|
},
|
||||||
|
titleContainer: {
|
||||||
|
marginTop: 60,
|
||||||
|
marginBottom: 20,
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: 8,
|
||||||
|
},
|
||||||
|
headerTitle: {
|
||||||
|
textAlign: 'center',
|
||||||
|
fontSize: 48,
|
||||||
|
lineHeight: 64,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
},
|
||||||
|
divider: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
marginVertical: 5,
|
||||||
|
width: '80%',
|
||||||
|
alignSelf: 'center',
|
||||||
|
},
|
||||||
|
dividerText: {
|
||||||
|
marginHorizontal: 15,
|
||||||
|
fontSize: 14,
|
||||||
|
opacity: 0.7,
|
||||||
|
},
|
||||||
|
dividerLine: {
|
||||||
|
flex: 1,
|
||||||
|
height: 1,
|
||||||
|
opacity: 0.3,
|
||||||
|
}
|
||||||
|
});
|
149
components/auth/AzureSignIn.tsx
Normal file
149
components/auth/AzureSignIn.tsx
Normal 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,
|
||||||
|
},
|
||||||
|
});
|
49
components/auth/Logout_Button.tsx
Normal file
49
components/auth/Logout_Button.tsx
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import { supabase } from '@/lib/supabase';
|
||||||
|
import { ThemedTextButton } from '@/components/theme';
|
||||||
|
import { Alert, StyleSheet } from 'react-native';
|
||||||
|
import React from 'react';
|
||||||
|
import { TextStyle, PressableProps, DimensionValue } from 'react-native';
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedTextButton
|
||||||
|
text='Logout'
|
||||||
|
width={width}
|
||||||
|
height={height}
|
||||||
|
textColor='white'
|
||||||
|
backgroundColor='red'
|
||||||
|
fontSize={fontSize}
|
||||||
|
fontWeight={fontWeight}
|
||||||
|
containerStyle={containerStyle}
|
||||||
|
buttonStyle={buttonStyle}
|
||||||
|
onPress={() => signOut()}
|
||||||
|
{...restProps}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
export default Logout_Button;
|
184
components/auth/Profile_Avatar.tsx
Normal file
184
components/auth/Profile_Avatar.tsx
Normal 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,
|
||||||
|
}
|
||||||
|
});
|
@ -1,6 +1,6 @@
|
|||||||
import { PropsWithChildren, useState } from 'react';
|
import { PropsWithChildren, useState } from 'react';
|
||||||
import { StyleSheet, TouchableOpacity } from 'react-native';
|
import { StyleSheet, TouchableOpacity } from 'react-native';
|
||||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
import { ThemedText, ThemedView } from '@/components/theme';
|
||||||
import { IconSymbol } from '@/components/ui/IconSymbol';
|
import { IconSymbol } from '@/components/ui/IconSymbol';
|
||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
@ -6,7 +6,7 @@ import Animated, {
|
|||||||
useAnimatedStyle,
|
useAnimatedStyle,
|
||||||
useScrollViewOffset,
|
useScrollViewOffset,
|
||||||
} from 'react-native-reanimated';
|
} from 'react-native-reanimated';
|
||||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
import { ThemedText, ThemedView } from '@/components/theme';
|
||||||
import { useBottomTabOverflow } from '@/components/ui/TabBarBackground';
|
import { useBottomTabOverflow } from '@/components/ui/TabBarBackground';
|
||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
@ -55,6 +55,8 @@ const ParallaxScrollView = ({
|
|||||||
scrollEventThrottle={16}
|
scrollEventThrottle={16}
|
||||||
scrollIndicatorInsets={{ bottom }}
|
scrollIndicatorInsets={{ bottom }}
|
||||||
contentContainerStyle={{ paddingBottom: bottom }}
|
contentContainerStyle={{ paddingBottom: bottom }}
|
||||||
|
keyboardShouldPersistTaps='handled'
|
||||||
|
keyboardDismissMode='interactive'
|
||||||
>
|
>
|
||||||
<Animated.View
|
<Animated.View
|
||||||
style={[
|
style={[
|
||||||
|
217
components/status/StatusCard.tsx
Normal file
217
components/status/StatusCard.tsx
Normal 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,
|
||||||
|
},
|
||||||
|
});
|
709
components/status/StatusList.tsx
Normal file
709
components/status/StatusList.tsx
Normal 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',
|
||||||
|
},
|
||||||
|
});
|
@ -1,58 +0,0 @@
|
|||||||
import { StyleSheet, Pressable } from 'react-native';
|
|
||||||
import { ThemedView } from '@/components/theme/Theme';
|
|
||||||
import { Colors } from '@/constants/Colors';
|
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
|
||||||
import { StyleProp, ViewStyle } from 'react-native';
|
|
||||||
|
|
||||||
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',
|
|
||||||
},
|
|
||||||
});
|
|
@ -1,33 +0,0 @@
|
|||||||
import Button from '@/components/theme/buttons/Button';
|
|
||||||
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].background,
|
|
||||||
fontSize: fontSize ?? DEFAULT_FONT_SIZE,
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
{text}
|
|
||||||
</ThemedText>
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
export default TextButton;
|
|
65
components/theme/buttons/ThemedButton.tsx
Normal file
65
components/theme/buttons/ThemedButton.tsx
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import React from 'react';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const DEFAULT_WIDTH = 320;
|
||||||
|
const DEFAULT_HEIGHT = 68;
|
||||||
|
|
||||||
|
type ThemedButtonProps = PressableProps & {
|
||||||
|
width?: DimensionValue;
|
||||||
|
height?: DimensionValue;
|
||||||
|
backgroundColor?: string;
|
||||||
|
containerStyle?: object;
|
||||||
|
buttonStyle?: object;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedButton: React.FC<ThemedButtonProps> = ({
|
||||||
|
width = DEFAULT_WIDTH,
|
||||||
|
height = DEFAULT_HEIGHT,
|
||||||
|
backgroundColor = Colors[useColorScheme() ?? 'dark'].text,
|
||||||
|
children,
|
||||||
|
containerStyle,
|
||||||
|
buttonStyle,
|
||||||
|
style,
|
||||||
|
...restProps // This now includes onPress automatically
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<ThemedView
|
||||||
|
style={[
|
||||||
|
styles.buttonContainer,
|
||||||
|
{
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
},
|
||||||
|
containerStyle,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Pressable
|
||||||
|
style={[styles.button, { backgroundColor }, buttonStyle, style]}
|
||||||
|
{...restProps} // This passes onPress and all other Pressable props
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Pressable>
|
||||||
|
</ThemedView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedButton;
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
buttonContainer: {
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: 3,
|
||||||
|
},
|
||||||
|
button: {
|
||||||
|
borderRadius: 10,
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
flexDirection: 'row',
|
||||||
|
},
|
||||||
|
});
|
63
components/theme/buttons/ThemedTextButton.tsx
Normal file
63
components/theme/buttons/ThemedTextButton.tsx
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
import React from 'react';
|
||||||
|
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';
|
||||||
|
|
||||||
|
// Extend ThemedButton props (which already extends PressableProps)
|
||||||
|
type ThemedTextButtonProps = Omit<PressableProps, 'children'> & {
|
||||||
|
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 = 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
|
||||||
|
}) => {
|
||||||
|
if (fontWeight === 'semibold') fontWeight = '600';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedButton
|
||||||
|
width={width}
|
||||||
|
height={height}
|
||||||
|
containerStyle={containerStyle}
|
||||||
|
buttonStyle={buttonStyle}
|
||||||
|
backgroundColor={backgroundColor}
|
||||||
|
{...restProps}
|
||||||
|
>
|
||||||
|
<ThemedText
|
||||||
|
style={[
|
||||||
|
{
|
||||||
|
color: textColor,
|
||||||
|
fontSize,
|
||||||
|
lineHeight: fontSize * 1.5,
|
||||||
|
fontWeight,
|
||||||
|
},
|
||||||
|
textStyle,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</ThemedText>
|
||||||
|
</ThemedButton>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedTextButton;
|
@ -1,4 +1,4 @@
|
|||||||
import { View, type ViewProps } from 'react-native';
|
import { type ViewProps } from 'react-native';
|
||||||
import { Text, type TextProps, StyleSheet } from 'react-native';
|
import { Text, type TextProps, StyleSheet } from 'react-native';
|
||||||
import { useThemeColor } from '@/hooks/useThemeColor';
|
import { useThemeColor } from '@/hooks/useThemeColor';
|
||||||
|
|
||||||
@ -7,28 +7,29 @@ export type ThemedViewProps = ViewProps & {
|
|||||||
darkColor?: string;
|
darkColor?: string;
|
||||||
};
|
};
|
||||||
export type ThemedTextProps = TextProps & {
|
export type ThemedTextProps = TextProps & {
|
||||||
|
fontSize?: number;
|
||||||
|
fontWeight?: 'normal' | 'semibold' | 'bold' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
|
||||||
lightColor?: string;
|
lightColor?: string;
|
||||||
darkColor?: string;
|
darkColor?: string;
|
||||||
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
|
type?: 'custom' | 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ThemedView = ({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) => {
|
const ThemedText = ({
|
||||||
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
|
fontSize = 16,
|
||||||
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
|
fontWeight = 'normal',
|
||||||
};
|
|
||||||
|
|
||||||
export const ThemedText = ({
|
|
||||||
style,
|
style,
|
||||||
lightColor,
|
lightColor,
|
||||||
darkColor,
|
darkColor,
|
||||||
type = 'default',
|
type='default',
|
||||||
...rest
|
...rest
|
||||||
}: ThemedTextProps) => {
|
}: ThemedTextProps) => {
|
||||||
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
|
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
|
||||||
|
if (fontWeight === 'semibold') fontWeight = '600';
|
||||||
return (
|
return (
|
||||||
<Text
|
<Text
|
||||||
style={[
|
style={[
|
||||||
{ color },
|
{ color },
|
||||||
|
type === 'custom' ? { fontSize, lineHeight: fontSize * 1.5, fontWeight } : undefined,
|
||||||
type === 'default' ? styles.default : undefined,
|
type === 'default' ? styles.default : undefined,
|
||||||
type === 'title' ? styles.title : undefined,
|
type === 'title' ? styles.title : undefined,
|
||||||
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
|
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
|
||||||
@ -40,6 +41,7 @@ export const ThemedText = ({
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
export default ThemedText;
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
default: {
|
default: {
|
13
components/theme/default/ThemedView.tsx
Normal file
13
components/theme/default/ThemedView.tsx
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { View, type ViewProps } from 'react-native';
|
||||||
|
import { useThemeColor } from '@/hooks/useThemeColor';
|
||||||
|
|
||||||
|
export type ThemedViewProps = ViewProps & {
|
||||||
|
lightColor?: string;
|
||||||
|
darkColor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedView = ({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) => {
|
||||||
|
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
|
||||||
|
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
|
||||||
|
};
|
||||||
|
export default ThemedView;
|
25
components/theme/index.tsx
Normal file
25
components/theme/index.tsx
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import ThemedText from '@/components/theme/default/ThemedText';
|
||||||
|
import ThemedView from '@/components/theme/default/ThemedView';
|
||||||
|
import ThemedButton from '@/components/theme/buttons/ThemedButton';
|
||||||
|
import ThemedTextButton from '@/components/theme/buttons/ThemedTextButton';
|
||||||
|
import ThemedTextInput from '@/components/theme/inputs/ThemedTextInput';
|
||||||
|
import ThemedCard from '@/components/theme/ui/ThemedCard';
|
||||||
|
import ThemedBadge from '@/components/theme/ui/ThemedBadge';
|
||||||
|
import ThemedIcon from '@/components/theme/ui/ThemedIcon';
|
||||||
|
import ThemedSwitch from '@/components/theme/inputs/ThemedSwitch';
|
||||||
|
import ThemedAvatar from '@/components/theme/ui/ThemedAvatar';
|
||||||
|
import ThemedSearchBar from '@/components/theme/inputs/ThemedSearchBar';
|
||||||
|
|
||||||
|
export {
|
||||||
|
ThemedText,
|
||||||
|
ThemedView,
|
||||||
|
ThemedButton,
|
||||||
|
ThemedTextButton,
|
||||||
|
ThemedTextInput,
|
||||||
|
ThemedCard,
|
||||||
|
ThemedBadge,
|
||||||
|
ThemedIcon,
|
||||||
|
ThemedSwitch,
|
||||||
|
ThemedAvatar,
|
||||||
|
ThemedSearchBar,
|
||||||
|
};
|
58
components/theme/inputs/ThemedSearchBar.tsx
Normal file
58
components/theme/inputs/ThemedSearchBar.tsx
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, ViewProps, DimensionValue } from 'react-native';
|
||||||
|
import ThemedView from '@/components/theme/default/ThemedView';
|
||||||
|
import ThemedTextInput from '@/components/theme/inputs/ThemedTextInput';
|
||||||
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedSearchBarProps = ViewProps & {
|
||||||
|
placeholder?: string;
|
||||||
|
value: string;
|
||||||
|
onChangeText: (text: string) => void;
|
||||||
|
width?: DimensionValue;
|
||||||
|
height?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedSearchBar: React.FC<ThemedSearchBarProps> = ({
|
||||||
|
placeholder = 'Search',
|
||||||
|
value,
|
||||||
|
onChangeText,
|
||||||
|
width = '100%',
|
||||||
|
height = 40,
|
||||||
|
style,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedView style={[styles.container, { width }, style]} {...restProps}>
|
||||||
|
<Ionicons name='search' size={20} color={Colors[scheme].text} style={styles.icon} />
|
||||||
|
<ThemedTextInput
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={value}
|
||||||
|
onChangeText={onChangeText}
|
||||||
|
height={height}
|
||||||
|
width={width}
|
||||||
|
style={styles.input}
|
||||||
|
/>
|
||||||
|
</ThemedView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
},
|
||||||
|
icon: {
|
||||||
|
position: 'absolute',
|
||||||
|
zIndex: 1,
|
||||||
|
left: 15,
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
paddingLeft: 45,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ThemedSearchBar;
|
24
components/theme/inputs/ThemedSwitch.tsx
Normal file
24
components/theme/inputs/ThemedSwitch.tsx
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Switch, SwitchProps } from 'react-native';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedSwitchProps = SwitchProps;
|
||||||
|
|
||||||
|
const ThemedSwitch: React.FC<ThemedSwitchProps> = ({ ...props }) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Switch
|
||||||
|
trackColor={{
|
||||||
|
false: Colors[scheme].border,
|
||||||
|
true: Colors[scheme].tint + '80',
|
||||||
|
}}
|
||||||
|
thumbColor={props.value ? Colors[scheme].tint : Colors[scheme].card}
|
||||||
|
ios_backgroundColor={Colors[scheme].border}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedSwitch;
|
66
components/theme/inputs/ThemedTextInput.tsx
Normal file
66
components/theme/inputs/ThemedTextInput.tsx
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, TextInput, TextInputProps, DimensionValue } from 'react-native';
|
||||||
|
import ThemedView from '@/components/theme/default/ThemedView';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedTextInputProps = TextInputProps & {
|
||||||
|
width?: DimensionValue;
|
||||||
|
height?: DimensionValue;
|
||||||
|
fontSize?: number;
|
||||||
|
containerStyle?: object;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedTextInput: React.FC<ThemedTextInputProps> = ({
|
||||||
|
width='90%',
|
||||||
|
height=50,
|
||||||
|
fontSize = 16,
|
||||||
|
containerStyle,
|
||||||
|
style,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedView
|
||||||
|
style={[
|
||||||
|
styles.inputContainer,
|
||||||
|
{
|
||||||
|
borderColor: Colors[scheme].accent,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
},
|
||||||
|
containerStyle,
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<TextInput
|
||||||
|
style={[
|
||||||
|
styles.input,
|
||||||
|
{
|
||||||
|
color: Colors[scheme].text,
|
||||||
|
backgroundColor: Colors[scheme].background,
|
||||||
|
fontSize,
|
||||||
|
},
|
||||||
|
style,
|
||||||
|
]}
|
||||||
|
placeholderTextColor={Colors[scheme].text + '80'} // 50% opacity
|
||||||
|
{...restProps}
|
||||||
|
/>
|
||||||
|
</ThemedView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedTextInput;
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
inputContainer: {
|
||||||
|
padding: 3,
|
||||||
|
borderRadius: 10,
|
||||||
|
borderWidth: 1,
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
paddingHorizontal: 15,
|
||||||
|
},
|
||||||
|
});
|
84
components/theme/ui/ThemedAvatar.tsx
Normal file
84
components/theme/ui/ThemedAvatar.tsx
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, Image, ImageProps, View } from 'react-native';
|
||||||
|
import ThemedText from '@/components/theme/default/ThemedText';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedAvatarProps = Omit<ImageProps, 'source'> & {
|
||||||
|
size?: number;
|
||||||
|
source?: ImageProps['source'];
|
||||||
|
name?: string;
|
||||||
|
borderWidth?: number;
|
||||||
|
borderColor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedAvatar: React.FC<ThemedAvatarProps> = ({
|
||||||
|
size = 50,
|
||||||
|
source,
|
||||||
|
name,
|
||||||
|
borderWidth = 0,
|
||||||
|
borderColor,
|
||||||
|
style,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
const border = borderColor || Colors[scheme].tint;
|
||||||
|
|
||||||
|
// Get initials from name
|
||||||
|
const getInitials = (name?: string) => {
|
||||||
|
if (!name) return '';
|
||||||
|
return name
|
||||||
|
.split(' ')
|
||||||
|
.map((part) => part[0])
|
||||||
|
.join('')
|
||||||
|
.toUpperCase()
|
||||||
|
.substring(0, 2);
|
||||||
|
};
|
||||||
|
|
||||||
|
const initials = getInitials(name);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
styles.container,
|
||||||
|
{
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
borderRadius: size / 2,
|
||||||
|
borderWidth,
|
||||||
|
borderColor: border,
|
||||||
|
backgroundColor: source ? 'transparent' : Colors[scheme].tint,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{source ? (
|
||||||
|
<Image
|
||||||
|
source={source}
|
||||||
|
style={[
|
||||||
|
{
|
||||||
|
width: size - 2 * borderWidth,
|
||||||
|
height: size - 2 * borderWidth,
|
||||||
|
borderRadius: (size - 2 * borderWidth) / 2,
|
||||||
|
},
|
||||||
|
style,
|
||||||
|
]}
|
||||||
|
{...restProps}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ThemedText style={{ color: Colors[scheme].background, fontSize: size * 0.4 }}>
|
||||||
|
{initials}
|
||||||
|
</ThemedText>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ThemedAvatar;
|
58
components/theme/ui/ThemedBadge.tsx
Normal file
58
components/theme/ui/ThemedBadge.tsx
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, ViewProps } from 'react-native';
|
||||||
|
import ThemedText from '@/components/theme/default/ThemedText';
|
||||||
|
import ThemedView from '@/components/theme/default/ThemedView';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedBadgeProps = ViewProps & {
|
||||||
|
value: number | string;
|
||||||
|
size?: number;
|
||||||
|
color?: string;
|
||||||
|
textColor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedBadge: React.FC<ThemedBadgeProps> = ({
|
||||||
|
value,
|
||||||
|
size = 24,
|
||||||
|
color,
|
||||||
|
textColor,
|
||||||
|
style,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
const badgeColor = color || Colors[scheme].tint;
|
||||||
|
const badgeTextColor = textColor || Colors[scheme].background;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedView
|
||||||
|
style={[
|
||||||
|
styles.badge,
|
||||||
|
{
|
||||||
|
width: size,
|
||||||
|
height: size,
|
||||||
|
borderRadius: size / 2,
|
||||||
|
backgroundColor: badgeColor,
|
||||||
|
},
|
||||||
|
style,
|
||||||
|
]}
|
||||||
|
{...restProps}
|
||||||
|
>
|
||||||
|
<ThemedText style={[styles.text, { color: badgeTextColor, fontSize: size * 0.5 }]}>
|
||||||
|
{value}
|
||||||
|
</ThemedText>
|
||||||
|
</ThemedView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
badge: {
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
},
|
||||||
|
text: {
|
||||||
|
fontWeight: 'bold',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ThemedBadge;
|
64
components/theme/ui/ThemedCard.tsx
Normal file
64
components/theme/ui/ThemedCard.tsx
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, ViewProps, Platform, DimensionValue } from 'react-native';
|
||||||
|
import ThemedView from '@/components/theme/default/ThemedView';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedCardProps = ViewProps & {
|
||||||
|
width?: DimensionValue;
|
||||||
|
height?: DimensionValue;
|
||||||
|
padding?: number;
|
||||||
|
elevation?: number;
|
||||||
|
borderRadius?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedCard: React.FC<ThemedCardProps> = ({
|
||||||
|
width = '100%',
|
||||||
|
height,
|
||||||
|
padding = 16,
|
||||||
|
elevation = 3,
|
||||||
|
borderRadius = 12,
|
||||||
|
style,
|
||||||
|
children,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemedView
|
||||||
|
style={[
|
||||||
|
styles.card,
|
||||||
|
{
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
padding,
|
||||||
|
borderRadius,
|
||||||
|
backgroundColor: Colors[scheme].card,
|
||||||
|
...Platform.select({
|
||||||
|
ios: {
|
||||||
|
shadowColor: Colors[scheme].text,
|
||||||
|
shadowOffset: { width: 0, height: elevation / 2 },
|
||||||
|
shadowOpacity: 0.1,
|
||||||
|
shadowRadius: elevation,
|
||||||
|
},
|
||||||
|
android: {
|
||||||
|
elevation,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
style,
|
||||||
|
]}
|
||||||
|
{...restProps}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</ThemedView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
card: {
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ThemedCard;
|
37
components/theme/ui/ThemedDivider.tsx
Normal file
37
components/theme/ui/ThemedDivider.tsx
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, ViewProps, View, DimensionValue } from 'react-native';
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedDividerProps = ViewProps & {
|
||||||
|
orientation?: 'horizontal' | 'vertical';
|
||||||
|
thickness?: DimensionValue;
|
||||||
|
length?: DimensionValue;
|
||||||
|
color?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedDivider: React.FC<ThemedDividerProps> = ({
|
||||||
|
orientation = 'horizontal',
|
||||||
|
thickness = 1,
|
||||||
|
length = '100%',
|
||||||
|
style,
|
||||||
|
...restProps
|
||||||
|
}) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
const color = restProps.color || Colors[scheme].border;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
orientation === 'horizontal'
|
||||||
|
? { height: thickness, width: length }
|
||||||
|
: { width: thickness, height: length },
|
||||||
|
{ backgroundColor: color },
|
||||||
|
style,
|
||||||
|
]}
|
||||||
|
{...restProps}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedDivider;
|
20
components/theme/ui/ThemedIcon.tsx
Normal file
20
components/theme/ui/ThemedIcon.tsx
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { StyleSheet, ViewProps } from 'react-native';
|
||||||
|
import { Ionicons } from '@expo/vector-icons'; // Or your preferred icon library
|
||||||
|
import { Colors } from '@/constants/Colors';
|
||||||
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
|
|
||||||
|
type ThemedIconProps = ViewProps & {
|
||||||
|
name: string;
|
||||||
|
size?: number;
|
||||||
|
color?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ThemedIcon: React.FC<ThemedIconProps> = ({ name, size = 24, color, style, ...restProps }) => {
|
||||||
|
const scheme = useColorScheme() ?? 'dark';
|
||||||
|
const iconColor = color || Colors[scheme].text;
|
||||||
|
|
||||||
|
return <Ionicons name={name} size={size} color={iconColor} style={style} {...restProps} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ThemedIcon;
|
@ -13,6 +13,9 @@ const MAPPING = {
|
|||||||
'paperplane.fill': 'send',
|
'paperplane.fill': 'send',
|
||||||
'chevron.left.forwardslash.chevron.right': 'code',
|
'chevron.left.forwardslash.chevron.right': 'code',
|
||||||
'chevron.right': 'chevron-right',
|
'chevron.right': 'chevron-right',
|
||||||
|
'gear.circle' : 'settings',
|
||||||
|
'gearshape.fill' : 'settings',
|
||||||
|
'person.fill' : 'person'
|
||||||
} as Partial<
|
} as Partial<
|
||||||
Record<
|
Record<
|
||||||
import('expo-symbols').SymbolViewProps['name'],
|
import('expo-symbols').SymbolViewProps['name'],
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
const black = '#1f1e2c';
|
const black = '#1f1e2c';
|
||||||
const white = '#ECEDEE'
|
const white = '#ECEDEE';
|
||||||
const darkTint = '#fff';
|
const darkTint = '#fff';
|
||||||
const lightTint = '#0a7ea4';
|
const lightTint = '#0a7ea4';
|
||||||
const darkIcon = '#9BA1A6';
|
const darkIcon = '#9BA1A6';
|
||||||
@ -18,6 +18,15 @@ export const Colors = {
|
|||||||
tabIconSelected: lightTint,
|
tabIconSelected: lightTint,
|
||||||
ttBlue,
|
ttBlue,
|
||||||
accent: ttLightBlue,
|
accent: ttLightBlue,
|
||||||
|
card: '#ffffff',
|
||||||
|
border: '#d0d7de',
|
||||||
|
notification: '#f85149',
|
||||||
|
placeholder: '#8b949e',
|
||||||
|
inactive: '#afb8c1',
|
||||||
|
subtle: '#f6f8fa',
|
||||||
|
error: '#e5484d',
|
||||||
|
success: '#46954a',
|
||||||
|
warning: '#daaa3f',
|
||||||
},
|
},
|
||||||
dark: {
|
dark: {
|
||||||
text: white,
|
text: white,
|
||||||
@ -28,5 +37,14 @@ export const Colors = {
|
|||||||
tabIconSelected: darkTint,
|
tabIconSelected: darkTint,
|
||||||
ttBlue,
|
ttBlue,
|
||||||
accent: ttDarkBlue,
|
accent: ttDarkBlue,
|
||||||
|
card: '#3a3b4a',
|
||||||
|
border: '#444c56',
|
||||||
|
notification: '#ff6a69',
|
||||||
|
placeholder: '#636e7b',
|
||||||
|
inactive: '#4d5560',
|
||||||
|
subtle: '#272934',
|
||||||
|
error: '#ff6369',
|
||||||
|
success: '#3fb950',
|
||||||
|
warning: '#d29922',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
27
constants/Types.ts
Normal file
27
constants/Types.ts
Normal 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;
|
||||||
|
};
|
@ -1,21 +1,43 @@
|
|||||||
import { createClient } from "@supabase/supabase-js";
|
// lib/supabase.ts
|
||||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
import { createClient } from '@supabase/supabase-js';
|
||||||
|
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||||
import * as SecureStore from 'expo-secure-store';
|
import * as SecureStore from 'expo-secure-store';
|
||||||
import * as aesjs from 'aes-js';
|
import * as aesjs from 'aes-js';
|
||||||
import 'react-native-get-random-values';
|
import 'react-native-get-random-values';
|
||||||
|
import { Platform } from 'react-native';
|
||||||
|
|
||||||
// As Expo's SecureStore does not support values larger than 2048
|
// Create a web-compatible storage implementation
|
||||||
// bytes, an AES-256 key is generated and stored in SecureStore, while
|
class WebStorage {
|
||||||
// it is used to encrypt/decrypt values stored in AsyncStorage.
|
async getItem(key: string) {
|
||||||
|
// In SSR context, return null
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return localStorage.getItem(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeItem(key: string) {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setItem(key: string, value: string) {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
localStorage.setItem(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Original LargeSecureStore implementation for native platforms
|
||||||
class LargeSecureStore {
|
class LargeSecureStore {
|
||||||
private async _encrypt(key: string, value: string) {
|
private async _encrypt(key: string, value: string) {
|
||||||
const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
|
const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
|
||||||
|
|
||||||
const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
|
const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
|
||||||
const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
|
const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
|
||||||
|
|
||||||
await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
|
await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
|
||||||
|
|
||||||
return aesjs.utils.hex.fromBytes(encryptedBytes);
|
return aesjs.utils.hex.fromBytes(encryptedBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -24,17 +46,19 @@ class LargeSecureStore {
|
|||||||
if (!encryptionKeyHex) {
|
if (!encryptionKeyHex) {
|
||||||
return encryptionKeyHex;
|
return encryptionKeyHex;
|
||||||
}
|
}
|
||||||
|
const cipher = new aesjs.ModeOfOperation.ctr(
|
||||||
const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
|
aesjs.utils.hex.toBytes(encryptionKeyHex),
|
||||||
|
new aesjs.Counter(1),
|
||||||
|
);
|
||||||
const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
|
const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
|
||||||
|
|
||||||
return aesjs.utils.utf8.fromBytes(decryptedBytes);
|
return aesjs.utils.utf8.fromBytes(decryptedBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getItem(key: string) {
|
async getItem(key: string) {
|
||||||
const encrypted = await AsyncStorage.getItem(key);
|
const encrypted = await AsyncStorage.getItem(key);
|
||||||
if (!encrypted) { return encrypted; }
|
if (!encrypted) {
|
||||||
|
return encrypted;
|
||||||
|
}
|
||||||
return await this._decrypt(key, encrypted);
|
return await this._decrypt(key, encrypted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,17 +69,18 @@ class LargeSecureStore {
|
|||||||
|
|
||||||
async setItem(key: string, value: string) {
|
async setItem(key: string, value: string) {
|
||||||
const encrypted = await this._encrypt(key, value);
|
const encrypted = await this._encrypt(key, value);
|
||||||
|
|
||||||
await AsyncStorage.setItem(key, encrypted);
|
await AsyncStorage.setItem(key, encrypted);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Choose the appropriate storage implementation based on platform
|
||||||
|
const storage = Platform.OS === 'web' ? new WebStorage() : new LargeSecureStore();
|
||||||
const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL as string;
|
const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL as string;
|
||||||
const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY as string;
|
const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY as string;
|
||||||
|
|
||||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
|
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
|
||||||
auth: {
|
auth: {
|
||||||
storage: new LargeSecureStore(),
|
storage,
|
||||||
autoRefreshToken: true,
|
autoRefreshToken: true,
|
||||||
persistSession: true,
|
persistSession: true,
|
||||||
detectSessionInUrl: false,
|
detectSessionInUrl: false,
|
||||||
|
7
metro.config.js
Normal file
7
metro.config.js
Normal 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;
|
3338
package-lock.json
generated
3338
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
42
package.json
42
package.json
@ -6,8 +6,8 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "expo start",
|
"start": "expo start",
|
||||||
"reset-project": "node ./scripts/reset-project.js",
|
"reset-project": "node ./scripts/reset-project.js",
|
||||||
"android": "expo start --android",
|
"android": "expo run:android",
|
||||||
"ios": "expo start --ios",
|
"ios": "expo run:ios",
|
||||||
"web": "expo start --web",
|
"web": "expo start --web",
|
||||||
"test": "jest --watchAll",
|
"test": "jest --watchAll",
|
||||||
"lint": "expo lint",
|
"lint": "expo lint",
|
||||||
@ -18,43 +18,63 @@
|
|||||||
"preset": "jest-expo"
|
"preset": "jest-expo"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"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",
|
"@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/bottom-tabs": "^7.2.0",
|
||||||
"@react-navigation/native": "^7.0.14",
|
"@react-navigation/native": "^7.0.14",
|
||||||
"@rneui/themed": "^4.0.0-rc.8",
|
|
||||||
"@supabase/supabase-js": "^2.48.1",
|
"@supabase/supabase-js": "^2.48.1",
|
||||||
"aes-js": "^3.1.2",
|
"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-blur": "~14.0.3",
|
||||||
"expo-constants": "~17.0.5",
|
"expo-constants": "~17.0.7",
|
||||||
"expo-dev-client": "~5.0.10",
|
"expo-dev-client": "~5.0.12",
|
||||||
|
"expo-device": "~7.0.2",
|
||||||
"expo-font": "~13.0.3",
|
"expo-font": "~13.0.3",
|
||||||
"expo-haptics": "~14.0.1",
|
"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-insights": "~0.8.2",
|
||||||
"expo-linking": "~7.0.5",
|
"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-splash-screen": "~0.29.21",
|
||||||
"expo-status-bar": "~2.0.1",
|
"expo-status-bar": "~2.0.1",
|
||||||
"expo-symbols": "~0.2.1",
|
"expo-symbols": "~0.2.1",
|
||||||
"expo-system-ui": "~4.0.7",
|
"expo-system-ui": "~4.0.7",
|
||||||
"expo-updates": "~0.26.13",
|
"expo-updates": "~0.27.3",
|
||||||
"expo-web-browser": "~14.0.2",
|
"expo-web-browser": "~14.0.2",
|
||||||
|
"jsonwebtoken": "^9.0.2",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-dom": "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-gesture-handler": "~2.20.2",
|
||||||
"react-native-get-random-values": "^1.11.0",
|
"react-native-get-random-values": "^1.11.0",
|
||||||
"react-native-reanimated": "~3.16.1",
|
"react-native-reanimated": "~3.16.1",
|
||||||
"react-native-safe-area-context": "4.12.0",
|
"react-native-safe-area-context": "4.12.0",
|
||||||
"react-native-screens": "~4.4.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-web": "~0.19.13",
|
||||||
"react-native-webview": "13.12.5",
|
"react-native-webview": "13.12.5",
|
||||||
"expo-secure-store": "~14.0.1"
|
"@sentry/react-native": "~6.3.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.25.2",
|
"@babel/core": "^7.25.2",
|
||||||
"@types/jest": "^29.5.12",
|
"@types/jest": "^29.5.12",
|
||||||
|
"@types/lodash": "^4.17.16",
|
||||||
"@types/react": "~18.3.12",
|
"@types/react": "~18.3.12",
|
||||||
"@types/react-test-renderer": "^18.3.0",
|
"@types/react-test-renderer": "^18.3.0",
|
||||||
"jest": "^29.2.1",
|
"jest": "^29.2.1",
|
||||||
|
99
scripts/files_to_clipboard
Executable file
99
scripts/files_to_clipboard
Executable file
@ -0,0 +1,99 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
import pyperclip
|
||||||
|
import questionary
|
||||||
|
|
||||||
|
# List of directories to exclude
|
||||||
|
EXCLUDED_DIRS = {'node_modules', '.next', '.venv', '.git', '__pycache__', '.idea', '.vscode', 'ui'}
|
||||||
|
|
||||||
|
def collect_files(project_path):
|
||||||
|
"""
|
||||||
|
Collects files from the project directory, excluding specified directories and filtering by extensions.
|
||||||
|
Returns a list of file paths relative to the project directory.
|
||||||
|
"""
|
||||||
|
collected_files = []
|
||||||
|
|
||||||
|
for root, dirs, files in os.walk(project_path):
|
||||||
|
# Exclude specified directories
|
||||||
|
dirs[:] = [d for d in dirs if d not in EXCLUDED_DIRS]
|
||||||
|
|
||||||
|
for file in files:
|
||||||
|
file_path = Path(root) / file
|
||||||
|
relative_path = file_path.relative_to(project_path)
|
||||||
|
collected_files.append(relative_path)
|
||||||
|
|
||||||
|
return collected_files
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# Parse command-line arguments
|
||||||
|
parser = argparse.ArgumentParser(description='Generate Markdown from selected files.')
|
||||||
|
parser.add_argument('path', nargs='?', default='.', help='Path to the project directory')
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
project_path = Path(args.path).resolve()
|
||||||
|
if not project_path.is_dir():
|
||||||
|
print(f"Error: '{project_path}' is not a directory.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Collect files from the project directory
|
||||||
|
file_list = collect_files(project_path)
|
||||||
|
|
||||||
|
if not file_list:
|
||||||
|
print("No files found in the project directory with the specified extensions.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Sort file_list for better organization
|
||||||
|
file_list.sort()
|
||||||
|
|
||||||
|
# Interactive file selection using questionary
|
||||||
|
print("\nSelect the files you want to include:")
|
||||||
|
selected_files = questionary.checkbox(
|
||||||
|
"Press space to select files, and Enter when you're done:",
|
||||||
|
choices=[str(f) for f in file_list]
|
||||||
|
).ask()
|
||||||
|
|
||||||
|
if not selected_files:
|
||||||
|
print("No files selected.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Generate markdown
|
||||||
|
markdown_lines = []
|
||||||
|
markdown_lines.append('')
|
||||||
|
|
||||||
|
for selected_file in selected_files:
|
||||||
|
file_path = project_path / selected_file
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
content = f.read()
|
||||||
|
# Determine the language for code block from file extension
|
||||||
|
language = file_path.suffix.lstrip('.')
|
||||||
|
markdown_lines.append(f'{selected_file}')
|
||||||
|
markdown_lines.append(f'```{language}')
|
||||||
|
markdown_lines.append(content)
|
||||||
|
markdown_lines.append('```')
|
||||||
|
markdown_lines.append('')
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error reading file {selected_file}: {e}")
|
||||||
|
|
||||||
|
markdown_text = '\n'.join(markdown_lines)
|
||||||
|
|
||||||
|
# Copy markdown content to clipboard
|
||||||
|
pyperclip.copy(markdown_text)
|
||||||
|
print("Markdown content has been copied to the clipboard.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Check if required libraries are installed
|
||||||
|
try:
|
||||||
|
import questionary
|
||||||
|
import pyperclip
|
||||||
|
except ImportError as e:
|
||||||
|
missing_module = e.name
|
||||||
|
print(f"Error: Missing required module '{missing_module}'.")
|
||||||
|
print(f"Please install it by running: pip install {missing_module}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
main()
|
40
scripts/generate_apple_secret.js
Normal file
40
scripts/generate_apple_secret.js
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
const dotenv = require('dotenv');
|
||||||
|
|
||||||
|
// Load environment variables from .env file
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const generateAppleSecret = (config) => {
|
||||||
|
const { teamId, clientId, keyId, privateKeyPath } = config;
|
||||||
|
const privateKey = fs.readFileSync(privateKeyPath).toString();
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const payload = {
|
||||||
|
iss: teamId,
|
||||||
|
iat: now,
|
||||||
|
exp: now + 86400 * 180, // 180 days
|
||||||
|
aud: 'https://appleid.apple.com',
|
||||||
|
sub: clientId,
|
||||||
|
};
|
||||||
|
const headers = {
|
||||||
|
alg: 'ES256',
|
||||||
|
kid: keyId,
|
||||||
|
};
|
||||||
|
return jwt.sign(payload, privateKey, { algorithm: 'ES256', header: headers });
|
||||||
|
};
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
teamId: process.env.APPLE_TEAM_ID || '',
|
||||||
|
clientId: process.env.AUTH_APPLE_ID || '',
|
||||||
|
keyId: process.env.APPLE_KEY_ID || '',
|
||||||
|
privateKeyPath: path.resolve(__dirname, process.env.APPLE_PRIVATE_KEY_PATH || ''),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!config.teamId || !config.clientId || !config.keyId || !config.privateKeyPath) {
|
||||||
|
console.error('Missing necessary Apple configuration');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const appleSecret = generateAppleSecret(config);
|
||||||
|
console.log(`Your Apple Secret:\n\n${appleSecret}\n`);
|
105
scripts/supabase_schema.sql
Normal file
105
scripts/supabase_schema.sql
Normal 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;
|
118
services/PushNotificationManager.tsx
Normal file
118
services/PushNotificationManager.tsx
Normal 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;
|
Reference in New Issue
Block a user