Sha256: de7f6be3f8de68013d41e79f17f3edcda3a5ff72bc70c2518d5790760d4c477c

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  static get targets () {
    return ['button', 'popup']
  }

  // Attaches controller logic to the element itself
  // This allows calling controller methods from the element in other controllers
  connect () {
    this.element.controller = this

    // Clicked outside popup
    document.addEventListener('click', (event) => {
      this.handleOutsideClick(event)
    })
  }

  handleOutsideClick (event) {
    if (!this.isClickedInside(event)) {
      this.close()
    }
  }

  toggle (event) {
    const expanded = this.buttonTarget.getAttribute('aria-expanded') === 'true'
    if (expanded) {
      this.close(null)
    } else {
      this.open()
    }
  }

  open () {
    this.buttonTarget.setAttribute('aria-expanded', 'true')
    this.popupTarget.classList.remove('closed')
  }

  close (event) {
    this.buttonTarget.setAttribute('aria-expanded', 'false')
    this.popupTarget.classList.add('closed')
  }

  isClickedInside (event) {
    if (!event) {
      return false
    }
    const inPopup = this.popupTarget.contains(event.target)
    const inButton = this.buttonTarget.contains(event.target)
    const inAddButton = event.target.dataset.action === 'click->filters#add'
    return (inPopup || inButton || inAddButton)
  }
}

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
headmin-0.4.2 app/assets/javascripts/headmin/controllers/filter_controller.js
headmin-0.4.1 app/assets/javascripts/headmin/controllers/filter_controller.js
headmin-0.4.0 app/assets/javascripts/headmin/controllers/filter_controller.js