/* global CustomEvent */ import { Controller } from '@hotwired/stimulus' export default class extends Controller { static get targets () { return ['idCheckbox', 'item', 'form', 'selectButton', 'placeholder', 'count'] } connect () { this.validate() this.updateCount() } // Actions select () { this.dispatchSelectionEvent() } submitForm () { this.hidePlaceholder() this.triggerFormSubmission() } inputChange () { this.handleInputChange() this.updateCount() } // Methods hidePlaceholder() { this.placeholderTarget.classList.add('d-none') } handleInputChange() { this.validate() } dispatchSelectionEvent () { document.dispatchEvent( new CustomEvent( 'mediaSelectionSubmitted', { detail: { name: this.element.dataset.name, items: this.renderItemsForEvent(this.selectedItems()) } } ) ) } triggerFormSubmission () { this.formTarget.requestSubmit() } renderItemsForEvent (items) { return items.map((item) => this.renderItemForEvent(item)) } renderItemForEvent (item) { return { blobId: item.querySelector('input[type="checkbox"]').value, thumbnail: item.querySelector('.h-thumbnail') } } selectedItems () { return this.itemTargets.filter((item) => { const checkbox = item.querySelector('input[type="checkbox"]') return checkbox.checked }) } selectedItemsCount () { return this.selectedItems().length } minSelectedItems () { return parseInt(this.element.dataset.min, 10) || 0 } maxSelectedItems () { return parseInt(this.element.dataset.max, 10) || Infinity } validate () { if (this.isValid()) { this.enableSelectButton() } else { this.disableSelectButton() } } enableSelectButton () { this.selectButtonTarget.removeAttribute('disabled') } disableSelectButton () { this.selectButtonTarget.setAttribute('disabled', '') } isValid () { const count = this.selectedItemsCount() return count >= this.minSelectedItems() && count <= this.maxSelectedItems() } updateCount() { this.countTarget.innerHTML = this.idCheckboxTargets.filter(checkbox => checkbox.checked).length; } }