generated from demchenkoalex/react-native-module-template
-
Notifications
You must be signed in to change notification settings - Fork 77
/
Chat.tsx
444 lines (417 loc) · 13.3 KB
/
Chat.tsx
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import {
KeyboardAccessoryView,
useComponentSize,
} from '@flyerhq/react-native-keyboard-accessory-view'
import { oneOf } from '@flyerhq/react-native-link-preview'
import dayjs from 'dayjs'
import calendar from 'dayjs/plugin/calendar'
import * as React from 'react'
import {
FlatList,
FlatListProps,
GestureResponderHandlers,
InteractionManager,
LayoutAnimation,
StatusBar,
StatusBarProps,
Text,
View,
} from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { usePrevious } from '../../hooks'
import { l10n } from '../../l10n'
import { defaultTheme } from '../../theme'
import { MessageType, Theme, User } from '../../types'
import {
calculateChatMessages,
initLocale,
L10nContext,
ThemeContext,
unwrap,
UserContext,
} from '../../utils'
import { CircularActivityIndicator } from '../CircularActivityIndicator'
import { Input, InputAdditionalProps, InputTopLevelProps } from '../Input'
import { Message, MessageTopLevelProps } from '../Message'
import ImageView from './ImageView'
import styles from './styles'
// Untestable
/* istanbul ignore next */
const animate = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
}
// eslint-disable-next-line jest/require-hook
dayjs.extend(calendar)
export type ChatTopLevelProps = InputTopLevelProps & MessageTopLevelProps
export interface ChatProps extends ChatTopLevelProps {
/** Allows you to replace the default Input widget e.g. if you want to create a channel view. */
customBottomComponent?: () => React.ReactNode
/** If {@link ChatProps.dateFormat} and/or {@link ChatProps.timeFormat} is not enough to
* customize date headers in your case, use this to return an arbitrary
* string based on a `dateTime` of a particular message. Can be helpful to
* return "Today" if `dateTime` is today. IMPORTANT: this will replace
* all default date headers, so you must handle all cases yourself, like
* for example today, yesterday and before. Or you can just return the same
* date header for any message. */
customDateHeaderText?: (dateTime: number) => string
/** Allows you to customize the date format. IMPORTANT: only for the date,
* do not return time here. @see {@link ChatProps.timeFormat} to customize the time format.
* @see {@link ChatProps.customDateHeaderText} for more customization. */
dateFormat?: string
/** Disable automatic image preview on tap. */
disableImageGallery?: boolean
/** Allows you to change what the user sees when there are no messages.
* `emptyChatPlaceholder` and `emptyChatPlaceholderTextStyle` are ignored
* in this case. */
emptyState?: () => React.ReactNode
/** Use this to enable `LayoutAnimation`. Experimental on Android (same as React Native). */
enableAnimation?: boolean
flatListProps?: Partial<FlatListProps<MessageType.DerivedAny[]>>
inputProps?: InputAdditionalProps
/** Used for pagination (infinite scroll) together with {@link ChatProps.onEndReached}.
* When true, indicates that there are no more pages to load and
* pagination will not be triggered. */
isLastPage?: boolean
/** Override the default localized copy. */
l10nOverride?: Partial<Record<keyof typeof l10n[keyof typeof l10n], string>>
locale?: keyof typeof l10n
messages: MessageType.Any[]
/** Used for pagination (infinite scroll). Called when user scrolls
* to the very end of the list (minus `onEndReachedThreshold`).
* See {@link ChatProps.flatListProps} to set it up. */
onEndReached?: () => Promise<void>
/** Show user names for received messages. Useful for a group chat. Will be
* shown only on text messages. */
showUserNames?: boolean
/** Chat theme. Implement {@link Theme} to create your own theme or use
* existing one, like the {@link defaultTheme}. */
theme?: Theme
/**
* Allows you to customize the time format. IMPORTANT: only for the time,
* do not return date here. @see {@link ChatProps.dateFormat} to customize the date format.
* @see {@link ChatProps.customDateHeaderText} for more customization.
*/
timeFormat?: string
user: User
}
/** Entry component, represents the complete chat */
export const Chat = ({
customBottomComponent,
customDateHeaderText,
dateFormat,
disableImageGallery,
emptyState,
enableAnimation,
flatListProps,
inputProps,
isAttachmentUploading,
isLastPage,
l10nOverride,
locale = 'en',
messages,
onAttachmentPress,
onEndReached,
onMessageLongPress,
onMessagePress,
onPreviewDataFetched,
onSendPress,
renderBubble,
renderCustomMessage,
renderFileMessage,
renderImageMessage,
renderTextMessage,
sendButtonVisibilityMode = 'editing',
showUserAvatars = false,
showUserNames = false,
textInputProps,
theme = defaultTheme,
timeFormat,
usePreviewData = true,
user,
}: ChatProps) => {
const {
container,
emptyComponentContainer,
emptyComponentTitle,
flatList,
flatListContentContainer,
footer,
footerLoadingPage,
header,
keyboardAccessoryView,
} = styles({ theme })
const { onLayout, size } = useComponentSize()
const animationRef = React.useRef(false)
const list = React.useRef<FlatList<MessageType.DerivedAny>>(null)
const insets = useSafeAreaInsets()
const [isImageViewVisible, setIsImageViewVisible] = React.useState(false)
const [isNextPageLoading, setNextPageLoading] = React.useState(false)
const [imageViewIndex, setImageViewIndex] = React.useState(0)
const [stackEntry, setStackEntry] = React.useState<StatusBarProps>({})
const l10nValue = React.useMemo(
() => ({ ...l10n[locale], ...unwrap(l10nOverride) }),
[l10nOverride, locale]
)
const { chatMessages, gallery } = calculateChatMessages(messages, user, {
customDateHeaderText,
dateFormat,
showUserNames,
timeFormat,
})
const previousChatMessages = usePrevious(chatMessages)
React.useEffect(() => {
if (
chatMessages[0]?.type !== 'dateHeader' &&
chatMessages[0]?.id !== previousChatMessages?.[0]?.id &&
chatMessages[0]?.author?.id === user.id
) {
list.current?.scrollToOffset({
animated: true,
offset: 0,
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatMessages])
React.useEffect(() => {
initLocale(locale)
}, [locale])
// Untestable
/* istanbul ignore next */
if (animationRef.current && enableAnimation) {
InteractionManager.runAfterInteractions(animate)
}
React.useEffect(() => {
// Untestable
/* istanbul ignore next */
if (animationRef.current && enableAnimation) {
InteractionManager.runAfterInteractions(animate)
} else {
animationRef.current = true
}
}, [enableAnimation, messages])
const handleEndReached = React.useCallback(
// Ignoring because `scroll` event for some reason doesn't trigger even basic
// `onEndReached`, impossible to test.
// TODO: Verify again later
/* istanbul ignore next */
async ({ distanceFromEnd }: { distanceFromEnd: number }) => {
if (
!onEndReached ||
isLastPage ||
distanceFromEnd <= 0 ||
messages.length === 0 ||
isNextPageLoading
) {
return
}
setNextPageLoading(true)
await onEndReached?.()
setNextPageLoading(false)
},
[isLastPage, isNextPageLoading, messages.length, onEndReached]
)
const handleImagePress = React.useCallback(
(message: MessageType.Image) => {
setImageViewIndex(
gallery.findIndex(
(image) => image.id === message.id && image.uri === message.uri
)
)
setIsImageViewVisible(true)
setStackEntry(
StatusBar.pushStackEntry({
barStyle: 'light-content',
animated: true,
})
)
},
[gallery]
)
const handleMessagePress = React.useCallback(
(message: MessageType.Any) => {
if (message.type === 'image' && !disableImageGallery) {
handleImagePress(message)
}
onMessagePress?.(message)
},
[disableImageGallery, handleImagePress, onMessagePress]
)
// TODO: Tapping on a close button results in the next warning:
// `An update to ImageViewing inside a test was not wrapped in act(...).`
/* istanbul ignore next */
const handleRequestClose = () => {
setIsImageViewVisible(false)
StatusBar.popStackEntry(stackEntry)
}
const keyExtractor = React.useCallback(
({ id }: MessageType.DerivedAny) => id,
[]
)
const renderItem = React.useCallback(
({ item: message }: { item: MessageType.DerivedAny; index: number }) => {
const messageWidth =
showUserAvatars &&
message.type !== 'dateHeader' &&
message.author.id !== user.id
? Math.floor(Math.min(size.width * 0.72, 440))
: Math.floor(Math.min(size.width * 0.77, 440))
const roundBorder =
message.type !== 'dateHeader' && message.nextMessageInGroup
const showAvatar =
message.type !== 'dateHeader' && !message.nextMessageInGroup
const showName = message.type !== 'dateHeader' && message.showName
const showStatus = message.type !== 'dateHeader' && message.showStatus
return (
<Message
{...{
enableAnimation,
message,
messageWidth,
onMessageLongPress,
onMessagePress: handleMessagePress,
onPreviewDataFetched,
renderBubble,
renderCustomMessage,
renderFileMessage,
renderImageMessage,
renderTextMessage,
roundBorder,
showAvatar,
showName,
showStatus,
showUserAvatars,
usePreviewData,
}}
/>
)
},
[
enableAnimation,
handleMessagePress,
onMessageLongPress,
onPreviewDataFetched,
renderBubble,
renderCustomMessage,
renderFileMessage,
renderImageMessage,
renderTextMessage,
showUserAvatars,
size.width,
usePreviewData,
user.id,
]
)
const renderListEmptyComponent = React.useCallback(
() => (
<View style={emptyComponentContainer}>
{oneOf(
emptyState,
<Text style={emptyComponentTitle}>
{l10nValue.emptyChatPlaceholder}
</Text>
)()}
</View>
),
[emptyComponentContainer, emptyComponentTitle, emptyState, l10nValue]
)
const renderListFooterComponent = React.useCallback(
() =>
// Impossible to test, see `handleEndReached` function
/* istanbul ignore next */
isNextPageLoading ? (
<View style={footerLoadingPage}>
<CircularActivityIndicator color={theme.colors.primary} size={16} />
</View>
) : (
<View style={footer} />
),
[footer, footerLoadingPage, isNextPageLoading, theme.colors.primary]
)
const renderScrollable = React.useCallback(
(panHandlers: GestureResponderHandlers) => (
<FlatList
automaticallyAdjustContentInsets={false}
contentContainerStyle={[
flatListContentContainer,
// eslint-disable-next-line react-native/no-inline-styles
{
justifyContent: chatMessages.length !== 0 ? undefined : 'center',
paddingTop: insets.bottom,
},
]}
initialNumToRender={10}
ListEmptyComponent={renderListEmptyComponent}
ListFooterComponent={renderListFooterComponent}
ListHeaderComponent={<View />}
ListHeaderComponentStyle={header}
maxToRenderPerBatch={6}
onEndReachedThreshold={0.75}
style={flatList}
showsVerticalScrollIndicator={false}
{...unwrap(flatListProps)}
data={chatMessages}
inverted
keyboardDismissMode='interactive'
keyExtractor={keyExtractor}
onEndReached={handleEndReached}
ref={list}
renderItem={renderItem}
{...panHandlers}
/>
),
[
chatMessages,
flatList,
flatListContentContainer,
flatListProps,
handleEndReached,
header,
insets.bottom,
keyExtractor,
renderItem,
renderListEmptyComponent,
renderListFooterComponent,
]
)
return (
<UserContext.Provider value={user}>
<ThemeContext.Provider value={theme}>
<L10nContext.Provider value={l10nValue}>
<View style={container} onLayout={onLayout}>
{customBottomComponent ? (
<>
<>{renderScrollable({})}</>
<>{customBottomComponent()}</>
</>
) : (
<KeyboardAccessoryView
{...{
renderScrollable,
style: keyboardAccessoryView,
}}
>
<Input
{...{
...unwrap(inputProps),
isAttachmentUploading,
onAttachmentPress,
onSendPress,
renderScrollable,
sendButtonVisibilityMode,
textInputProps,
}}
/>
</KeyboardAccessoryView>
)}
<ImageView
imageIndex={imageViewIndex}
images={gallery}
onRequestClose={handleRequestClose}
visible={isImageViewVisible}
/>
</View>
</L10nContext.Provider>
</ThemeContext.Provider>
</UserContext.Provider>
)
}