-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathApp.tsx
More file actions
543 lines (488 loc) Β· 16.7 KB
/
Copy pathApp.tsx
File metadata and controls
543 lines (488 loc) Β· 16.7 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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import {
type CSSProperties,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import type {
ChannelFilters,
ChannelOptions,
ChannelSort,
LocalMessage,
TextComposerMiddleware,
} from 'stream-chat';
import {
ChannelSearchSource,
createActiveCommandGuardMiddleware,
createCommandInjectionMiddleware,
createCommandStringExtractionMiddleware,
createDraftCommandInjectionMiddleware,
SearchController,
UserSearchSource,
} from 'stream-chat';
import {
Attachment,
type AttachmentProps,
Chat,
ChatView,
defaultReactionOptions,
DialogManagerProvider,
MessageReactions,
NotificationList,
type NotificationListProps,
type ReactionOptions,
Search,
Streami18n,
useCreateChatClient,
WithComponents,
} from 'stream-chat-react';
import {
createTextComposerEmojiMiddleware,
EmojiPicker,
loadDefaultExtendedReactionOptions,
StreamEmojiPicker,
} from 'stream-chat-react/emojis';
import { humanId } from 'human-id';
import { appSettingsStore, useAppSettingsSelector } from './AppSettings';
import { DESKTOP_LAYOUT_BREAKPOINT } from './ChatLayout/constants.ts';
import { ChatSkipNavigation } from './AccessibilityNavigation/ChatSkipNavigation.tsx';
import { ChannelsPanels, ThreadsPanels } from './ChatLayout/Panels.tsx';
import { SidebarProvider } 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 { SystemNotification } from './SystemNotification/SystemNotification.tsx';
import { chatViewSelectorItemSet } from './Sidebar/ChatViewSelectorItemSet.tsx';
import {
CustomAttachmentActions,
customReactionOptions,
customReactionOptionsUpvote,
CustomSystemMessage,
getAttachmentActionsVariant,
getMessageUiComponent,
getMessageUiVariant,
getReactionsVariant,
getSystemMessageVariant,
SegmentedReactionsList,
} from './CustomMessageUi';
import { ConfigurableMessageActions } from './CustomMessageActions';
import { SidebarToggle } from './Sidebar/SidebarToggle.tsx';
const PUBLIC_VITE_EXAMPLE_API_KEY = 'xzwhhgtazy6h';
const parseUserIdFromToken = (token: string): string | undefined => {
try {
const [, payload] = token.split('.');
if (!payload) return undefined;
return JSON.parse(atob(payload))?.user_id;
} catch {
return undefined;
}
};
const apiKey =
new URLSearchParams(window.location.search).get('api_key') ||
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 sort: ChannelSort = { last_message_at: -1, updated_at: -1 };
// @ts-expect-error ai_generated isn't on LocalMessage's public type yet
const isMessageAIGenerated = (message: LocalMessage) => !!message?.ai_generated;
const useUser = () => {
const searchParams = useMemo(() => new URLSearchParams(window.location.search), []);
const userId = useMemo(
() =>
searchParams.get('user_id') ||
(token ? parseUserIdFromToken(token) : undefined) ||
import.meta.env.VITE_USER_ID ||
localStorage.getItem('user_id') ||
humanId({ separator: '_', capitalize: false }),
[searchParams],
);
const userImage = useMemo(
() => searchParams.get('user_image') || undefined,
[searchParams],
);
const userName = useMemo(
() => searchParams.get('user_name') || undefined,
[searchParams],
);
useEffect(() => {
const storedUserId = localStorage.getItem('user_id');
if (userId && storedUserId === userId) return;
localStorage.setItem('user_id', userId);
}, [userId]);
const environment =
apiKey === PUBLIC_VITE_EXAMPLE_API_KEY
? 'public-shared-chat-redesign'
: 'shared-chat-redesign';
const tokenProvider = useCallback(() => {
if (token && userId === parseUserIdFromToken(token)) {
return Promise.resolve(token);
}
const url = new URL('https://pronto.getstream.io/api/auth/create-token');
url.searchParams.set('environment', environment);
url.searchParams.set('user_id', userId);
return fetch(url.toString())
.then((response) => response.json())
.then((data) => data.token as string);
}, [environment, userId]);
return { tokenProvider, userId, userImage, userName };
};
const CustomMessageReactions = (props: React.ComponentProps<typeof MessageReactions>) => {
const { flipHorizontalPosition, verticalPosition, visualStyle } =
useAppSettingsSelector((state) => state.reactions);
return (
<MessageReactions
{...props}
flipHorizontalPosition={flipHorizontalPosition}
verticalPosition={verticalPosition}
visualStyle={visualStyle}
/>
);
};
const CustomChannelSearch = () => <Search exitSearchOnInputBlur />;
// Demonstrates integrator-owned persistence of the picker's skin tone and
// frequently-used emoji via localStorage. The SDK itself never touches storage β
// it exposes these as controlled props so apps own where the state lives.
const EMOJI_SKIN_TONE_KEY = 'vite-example/emoji-skin-tone';
const EMOJI_FREQUENTLY_USED_KEY = 'vite-example/emoji-frequently-used';
const readStored = <T,>(key: string, fallback: T): T => {
try {
const raw = localStorage.getItem(key);
return raw ? (JSON.parse(raw) as T) : fallback;
} catch {
return fallback;
}
};
const writeStored = (key: string, value: unknown) => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// ignore storage failures (e.g. private browsing)
}
};
const EmojiPickerWithCustomOptions = (
props: React.ComponentProps<typeof StreamEmojiPicker>,
) => {
const { mode } = useAppSettingsSelector((state) => state.theme);
const { engine, ...pickerOptions } = useAppSettingsSelector(
(state) => state.emojiPicker,
);
const [skinTone, setSkinTone] = useState(() => readStored(EMOJI_SKIN_TONE_KEY, 0));
const [frequentlyUsedEmoji, setFrequentlyUsedEmoji] = useState(() =>
readStored<string[]>(EMOJI_FREQUENTLY_USED_KEY, []),
);
// The deprecated emoji-mart picker self-manages skin tone + frequently-used and
// accepts the same emoji-mart-compatible option names, so it only needs pickerProps.
if (engine === 'emoji-mart') {
return <EmojiPicker pickerProps={{ ...pickerOptions, theme: mode }} />;
}
return (
<StreamEmojiPicker
{...props}
frequentlyUsedEmoji={frequentlyUsedEmoji}
onFrequentlyUsedChange={(ids) => {
setFrequentlyUsedEmoji(ids);
writeStored(EMOJI_FREQUENTLY_USED_KEY, ids);
}}
onSkinToneChange={(tone) => {
setSkinTone(tone);
writeStored(EMOJI_SKIN_TONE_KEY, tone);
}}
pickerProps={{
...props.pickerProps,
...pickerOptions,
theme: mode,
}}
skinTone={skinTone}
/>
);
};
const ConfigurableNotificationList = (props: NotificationListProps) => {
const { verticalAlignment } = useAppSettingsSelector((state) => state.notifications);
return <NotificationList {...props} verticalAlignment={verticalAlignment} />;
};
const language = new URLSearchParams(window.location.search).get('language');
const i18nInstance = language
? new Streami18n({
language: language as NonNullable<
ConstructorParameters<typeof Streami18n>[0]
>['language'],
})
: undefined;
const messageUiVariant = getMessageUiVariant();
const MessageUiOverride = messageUiVariant
? getMessageUiComponent(messageUiVariant)
: null;
const systemMessageVariant = getSystemMessageVariant();
const reactionsVariant = getReactionsVariant();
const attachmentActionsVariant = getAttachmentActionsVariant();
const globalDialogManager = 'globalDialogManager';
const CustomAttachmentWithActions = (props: AttachmentProps) => (
<Attachment {...props} AttachmentActions={CustomAttachmentActions} />
);
const App = () => {
const { tokenProvider, userId, userImage, userName } = useUser();
// Restore "react with any emoji": lazily load the full emoji set and expose it as the
// extended reaction options (the reaction selector's "+" list). The dataset loads on
// demand via the same code-split chunk the picker uses; until it resolves only the
// quick reactions show.
const [reactionOptions, setReactionOptions] =
useState<ReactionOptions>(defaultReactionOptions);
useEffect(() => {
let active = true;
loadDefaultExtendedReactionOptions().then((extended) => {
if (active) setReactionOptions({ ...defaultReactionOptions, extended });
});
return () => {
active = false;
};
}, []);
const chatView = useAppSettingsSelector((state) => state.chatView);
const { mode: themeMode } = useAppSettingsSelector((state) => state.theme);
const initialSearchParams = useMemo(
() => new URLSearchParams(window.location.search),
[],
);
const options = useMemo<ChannelOptions>(
() => ({
// filter_values: {
// user_id: userId,
// },
// predefined_filter: 'livestreams_channels',
presence: true,
state: true,
limit: 10,
}),
[],
);
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: () => ({
$or: [{ members: { $in: [chatClient.userID!] } }, { type: 'public' }],
members: undefined,
}),
},
},
}),
new UserSearchSource(chatClient),
],
});
}, [chatClient]);
const filters: ChannelFilters = useMemo(
() => ({
$or: [
{
members: { $in: [userId] },
},
{ type: 'public' },
// public example channels
{
$and: [
{
cid: {
$in: ['random', 'general', 'music', 'jokes'].map(
(channelId) => `messaging:${channelId}`,
),
},
},
{
members: { $in: [userId] },
},
],
},
],
}),
[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() 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={{
EmojiPicker: EmojiPickerWithCustomOptions,
NotificationList: ConfigurableNotificationList,
MessageReactions: CustomMessageReactions,
reactionOptions,
Search: CustomChannelSearch,
HeaderEndContent: SidebarToggle,
HeaderStartContent: SidebarToggle,
MessageActions: ConfigurableMessageActions,
...messageUiOverrides,
}}
>
<SidebarProvider initialOpen={initialSidebarOpen}>
<Chat
client={chatClient}
i18nInstance={i18nInstance}
isMessageAIGenerated={isMessageAIGenerated}
searchController={searchController}
theme={chatTheme}
>
<ChatSkipNavigation />
<div
className='app-chat-layout'
data-variant={messageUiVariant ?? undefined}
ref={appLayoutRef}
style={initialAppLayoutStyle}
>
<SystemNotification />
<div className='app-chat-layout__body'>
<PanelLayoutStyleSync layoutRef={appLayoutRef} />
<ChatViewSelectorWidthSync
iconOnly={chatView.iconOnly}
layoutRef={appLayoutRef}
/>
<ChatView>
<DialogManagerProvider id={globalDialogManager}>
<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}
/>
</DialogManagerProvider>
</ChatView>
</div>
</div>
</Chat>
</SidebarProvider>
</WithComponents>
);
};
export default App;