Skip to content

Instantly share code, notes, and snippets.

@kareniel
Created February 23, 2018 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kareniel/c163e1aab5a0a7ec31bf7cb13425f2e6 to your computer and use it in GitHub Desktop.
Save kareniel/c163e1aab5a0a7ec31bf7cb13425f2e6 to your computer and use it in GitHub Desktop.
var Nanocomponent = require('nanocomponent')
var nanostate = require('nanostate')
module.exports = Component
function Component (el) {
if (!(this instanceof Component)) return new Component(el)
this._el = el
this.machine = nanostate('hidden', {
hidden: { toggle: 'entering' },
entering: { animationend: 'visible', toggle: 'leaving' },
visible: { toggle: 'leaving' },
leaving: { animationend: 'hidden', toggle: 'entering' }
})
this.machine.on('*', state => {
if (state === 'visible' || state === 'hidden') {
this.rerender()
}
})
this._classes = Object.keys(this.machine.transitions).map(c => `modal-${c}`)
Nanocomponent.call(this)
}
Component.prototype = Object.create(Nanocomponent.prototype)
Component.prototype.createElement = function (state, emit) {
if (!this.el) this.el = this._el(state, emit)
this.state = state
this.emit = emit
this._classes.forEach(c => this.el.classList.remove(c))
this.el.classList.add(`modal-${this.machine.state}`)
return this.el
}
Component.prototype.load = function (el) {
var events = ['animationend', 'webkitAnimationEnd', 'MozAnimationEnd', 'oAnimationEnd']
events.forEach(event => {
el.addEventListener(event, () => {
this.machine.emit('animationend')
})
})
}
Component.prototype.update = function (state, emit) {
if (!this.el) this.el = this._el(state, emit)
this.state = state
this.emit = emit
return false
}
Component.prototype.toggle = function () {
this.machine.emit('toggle')
this.rerender()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment