-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatConversationScreen.tsx
More file actions
207 lines (182 loc) · 6.57 KB
/
ChatConversationScreen.tsx
File metadata and controls
207 lines (182 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { useRoute } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
ActivityIndicator,
FlatList,
KeyboardAvoidingView,
Platform,
StyleSheet,
} from 'react-native';
import ChatConversationFooter from '@/components/chat/ChatConversationFooter';
import ChatMessage from '@/components/chat/ChatMessage';
import StatusMessage from '@/components/common/EmptyStateHelper';
import DetailsHeader from '@/components/details/DetailsHeader';
import { EMPTY_VALUE } from '@/constants/common';
import { useAccount } from '@/context/AccountContext';
import { useMessages, MessagesProvider } from '@/context/MessagesContext';
import { useChatData } from '@/hooks/queries/useChatData';
import { screenStyle } from '@/styles';
import type { Message } from '@/types/chat';
import type { RootStackParamList } from '@/types/navigation';
import { mapToChatListItemProps } from '@/utils/chat';
import { TestIDs } from '@/utils/testID';
const SCROLL_TO_NEWEST_DELAY_MS = 200;
const KEYBOARD_VERTICAL_OFFSET = 100;
const LOAD_MORE_THRESHOLD = 0.5;
const ChatConversationScreenContent = () => {
const [inputText, setInputText] = useState('');
const [contentHeight, setContentHeight] = useState(0);
const [layoutHeight, setLayoutHeight] = useState(0);
const { i18n, t } = useTranslation();
const flatListRef = useRef<FlatList<Message>>(null);
const previousFirstMessageIdRef = useRef<string | null>(null);
const { userData } = useAccount();
const currentUserId = userData?.id ?? '';
const {
messages,
messagesLoading,
messagesFetchingNext,
hasMoreMessages,
messagesError,
isUnauthorised,
fetchMessages,
chatId,
} = useMessages();
const { data: chatData } = useChatData(chatId);
const chatProps = useMemo(
() => (chatData ? mapToChatListItemProps(chatData, i18n.language, currentUserId) : null),
[chatData, i18n.language, currentUserId],
);
const otherParticipant =
chatData?.type === 'Direct'
? chatData.participants?.find((p) => p.identity.id !== currentUserId)
: null;
const handleScrollToIndexFailed = useCallback(() => {
flatListRef.current?.scrollToOffset({ offset: 0, animated: true });
}, []);
const scrollToNewestMessage = useCallback(() => {
if (messages.length === 0) return;
setTimeout(() => {
try {
flatListRef.current?.scrollToIndex({
index: 0,
animated: true,
});
} catch (error) {
handleScrollToIndexFailed();
}
}, SCROLL_TO_NEWEST_DELAY_MS);
}, [messages.length, handleScrollToIndexFailed]);
useEffect(() => {
const currentFirstMessageId = messages[0]?.id ?? null;
const previousFirstMessageId = previousFirstMessageIdRef.current;
if (
currentFirstMessageId &&
currentFirstMessageId !== previousFirstMessageId &&
previousFirstMessageId !== null
) {
scrollToNewestMessage();
}
previousFirstMessageIdRef.current = currentFirstMessageId;
}, [messages, scrollToNewestMessage]);
const handleLoadMore = () => {
if (hasMoreMessages && !messagesFetchingNext) {
fetchMessages();
}
};
const sendMessage = () => {
if (!inputText.trim()) return;
setInputText('');
};
const handleContentSizeChange = useCallback((_width: number, height: number) => {
setContentHeight(height);
}, []);
const handleLayout = useCallback((event: { nativeEvent: { layout: { height: number } } }) => {
setLayoutHeight(event.nativeEvent.layout.height);
}, []);
const contentFillsScreen = contentHeight > layoutHeight;
const displayMessages = useMemo(
() => (contentFillsScreen ? messages : [...messages].reverse()),
[messages, contentFillsScreen],
);
const contentContainerStyle = useMemo(
() => (contentFillsScreen ? undefined : screenStyle.contentContainerTop),
[contentFillsScreen],
);
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={KEYBOARD_VERTICAL_OFFSET}
>
<DetailsHeader
id={otherParticipant?.identity.id ?? chatId ?? ''}
title={chatProps?.title ?? EMPTY_VALUE}
subtitle={chatId ?? ''}
statusText=""
imagePath={otherParticipant?.identity.icon ?? ''}
avatars={chatProps?.avatars}
variant="chat"
/>
<StatusMessage
isLoading={messagesLoading}
isError={messagesError}
isEmpty={messages.length === 0}
isUnauthorised={isUnauthorised}
loadingTestId={TestIDs.CHAT_CONVERSATION_LOADING_INDICATOR}
errorTestId={TestIDs.CHAT_CONVERSATION_ERROR_STATE}
emptyTestId={TestIDs.CHAT_CONVERSATION_EMPTY_STATE}
emptyTitle={t('messagesScreen.emptyStateTitle')}
emptyDescription={t('messagesScreen.emptyStateDescription')}
>
<FlatList
ref={flatListRef}
style={styles.flatList}
contentContainerStyle={contentContainerStyle}
data={displayMessages}
extraData={displayMessages}
inverted={contentFillsScreen}
keyExtractor={(item) => item.id}
keyboardShouldPersistTaps="handled"
renderItem={({ item }) => (
<ChatMessage message={item} currentUserId={currentUserId} locale={i18n.language} />
)}
onEndReached={handleLoadMore}
onEndReachedThreshold={LOAD_MORE_THRESHOLD}
onScrollToIndexFailed={handleScrollToIndexFailed}
onContentSizeChange={handleContentSizeChange}
onLayout={handleLayout}
ListHeaderComponent={messagesFetchingNext ? <ActivityIndicator /> : null}
showsVerticalScrollIndicator={false}
maintainVisibleContentPosition={
contentFillsScreen
? {
minIndexForVisible: 0,
}
: undefined
}
/>
</StatusMessage>
<ChatConversationFooter value={inputText} onChangeText={setInputText} onSend={sendMessage} />
</KeyboardAvoidingView>
);
};
const ChatConversationScreen = () => {
const route = useRoute<RouteProp<RootStackParamList, 'chatConversation'>>();
const chatId = route.params?.id;
return (
<MessagesProvider chatId={chatId}>
<ChatConversationScreenContent />
</MessagesProvider>
);
};
const styles = StyleSheet.create({
container: screenStyle.containerFlex,
flatList: {
...screenStyle.containerFlex,
...screenStyle.padding,
},
});
export default ChatConversationScreen;