oh my god this is so hard
This commit is contained in:
parent
f48ec76cba
commit
c0ebccf6b1
@ -10,6 +10,7 @@ import {
|
||||
SystemMessage,
|
||||
} from 'react-native-gifted-chat';
|
||||
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
|
||||
import AccessoryBar from '@/components/chat/AccessoryBar';
|
||||
import CustomActions from '@/components/chat/CustomActions';
|
||||
import CustomView from '@/components/chat/CustomView';
|
||||
import * as Clipboard from 'expo-clipboard';
|
||||
@ -20,44 +21,36 @@ import {
|
||||
ActionKind,
|
||||
User,
|
||||
Message,
|
||||
NotificationMessage,
|
||||
} from '@/constants/Types';
|
||||
import {getInitialMessages, sendMessage} from '@/constants/APIs';
|
||||
import {getMessages, sendMessage} from '@/constants/APIs';
|
||||
import { getUser, getPartner } from '@/components/services/SecureStore';
|
||||
import { sendPushNotification } from '@/components/services/notifications/PushNotificationManager';
|
||||
|
||||
const reducer = (state: GCState, action: GCStateAction) => {
|
||||
switch (action.type) {
|
||||
case ActionKind.SEND_MESSAGE: {
|
||||
return {
|
||||
...state,
|
||||
messages: action.payload,
|
||||
};
|
||||
return { ...state, messages: action.payload };
|
||||
}
|
||||
case ActionKind.LOAD_EARLIER_MESSAGES: {
|
||||
return {
|
||||
...state,
|
||||
loadEarlier: true,
|
||||
isLoadingEarlier: false,
|
||||
messages: action.payload,
|
||||
return { ...state, loadEarlier: true,
|
||||
isLoadingEarlier: false, messages: action.payload
|
||||
};
|
||||
}
|
||||
case ActionKind.LOAD_EARLIER_START: {
|
||||
return {
|
||||
...state,
|
||||
isLoadingEarlier: true,
|
||||
}
|
||||
return { ...state, isLoadingEarlier: true }
|
||||
}
|
||||
case ActionKind.SET_IS_TYPING: {
|
||||
return {
|
||||
...state,
|
||||
isTyping: action.payload,
|
||||
}
|
||||
return { ...state, isTyping: action.payload }
|
||||
}
|
||||
default: return state;
|
||||
}
|
||||
};
|
||||
|
||||
const MessagesScreen = () => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [partner, setPartner] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [state, dispatch] = useReducer(reducer, {
|
||||
messages: [],
|
||||
step: 0,
|
||||
@ -66,32 +59,42 @@ const MessagesScreen = () => {
|
||||
isTyping: false,
|
||||
});
|
||||
const msgUser: GCUser = {
|
||||
_id: user?.id || 0,
|
||||
_id: user?.id ?? 0,
|
||||
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 = {
|
||||
_id: partner?.id || 0,
|
||||
_id: partner?.id ?? 0,
|
||||
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(() => {
|
||||
const initializeUsers = async () => {
|
||||
const initialize = async () => {
|
||||
try{
|
||||
const userData: User = await getUser() as User;
|
||||
const partnerData: User = await getPartner() as User;
|
||||
if (userData && partnerData) {
|
||||
setUser(userData);
|
||||
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 {
|
||||
const initialMessages = await getInitialMessages(userId);
|
||||
const initialMessages = await getMessages(userId, limit, offset);
|
||||
if (initialMessages) {
|
||||
const formattedMessages = formatMessages(initialMessages);
|
||||
dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
|
||||
@ -113,62 +116,85 @@ const MessagesScreen = () => {
|
||||
|
||||
const onSend = useCallback(async (messages: any[]) => {
|
||||
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 = {
|
||||
id: tempId,
|
||||
senderId: user.id,
|
||||
receiverId: partner?.id ?? 0,
|
||||
text: messages[0].text,
|
||||
createdAt: new Date(),
|
||||
createdAt,
|
||||
isRead: false,
|
||||
hasLocation: false,
|
||||
hasMedia: 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]);
|
||||
dispatch({
|
||||
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);
|
||||
if (!sentMessage)
|
||||
throw new Error('Message failed to send');
|
||||
const updatedMessages = state.messages.map(msg =>
|
||||
msg._id === tempId ? {...msg, _id: sentMessage.id} : msg
|
||||
) as IMessage[];
|
||||
dispatch({
|
||||
type: ActionKind.SEND_MESSAGE,
|
||||
payload: updatedMessages,
|
||||
});
|
||||
|
||||
// Fetch the latest messages from the server to ensure consistency
|
||||
const updatedMessages = await getMessages(user?.id ?? 0);
|
||||
if (updatedMessages) {
|
||||
const formattedMessages = formatMessages(updatedMessages);
|
||||
dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error sending message:', error);
|
||||
const updatedMessages = state.messages.filter(msg => msg._id !== tempId);
|
||||
dispatch({
|
||||
type: ActionKind.SEND_MESSAGE,
|
||||
payload: updatedMessages,
|
||||
});
|
||||
|
||||
// In case of an error, remove the temporary message from the state
|
||||
const updatedMessages = state.messages.filter((msg) => msg._id !== tempId);
|
||||
dispatch({ type: ActionKind.SEND_MESSAGE, payload: updatedMessages });
|
||||
Alert.alert('Error', 'Failed to send message. Please try again.');
|
||||
}
|
||||
}, [user, state.messages]);
|
||||
|
||||
}, [user, partner, state.messages]);
|
||||
|
||||
const onLoadEarlier = useCallback(async () => {
|
||||
if (!user || !partner) return;
|
||||
if (!user) return;
|
||||
|
||||
// Set loading state
|
||||
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 {
|
||||
const earlierMessages = await getInitialMessages(user.id, 20, state.messages.length);
|
||||
const earlierMessages = await getMessages(user.id, 20, offset);
|
||||
if (earlierMessages) {
|
||||
const formattedMessages = formatMessages(earlierMessages);
|
||||
|
||||
// Prepend older messages
|
||||
dispatch({
|
||||
type: ActionKind.LOAD_EARLIER_MESSAGES,
|
||||
payload: GiftedChat.prepend(state.messages, formattedMessages, Platform.OS !== 'web')
|
||||
payload: GiftedChat.prepend(state.messages, formattedMessages),
|
||||
});
|
||||
}
|
||||
} 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(() => {
|
||||
return [
|
||||
@ -229,7 +255,7 @@ const MessagesScreen = () => {
|
||||
},
|
||||
]);
|
||||
else console.warn('replies param is not set correctly');
|
||||
}, []);
|
||||
}, [msgUser, onSend]);
|
||||
|
||||
const renderQuickReplySend = useCallback(() => {
|
||||
return <ThemedText>{'custom send =>'}</ThemedText>
|
||||
@ -239,6 +265,15 @@ const MessagesScreen = () => {
|
||||
dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping });
|
||||
}, [dispatch]);
|
||||
|
||||
const renderAccessory = useCallback(() => {
|
||||
return (
|
||||
<AccessoryBar
|
||||
onSend={onSend}
|
||||
isTyping={() => setIsTyping(!state.isTyping)}
|
||||
/>
|
||||
);
|
||||
}, [onSend, setIsTyping, state.isTyping]);
|
||||
|
||||
const renderCustomActions = useCallback(
|
||||
props =>
|
||||
Platform.OS === 'web' ? null : (
|
||||
@ -272,7 +307,7 @@ const MessagesScreen = () => {
|
||||
);
|
||||
}, []);
|
||||
|
||||
if (!user || !partner) return (
|
||||
if (loading) return (
|
||||
<ActivityIndicator size='large' color='#0000ff'/>
|
||||
);
|
||||
|
||||
@ -286,7 +321,7 @@ const MessagesScreen = () => {
|
||||
onLoadEarlier={onLoadEarlier}
|
||||
isLoadingEarlier={state.isLoadingEarlier}
|
||||
parsePatterns={parsePatterns}
|
||||
user={msgUser as GCUser}
|
||||
user={msgUser}
|
||||
scrollToBottom
|
||||
onPressAvatar={onPressAvatar}
|
||||
onLongPressAvatar={onLongPressAvatar}
|
||||
@ -297,6 +332,7 @@ const MessagesScreen = () => {
|
||||
fontWeight: '200',
|
||||
}}
|
||||
renderQuickReplySend={renderQuickReplySend}
|
||||
renderAccessory={renderAccessory}
|
||||
renderActions={renderCustomActions}
|
||||
renderSystemMessage={renderSystemMessage}
|
||||
renderCustomView={renderCustomView}
|
||||
|
3
components/.map_fix/map.js
Normal file
3
components/.map_fix/map.js
Normal file
@ -0,0 +1,3 @@
|
||||
import MapView from 'react-native-maps';
|
||||
|
||||
export default MapView;
|
3
components/.map_fix/map.web.js
Normal file
3
components/.map_fix/map.web.js
Normal file
@ -0,0 +1,3 @@
|
||||
import MapView from "@teovilla/react-native-web-maps";
|
||||
|
||||
export default MapView;
|
@ -8,7 +8,8 @@ import {
|
||||
ViewStyle
|
||||
} from 'react-native';
|
||||
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 = {
|
||||
currentMessage: any;
|
||||
|
@ -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;
|
||||
try {
|
||||
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/getInitialMessages`;
|
||||
const response = await fetch((apiUrl + `?userId=${userId}&limit=${limit}`), {
|
||||
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/get`;
|
||||
const response = await fetch((apiUrl+`?userId=${userId}&limit=${limit}&offset=${offset}`), {
|
||||
headers: {
|
||||
'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) => {
|
||||
if (!message) return;
|
||||
try {
|
||||
const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/api/messages/send`;
|
||||
const response = await fetch(apiUrl, {
|
||||
|
29
package.json
29
package.json
@ -14,25 +14,26 @@
|
||||
"preset": "jest-expo"
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/vector-icons": "^14.0.2",
|
||||
"@react-navigation/native": "^6.0.2",
|
||||
"@expo/vector-icons": "^14.0.4",
|
||||
"@react-navigation/native": "^6.1.18",
|
||||
"@teovilla/react-native-web-maps": "^0.9.5",
|
||||
"@types/lodash.debounce": "^4.0.9",
|
||||
"expo": "~51.0.28",
|
||||
"expo": "~51.0.38",
|
||||
"expo-apple-authentication": "~6.4.2",
|
||||
"expo-clipboard": "~6.0.3",
|
||||
"expo-constants": "~16.0.2",
|
||||
"expo-device": "~6.0.2",
|
||||
"expo-file-system": "~17.0.1",
|
||||
"expo-font": "~12.0.9",
|
||||
"expo-font": "~12.0.10",
|
||||
"expo-image-manipulator": "~12.0.5",
|
||||
"expo-image-picker": "~15.0.7",
|
||||
"expo-linking": "~6.3.1",
|
||||
"expo-location": "~17.0.1",
|
||||
"expo-notifications": "~0.28.18",
|
||||
"expo-notifications": "~0.28.19",
|
||||
"expo-permissions": "^14.4.0",
|
||||
"expo-router": "~3.5.23",
|
||||
"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-system-ui": "~3.0.7",
|
||||
"expo-web-browser": "~13.0.3",
|
||||
@ -40,22 +41,22 @@
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
"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-gifted-chat": "^2.6.4",
|
||||
"react-native-maps": "1.14.0",
|
||||
"react-native-reanimated": "~3.10.1",
|
||||
"react-native-safe-area-context": "4.10.5",
|
||||
"react-native-screens": "3.31.1",
|
||||
"react-native-web": "~0.19.10"
|
||||
"react-native-web": "~0.19.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.20.0",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/react": "~18.2.45",
|
||||
"@types/react-test-renderer": "^18.0.7",
|
||||
"jest": "^29.2.1",
|
||||
"jest-expo": "~51.0.3",
|
||||
"@babel/core": "^7.25.9",
|
||||
"@types/jest": "^29.5.13",
|
||||
"@types/react": "~18.2.79",
|
||||
"@types/react-test-renderer": "^18.3.0",
|
||||
"jest": "^29.7.0",
|
||||
"jest-expo": "~51.0.4",
|
||||
"react-test-renderer": "18.2.0",
|
||||
"typescript": "~5.3.3"
|
||||
},
|
||||
|
2519
pnpm-lock.yaml
generated
2519
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user