-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathReportActionItemMessageEdit.tsx
489 lines (438 loc) · 21.1 KB
/
ReportActionItemMessageEdit.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
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import lodashDebounce from 'lodash/debounce';
import type {ForwardedRef} from 'react';
import React, {forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {Keyboard, View} from 'react-native';
import type {NativeSyntheticEvent, TextInput, TextInputFocusEventData, TextInputKeyPressEventData} from 'react-native';
import type {Emoji} from '@assets/emojis/types';
import Composer from '@components/Composer';
import EmojiPickerButton from '@components/EmojiPicker/EmojiPickerButton';
import ExceededCommentLength from '@components/ExceededCommentLength';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import Tooltip from '@components/Tooltip';
import useHandleExceedMaxCommentLength from '@hooks/useHandleExceedMaxCommentLength';
import useKeyboardState from '@hooks/useKeyboardState';
import useLocalize from '@hooks/useLocalize';
import useReportScrollManager from '@hooks/useReportScrollManager';
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 * as ComposerUtils from '@libs/ComposerUtils';
import * as EmojiUtils from '@libs/EmojiUtils';
import focusComposerWithDelay from '@libs/focusComposerWithDelay';
import focusEditAfterCancelDelete from '@libs/focusEditAfterCancelDelete';
import onyxSubscribe from '@libs/onyxSubscribe';
import ReportActionComposeFocusManager from '@libs/ReportActionComposeFocusManager';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import setShouldShowComposeInputKeyboardAware from '@libs/setShouldShowComposeInputKeyboardAware';
import * as ComposerActions from '@userActions/Composer';
import * as EmojiPickerAction from '@userActions/EmojiPickerAction';
import * as InputFocus from '@userActions/InputFocus';
import * as Report from '@userActions/Report';
import * as User from '@userActions/User';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type * as OnyxTypes from '@src/types/onyx';
import * as ReportActionContextMenu from './ContextMenu/ReportActionContextMenu';
type ReportActionItemMessageEditProps = {
/** All the data of the action */
action: OnyxTypes.ReportAction;
/** Draft message */
draftMessage: string;
/** ReportID that holds the comment we're editing */
reportID: string;
/** Position index of the report action in the overall report FlatList view */
index: number;
/** Whether or not the emoji picker is disabled */
shouldDisableEmojiPicker?: boolean;
/** Stores user's preferred skin tone */
preferredSkinTone?: number;
};
// native ids
const emojiButtonID = 'emojiButton';
const messageEditInput = 'messageEditInput';
const isMobileSafari = Browser.isMobileSafari();
function ReportActionItemMessageEdit(
{action, draftMessage, reportID, index, shouldDisableEmojiPicker = false, preferredSkinTone = CONST.EMOJI_DEFAULT_SKIN_TONE}: ReportActionItemMessageEditProps,
forwardedRef: ForwardedRef<TextInput & HTMLTextAreaElement>,
) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const reportScrollManager = useReportScrollManager();
const {translate, preferredLocale} = useLocalize();
const {isKeyboardShown} = useKeyboardState();
const {isSmallScreenWidth} = useWindowDimensions();
const getInitialDraft = () => {
if (draftMessage === action?.message?.[0].html) {
// We only convert the report action message to markdown if the draft message is unchanged.
const parser = new ExpensiMark();
return parser.htmlToMarkdown(draftMessage).trim();
}
// We need to decode saved draft message because it's escaped before saving.
return Str.htmlDecode(draftMessage);
};
const getInitialSelection = () => {
if (isMobileSafari) {
return {start: 0, end: 0};
}
const length = getInitialDraft().length;
return {start: length, end: length};
};
const emojisPresentBefore = useRef<Emoji[]>([]);
const [draft, setDraft] = useState(() => {
const initialDraft = getInitialDraft();
if (initialDraft) {
emojisPresentBefore.current = EmojiUtils.extractEmojis(initialDraft);
}
return initialDraft;
});
const [selection, setSelection] = useState<{
start: number;
end: number;
}>(getInitialSelection);
const [isFocused, setIsFocused] = useState<boolean>(false);
const {hasExceededMaxCommentLength, validateCommentMaxLength} = useHandleExceedMaxCommentLength();
const [modal, setModal] = useState<OnyxTypes.Modal>({
willAlertModalBecomeVisible: false,
isVisible: false,
});
const [onyxFocused, setOnyxFocused] = useState<boolean>(false);
const textInputRef = useRef<(HTMLTextAreaElement & TextInput) | null>(null);
const isFocusedRef = useRef<boolean>(false);
const insertedEmojis = useRef<Emoji[]>([]);
const draftRef = useRef(draft);
useEffect(() => {
if (ReportActionsUtils.isDeletedAction(action) || (action.message && draftMessage === action.message[0].html)) {
return;
}
setDraft(Str.htmlDecode(draftMessage));
}, [draftMessage, action]);
useEffect(() => {
// required for keeping last state of isFocused variable
isFocusedRef.current = isFocused;
}, [isFocused]);
useEffect(() => {
InputFocus.composerFocusKeepFocusOn(textInputRef.current as HTMLElement, isFocused, modal, onyxFocused);
}, [isFocused, modal, onyxFocused]);
useEffect(() => {
const unsubscribeOnyxModal = onyxSubscribe({
key: ONYXKEYS.MODAL,
callback: (modalArg) => {
if (modalArg === null) {
return;
}
setModal(modalArg);
},
});
const unsubscribeOnyxFocused = onyxSubscribe({
key: ONYXKEYS.INPUT_FOCUSED,
callback: (modalArg) => {
if (modalArg === null) {
return;
}
setOnyxFocused(modalArg);
},
});
return () => {
unsubscribeOnyxModal();
unsubscribeOnyxFocused();
};
}, []);
// We consider the report action active if it's focused, its emoji picker is open or its context menu is open
const isActive = useCallback(
() => isFocusedRef.current || EmojiPickerAction.isActive(action.reportActionID) || ReportActionContextMenu.isActiveReportAction(action.reportActionID),
[action.reportActionID],
);
useEffect(() => {
// For mobile Safari, updating the selection prop on an unfocused input will cause it to automatically gain focus
// and subsequent programmatic focus shifts (e.g., modal focus trap) to show the blue frame (:focus-visible style),
// so we need to ensure that it is only updated after focus.
if (isMobileSafari) {
setDraft((prevDraft) => {
setSelection({
start: prevDraft.length,
end: prevDraft.length,
});
return prevDraft;
});
// Scroll content of textInputRef to bottom
if (textInputRef.current) {
textInputRef.current.scrollTop = textInputRef.current.scrollHeight;
}
}
return () => {
InputFocus.callback(() => setIsFocused(false));
InputFocus.inputFocusChange(false);
// Skip if the current report action is not active
if (!isActive()) {
return;
}
if (EmojiPickerAction.isActive(action.reportActionID)) {
EmojiPickerAction.clearActive();
}
if (ReportActionContextMenu.isActiveReportAction(action.reportActionID)) {
ReportActionContextMenu.clearActiveReportAction();
}
// Show the main composer when the focused message is deleted from another client
// to prevent the main composer stays hidden until we swtich to another chat.
setShouldShowComposeInputKeyboardAware(true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- this cleanup needs to be called only on unmount
}, [action.reportActionID]);
// show the composer after editing is complete for devices that hide the composer during editing.
useEffect(() => () => ComposerActions.setShouldShowComposeInput(true), []);
/**
* Save the draft of the comment. This debounced so that we're not ceaselessly saving your edit. Saving the draft
* allows one to navigate somewhere else and come back to the comment and still have it in edit mode.
* @param {String} newDraft
*/
const debouncedSaveDraft = useMemo(
() =>
lodashDebounce((newDraft: string) => {
Report.saveReportActionDraft(reportID, action, newDraft);
}, 1000),
[reportID, action],
);
/**
* Update frequently used emojis list. We debounce this method in the constructor so that UpdateFrequentlyUsedEmojis
* API is not called too often.
*/
const debouncedUpdateFrequentlyUsedEmojis = useMemo(
() =>
lodashDebounce(() => {
User.updateFrequentlyUsedEmojis(EmojiUtils.getFrequentlyUsedEmojis(insertedEmojis.current));
insertedEmojis.current = [];
}, 1000),
[],
);
/**
* Update the value of the draft in Onyx
*
* @param {String} newDraftInput
*/
const updateDraft = useCallback(
(newDraftInput: string) => {
const {text: newDraft, emojis, cursorPosition} = EmojiUtils.replaceAndExtractEmojis(newDraftInput, preferredSkinTone, preferredLocale);
if (emojis?.length > 0) {
const newEmojis = EmojiUtils.getAddedEmojis(emojis, emojisPresentBefore.current);
if (newEmojis?.length > 0) {
insertedEmojis.current = [...insertedEmojis.current, ...newEmojis];
debouncedUpdateFrequentlyUsedEmojis();
}
}
emojisPresentBefore.current = emojis;
setDraft(newDraft);
if (newDraftInput !== newDraft) {
const position = Math.max(selection.end + (newDraft.length - draftRef.current.length), cursorPosition ?? 0);
setSelection({
start: position,
end: position,
});
}
draftRef.current = newDraft;
// We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted.
debouncedSaveDraft(newDraft);
},
[debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, preferredSkinTone, preferredLocale, selection.end],
);
useEffect(() => {
updateDraft(draft);
// eslint-disable-next-line react-hooks/exhaustive-deps -- run this only when language is changed
}, [action.reportActionID, preferredLocale]);
/**
* Delete the draft of the comment being edited. This will take the comment out of "edit mode" with the old content.
*/
const deleteDraft = useCallback(() => {
debouncedSaveDraft.cancel();
Report.deleteReportActionDraft(reportID, action);
if (isActive()) {
ReportActionComposeFocusManager.clear();
ReportActionComposeFocusManager.focus();
}
// Scroll to the last comment after editing to make sure the whole comment is clearly visible in the report.
if (index === 0) {
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
reportScrollManager.scrollToIndex(index, false);
keyboardDidHideListener.remove();
});
}
}, [action, debouncedSaveDraft, index, reportID, reportScrollManager, isActive]);
/**
* Save the draft of the comment to be the new comment message. This will take the comment out of "edit mode" with
* the new content.
*/
const publishDraft = useCallback(() => {
// Do nothing if draft exceed the character limit
if (ReportUtils.getCommentLength(draft) > CONST.MAX_COMMENT_LENGTH) {
return;
}
// To prevent re-mount after user saves edit before debounce duration (example: within 1 second), we cancel
// debounce here.
debouncedSaveDraft.cancel();
const trimmedNewDraft = draft.trim();
// When user tries to save the empty message, it will delete it. Prompt the user to confirm deleting.
if (!trimmedNewDraft) {
textInputRef.current?.blur();
ReportActionContextMenu.showDeleteModal(reportID, action, true, deleteDraft, () => focusEditAfterCancelDelete(textInputRef.current));
return;
}
Report.editReportComment(reportID, action, trimmedNewDraft);
deleteDraft();
}, [action, debouncedSaveDraft, deleteDraft, draft, reportID]);
/**
* @param emoji
*/
const addEmojiToTextBox = (emoji: string) => {
setSelection((prevSelection) => ({
start: prevSelection.start + emoji.length + CONST.SPACE_LENGTH,
end: prevSelection.start + emoji.length + CONST.SPACE_LENGTH,
}));
updateDraft(ComposerUtils.insertText(draft, selection, `${emoji} `));
};
/**
* Key event handlers that short cut to saving/canceling.
*
* @param {Event} e
*/
const triggerSaveOrCancel = useCallback(
(e: NativeSyntheticEvent<TextInputKeyPressEventData> | KeyboardEvent) => {
if (!e || ComposerUtils.canSkipTriggerHotkeys(isSmallScreenWidth, isKeyboardShown)) {
return;
}
const keyEvent = e as KeyboardEvent;
if (keyEvent.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey && !keyEvent.shiftKey) {
e.preventDefault();
publishDraft();
} else if (keyEvent.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
e.preventDefault();
deleteDraft();
}
},
[deleteDraft, isKeyboardShown, isSmallScreenWidth, publishDraft],
);
/**
* Focus the composer text input
*/
const focus = focusComposerWithDelay(textInputRef.current);
useEffect(() => {
validateCommentMaxLength(draft);
}, [draft, validateCommentMaxLength]);
return (
<>
<View style={[styles.chatItemMessage, styles.flexRow]}>
<View
style={[
isFocused ? styles.chatItemComposeBoxFocusedColor : styles.chatItemComposeBoxColor,
styles.flexRow,
styles.flex1,
styles.chatItemComposeBox,
hasExceededMaxCommentLength && styles.borderColorDanger,
]}
>
<View style={[styles.justifyContentEnd, styles.mb1]}>
<Tooltip text={translate('common.cancel')}>
<PressableWithFeedback
onPress={deleteDraft}
style={styles.composerSizeButton}
role={CONST.ROLE.BUTTON}
accessibilityLabel={translate('common.close')}
// disable dimming
hoverDimmingValue={1}
pressDimmingValue={1}
// Keep focus on the composer when cancel button is clicked.
onMouseDown={(e) => e.preventDefault()}
>
<Icon
fill={theme.icon}
src={Expensicons.Close}
/>
</PressableWithFeedback>
</Tooltip>
</View>
<View style={[StyleUtils.getContainerComposeStyles(), styles.textInputComposeBorder]}>
<Composer
multiline
ref={(el: TextInput & HTMLTextAreaElement) => {
textInputRef.current = el;
if (typeof forwardedRef === 'function') {
forwardedRef(el);
} else if (forwardedRef) {
// eslint-disable-next-line no-param-reassign
forwardedRef.current = el;
}
}}
id={messageEditInput}
onChangeText={updateDraft} // Debounced saveDraftComment
onKeyPress={triggerSaveOrCancel}
value={draft}
maxLines={isSmallScreenWidth ? CONST.COMPOSER.MAX_LINES_SMALL_SCREEN : CONST.COMPOSER.MAX_LINES} // This is the same that slack has
style={[styles.textInputCompose, styles.flex1, styles.bgTransparent]}
onFocus={() => {
setIsFocused(true);
reportScrollManager.scrollToIndex(index, true);
setShouldShowComposeInputKeyboardAware(false);
// Clear active report action when another action gets focused
if (!EmojiPickerAction.isActive(action.reportActionID)) {
EmojiPickerAction.clearActive();
}
if (!ReportActionContextMenu.isActiveReportAction(action.reportActionID)) {
ReportActionContextMenu.clearActiveReportAction();
}
}}
onBlur={(event: NativeSyntheticEvent<TextInputFocusEventData>) => {
setIsFocused(false);
// @ts-expect-error TODO: TextInputFocusEventData doesn't contain relatedTarget.
const relatedTargetId = event.nativeEvent?.relatedTarget?.id;
if (relatedTargetId && [messageEditInput, emojiButtonID].includes(relatedTargetId)) {
return;
}
setShouldShowComposeInputKeyboardAware(true);
}}
selection={selection}
onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
/>
</View>
<View style={styles.editChatItemEmojiWrapper}>
<EmojiPickerButton
isDisabled={shouldDisableEmojiPicker}
onModalHide={() => focus(true)}
onEmojiSelected={addEmojiToTextBox}
id={emojiButtonID}
emojiPickerID={action.reportActionID}
/>
</View>
<View style={styles.alignSelfEnd}>
<Tooltip text={translate('common.saveChanges')}>
<PressableWithFeedback
style={[styles.chatItemSubmitButton, hasExceededMaxCommentLength ? {} : styles.buttonSuccess]}
onPress={publishDraft}
disabled={hasExceededMaxCommentLength}
role={CONST.ROLE.BUTTON}
accessibilityLabel={translate('common.saveChanges')}
hoverDimmingValue={1}
pressDimmingValue={0.2}
// Keep focus on the composer when send button is clicked.
onMouseDown={(e) => e.preventDefault()}
>
<Icon
src={Expensicons.Checkmark}
fill={hasExceededMaxCommentLength ? theme.icon : theme.textLight}
/>
</PressableWithFeedback>
</Tooltip>
</View>
</View>
</View>
{hasExceededMaxCommentLength && <ExceededCommentLength />}
</>
);
}
ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit';
export default forwardRef(ReportActionItemMessageEdit);