hyapp-h5/common/toast.js
2026-05-29 19:55:17 +08:00

88 lines
2.7 KiB
JavaScript

(function () {
var STYLE_ID = 'hy-global-toast-style';
var TOAST_ID = 'hy-global-toast';
var timer = 0;
function ensureStyle() {
if (document.getElementById(STYLE_ID)) return;
var style = document.createElement('style');
style.id = STYLE_ID;
style.textContent = [
'.hy-global-toast{',
'position:fixed;',
'left:50%;',
'top:max(84px,calc(env(safe-area-inset-top) + 24px));',
'z-index:10000;',
'max-width:min(320px,calc(100vw - 48px));',
'padding:10px 14px;',
'border-radius:8px;',
'background:rgba(0,0,0,.82);',
'color:#fff;',
'font:800 14px/1.35 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;',
'text-align:center;',
'box-shadow:0 10px 28px rgba(0,0,0,.22);',
'opacity:0;',
'pointer-events:none;',
'transform:translate(-50%,-8px);',
'transition:opacity .18s ease,transform .18s ease;',
'}',
'.hy-global-toast.is-visible{',
'opacity:1;',
'transform:translate(-50%,0);',
'}',
].join('');
document.head.appendChild(style);
}
function ensureToast() {
var node = document.getElementById(TOAST_ID);
if (node) return node;
ensureStyle();
node = document.createElement('div');
node.id = TOAST_ID;
node.className = 'hy-global-toast';
node.setAttribute('role', 'status');
node.setAttribute('aria-live', 'polite');
document.body.appendChild(node);
return node;
}
function hide() {
var node = document.getElementById(TOAST_ID);
if (node) node.classList.remove('is-visible');
}
function show(message, options) {
var text = String(message || '').trim();
if (!text) return;
if (!document.body) {
document.addEventListener(
'DOMContentLoaded',
function () {
show(text, options);
},
{ once: true }
);
return;
}
var node = ensureToast();
var duration = Number((options && options.duration) || 1800);
node.textContent = text;
window.requestAnimationFrame(function () {
node.classList.add('is-visible');
});
window.clearTimeout(timer);
timer = window.setTimeout(hide, duration);
}
window.HyAppToast = {
show: show,
hide: hide,
};
window.addEventListener('hyapp:toast', function (event) {
var detail = event.detail || {};
show(detail.message || detail.text, detail);
});
})();