From 6af9af95831577e39e9f304c4884b221aa671d16 Mon Sep 17 00:00:00 2001 From: Bauke Date: Thu, 14 Dec 2023 13:11:02 +0100 Subject: [PATCH] Clean up some autocomplete handling. --- .../content-scripts/features/autocomplete.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/source/content-scripts/features/autocomplete.tsx b/source/content-scripts/features/autocomplete.tsx index ba68cf3..185be04 100644 --- a/source/content-scripts/features/autocomplete.tsx +++ b/source/content-scripts/features/autocomplete.tsx @@ -65,9 +65,10 @@ export class AutocompleteFeature extends Component { } globalInputHandler = (event: CompositionEvent | KeyboardEvent) => { - const activeElement = document.activeElement as HTMLElement; + const textarea = event.target; + // Only add the autocompletes to textareas. - if (activeElement.tagName !== "TEXTAREA") { + if (!(textarea instanceof HTMLTextAreaElement)) { return; } @@ -80,13 +81,17 @@ export class AutocompleteFeature extends Component { const dataAttribute = `data-trx-autocomplete-${target}`; const key = event instanceof KeyboardEvent ? event.key : event.data; - if (key === prefix && !activeElement.getAttribute(dataAttribute)) { - activeElement.setAttribute(dataAttribute, "true"); - activeElement.addEventListener("keyup", (event) => { - this.textareaInputHandler(event, prefix, target, values); + if (key === prefix && !textarea.getAttribute(dataAttribute)) { + textarea.setAttribute(dataAttribute, "true"); + textarea.addEventListener("keyup", (event) => { + if (!(event.target instanceof HTMLTextAreaElement)) { + return; + } + + this.textareaInputHandler(event.target, prefix, target, values); }); - this.textareaInputHandler(event, prefix, target, values); + this.textareaInputHandler(textarea, prefix, target, values); } }; @@ -95,12 +100,11 @@ export class AutocompleteFeature extends Component { }; textareaInputHandler = ( - event: CompositionEvent | KeyboardEvent, + textarea: HTMLTextAreaElement, prefix: string, target: string, values: Set, ) => { - const textarea = event.target as HTMLTextAreaElement; const text = textarea.value; // If the prefix isn't in the textarea, return early. @@ -129,7 +133,9 @@ export class AutocompleteFeature extends Component { // Find all the values that match the input using `includes`. const matches = new Set( - [...values].filter((value) => value.includes(input.toLowerCase())), + [...values].filter((value) => + value.toLowerCase().includes(input.toLowerCase()), + ), ); // If there are no matches, return early.