Sha256: 846854df0e6b79cebe7647fdac0ff874d338db3d1f4082c31bbf3823f66a7a35

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

import { Controller } from "@hotwired/stimulus"
import { debounce } from "https://cdn.skypack.dev/es-toolkit@v1.27.0/function"

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)
    this.dispatch("after")
  }

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

Version data entries

1 entries across 1 versions & 1 rubygems

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