import { BaseHoverManager } from './BaseHoverManager.js'; import { Modal } from './Modal.js'; import { SmartButton } from './SmartButton.js'; const baseURL = window.location.origin; // Configuration du préfixe REST - peut être surchargée via window.NEWSITEEDITOR_CONFIG const REST_PREFIX = (window.NEWSITEEDITOR_CONFIG && window.NEWSITEEDITOR_CONFIG.restPrefix) || "/rest"; export class newDeleteManager extends BaseHoverManager { constructor(toggleButtonId = "delete", bgModalId = "modalDelete", deleteButtonId = "btnDelete") { super("[data-deleteid]", "deletable", "inDelete"); this.deleteID = null; this.bgModal = new Modal(bgModalId); this.smartButton = new SmartButton("btnDelete"); this.toggleButton = document.getElementById(toggleButtonId); this.type = "data-deleteType"; this.storeData = this.storeData.bind(this); this.removeResource = this.removeResource.bind(this); this.onHoverDisabled = () => { this.bgModal.setVisible(false); this.smartButton.hide(); this.deleteID = null; }; this.handleClick = (e) => { const el = e.currentTarget; this.storeData(e); if (el.classList.contains(this.hoverClass)) { this.getElements().forEach((otherEl) => { if (otherEl !== el) { otherEl.classList.remove(this.hoverClass, this.clickedClass); } }); el.classList.add(this.clickedClass); this.smartButton.setPosition(e.pageX, e.pageY - 20); } } } storeData(e) { const id = e.currentTarget.getAttribute("data-deleteid"); if (id) { this.deleteID = id; } } init() { super.init(); if (this.toggleButton) { this.toggleButton.addEventListener("click", this.toggleHover); } if (this.smartButton.getElement()) { this.smartButton.onClick(() => { this.bgModal.setVisible(true); this.smartButton.hide(); }) this.bgModal.onBackgroundClick(() => this.bgModal.setVisible(false)); this.bgModal.onCloseButtonClick(".cancelBtn"); this.bgModal.onValidate(() => this.removeResource()); } } getType() { if (!this.deleteID) return null; const el = document.querySelector(`[data-deleteid="${this.deleteID}"]`); return el?.getAttribute(this.type) ?? null; } clearElementState(el) { el.classList.remove(this.hoverClass, this.clickedClass); } async removeResource() { try { if (!this.getType()) { console.error("No type define in [data-deleteType]"); this.bgModal.setVisible(false); return; } const response = await fetch( `${baseURL}${REST_PREFIX}/dashboard/${this.getType()}/${this.deleteID}`, { method: "DELETE", } ); if (!response.ok) { throw new Error( `Erreur ${response.status} : la ressource n'a pas pu être supprimée.` ); } const data = await response.json(); if (data.code === "200") { document .querySelector('[data-deleteid="' + this.deleteID + '"]') .remove(); this.bgModal.setVisible(false); } return data; } catch (error) { console.error("Erreur lors de la suppression :", error); throw error; } } }