-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathAttachmentSelector.tsx
More file actions
261 lines (238 loc) Β· 8.71 KB
/
AttachmentSelector.tsx
File metadata and controls
261 lines (238 loc) Β· 8.71 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
import React, { ElementRef, useCallback, useEffect, useRef, useState } from 'react';
import { UploadIcon as DefaultUploadIcon } from './icons';
import { CHANNEL_CONTAINER_ID } from '../Channel/constants';
import { DialogAnchor, useDialog, useDialogIsOpen } from '../Dialog';
import { DialogMenuButton } from '../Dialog/DialogMenu';
import { Modal } from '../Modal';
import { PollCreationDialog as DefaultPollCreationDialog } from '../Poll';
import { Portal } from '../Portal/Portal';
import { UploadFileInput } from '../ReactFileUtilities';
import {
useChannelStateContext,
useComponentContext,
useMessageInputContext,
useTranslationContext,
} from '../../context';
import {
AttachmentSelectorContextProvider,
useAttachmentSelectorContext,
} from '../../context/AttachmentSelectorContext';
import { useStableId } from '../UtilityComponents/useStableId';
import type { DefaultStreamChatGenerics } from '../../types';
export const SimpleAttachmentSelector = () => {
const {
AttachmentSelectorInitiationButtonContents,
FileUploadIcon = DefaultUploadIcon,
} = useComponentContext();
const inputRef = useRef<HTMLInputElement | null>(null);
const [labelElement, setLabelElement] = useState<HTMLLabelElement | null>(null);
const id = useStableId();
useEffect(() => {
if (!labelElement) return;
const handleKeyUp = (event: KeyboardEvent) => {
if (![' ', 'Enter'].includes(event.key) || !inputRef.current) return;
event.preventDefault();
inputRef.current.click();
};
labelElement.addEventListener('keyup', handleKeyUp);
return () => {
labelElement.removeEventListener('keyup', handleKeyUp);
};
}, [labelElement]);
return (
<div className='str-chat__file-input-container' data-testid='file-upload-button'>
<UploadFileInput id={id} ref={inputRef} />
<label
className='str-chat__file-input-label'
htmlFor={id}
ref={setLabelElement}
tabIndex={0}
>
{AttachmentSelectorInitiationButtonContents ? (
<AttachmentSelectorInitiationButtonContents />
) : (
<FileUploadIcon />
)}
</label>
</div>
);
};
const AttachmentSelectorMenuInitButtonIcon = () => {
const { AttachmentSelectorInitiationButtonContents, FileUploadIcon } =
useComponentContext('SimpleAttachmentSelector');
if (AttachmentSelectorInitiationButtonContents) {
return <AttachmentSelectorInitiationButtonContents />;
}
if (FileUploadIcon) {
return <FileUploadIcon />;
}
return <div className='str-chat__attachment-selector__menu-button__icon' />;
};
export type AttachmentSelectorModalContentProps = {
close: () => void;
};
export type AttachmentSelectorActionProps = {
closeMenu: () => void;
openModalForAction: (actionType: AttachmentSelectorAction['type']) => void;
};
export type AttachmentSelectorAction = {
ActionButton: React.ComponentType<AttachmentSelectorActionProps>;
type: 'uploadFile' | 'createPoll' | (string & {});
ModalContent?: React.ComponentType<AttachmentSelectorModalContentProps>;
};
export const DefaultAttachmentSelectorComponents = {
File({ closeMenu }: AttachmentSelectorActionProps) {
const { t } = useTranslationContext();
const { fileInput } = useAttachmentSelectorContext();
return (
<DialogMenuButton
className='str-chat__attachment-selector-actions-menu__button str-chat__attachment-selector-actions-menu__upload-file-button'
onClick={() => {
if (fileInput) fileInput.click();
closeMenu();
}}
>
{t<string>('File')}
</DialogMenuButton>
);
},
Poll({ closeMenu, openModalForAction }: AttachmentSelectorActionProps) {
const { t } = useTranslationContext();
return (
<DialogMenuButton
className='str-chat__attachment-selector-actions-menu__button str-chat__attachment-selector-actions-menu__create-poll-button'
onClick={() => {
openModalForAction('createPoll');
closeMenu();
}}
>
{t<string>('Poll')}
</DialogMenuButton>
);
},
};
export const defaultAttachmentSelectorActionSet: AttachmentSelectorAction[] = [
{ ActionButton: DefaultAttachmentSelectorComponents.File, type: 'uploadFile' },
{
ActionButton: DefaultAttachmentSelectorComponents.Poll,
type: 'createPoll',
},
];
export type AttachmentSelectorProps = {
attachmentSelectorActionSet?: AttachmentSelectorAction[];
getModalPortalDestination?: () => HTMLElement | null;
};
const useAttachmentSelectorActionsFiltered = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>(
original: AttachmentSelectorAction[],
) => {
const { PollCreationDialog = DefaultPollCreationDialog } = useComponentContext();
const { channelCapabilities, channelConfig } =
useChannelStateContext<StreamChatGenerics>();
const { isThreadInput } = useMessageInputContext();
return original
.filter((action) => {
if (action.type === 'uploadFile' && !channelCapabilities['upload-file'])
return false;
if (
action.type === 'createPoll' &&
(!channelConfig?.polls || isThreadInput || !channelCapabilities['send-poll'])
)
return false;
return true;
})
.map((action) => {
if (action.type === 'createPoll' && !action.ModalContent) {
return { ...action, ModalContent: PollCreationDialog };
}
return action;
});
};
export const AttachmentSelector = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>({
attachmentSelectorActionSet = defaultAttachmentSelectorActionSet,
getModalPortalDestination,
}: AttachmentSelectorProps) => {
const { t } = useTranslationContext();
const { channelCapabilities } = useChannelStateContext<StreamChatGenerics>();
const { isThreadInput } = useMessageInputContext();
const actions = useAttachmentSelectorActionsFiltered<StreamChatGenerics>(
attachmentSelectorActionSet,
);
const menuDialogId = `attachment-actions-menu${isThreadInput ? '-thread' : ''}`;
const menuDialog = useDialog({ id: menuDialogId });
const menuDialogIsOpen = useDialogIsOpen(menuDialogId);
const [modalContentAction, setModalContentActionAction] =
useState<AttachmentSelectorAction>();
const openModal = useCallback(
(actionType: AttachmentSelectorAction['type']) => {
const action = actions.find((a) => a.type === actionType);
if (!action?.ModalContent) return;
setModalContentActionAction(action);
},
[actions],
);
const closeModal = useCallback(() => setModalContentActionAction(undefined), []);
const [fileInput, setFileInput] = useState<HTMLInputElement | null>(null);
const menuButtonRef = useRef<ElementRef<'button'>>(null);
const getDefaultPortalDestination = useCallback(
() => document.getElementById(CHANNEL_CONTAINER_ID),
[],
);
if (actions.length === 0) return null;
if (actions.length === 1 && actions[0].type === 'uploadFile')
return <SimpleAttachmentSelector />;
const ModalContent = modalContentAction?.ModalContent;
const modalIsOpen = !!ModalContent;
return (
<AttachmentSelectorContextProvider value={{ fileInput }}>
<div className='str-chat__attachment-selector'>
{channelCapabilities['upload-file'] && <UploadFileInput ref={setFileInput} />}
<button
aria-expanded={menuDialogIsOpen}
aria-haspopup='true'
aria-label={t('aria/Open Attachment Selector')}
className='str-chat__attachment-selector__menu-button'
data-testid='invoke-attachment-selector-button'
onClick={() => menuDialog?.toggle()}
ref={menuButtonRef}
>
<AttachmentSelectorMenuInitButtonIcon />
</button>
<DialogAnchor
id={menuDialogId}
placement='top-start'
referenceElement={menuButtonRef.current}
trapFocus
>
<div
className='str-chat__attachment-selector-actions-menu str-chat__dialog-menu'
data-testid='attachment-selector-actions-menu'
>
{actions.map(({ ActionButton, type }) => (
<ActionButton
closeMenu={menuDialog.close}
key={`attachment-selector-item-${type}`}
openModalForAction={openModal}
/>
))}
</div>
</DialogAnchor>
<Portal
getPortalDestination={getModalPortalDestination ?? getDefaultPortalDestination}
isOpen={modalIsOpen}
>
<Modal
className='str-chat__create-poll-modal'
onClose={closeModal}
open={modalIsOpen}
>
{ModalContent && <ModalContent close={closeModal} />}
</Modal>
</Portal>
</div>
</AttachmentSelectorContextProvider>
);
};