-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathChat.tsx
More file actions
338 lines (304 loc) · 11 KB
/
Chat.tsx
File metadata and controls
338 lines (304 loc) · 11 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
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
import React, { PropsWithChildren, useEffect, useState } from 'react';
import { Image, Platform } from 'react-native';
import type { Channel, StreamChat } from 'stream-chat';
import { useAppSettings } from './hooks/useAppSettings';
import { useCreateChatContext } from './hooks/useCreateChatContext';
import { useIsOnline } from './hooks/useIsOnline';
import { useMutedUsers } from './hooks/useMutedUsers';
import { useSyncDatabase } from './hooks/useSyncDatabase';
import { ChannelsStateProvider } from '../../contexts/channelsStateContext/ChannelsStateContext';
import { ChatContextValue, ChatProvider } from '../../contexts/chatContext/ChatContext';
import { useDebugContext } from '../../contexts/debugContext/DebugContext';
import { useOverlayContext } from '../../contexts/overlayContext/OverlayContext';
import { DeepPartial, ThemeProvider } from '../../contexts/themeContext/ThemeContext';
import type { Theme } from '../../contexts/themeContext/utils/theme';
import {
DEFAULT_USER_LANGUAGE,
TranslationProvider,
} from '../../contexts/translationContext/TranslationContext';
import { useStreami18n } from '../../hooks/useStreami18n';
import init from '../../init';
import { NativeHandlers } from '../../native';
import { SqliteClient } from '../../store/SqliteClient';
import type { DefaultStreamChatGenerics } from '../../types/types';
import { DBSyncManager } from '../../utils/DBSyncManager';
import type { Streami18n } from '../../utils/i18n/Streami18n';
import { version } from '../../version.json';
init();
export type ChatProps<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
> = Pick<ChatContextValue<StreamChatGenerics>, 'client'> &
Partial<Pick<ChatContextValue<StreamChatGenerics>, 'ImageComponent' | 'isMessageAIGenerated'>> & {
/**
* When false, ws connection won't be disconnection upon backgrounding the app.
* To receive push notifications, its necessary that user doesn't have active
* websocket connection. So by default, we disconnect websocket connection when
* app goes to background, and reconnect when app comes to foreground.
*/
closeConnectionOnBackground?: boolean;
/**
* Enables offline storage and loading for chat data.
*/
enableOfflineSupport?: boolean;
/**
* Instance of Streami18n class should be provided to Chat component to enable internationalization.
*
* Stream provides following list of in-built translations:
* 1. English (en)
* 2. Dutch (nl)
* 3. ...
* 4. ...
*
* Simplest way to start using chat components in one of the in-built languages would be following:
*
* ```
* const i18n = new Streami18n('nl');
* <Chat client={chatClient} i18nInstance={i18n}>
* ...
* </Chat>
* ```
*
* If you would like to override certain keys in in-built translation.
* UI will be automatically updated in this case.
*
* ```
* const i18n = new Streami18n('nl');
*
* i18n.registerTranslation('nl', {
* 'Nothing yet...': 'Nog Niet ...',
* '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} en {{ secondUser }} zijn aan het typen...',
* });
*
* <Chat client={chatClient} i18nInstance={i18n}>
* ...
* </Chat>
* ```
*
* You can use the same function to add whole new language.
*
* ```
* const i18n = new Streami18n('it');
*
* i18n.registerTranslation('it', {
* 'Nothing yet...': 'Non ancora ...',
* '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} a {{ secondUser }} stanno scrivendo...',
* });
*
* // Make sure to call setLanguage to reflect new language in UI.
* i18n.setLanguage('it');
* <Chat client={chatClient} i18nInstance={i18n}>
* ...
* </Chat>
* ```
*/
i18nInstance?: Streami18n;
/**
* Custom loading indicator component to be used to represent the loading state of the chat.
*
* This can be used during the phase when db is not initialised.
*/
LoadingIndicator?: React.ComponentType | null;
/**
* You can pass the theme object to customize the styles of Chat components. You can check the default theme in [theme.ts](https://github.com/GetStream/stream-chat-react-native/blob/main/package/src/contexts/themeContext/utils/theme.ts)
*
* Please check section about [themes in cookbook](https://github.com/GetStream/stream-chat-react-native/wiki/Cookbook-v3.0#theme) for details.
*
* ```
* import type { DeepPartial, Theme } from 'stream-chat-react-native';
*
* const theme: DeepPartial<Theme> = {
* messageSimple: {
* file: {
* container: {
* backgroundColor: 'red',
* },
* icon: {
* height: 16,
* width: 16,
* },
* },
* },
* };
*
* <Chat style={theme}>
* </Chat>
* ```
*
* @overrideType object
*/
style?: DeepPartial<Theme>;
};
const ChatWithContext = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>(
props: PropsWithChildren<ChatProps<StreamChatGenerics>>,
) => {
const {
children,
client,
closeConnectionOnBackground = true,
enableOfflineSupport = false,
i18nInstance,
ImageComponent = Image,
isMessageAIGenerated,
LoadingIndicator = null,
style,
} = props;
const [channel, setChannel] = useState<Channel<StreamChatGenerics>>();
// Setup translators
const translators = useStreami18n(i18nInstance);
/**
* Setup connection event listeners
*/
const { connectionRecovering, isOnline } = useIsOnline<StreamChatGenerics>(
client,
closeConnectionOnBackground,
);
const [initialisedDatabaseConfig, setInitialisedDatabaseConfig] = useState<{
initialised: boolean;
userID?: string;
}>({
initialised: false,
userID: client.userID,
});
/**
* Setup muted user listener
* TODO: reimplement
*/
const mutedUsers = useMutedUsers<StreamChatGenerics>(client);
const debugRef = useDebugContext();
const isDebugModeEnabled = __DEV__ && debugRef && debugRef.current;
const userID = client.userID;
useEffect(() => {
if (client) {
const sdkName = (
NativeHandlers.SDK ? NativeHandlers.SDK.replace('stream-chat-', '') : 'react-native'
) as 'react-native' | 'expo';
client.sdkIdentifier = {
name: sdkName,
version,
};
client.deviceIdentifier = { os: `${Platform.OS} ${Platform.Version}` };
// This is to disable recovery related logic in js client, since we handle it in this SDK
client.recoverStateOnReconnect = false;
client.persistUserOnConnectionFailure = enableOfflineSupport;
}
if (isDebugModeEnabled) {
if (debugRef.current.setEventType) {
debugRef.current.setEventType('send');
}
if (debugRef.current.setSendEventParams) {
debugRef.current.setSendEventParams({
action: 'Client',
data: client.user,
});
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [client, enableOfflineSupport]);
const setActiveChannel = (newChannel?: Channel<StreamChatGenerics>) => setChannel(newChannel);
useEffect(() => {
if (!(userID && enableOfflineSupport)) {
return;
}
const initializeDatabase = () => {
// This acts as a lock for some very rare occurrences of concurrency
// issues we've encountered before with the QuickSqliteClient being
// uninitialized before it's being invoked.
setInitialisedDatabaseConfig({ initialised: false, userID });
SqliteClient.initializeDatabase()
.then(async () => {
setInitialisedDatabaseConfig({ initialised: true, userID });
await DBSyncManager.init(client as unknown as StreamChat);
})
.catch((error) => {
console.log('Error Initializing DB:', error);
});
};
initializeDatabase();
return () => {
if (userID && enableOfflineSupport) {
SqliteClient.closeDB();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userID, enableOfflineSupport]);
useEffect(() => {
if (!client) {
return;
}
client.threads.registerSubscriptions();
client.polls.registerSubscriptions();
return () => {
client.threads.unregisterSubscriptions();
client.polls.unregisterSubscriptions();
};
}, [client]);
// In case something went wrong, make sure to also unsubscribe the listener
// on unmount if it exists to prevent a memory leak.
useEffect(() => () => DBSyncManager.connectionChangedListener?.unsubscribe(), []);
const initialisedDatabase =
initialisedDatabaseConfig.initialised && userID === initialisedDatabaseConfig.userID;
const appSettings = useAppSettings(client, isOnline, enableOfflineSupport, initialisedDatabase);
const chatContext = useCreateChatContext({
appSettings,
channel,
client,
connectionRecovering,
enableOfflineSupport,
ImageComponent,
isMessageAIGenerated,
isOnline,
mutedUsers,
setActiveChannel,
});
useSyncDatabase({
client,
enableOfflineSupport,
initialisedDatabase,
});
if (userID && enableOfflineSupport && !initialisedDatabase) {
// if user id has been set and offline support is enabled, we need to wait for database to be initialised
return LoadingIndicator ? <LoadingIndicator /> : null;
}
return (
<ChatProvider<StreamChatGenerics> value={chatContext}>
<TranslationProvider
value={{ ...translators, userLanguage: client.user?.language || DEFAULT_USER_LANGUAGE }}
>
<ThemeProvider style={style}>
<ChannelsStateProvider<StreamChatGenerics>>{children}</ChannelsStateProvider>
</ThemeProvider>
</TranslationProvider>
</ChatProvider>
);
};
/**
* Chat - Wrapper component for Chat. The needs to be placed around any other chat components.
* This Chat component provides the ChatContext to all other components.
*
* The ChatContext provides the following props:
*
* - channel - currently active channel
* - client - client connection
* - connectionRecovering - whether or not websocket is reconnecting
* - isOnline - whether or not set user is active
* - setActiveChannel - function to set the currently active channel
*
* The Chat Component takes the following generics in order:
* - At (AttachmentType) - custom Attachment object extension
* - Ct (ChannelType) - custom Channel object extension
* - Co (CommandType) - custom Command string union extension
* - Ev (EventType) - custom Event object extension
* - Me (MessageType) - custom Message object extension
* - Re (ReactionType) - custom Reaction object extension
* - Us (UserType) - custom User object extension
*/
export const Chat = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>(
props: PropsWithChildren<ChatProps<StreamChatGenerics>>,
) => {
const { style } = useOverlayContext();
return <ChatWithContext {...{ style }} {...props} />;
};