Skip to content

Commit 9825902

Browse files
authored
fix: multichar trigger replaces entire text (#220)
1 parent 00c81ba commit 9825902

File tree

3 files changed

+27
-6
lines changed

3 files changed

+27
-6
lines changed

cypress/integration/textarea.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,16 @@ describe("React Textarea Autocomplete", () => {
339339
cy.get(".rta__textarea").should("have.value", "This is test test2");
340340
});
341341

342+
// https://github.com/webscopeio/react-textarea-autocomplete/issues/219
343+
it("test multi-character trigger doesn't replace entire text", () => {
344+
cy.get(".rta__textarea").type("This is test /filtere");
345+
cy.get(".rta__autocomplete").should("be.visible");
346+
cy.get(".rta__list")
347+
.get("li:nth-child(1)")
348+
.click();
349+
cy.get(".rta__textarea").should("have.value", "This is test emily");
350+
});
351+
342352
it("change value from outside should trigger the autocomplete as well", () => {
343353
cy.get(".rta__autocomplete").should("not.be.visible");
344354
cy.get('[data-test="changeValueTo"]').click();

example/App.jsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,17 @@ class App extends React.Component {
367367
component: Item,
368368
output: this._outputCaretEnd
369369
},
370+
"/filter": {
371+
dataProvider: token => [
372+
{ name: "a", char: "amy" },
373+
{ name: "b", char: "ben" },
374+
{ name: "c", char: "cheryl" },
375+
{ name: "d", char: "daniel" },
376+
{ name: "e", char: "emily" }
377+
].filter(x => x.name == token.slice(6) || token.length === 6),
378+
component: Item,
379+
output: this._outputCaretEnd
380+
},
370381
"(": {
371382
dataProvider: token => [
372383
{ name: "country", char: "country" },

src/Textarea.jsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -435,14 +435,14 @@ class ReactTextareaAutocomplete extends React.Component<
435435

436436
const textToModify = textareaValue.slice(0, selectionEnd);
437437

438+
/**
439+
* It's important to escape the currentTrigger char for chars like [, (,...
440+
*/
441+
const escapedCurrentTrigger = escapeRegex(currentTrigger);
442+
const escapedCurrentTriggerWithWhitespace = escapedCurrentTrigger + (trigger[currentTrigger].allowWhitespace ? "" : "\\s");
438443
const startOfTokenPosition = textToModify.search(
439-
/**
440-
* It's important to escape the currentTrigger char for chars like [, (,...
441-
*/
442444
new RegExp(
443-
`${escapeRegex(currentTrigger)}${`[^${escapeRegex(currentTrigger)}${
444-
trigger[currentTrigger].allowWhitespace ? "" : "\\s"
445-
}]`}*$`
445+
`${escapedCurrentTrigger}((?!${escapedCurrentTriggerWithWhitespace}).)*$`
446446
)
447447
);
448448

0 commit comments

Comments
 (0)