-
Notifications
You must be signed in to change notification settings - Fork 15
/
composer.js
504 lines (421 loc) · 15.1 KB
/
composer.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
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
import React from 'react';
import PropTypes from 'prop-types';
import MarkdownIt from 'markdown-it';
import LinkSchemePlugin from 'markdown-it-linkscheme';
import Turndown from 'turndown';
import {escape, isFunction, isEmpty, unescape} from 'lodash';
import Quill from './quill';
import {
buildContents,
buildMentionAvatar,
buildMentionText,
getFirstName,
getMentions,
getQuillText,
keepReplacement,
replaceMentions,
addEmptyCheckToHandlerParams,
getKeyBindingDelta,
updateKeyBindings,
} from './utils';
import SanitizePlugin from './sanitize';
import './styles.scss';
// converts markdown to html
// options: break converts new line (\n) into <br> tags
const md = new MarkdownIt('commonmark', {breaks: true});
// converts html to markdown
// options: codeBlockStyle: 'fenced' will wrap code blocks around ``` rather than the default of indents
// keepReplacement: function that converts spark-mention tags to our placeholder mentions for conversion
const td = new Turndown({codeBlockStyle: 'fenced', keepReplacement});
// not a full sanitization plugin
// only converts < and > carots to their html entities
md.use(SanitizePlugin);
// add a scheme (ie: http://) to a link if it doesn't have one
md.use(LinkSchemePlugin);
// Turndown escapes markdown characters to prevent them from being compiled back to html
// We don't need this, so we're just going to return the text without any escaped characters
td.escape = (text) => text;
// Turndown tries to convert all html elements. This is a filter for the ones to keep
td.keep(['spark-mention']);
class Composer extends React.Component {
constructor(props) {
super(props);
this.quill = undefined;
this.insert = this.insert.bind(this);
this.handleEnter = this.handleEnter.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleMentionSelect = this.handleMentionSelect.bind(this);
this.handleMentionOpen = this.handleMentionOpen.bind(this);
this.handleMentionClose = this.handleMentionClose.bind(this);
this.saveToDraft = this.saveToDraft.bind(this);
this.openMentionList = this.openMentionList.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleClear = this.handleClear.bind(this);
}
componentDidMount() {
const {draft, emitter, keyBindings, placeholder} = this.props;
try {
emitter.on('INSERT_TEXT', this.insert);
emitter.on('SEND', this.handleEnter);
emitter.on('OPEN_MENTION', this.openMentionList);
emitter.on('FOCUS', this.handleFocus);
emitter.on('CLEAR', this.handleClear);
// binds additional util fnc to keybinding handler callback
const boundKeyBindings = addEmptyCheckToHandlerParams(keyBindings);
const bindings = {
enter: {
key: 13,
// need to bind our own this or else quill will bind their own and cause us to not be able to access other class methods
handler: this.handleEnter.bind(this),
},
tab: {
key: 9,
// disable tab in message composer
handler: () => {},
},
// key bindings from props will override our defaults above
...boundKeyBindings,
};
this.quill = new Quill('#quill-composer', {
modules: {
keyboard: {
bindings,
},
mention: {
dataAttributes: ['displayName', 'firstName', 'objectType', 'src', 'items', 'secondary'],
defaultMenuOrientation: 'top',
mentionDenotationChars: ['@'],
onSelect: this.handleMentionSelect,
onOpen: this.handleMentionOpen,
onClose: this.handleMentionClose,
renderItem: this.handleMentionItem,
source: this.handleMention.bind(this),
spaceAfterInsert: false,
},
toolbar: {
container: '#toolbar',
},
},
formats: [
// add format to enable during copy and paste
'mention',
// 'bold',
// 'list',
// 'italic',
// 'size',
// 'strike',
// 'underline',
// 'blockquote',
// 'indent',
// 'header',
// 'direction',
],
placeholder,
});
// inserts the initial text to the composer
// may contain formats as html tags, so convert those to markdowns
if (typeof draft?.value === 'string') {
// replace new lines with <br> tag and new line so it will display properly
// turndown will trim \n in text, so add a <br> tag since we want the line break
// but turndown doesn't trim them in code blocks, but will ignore <br> tags
const modified = draft.value.replace(/\n/g, '<br />\n');
// converts text from html to a string with markdown
// remove the extra new line before the close code fence
const text = td.turndown(modified).replace(/\n```/g, '```');
// there may be mentions, so convert it to deltas before we insert
const contents = buildContents(text);
this.quill.setContents(contents);
}
this.quill.on('text-change', this.handleTextChange);
} catch (e) {
let func = 'componentDidMount';
if (e.func) {
func += `->${e.func}`;
}
e.message = `${func}: ${e.message}`;
throw e;
}
}
componentDidUpdate(prevProps) {
const {draft, mentions, placeholder, keyBindings} = this.props;
try {
// checks if keybindings need to be updated
const keyBindingDelta = getKeyBindingDelta(prevProps.keyBindings, keyBindings);
if (!isEmpty(keyBindingDelta)) {
addEmptyCheckToHandlerParams(keyBindings);
updateKeyBindings(this.quill, keyBindingDelta, keyBindings);
}
const prevDraft = prevProps.draft;
// updates the text in the composer as we switch conversations
if (prevDraft.id !== draft.id) {
if (draft?.value) {
// there may be mentions, so convert it to deltas before we insert
const contents = buildContents(draft.value, mentions?.participants?.current);
this.quill.setContents(contents);
} else {
this.quill.setText('');
}
}
// update the placeholder if it changed
if (prevProps.placeholder !== placeholder) {
this.quill.root.dataset.placeholder = placeholder;
}
} catch (e) {
let func = 'componentDidUpdate';
if (e.func) {
func += `->${e.func}`;
}
e.message = `${func}: ${e.message}`;
throw e;
}
}
handleEnter() {
const {markdown, onError, send} = this.props;
try {
// markdown is enabled if undefined
const enableMarkdown = !markdown?.disabled;
// gets the text from the composer with mentions as a placeholder string
const text = getQuillText(this.quill).trim();
// gets the ids that were mentioned
const mentioned = getMentions(this.quill);
const hasMentions = mentioned.people.length || mentioned.group.length;
// if markdown is enabled, converts text from markdown to html
// if markdown is not enabled and there are mentions, escape all html to avoid injection
// otherwise just use the original text as the display name
let object = {displayName: text};
if (enableMarkdown) {
// render text to markdown and convert mention placeholders to elements
// pass in mentioned people so actual mentions are the only things converted
// new lines in the text will be represented with a br tag so no need to worry about them
// element tags will have new lines after them which we don't want so we remove them here too
const marked = replaceMentions(md.render(text).replace(/>\n/g, '>'), mentioned);
// after rendering text will have p tags around it
// remove these and check if there is any html remaining (including mentions)
// set content as rendered markdown with appropriate display name if there is
if (/<.+?>(?:.|\n)+<\/.+?>/.test(marked.replace(/<\/?p>/g, ''))) {
object = {
content: marked,
displayName: marked.replace(/<.+?>/g, ''),
};
}
} else if (hasMentions) {
// mentions will always be html so escape html in text before converting mentions
// pass in mentioned people so actual mentions are the only things converted
const escaped = replaceMentions(escape(text), mentioned);
// set content as the html escaped version of the rest of the text
// set display name as the unescaped version of the escaped content after removing mention tags
object = {
content: escaped,
displayName: unescape(escaped.replace(/<.+?>/g, '')),
};
}
// if there are mentions then include them in the object
if (mentioned.people.length) {
object.mentions = mentioned.people;
}
if (mentioned.group.length) {
object.groupMentions = mentioned.group;
}
object.mentionType = mentioned.mentionType;
// sends the message, if it succeeded then clear the composer
if (send(object)) {
// clear the composer and reset the draft
this.handleClear();
}
} catch (e) {
if (isFunction(onError)) {
let func = 'handleEnter';
if (e.func) {
func += `->${e.func}`;
}
onError('QuillComposer', func, e);
}
}
}
// When user types @, this renders the mention list
handleMention(searchTerm, renderList) {
const {onError} = this.props;
try {
const participants = this.props.mentions.participants.current;
let matches;
// Goes through the list and checks if the search term is in it
if (searchTerm.length === 0) {
matches = participants.slice(0, 20);
} else {
matches = [];
for (let i = 0; i < participants.length; i += 1) {
if (matches.length >= 20) {
// only show up to 20 people
break;
}
if (participants[i].displayName.toLowerCase().indexOf(searchTerm.toLowerCase()) >= 0) {
matches.push(participants[i]);
}
}
}
renderList(matches, searchTerm);
} catch (e) {
if (isFunction(onError)) {
onError('QuillComposer', 'handleMention', e);
}
}
}
// This renders each item in the mention list
// The return is set as the innerHTML of an element
handleMentionItem(item) {
const avatar = buildMentionAvatar(item);
const text = buildMentionText(item);
return `${avatar}${text}`;
}
// Called when user selects a mention item
handleMentionSelect(item, insertItem) {
const {mentions, onError} = this.props;
try {
const participants = mentions.participants.current;
let sanitizedItem;
const sanitizeMention = (mentionItem) => {
const copy = {...mentionItem};
const name = mentionItem.displayName;
const first = mentionItem.firstName || getFirstName(name);
// show just the first name unless someone else has the same first name
// check how many other participants have the same first name
const duplicates = participants.reduce((sum, participant) => {
const given = participant.firstName || getFirstName(participant.displayName);
return first === given ? sum + 1 : sum;
}, 0);
// if there is more than one of you, then show full name instead
copy.value = duplicates > 1 ? name : first;
return copy;
};
if (item.items) {
let modItems = JSON.parse(item.items);
modItems = modItems.map(sanitizeMention);
sanitizedItem = {...item, items: JSON.stringify(modItems), value: item.displayName};
} else {
sanitizedItem = sanitizeMention(item);
}
insertItem(sanitizedItem);
} catch (e) {
if (isFunction(onError)) {
onError('QuillComposer', 'handleMentionSelect', e);
}
}
}
handleMentionOpen() {
const {onMentionOpen} = this.props;
if (onMentionOpen) {
onMentionOpen();
}
}
handleMentionClose() {
const {onMentionClose} = this.props;
if (onMentionClose) {
onMentionClose();
}
}
handleTextChange(delta, oldDelta, source) {
const {notifyKeyDown} = this.props;
// only do these stuff if user initiated
if (source === 'user') {
if (notifyKeyDown) {
notifyKeyDown();
}
this.saveToDraft();
}
}
saveToDraft() {
const {draft} = this.props;
const text = getQuillText(this.quill);
if (draft?.save) {
draft.save(text, draft.id);
}
}
// Inserts text into the composer at cursor position
insert(text) {
const {onError} = this.props;
try {
let index = 0;
// position of cursor in the editor
const selection = this.quill.getSelection(true);
// this _should_ always be true, use the position of the cursor
if (selection) {
({index} = selection);
} else {
// but just in case it's not found, insert to the end as a backup
index = this.quill.getLength() - 1;
}
// insert the text and move cursor to after it
this.quill.insertText(index, text, 'user');
this.quill.setSelection(index + text.length);
} catch (e) {
if (isFunction(onError)) {
onError('QuillComposer', 'insert', e);
}
}
}
openMentionList() {
const length = this.quill.getLength();
const selection = this.quill.getSelection();
const index = selection ? selection.index : length - 1;
// to open the mention list, we need to clear the user's selection first
// then insert the @ character and set the selection to after the character
this.quill.setSelection();
this.quill.insertText(index, '@');
this.quill.setSelection(index + 1);
}
handleFocus() {
this.quill.focus();
// empty quill editor getLength returns 1, so it is safe to use length-1 to point to cursor index 0
const length = this.quill.getLength();
// position cursor at end of content, if any
this.quill.setSelection(length - 1);
}
handleClear() {
this.quill.setText('');
this.saveToDraft();
}
render() {
return <div id="quill-composer" />;
}
}
Composer.displayName = 'QuillComposer';
Composer.propTypes = {
draft: PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string,
save: PropTypes.func,
}),
emitter: PropTypes.shape({
on: PropTypes.func,
off: PropTypes.func,
emit: PropTypes.func,
}).isRequired,
keyBindings: PropTypes.object,
markdown: PropTypes.shape({
disabled: PropTypes.bool,
}),
mentions: PropTypes.shape({
participants: PropTypes.shape({
current: PropTypes.array,
}),
}),
notifyKeyDown: PropTypes.func,
onMentionClose: PropTypes.func,
onMentionOpen: PropTypes.func,
onError: PropTypes.func,
placeholder: PropTypes.string,
send: PropTypes.func,
};
Composer.defaultProps = {
draft: undefined,
keyBindings: {},
markdown: undefined,
mentions: undefined,
notifyKeyDown: undefined,
onMentionClose: undefined,
onMentionOpen: undefined,
onError: undefined,
placeholder: 'Compose something awesome...',
send: undefined,
};
export default Composer;