Subversion Repositories oidplus

Rev

View as "text/javascript" | Blame | Last modification | View Log | RSS feed

  1. import Bs5Utils from "../Bs5Utils";
  2.  
  3. export default class Snack {
  4.     /**
  5.      * A counter for the Snacks
  6.      * @type {number}
  7.      */
  8.     #count = 0;
  9.  
  10.     /**
  11.      * Display a lightweight toast
  12.      * @param type - the theme of the snack
  13.      * @param title - the title of the of the snack
  14.      * @param delay - in ms, if specified the snack will autohide after the specified amount
  15.      * @param dismissible - set whether the dismiss button should show
  16.      */
  17.     show(type, title, delay = 0, dismissible = true) {
  18.         this.#count++;
  19.  
  20.         const style = Bs5Utils.defaults.styles[type],
  21.             btnCloseStyle = style.btnClose.join(' '),
  22.             snack = document.createElement('div');
  23.  
  24.         snack.classList.add('toast', 'align-items-center', 'border-1', 'border-dark');
  25.         style.main.forEach(value => {
  26.             snack.classList.add(value);
  27.         });
  28.         snack.setAttribute('id', `snack-${this.#count}`);
  29.         snack.setAttribute('role', 'alert');
  30.         snack.setAttribute('aria-live', 'assertive');
  31.         snack.setAttribute('aria-atomic', 'true');
  32.         snack.innerHTML = `<div class="d-flex">
  33.                         <div class="toast-body">${title}</div>
  34.                         ${dismissible ? `<button type="button" class="btn-close ${btnCloseStyle} me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>` : ''}
  35.                       </div>`;
  36.  
  37.         if (!Bs5Utils.defaults.toasts.stacking) {
  38.             document.querySelectorAll(`#${Bs5Utils.defaults.toasts.container} .toast`).forEach((toast) => {
  39.                 toast.remove();
  40.             });
  41.         }
  42.  
  43.         document.querySelector(`#${Bs5Utils.defaults.toasts.container}`).appendChild(snack);
  44.  
  45.         snack.addEventListener('hidden.bs.toast', function (e) {
  46.             e.target.remove();
  47.         });
  48.  
  49.         const opts = {
  50.             autohide: (delay > 0 && typeof delay === 'number'),
  51.         };
  52.  
  53.         if (delay > 0 && typeof delay === 'number') {
  54.             opts['delay'] = delay;
  55.         }
  56.  
  57.         const bsSnack = new bootstrap.Toast(snack, opts);
  58.  
  59.         bsSnack.show();
  60.  
  61.         return bsSnack;
  62.     }
  63. }