oh my god this is so hard

This commit is contained in:
Gabriel Brown 2024-10-22 16:38:06 -05:00
parent f48ec76cba
commit c0ebccf6b1
8 changed files with 1444 additions and 1318 deletions

View File

@ -10,6 +10,7 @@ import {
SystemMessage, SystemMessage,
} from 'react-native-gifted-chat'; } from 'react-native-gifted-chat';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'; import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import AccessoryBar from '@/components/chat/AccessoryBar';
import CustomActions from '@/components/chat/CustomActions'; import CustomActions from '@/components/chat/CustomActions';
import CustomView from '@/components/chat/CustomView'; import CustomView from '@/components/chat/CustomView';
import * as Clipboard from 'expo-clipboard'; import * as Clipboard from 'expo-clipboard';
@ -20,44 +21,36 @@ import {
ActionKind, ActionKind,
User, User,
Message, Message,
NotificationMessage,
} from '@/constants/Types'; } from '@/constants/Types';
import {getInitialMessages, sendMessage} from '@/constants/APIs'; import {getMessages, sendMessage} from '@/constants/APIs';
import { getUser, getPartner } from '@/components/services/SecureStore'; import { getUser, getPartner } from '@/components/services/SecureStore';
import { sendPushNotification } from '@/components/services/notifications/PushNotificationManager';
const reducer = (state: GCState, action: GCStateAction) => { const reducer = (state: GCState, action: GCStateAction) => {
switch (action.type) { switch (action.type) {
case ActionKind.SEND_MESSAGE: { case ActionKind.SEND_MESSAGE: {
return { return { ...state, messages: action.payload };
...state,
messages: action.payload,
};
} }
case ActionKind.LOAD_EARLIER_MESSAGES: { case ActionKind.LOAD_EARLIER_MESSAGES: {
return { return { ...state, loadEarlier: true,
...state, isLoadingEarlier: false, messages: action.payload
loadEarlier: true,
isLoadingEarlier: false,
messages: action.payload,
}; };
} }
case ActionKind.LOAD_EARLIER_START: { case ActionKind.LOAD_EARLIER_START: {
return { return { ...state, isLoadingEarlier: true }
...state,
isLoadingEarlier: true,
}
} }
case ActionKind.SET_IS_TYPING: { case ActionKind.SET_IS_TYPING: {
return { return { ...state, isTyping: action.payload }
...state,
isTyping: action.payload,
}
} }
default: return state;
} }
}; };
const MessagesScreen = () => { const MessagesScreen = () => {
const [user, setUser] = useState<User | null>(null); const [user, setUser] = useState<User | null>(null);
const [partner, setPartner] = useState<User | null>(null); const [partner, setPartner] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [state, dispatch] = useReducer(reducer, { const [state, dispatch] = useReducer(reducer, {
messages: [], messages: [],
step: 0, step: 0,
@ -66,32 +59,42 @@ const MessagesScreen = () => {
isTyping: false, isTyping: false,
}); });
const msgUser: GCUser = { const msgUser: GCUser = {
_id: user?.id || 0, _id: user?.id ?? 0,
name: user?.fullName ?? 'You', name: user?.fullName ?? 'You',
avatar: user?.pfpUrl ?? require('@/assets/images/default-profile.png'), avatar: `${process.env.EXPO_PUBLIC_API_URL}${user?.pfpUrl}` ??
`${process.env.EXPO_PUBLIC_API_URL}/images/default-profile.png`,
}; };
const msgPartner: GCUser = { const msgPartner: GCUser = {
_id: partner?.id || 0, _id: partner?.id ?? 0,
name: partner?.fullName ?? 'Your Partner', name: partner?.fullName ?? 'Your Partner',
avatar: partner?.pfpUrl ?? require('@/assets/images/default-profile.png'), avatar: `${process.env.EXPO_PUBLIC_API_URL}${partner?.pfpUrl}` ??
`${process.env.EXPO_PUBLIC_API_URL}/images/default-profile.png`,
}; };
useEffect(() => { useEffect(() => {
const initializeUsers = async () => { const initialize = async () => {
try{
const userData: User = await getUser() as User; const userData: User = await getUser() as User;
const partnerData: User = await getPartner() as User; const partnerData: User = await getPartner() as User;
if (userData && partnerData) { if (userData && partnerData) {
setUser(userData); setUser(userData);
setPartner(partnerData); setPartner(partnerData);
fetchInitialMessages(userData.id); await fetchInitialMessages(userData.id);
} else
throw new Error('User or partner not found');
} catch (error) {
console.error('Error initializing users:', error);
Alert.alert('Error', 'Failed to initialize users. Please try again.');
} finally {
setLoading(false);
} }
}; };
initializeUsers(); initialize();
}, []); }, []);
const fetchInitialMessages = async (userId: number) => { const fetchInitialMessages = async (userId: number, limit: number = 20, offset: number = 0) => {
try { try {
const initialMessages = await getInitialMessages(userId); const initialMessages = await getMessages(userId, limit, offset);
if (initialMessages) { if (initialMessages) {
const formattedMessages = formatMessages(initialMessages); const formattedMessages = formatMessages(initialMessages);
dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages }); dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
@ -113,62 +116,85 @@ const MessagesScreen = () => {
const onSend = useCallback(async (messages: any[]) => { const onSend = useCallback(async (messages: any[]) => {
if (!user || !partner) return; if (!user || !partner) return;
const tempId = Math.round(Math.random() * -1000000);
try { // Prepare the message to be sent
const createdAt = new Date();
const tempId = Math.round(Math.random() * -1000000); // Temporary ID
const messageToSend: Message = { const messageToSend: Message = {
id: tempId, id: tempId,
senderId: user.id, senderId: user.id,
receiverId: partner?.id ?? 0, receiverId: partner?.id ?? 0,
text: messages[0].text, text: messages[0].text,
createdAt: new Date(), createdAt,
isRead: false, isRead: false,
hasLocation: false, hasLocation: false,
hasMedia: false, hasMedia: false,
hasQuickReply: false, hasQuickReply: false,
}; };
const notificationMessage: NotificationMessage = {
sound: 'default',
title: 'New message from ' + user.fullName,
body: messageToSend.text,
data: {
message: messageToSend,
},
};
//sendPushNotification(partner.pushToken, notificationMessage);
sendPushNotification(user.pushToken, notificationMessage);
// Add the message with a tempId immediately to the state
const tempFormattedMessages = formatMessages([messageToSend]); const tempFormattedMessages = formatMessages([messageToSend]);
dispatch({ dispatch({
type: ActionKind.SEND_MESSAGE, type: ActionKind.SEND_MESSAGE,
payload: GiftedChat.append(state.messages, tempFormattedMessages, Platform.OS !== 'web'), payload: GiftedChat.append(state.messages, tempFormattedMessages),
}); });
try {
// Send the message to the server
const sentMessage = await sendMessage(messageToSend); const sentMessage = await sendMessage(messageToSend);
if (!sentMessage)
throw new Error('Message failed to send'); // Fetch the latest messages from the server to ensure consistency
const updatedMessages = state.messages.map(msg => const updatedMessages = await getMessages(user?.id ?? 0);
msg._id === tempId ? {...msg, _id: sentMessage.id} : msg if (updatedMessages) {
) as IMessage[]; const formattedMessages = formatMessages(updatedMessages);
dispatch({ dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
type: ActionKind.SEND_MESSAGE, }
payload: updatedMessages,
});
} catch (error) { } catch (error) {
console.error('Error sending message:', error); console.error('Error sending message:', error);
const updatedMessages = state.messages.filter(msg => msg._id !== tempId);
dispatch({ // In case of an error, remove the temporary message from the state
type: ActionKind.SEND_MESSAGE, const updatedMessages = state.messages.filter((msg) => msg._id !== tempId);
payload: updatedMessages, dispatch({ type: ActionKind.SEND_MESSAGE, payload: updatedMessages });
});
Alert.alert('Error', 'Failed to send message. Please try again.'); Alert.alert('Error', 'Failed to send message. Please try again.');
} }
}, [user, state.messages]); }, [user, partner, state.messages]);
const onLoadEarlier = useCallback(async () => { const onLoadEarlier = useCallback(async () => {
if (!user || !partner) return; if (!user) return;
// Set loading state
dispatch({ type: ActionKind.LOAD_EARLIER_START }); dispatch({ type: ActionKind.LOAD_EARLIER_START });
// Fetch the current size of messages already in chat to calculate the new offset
const offset = state.messages.length;
try { try {
const earlierMessages = await getInitialMessages(user.id, 20, state.messages.length); const earlierMessages = await getMessages(user.id, 20, offset);
if (earlierMessages) { if (earlierMessages) {
const formattedMessages = formatMessages(earlierMessages); const formattedMessages = formatMessages(earlierMessages);
// Prepend older messages
dispatch({ dispatch({
type: ActionKind.LOAD_EARLIER_MESSAGES, type: ActionKind.LOAD_EARLIER_MESSAGES,
payload: GiftedChat.prepend(state.messages, formattedMessages, Platform.OS !== 'web') payload: GiftedChat.prepend(state.messages, formattedMessages),
}); });
} }
} catch (error) { } catch (error) {
console.error('Error fetching earlier messages:', error); console.error('Error loading earlier messages:', error);
} }
}, [dispatch, state.messages]); }, [user, state.messages]);
const parsePatterns = useCallback(() => { const parsePatterns = useCallback(() => {
return [ return [
@ -229,7 +255,7 @@ const MessagesScreen = () => {
}, },
]); ]);
else console.warn('replies param is not set correctly'); else console.warn('replies param is not set correctly');
}, []); }, [msgUser, onSend]);
const renderQuickReplySend = useCallback(() => { const renderQuickReplySend = useCallback(() => {
return <ThemedText>{'custom send =>'}</ThemedText> return <ThemedText>{'custom send =>'}</ThemedText>
@ -239,6 +265,15 @@ const MessagesScreen = () => {
dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping }); dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping });
}, [dispatch]); }, [dispatch]);
const renderAccessory = useCallback(() => {
return (
<AccessoryBar
onSend={onSend}
isTyping={() => setIsTyping(!state.isTyping)}
/>
);
}, [onSend, setIsTyping, state.isTyping]);
const renderCustomActions = useCallback( const renderCustomActions = useCallback(
props => props =>
Platform.OS === 'web' ? null : ( Platform.OS === 'web' ? null : (
@ -272,7 +307,7 @@ const MessagesScreen = () => {
); );
}, []); }, []);
if (!user || !partner) return ( if (loading) return (
<ActivityIndicator size='large' color='#0000ff'/> <ActivityIndicator size='large' color='#0000ff'/>
); );
@ -286,7 +321,7 @@ const MessagesScreen = () => {
onLoadEarlier={onLoadEarlier} onLoadEarlier={onLoadEarlier}
isLoadingEarlier={state.isLoadingEarlier} isLoadingEarlier={state.isLoadingEarlier}
parsePatterns={parsePatterns} parsePatterns={parsePatterns}
user={msgUser as GCUser} user={msgUser}
scrollToBottom scrollToBottom
onPressAvatar={onPressAvatar} onPressAvatar={onPressAvatar}
onLongPressAvatar={onLongPressAvatar} onLongPressAvatar={onLongPressAvatar}
@ -297,6 +332,7 @@ const MessagesScreen = () => {
fontWeight: '200', fontWeight: '200',
}} }}
renderQuickReplySend={renderQuickReplySend} renderQuickReplySend={renderQuickReplySend}
renderAccessory={renderAccessory}
renderActions={renderCustomActions} renderActions={renderCustomActions}
renderSystemMessage={renderSystemMessage} renderSystemMessage={renderSystemMessage}
renderCustomView={renderCustomView} renderCustomView={renderCustomView}

