100 lines
5.6 KiB
JavaScript
100 lines
5.6 KiB
JavaScript
// Shared shell service: safe to call from pages and refreshed partials.
|
||
(() => {
|
||
const pd = window.PlotDirector ||= {};
|
||
if (pd.toast) return;
|
||
const host = document.querySelector('[data-toast-host]');
|
||
if (!host) return;
|
||
const validPositions = new Set(['bottom-left', 'bottom-right']);
|
||
const storageKey = 'plotdirector.toastPosition.' + (host.dataset.toastUser || 'anonymous');
|
||
const applyPosition = position => {
|
||
host.dataset.toastPosition = validPositions.has(position) ? position : 'bottom-left';
|
||
document.querySelectorAll('[data-toast-position-choice]').forEach(choice => choice.value = host.dataset.toastPosition);
|
||
};
|
||
applyPosition(host.dataset.toastPosition);
|
||
window.addEventListener('storage', event => {
|
||
if (event.key === storageKey && validPositions.has(event.newValue)) applyPosition(event.newValue);
|
||
});
|
||
document.addEventListener('change', async event => {
|
||
const choice = event.target.closest('[data-toast-position-choice]');
|
||
if (!choice || !validPositions.has(choice.value)) return;
|
||
const previous = host.dataset.toastPosition;
|
||
applyPosition(choice.value);
|
||
choice.disabled = true;
|
||
const status = document.querySelector('[data-toast-position-status]');
|
||
if (status) status.textContent = 'Saving toast position…';
|
||
try {
|
||
const body = new FormData();
|
||
body.set('position', choice.value);
|
||
body.set('__RequestVerificationToken', document.querySelector('[data-appearance-form] [name="__RequestVerificationToken"]').value);
|
||
const response = await fetch(host.dataset.toastPositionUrl, {method:'POST', body, headers:{'X-Requested-With':'XMLHttpRequest'}});
|
||
if (!response.ok || response.redirected) throw new Error();
|
||
const saved = await response.json();
|
||
if (!validPositions.has(saved.toastPosition)) throw new Error();
|
||
applyPosition(saved.toastPosition);
|
||
try { localStorage.setItem(storageKey, saved.toastPosition); } catch { }
|
||
if (status) status.textContent = 'Toast position saved';
|
||
} catch {
|
||
applyPosition(previous);
|
||
if (status) status.textContent = 'Could not save toast position. Please try again.';
|
||
pd.toast.error('Could not save toast position. Please try again.');
|
||
} finally { choice.disabled = false; }
|
||
});
|
||
let sequence = 0;
|
||
const regions = {};
|
||
for (const priority of ['polite', 'assertive']) {
|
||
const region = document.createElement('div');
|
||
region.className = 'pd-toast-region';
|
||
region.setAttribute('aria-live', priority);
|
||
region.setAttribute('aria-relevant', 'additions');
|
||
host.append(region);
|
||
regions[priority] = region;
|
||
}
|
||
const active = new Map(), recent = new Map();
|
||
const labels = { success: 'Success', info: 'Information', warning: 'Warning', error: 'Error' };
|
||
function show(type, message, options = {}) {
|
||
message = String(message ?? '').trim();
|
||
if (!message) return;
|
||
const key = type + ':' + message, now = Date.now();
|
||
if (active.has(key) || now - (recent.get(key) || 0) < 5000) return;
|
||
for (const [entry, time] of recent) if (now - time >= 5000) recent.delete(entry);
|
||
recent.set(key, now);
|
||
if (active.size >= 4) active.values().next().value();
|
||
const node = document.createElement('div');
|
||
node.className = 'pd-toast pd-toast--' + type;
|
||
node.style.order = String(sequence++);
|
||
node.setAttribute('role', type === 'error' || type === 'warning' ? 'alert' : 'status');
|
||
node.setAttribute('aria-atomic', 'true');
|
||
const content = document.createElement('span');
|
||
const label = document.createElement('strong');
|
||
label.textContent = labels[type] + ': ';
|
||
content.append(label, document.createTextNode(message));
|
||
const close = document.createElement('button');
|
||
close.type = 'button'; close.textContent = '×';
|
||
close.setAttribute('aria-label', 'Dismiss ' + labels[type].toLowerCase() + ' notification');
|
||
let timer;
|
||
const dismiss = () => { clearTimeout(timer); node.remove(); active.delete(key); };
|
||
close.addEventListener('click', dismiss);
|
||
node.addEventListener('keydown', event => { if (event.key === 'Escape') dismiss(); });
|
||
node.append(content, close); regions[type === 'error' || type === 'warning' ? 'assertive' : 'polite'].append(node); active.set(key, dismiss);
|
||
const duration = options.duration ?? (type === 'error' || type === 'warning' ? 0 : 6000);
|
||
const start = () => { clearTimeout(timer); if (duration > 0) timer = setTimeout(dismiss, duration); };
|
||
node.addEventListener('mouseenter', () => clearTimeout(timer));
|
||
node.addEventListener('focusin', () => clearTimeout(timer));
|
||
node.addEventListener('mouseleave', () => { if (!node.contains(document.activeElement)) start(); });
|
||
node.addEventListener('focusout', () => { if (!node.matches(':hover')) start(); });
|
||
start();
|
||
return dismiss;
|
||
}
|
||
pd.toast = Object.fromEntries(Object.keys(labels).map(type => [type, (message, options) => show(type, message, options)]));
|
||
// Consume encoded server flash markers once, including markers inserted by partial refreshes.
|
||
function consume() {
|
||
document.querySelectorAll('[data-toast-message]').forEach(node => {
|
||
const type = node.dataset.toastMessage;
|
||
if (Object.hasOwn(labels, type)) pd.toast[type](node.textContent);
|
||
node.remove();
|
||
});
|
||
}
|
||
consume();
|
||
new MutationObserver(consume).observe(document.body, { childList: true, subtree: true });
|
||
})();
|