Files
basecoat/docs/_includes/components/toast-script.njk
T

52 lines
1.6 KiB
Plaintext

<script>
if (!window._toastComponentLoaded) {
window._toastComponentLoaded = true;
const registerToastComponent = () => {
Alpine.store('toaster', { isPaused: false });
Alpine.data('toast', (category = '', timeoutDuration = null) => ({
open: false,
timeoutDuration: null,
timeoutId: null,
init() {
this.timeoutDuration = timeoutDuration || (category === 'error' ? 5000 : 3000);
this.timeoutId = setTimeout(() => { this.close() }, this.timeoutDuration);
this.open = true;
this.$watch('$store.toaster.isPaused', (isPaused) => {
if (!this.open) return;
if (isPaused) {
this.pauseTimeout();
} else {
this.resumeTimeout();
}
});
},
pauseTimeout() {
clearTimeout(this.timeoutId);
this.timeoutId = null;
},
resumeTimeout(index) {
if (this.open && this.timeoutId === null) {
this.timeoutId = setTimeout(() => { this.close() }, this.timeoutDuration);
}
},
close() {
this.pauseTimeout();
this.open = false;
this.$el.blur();
},
$toast: {
['@mouseenter']() { this.$store.toaster.isPaused = true },
['@mouseleave']() { this.$store.toaster.isPaused = false },
['@keydown.escape.prevent']() { this.close() },
},
}));
}
{% for event in (register_on or ["alpine:init"]) %}
document.addEventListener('{{ event }}', registerToastComponent);
{% endfor %}
}
</script>