import { Controller } from '@hotwired/stimulus' import { useFetch } from '../mixins/use_fetch' export default class extends Controller { static targets = [ 'title', 'content', 'spinner' ] static values = { loading: Boolean } connect() { useFetch(this) } show({ title, url }) { this.titleTarget.innerHTML = title this.element.classList.remove('hidden') this.loadContent(url) } hide() { this.element.classList.add('hidden') } loadContent(url) { this.loadingValue = true fetch(url, this.getInitObject()) .then(this.checkStatus) .then(this.parseJSON) .then(response => { this.handleResponse(response) }) .catch(error => { this.handleResponse(this.createErrorResponse(error)) }) .finally(() => { this.loadingValue = false }) } submitForm(event) { event.preventDefault() this.loadingValue = true const form = event.target const formData = new FormData(form) formData.append(event.submitter.name, event.submitter.value) fetch(form.action, this.getInitObject('post', formData)) .then(this.checkStatus) .then(this.parseJSON) .then(response => { this.handleResponse(response) }) .catch(error => { this.handleResponse(this.createErrorResponse(error)) }) .finally(() => { this.loadingValue = false }) } handleResponse(modalResponse) { if (modalResponse.redirect) { window.location = modalResponse.redirect return } if (true === modalResponse.close) { this.element.classList.add('hidden') return } this.contentTarget.innerHTML = modalResponse.content } createErrorResponse(error) { return { close: false, redirect: null, content: error.message, } } loadingValueChanged() { this.spinnerTarget.classList.toggle('hidden', false === this.loadingValue) this.contentTarget.classList.toggle('hidden', true === this.loadingValue) } }