From 2ab322adfedf6b0a83e8b8132c2fa2b9978b7978 Mon Sep 17 00:00:00 2001 From: Jorge Manrubia Date: Tue, 1 Jul 2025 09:42:22 +0200 Subject: [PATCH] Tidy up code to normalize text, extract text helpers --- app/javascript/controllers/filter_controller.js | 7 ++----- app/javascript/helpers/text_helpers.js | 10 ++++++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/app/javascript/controllers/filter_controller.js b/app/javascript/controllers/filter_controller.js index f4eadad02..688c46155 100644 --- a/app/javascript/controllers/filter_controller.js +++ b/app/javascript/controllers/filter_controller.js @@ -1,5 +1,6 @@ import { Controller } from "@hotwired/stimulus" import { debounce } from "helpers/timing_helpers" +import { filterMatches } from "helpers/text_helpers" export default class extends Controller { static targets = [ "input", "item" ] @@ -10,7 +11,7 @@ export default class extends Controller { filter() { this.itemTargets.forEach(item => { - if (this.#convertDiacritics(item.innerText).toLowerCase().includes(this.inputTarget.value.toLowerCase())) { + if (filterMatches(item.innerText, this.inputTarget.value)) { item.removeAttribute("hidden") } else { item.toggleAttribute("hidden", true) @@ -19,8 +20,4 @@ export default class extends Controller { this.dispatch("changed") } - - #convertDiacritics(text) { - return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "") - } } diff --git a/app/javascript/helpers/text_helpers.js b/app/javascript/helpers/text_helpers.js index 2a0a2dced..22593fe6f 100644 --- a/app/javascript/helpers/text_helpers.js +++ b/app/javascript/helpers/text_helpers.js @@ -1,3 +1,13 @@ export function isMultiLineString(string) { return /\r|\n/.test(string) } + +export function normalizeFilteredText(string) { + return string + .toLowerCase() + .normalize("NFD").replace(/[\u0300-\u036f]/g, "") // Remove diacritics +} + +export function filterMatches(text, potentialMatch) { + return normalizeFilteredText(text).includes(normalizeFilteredText(potentialMatch)) +}