forked from mattermost/mattermost-webapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
suggestion_box.jsx
685 lines (569 loc) · 21.8 KB
/
suggestion_box.jsx
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import PropTypes from 'prop-types';
import React from 'react';
import EventEmitter from 'mattermost-redux/utils/event_emitter';
import QuickInput from 'components/quick_input.jsx';
import Constants from 'utils/constants.jsx';
import * as UserAgent from 'utils/user_agent.jsx';
import * as Utils from 'utils/utils.jsx';
const KeyCodes = Constants.KeyCodes;
export default class SuggestionBox extends React.Component {
static propTypes = {
/**
* The list component to render, usually SuggestionList
*/
listComponent: PropTypes.func.isRequired,
/**
* The date component to render
*/
dateComponent: PropTypes.func,
/**
* The value of in the input
*/
value: PropTypes.string.isRequired,
/**
* Array of suggestion providers
*/
providers: PropTypes.arrayOf(PropTypes.object),
/**
* Where the list will be displayed relative to the input box, defaults to 'top'
*/
listStyle: PropTypes.string,
/**
* CSS class for the div parent of the input box
*/
containerClass: PropTypes.string,
/**
* Set to true to draw dividers between types of list items, defaults to false
*/
renderDividers: PropTypes.bool,
/**
* Set to true to render a message when there were no results found, defaults to false
*/
renderNoResults: PropTypes.bool,
/**
* Set to allow TAB to select an item in the list, defaults to true
*/
completeOnTab: PropTypes.bool,
/**
* Function called when input box gains focus
*/
onFocus: PropTypes.func,
/**
* Function called when input box loses focus
*/
onBlur: PropTypes.func,
/**
* Function called when input box value changes
*/
onChange: PropTypes.func,
/**
* Function called when a key is pressed and the input box is in focus
*/
onKeyDown: PropTypes.func,
/**
* Function called when an item is selected
*/
onItemSelected: PropTypes.func,
/**
* Flags if the suggestion_box is for the RHS (Reply).
*/
isRHS: PropTypes.bool,
/**
* The number of characters required to show the suggestion list, defaults to 1
*/
requiredCharacters: PropTypes.number,
/**
* If true, the suggestion box is opened on focus, default to false
*/
openOnFocus: PropTypes.bool,
/**
* If true, the suggestion box is disabled
*/
disabled: PropTypes.bool,
/**
* If true, it displays allow to display a default list when empty
*/
openWhenEmpty: PropTypes.bool,
/**
* If true, replace all input in the suggestion box with the selected option after a select, defaults to false
*/
replaceAllInputOnSelect: PropTypes.bool,
/**
* An optional, opaque identifier that distinguishes the context in which the suggestion
* box is rendered. This allows the reused component to otherwise respond to changes.
*/
contextId: PropTypes.string,
/**
* If true, listen for clicks on a mention and populate the input with said mention, defaults to false
*/
listenForMentionKeyClick: PropTypes.bool,
}
static defaultProps = {
listStyle: 'top',
containerClass: '',
renderDividers: false,
renderNoResults: false,
completeOnTab: true,
isRHS: false,
requiredCharacters: 1,
openOnFocus: false,
openWhenEmpty: false,
replaceAllInputOnSelect: false,
listenForMentionKeyClick: false,
}
constructor(props) {
super(props);
// Keep track of whether we're composing a CJK character so we can make suggestions for partial characters
this.composing = false;
this.pretext = '';
// Used for debouncing pretext changes
this.timeoutId = '';
// pretext: the text before the cursor
// matchedPretext: a list of the text before the cursor that will be replaced if the corresponding autocomplete term is selected
// terms: a list of strings which the previously typed text may be replaced by
// items: a list of objects backing the terms which may be used in rendering
// components: a list of react components that can be used to render their corresponding item
// selection: the term currently selected by the keyboard
this.state = {
focused: false,
cleared: true,
matchedPretext: [],
items: [],
terms: [],
components: [],
selection: '',
allowDividers: true,
presentationType: 'text',
};
}
componentDidMount() {
if (this.props.listenForMentionKeyClick) {
EventEmitter.addListener('mention_key_click', this.handleMentionKeyClick);
}
}
componentWillUnmount() {
EventEmitter.removeListener('mention_key_click', this.handleMentionKeyClick);
}
componentDidUpdate(prevProps) {
if (prevProps.contextId !== this.props.contextId) {
const textbox = this.getTextbox();
const pretext = textbox.value.substring(0, textbox.selectionEnd).toLowerCase();
this.handlePretextChanged(pretext);
}
}
handleMentionKeyClick = (mentionKey, isRHS) => {
if (this.props.isRHS !== isRHS) {
return;
}
let insertText = '@' + mentionKey;
// if the current text does not end with a whitespace, then insert a space
if (this.props.value && (/[^\s]$/).test(this.props.value)) {
insertText = ' ' + insertText;
}
this.addTextAtCaret(insertText, '');
}
getTextbox = () => {
if (!this.refs.input) {
return null;
}
const input = this.refs.input.getInput();
if (input.getDOMNode) {
return input.getDOMNode();
}
return input;
}
recalculateSize = () => {
// Pretty hacky way to force an AutosizeTextarea to recalculate its height if that's what
// we're rendering as the input
const input = this.refs.input.getInput();
if (input.recalculateSize) {
input.recalculateSize();
}
}
handleEmitClearSuggestions = (delay = 0) => {
setTimeout(() => {
this.clear();
}, delay);
}
handleFocusOut = (e) => {
// Focus is switching TO e.relatedTarget, so only treat this as a blur event if we're not switching
// between children (like from the textbox to the suggestion list)
if (this.container.contains(e.relatedTarget)) {
return;
}
if (UserAgent.isIos() && !e.relatedTarget) {
// On Safari and iOS classic app, the autocomplete stays open
// when you tap outside of the post textbox or search box.
return;
}
this.handleEmitClearSuggestions();
this.setState({focused: false});
if (this.props.onBlur) {
this.props.onBlur();
}
};
handleFocusIn = (e) => {
// Focus is switching FROM e.relatedTarget, so only treat this as a focus event if we're not switching
// between children (like from the textbox to the suggestion list)
if (this.container.contains(e.relatedTarget)) {
return;
}
this.setState({focused: true});
if (this.props.openOnFocus || this.props.openWhenEmpty) {
setTimeout(() => {
const textbox = this.getTextbox();
if (textbox) {
const pretext = textbox.value.substring(0, textbox.selectionEnd);
if (this.props.openWhenEmpty || pretext.length >= this.props.requiredCharacters) {
this.handlePretextChanged(pretext);
}
}
});
}
if (this.props.onFocus) {
this.props.onFocus();
}
};
handleChange = (e) => {
const textbox = this.getTextbox();
const pretext = textbox.value.substring(0, textbox.selectionEnd).toLowerCase();
if (!this.composing && this.pretext !== pretext) {
this.handlePretextChanged(pretext);
}
if (this.props.onChange) {
this.props.onChange(e);
}
}
handleCompositionStart = () => {
this.composing = true;
}
handleCompositionUpdate = (e) => {
if (!e.data) {
return;
}
// The caret appears before the CJK character currently being composed, so re-add it to the pretext
const textbox = this.getTextbox();
const pretext = textbox.value.substring(0, textbox.selectionStart) + e.data;
this.pretext = pretext;
}
handleCompositionEnd = () => {
this.composing = false;
}
addTextAtCaret = (term, matchedPretext) => {
const textbox = this.getTextbox();
const caret = textbox.selectionEnd;
const text = this.props.value;
const pretext = textbox.value.substring(0, textbox.selectionEnd);
let prefix;
let keepPretext = false;
if (pretext.toLowerCase().endsWith(matchedPretext.toLowerCase())) {
prefix = pretext.substring(0, pretext.length - matchedPretext.length);
} else {
// the pretext has changed since we got a term to complete so see if the term still fits the pretext
const termWithoutMatched = term.substring(matchedPretext.length);
const overlap = SuggestionBox.findOverlap(pretext, termWithoutMatched);
keepPretext = overlap.length === 0;
prefix = pretext.substring(0, pretext.length - overlap.length - matchedPretext.length);
}
const suffix = text.substring(caret);
let newValue;
if (keepPretext) {
newValue = pretext;
} else {
newValue = prefix + term + ' ' + suffix;
}
textbox.value = newValue;
if (this.props.onChange) {
// fake an input event to send back to parent components
const e = {
target: textbox,
};
// don't call handleChange or we'll get into an event loop
this.props.onChange(e);
}
// set the caret position after the next rendering
window.requestAnimationFrame(() => {
if (textbox.value === newValue) {
Utils.setCaretPosition(textbox, prefix.length + term.length + 1);
}
});
}
replaceText = (term) => {
const textbox = this.getTextbox();
textbox.value = term;
if (this.props.onChange) {
// fake an input event to send back to parent components
const e = {
target: textbox,
};
// don't call handleChange or we'll get into an event loop
this.props.onChange(e);
}
}
handleCompleteWord = (term, matchedPretext) => {
if (this.props.replaceAllInputOnSelect) {
this.replaceText(term);
} else {
this.addTextAtCaret(term, matchedPretext);
}
if (this.props.onItemSelected) {
const items = this.state.items;
const terms = this.state.terms;
for (let i = 0; i < terms.length; i++) {
if (terms[i] === term) {
this.props.onItemSelected(items[i]);
break;
}
}
}
this.clear();
this.refs.input.focus();
for (const provider of this.props.providers) {
if (provider.handleCompleteWord) {
provider.handleCompleteWord(term, matchedPretext);
}
}
}
selectNext = () => {
this.setSelectionByDelta(1);
}
selectPrevious = () => {
this.setSelectionByDelta(-1);
}
setSelectionByDelta = (delta) => {
let selectionIndex = this.state.terms.indexOf(this.state.selection);
if (selectionIndex === -1) {
this.setState({
selection: '',
});
return;
}
selectionIndex += delta;
if (selectionIndex < 0) {
selectionIndex = 0;
} else if (selectionIndex > this.state.terms.length - 1) {
selectionIndex = this.state.terms.length - 1;
}
this.setState({
selection: this.state.terms[selectionIndex],
});
}
clear = () => {
this.setState({
cleared: true,
matchedPretext: [],
terms: [],
items: [],
components: [],
});
}
hasSuggestions = () => {
return this.state.items.some((item) => !item.loading);
}
handleKeyDown = (e) => {
if ((this.props.openWhenEmpty || this.props.value) && this.hasSuggestions()) {
if (Utils.isKeyPressed(e, KeyCodes.UP)) {
this.selectPrevious();
e.preventDefault();
} else if (Utils.isKeyPressed(e, KeyCodes.DOWN)) {
this.selectNext();
e.preventDefault();
} else if (Utils.isKeyPressed(e, KeyCodes.ENTER) || (this.props.completeOnTab && Utils.isKeyPressed(e, KeyCodes.TAB))) {
let matchedPretext = '';
for (let i = 0; i < this.state.terms.length; i++) {
if (this.state.terms[i] === this.state.selection) {
matchedPretext = this.state.matchedPretext[i];
}
}
// If these don't match, the user typed quickly and pressed enter before we could
// update the pretext, so update the pretext before completing
if (this.pretext.endsWith(matchedPretext)) {
this.handleCompleteWord(this.state.selection, matchedPretext);
} else {
clearTimeout(this.timeoutId);
this.nonDebouncedPretextChanged(this.pretext, true);
}
if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
e.preventDefault();
} else if (Utils.isKeyPressed(e, KeyCodes.ESCAPE)) {
this.clear();
this.setState({presentationType: 'text'});
e.preventDefault();
e.stopPropagation();
} else if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
} else if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
}
handleReceivedSuggestions = (suggestions) => {
const newComponents = [];
const newPretext = [];
for (let i = 0; i < suggestions.terms.length; i++) {
newComponents.push(suggestions.component);
newPretext.push(suggestions.matchedPretext);
}
const terms = suggestions.terms;
const items = suggestions.items;
let selection = this.state.selection;
if (terms.length > 0) {
// if the current selection is no longer in the map, select the first term in the list
if (!this.state.selection || terms.indexOf(this.state.selection) === -1) {
selection = terms[0];
}
} else if (this.state.selection) {
selection = '';
}
this.setState({
cleared: false,
selection,
terms,
items,
components: newComponents,
matchedPretext: newPretext,
});
return {selection, matchedPretext: suggestions.matchedPretext};
}
handleReceivedSuggestionsAndComplete = (suggestions) => {
const {selection, matchedPretext} = this.handleReceivedSuggestions(suggestions);
if (selection) {
this.handleCompleteWord(selection, matchedPretext);
}
}
nonDebouncedPretextChanged = (pretext, complete = false) => {
this.pretext = pretext;
let handled = false;
let callback = this.handleReceivedSuggestions;
if (complete) {
callback = this.handleReceivedSuggestionsAndComplete;
}
for (const provider of this.props.providers) {
handled = provider.handlePretextChanged(pretext, callback) || handled;
if (handled) {
this.setState({
presentationType: provider.presentationType(),
allowDividers: provider.allowDividers(),
});
break;
}
}
if (!handled) {
this.clear();
}
}
debouncedPretextChanged = (pretext) => {
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(() => this.nonDebouncedPretextChanged(pretext), Constants.SEARCH_TIMEOUT_MILLISECONDS);
};
handlePretextChanged = (pretext) => {
this.pretext = pretext;
this.debouncedPretextChanged(pretext);
}
blur = () => {
this.refs.input.blur();
}
setContainerRef = (container) => {
// Attach/detach event listeners that aren't supported by React
if (this.container) {
this.container.removeEventListener('focusin', this.handleFocusIn);
this.container.removeEventListener('focusout', this.handleFocusOut);
}
if (container) {
container.addEventListener('focusin', this.handleFocusIn);
container.addEventListener('focusout', this.handleFocusOut);
}
// Save ref
this.container = container;
};
render() {
const {
listComponent,
dateComponent,
listStyle,
renderNoResults,
...props
} = this.props;
const renderDividers = this.props.renderDividers && this.state.allowDividers;
// Don't pass props used by SuggestionBox
Reflect.deleteProperty(props, 'providers');
Reflect.deleteProperty(props, 'onChange'); // We use onInput instead of onChange on the actual input
Reflect.deleteProperty(props, 'onItemSelected');
Reflect.deleteProperty(props, 'completeOnTab');
Reflect.deleteProperty(props, 'isRHS');
Reflect.deleteProperty(props, 'requiredCharacters');
Reflect.deleteProperty(props, 'openOnFocus');
Reflect.deleteProperty(props, 'openWhenEmpty');
Reflect.deleteProperty(props, 'onFocus');
Reflect.deleteProperty(props, 'onBlur');
Reflect.deleteProperty(props, 'containerClass');
Reflect.deleteProperty(props, 'replaceAllInputOnSelect');
Reflect.deleteProperty(props, 'renderDividers');
Reflect.deleteProperty(props, 'contextId');
Reflect.deleteProperty(props, 'listenForMentionKeyClick');
// This needs to be upper case so React doesn't think it's an html tag
const SuggestionListComponent = listComponent;
const SuggestionDateComponent = dateComponent;
return (
<div
ref={this.setContainerRef}
className={this.props.containerClass}
>
<QuickInput
ref='input'
autoComplete='off'
{...props}
onInput={this.handleChange}
onCompositionStart={this.handleCompositionStart}
onCompositionUpdate={this.handleCompositionUpdate}
onCompositionEnd={this.handleCompositionEnd}
onKeyDown={this.handleKeyDown}
/>
{(this.props.openWhenEmpty || this.props.value.length >= this.props.requiredCharacters) && this.state.presentationType === 'text' &&
<SuggestionListComponent
ref='list'
open={this.state.focused}
pretext={this.pretext}
location={listStyle}
renderDividers={renderDividers}
renderNoResults={renderNoResults}
onCompleteWord={this.handleCompleteWord}
cleared={this.state.cleared}
matchedPretext={this.state.matchedPretext}
items={this.state.items}
terms={this.state.terms}
selection={this.state.selection}
components={this.state.components}
/>
}
{(this.props.openWhenEmpty || this.props.value.length >= this.props.requiredCharacters) && this.state.presentationType === 'date' &&
<SuggestionDateComponent
ref='date'
items={this.state.items}
terms={this.state.terms}
components={this.state.components}
matchedPretext={this.state.matchedPretext}
onCompleteWord={this.handleCompleteWord}
/>
}
</div>
);
}
// Finds the longest substring that's at both the end of b and the start of a. For example,
// if a = "firepit" and b = "pitbull", findOverlap would return "pit".
static findOverlap(a, b) {
const aLower = a.toLowerCase();
const bLower = b.toLowerCase();
for (let i = bLower.length; i > 0; i--) {
const substring = bLower.substring(0, i);
if (aLower.endsWith(substring)) {
return substring;
}
}
return '';
}
}