import getCookie from "../get_cookie.js"; export default class extends Stimulus.Controller { static values = { url: String, deleteUrl: String } static get targets() { return [ "completed", "form", "display", "checkbox" ] } connect() { this.editing = false } // load() { // fetch(`${this.urlValue}`) // .then((response) => response.text()) // .then((html) => { // this.formTarget.innerHTML = html; // if (this.formTarget.querySelector("[name=destroy]")) { // this.destroyButton = this.formTarget.querySelector("[name=destroy]") // this.destroyButton.addEventListener("click", this.destroy.bind(this)) // } // if (this.formTarget.querySelector("[name=edit]")) { // this.editButton = this.formTarget.querySelector("[name=edit]") // this.editButton.addEventListener("click", this.edit.bind(this)) // } // }) // } validate() { const inputs = new Set() this.formTarget.querySelectorAll("input").forEach(input => { inputs.add(input.checkValidity()) }) let valid = (inputs.has(false)) ? false : true return valid } change(event) { if (event.target.type === "checkbox") { this.post(event) } } edit(event) { this.formTarget.classList.remove("--hidden") this.displayTarget.classList.add("--hidden") this.editing = true } toggle(event) { if (this.checkboxTarget.checked == true) { this.checkboxTarget.checked = false } else { this.checkboxTarget.checked = true } if (this.validate()) { this.post() } } cancel(event) { if (event) { event.preventDefault() } if (this.editing) { this.formTarget.classList.add("--hidden") this.displayTarget.classList.remove("--hidden") this.editing = false } } post(event) { if (event) { event.preventDefault() } // construct a new FormData object from the html form const formData = new FormData(this.formTarget) // get the csrftoken const csrftoken = getCookie("csrftoken") const options = { method: "POST", body: new URLSearchParams(formData), mode: "same-origin", }; // construct a new Request passing in the csrftoken const request = new Request(`${this.urlValue}`, { headers: { "X-CSRFToken": csrftoken }, }) // finally make the post request and wait for the server to respond fetch(request, options) .then((response) => response.text()) .then((html) => { this.element.outerHTML = html }) .catch((error) => { return error; }) } destroy(event) { const confirmation = confirm( "Are you sure you would like to delete this entry?" ) if (confirmation) { // get the csrftoken const csrftoken = getCookie("csrftoken") const options = { method: "POST", mode: "same-origin", }; // construct a new Request passing in the csrftoken const request = new Request(`${this.deleteUrlValue}`, { headers: { "X-CSRFToken": csrftoken }, }) // finally make the post request and wait for the server to respond fetch(request, options) .then((response) => response.text()) .then((html) => { this.element.innerHTML = html; setTimeout(() => { this.element.remove() }, 3000) }) .catch((error) => { return error; }) } } }