Skip to content

Commit 712c794

Browse files
authored
fix: take the last possible occurence of token (#81)
When we match trigger char in the text ":" for example, we should return the last possible occurence. Let's have a text "text:smile:good_smile" it this situation we should return ":good_smile" not ":smile:good_smile" CLOSE #61 #62
1 parent 3dd9c28 commit 712c794

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/Textarea.jsx

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,9 @@ class ReactTextareaAutocomplete extends React.Component<
160160
*/
161161
new RegExp(
162162
`\\${currentTrigger}${
163-
trigger[currentTrigger].allowWhitespace ? '.' : '\\S'
163+
trigger[currentTrigger].allowWhitespace
164+
? '.'
165+
: `[^\\${currentTrigger}\\s]`
164166
}*$`
165167
)
166168
);
@@ -310,6 +312,12 @@ class ReactTextareaAutocomplete extends React.Component<
310312
// throw away if we resolved old trigger
311313
if (currentTrigger !== this.state.currentTrigger) return;
312314

315+
// if we haven't resolved any data let's close the autocomplete
316+
if (!data.length) {
317+
this._closeAutocomplete();
318+
return;
319+
}
320+
313321
this.setState({
314322
dataLoading: false,
315323
data,
@@ -330,7 +338,11 @@ class ReactTextareaAutocomplete extends React.Component<
330338
_createRegExp = () => {
331339
const { trigger } = this.props;
332340

333-
this.tokenRegExp = new RegExp(`[${Object.keys(trigger).join('')}][^\\s]*$`);
341+
// negative lookahead to match only the trigger + the actual token = "bladhwd:adawd:word test" => ":word"
342+
// https://stackoverflow.com/a/8057827/2719917
343+
this.tokenRegExp = new RegExp(
344+
`([${Object.keys(trigger).join('')}])(?:(?!\\1)[^\\s])*$`
345+
);
334346
};
335347

336348
_update({ value, trigger }: TextareaProps) {
@@ -490,7 +502,12 @@ class ReactTextareaAutocomplete extends React.Component<
490502
return;
491503
}
492504

493-
if (movePopupAsYouType || (top === null && left === null)) {
505+
if (
506+
movePopupAsYouType ||
507+
(top === null && left === null) ||
508+
// if we have single char - trigger it means we want to re-position the autocomplete
509+
lastToken.length === 1
510+
) {
494511
this.setState(getCaretCoordinates(textarea, selectionEnd));
495512
}
496513

0 commit comments

Comments
 (0)