|
| 1 | +/* |
| 2 | + * SimpleToast - A small library for toasts |
| 3 | + */ |
| 4 | +(() => { |
| 5 | + const style = { |
| 6 | + root: { |
| 7 | + display: 'flex', |
| 8 | + 'flex-direction': 'column-reverse', |
| 9 | + position: 'fixed', |
| 10 | + bottom: 0, |
| 11 | + right: 0, |
| 12 | + zIndex: 1000, |
| 13 | + }, |
| 14 | + shared: { |
| 15 | + display: 'inline-block', |
| 16 | + maxWidth: '320px', |
| 17 | + padding: '5px 8px', |
| 18 | + borderRadius: '3px', |
| 19 | + fontFamily: 'cursive, sans-serif', |
| 20 | + fontSize: '13px', |
| 21 | + cursor: 'pointer', |
| 22 | + color: '#fafeff', |
| 23 | + margin: '4px', |
| 24 | + }, |
| 25 | + toast: { |
| 26 | + textShadow: '#3498db 1px 2px 1px', |
| 27 | + background: '#2980b9', |
| 28 | + }, |
| 29 | + button: { |
| 30 | + textShadow: '#173646 0px 0px 3px', |
| 31 | + background: '#2c9fea', |
| 32 | + }, |
| 33 | + }; |
| 34 | + |
| 35 | + function applyCSS(element, css = {}) { |
| 36 | + Object.keys(css).forEach((key) => { |
| 37 | + element.style[key] = css[key]; |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + const toasts = new Map(); |
| 42 | + const root = (() => { |
| 43 | + const el = document.createElement('div'); |
| 44 | + el.setAttribute('id', 'AlertToast'); |
| 45 | + applyCSS(el, style.root); |
| 46 | + |
| 47 | + const body = document.getElementsByTagName('body')[0]; |
| 48 | + body.insertBefore(el, body.firstChild); |
| 49 | + |
| 50 | + setInterval(() => { // TODO: don't always run a timer |
| 51 | + const now = Date.now(); |
| 52 | + toasts.forEach((toast) => { |
| 53 | + if (!toast.timeout || now < toast.timeout) return; |
| 54 | + // Close toast |
| 55 | + toast.close(); |
| 56 | + }); |
| 57 | + }, 1000); |
| 58 | + return el; |
| 59 | + })(); |
| 60 | + let count = 0; |
| 61 | + |
| 62 | + function Toast({text, css, buttons, timeout}) { |
| 63 | + if (!text) return; |
| 64 | + const id = count++; |
| 65 | + const el = document.createElement('div'); |
| 66 | + el.setAttribute('id', `AlertToast-${id}`); |
| 67 | + applyCSS(el, style.shared); |
| 68 | + applyCSS(el, style.toast); |
| 69 | + applyCSS(el, css); |
| 70 | + |
| 71 | + // Add body |
| 72 | + el.textContent = text; |
| 73 | + const toast = { |
| 74 | + close: () => { |
| 75 | + root.removeChild(el); |
| 76 | + toasts.delete(id); |
| 77 | + }, |
| 78 | + }; |
| 79 | + if (timeout) { |
| 80 | + toast.timeout = Date.now() + timeout; |
| 81 | + } |
| 82 | + |
| 83 | + if (buttons) { |
| 84 | + // TODO: Add buttons |
| 85 | + } |
| 86 | + el.addEventListener('click', toast.close); |
| 87 | + |
| 88 | + root.appendChild(el); |
| 89 | + toasts.set(id, toast); |
| 90 | + return toast; |
| 91 | + } |
| 92 | + |
| 93 | + window.SimpleToast = Toast; |
| 94 | +})(); |
0 commit comments