-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportActionItemMessageEdit.js
441 lines (399 loc) · 19.8 KB
/
ReportActionItemMessageEdit.js
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
import lodashGet from 'lodash/get';
import React, {useState, useRef, useMemo, useEffect, useCallback} from 'react';
import {InteractionManager, Keyboard, View} from 'react-native';
import PropTypes from 'prop-types';
import _ from 'underscore';
import ExpensiMark from 'expensify-common/lib/ExpensiMark';
import Str from 'expensify-common/lib/str';
import reportActionPropTypes from './reportActionPropTypes';
import styles from '../../../styles/styles';
import compose from '../../../libs/compose';
import themeColors from '../../../styles/themes/default';
import * as StyleUtils from '../../../styles/StyleUtils';
import containerComposeStyles from '../../../styles/containerComposeStyles';
import Composer from '../../../components/Composer';
import * as Report from '../../../libs/actions/Report';
import {withReportActionsDrafts} from '../../../components/OnyxProvider';
import openReportActionComposeViewWhenClosingMessageEdit from '../../../libs/openReportActionComposeViewWhenClosingMessageEdit';
import ReportActionComposeFocusManager from '../../../libs/ReportActionComposeFocusManager';
import EmojiPickerButton from '../../../components/EmojiPicker/EmojiPickerButton';
import Icon from '../../../components/Icon';
import * as Expensicons from '../../../components/Icon/Expensicons';
import Tooltip from '../../../components/Tooltip';
import * as ReportActionContextMenu from './ContextMenu/ReportActionContextMenu';
import * as ReportUtils from '../../../libs/ReportUtils';
import * as EmojiUtils from '../../../libs/EmojiUtils';
import reportPropTypes from '../../reportPropTypes';
import ExceededCommentLength from '../../../components/ExceededCommentLength';
import CONST from '../../../CONST';
import refPropTypes from '../../../components/refPropTypes';
import * as ComposerUtils from '../../../libs/ComposerUtils';
import * as ComposerActions from '../../../libs/actions/Composer';
import * as User from '../../../libs/actions/User';
import PressableWithFeedback from '../../../components/Pressable/PressableWithFeedback';
import getButtonState from '../../../libs/getButtonState';
import withLocalize, {withLocalizePropTypes} from '../../../components/withLocalize';
import useLocalize from '../../../hooks/useLocalize';
import useKeyboardState from '../../../hooks/useKeyboardState';
import useWindowDimensions from '../../../hooks/useWindowDimensions';
import useReportScrollManager from '../../../hooks/useReportScrollManager';
import * as EmojiPickerAction from '../../../libs/actions/EmojiPickerAction';
import focusWithDelay from '../../../libs/focusWithDelay';
import ONYXKEYS from '../../../ONYXKEYS';
const propTypes = {
/** All the data of the action */
action: PropTypes.shape(reportActionPropTypes).isRequired,
/** Draft message */
draftMessage: PropTypes.string.isRequired,
/** ReportID that holds the comment we're editing */
reportID: PropTypes.string.isRequired,
/** Position index of the report action in the overall report FlatList view */
index: PropTypes.number.isRequired,
/** A ref to forward to the text input */
forwardedRef: refPropTypes,
/** The report currently being looked at */
// eslint-disable-next-line react/no-unused-prop-types
report: reportPropTypes,
/** Whether or not the emoji picker is disabled */
shouldDisableEmojiPicker: PropTypes.bool,
/** Draft message - if this is set the comment is in 'edit' mode */
// eslint-disable-next-line react/forbid-prop-types
drafts: PropTypes.object,
/** Stores user's preferred skin tone */
preferredSkinTone: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
...withLocalizePropTypes,
};
const defaultProps = {
forwardedRef: () => {},
report: {},
shouldDisableEmojiPicker: false,
preferredSkinTone: CONST.EMOJI_DEFAULT_SKIN_TONE,
drafts: {},
};
// native ids
const saveButtonID = 'saveButton';
const cancelButtonID = 'cancelButton';
const emojiButtonID = 'emojiButton';
const messageEditInput = 'messageEditInput';
function ReportActionItemMessageEdit(props) {
const reportScrollManager = useReportScrollManager();
const {translate} = useLocalize();
const {isKeyboardShown} = useKeyboardState();
const {isSmallScreenWidth} = useWindowDimensions();
const [draft, setDraft] = useState(() => {
if (props.draftMessage === props.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(props.draftMessage).trim();
}
// We need to decode saved draft message because it's escaped before saving.
return Str.htmlDecode(props.draftMessage);
});
const [selection, setSelection] = useState({start: 0, end: 0});
const [isFocused, setIsFocused] = useState(false);
const [hasExceededMaxCommentLength, setHasExceededMaxCommentLength] = useState(false);
const textInputRef = useRef(null);
const isFocusedRef = useRef(false);
const insertedEmojis = useRef([]);
useEffect(() => {
if (props.draftMessage === props.action.message[0].html) {
return;
}
setDraft(Str.htmlDecode(props.draftMessage));
}, [props.draftMessage, props.action.message]);
useEffect(() => {
// required for keeping last state of isFocused variable
isFocusedRef.current = isFocused;
}, [isFocused]);
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.
setDraft((prevDraft) => {
setSelection({
start: prevDraft.length,
end: prevDraft.length,
});
return prevDraft;
});
return () => {
// Skip if this is not the focused message so the other edit composer stays focused.
// In small screen devices, when EmojiPicker is shown, the current edit message will lose focus, we need to check this case as well.
if (!isFocusedRef.current && !EmojiPickerAction.isActiveReportAction(props.action.reportActionID)) {
return;
}
// 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.
ComposerActions.setShouldShowComposeInput(true);
};
}, [props.action.reportActionID]);
/**
* 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(
() =>
_.debounce((newDraft) => {
Report.saveReportActionDraft(props.reportID, props.action, newDraft);
}, 1000),
[props.reportID, props.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(
() =>
_.debounce(() => {
User.updateFrequentlyUsedEmojis(EmojiUtils.getFrequentlyUsedEmojis(insertedEmojis.current));
insertedEmojis.current = [];
}, 1000),
[],
);
/**
* Update the value of the draft in Onyx
*
* @param {String} newDraftInput
*/
const updateDraft = useCallback(
(newDraftInput) => {
const {text: newDraft = '', emojis = []} = EmojiUtils.replaceEmojis(newDraftInput, props.preferredSkinTone, props.preferredLocale);
if (!_.isEmpty(emojis)) {
insertedEmojis.current = [...insertedEmojis.current, ...emojis];
debouncedUpdateFrequentlyUsedEmojis();
}
setDraft((prevDraft) => {
if (newDraftInput !== newDraft) {
setSelection((prevSelection) => {
const remainder = prevDraft.slice(prevSelection.end).length;
return {
start: newDraft.length - remainder,
end: newDraft.length - remainder,
};
});
}
return newDraft;
});
// This component is rendered only when draft is set to a non-empty string. In order to prevent component
// unmount when user deletes content of textarea, we set previous message instead of empty string.
if (newDraft.trim().length > 0) {
// We want to escape the draft message to differentiate the HTML from the report action and the HTML the user drafted.
debouncedSaveDraft(_.escape(newDraft));
} else {
debouncedSaveDraft(props.action.message[0].html);
}
},
[props.action.message, debouncedSaveDraft, debouncedUpdateFrequentlyUsedEmojis, props.preferredSkinTone, props.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.saveReportActionDraft(props.reportID, props.action, '');
ComposerActions.setShouldShowComposeInput(true);
ReportActionComposeFocusManager.focus();
// Scroll to the last comment after editing to make sure the whole comment is clearly visible in the report.
if (props.index === 0) {
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
reportScrollManager.scrollToIndex({animated: true, index: props.index}, false);
keyboardDidHideListener.remove();
});
}
}, [props.action, debouncedSaveDraft, props.index, props.reportID, reportScrollManager]);
/**
* 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();
const report = ReportUtils.getReport(props.reportID);
// Updates in child message should cause the parent draft message to change
if (report.parentReportActionID && lodashGet(props.action, 'childType', '') === CONST.REPORT.TYPE.CHAT) {
if (lodashGet(props.drafts, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${report.parentReportID}_${props.action.reportActionID}`], undefined)) {
Report.saveReportActionDraft(report.parentReportID, props.action.reportActionID, trimmedNewDraft);
}
}
// Updates in the parent message should cause the child draft message to change
if (props.action.childReportID) {
if (lodashGet(props.drafts, [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${props.action.childReportID}_${props.action.reportActionID}`], undefined)) {
Report.saveReportActionDraft(props.action.childReportID, props.action.reportActionID, trimmedNewDraft);
}
}
// When user tries to save the empty message, it will delete it. Prompt the user to confirm deleting.
if (!trimmedNewDraft) {
ReportActionContextMenu.showDeleteModal(props.reportID, props.action, false, deleteDraft, () => InteractionManager.runAfterInteractions(() => textInputRef.current.focus()));
return;
}
Report.editReportComment(props.reportID, props.action, trimmedNewDraft);
deleteDraft();
}, [props.action, debouncedSaveDraft, deleteDraft, draft, props.reportID, props.drafts]);
/**
* @param {String} emoji
*/
const addEmojiToTextBox = (emoji) => {
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) => {
if (!e || ComposerUtils.canSkipTriggerHotkeys(isSmallScreenWidth, isKeyboardShown)) {
return;
}
if (e.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey && !e.shiftKey) {
e.preventDefault();
publishDraft();
} else if (e.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
e.preventDefault();
deleteDraft();
}
},
[deleteDraft, isKeyboardShown, isSmallScreenWidth, publishDraft],
);
/**
* Focus the composer text input
*/
const focus = focusWithDelay(textInputRef.current);
return (
<>
<View style={[styles.chatItemMessage, styles.flexRow]}>
<View style={[styles.justifyContentEnd]}>
<Tooltip text={translate('common.cancel')}>
<PressableWithFeedback
onPress={deleteDraft}
style={styles.chatItemSubmitButton}
nativeID={cancelButtonID}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('common.close')}
// disable dimming
hoverDimmingValue={1}
pressDimmingValue={1}
hoverStyle={StyleUtils.getButtonBackgroundColorStyle(CONST.BUTTON_STATES.ACTIVE)}
pressStyle={StyleUtils.getButtonBackgroundColorStyle(CONST.BUTTON_STATES.PRESSED)}
>
{({hovered, pressed}) => (
<Icon
src={Expensicons.Close}
fill={StyleUtils.getIconFillColor(getButtonState(hovered, pressed))}
/>
)}
</PressableWithFeedback>
</Tooltip>
</View>
<View
style={[
isFocused ? styles.chatItemComposeBoxFocusedColor : styles.chatItemComposeBoxColor,
styles.flexRow,
styles.flex1,
styles.chatItemComposeBox,
hasExceededMaxCommentLength && styles.borderColorDanger,
]}
>
<View style={containerComposeStyles}>
<Composer
multiline
ref={(el) => {
textInputRef.current = el;
// eslint-disable-next-line no-param-reassign
props.forwardedRef.current = el;
}}
nativeID={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({animated: true, index: props.index}, true);
ComposerActions.setShouldShowComposeInput(false);
}}
onBlur={(event) => {
setIsFocused(false);
const relatedTargetId = lodashGet(event, 'nativeEvent.relatedTarget.id');
// Return to prevent re-render when save/cancel button is pressed which cancels the onPress event by re-rendering
if (_.contains([saveButtonID, cancelButtonID, emojiButtonID], relatedTargetId)) {
return;
}
if (messageEditInput === relatedTargetId) {
return;
}
openReportActionComposeViewWhenClosingMessageEdit();
}}
selection={selection}
onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
/>
</View>
<View style={styles.editChatItemEmojiWrapper}>
<EmojiPickerButton
isDisabled={props.shouldDisableEmojiPicker}
onModalHide={() => {
setIsFocused(true);
focus(true);
}}
onEmojiSelected={addEmojiToTextBox}
nativeID={emojiButtonID}
reportAction={props.action}
/>
</View>
<View style={styles.alignSelfEnd}>
<Tooltip text={translate('common.saveChanges')}>
<PressableWithFeedback
style={[styles.chatItemSubmitButton, hasExceededMaxCommentLength ? {} : styles.buttonSuccess]}
onPress={publishDraft}
nativeID={saveButtonID}
disabled={hasExceededMaxCommentLength}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('common.saveChanges')}
hoverDimmingValue={1}
pressDimmingValue={0.2}
>
<Icon
src={Expensicons.Checkmark}
fill={hasExceededMaxCommentLength ? themeColors.icon : themeColors.textLight}
/>
</PressableWithFeedback>
</Tooltip>
</View>
</View>
</View>
<ExceededCommentLength
comment={draft}
onExceededMaxCommentLength={(hasExceeded) => setHasExceededMaxCommentLength(hasExceeded)}
/>
</>
);
}
ReportActionItemMessageEdit.propTypes = propTypes;
ReportActionItemMessageEdit.defaultProps = defaultProps;
ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit';
export default compose(
withLocalize,
withReportActionsDrafts({
propName: 'drafts',
}),
)(
React.forwardRef((props, ref) => (
<ReportActionItemMessageEdit
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
)),
);