Add Sign in with Apple sorta

This commit is contained in:
Gabriel Brown 2025-03-05 12:58:18 -06:00
parent 06471f688a
commit c62926b8f2
35 changed files with 1458 additions and 620 deletions

3
.gitignore vendored
View File

@ -29,6 +29,9 @@ yarn-error.*
.DS_Store
*.pem
# Apple Secret
AuthKey_*.p8
# local env files
.env
.env*.local

View File

@ -4,5 +4,6 @@
"useTabs": false,
"singleQuote": true,
"jsxSingleQuote": true,
"trailingComma": "all"
"trailingComma": "all",
"semi": true
}

View File

@ -9,6 +9,7 @@
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"ios": {
"usesAppleSignIn": true,
"supportsTablet": true,
"bundleIdentifier": "com.gibbyb.techtrackerexpo"
},
@ -35,7 +36,8 @@
"backgroundColor": "#ffffff"
}
],
"expo-secure-store"
"expo-secure-store",
"expo-apple-authentication"
],
"experiments": {
"typedRoutes": true

View File

@ -37,16 +37,14 @@ const TabLayout = () => {
name='index'
options={{
title: 'Home',
tabBarIcon: ({ color }) =>
<IconSymbol size={28} name='house.fill' color={color} />,
tabBarIcon: ({ color }) => <IconSymbol size={28} name='house.fill' color={color} />,
}}
/>
<Tabs.Screen
name='settings'
options={{
title: 'Settings',
tabBarIcon: ({ color }) =>
<IconSymbol size={28} name='gearshape.fill' color={color} />,
tabBarIcon: ({ color }) => <IconSymbol size={28} name='gearshape.fill' color={color} />,
}}
/>
</Tabs>

View File

@ -1,23 +1,20 @@
import { Image, StyleSheet, Platform } from 'react-native';
import ParallaxScrollView from '@/components/default/ParallaxScrollView';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { ThemedText, ThemedView } from '@/components/theme';
const HomeScreen = () => {
return (
<ParallaxScrollView
headerImage={
<Image
source={require('@/assets/images/tech_tracker_logo.png')}
style={styles.reactLogo}
/>
<Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.reactLogo} />
}
headerTitle={
<ThemedText type='title' style={styles.headerTitle}>Tech Tracker</ThemedText>
<ThemedText type='title' style={styles.headerTitle}>
Tech Tracker
</ThemedText>
}
>
<ThemedView style={styles.titleContainer}>
</ThemedView>
<ThemedView style={styles.titleContainer}></ThemedView>
</ParallaxScrollView>
);
};

View File

@ -1,9 +1,8 @@
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 { ThemedText, ThemedView } from '@/components/theme';
import { IconSymbol } from '@/components/ui/IconSymbol';
import Logout_Button from '@/components/auth/Logout_Button';
const TabTwoScreen = () => {
return (
@ -17,6 +16,7 @@ const TabTwoScreen = () => {
</ThemedText>
}
>
<Logout_Button />
</ParallaxScrollView>
);
};

View File

@ -1,7 +1,6 @@
import { Link, Stack } from 'expo-router';
import { StyleSheet } from 'react-native';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import TextButton from '@/components/theme/buttons/TextButton';
import { ThemedText, ThemedView, ThemedTextButton } from '@/components/theme';
const NotFoundScreen = () => {
return (
@ -10,7 +9,7 @@ const NotFoundScreen = () => {
<ThemedView style={styles.container}>
<ThemedText type='title'>This screen doesn't exist.</ThemedText>
<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>
</ThemedView>
</>

View File

@ -3,19 +3,36 @@ import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import 'react-native-reanimated';
import { ThemedView } from '@/components/theme';
import { Session } from '@supabase/supabase-js';
import { useColorScheme } from '@/hooks/useColorScheme';
import { supabase } from '@/lib/supabase';
import LoginPage from '@/components/auth/Login';
import Account from '@/components/Account';
// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
const RootLayout = () => {
const scheme = useColorScheme() ?? 'dark';
const [session, setSession] = useState<Session | null>(null);
const [loaded] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
});
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
});
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
});
}, []);
useEffect(() => {
if (loaded) {
SplashScreen.hideAsync();
@ -28,12 +45,19 @@ const RootLayout = () => {
return (
<ThemeProvider value={scheme === 'dark' ? DarkTheme : DefaultTheme}>
<Stack>
<Stack.Screen name='(tabs)' options={{ headerShown: false }} />
<Stack.Screen name='+not-found' />
</Stack>
{session && session.user ? (
<Stack>
<Stack.Screen name='(tabs)' options={{ headerShown: false }} />
<Stack.Screen name='+not-found' />
</Stack>
) : (
<ThemedView style={{ flex: 1 }}>
<LoginPage />
</ThemedView>
)}
<StatusBar style='auto' />
</ThemeProvider>
);
};
export default RootLayout;

View File

@ -1,44 +1,44 @@
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'
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('')
const [loading, setLoading] = useState(true);
const [username, setUsername] = useState('');
const [website, setWebsite] = useState('');
const [avatarUrl, setAvatarUrl] = useState('');
useEffect(() => {
if (session) getProfile()
}, [session])
if (session) getProfile();
}, [session]);
async function getProfile() {
try {
setLoading(true)
if (!session?.user) throw new Error('No user on the session!')
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()
.single();
if (error && status !== 406) {
throw error
throw error;
}
if (data) {
setUsername(data.username)
setWebsite(data.website)
setAvatarUrl(data.avatar_url)
setUsername(data.username);
setWebsite(data.website);
setAvatarUrl(data.avatar_url);
}
} catch (error) {
if (error instanceof Error) {
Alert.alert(error.message)
Alert.alert(error.message);
}
} finally {
setLoading(false)
setLoading(false);
}
}
@ -47,13 +47,13 @@ export default function Account({ session }: { session: Session }) {
website,
avatar_url,
}: {
username: string
website: string
avatar_url: string
username: string;
website: string;
avatar_url: string;
}) {
try {
setLoading(true)
if (!session?.user) throw new Error('No user on the session!')
setLoading(true);
if (!session?.user) throw new Error('No user on the session!');
const updates = {
id: session?.user.id,
@ -61,32 +61,32 @@ export default function Account({ session }: { session: Session }) {
website,
avatar_url,
updated_at: new Date(),
}
};
const { error } = await supabase.from('profiles').upsert(updates)
const { error } = await supabase.from('profiles').upsert(updates);
if (error) {
throw error
throw error;
}
} catch (error) {
if (error instanceof Error) {
Alert.alert(error.message)
Alert.alert(error.message);
}
} finally {
setLoading(false)
setLoading(false);
}
}
return (
<View style={styles.container}>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Input label="Email" value={session?.user?.email} disabled />
<Input label='Email' value={session?.user?.email} disabled />
</View>
<View style={styles.verticallySpaced}>
<Input label="Username" value={username || ''} onChangeText={(text) => setUsername(text)} />
<Input label='Username' value={username || ''} onChangeText={(text) => setUsername(text)} />
</View>
<View style={styles.verticallySpaced}>
<Input label="Website" value={website || ''} onChangeText={(text) => setWebsite(text)} />
<Input label='Website' value={website || ''} onChangeText={(text) => setWebsite(text)} />
</View>
<View style={[styles.verticallySpaced, styles.mt20]}>
@ -98,10 +98,10 @@ export default function Account({ session }: { session: Session }) {
</View>
<View style={styles.verticallySpaced}>
<Button title="Sign Out" onPress={() => supabase.auth.signOut()} />
<Button title='Sign Out' onPress={() => supabase.auth.signOut()} />
</View>
</View>
)
);
}
const styles = StyleSheet.create({
@ -117,4 +117,4 @@ const styles = StyleSheet.create({
mt20: {
marginTop: 20,
},
})
});

