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

58 lines
1.1 KiB
JavaScript
Raw Normal View History

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