Sha256: c36a3924a740fe9c2487ff25a1e2acc8382b48a5d6e4c2c40c1ffedef2b73e2e

Contents?: true

Size: 1003 Bytes

Versions: 1

Compression:

Stored size: 1003 Bytes

Contents

import { Controller } from "@hotwired/stimulus"
import { debounce } from "https://cdn.skypack.dev/lodash-es@4.17.21?min"

export default class extends Controller {
  static targets = [ "list" ]
  static classes = [ "active", "selected" ]

  initialize() {
    this.filter = debounce(this.filter.bind(this), 300)
  }

  filter({ target }) {
    this.#reset()

    if (target.value != "") {
      this.#selectMatches(target.value)
      this.#activate()
    } else {
      this.#deactivate()
    }
  }

  #reset() {
    this.listTarget.querySelectorAll(`.${this.selectedClass}`).forEach((element) => {
      element.classList.remove(this.selectedClass)
    })
  }

  #selectMatches(value) {
    this.listTarget.querySelectorAll(`[data-value*="${value.toLowerCase()}"]`).forEach((element) => {
      element.classList.add(this.selectedClass)
    })
  }

  #activate() {
    this.listTarget.classList.add(this.activeClass)
  }

  #deactivate() {
    this.listTarget.classList.remove(this.activeClass)
  }
}

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
css-zero-0.0.84 lib/generators/css_zero/add/templates/app/javascript/controllers/filter_controller.js