36 lines
1.3 KiB
JavaScript
36 lines
1.3 KiB
JavaScript
/*
|
|
toast.js — transient notifications. toast(message, { error, timeout, action: { label, onClick } })
|
|
Also exposed as window.bugtv.toast for non-module callers.
|
|
*/
|
|
import { h } from '../util.js';
|
|
|
|
let stack = null;
|
|
|
|
function ensureStack() {
|
|
if (stack && document.body.contains(stack)) return stack;
|
|
stack = document.getElementById('toasts') || h('div#toasts.toasts', { role: 'status', 'aria-live': 'polite' });
|
|
if (!stack.isConnected) document.body.appendChild(stack);
|
|
return stack;
|
|
}
|
|
|
|
export function toast(message, opts = {}) {
|
|
const el = h('div.toast', { class: opts.error ? 'toast--error' : null },
|
|
h('span.toast__msg', String(message)),
|
|
opts.action ? h('button.toast__action', { type: 'button', onclick: () => { opts.action.onClick(); dismiss(); } }, opts.action.label) : null);
|
|
ensureStack().appendChild(el);
|
|
requestAnimationFrame(() => el.classList.add('is-shown'));
|
|
let done = false;
|
|
function dismiss() {
|
|
if (done) return;
|
|
done = true;
|
|
el.classList.remove('is-shown');
|
|
setTimeout(() => el.remove(), 300);
|
|
}
|
|
setTimeout(dismiss, opts.timeout || (opts.error ? 6000 : 3500));
|
|
return dismiss;
|
|
}
|
|
|
|
export function errorToast(err, fallback) {
|
|
return toast(err && err.message ? err.message : fallback || 'Something went wrong', { error: true });
|
|
}
|