-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Textarea.jsx
1240 lines (1048 loc) 路 32.4 KB
/
Textarea.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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
/* eslint react/no-multi-comp: 0 */
import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
import getCaretCoordinates from "textarea-caret";
import CustomEvent from "custom-event";
import Listeners, { KEY_CODES } from "./listener";
import List from "./List";
import { defaultScrollToItem } from "./utilities";
import type {
TextareaProps,
TextareaState,
caretPositionType,
outputType,
triggerType,
settingType,
} from "./types";
const DEFAULT_CARET_POSITION = "next";
const POSITION_CONFIGURATION = {
X: {
LEFT: "rta__autocomplete--left",
RIGHT: "rta__autocomplete--right",
},
Y: {
TOP: "rta__autocomplete--top",
BOTTOM: "rta__autocomplete--bottom",
},
};
const errorMessage = (message: string) =>
console.error(
`RTA: dataProvider fails: ${message}
\nCheck the documentation or create issue if you think it's bug. https://github.com/webscopeio/react-textarea-autocomplete/issues`
);
const reservedRegexChars = [
".",
"^",
"$",
"*",
"+",
"-",
"?",
"(",
")",
"[",
"]",
"{",
"}",
"\\",
"|",
];
const escapeRegex = (text) =>
[...text]
.map((character) =>
reservedRegexChars.includes(character) ? `\\${character}` : character
)
.join("");
// The main purpose of this component is to figure out to which side the autocomplete should be opened
type AutocompleteProps = {
style: ?Object,
className: ?string,
innerRef: () => void,
boundariesElement: string | HTMLElement,
top: ?number,
left: ?number,
children: *,
textareaRef: HTMLElement,
renderToBody: ?boolean,
};
class Autocomplete extends React.Component<AutocompleteProps> {
containerElem: HTMLElement;
ref: HTMLElement;
componentDidMount() {
const { boundariesElement } = this.props;
if (typeof boundariesElement === "string") {
const elem = document.querySelector(boundariesElement);
if (!elem) {
throw new Error(
"RTA: Invalid prop boundariesElement: it has to be string or HTMLElement."
);
}
this.containerElem = elem;
} else if (boundariesElement instanceof HTMLElement) {
this.containerElem = boundariesElement;
} else {
throw new Error(
"RTA: Invalid prop boundariesElement: it has to be string or HTMLElement."
);
}
if (!this.containerElem || !this.containerElem.contains(this.ref)) {
if (process.env.NODE_ENV !== "test") {
throw new Error(
"RTA: Invalid prop boundariesElement: it has to be one of the parents of the RTA."
);
}
}
}
componentDidUpdate() {
const top = this.props.top || 0;
const left = this.props.left || 0;
const usedClasses = [];
const unusedClasses = [];
let topPosition = 0;
let leftPosition = 0;
const containerBounds = this.containerElem.getBoundingClientRect();
const dropdownBounds = this.ref.getBoundingClientRect();
const textareaBounds = this.props.textareaRef.getBoundingClientRect();
const computedStyle = window.getComputedStyle(this.ref);
const marginTop = parseInt(
computedStyle.getPropertyValue("margin-top"),
10
);
const marginBottom = parseInt(
computedStyle.getPropertyValue("margin-bottom"),
10
);
const marginLeft = parseInt(
computedStyle.getPropertyValue("margin-left"),
10
);
const marginRight = parseInt(
computedStyle.getPropertyValue("margin-right"),
10
);
const dropdownBottom =
marginTop +
marginBottom +
textareaBounds.top +
top +
dropdownBounds.height;
const dropdownRight =
marginLeft +
marginRight +
textareaBounds.left +
left +
dropdownBounds.width;
if (dropdownRight > containerBounds.right &&
textareaBounds.left + left > dropdownBounds.width) {
leftPosition = left - dropdownBounds.width;
usedClasses.push(POSITION_CONFIGURATION.X.LEFT);
unusedClasses.push(POSITION_CONFIGURATION.X.RIGHT);
} else {
leftPosition = left;
usedClasses.push(POSITION_CONFIGURATION.X.RIGHT);
unusedClasses.push(POSITION_CONFIGURATION.X.LEFT);
}
if (dropdownBottom > containerBounds.bottom &&
textareaBounds.top + top > dropdownBounds.height) {
topPosition = top - dropdownBounds.height;
usedClasses.push(POSITION_CONFIGURATION.Y.TOP);
unusedClasses.push(POSITION_CONFIGURATION.Y.BOTTOM);
} else {
topPosition = top;
usedClasses.push(POSITION_CONFIGURATION.Y.BOTTOM);
unusedClasses.push(POSITION_CONFIGURATION.Y.TOP);
}
if (this.props.renderToBody) {
topPosition += textareaBounds.top;
leftPosition += textareaBounds.left;
}
this.ref.style.top = `${topPosition}px`;
this.ref.style.left = `${leftPosition}px`;
this.ref.classList.remove(...unusedClasses);
this.ref.classList.add(...usedClasses);
}
render() {
const { style, className, innerRef, children, renderToBody } = this.props;
const body = document.body;
const autocompleteContainer = (
<div
ref={(ref) => {
// $FlowFixMe
this.ref = ref;
// $FlowFixMe
innerRef(ref);
}}
className={`rta__autocomplete ${className || ""}`}
style={style}
>
{children}
</div>
);
return renderToBody && body !== null
? ReactDOM.createPortal(autocompleteContainer, body)
: autocompleteContainer;
}
}
class ReactTextareaAutocomplete extends React.Component<
TextareaProps,
TextareaState
> {
static defaultProps = {
movePopupAsYouType: false,
value: null,
minChar: 1,
boundariesElement: "body",
scrollToItem: true,
textAreaComponent: "textarea",
renderToBody: false,
};
constructor(props: TextareaProps) {
super(props);
const { loadingComponent, trigger, value } = this.props;
if (value) this.state.value = value;
this._createRegExp();
if (!loadingComponent) {
throw new Error("RTA: loadingComponent is not defined");
}
if (!trigger) {
throw new Error("RTA: trigger is not defined");
}
}
state = {
top: null,
left: null,
currentTrigger: null,
actualToken: "",
data: null,
value: "",
dataLoading: false,
selectionEnd: 0,
component: null,
textToReplace: null,
};
escListenerInit = () => {
if (!this.escListener) {
this.escListener = Listeners.add(KEY_CODES.ESC, this._closeAutocomplete);
}
};
escListenerDestroy = () => {
if (this.escListener) {
Listeners.remove(this.escListener);
this.escListener = null;
}
};
componentDidMount() {
Listeners.startListen(this.textareaRef);
// handle caret change
this.textareaRef &&
this.textareaRef.addEventListener("focus", this._handleCaretChange);
this.textareaRef &&
this.textareaRef.addEventListener("click", this._handleCaretChange);
this.textareaRef &&
this.textareaRef.addEventListener("keydown", this._handleCaretChange);
}
componentDidUpdate({ trigger: oldTrigger, value: oldValue }: TextareaProps) {
const { trigger, value } = this.props;
if (Object.keys(trigger).join("") !== Object.keys(oldTrigger).join("")) {
this._createRegExp();
}
if (oldValue !== value && this.lastValueBubbledEvent !== value) {
this.lastTrigger = 0;
this._changeHandler();
}
}
static getDerivedStateFromProps({ value }: TextareaProps) {
if (value === null || value === undefined) return null;
return {
value,
};
}
componentWillUnmount() {
this.escListenerDestroy();
Listeners.stopListen(this.textareaRef);
// handle caret change
this.textareaRef &&
this.textareaRef.removeEventListener("focus", this._handleCaretChange);
this.textareaRef &&
this.textareaRef.removeEventListener("click", this._handleCaretChange);
this.textareaRef &&
this.textareaRef.removeEventListener("keydown", this._handleCaretChange);
}
getSelectionPosition = (): ?{|
selectionStart: number,
selectionEnd: number,
|} => {
if (!this.textareaRef) return null;
return {
selectionStart: this.textareaRef.selectionStart,
selectionEnd: this.textareaRef.selectionEnd,
};
};
getSelectedText = (): ?string => {
if (!this.textareaRef) return null;
const { selectionStart, selectionEnd } = this.textareaRef;
if (selectionStart === selectionEnd) return null;
return this.state.value.substr(
selectionStart,
selectionEnd - selectionStart
);
};
setCaretPosition = (position: number = 0) => {
if (!this.textareaRef) return;
this.textareaRef.focus();
this.textareaRef.setSelectionRange(position, position);
};
getCaretPosition = (): number => {
if (!this.textareaRef) {
return 0;
}
const position = this.textareaRef.selectionEnd;
return position;
};
_handleCaretChange = (e: Event) => {
const cleanLastTrigger = () => {
const beforeHandle = this.getCaretPosition() - 1;
this.lastTrigger = this.lastTrigger ? beforeHandle : 0;
};
if (e.type === "keydown") {
// $FlowFixMe
const code = e.keyCode || e.which;
switch (code) {
case KEY_CODES.UP:
case KEY_CODES.DOWN:
if (!this._isAutocompleteOpen()) {
cleanLastTrigger();
}
break;
case KEY_CODES.LEFT:
case KEY_CODES.RIGHT:
cleanLastTrigger();
break;
default:
}
return;
}
cleanLastTrigger();
};
_onSelect = (item: Object | string) => {
const { selectionEnd, currentTrigger, value: textareaValue } = this.state;
const { onItemSelected } = this.props;
if (!currentTrigger) return;
const getTextToReplaceForCurrentTrigger = this._getTextToReplace(
currentTrigger
);
if (!getTextToReplaceForCurrentTrigger) {
this._closeAutocomplete();
return;
}
const newToken = getTextToReplaceForCurrentTrigger(item);
if (!newToken) {
this._closeAutocomplete();
return;
}
if (onItemSelected) {
onItemSelected({
currentTrigger,
item,
});
}
const computeCaretPosition = (
position: caretPositionType,
token: string,
startToken: number
): number => {
switch (position) {
case "start":
return startToken;
case "next":
case "end":
return startToken + token.length;
default:
if (!Number.isInteger(position)) {
throw new Error(
'RTA: caretPosition should be "start", "next", "end" or number.'
);
}
return position;
}
};
const textToModify = textareaValue.slice(0, selectionEnd);
/**
* It's important to escape the currentTrigger char for chars like [, (,...
* This is a ridiculous dark magic, basically we found position of the last current token (from current trigger) and then we replace the text from that position (calculating the offset)
*/
const escapedCurrentTrigger = escapeRegex(currentTrigger);
const triggerOffset = textToModify.length - textToModify.lastIndexOf(currentTrigger);
const startOfTokenPosition = textToModify.search(
new RegExp(
`(?!${escapedCurrentTrigger})$`
)
) - triggerOffset;
// we add space after emoji is selected if a caret position is next
const newTokenString =
newToken.caretPosition === "next" ? `${newToken.text} ` : newToken.text;
const newCaretPosition = computeCaretPosition(
newToken.caretPosition,
newTokenString,
startOfTokenPosition
);
const modifiedText =
textToModify.substring(0, startOfTokenPosition) + newTokenString;
const newValue = textareaValue.replace(textToModify, modifiedText);
// set the new textarea value and after that set the caret back to its position
this.setState(
{
value: newValue,
dataLoading: false,
},
() => {
const insertedTrigger = this.tokenRegExpEnding.exec(newTokenString);
const insertedTriggerModifier = insertedTrigger
? insertedTrigger[0].length
: 1;
this.lastTrigger = newCaretPosition
? newCaretPosition - insertedTriggerModifier
: newCaretPosition;
this.textareaRef.value = newValue;
this.textareaRef.selectionEnd = newCaretPosition;
this._changeHandler();
const scrollTop = this.textareaRef.scrollTop;
this.setCaretPosition(newCaretPosition);
/*
Chrome does not maintain scroll position
Relevant discussion https://github.com/webscopeio/react-textarea-autocomplete/pull/97
*/
if (window.chrome) {
this.textareaRef.scrollTop = scrollTop;
}
}
);
};
_getTextToReplace = (currentTrigger: string): ?outputType => {
const triggerSettings = this.props.trigger[currentTrigger];
if (!currentTrigger || !triggerSettings) return null;
const { output } = triggerSettings;
return (item: Object | string) => {
if (
typeof item === "object" &&
(!output || typeof output !== "function")
) {
throw new Error(
'Output functor is not defined! If you are using items as object you have to define "output" function. https://github.com/webscopeio/react-textarea-autocomplete#trigger-type'
);
}
if (output) {
const textToReplace = output(item, currentTrigger);
if (textToReplace === undefined || typeof textToReplace === "number") {
throw new Error(
`Output functor should return string or object in shape {text: string, caretPosition: string | number}.\nGot "${String(
textToReplace
)}". Check the implementation for trigger "${currentTrigger}"\n\nSee https://github.com/webscopeio/react-textarea-autocomplete#trigger-type for more information.\n`
);
}
if (textToReplace === null) return null;
if (typeof textToReplace === "string") {
return {
text: textToReplace,
caretPosition: DEFAULT_CARET_POSITION,
};
}
if (!textToReplace.text && typeof textToReplace.text !== 'string') {
throw new Error(
`Output "text" is not defined! Object should has shape {text: string, caretPosition: string | number}. Check the implementation for trigger "${currentTrigger}"\n`
);
}
if (!textToReplace.caretPosition) {
throw new Error(
`Output "caretPosition" is not defined! Object should has shape {text: string, caretPosition: string | number}. Check the implementation for trigger "${currentTrigger}"\n`
);
}
return textToReplace;
}
if (typeof item !== "string") {
throw new Error("Output item should be string\n");
}
return {
text: `${currentTrigger}${item}${currentTrigger}`,
caretPosition: DEFAULT_CARET_POSITION,
};
};
};
_getCurrentTriggerSettings = (): ?settingType => {
const { currentTrigger } = this.state;
if (!currentTrigger) return null;
return this.props.trigger[currentTrigger];
};
_getValuesFromProvider = () => {
const { currentTrigger, actualToken } = this.state;
const triggerSettings = this._getCurrentTriggerSettings();
if (!currentTrigger || !triggerSettings) {
return;
}
const { dataProvider, component } = triggerSettings;
if (typeof dataProvider !== "function") {
throw new Error("Trigger provider has to be a function!");
}
this.setState({
dataLoading: true,
});
let providedData = dataProvider(actualToken);
if (!(providedData instanceof Promise)) {
providedData = Promise.resolve(providedData);
}
providedData
.then((data) => {
if (!Array.isArray(data)) {
throw new Error("Trigger provider has to provide an array!");
}
if (typeof component !== "function") {
throw new Error("Component should be defined!");
}
// throw away if we resolved old trigger
if (currentTrigger !== this.state.currentTrigger) return;
// if we haven't resolved any data let's close the autocomplete
if (!data.length) {
this._closeAutocomplete();
return;
}
this.setState({
dataLoading: false,
data,
component,
});
})
.catch((e) => errorMessage(e.message));
};
_getSuggestions = (): ?Array<Object | string> => {
const { currentTrigger, data } = this.state;
if (!currentTrigger || !data || (data && !data.length)) return null;
return data;
};
_createRegExp = () => {
const { trigger } = this.props;
// negative lookahead to match only the trigger + the actual token = "bladhwd:adawd:word test" => ":word"
// https://stackoverflow.com/a/8057827/2719917
this.tokenRegExp = new RegExp(
`(${Object.keys(trigger)
// the sort is important for multi-char combos as "/kick", "/"
.sort((a, b) => {
if (a < b) {
return 1;
}
if (a > b) {
return -1;
}
return 0;
})
.map((a) => escapeRegex(a))
.join("|")})((?:(?!\\1)[^\\s])*$)`
);
this.tokenRegExpEnding = new RegExp(
`(${Object.keys(trigger)
// the sort is important for multi-char combos as "/kick", "/"
.sort((a, b) => {
if (a < b) {
return 1;
}
if (a > b) {
return -1;
}
return 0;
})
.map((a) => escapeRegex(a))
.join("|")})$`
);
};
/**
* Close autocomplete, also clean up trigger (to avoid slow promises)
*/
_closeAutocomplete = () => {
const { currentTrigger } = this.state;
this.escListenerDestroy();
this.setState(
{
data: null,
dataLoading: false,
currentTrigger: null,
},
() => {
if (currentTrigger) this._onItemHighlightedHandler(null);
}
);
};
_cleanUpProps = (): Object => {
const props = { ...this.props };
const notSafe = [
"loadingComponent",
"boundariesElement",
"containerStyle",
"minChar",
"scrollToItem",
"ref",
"innerRef",
"onChange",
"onCaretPositionChange",
"className",
"value",
"trigger",
"listStyle",
"itemStyle",
"containerStyle",
"loaderStyle",
"className",
"containerClassName",
"listClassName",
"itemClassName",
"loaderClassName",
"dropdownStyle",
"dropdownClassName",
"movePopupAsYouType",
"textAreaComponent",
"renderToBody",
"onItemSelected",
"onItemHighlighted",
];
// eslint-disable-next-line
for (const prop in props) {
if (notSafe.includes(prop)) delete props[prop];
}
return props;
};
_changeHandler = (e?: SyntheticInputEvent<*>) => {
const {
trigger,
onChange,
minChar,
onCaretPositionChange,
movePopupAsYouType,
} = this.props;
const { top, left } = this.state;
let event = e;
if (!event) {
// fire onChange event after successful selection
event = new CustomEvent("change", { bubbles: true });
this.textareaRef.dispatchEvent(event);
}
const textarea = event.target || this.textareaRef; // fallback to support Shadow DOM
const { selectionEnd } = textarea;
const value = textarea.value;
this.lastValueBubbledEvent = value;
if (onChange && event) {
event.persist && event.persist();
onChange(new Proxy(event, {
get(original, prop, receiver) {
if(prop === "target"){
return textarea;
}
return Reflect.get(original, prop, receiver);
}
}));
}
if (onCaretPositionChange) {
const caretPosition = this.getCaretPosition();
onCaretPositionChange(caretPosition);
}
this.setState({
value,
});
const setTopLeft = () => {
const { top: newTop, left: newLeft } = getCaretCoordinates(
textarea,
selectionEnd
);
this.setState({
// make position relative to textarea
top: newTop - this.textareaRef.scrollTop || 0,
left: newLeft,
});
};
const cleanLastTrigger = (triggerLength) => {
this.lastTrigger = selectionEnd - triggerLength;
this._closeAutocomplete();
setTopLeft();
};
if (selectionEnd <= this.lastTrigger) {
const affectedTextareaValue = value.slice(0, selectionEnd);
const newTrigger = this.tokenRegExp.exec(affectedTextareaValue);
cleanLastTrigger(newTrigger ? newTrigger[0].length : 0);
}
const affectedTextareaValue = value.slice(this.lastTrigger, selectionEnd);
let tokenMatch = this.tokenRegExp.exec(affectedTextareaValue);
let lastToken = tokenMatch && tokenMatch[0];
let currentTrigger = (tokenMatch && tokenMatch[1]) || null;
const currentTriggerLength = currentTrigger ? currentTrigger.length - 1 : 0;
// with this approach we want to know if the user just inserted a new trigger sequence
const newTrigger = this.tokenRegExpEnding.exec(affectedTextareaValue);
if (newTrigger) {
cleanLastTrigger(newTrigger[0].length);
} else if (!this._isAutocompleteOpen()) {
this._closeAutocomplete();
}
/*
if we lost the trigger token or there is no following character we want to close
the autocomplete
*/
if (
(!lastToken || lastToken.length <= minChar + currentTriggerLength) &&
// check if our current trigger disallows whitespace
((this.state.currentTrigger &&
!trigger[this.state.currentTrigger].allowWhitespace) ||
!this.state.currentTrigger)
) {
this._closeAutocomplete();
return;
}
/**
* This code has to be sync that is the reason why we obtain the currentTrigger
* from currentTrigger not this.state.currentTrigger
*
* Check if the currently typed token has to be afterWhitespace, or not.
*
* This setting means that there has to be whitespace before the token (on it has to be the the first character typed into textarea)
*/
if (
currentTrigger &&
trigger[currentTrigger].afterWhitespace &&
!/\s/.test(value[selectionEnd - lastToken.length - 1]) &&
value[selectionEnd - lastToken.length - 1] !== undefined
) {
this._closeAutocomplete();
return;
}
/**
If our current trigger allows whitespace
get the correct token for DataProvider, so we need to construct new RegExp
*/
if (
this.state.currentTrigger &&
trigger[this.state.currentTrigger].allowWhitespace
) {
tokenMatch = new RegExp(
`${escapeRegex(this.state.currentTrigger)}.*$`
).exec(value.slice(0, selectionEnd));
lastToken = tokenMatch && tokenMatch[0];
if (!lastToken) {
this._closeAutocomplete();
return;
}
currentTrigger =
Object.keys(trigger).find(
(a) =>
a.slice(0, currentTriggerLength + 1) ===
lastToken.slice(0, currentTriggerLength + 1)
) || null;
}
const actualToken = lastToken.slice(1);
// if trigger is not configured step out from the function, otherwise proceed
if (!currentTrigger) {
return;
}
if (
movePopupAsYouType ||
(top === null && left === null) ||
// if the trigger got changed, let's reposition the autocomplete
this.state.currentTrigger !== currentTrigger
) {
setTopLeft();
}
this.escListenerInit();
const textToReplace = this._getTextToReplace(currentTrigger);
this.setState(
{
selectionEnd,
currentTrigger,
textToReplace,
actualToken,
},
() => {
try {
this._getValuesFromProvider();
} catch (err) {
errorMessage(err.message);
}
}
);
};
_selectHandler = (e: SyntheticInputEvent<*>) => {
const { onCaretPositionChange, onSelect } = this.props;
if (onCaretPositionChange) {
const caretPosition = this.getCaretPosition();
onCaretPositionChange(caretPosition);
}
if (onSelect) {
e.persist();
onSelect(e);
}
};
_shouldStayOpen = (e: SyntheticFocusEvent<*>) => {
let el = e.relatedTarget;
// IE11 doesn't know about `relatedTarget` // https://stackoverflow.com/a/49325196/2719917
if (el === null) {
el = document.activeElement;
}
if (
this.dropdownRef &&
el instanceof Node &&
this.dropdownRef.contains(el)
) {
return true;
}
return false;
};
_onClick = (e: SyntheticFocusEvent<*>) => {
const { onClick } = this.props;
if (onClick) {
e.persist();
onClick(e);
}
if (this._shouldStayOpen(e)) {
return;
}
this._closeAutocomplete();
};
_onBlur = (e: SyntheticFocusEvent<*>) => {
const { onBlur } = this.props;
if (onBlur) {
e.persist();
onBlur(e);
}
if (this._shouldStayOpen(e)) {
return;
}
this._closeAutocomplete();
};
_onScrollHandler = () => {
this._closeAutocomplete();
};
_onItemHighlightedHandler = (item: Object | string | null) => {
const { onItemHighlighted } = this.props;
const { currentTrigger } = this.state;
if (onItemHighlighted) {
if (typeof onItemHighlighted === "function") {
onItemHighlighted({ currentTrigger, item });
} else {
throw new Error("`onItemHighlighted` has to be a function");
}
}
};
_dropdownScroll = (item: HTMLDivElement) => {
const { scrollToItem } = this.props;
if (!scrollToItem) return;
if (scrollToItem === true) {
defaultScrollToItem(this.dropdownRef, item);
return;
}
if (typeof scrollToItem !== "function" || scrollToItem.length !== 2) {
throw new Error(
"`scrollToItem` has to be boolean (true for default implementation) or function with two parameters: container, item."