-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathApp.tsx
More file actions
442 lines (389 loc) Β· 13.6 KB
/
App.tsx
File metadata and controls
442 lines (389 loc) Β· 13.6 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
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
import { type CSSProperties, useCallback, useEffect, useMemo, useRef } from 'react';
import {
ChannelFilters,
ChannelOptions,
ChannelSort,
LocalMessage,
TextComposerMiddleware,
SearchController,
ChannelSearchSource,
UserSearchSource,
createActiveCommandGuardMiddleware,
createCommandInjectionMiddleware,
createCommandStringExtractionMiddleware,
createDraftCommandInjectionMiddleware,
} from 'stream-chat';
import {
Attachment,
type AttachmentProps,
Button,
Chat,
ChatView,
createIcon,
MessageReactions,
type NotificationListProps,
NotificationList,
Streami18n,
WithComponents,
defaultReactionOptions,
type ReactionOptions,
mapEmojiMartData,
useCreateChatClient,
useTranslationContext,
Search,
} from 'stream-chat-react';
import { createTextComposerEmojiMiddleware, EmojiPicker } from 'stream-chat-react/emojis';
import { init, SearchIndex } from 'emoji-mart';
import data from '@emoji-mart/data/sets/14/native.json';
import { humanId } from 'human-id';
import { appSettingsStore, useAppSettingsSelector } from './AppSettings';
import { DESKTOP_LAYOUT_BREAKPOINT } from './ChatLayout/constants.ts';
import { ChannelsPanels, ThreadsPanels } from './ChatLayout/Panels.tsx';
import { SidebarProvider, useSidebar } from './ChatLayout/SidebarContext.tsx';
import {
ChatViewSelectorWidthSync,
PanelLayoutStyleSync,
SidebarLayoutSync,
} from './ChatLayout/Resize.tsx';
import {
ChatStateSync,
getSelectedChannelIdFromUrl,
getSelectedChatViewFromUrl,
} from './ChatLayout/Sync.tsx';
import { LoadingScreen } from './LoadingScreen/LoadingScreen.tsx';
import { chatViewSelectorItemSet } from './Sidebar/ChatViewSelectorItemSet.tsx';
import {
CustomAttachmentActions,
CustomSystemMessage,
SegmentedReactionsList,
customReactionOptions,
customReactionOptionsUpvote,
getAttachmentActionsVariant,
getMessageUiComponent,
getMessageUiVariant,
getReactionsVariant,
getSystemMessageVariant,
} from './CustomMessageUi';
init({ data });
const parseUserIdFromToken = (token: string) => {
const [, payload] = token.split('.');
if (!payload) throw new Error('Token is missing');
return JSON.parse(atob(payload))?.user_id;
};
const apiKey = import.meta.env.VITE_STREAM_API_KEY;
const token =
new URLSearchParams(window.location.search).get('token') ||
import.meta.env.VITE_USER_TOKEN;
if (!apiKey) {
throw new Error('VITE_STREAM_API_KEY is not defined');
}
const options: ChannelOptions = {
presence: true,
state: true,
};
const sort: ChannelSort = { last_message_at: -1, updated_at: -1 };
// @ts-ignore
const isMessageAIGenerated = (message: LocalMessage) => !!message?.ai_generated;
const newReactionOptions: ReactionOptions = {
...defaultReactionOptions,
extended: mapEmojiMartData(data),
};
const useUser = () => {
const searchParams = useMemo(() => new URLSearchParams(window.location.search), []);
const userId = useMemo(() => {
return (
searchParams.get('user_id') ||
import.meta.env.VITE_USER_ID ||
localStorage.getItem('user_id') ||
humanId({ separator: '_', capitalize: false })
);
}, []);
const userImage = useMemo(() => searchParams.get('user_image') || undefined, []);
const userName = useMemo(() => searchParams.get('user_name') || undefined, []);
useEffect(() => {
const storedUserId = localStorage.getItem('user_id');
if (userId && storedUserId === userId) return;
localStorage.setItem('user_id', userId);
}, [userId]);
const tokenProvider = useCallback(() => {
return token && userId === parseUserIdFromToken(token)
? Promise.resolve(token)
: fetch(
`https://pronto.getstream.io/api/auth/create-token?environment=shared-chat-redesign&user_id=${userId}`,
)
.then((response) => response.json())
.then((data) => data.token as string);
}, [userId]);
return { tokenProvider, userId, userImage, userName };
};
const CustomMessageReactions = (props: React.ComponentProps<typeof MessageReactions>) => {
const { visualStyle, verticalPosition, flipHorizontalPosition } =
useAppSettingsSelector((state) => state.reactions);
return (
<MessageReactions
{...props}
flipHorizontalPosition={flipHorizontalPosition}
verticalPosition={verticalPosition}
visualStyle={visualStyle}
/>
);
};
const CustomChannelSearch = () => <Search exitSearchOnInputBlur />;
const EmojiPickerWithCustomOptions = (
props: React.ComponentProps<typeof EmojiPicker>,
) => {
const { mode } = useAppSettingsSelector((state) => state.theme);
return <EmojiPicker {...props} pickerProps={{ theme: mode }} />;
};
const ConfigurableNotificationList = (props: NotificationListProps) => {
const { verticalAlignment } = useAppSettingsSelector((state) => state.notifications);
return <NotificationList {...props} verticalAlignment={verticalAlignment} />;
};
const IconSidebar = createIcon(
'IconSidebar',
<path
d='M6.875 3.75V16.25M3.125 3.75H16.875C17.2202 3.75 17.5 4.02982 17.5 4.375V15.625C17.5 15.9702 17.2202 16.25 16.875 16.25H3.125C2.77982 16.25 2.5 15.9702 2.5 15.625V4.375C2.5 4.02982 2.77982 3.75 3.125 3.75Z'
fill='none'
stroke='currentColor'
strokeLinecap='round'
strokeLinejoin='round'
strokeWidth='1.5'
/>,
);
const SidebarToggle = () => {
const { closeSidebar, openSidebar, sidebarOpen } = useSidebar();
const { t } = useTranslationContext();
return (
<Button
appearance='ghost'
aria-label={sidebarOpen ? t('aria/Collapse sidebar') : t('aria/Expand sidebar')}
circular
className='str-chat__header-sidebar-toggle'
onClick={sidebarOpen ? closeSidebar : openSidebar}
size='md'
variant='secondary'
>
<IconSidebar />
</Button>
);
};
const language = new URLSearchParams(window.location.search).get('language');
const i18nInstance = language ? new Streami18n({ language: language as any }) : undefined;
const messageUiVariant = getMessageUiVariant();
const MessageUiOverride = messageUiVariant
? getMessageUiComponent(messageUiVariant)
: null;
const systemMessageVariant = getSystemMessageVariant();
const reactionsVariant = getReactionsVariant();
const attachmentActionsVariant = getAttachmentActionsVariant();
const CustomAttachmentWithActions = (props: AttachmentProps) => (
<Attachment {...props} AttachmentActions={CustomAttachmentActions} />
);
const App = () => {
const { tokenProvider, userId, userImage, userName } = useUser();
const chatView = useAppSettingsSelector((state) => state.chatView);
const { mode: themeMode } = useAppSettingsSelector((state) => state.theme);
const initialSearchParams = useMemo(
() => new URLSearchParams(window.location.search),
[],
);
const initialChannelId = useMemo(() => getSelectedChannelIdFromUrl(), []);
const initialChatView = useMemo(() => getSelectedChatViewFromUrl(), []);
const initialThreadId = useMemo(
() => initialSearchParams.get('thread'),
[initialSearchParams],
);
const initialPanelLayout = useMemo(
() => appSettingsStore.getLatestValue().panelLayout,
[],
);
const initialSidebarOpen = useMemo(() => {
if (typeof window === 'undefined') return !initialPanelLayout.leftPanel.collapsed;
const isMobile = window.innerWidth < DESKTOP_LAYOUT_BREAKPOINT;
if (!isMobile) return !initialPanelLayout.leftPanel.collapsed;
const hasSelectedChannel = Boolean(initialChannelId);
const hasSelectedThread = Boolean(initialThreadId);
const channelsView = initialChatView !== 'threads';
// Keep sidebar open on mobile when a channel is preselected via URL.
// It will auto-collapse later once the selected channel is actually resolved.
if (channelsView && hasSelectedChannel) {
return true;
}
if ((!channelsView && hasSelectedThread) || hasSelectedThread) {
return false;
}
return true;
}, [
initialChannelId,
initialChatView,
initialPanelLayout.leftPanel.collapsed,
initialThreadId,
]);
const appLayoutRef = useRef<HTMLDivElement | null>(null);
const chatClient = useCreateChatClient({
apiKey,
tokenOrProvider: tokenProvider,
userData: {
id: userId,
...(userImage && { image: userImage }),
...(userName && { name: userName }),
},
});
const searchController = useMemo(() => {
if (!chatClient) return undefined;
return new SearchController({
sources: [
new ChannelSearchSource(chatClient, undefined, {
initialFilterConfig: {
$or: {
enabled: true,
generate: () => ({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$or: [{ members: { $in: [chatClient.userID!] } }, { type: 'public' }],
members: undefined,
}),
},
},
}),
new UserSearchSource(chatClient),
],
});
}, [chatClient]);
const filters: ChannelFilters = useMemo(
() => ({
$or: [
{
members: { $in: [userId] },
},
{ type: 'public' },
],
}),
[userId],
);
useEffect(() => {
if (!chatClient) return;
chatClient.setMessageComposerSetupFunction(({ composer }) => {
// todo: find a way to register multiple setup functions so that the SDK can have own setup independent from the integrator setup
composer.compositionMiddlewareExecutor.insert({
middleware: [createCommandInjectionMiddleware(composer)],
position: { after: 'stream-io/message-composer-middleware/attachments' },
unique: true,
});
composer.draftCompositionMiddlewareExecutor.insert({
middleware: [createDraftCommandInjectionMiddleware(composer)],
position: { after: 'stream-io/message-composer-middleware/draft-attachments' },
});
composer.textComposer.middlewareExecutor.insert({
middleware: [createActiveCommandGuardMiddleware() as TextComposerMiddleware],
position: { before: 'stream-io/text-composer/commands-middleware' },
});
composer.textComposer.middlewareExecutor.insert({
middleware: [createCommandStringExtractionMiddleware() as TextComposerMiddleware],
position: { after: 'stream-io/text-composer/commands-middleware' },
});
composer.textComposer.middlewareExecutor.insert({
middleware: [
createTextComposerEmojiMiddleware(SearchIndex) as TextComposerMiddleware,
],
position: { before: 'stream-io/text-composer/mentions-middleware' },
unique: true,
});
composer.updateConfig({
linkPreviews: { enabled: true },
location: { enabled: true },
});
});
}, [chatClient]);
const chatTheme = themeMode === 'dark' ? 'str-chat__theme-dark' : 'messaging light';
const initialAppLayoutStyle = useMemo(
() =>
({
'--app-left-panel-width': `${initialPanelLayout.leftPanel.width}px`,
'--app-thread-panel-width': `${initialPanelLayout.threadPanel.width}px`,
}) as CSSProperties,
[initialPanelLayout.leftPanel.width, initialPanelLayout.threadPanel.width],
);
if (!chatClient) {
return (
<LoadingScreen
initialAppLayoutStyle={initialAppLayoutStyle}
initialChannelSelected={Boolean(initialChannelId)}
initialSidebarOpen={initialSidebarOpen}
/>
);
}
const messageUiOverrides: Record<string, unknown> = {};
if (MessageUiOverride) {
messageUiOverrides.Message = MessageUiOverride;
}
if (messageUiVariant === '8') {
messageUiOverrides.reactionOptions = customReactionOptions;
}
if (systemMessageVariant === 'custom') {
messageUiOverrides.MessageSystem = CustomSystemMessage;
}
if (reactionsVariant === 'custom-options') {
messageUiOverrides.reactionOptions = customReactionOptionsUpvote;
}
if (reactionsVariant === 'segmented') {
messageUiOverrides.ReactionsList = SegmentedReactionsList;
}
if (attachmentActionsVariant === 'custom') {
messageUiOverrides.Attachment = CustomAttachmentWithActions;
}
return (
<WithComponents
overrides={{
emojiSearchIndex: SearchIndex,
EmojiPicker: EmojiPickerWithCustomOptions,
NotificationList: ConfigurableNotificationList,
MessageReactions: CustomMessageReactions,
reactionOptions: newReactionOptions,
Search: CustomChannelSearch,
HeaderEndContent: SidebarToggle,
HeaderStartContent: SidebarToggle,
...messageUiOverrides,
}}
>
<SidebarProvider initialOpen={initialSidebarOpen}>
<Chat
searchController={searchController}
client={chatClient}
i18nInstance={i18nInstance}
isMessageAIGenerated={isMessageAIGenerated}
theme={chatTheme}
>
<div
className='app-chat-layout'
ref={appLayoutRef}
style={initialAppLayoutStyle}
data-variant={messageUiVariant ?? undefined}
>
<PanelLayoutStyleSync layoutRef={appLayoutRef} />
<ChatViewSelectorWidthSync
iconOnly={chatView.iconOnly}
layoutRef={appLayoutRef}
/>
<ChatView>
<ChatStateSync initialChatView={initialChatView} />
<SidebarLayoutSync />
<ChannelsPanels
filters={filters}
iconOnly={chatView.iconOnly}
initialChannelId={initialChannelId ?? undefined}
itemSet={chatViewSelectorItemSet}
options={options}
sort={sort}
/>
<ThreadsPanels
iconOnly={chatView.iconOnly}
itemSet={chatViewSelectorItemSet}
/>
</ChatView>
</div>
</Chat>
</SidebarProvider>
</WithComponents>
);
};
export default App;