-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportActionItemMessageEdit.js
309 lines (280 loc) · 12.7 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
import lodashGet from 'lodash/get';
import React 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 reportActionPropTypes from './reportActionPropTypes';
import styles from '../../../styles/styles';
import Composer from '../../../components/Composer';
import * as Report from '../../../libs/actions/Report';
import * as ReportScrollManager from '../../../libs/ReportScrollManager';
import toggleReportActionComposeView from '../../../libs/toggleReportActionComposeView';
import openReportActionComposeViewWhenClosingMessageEdit from '../../../libs/openReportActionComposeViewWhenClosingMessageEdit';
import Button from '../../../components/Button';
import ReportActionComposeFocusManager from '../../../libs/ReportActionComposeFocusManager';
import compose from '../../../libs/compose';
import EmojiPickerButton from '../../../components/EmojiPicker/EmojiPickerButton';
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 withWindowDimensions, {windowDimensionsPropTypes} from '../../../components/withWindowDimensions';
import withLocalize, {withLocalizePropTypes} from '../../../components/withLocalize';
import withKeyboardState, {keyboardStatePropTypes} from '../../../components/withKeyboardState';
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: PropTypes.func,
/** 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,
...withLocalizePropTypes,
...windowDimensionsPropTypes,
...keyboardStatePropTypes,
};
const defaultProps = {
forwardedRef: () => {},
report: {},
shouldDisableEmojiPicker: false,
};
class ReportActionItemMessageEdit extends React.Component {
constructor(props) {
super(props);
this.updateDraft = this.updateDraft.bind(this);
this.deleteDraft = this.deleteDraft.bind(this);
this.debouncedSaveDraft = _.debounce(this.debouncedSaveDraft.bind(this), 1000);
this.publishDraft = this.publishDraft.bind(this);
this.triggerSaveOrCancel = this.triggerSaveOrCancel.bind(this);
this.onSelectionChange = this.onSelectionChange.bind(this);
this.addEmojiToTextBox = this.addEmojiToTextBox.bind(this);
this.saveButtonID = 'saveButton';
this.cancelButtonID = 'cancelButton';
this.emojiButtonID = 'emojiButton';
this.messageEditInput = 'messageEditInput';
const parser = new ExpensiMark();
const draftMessage = parser.htmlToMarkdown(this.props.draftMessage);
this.state = {
draft: draftMessage,
selection: {
start: draftMessage.length,
end: draftMessage.length,
},
isFocused: false,
};
}
/**
* Update Selection on change cursor position.
*
* @param {Event} e
*/
onSelectionChange(e) {
this.setState({selection: e.nativeEvent.selection});
}
/**
* Update the value of the draft in Onyx
*
* @param {String} draft
*/
updateDraft(draft) {
const newDraft = EmojiUtils.replaceEmojis(draft, this.props.isSmallScreenWidth);
this.setState((prevState) => {
const newState = {draft: newDraft};
if (draft !== newDraft) {
const remainder = prevState.draft.slice(prevState.selection.end).length;
newState.selection = {
start: newDraft.length - remainder,
end: newDraft.length - remainder,
};
}
return newState;
});
// 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) {
this.debouncedSaveDraft(newDraft);
} else {
this.debouncedSaveDraft(this.props.action.message[0].html);
}
}
/**
* Delete the draft of the comment being edited. This will take the comment out of "edit mode" with the old content.
*/
deleteDraft() {
this.debouncedSaveDraft.cancel();
Report.saveReportActionDraft(this.props.reportID, this.props.action.reportActionID, '');
toggleReportActionComposeView(true, this.props.isSmallScreenWidth);
ReportActionComposeFocusManager.focus();
// Scroll to the last comment after editing to make sure the whole comment is clearly visible in the report.
if (this.props.index === 0) {
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
ReportScrollManager.scrollToIndex({animated: true, index: this.props.index}, false);
keyboardDidHideListener.remove();
});
}
}
/**
* 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
*/
debouncedSaveDraft(newDraft) {
Report.saveReportActionDraft(this.props.reportID, this.props.action.reportActionID, newDraft);
}
/**
* 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.
*/
publishDraft() {
// Do nothing if draft exceed the character limit
if (ReportUtils.getCommentLength(this.state.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.
this.debouncedSaveDraft.cancel();
const trimmedNewDraft = this.state.draft.trim();
// When user tries to save the empty message, it will delete it. Prompt the user to confirm deleting.
if (!trimmedNewDraft) {
ReportActionContextMenu.showDeleteModal(
this.props.reportID,
this.props.action,
false,
this.deleteDraft,
() => InteractionManager.runAfterInteractions(() => this.textInput.focus()),
);
return;
}
Report.editReportComment(this.props.reportID, this.props.action, trimmedNewDraft);
this.deleteDraft();
}
/**
* @param {String} emoji
*/
addEmojiToTextBox(emoji) {
const newComment = this.state.draft.slice(0, this.state.selection.start)
+ emoji + this.state.draft.slice(this.state.selection.end, this.state.draft.length);
this.setState(prevState => ({
selection: {
start: prevState.selection.start + emoji.length,
end: prevState.selection.start + emoji.length,
},
}));
this.updateDraft(newComment);
}
/**
* Key event handlers that short cut to saving/canceling.
*
* @param {Event} e
*/
triggerSaveOrCancel(e) {
// Do not trigger actions for mobileWeb or native clients that have the keyboard open because for those devices, we want the return key to insert newlines rather than submit the form
if (!e || this.props.isSmallScreenWidth || this.props.isKeyboardShown) {
return;
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.publishDraft();
} else if (e.key === 'Escape') {
e.preventDefault();
this.deleteDraft();
}
}
render() {
const draftLength = ReportUtils.getCommentLength(this.state.draft);
const hasExceededMaxCommentLength = draftLength > CONST.MAX_COMMENT_LENGTH;
return (
<View style={styles.chatItemMessage}>
<View
style={[
styles.chatItemComposeBox,
styles.flexRow,
this.state.isFocused ? styles.chatItemComposeBoxFocusedColor : styles.chatItemComposeBoxColor,
hasExceededMaxCommentLength && styles.borderColorDanger,
]}
>
<Composer
multiline
ref={(el) => {
this.textInput = el;
this.props.forwardedRef(el);
}}
nativeID={this.messageEditInput}
onChangeText={this.updateDraft} // Debounced saveDraftComment
onKeyPress={this.triggerSaveOrCancel}
value={this.state.draft}
maxLines={16} // This is the same that slack has
style={[styles.textInputCompose, styles.flex4, styles.editInputComposeSpacing]}
onFocus={() => {
this.setState({isFocused: true});
ReportScrollManager.scrollToIndex({animated: true, index: this.props.index}, true);
toggleReportActionComposeView(false, this.props.isSmallScreenWidth);
}}
onBlur={(event) => {
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([this.saveButtonID, this.cancelButtonID, this.emojiButtonID], relatedTargetId)) {
return;
}
this.setState({isFocused: false});
if (this.messageEditInput === relatedTargetId) {
return;
}
openReportActionComposeViewWhenClosingMessageEdit(this.props.isSmallScreenWidth);
}}
selection={this.state.selection}
onSelectionChange={this.onSelectionChange}
/>
<View style={styles.editChatItemEmojiWrapper}>
<EmojiPickerButton
isDisabled={this.props.shouldDisableEmojiPicker}
onModalHide={() => InteractionManager.runAfterInteractions(() => this.textInput.focus())}
onEmojiSelected={this.addEmojiToTextBox}
nativeID={this.emojiButtonID}
/>
</View>
</View>
<View style={[styles.flexRow, styles.mt1]}>
<Button
small
style={[styles.mr2]}
nativeID={this.cancelButtonID}
onPress={this.deleteDraft}
text={this.props.translate('common.cancel')}
/>
<Button
small
success
isDisabled={hasExceededMaxCommentLength}
nativeID={this.saveButtonID}
style={[styles.mr2]}
onPress={this.publishDraft}
text={this.props.translate('common.saveChanges')}
/>
<ExceededCommentLength commentLength={draftLength} />
</View>
</View>
);
}
}
ReportActionItemMessageEdit.propTypes = propTypes;
ReportActionItemMessageEdit.defaultProps = defaultProps;
export default compose(
withLocalize,
withWindowDimensions,
withKeyboardState,
)(React.forwardRef((props, ref) => (
/* eslint-disable-next-line react/jsx-props-no-spreading */
<ReportActionItemMessageEdit {...props} forwardedRef={ref} />
)));