View File

@ -0,0 +1,3 @@
import MapView from 'react-native-maps';
export default MapView;

View File

@ -0,0 +1,3 @@
import MapView from "@teovilla/react-native-web-maps";
export default MapView;

View File

@ -8,7 +8,8 @@ import {
ViewStyle ViewStyle
} from 'react-native'; } from 'react-native';
import { ThemedText, ThemedView } from '@/components/theme/Theme'; import { ThemedText, ThemedView } from '@/components/theme/Theme';
import MapView from 'react-native-maps'; import MapView from '@/components/.map_fix/map';
//import MapView from 'react-native-maps';
type Props = { type Props = {
currentMessage: any; currentMessage: any;

View File

@ -195,11 +195,11 @@ export const sendRelationshipRequest = async (userId: number, targetUserId: numb
} }
}; };
export const getInitialMessages = async (userId: number, limit: number = 20) => { export const getMessages = async (userId: number, limit: number = 20, offset: number = 0) => {
if (!userId || isNaN(userId)) return; if (!userId || isNaN(userId)) return;
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/getInitialMessages`; const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/get`;
const response = await fetch((apiUrl + `?userId=${userId}&limit=${limit}`), { const response = await fetch((apiUrl+`?userId=${userId}&limit=${limit}&offset=${offset}`), {
headers: { headers: {
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '', 'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
}, },
@ -218,7 +218,6 @@ export const getInitialMessages = async (userId: number, limit: number = 20) =>
}; };
export const sendMessage = async (message: Message) => { export const sendMessage = async (message: Message) => {
if (!message) return;
try { try {
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/send`; const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/send`;
const response = await fetch(apiUrl, { const response = await fetch(apiUrl, {

View File

@ -14,25 +14,26 @@
"preset": "jest-expo" "preset": "jest-expo"
}, },
"dependencies": { "dependencies": {
"@expo/vector-icons": "^14.0.2", "@expo/vector-icons": "^14.0.4",
"@react-navigation/native": "^6.0.2", "@react-navigation/native": "^6.1.18",
"@teovilla/react-native-web-maps": "^0.9.5",
"@types/lodash.debounce": "^4.0.9", "@types/lodash.debounce": "^4.0.9",
"expo": "~51.0.28", "expo": "~51.0.38",
"expo-apple-authentication": "~6.4.2", "expo-apple-authentication": "~6.4.2",
"expo-clipboard": "~6.0.3", "expo-clipboard": "~6.0.3",
"expo-constants": "~16.0.2", "expo-constants": "~16.0.2",
"expo-device": "~6.0.2", "expo-device": "~6.0.2",
"expo-file-system": "~17.0.1", "expo-file-system": "~17.0.1",
"expo-font": "~12.0.9", "expo-font": "~12.0.10",
"expo-image-manipulator": "~12.0.5", "expo-image-manipulator": "~12.0.5",
"expo-image-picker": "~15.0.7", "expo-image-picker": "~15.0.7",
"expo-linking": "~6.3.1", "expo-linking": "~6.3.1",
"expo-location": "~17.0.1", "expo-location": "~17.0.1",
"expo-notifications": "~0.28.18", "expo-notifications": "~0.28.19",
"expo-permissions": "^14.4.0", "expo-permissions": "^14.4.0",
"expo-router": "~3.5.23", "expo-router": "~3.5.23",
"expo-secure-store": "~13.0.2", "expo-secure-store": "~13.0.2",
"expo-splash-screen": "~0.27.5", "expo-splash-screen": "~0.27.6",
"expo-status-bar": "~1.12.1", "expo-status-bar": "~1.12.1",
"expo-system-ui": "~3.0.7", "expo-system-ui": "~3.0.7",
"expo-web-browser": "~13.0.3", "expo-web-browser": "~13.0.3",
@ -40,22 +41,22 @@
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-native": "0.74.5", "react-native": "0.74.5",
"react-native-gesture-handler": "~2.16.1", "react-native-gesture-handler": "~2.16.2",
"react-native-get-random-values": "~1.11.0", "react-native-get-random-values": "~1.11.0",
"react-native-gifted-chat": "^2.6.4", "react-native-gifted-chat": "^2.6.4",
"react-native-maps": "1.14.0", "react-native-maps": "1.14.0",
"react-native-reanimated": "~3.10.1", "react-native-reanimated": "~3.10.1",
"react-native-safe-area-context": "4.10.5", "react-native-safe-area-context": "4.10.5",
"react-native-screens": "3.31.1", "react-native-screens": "3.31.1",
"react-native-web": "~0.19.10" "react-native-web": "~0.19.13"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.25.9",
"@types/jest": "^29.5.12", "@types/jest": "^29.5.13",
"@types/react": "~18.2.45", "@types/react": "~18.2.79",
"@types/react-test-renderer": "^18.0.7", "@types/react-test-renderer": "^18.3.0",
"jest": "^29.2.1", "jest": "^29.7.0",
"jest-expo": "~51.0.3", "jest-expo": "~51.0.4",
"react-test-renderer": "18.2.0", "react-test-renderer": "18.2.0",
"typescript": "~5.3.3" "typescript": "~5.3.3"
}, },

2519
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff