sutty-base-jekyll-theme/_packs/controllers/notification_controller.js

67 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-01-12 16:35:23 +00:00
import { Controller } from 'stimulus'
import { Liquid } from 'liquidjs'
/*
* Waits for notifications and shows them by fetching and rendering
* a template.
*/
export default class extends Controller {
connect () {
window.addEventListener('notification', async event => await this.render(event.detail.template, event.detail.data))
}
/*
* Renders and replaces notification contents and then shows it. Does
* nothing if the template isn't found.
*/
async render (name, data = {}) {
const response = await fetch(this.template(name))
if (!response.ok) return
2021-10-27 18:23:50 +00:00
data.site = window.site
2021-01-12 16:35:23 +00:00
const template = await response.text()
const html = await this.engine.parseAndRender(template, data)
this.element.innerHTML = html
this.show()
}
/*
* Gets the template path from a name
*
* @return [String]
*/
template (name) {
return this.data.get('templates') + name + '.html'
}
/*
* Shows the notification
*/
show () {
this.element.classList.add('show')
this.element.classList.remove('hide')
}
/*
* Hides the notification
*/
hide () {
this.element.classList.add('hide')
this.element.classList.remove('show')
}
/*
* Liquid renderer
*
* @return Liquid
*/
get engine () {
if (!window.liquid) window.liquid = new Liquid()
return window.liquid
}
}