-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ComposerWithSuggestions.tsx
856 lines (737 loc) · 33.4 KB
/
ComposerWithSuggestions.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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
import {useIsFocused, useNavigation} from '@react-navigation/native';
import lodashDebounce from 'lodash/debounce';
import type {ForwardedRef, MutableRefObject, RefAttributes, RefObject} from 'react';
import React, {forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import type {
LayoutChangeEvent,
MeasureInWindowOnSuccessCallback,
NativeSyntheticEvent,
TextInput,
TextInputFocusEventData,
TextInputKeyPressEventData,
TextInputScrollEventData,
} from 'react-native';
import {DeviceEventEmitter, findNodeHandle, InteractionManager, NativeModules, View} from 'react-native';
import {useFocusedInputHandler} from 'react-native-keyboard-controller';
import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import {useSharedValue} from 'react-native-reanimated';
import type {useAnimatedRef} from 'react-native-reanimated';
import type {Emoji} from '@assets/emojis/types';
import type {FileObject} from '@components/AttachmentModal';
import type {MeasureParentContainerAndCursorCallback} from '@components/AutoCompleteSuggestions/types';
import Composer from '@components/Composer';
import type {CustomSelectionChangeEvent, TextSelection} from '@components/Composer/types';
import useKeyboardState from '@hooks/useKeyboardState';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as Browser from '@libs/Browser';
import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus';
import * as ComposerUtils from '@libs/ComposerUtils';
import convertToLTRForComposer from '@libs/convertToLTRForComposer';
import {getDraftComment} from '@libs/DraftCommentUtils';
import * as EmojiUtils from '@libs/EmojiUtils';
import focusComposerWithDelay from '@libs/focusComposerWithDelay';
import getPlatform from '@libs/getPlatform';
import * as KeyDownListener from '@libs/KeyboardShortcut/KeyDownPressListener';
import {parseHtmlToMarkdown} from '@libs/OnyxAwareParser';
import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import updateMultilineInputRange from '@libs/updateMultilineInputRange';
import willBlurTextInputOnTapOutsideFunc from '@libs/willBlurTextInputOnTapOutside';
import getCursorPosition from '@pages/home/report/ReportActionCompose/getCursorPosition';
import getScrollPosition from '@pages/home/report/ReportActionCompose/getScrollPosition';
import type {ComposerRef, SuggestionsRef} from '@pages/home/report/ReportActionCompose/ReportActionCompose';
import SilentCommentUpdater from '@pages/home/report/ReportActionCompose/SilentCommentUpdater';
import Suggestions from '@pages/home/report/ReportActionCompose/Suggestions';
import * as EmojiPickerActions from '@userActions/EmojiPickerAction';
import * as InputFocus from '@userActions/InputFocus';
import * as Modal from '@userActions/Modal';
import * as Report from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type * as OnyxTypes from '@src/types/onyx';
import type ChildrenProps from '@src/types/utils/ChildrenProps';
type SyncSelection = {
position: number;
value: string;
};
type AnimatedRef = ReturnType<typeof useAnimatedRef>;
type NewlyAddedChars = {startIndex: number; endIndex: number; diff: string};
type ComposerWithSuggestionsOnyxProps = {
/** The parent report actions for the report */
parentReportActions: OnyxEntry<OnyxTypes.ReportActions>;
/** The modal state */
modal: OnyxEntry<OnyxTypes.Modal>;
/** The preferred skin tone of the user */
preferredSkinTone: number;
/** Whether the input is focused */
editFocused: OnyxEntry<boolean>;
};
type ComposerWithSuggestionsProps = ComposerWithSuggestionsOnyxProps &
Partial<ChildrenProps> & {
/** Report ID */
reportID: string;
/** Callback to focus composer */
onFocus: () => void;
/** Callback to blur composer */
onBlur: (event: NativeSyntheticEvent<TextInputFocusEventData>) => void;
/** Callback to update the value of the composer */
onValueChange: (value: string) => void;
/** Whether the composer is full size */
isComposerFullSize: boolean;
/** Whether the menu is visible */
isMenuVisible: boolean;
/** The placeholder for the input */
inputPlaceholder: string;
/** Function to display a file in a modal */
displayFileInModal: (file: FileObject) => void;
/** Whether the text input should clear */
textInputShouldClear: boolean;
/** Function to set the text input should clear */
setTextInputShouldClear: (shouldClear: boolean) => void;
/** Whether the user is blocked from concierge */
isBlockedFromConcierge: boolean;
/** Whether the input is disabled */
disabled: boolean;
/** Whether the full composer is available */
isFullComposerAvailable: boolean;
/** Function to set whether the full composer is available */
setIsFullComposerAvailable: (isFullComposerAvailable: boolean) => void;
/** Function to set whether the comment is empty */
setIsCommentEmpty: (isCommentEmpty: boolean) => void;
/** Function to handle sending a message */
handleSendMessage: () => void;
/** Whether the compose input should show */
shouldShowComposeInput: OnyxEntry<boolean>;
/** Function to measure the parent container */
measureParentContainer: (callback: MeasureInWindowOnSuccessCallback) => void;
/** Whether the scroll is likely to trigger a layout */
isScrollLikelyLayoutTriggered: RefObject<boolean>;
/** Function to raise the scroll is likely layout triggered */
raiseIsScrollLikelyLayoutTriggered: () => void;
/** The ref to the suggestions */
suggestionsRef: React.RefObject<SuggestionsRef>;
/** The ref to the animated input */
animatedRef: AnimatedRef;
/** The ref to the next modal will open */
isNextModalWillOpenRef: MutableRefObject<boolean | null>;
/** Whether the edit is focused */
editFocused: boolean;
/** Wheater chat is empty */
isEmptyChat?: boolean;
/** The last report action */
lastReportAction?: OnyxEntry<OnyxTypes.ReportAction>;
/** Whether to include chronos */
includeChronos?: boolean;
/** The parent report action ID */
parentReportActionID?: string;
/** The parent report ID */
// eslint-disable-next-line react/no-unused-prop-types -- its used in the withOnyx HOC
parentReportID: string | undefined;
/** Whether report is from group policy */
isGroupPolicyReport: boolean;
/** policy ID of the report */
policyID: string;
};
type SwitchToCurrentReportProps = {
preexistingReportID: string;
callback: () => void;
};
const {RNTextInputReset} = NativeModules;
const isIOSNative = getPlatform() === CONST.PLATFORM.IOS;
/**
* Broadcast that the user is typing. Debounced to limit how often we publish client events.
*/
const debouncedBroadcastUserIsTyping = lodashDebounce(
(reportID: string) => {
Report.broadcastUserIsTyping(reportID);
},
1000,
{
maxWait: 1000,
leading: true,
},
);
const willBlurTextInputOnTapOutside = willBlurTextInputOnTapOutsideFunc();
// We want consistent auto focus behavior on input between native and mWeb so we have some auto focus management code that will
// prevent auto focus on existing chat for mobile device
const shouldFocusInputOnScreenFocus = canFocusInputOnScreenFocus();
/**
* This component holds the value and selection state.
* If a component really needs access to these state values it should be put here.
* However, double check if the component really needs access, as it will re-render
* on every key press.
*/
function ComposerWithSuggestions(
{
// Onyx
modal,
preferredSkinTone = CONST.EMOJI_DEFAULT_SKIN_TONE,
parentReportActions,
// Props: Report
reportID,
includeChronos,
isEmptyChat,
lastReportAction,
parentReportActionID,
isGroupPolicyReport,
policyID,
// Focus
onFocus,
onBlur,
onValueChange,
// Composer
isComposerFullSize,
isMenuVisible,
inputPlaceholder,
displayFileInModal,
textInputShouldClear,
setTextInputShouldClear,
isBlockedFromConcierge,
disabled,
isFullComposerAvailable,
setIsFullComposerAvailable,
setIsCommentEmpty,
handleSendMessage,
shouldShowComposeInput,
measureParentContainer = () => {},
isScrollLikelyLayoutTriggered,
raiseIsScrollLikelyLayoutTriggered,
// Refs
suggestionsRef,
animatedRef,
isNextModalWillOpenRef,
editFocused,
// For testing
children,
}: ComposerWithSuggestionsProps,
ref: ForwardedRef<ComposerRef>,
) {
const {isKeyboardShown} = useKeyboardState();
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {preferredLocale} = useLocalize();
const isFocused = useIsFocused();
const navigation = useNavigation();
const emojisPresentBefore = useRef<Emoji[]>([]);
const mobileInputScrollPosition = useRef(0);
const cursorPositionValue = useSharedValue({x: 0, y: 0});
const tag = useSharedValue(-1);
const draftComment = getDraftComment(reportID) ?? '';
const [value, setValue] = useState(() => {
if (draftComment) {
emojisPresentBefore.current = EmojiUtils.extractEmojis(draftComment);
}
return draftComment;
});
const commentRef = useRef(value);
const lastTextRef = useRef(value);
const {isSmallScreenWidth} = useWindowDimensions();
const maxComposerLines = isSmallScreenWidth ? CONST.COMPOSER.MAX_LINES_SMALL_SCREEN : CONST.COMPOSER.MAX_LINES;
const parentReportAction = parentReportActions?.[parentReportActionID ?? '-1'];
const shouldAutoFocus =
!modal?.isVisible &&
Modal.areAllModalsHidden() &&
isFocused &&
(shouldFocusInputOnScreenFocus || (isEmptyChat && !ReportActionsUtils.isTransactionThread(parentReportAction))) &&
shouldShowComposeInput;
const valueRef = useRef(value);
valueRef.current = value;
const [selection, setSelection] = useState<TextSelection>(() => ({start: 0, end: 0, positionX: 0, positionY: 0}));
const [composerHeight, setComposerHeight] = useState(0);
const textInputRef = useRef<TextInput | null>(null);
const insertedEmojisRef = useRef<Emoji[]>([]);
const syncSelectionWithOnChangeTextRef = useRef<SyncSelection | null>(null);
// The ref to check whether the comment saving is in progress
const isCommentPendingSaved = useRef(false);
/**
* Set the TextInput Ref
*/
const setTextInputRef = useCallback(
(el: TextInput) => {
ReportActionComposeFocusManager.composerRef.current = el;
textInputRef.current = el;
if (typeof animatedRef === 'function') {
animatedRef(el);
}
},
[animatedRef],
);
const resetKeyboardInput = useCallback(() => {
if (!RNTextInputReset) {
return;
}
RNTextInputReset.resetKeyboardInput(findNodeHandle(textInputRef.current));
}, [textInputRef]);
const debouncedSaveReportComment = useMemo(
() =>
lodashDebounce((selectedReportID: string, newComment: string | null) => {
Report.saveReportDraftComment(selectedReportID, newComment);
isCommentPendingSaved.current = false;
}, 1000),
[],
);
useEffect(() => {
const switchToCurrentReport = DeviceEventEmitter.addListener(`switchToPreExistingReport_${reportID}`, ({preexistingReportID, callback}: SwitchToCurrentReportProps) => {
if (!commentRef.current) {
callback();
return;
}
Report.saveReportDraftComment(preexistingReportID, commentRef.current, callback);
});
return () => {
switchToCurrentReport.remove();
};
}, [reportID]);
/**
* Find the newly added characters between the previous text and the new text based on the selection.
*
* @param prevText - The previous text.
* @param newText - The new text.
* @returns An object containing information about the newly added characters.
* @property startIndex - The start index of the newly added characters in the new text.
* @property endIndex - The end index of the newly added characters in the new text.
* @property diff - The newly added characters.
*/
const findNewlyAddedChars = useCallback(
(prevText: string, newText: string): NewlyAddedChars => {
let startIndex = -1;
let endIndex = -1;
let currentIndex = 0;
// Find the first character mismatch with newText
while (currentIndex < newText.length && prevText.charAt(currentIndex) === newText.charAt(currentIndex) && selection.start > currentIndex) {
currentIndex++;
}
if (currentIndex < newText.length) {
startIndex = currentIndex;
const commonSuffixLength = ComposerUtils.findCommonSuffixLength(prevText, newText, selection?.end ?? 0);
// if text is getting pasted over find length of common suffix and subtract it from new text length
if (commonSuffixLength > 0 || (selection?.end ?? 0) - selection.start > 0) {
endIndex = newText.length - commonSuffixLength;
} else {
endIndex = currentIndex + newText.length;
}
}
return {
startIndex,
endIndex,
diff: newText.substring(startIndex, endIndex),
};
},
[selection.start, selection.end],
);
/**
* Update the value of the comment in Onyx
*/
const updateComment = useCallback(
(commentValue: string, shouldDebounceSaveComment?: boolean) => {
raiseIsScrollLikelyLayoutTriggered();
const {startIndex, endIndex, diff} = findNewlyAddedChars(lastTextRef.current, commentValue);
const isEmojiInserted = diff.length && endIndex > startIndex && diff.trim() === diff && EmojiUtils.containsOnlyEmojis(diff);
const commentWithSpaceInserted = isEmojiInserted ? ComposerUtils.insertWhiteSpaceAtIndex(commentValue, endIndex) : commentValue;
const {text: newComment, emojis, cursorPosition} = EmojiUtils.replaceAndExtractEmojis(commentWithSpaceInserted, preferredSkinTone, preferredLocale);
if (emojis.length) {
const newEmojis = EmojiUtils.getAddedEmojis(emojis, emojisPresentBefore.current);
if (newEmojis.length) {
// Ensure emoji suggestions are hidden after inserting emoji even when the selection is not changed
if (suggestionsRef.current) {
suggestionsRef.current.resetSuggestions();
}
insertedEmojisRef.current = [...insertedEmojisRef.current, ...newEmojis];
}
}
const newCommentConverted = convertToLTRForComposer(newComment);
const isNewCommentEmpty = !!newCommentConverted.match(/^(\s)*$/);
const isPrevCommentEmpty = !!commentRef.current.match(/^(\s)*$/);
/** Only update isCommentEmpty state if it's different from previous one */
if (isNewCommentEmpty !== isPrevCommentEmpty) {
setIsCommentEmpty(isNewCommentEmpty);
}
emojisPresentBefore.current = emojis;
setValue(newCommentConverted);
if (commentValue !== newComment) {
const position = Math.max((selection.end ?? 0) + (newComment.length - commentRef.current.length), cursorPosition ?? 0);
if (commentWithSpaceInserted !== newComment && isIOSNative) {
syncSelectionWithOnChangeTextRef.current = {position, value: newComment};
}
setSelection((prevSelection) => ({
start: position,
end: position,
positionX: prevSelection.positionX,
positionY: prevSelection.positionY,
}));
}
commentRef.current = newCommentConverted;
if (shouldDebounceSaveComment) {
isCommentPendingSaved.current = true;
debouncedSaveReportComment(reportID, newCommentConverted);
} else {
Report.saveReportDraftComment(reportID, newCommentConverted);
}
if (newCommentConverted) {
debouncedBroadcastUserIsTyping(reportID);
}
},
[findNewlyAddedChars, preferredLocale, preferredSkinTone, reportID, setIsCommentEmpty, suggestionsRef, raiseIsScrollLikelyLayoutTriggered, debouncedSaveReportComment, selection.end],
);
const prepareCommentAndResetComposer = useCallback((): string => {
const trimmedComment = commentRef.current.trim();
const commentLength = ReportUtils.getCommentLength(trimmedComment, {reportID});
// Don't submit empty comments or comments that exceed the character limit
if (!commentLength || commentLength > CONST.MAX_COMMENT_LENGTH) {
return '';
}
// Since we're submitting the form here which should clear the composer
// We don't really care about saving the draft the user was typing
// We need to make sure an empty draft gets saved instead
debouncedSaveReportComment.cancel();
isCommentPendingSaved.current = false;
setSelection({start: 0, end: 0, positionX: 0, positionY: 0});
updateComment('');
setTextInputShouldClear(true);
if (isComposerFullSize) {
Report.setIsComposerFullSize(reportID, false);
}
setIsFullComposerAvailable(false);
return trimmedComment;
}, [updateComment, setTextInputShouldClear, isComposerFullSize, setIsFullComposerAvailable, reportID, debouncedSaveReportComment]);
/**
* Callback to add whatever text is chosen into the main input (used f.e as callback for the emoji picker)
*/
const replaceSelectionWithText = useCallback(
(text: string) => {
// selection replacement should be debounced to avoid conflicts with text typing
// (f.e. when emoji is being picked and 1 second still did not pass after user finished typing)
updateComment(ComposerUtils.insertText(commentRef.current, selection, text), true);
},
[selection, updateComment],
);
const triggerHotkeyActions = useCallback(
(event: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
const webEvent = event as unknown as KeyboardEvent;
if (!webEvent || ComposerUtils.canSkipTriggerHotkeys(isSmallScreenWidth, isKeyboardShown)) {
return;
}
if (suggestionsRef.current?.triggerHotkeyActions(webEvent)) {
return;
}
// Submit the form when Enter is pressed
if (webEvent.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey && !webEvent.shiftKey) {
webEvent.preventDefault();
handleSendMessage();
}
// Trigger the edit box for last sent message if ArrowUp is pressed and the comment is empty and Chronos is not in the participants
const valueLength = valueRef.current.length;
if (
'key' in event &&
event.key === CONST.KEYBOARD_SHORTCUTS.ARROW_UP.shortcutKey &&
textInputRef.current &&
'selectionStart' in textInputRef.current &&
textInputRef.current?.selectionStart === 0 &&
valueLength === 0 &&
!includeChronos
) {
event.preventDefault();
if (lastReportAction) {
const message = Array.isArray(lastReportAction?.message) ? lastReportAction?.message?.at(-1) ?? null : lastReportAction?.message ?? null;
Report.saveReportActionDraft(reportID, lastReportAction, parseHtmlToMarkdown(message?.html ?? ''));
}
}
},
[isSmallScreenWidth, isKeyboardShown, suggestionsRef, includeChronos, handleSendMessage, lastReportAction, reportID],
);
const onChangeText = useCallback(
(commentValue: string) => {
updateComment(commentValue, true);
if (isIOSNative && syncSelectionWithOnChangeTextRef.current) {
const positionSnapshot = syncSelectionWithOnChangeTextRef.current.position;
syncSelectionWithOnChangeTextRef.current = null;
// ensure that selection is set imperatively after all state changes are effective
InteractionManager.runAfterInteractions(() => {
// note: this implementation is only available on non-web RN, thus the wrapping
// 'if' block contains a redundant (since the ref is only used on iOS) platform check
textInputRef.current?.setSelection(positionSnapshot, positionSnapshot);
});
}
},
[updateComment],
);
const onSelectionChange = useCallback(
(e: CustomSelectionChangeEvent) => {
if (!textInputRef.current?.isFocused()) {
return;
}
suggestionsRef.current?.onSelectionChange?.(e);
setSelection(e.nativeEvent.selection);
},
[suggestionsRef],
);
const hideSuggestionMenu = useCallback(
(e: NativeSyntheticEvent<TextInputScrollEventData>) => {
mobileInputScrollPosition.current = e?.nativeEvent?.contentOffset?.y ?? 0;
if (!suggestionsRef.current || isScrollLikelyLayoutTriggered.current) {
return;
}
suggestionsRef.current.updateShouldShowSuggestionMenuToFalse(false);
},
[suggestionsRef, isScrollLikelyLayoutTriggered],
);
const setShouldBlockSuggestionCalcToFalse = useCallback(() => {
if (!suggestionsRef.current) {
return false;
}
InputFocus.inputFocusChange(false);
return suggestionsRef.current.setShouldBlockSuggestionCalc(false);
}, [suggestionsRef]);
/**
* Focus the composer text input
* @param [shouldDelay=false] Impose delay before focusing the composer
*/
const focus = useCallback((shouldDelay = false) => {
focusComposerWithDelay(textInputRef.current)(shouldDelay);
}, []);
const setUpComposeFocusManager = useCallback(() => {
// This callback is used in the contextMenuActions to manage giving focus back to the compose input.
ReportActionComposeFocusManager.onComposerFocus((shouldFocusForNonBlurInputOnTapOutside = false) => {
if ((!willBlurTextInputOnTapOutside && !shouldFocusForNonBlurInputOnTapOutside) || !isFocused) {
return;
}
focus(false);
}, true);
}, [focus, isFocused]);
/**
* Check if the composer is visible. Returns true if the composer is not covered up by emoji picker or menu. False otherwise.
* @returns {Boolean}
*/
const checkComposerVisibility = useCallback(() => {
// Checking whether the screen is focused or not, helps avoid `modal.isVisible` false when popups are closed, even if the modal is opened.
const isComposerCoveredUp = !isFocused || EmojiPickerActions.isEmojiPickerVisible() || isMenuVisible || !!modal?.isVisible || modal?.willAlertModalBecomeVisible;
return !isComposerCoveredUp;
}, [isMenuVisible, modal, isFocused]);
const focusComposerOnKeyPress = useCallback(
(e: KeyboardEvent) => {
const isComposerVisible = checkComposerVisibility();
if (!isComposerVisible) {
return;
}
if (!ReportUtils.shouldAutoFocusOnKeyPress(e)) {
return;
}
// if we're typing on another input/text area, do not focus
if (['INPUT', 'TEXTAREA'].includes((e.target as Element | null)?.nodeName ?? '')) {
return;
}
focus();
},
[checkComposerVisibility, focus],
);
const blur = useCallback(() => {
if (!textInputRef.current) {
return;
}
textInputRef.current.blur();
}, []);
useEffect(() => {
const unsubscribeNavigationBlur = navigation.addListener('blur', () => KeyDownListener.removeKeyDownPressListener(focusComposerOnKeyPress));
const unsubscribeNavigationFocus = navigation.addListener('focus', () => {
KeyDownListener.addKeyDownPressListener(focusComposerOnKeyPress);
// The report isn't unmounted and can be focused again after going back from another report so we should update the composerRef again
ReportActionComposeFocusManager.composerRef.current = textInputRef.current;
setUpComposeFocusManager();
});
KeyDownListener.addKeyDownPressListener(focusComposerOnKeyPress);
setUpComposeFocusManager();
return () => {
ReportActionComposeFocusManager.clear(true);
KeyDownListener.removeKeyDownPressListener(focusComposerOnKeyPress);
unsubscribeNavigationBlur();
unsubscribeNavigationFocus();
};
}, [focusComposerOnKeyPress, navigation, setUpComposeFocusManager]);
const prevIsModalVisible = usePrevious(modal?.isVisible);
const prevIsFocused = usePrevious(isFocused);
useEffect(() => {
if (modal?.isVisible && !prevIsModalVisible) {
// eslint-disable-next-line no-param-reassign
isNextModalWillOpenRef.current = false;
}
// We want to blur the input immediately when a screen is out of focus.
if (!isFocused) {
textInputRef.current?.blur();
}
// We want to focus or refocus the input when a modal has been closed or the underlying screen is refocused.
// We avoid doing this on native platforms since the software keyboard popping
// open creates a jarring and broken UX.
if (!((willBlurTextInputOnTapOutside || shouldAutoFocus) && !isNextModalWillOpenRef.current && !modal?.isVisible && isFocused && (!!prevIsModalVisible || !prevIsFocused))) {
return;
}
if (editFocused) {
InputFocus.inputFocusChange(false);
return;
}
focus(true);
}, [focus, prevIsFocused, editFocused, prevIsModalVisible, isFocused, modal?.isVisible, isNextModalWillOpenRef, shouldAutoFocus]);
useEffect(() => {
// Scrolls the composer to the bottom and sets the selection to the end, so that longer drafts are easier to edit
updateMultilineInputRange(textInputRef.current, !!shouldAutoFocus);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useImperativeHandle(
ref,
() => ({
blur,
focus,
replaceSelectionWithText,
prepareCommentAndResetComposer,
isFocused: () => !!textInputRef.current?.isFocused(),
}),
[blur, focus, prepareCommentAndResetComposer, replaceSelectionWithText],
);
useEffect(() => {
lastTextRef.current = value;
}, [value]);
useEffect(() => {
onValueChange(value);
}, [onValueChange, value]);
const onLayout = useCallback(
(e: LayoutChangeEvent) => {
const composerLayoutHeight = e.nativeEvent.layout.height;
if (composerHeight === composerLayoutHeight) {
return;
}
setComposerHeight(composerLayoutHeight);
},
[composerHeight],
);
const onClear = useCallback(() => {
mobileInputScrollPosition.current = 0;
setTextInputShouldClear(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
tag.value = findNodeHandle(textInputRef.current) ?? -1;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useFocusedInputHandler(
{
onSelectionChange: (event) => {
'worklet';
if (event.target === tag.value) {
cursorPositionValue.value = {
x: event.selection.end.x,
y: event.selection.end.y,
};
}
},
},
[],
);
const measureParentContainerAndReportCursor = useCallback(
(callback: MeasureParentContainerAndCursorCallback) => {
const {scrollValue} = getScrollPosition({mobileInputScrollPosition, textInputRef});
const {x: xPosition, y: yPosition} = getCursorPosition({positionOnMobile: cursorPositionValue.value, positionOnWeb: selection});
measureParentContainer((x, y, width, height) => {
callback({
x,
y,
width,
height,
scrollValue,
cursorCoordinates: {x: xPosition, y: yPosition},
});
});
},
[measureParentContainer, cursorPositionValue, selection],
);
return (
<>
<View style={[StyleUtils.getContainerComposeStyles(), styles.textInputComposeBorder]}>
<Composer
checkComposerVisibility={checkComposerVisibility}
autoFocus={!!shouldAutoFocus}
multiline
ref={setTextInputRef}
placeholder={inputPlaceholder}
placeholderTextColor={theme.placeholderText}
onChangeText={onChangeText}
onKeyPress={triggerHotkeyActions}
textAlignVertical="top"
style={[styles.textInputCompose, isComposerFullSize ? styles.textInputFullCompose : styles.textInputCollapseCompose]}
maxLines={maxComposerLines}
onFocus={onFocus}
onBlur={onBlur}
onClick={setShouldBlockSuggestionCalcToFalse}
onPasteFile={displayFileInModal}
shouldClear={textInputShouldClear}
onClear={onClear}
isDisabled={isBlockedFromConcierge || disabled}
isReportActionCompose
selection={selection}
onSelectionChange={onSelectionChange}
isFullComposerAvailable={isFullComposerAvailable}
setIsFullComposerAvailable={setIsFullComposerAvailable}
isComposerFullSize={isComposerFullSize}
value={value}
testID="composer"
shouldCalculateCaretPosition
onLayout={onLayout}
onScroll={hideSuggestionMenu}
shouldContainScroll={Browser.isMobileSafari()}
isGroupPolicyReport={isGroupPolicyReport}
/>
</View>
<Suggestions
ref={suggestionsRef}
isComposerFocused={textInputRef.current?.isFocused()}
updateComment={updateComment}
measureParentContainerAndReportCursor={measureParentContainerAndReportCursor}
isGroupPolicyReport={isGroupPolicyReport}
policyID={policyID}
// Input
value={value}
setValue={setValue}
selection={selection}
setSelection={setSelection}
resetKeyboardInput={resetKeyboardInput}
/>
{ReportUtils.isValidReportIDFromPath(reportID) && (
<SilentCommentUpdater
reportID={reportID}
value={value}
updateComment={updateComment}
commentRef={commentRef}
isCommentPendingSaved={isCommentPendingSaved}
/>
)}
{/* Only used for testing so far */}
{children}
</>
);
}
ComposerWithSuggestions.displayName = 'ComposerWithSuggestions';
const ComposerWithSuggestionsWithRef = forwardRef(ComposerWithSuggestions);
export default withOnyx<ComposerWithSuggestionsProps & RefAttributes<ComposerRef>, ComposerWithSuggestionsOnyxProps>({
modal: {
key: ONYXKEYS.MODAL,
},
preferredSkinTone: {
key: ONYXKEYS.PREFERRED_EMOJI_SKIN_TONE,
selector: EmojiUtils.getPreferredSkinToneIndex,
},
editFocused: {
key: ONYXKEYS.INPUT_FOCUSED,
},
parentReportActions: {
key: ({parentReportID}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`,
canEvict: false,
initWithStoredValues: false,
},
})(memo(ComposerWithSuggestionsWithRef));
export type {ComposerWithSuggestionsProps};