View File

@ -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,
},
})

View File

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

162
components/auth/Login.tsx Normal file
View File

@ -0,0 +1,162 @@
import React, { useState, useEffect } from 'react';
import { Alert, StyleSheet, AppState, Image, Platform } from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import AppleSignIn from '@/components/auth/AppleSignIn';
// 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 LoginPage = () => {
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: email,
password: password,
});
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
fontSize={24}
onChangeText={(text) => setEmail(text)}
value={email}
placeholder='email@address.com'
/>
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<ThemedTextInput
fontSize={24}
onChangeText={(text) => setPassword(text)}
value={password}
secureTextEntry={true}
placeholder='Password'
/>
</ThemedView>
<ThemedView style={[styles.verticallySpaced, styles.mt20]}>
<ThemedTextButton
text='Sign in'
disabled={loading}
onPress={() => signInWithEmail()}
fontSize={24}
/>
</ThemedView>
<ThemedView style={styles.verticallySpaced}>
<ThemedTextButton
text='Sign up'
disabled={loading}
onPress={() => signUpWithEmail()}
fontSize={24}
/>
</ThemedView>
{/* Apple Sign In - Only shows on iOS */}
<ThemedView style={[styles.verticallySpaced, styles.mt20]}>
<AppleSignIn
onSignInStart={() => setLoading(true)}
onSignInComplete={() => setLoading(false)}
onSignInError={() => setLoading(false)}
/>
</ThemedView>
</ThemedView>
);
};
export default LoginPage;
const styles = StyleSheet.create({
container: {
padding: 12,
height: '100%',
},
verticallySpaced: {
paddingTop: 4,
paddingBottom: 4,
alignItems: 'center',
},
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: 20,
},
dividerText: {
marginHorizontal: 10,
fontSize: 16,
opacity: 0.7,
},
});

