import {controllerFactory} from '@utils/createController' import {useIntersection} from 'stimulus-use' export default class InputFilterController extends controllerFactory()({ targets: { emptyRoot: null, input: HTMLInputElement, searchString: null, }, }) { private items: {el: HTMLElement; searchString: string}[] private handleNewQuery(query: string) { let foundSomething = false for (const {el, searchString} of this.items) { const contains = searchString.includes(query.trim().toLowerCase()) if (!foundSomething && contains) foundSomething = true if (contains) { el.classList.remove('ariadne-hidden') } else { el.classList.add('ariadne-hidden') } } if (foundSomething) { this.emptyRootTarget.classList.add('ariadne-hidden') } else { this.emptyRootTarget.classList.remove('ariadne-hidden') } } connect() { this.items = this.searchStringTargets.map((el: HTMLElement) => { return { el, searchString: (el.textContent ?? '').trim().toLowerCase(), } }) useIntersection(this) } appear() { this.reset() } handleInput() { if (this.hasSearchStringTarget) this.handleNewQuery(this.inputTarget.value) } reset() { this.handleNewQuery('') if (this.hasInputTarget) this.inputTarget.value = '' } }