Sha256: dbd543a0cc421d2ad622e35f75940bd37f5b441879484fee5e7d09b42f597b25

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 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

4 entries across 4 versions & 1 rubygems

Version Path
headmin-0.3.4 app/assets/javascripts/headmin/controllers/filter_controller.js
headmin-0.3.3 app/assets/javascripts/headmin/controllers/filter_controller.js
headmin-0.3.2 app/assets/javascripts/headmin/controllers/filter_controller.js
headmin-0.3.1 app/assets/javascripts/headmin/controllers/filter_controller.js