View File

@ -0,0 +1,23 @@
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import { Alert, StyleSheet, AppState } from 'react-native';
const Logout_Button = () => {
const signOut = async () => {
const { error } = await supabase.auth.signOut();
if (error) Alert.alert(error.message);
};
return (
<ThemedTextButton
width={120}
height={60}
text='Logout'
fontSize={16}
onPress={() => signOut()}
/>
);
};
export default Logout_Button;
const styles = StyleSheet.create({});

View File

@ -1,6 +1,6 @@
import { PropsWithChildren, useState } from 'react';
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 { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

View File

@ -6,7 +6,7 @@ import Animated, {
useAnimatedStyle,
useScrollViewOffset,
} from 'react-native-reanimated';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
import { ThemedText, ThemedView } from '@/components/theme';
import { useBottomTabOverflow } from '@/components/ui/TabBarBackground';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

View File

@ -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;

View File

@ -1,25 +1,30 @@
import { StyleSheet, Pressable } from 'react-native';
import { ThemedView } from '@/components/theme/Theme';
import React from 'react';
import { StyleSheet, Pressable, PressableProps } from 'react-native';
import ThemedView from '@/components/theme/default/ThemedView';
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 = {
type ThemedButtonProps = PressableProps & {
width?: number;
height?: number;
onPress?: () => void;
containerStyle?: object;
buttonStyle?: object;
};
const Button = ({
const ThemedButton: React.FC<ThemedButtonProps> = ({
width,
height,
children,
onPress,
}: Props & React.ComponentProps<typeof Pressable>) => {
containerStyle,
buttonStyle,
style,
...restProps // This now includes onPress automatically
}) => {
const scheme = useColorScheme() ?? 'dark';
return (
<ThemedView
style={[
@ -28,18 +33,20 @@ const Button = ({
width: width ?? DEFAULT_WIDTH,
height: height ?? DEFAULT_HEIGHT,
},
containerStyle,
]}
>
<Pressable
style={[styles.button, { backgroundColor: Colors[scheme].text }]}
onPress={onPress}
style={[styles.button, { backgroundColor: Colors[scheme].text }, buttonStyle, style]}
{...restProps} // This passes onPress and all other Pressable props
>
{children}
</Pressable>
</ThemedView>
);
};
export default Button;
export default ThemedButton;
const styles = StyleSheet.create({
buttonContainer: {

View File

@ -0,0 +1,56 @@
import React from 'react';
import { TextStyle, PressableProps } from 'react-native';
import ThemedButton from '@/components/theme/buttons/ThemedButton';
import ThemedText from '@/components/theme/default/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
const DEFAULT_FONT_SIZE = 16;
// Extend ThemedButton props (which already extends PressableProps)
type ThemedTextButtonProps = Omit<PressableProps, 'children'> & {
width?: number;
height?: number;
text: string;
fontSize?: number;
textStyle?: TextStyle;
containerStyle?: object;
buttonStyle?: object;
};
const ThemedTextButton: React.FC<ThemedTextButtonProps> = ({
width,
height,
text,
fontSize,
textStyle,
containerStyle,
buttonStyle,
...restProps // This includes onPress and all other Pressable props
}) => {
const scheme = useColorScheme() ?? 'dark';
return (
<ThemedButton
width={width}
height={height}
containerStyle={containerStyle}
buttonStyle={buttonStyle}
{...restProps}
>
<ThemedText
style={[
{
color: Colors[scheme].background,
fontSize: fontSize ?? DEFAULT_FONT_SIZE,
},
textStyle,
]}
>
{text}
</ThemedText>
</ThemedButton>
);
};
export default ThemedTextButton;

View File

@ -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 { useThemeColor } from '@/hooks/useThemeColor';
@ -12,12 +12,7 @@ export type ThemedTextProps = TextProps & {
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
};
export const ThemedView = ({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) => {
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
};
export const ThemedText = ({
const ThemedText = ({
style,
lightColor,
darkColor,
@ -40,6 +35,7 @@ export const ThemedText = ({
/>
);
};
export default ThemedText;
const styles = StyleSheet.create({
default: {

View 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;

View 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,
};

View 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;

View 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;

View File

@ -0,0 +1,69 @@
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';
const DEFAULT_WIDTH = 320;
const DEFAULT_HEIGHT = 50;
type ThemedTextInputProps = TextInputProps & {
width?: DimensionValue;
height?: DimensionValue;
fontSize?: number;
containerStyle?: object;
};
const ThemedTextInput: React.FC<ThemedTextInputProps> = ({
width = DEFAULT_WIDTH,
height = DEFAULT_HEIGHT,
fontSize = 16,
containerStyle,
style,
...restProps
}) => {
const scheme = useColorScheme() ?? 'dark';
return (
<ThemedView
style={[
styles.inputContainer,
{
width,
height,
borderColor: Colors[scheme].accent },
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%',
borderRadius: 8,
paddingHorizontal: 15,
},
});

View 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;

View 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;

View 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;

View 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;

View 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;

View File

@ -1,5 +1,5 @@
const black = '#1f1e2c';
const white = '#ECEDEE'
const white = '#ECEDEE';
const darkTint = '#fff';
const lightTint = '#0a7ea4';
const darkIcon = '#9BA1A6';
@ -18,6 +18,15 @@ export const Colors = {
tabIconSelected: lightTint,
ttBlue,
accent: ttLightBlue,
card: '#ffffff',
border: '#d0d7de',
notification: '#f85149',
placeholder: '#8b949e',
inactive: '#afb8c1',
subtle: '#f6f8fa',
error: '#e5484d',
success: '#46954a',
warning: '#daaa3f',
},
dark: {
text: white,
@ -28,5 +37,14 @@ export const Colors = {
tabIconSelected: darkTint,
ttBlue,
accent: ttDarkBlue,
card: '#3a3b4a',
border: '#444c56',
notification: '#ff6a69',
placeholder: '#636e7b',
inactive: '#4d5560',
subtle: '#272934',
error: '#ff6369',
success: '#3fb950',
warning: '#d29922',
},
};

View File

@ -1,21 +1,43 @@
import { createClient } from "@supabase/supabase-js";
import AsyncStorage from "@react-native-async-storage/async-storage";
// lib/supabase.ts
import { createClient } from '@supabase/supabase-js';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as SecureStore from 'expo-secure-store';
import * as aesjs from 'aes-js';
import 'react-native-get-random-values';
import { Platform } from 'react-native';
// As Expo's SecureStore does not support values larger than 2048
// bytes, an AES-256 key is generated and stored in SecureStore, while
// it is used to encrypt/decrypt values stored in AsyncStorage.
// Create a web-compatible storage implementation
class WebStorage {
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 {
private async _encrypt(key: string, value: string) {
const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8));
const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1));
const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value));
await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey));
return aesjs.utils.hex.fromBytes(encryptedBytes);
}
@ -24,17 +46,19 @@ class LargeSecureStore {
if (!encryptionKeyHex) {
return encryptionKeyHex;
}
const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1));
const cipher = new aesjs.ModeOfOperation.ctr(
aesjs.utils.hex.toBytes(encryptionKeyHex),
new aesjs.Counter(1),
);
const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value));
return aesjs.utils.utf8.fromBytes(decryptedBytes);
}
async getItem(key: string) {
const encrypted = await AsyncStorage.getItem(key);
if (!encrypted) { return encrypted; }
if (!encrypted) {
return encrypted;
}
return await this._decrypt(key, encrypted);
}
@ -45,17 +69,18 @@ class LargeSecureStore {
async setItem(key: string, value: string) {
const encrypted = await this._encrypt(key, value);
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 supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY as string;
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
storage: new LargeSecureStore(),
storage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,

707
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -18,14 +18,15 @@
"preset": "jest-expo"
},
"dependencies": {
"@expo/metro-runtime": "~4.0.1",
"@expo/vector-icons": "^14.0.2",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/native": "^7.0.14",
"@rneui/themed": "^4.0.0-rc.8",
"@supabase/supabase-js": "^2.48.1",
"aes-js": "^3.1.2",
"expo": "~52.0.28",
"expo-apple-authentication": "~7.1.3",
"expo-blur": "~14.0.3",
"expo-constants": "~17.0.5",
"expo-dev-client": "~5.0.10",
@ -34,12 +35,14 @@
"expo-insights": "~0.8.2",
"expo-linking": "~7.0.5",
"expo-router": "~4.0.17",
"expo-secure-store": "~14.0.1",
"expo-splash-screen": "~0.29.21",
"expo-status-bar": "~2.0.1",
"expo-symbols": "~0.2.1",
"expo-system-ui": "~4.0.7",
"expo-updates": "~0.26.13",
"expo-web-browser": "~14.0.2",
"jsonwebtoken": "^9.0.2",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-native": "0.76.6",
@ -49,8 +52,7 @@
"react-native-safe-area-context": "4.12.0",
"react-native-screens": "~4.4.0",
"react-native-web": "~0.19.13",
"react-native-webview": "13.12.5",
"expo-secure-store": "~14.0.1"
"react-native-webview": "13.12.5"
},
"devDependencies": {
"@babel/core": "^7.25.2",

99
scripts/files_to_clipboard Executable file
View 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()

View File

@ -0,0 +1,48 @@
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`);