Dragon-Knight/assets/scripts/confirm_modal.js

63 lines
1.7 KiB
JavaScript

class ConfirmModal {
constructor(options = {}) {
this.modal = document.querySelector(options.modalSelector || "#confirm-modal")
this.message = this.modal.querySelector(options.messageSelector || "#msg")
this.confirmBtn = this.modal.querySelector(options.confirmSelector || "#confirm")
this.cancelBtn = this.modal.querySelector(options.cancelSelector || "#cancel")
this.linkSelector = options.linkSelector || '.confirm-link'
this.messageGenerator = options.messageGenerator || this.defaultMessageGenerator.bind(this)
this.currentUrl = null
if (options.confirmText) this.confirmBtn.textContent = options.confirmText
if (options.cancelText) this.cancelBtn.textContent = options.cancelText
this.init()
}
init() {
document.querySelectorAll(this.linkSelector).forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault()
const message = this.messageGenerator(link)
this.show(link.href, message)
})
})
this.confirmBtn.addEventListener('click', () => this.confirm())
this.cancelBtn.addEventListener('click', () => this.hide())
this.modal.addEventListener('click', (e) => {
if (e.target === this.modal) this.hide()
})
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.modal.style.display === 'block') {
this.hide()
}
})
}
defaultMessageGenerator(link) {
return link.dataset.message || 'Are you sure you want to continue?'
}
show(url, message) {
this.currentUrl = url
this.message.textContent = message
this.modal.style.display = 'block'
this.confirmBtn.focus()
}
hide() {
this.modal.style.display = 'none'
this.currentUrl = null
}
confirm() {
if (this.currentUrl) {
window.location.href = this.currentUrl
}
this.hide()
}
}