forked from box/box-annotations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApprovalCommentForm.js
313 lines (280 loc) · 10.6 KB
/
ApprovalCommentForm.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
/* eslint-disable react/destructuring-assignment, react/no-access-state-in-setstate */
/**
* @flow
* @file Component for Approval comment form
*/
import * as React from 'react';
import noop from 'lodash/noop';
import classNames from 'classnames';
import { ContentState, EditorState } from 'draft-js';
import { FormattedMessage, injectIntl } from 'react-intl';
import Form from 'box-react-ui/lib/components/form-elements/form/Form';
import DraftJSMentionSelector, {
DraftMentionDecorator
} from 'box-react-ui/lib/components/form-elements/draft-js-mention-selector';
import commonMessages from 'box-react-ui/lib/common/messages';
import AddApproval from './AddApproval';
import CommentInputControls from './CommentInputControls';
import Avatar from '../Avatar';
import messages from '../../messages';
import './ApprovalCommentForm.scss';
type Props = {
className: string,
createComment?: Function,
createTask?: Function,
updateTask?: Function,
getApproverWithQuery?: Function,
getMentionWithQuery?: Function,
intl: any,
isDisabled?: boolean,
isOpen: boolean,
approverSelectorContacts?: SelectorItems,
mentionSelectorContacts?: SelectorItems,
onCancel: Function,
onFocus: Function,
onSubmit: Function,
user: User,
isEditing?: boolean,
entityId?: string,
tagged_message?: string,
getAvatarUrl: string => Promise<?string>,
};
type State = {
approvalDate: ?Date,
approvers: SelectorItems,
approverSelectorError: string,
commentEditorState: any,
isAddApprovalVisible: boolean,
};
class ApprovalCommentForm extends React.Component<Props, State> {
static defaultProps = {
isOpen: false
};
state = {
approvalDate: null,
approvers: [],
approverSelectorError: '',
commentEditorState: EditorState.createWithContent(
ContentState.createFromText(this.props.tagged_message || ''),
DraftMentionDecorator,
),
isAddApprovalVisible: false
};
componentWillReceiveProps(nextProps: Props): void {
const { isOpen } = nextProps;
if (isOpen !== this.props.isOpen && !isOpen) {
this.setState({
commentEditorState: EditorState.createEmpty(
DraftMentionDecorator,
),
isAddApprovalVisible: false
});
}
}
onFormChangeHandler = (formData: any): void =>
this.setState({ isAddApprovalVisible: formData.addApproval === 'on' });
onFormValidSubmitHandler = (formData: any): void => {
const {
createComment = noop,
createTask = noop,
intl,
updateTask = noop,
onSubmit,
entityId
} = this.props;
const { text, hasMention } = this.getFormattedCommentText();
if (!text) {
return;
}
if (formData.addApproval === 'on') {
const { approvers, approvalDate } = this.state;
if (approvers.length === 0) {
this.setState({
approverSelectorError: intl.formatMessage(
commonMessages.requiredFieldError,
)
});
return;
}
createTask({
text,
assignees: approvers,
dueAt: approvalDate
});
} else if (entityId) {
updateTask({ text, id: entityId });
} else {
createComment({ text, hasMention });
}
if (onSubmit) {
onSubmit();
}
this.setState({
commentEditorState: EditorState.createEmpty(DraftMentionDecorator),
isAddApprovalVisible: false,
approvalDate: null,
approvers: []
});
};
onMentionSelectorChangeHandler = (nextEditorState: any): void =>
this.setState({ commentEditorState: nextEditorState });
onApprovalDateChangeHandler = (date: Date): void => {
this.setState({ approvalDate: date });
};
/**
* Formats the comment editor's text such that it will be accepted by the server.
*
* @returns {Object}
*/
getFormattedCommentText = (): { text: string, hasMention: boolean } => {
const { commentEditorState } = this.state;
const contentState = commentEditorState.getCurrentContent();
const blockMap = contentState.getBlockMap();
const resultStringArr = [];
// The API needs to explicitly know if a message contains a mention.
let hasMention = false;
// For all ContentBlocks in the ContentState:
blockMap.forEach((block) => {
const text = block.getText();
const blockMapStringArr = [];
// Break down the ContentBlock into ranges
block.findEntityRanges(
() => true,
(start, end) => {
const entityKey = block.getEntityAt(start);
// If the range is an Entity, format its text eg '@[1:Username]'
// Otherwise append its text to the block result as-is
if (entityKey) {
const entity = contentState.getEntity(entityKey);
const stringToAdd = `@[${
entity.getData().id
}:${text.substring(start + 1, end)}]`;
blockMapStringArr.push(stringToAdd);
hasMention = true;
} else {
blockMapStringArr.push(text.substring(start, end));
}
},
);
resultStringArr.push(blockMapStringArr.join(''));
});
// Concatentate the array of block strings with newlines
// (Each block represents a paragraph)
return { text: resultStringArr.join('\n'), hasMention };
};
handleApproverSelectorInput = (value: any): void => {
const { getApproverWithQuery = noop } = this.props;
getApproverWithQuery(value);
this.setState({ approverSelectorError: '' });
};
handleApproverSelectorSelect = (pills: any): void => {
this.setState({ approvers: this.state.approvers.concat(pills) });
};
handleApproverSelectorRemove = (option: any, index: number): void => { // eslint-disable-line
const approvers = this.state.approvers.slice();
approvers.splice(index, 1);
this.setState({ approvers });
};
render(): React.Node {
const {
approverSelectorContacts,
className,
createTask,
getMentionWithQuery,
intl: { formatMessage },
isDisabled,
isOpen,
mentionSelectorContacts = [],
onCancel,
onFocus,
user,
isEditing,
tagged_message,
getAvatarUrl
} = this.props;
const {
approvalDate,
approvers,
approverSelectorError,
commentEditorState,
isAddApprovalVisible
} = this.state;
const inputContainerClassNames = classNames(
'bcs-comment-input-container',
className,
{
'bcs-comment-input-is-open': isOpen
},
);
return (
<div className={inputContainerClassNames}>
{!isEditing && (
<div className='bcs-avatar-container'>
<Avatar getAvatarUrl={getAvatarUrl} user={user} />
</div>
)}
<div className='bcs-comment-input-form-container'>
<Form
onChange={this.onFormChangeHandler}
onValidSubmit={this.onFormValidSubmitHandler}
>
<DraftJSMentionSelector
className='bcs-comment-input'
contacts={isOpen ? mentionSelectorContacts : []}
editorState={commentEditorState}
hideLabel
isDisabled={isDisabled}
isRequired={isOpen}
name='commentText'
label='Comment'
onChange={this.onMentionSelectorChangeHandler}
onFocus={onFocus}
onMention={getMentionWithQuery}
placeholder={
tagged_message
? null
: formatMessage(messages.commentWrite)
}
validateOnBlur={false}
/>
<aside
className={classNames('bcs-at-mention-tip', {
'accessibility-hidden': isOpen,
})}
>
<FormattedMessage {...messages.atMentionTip} />
</aside>
{createTask ? (
<AddApproval
approvalDate={approvalDate}
approvers={approvers}
approverSelectorContacts={
approverSelectorContacts
}
approverSelectorError={approverSelectorError}
formatMessage={formatMessage}
isAddApprovalVisible={isAddApprovalVisible}
onApprovalDateChange={
this.onApprovalDateChangeHandler
}
onApproverSelectorInput={
this.handleApproverSelectorInput
}
onApproverSelectorRemove={
this.handleApproverSelectorRemove
}
onApproverSelectorSelect={
this.handleApproverSelectorSelect
}
/>
) : null}
<CommentInputControls onCancel={onCancel} />
</Form>
</div>
</div>
);
}
}
// For testing only
export { ApprovalCommentForm as ApprovalCommentFormUnwrapped };
export default injectIntl(ApprovalCommentForm);