-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathTextBox.tsx
More file actions
280 lines (237 loc) · 9.28 KB
/
TextBox.tsx
File metadata and controls
280 lines (237 loc) · 9.28 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
import { hooks } from 'botframework-webchat-api';
import { usePonyfill } from 'botframework-webchat-api/hook';
import classNames from 'classnames';
import React, { useCallback, useMemo, useRef } from 'react';
import AccessibleInputText from '../Utils/AccessibleInputText';
import navigableEvent from '../Utils/TypeFocusSink/navigableEvent';
import { useStyleToEmotionObject } from '../hooks/internal/styleToEmotionObject';
import { useRegisterFocusSendBox, type SendBoxFocusOptions } from '../hooks/sendBoxFocus';
import useScrollDown from '../hooks/useScrollDown';
import useScrollUp from '../hooks/useScrollUp';
import useStyleSet from '../hooks/useStyleSet';
import useSubmit from '../providers/internal/SendBox/useSubmit';
import withEmoji from '../withEmoji/withEmoji';
import AutoResizeTextArea from './AutoResizeTextArea';
import type { MutableRefObject } from 'react';
import testIds from '../testIds';
const { useLocalizer, useSendBoxValue, useStopDictate, useStyleOptions, useUIState } = hooks;
const DEFAULT_INPUT_MODE = 'text';
const ROOT_STYLE = {
'&.webchat__send-box-text-box': {
display: 'flex',
'& .webchat__send-box-text-box__input, & .webchat__send-box-text-box__text-area': {
flex: 1
}
}
};
/**
* Submits the text box and optionally set the focus after send.
*/
type SubmitTextBoxFunction = {
/**
* Submits the text box, without setting the focus after send.
*
* @deprecated Instead of passing `false`, you should leave the `setFocus` argument `undefined`.
*/
(setFocus: false): void;
/**
* Submits the text box and optionally set the focus after send.
*/
(setFocus?: 'sendBox' | 'sendBoxWithoutKeyboard'): void;
};
function useTextBoxSubmit(): SubmitTextBoxFunction {
const submit = useSubmit();
return useCallback<SubmitTextBoxFunction>(
(setFocus?: false | 'sendBox' | 'sendBoxWithoutKeyboard') => submit({ setFocus: setFocus || undefined }),
[submit]
);
}
function useTextBoxValue(): [string, (textBoxValue: string) => void] {
const [value, setValue] = useSendBoxValue();
const stopDictate = useStopDictate();
const setter = useCallback<(nextValue: string) => void>(
nextValue => {
if (typeof nextValue !== 'string') {
throw new Error('botframework-webchat: First argument passed to useTextBoxValue() must be a string.');
}
setValue(nextValue);
stopDictate();
},
[setValue, stopDictate]
);
return [value, setter];
}
const PREVENT_DEFAULT_HANDLER = event => event.preventDefault();
const SingleLineTextBox = withEmoji(AccessibleInputText);
const MultiLineTextBox = withEmoji(AutoResizeTextArea);
const TextBox = ({ className = '' }: Readonly<{ className?: string | undefined }>) => {
const [value, setValue] = useSendBoxValue();
const [{ sendBoxTextBox: sendBoxTextBoxStyleSet }] = useStyleSet();
const [{ emojiSet, sendBoxTextWrap }] = useStyleOptions();
const [uiState] = useUIState();
const inputElementRef: MutableRefObject<HTMLInputElement & HTMLTextAreaElement> = useRef();
const localize = useLocalizer();
const rootClassName = useStyleToEmotionObject()(ROOT_STYLE) + '';
const scrollDown = useScrollDown();
const scrollUp = useScrollUp();
const submitTextBox = useTextBoxSubmit();
const disabled = uiState === 'disabled';
const sendBoxString = localize('TEXT_INPUT_ALT');
const typeYourMessageString = localize('TEXT_INPUT_PLACEHOLDER');
const handleKeyPress = useCallback(
event => {
const { key, shiftKey } = event;
if (key === 'Enter' && !shiftKey) {
event.preventDefault();
// If text box is submitted, focus on the send box
submitTextBox('sendBox');
}
},
[submitTextBox]
);
const handleSubmit = useCallback(
event => {
event.preventDefault();
// Consider clearing the send box only after we received POST_ACTIVITY_PENDING
// E.g. if the connection is bad, sending the message essentially do nothing but just clearing the send box
submitTextBox();
},
[submitTextBox]
);
const handleKeyDownCapture = useCallback(
event => {
const { ctrlKey, metaKey, shiftKey } = event;
if (ctrlKey || metaKey || shiftKey) {
return;
}
// Navigable event means the end-user is focusing on an inputtable element, but it is okay to capture the arrow keys.
if (navigableEvent(event)) {
let handled = true;
switch (event.key) {
case 'End':
scrollDown({ displacement: Infinity });
break;
case 'Home':
scrollUp({ displacement: Infinity });
break;
case 'PageDown':
scrollDown();
break;
case 'PageUp':
scrollUp();
break;
default:
handled = false;
break;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
}
},
[scrollDown, scrollUp]
);
const [{ requestAnimationFrame, requestIdleCallback }] = usePonyfill();
const requestIdleCallbackWithPonyfill = useMemo(
() => requestIdleCallback ?? ((callback: () => void) => requestAnimationFrame(callback)),
[requestAnimationFrame, requestIdleCallback]
);
const focusCallback = useCallback(
({ noKeyboard, waitUntil }: SendBoxFocusOptions) => {
waitUntil(
(async () => {
const { current } = inputElementRef;
if (current) {
// Setting `inputMode` to `none` temporarily to suppress soft keyboard in iOS.
// We will revert the change once the end-user tap on the send box.
// This code path is only triggered when the user press "send" button to send the message, instead of pressing ENTER key.
if (noKeyboard) {
if (current.getAttribute('inputmode') !== 'none') {
// Collapse the virtual keybaord if it was expanded.
current.setAttribute('inputmode', 'none');
// iOS 26.3 quirks: `HTMLElement.focus()` does not pickup `inputmode="none"` changes immediately.
// We need to wait for next frame before calling `focus()`.
// This is a regression from iOS 26.2.
await new Promise<void>(resolve => requestIdleCallbackWithPonyfill(resolve));
}
} else if (current.hasAttribute('inputmode')) {
// Expanding the virtual keyboard if it was collapsed.
// However, we are not pausing here to workaround iOS 26.3 quirks.
// If we pause here, it will not able to handle this scenario: focus on an activity on the transcript, press A, the letter A should be inputted into the send box.
// In other words, if we pause here, the event will be send to the activity/transcript, instead of the newly focused send box.
// This is related to BasicTranscript.handleTranscriptKeyDownCapture().
current.removeAttribute('inputmode');
}
current?.focus();
}
})()
);
},
[inputElementRef, requestIdleCallbackWithPonyfill]
);
useRegisterFocusSendBox(focusCallback);
const handleClick = useCallback(
({ currentTarget }) => currentTarget.setAttribute('inputmode', DEFAULT_INPUT_MODE),
[]
);
const emojiMap = useMemo(() => new Map<string, string>(Object.entries(emojiSet)), [emojiSet]);
return (
<form
aria-disabled={disabled}
className={classNames(
'webchat__send-box-text-box',
rootClassName,
sendBoxTextBoxStyleSet + '',
(className || '') + ''
)}
onSubmit={disabled ? PREVENT_DEFAULT_HANDLER : handleSubmit}
>
{!sendBoxTextWrap ? (
<SingleLineTextBox
aria-label={sendBoxString}
className="webchat__send-box-text-box__input"
data-id="webchat-sendbox-input"
data-testid={testIds.sendBoxTextBox}
disabled={disabled}
emojiMap={emojiMap}
enterKeyHint="send"
inputMode={DEFAULT_INPUT_MODE}
onChange={setValue}
onClick={handleClick}
onKeyDownCapture={disabled ? undefined : handleKeyDownCapture}
onKeyPress={disabled ? undefined : handleKeyPress}
placeholder={typeYourMessageString}
readOnly={disabled}
ref={inputElementRef}
type="text"
value={value}
/>
) : (
<MultiLineTextBox
aria-label={sendBoxString}
className="webchat__send-box-text-box__text-area"
data-id="webchat-sendbox-input"
data-testid={testIds.sendBoxTextBox}
disabled={disabled}
emojiMap={emojiMap}
enterKeyHint="send"
inputMode={DEFAULT_INPUT_MODE}
onChange={setValue}
onClick={handleClick}
onKeyDownCapture={disabled ? undefined : handleKeyDownCapture}
onKeyPress={disabled ? undefined : handleKeyPress}
placeholder={typeYourMessageString}
readOnly={disabled}
ref={inputElementRef}
rows={1}
textAreaClassName="webchat__send-box-text-box__html-text-area"
value={value}
/>
)}
{disabled && <div className="webchat__send-box-text-box__glass" />}
</form>
);
};
export default TextBox;
export { useTextBoxSubmit, useTextBoxValue };