-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathSendBox.tsx
252 lines (227 loc) · 8.87 KB
/
SendBox.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
import { hooks, type SendBoxFocusOptions } from 'botframework-webchat-component';
import cx from 'classnames';
import React, { memo, useCallback, useRef, useState, type FormEventHandler, type MouseEventHandler } from 'react';
import { useRefFrom } from 'use-ref-from';
import { SendIcon } from '../../icons';
import { useStyles, useVariantClassName } from '../../styles';
import testIds from '../../testIds';
import { DropZone } from '../dropZone';
import { SuggestedActions } from '../suggestedActions';
import { TelephoneKeypadSurrogate, useTelephoneKeypadShown, type DTMF } from '../telephoneKeypad';
import AddAttachmentButton from './AddAttachmentButton';
import Attachments from './Attachments';
import ErrorMessage from './ErrorMessage';
import useSubmitError from './private/useSubmitError';
import useTranscriptNavigation from './private/useTranscriptNavigation';
import useUniqueId from './private/useUniqueId';
import styles from './SendBox.module.css';
import TelephoneKeypadToolbarButton from './TelephoneKeypadToolbarButton';
import TextArea from './TextArea';
import { Toolbar, ToolbarButton, ToolbarSeparator } from './Toolbar';
const {
useFocus,
useLocalizer,
useMakeThumbnail,
useRegisterFocusSendBox,
useSendBoxAttachments,
useSendBoxValue,
useSendMessage,
useStyleOptions,
useUIState
} = hooks;
type Props = Readonly<{
className?: string | undefined;
isPrimary?: boolean | undefined;
placeholder?: string | undefined;
}>;
function SendBox(props: Props) {
const [{ hideTelephoneKeypadButton, hideUploadButton, maxMessageLength }] = useStyleOptions();
const [attachments, setAttachments] = useSendBoxAttachments();
const [globalMessage, setGlobalMessage] = useSendBoxValue();
const [localMessage, setLocalMessage] = useState('');
const [telephoneKeypadShown] = useTelephoneKeypadShown();
const [uiState] = useUIState();
const classNames = useStyles(styles);
const variantClassName = useVariantClassName(styles);
const errorMessageId = useUniqueId('sendbox__error-message-id');
const inputRef = useRef<HTMLTextAreaElement>(null);
const localize = useLocalizer();
const makeThumbnail = useMakeThumbnail();
const sendMessage = useSendMessage();
const setFocus = useFocus();
const message = props.isPrimary ? globalMessage : localMessage;
const setMessage = props.isPrimary ? setGlobalMessage : setLocalMessage;
const isBlueprint = uiState === 'blueprint';
const [errorMessage, commitLatestError] = useSubmitError({ message, attachments });
const isMessageLengthExceeded = !!maxMessageLength && message.length > maxMessageLength;
const shouldShowMessageLength =
!isBlueprint && !telephoneKeypadShown && maxMessageLength && isFinite(maxMessageLength);
const shouldShowTelephoneKeypad = !isBlueprint && telephoneKeypadShown;
useRegisterFocusSendBox(
useCallback(
({ noKeyboard, waitUntil }: SendBoxFocusOptions) => {
if (!inputRef.current) {
return;
}
if (noKeyboard) {
waitUntil(
(async () => {
const previousReadOnly = inputRef.current?.getAttribute('readonly');
inputRef.current?.setAttribute('readonly', 'true');
// TODO: [P2] We should update this logic to handle quickly-successive `focusCallback`.
// If a succeeding `focusCallback` is being called, the `setTimeout` should run immediately.
// Or the second `focusCallback` should not set `readonly` to `true`.
// eslint-disable-next-line no-restricted-globals
await new Promise(resolve => setTimeout(resolve, 0));
inputRef.current?.focus();
if (typeof previousReadOnly !== 'string') {
inputRef.current?.removeAttribute('readonly');
} else {
inputRef.current?.setAttribute('readonly', previousReadOnly);
}
})()
);
} else {
inputRef.current?.focus();
}
},
[inputRef]
)
);
const attachmentsRef = useRefFrom(attachments);
const messageRef = useRefFrom(message);
const handleSendBoxClick = useCallback<MouseEventHandler>(
event => {
if ('tabIndex' in event.target && typeof event.target.tabIndex === 'number' && event.target.tabIndex >= 0) {
return;
}
setFocus('sendBox');
},
[setFocus]
);
const handleMessageChange: React.FormEventHandler<HTMLTextAreaElement> = useCallback(
event => setMessage(event.currentTarget.value),
[setMessage]
);
const handleAddFiles = useCallback(
async (inputFiles: File[]) => {
const newAttachments = Object.freeze(
await Promise.all(
inputFiles.map(file =>
makeThumbnail(file).then(thumbnailURL =>
Object.freeze({
blob: file,
...(thumbnailURL && { thumbnailURL })
})
)
)
)
);
setAttachments(newAttachments);
// TODO: Currently in the UX, we have no way to remove attachments.
// Keep concatenating doesn't make sense in current UX.
// When end-user can remove attachment, we should enable the code again.
// setAttachments(attachments => attachments.concat(newAttachments));
},
[makeThumbnail, setAttachments]
);
const handleFormSubmit: FormEventHandler<HTMLFormElement> = useCallback(
event => {
event.preventDefault();
const error = commitLatestError();
if (error !== 'empty' && !isMessageLengthExceeded) {
sendMessage(messageRef.current, undefined, { attachments: attachmentsRef.current });
setMessage('');
setAttachments([]);
}
setFocus('sendBox');
},
[
commitLatestError,
isMessageLengthExceeded,
setFocus,
sendMessage,
setMessage,
messageRef,
attachmentsRef,
setAttachments
]
);
const handleTelephoneKeypadButtonClick = useCallback(
// TODO: We need more official way of sending DTMF.
(dtmf: DTMF) => sendMessage(`/DTMFKey ${dtmf}`),
[sendMessage]
);
const handleTranscriptNavigation = useTranscriptNavigation();
const aria = {
'aria-invalid': 'false' as const,
...(errorMessage && {
'aria-describedby': errorMessageId,
'aria-errormessage': errorMessageId,
'aria-invalid': 'true' as const
})
};
return (
<form
{...aria}
className={cx(classNames['sendbox'], variantClassName, props.className)}
data-testid={testIds.sendBoxContainer}
onSubmit={handleFormSubmit}
>
<SuggestedActions />
<div
className={cx(classNames['sendbox__sendbox'])}
onClickCapture={handleSendBoxClick}
onKeyDown={handleTranscriptNavigation}
>
<TextArea
aria-label={isMessageLengthExceeded ? localize('TEXT_INPUT_LENGTH_EXCEEDED_ALT') : localize('TEXT_INPUT_ALT')}
className={cx(classNames['sendbox__sendbox-text'], classNames['sendbox__text-area--in-grid'])}
data-testid={testIds.sendBoxTextBox}
hidden={shouldShowTelephoneKeypad}
onInput={handleMessageChange}
placeholder={props.placeholder ?? localize('TEXT_INPUT_PLACEHOLDER')}
ref={inputRef}
value={message}
/>
<TelephoneKeypadSurrogate
autoFocus={true}
className={classNames['sendbox__telephone-keypad--in-grid']}
isHorizontal={false}
onButtonClick={handleTelephoneKeypadButtonClick}
/>
<Attachments attachments={attachments} className={classNames['sendbox__attachment--in-grid']} />
<div className={cx(classNames['sendbox__sendbox-controls'], classNames['sendbox__sendbox-controls--in-grid'])}>
{shouldShowMessageLength && (
<div
className={cx(classNames['sendbox__text-counter'], {
[classNames['sendbox__text-counter--error']]: isMessageLengthExceeded
})}
>
{`${message.length}/${maxMessageLength}`}
</div>
)}
<Toolbar>
{!hideTelephoneKeypadButton && <TelephoneKeypadToolbarButton />}
{!hideUploadButton && <AddAttachmentButton onFilesAdded={handleAddFiles} />}
<ToolbarSeparator />
<ToolbarButton
aria-label={localize('TEXT_INPUT_SEND_BUTTON_ALT')}
data-testid={testIds.sendBoxSendButton}
disabled={isMessageLengthExceeded || shouldShowTelephoneKeypad}
type="submit"
>
<SendIcon />
</ToolbarButton>
</Toolbar>
</div>
<DropZone onFilesAdded={handleAddFiles} />
<ErrorMessage error={errorMessage} id={errorMessageId} />
</div>
</form>
);
}
const PrimarySendBox = memo((props: Exclude<Props, 'primary'>) => <SendBox {...props} isPrimary={true} />);
PrimarySendBox.displayName = 'PrimarySendBox';
export default memo(SendBox);
export { PrimarySendBox };