Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Last active May 7, 2018 10:28
Show Gist options
  • Save m3g4p0p/8638c37447c638bede24fc1a767ab486 to your computer and use it in GitHub Desktop.
Save m3g4p0p/8638c37447c638bede24fc1a767ab486 to your computer and use it in GitHub Desktop.
A simple modal module using from-html https://github.com/m3g4p0p/from-html.js
import fromHTML from 'from-html'
import './modal.scss'
/**
* @class Modal
*/
export default class Modal {
/**
* @constructs Modal
*/
constructor () {
/**
* @member {HTMLElement} Modal#overlay
* @member {HTMLElement} Modal#content
* @member {HTMLElement} Modal#cancelBtn
* @member {HTMLElement} Modal#confirmBtn
*/
Object.assign(this, fromHTML(`
<div class="modal__overlay" ref="overlay">
<div class="modal__container">
<div class="modal__content" ref="content"></div>
<div class="modal__buttons">
<button class="modal__confirm-btn" ref="confirmBtn"></button>
<button class="modal__cancel-btn" ref="cancelBtn"></button>
</div>
</div>
</div>
`))
this.overlay.addEventListener('click', this)
document.body.appendChild(this.overlay)
}
/**
* @param {Boolean} value
* @returns {this}
*/
toggleActive (value) {
this.overlay.classList.toggle('modal__overlay--active', value)
return this
}
/**
* @param {Boolean} value
* @returns {this}
*/
toggleConfirm (value) {
this.confirmBtn.classList.toggle('modal__confirm-btn--active', value)
return this
}
/**
* @param {Boolean} value
* @returns {this}
*/
toggleCancel (value) {
this.cancelBtn.classList.toggle('modal__cancel-btn--active', value)
return this
}
/**
* @param {String} msg
* @param {String|null} confirm
* @param {String|null} cancel
* @returns {Promise}
*/
message (msg, confirm = null, cancel = null) {
this.content.textContent = msg
this.confirmBtn.textContent = confirm
this.cancelBtn.textContent = cancel
this
.toggleActive(true)
.toggleConfirm(confirm !== null)
.toggleCancel(cancel !== null)
return new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
}
/**
* @param {Event} event
* @param {HTMLElement} event.target
*/
handleEvent ({ target }) {
switch (target) {
case this.confirmBtn:
this.toggleActive(false).resolve()
break
case this.cancelBtn:
this.toggleActive(false).reject()
break
default:
// Do nothing
}
}
}
.modal {
&__overlay {
position: fixed;
display: none;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, .5);
&--active {
display: flex;
justify-content: center;
align-items: center;
}
}
&__container {
background-color: white;
padding: 1em;
max-width: 50vw;
}
&__buttons {
display: flex;
justify-content: space-around;
margin-top: 1em;
}
&__confirm-btn,
&__cancel-btn {
display: none;
&--active {
display: block;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment