-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.tsx
executable file
·388 lines (343 loc) · 15.8 KB
/
index.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
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
import type {MarkdownStyle} from '@expensify/react-native-live-markdown';
import {useIsFocused} from '@react-navigation/native';
import lodashDebounce from 'lodash/debounce';
import type {BaseSyntheticEvent, ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
// eslint-disable-next-line no-restricted-imports
import type {NativeSyntheticEvent, TextInput, TextInputKeyPressEventData, TextInputSelectionChangeEventData} from 'react-native';
import {DeviceEventEmitter, InteractionManager, StyleSheet} from 'react-native';
import type {ComposerProps} from '@components/Composer/types';
import type {AnimatedMarkdownTextInputRef} from '@components/RNMarkdownTextInput';
import RNMarkdownTextInput from '@components/RNMarkdownTextInput';
import useHtmlPaste from '@hooks/useHtmlPaste';
import useIsScrollBarVisible from '@hooks/useIsScrollBarVisible';
import useMarkdownStyle from '@hooks/useMarkdownStyle';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import addEncryptedAuthTokenToURL from '@libs/addEncryptedAuthTokenToURL';
import * as Browser from '@libs/Browser';
import * as EmojiUtils from '@libs/EmojiUtils';
import * as FileUtils from '@libs/fileDownload/FileUtils';
import isEnterWhileComposition from '@libs/KeyboardShortcut/isEnterWhileComposition';
import variables from '@styles/variables';
import CONST from '@src/CONST';
const excludeNoStyles: Array<keyof MarkdownStyle> = [];
const excludeReportMentionStyle: Array<keyof MarkdownStyle> = ['mentionReport'];
const imagePreviewAuthRequiredURLs = [CONST.EXPENSIFY_URL, CONST.STAGING_EXPENSIFY_URL];
// Enable Markdown parsing.
// On web we like to have the Text Input field always focused so the user can easily type a new chat
function Composer(
{
value,
defaultValue,
maxLines = -1,
onKeyPress = () => {},
style,
autoFocus = false,
shouldCalculateCaretPosition = false,
isDisabled = false,
onClear = () => {},
onPasteFile = () => {},
onSelectionChange = () => {},
checkComposerVisibility = () => false,
selection: selectionProp = {
start: 0,
end: 0,
},
isComposerFullSize = false,
shouldContainScroll = true,
isGroupPolicyReport = false,
showSoftInputOnFocus = true,
...props
}: ComposerProps,
ref: ForwardedRef<TextInput | HTMLInputElement>,
) {
const textContainsOnlyEmojis = useMemo(() => EmojiUtils.containsOnlyEmojis(value ?? ''), [value]);
const theme = useTheme();
const styles = useThemeStyles();
const markdownStyle = useMarkdownStyle(value, !isGroupPolicyReport ? excludeReportMentionStyle : excludeNoStyles);
const StyleUtils = useStyleUtils();
const textInput = useRef<AnimatedMarkdownTextInputRef | null>(null);
const [selection, setSelection] = useState<
| {
start: number;
end?: number;
positionX?: number;
positionY?: number;
}
| undefined
>({
start: selectionProp.start,
end: selectionProp.end,
});
const [hasMultipleLines, setHasMultipleLines] = useState(false);
const [isRendered, setIsRendered] = useState(false);
// On mobile safari, the cursor will move from right to left with inputMode set to none during report transition
// To avoid that we should hide the cursor util the transition is finished
const [shouldTransparentCursor, setShouldTransparentCursor] = useState(!showSoftInputOnFocus && Browser.isMobileSafari());
const isScrollBarVisible = useIsScrollBarVisible(textInput, value ?? '');
const [prevScroll, setPrevScroll] = useState<number | undefined>();
const [prevHeight, setPrevHeight] = useState<number | undefined>();
const isReportFlatListScrolling = useRef(false);
useEffect(() => {
if (!!selection && selectionProp.start === selection.start && selectionProp.end === selection.end) {
return;
}
setSelection(selectionProp);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [selectionProp]);
/**
* Adds the cursor position to the selection change event.
*/
const addCursorPositionToSelectionChange = (event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
const webEvent = event as BaseSyntheticEvent<TextInputSelectionChangeEventData>;
const sel = window.getSelection();
if (shouldCalculateCaretPosition && isRendered && sel) {
const range = sel.getRangeAt(0).cloneRange();
range.collapse(true);
const rect = range.getClientRects()[0] || range.startContainer.parentElement?.getClientRects()[0];
const containerRect = textInput.current?.getBoundingClientRect();
let x = 0;
let y = 0;
if (rect && containerRect) {
x = rect.left - containerRect.left;
y = rect.top - containerRect.top + (textInput?.current?.scrollTop ?? 0) - rect.height / 2;
}
const selectionValue = {
start: webEvent.nativeEvent.selection.start,
end: webEvent.nativeEvent.selection.end,
positionX: x - CONST.SPACE_CHARACTER_WIDTH,
positionY: y,
};
onSelectionChange({
...webEvent,
nativeEvent: {
...webEvent.nativeEvent,
selection: selectionValue,
},
});
setSelection(selectionValue);
} else {
onSelectionChange(webEvent);
setSelection(webEvent.nativeEvent.selection);
}
};
/**
* Check the paste event for an attachment, parse the data and call onPasteFile from props with the selected file,
* Otherwise, convert pasted HTML to Markdown and set it on the composer.
*/
const handlePaste = useCallback(
(event: ClipboardEvent) => {
const isVisible = checkComposerVisibility();
const isFocused = textInput.current?.isFocused();
const isContenteditableDivFocused = document.activeElement?.nodeName === 'DIV' && document.activeElement?.hasAttribute('contenteditable');
if (!(isVisible || isFocused)) {
return true;
}
if (textInput.current !== event.target && !(isContenteditableDivFocused && !event.clipboardData?.files.length)) {
const eventTarget = event.target as HTMLInputElement | HTMLTextAreaElement | null;
// To make sure the composer does not capture paste events from other inputs, we check where the event originated
// If it did originate in another input, we return early to prevent the composer from handling the paste
const isTargetInput = eventTarget?.nodeName === 'INPUT' || eventTarget?.nodeName === 'TEXTAREA' || eventTarget?.contentEditable === 'true';
if (isTargetInput || (!isFocused && isContenteditableDivFocused && event.clipboardData?.files.length)) {
return true;
}
textInput.current?.focus();
}
event.preventDefault();
const TEXT_HTML = 'text/html';
const clipboardDataHtml = event.clipboardData?.getData(TEXT_HTML) ?? '';
// If paste contains files, then trigger file management
if (event.clipboardData?.files.length && event.clipboardData.files.length > 0) {
// Prevent the default so we do not post the file name into the text box
onPasteFile(event.clipboardData.files[0]);
return true;
}
// If paste contains base64 image
if (clipboardDataHtml?.includes(CONST.IMAGE_BASE64_MATCH)) {
const domparser = new DOMParser();
const pastedHTML = clipboardDataHtml;
const embeddedImages = domparser.parseFromString(pastedHTML, TEXT_HTML)?.images;
if (embeddedImages.length > 0 && embeddedImages[0].src) {
const src = embeddedImages[0].src;
const file = FileUtils.base64ToFile(src, 'image.png');
onPasteFile(file);
return true;
}
}
// If paste contains image from Google Workspaces ex: Sheets, Docs, Slide, etc
if (clipboardDataHtml?.includes(CONST.GOOGLE_DOC_IMAGE_LINK_MATCH)) {
const domparser = new DOMParser();
const pastedHTML = clipboardDataHtml;
const embeddedImages = domparser.parseFromString(pastedHTML, TEXT_HTML).images;
if (embeddedImages.length > 0 && embeddedImages[0]?.src) {
const src = embeddedImages[0].src;
if (src.includes(CONST.GOOGLE_DOC_IMAGE_LINK_MATCH)) {
fetch(src)
.then((response) => response.blob())
.then((blob) => {
const file = new File([blob], 'image.jpg', {type: 'image/jpeg'});
onPasteFile(file);
});
return true;
}
}
}
return false;
},
[onPasteFile, checkComposerVisibility],
);
useEffect(() => {
if (!textInput.current) {
return;
}
const debouncedSetPrevScroll = lodashDebounce(() => {
if (!textInput.current) {
return;
}
setPrevScroll(textInput.current.scrollTop);
}, 100);
textInput.current.addEventListener('scroll', debouncedSetPrevScroll);
return () => {
textInput.current?.removeEventListener('scroll', debouncedSetPrevScroll);
};
}, []);
useEffect(() => {
const scrollingListener = DeviceEventEmitter.addListener(CONST.EVENTS.SCROLLING, (scrolling: boolean) => {
isReportFlatListScrolling.current = scrolling;
});
return () => scrollingListener.remove();
}, []);
useEffect(() => {
const handleWheel = (e: MouseEvent) => {
if (isReportFlatListScrolling.current) {
e.preventDefault();
return;
}
e.stopPropagation();
};
textInput.current?.addEventListener('wheel', handleWheel, {passive: false});
return () => {
textInput.current?.removeEventListener('wheel', handleWheel);
};
}, []);
useEffect(() => {
if (!textInput.current || prevScroll === undefined || prevHeight === undefined) {
return;
}
// eslint-disable-next-line react-compiler/react-compiler
textInput.current.scrollTop = prevScroll + prevHeight - textInput.current.clientHeight;
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [isComposerFullSize]);
const isActive = useIsFocused();
useHtmlPaste(textInput, handlePaste, isActive);
useEffect(() => {
setIsRendered(true);
}, []);
useEffect(() => {
if (!shouldTransparentCursor) {
return;
}
InteractionManager.runAfterInteractions(() => {
setShouldTransparentCursor(false);
});
}, [shouldTransparentCursor]);
const clear = useCallback(() => {
if (!textInput.current) {
return;
}
const currentText = textInput.current.value;
textInput.current.clear();
// We need to reset the selection to 0,0 manually after clearing the text input on web
const selectionEvent = {
nativeEvent: {
selection: {
start: 0,
end: 0,
},
},
} as NativeSyntheticEvent<TextInputSelectionChangeEventData>;
onSelectionChange(selectionEvent);
setSelection({start: 0, end: 0});
onClear(currentText);
}, [onClear, onSelectionChange]);
useImperativeHandle(
ref,
() => {
const textInputRef = textInput.current;
if (!textInputRef) {
throw new Error('textInputRef is not available. This should never happen and indicates a developer error.');
}
return {
...textInputRef,
// Overwrite clear with our custom implementation, which mimics how the native TextInput's clear method works
clear,
// We have to redefine these methods as they are inherited by prototype chain and are not accessible directly
blur: () => textInputRef.blur(),
focus: () => textInputRef.focus(),
get scrollTop() {
return textInputRef.scrollTop;
},
};
},
[clear],
);
const handleKeyPress = useCallback(
(e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
// Prevent onKeyPress from being triggered if the Enter key is pressed while text is being composed
if (!onKeyPress || isEnterWhileComposition(e as unknown as KeyboardEvent)) {
return;
}
onKeyPress(e);
},
[onKeyPress],
);
const scrollStyleMemo = useMemo(() => {
if (shouldContainScroll) {
return isScrollBarVisible ? [styles.overflowScroll, styles.overscrollBehaviorContain] : styles.overflowHidden;
}
return styles.overflowAuto;
}, [shouldContainScroll, styles.overflowAuto, styles.overflowScroll, styles.overscrollBehaviorContain, styles.overflowHidden, isScrollBarVisible]);
const inputStyleMemo = useMemo(
() => [
StyleSheet.flatten([style, {outline: 'none'}]),
StyleUtils.getComposeTextAreaPadding(isComposerFullSize),
Browser.isMobileSafari() || Browser.isSafari() ? styles.rtlTextRenderForSafari : {},
scrollStyleMemo,
StyleUtils.getComposerMaxHeightStyle(maxLines, isComposerFullSize),
isComposerFullSize ? {height: '100%', maxHeight: 'none'} : undefined,
textContainsOnlyEmojis && hasMultipleLines ? styles.onlyEmojisTextLineHeight : {},
],
[style, styles.rtlTextRenderForSafari, styles.onlyEmojisTextLineHeight, scrollStyleMemo, hasMultipleLines, StyleUtils, maxLines, isComposerFullSize, textContainsOnlyEmojis],
);
return (
<RNMarkdownTextInput
id={CONST.COMPOSER.NATIVE_ID}
autoComplete="off"
autoCorrect={!Browser.isMobileSafari()}
placeholderTextColor={theme.placeholderText}
ref={(el) => (textInput.current = el)}
selection={selection}
style={[inputStyleMemo, shouldTransparentCursor ? {caretColor: 'transparent'} : undefined]}
markdownStyle={markdownStyle}
value={value}
defaultValue={defaultValue}
autoFocus={autoFocus}
inputMode={showSoftInputOnFocus ? 'text' : 'none'}
/* eslint-disable-next-line react/jsx-props-no-spreading */
{...props}
onSelectionChange={addCursorPositionToSelectionChange}
onContentSizeChange={(e) => {
setPrevHeight(e.nativeEvent.contentSize.height);
setHasMultipleLines(e.nativeEvent.contentSize.height > variables.componentSizeLarge);
}}
disabled={isDisabled}
onKeyPress={handleKeyPress}
addAuthTokenToImageURLCallback={addEncryptedAuthTokenToURL}
imagePreviewAuthRequiredURLs={imagePreviewAuthRequiredURLs}
/>
);
}
Composer.displayName = 'Composer';
export default React.forwardRef(Composer);