Sha256: b9d91fd3aa6fbfb9182c9b9cf39f863f56ac98a5a8c4f52036bedf1c31343de4

Contents?: true

Size: 1.93 KB

Versions: 10

Compression:

Stored size: 1.93 KB

Contents

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = [ "checkbox", "toggleCheckbox", "toggleLabel", "wrapper" ]
  static classes = [ "unavailable" ]
  
  connect() {
    this.enableSelectAll()
  }
  
  enableSelectAll() {
    if (!this.hasWrapperTarget) { return }
    if (!this.hasUnavailableClass) { return }
    
    this.wrapperTarget.classList.remove(this.unavailableClass)
    this.updateToggle()
  }
  
  selectAllOrNone(event) {
    event.preventDefault()
    event.stopPropagation()
    if (this.allSelected) {
      this.selectNone()
    } else {
      this.selectAll()
    }
    this.updateToggle()
    this.dispatch('toggled')
  }
  
  selectAll() {
    this.checkboxTargets.forEach(checkbox => {
      checkbox.checked = true
    })
  }
  
  selectNone() {
    this.checkboxTargets.forEach(checkbox => {
      checkbox.checked = false
    })
  }
  
  updateToggle() {
    if (!this.hasToggleCheckboxTarget) { return }
    let checkbox = this.toggleCheckboxTarget
    let useAlternateLabel = false
    
    if (this.allSelected) {
      if (checkbox) {
        checkbox.checked = true
        checkbox.indeterminate = false
      }
      useAlternateLabel = true
    } else if (this.selectedValues.length > 0) {
      if (checkbox) {
        checkbox.indeterminate = true
      }
    } else {
      if (checkbox) {
        checkbox.checked = false
        checkbox.indeterminate = false
      }
    }
    
    if (this.hasToggleLabelTarget) {
      this.toggleLabelTarget.dispatchEvent(new CustomEvent(`${this.identifier}:toggle-select-all-label`, { detail: { useAlternate: useAlternateLabel }} ))
    }
  }
  
  get selectedValues() {
    let values = []
    this.checkboxTargets.forEach(checkbox => {
      if (checkbox.checked) {
        values.push(checkbox.value)
      }
    })
    return values
  }
  
  get allSelected() {
    return this.selectedValues.length === this.checkboxTargets.length
  }
}

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
bullet_train-1.14.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.13.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.12.3 app/javascript/controllers/select_all_controller.js
bullet_train-1.12.2 app/javascript/controllers/select_all_controller.js
bullet_train-1.12.1 app/javascript/controllers/select_all_controller.js
bullet_train-1.12.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.11.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.10.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.9.0 app/javascript/controllers/select_all_controller.js
bullet_train-1.8.5 app/javascript/controllers/select_all_controller.js