You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4024 lines
122 KiB

3 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*!
  2. * sweetalert2 v11.7.3
  3. * Released under the MIT License.
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  7. typeof define === 'function' && define.amd ? define(factory) :
  8. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Sweetalert2 = factory());
  9. })(this, (function () { 'use strict';
  10. /**
  11. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  12. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  13. * This is the approach that Babel will probably take to implement private methods/fields
  14. * https://github.com/tc39/proposal-private-methods
  15. * https://github.com/babel/babel/pull/7555
  16. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  17. * then we can use that language feature.
  18. */
  19. var privateProps = {
  20. awaitingPromise: new WeakMap(),
  21. promise: new WeakMap(),
  22. innerParams: new WeakMap(),
  23. domCache: new WeakMap()
  24. };
  25. const swalPrefix = 'swal2-';
  26. /**
  27. * @param {string[]} items
  28. * @returns {object}
  29. */
  30. const prefix = items => {
  31. const result = {};
  32. for (const i in items) {
  33. result[items[i]] = swalPrefix + items[i];
  34. }
  35. return result;
  36. };
  37. const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
  38. const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
  39. const consolePrefix = 'SweetAlert2:';
  40. /**
  41. * Filter the unique values into a new array
  42. *
  43. * @param {Array} arr
  44. * @returns {Array}
  45. */
  46. const uniqueArray = arr => {
  47. const result = [];
  48. for (let i = 0; i < arr.length; i++) {
  49. if (result.indexOf(arr[i]) === -1) {
  50. result.push(arr[i]);
  51. }
  52. }
  53. return result;
  54. };
  55. /**
  56. * Capitalize the first letter of a string
  57. *
  58. * @param {string} str
  59. * @returns {string}
  60. */
  61. const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
  62. /**
  63. * Standardize console warnings
  64. *
  65. * @param {string | Array} message
  66. */
  67. const warn = message => {
  68. console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
  69. };
  70. /**
  71. * Standardize console errors
  72. *
  73. * @param {string} message
  74. */
  75. const error = message => {
  76. console.error(`${consolePrefix} ${message}`);
  77. };
  78. /**
  79. * Private global state for `warnOnce`
  80. *
  81. * @type {Array}
  82. * @private
  83. */
  84. const previousWarnOnceMessages = [];
  85. /**
  86. * Show a console warning, but only if it hasn't already been shown
  87. *
  88. * @param {string} message
  89. */
  90. const warnOnce = message => {
  91. if (!previousWarnOnceMessages.includes(message)) {
  92. previousWarnOnceMessages.push(message);
  93. warn(message);
  94. }
  95. };
  96. /**
  97. * Show a one-time console warning about deprecated params/methods
  98. *
  99. * @param {string} deprecatedParam
  100. * @param {string} useInstead
  101. */
  102. const warnAboutDeprecation = (deprecatedParam, useInstead) => {
  103. warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release. Please use "${useInstead}" instead.`);
  104. };
  105. /**
  106. * If `arg` is a function, call it (with no arguments or context) and return the result.
  107. * Otherwise, just pass the value through
  108. *
  109. * @param {Function | any} arg
  110. * @returns {any}
  111. */
  112. const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
  113. /**
  114. * @param {any} arg
  115. * @returns {boolean}
  116. */
  117. const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
  118. /**
  119. * @param {any} arg
  120. * @returns {Promise}
  121. */
  122. const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
  123. /**
  124. * @param {any} arg
  125. * @returns {boolean}
  126. */
  127. const isPromise = arg => arg && Promise.resolve(arg) === arg;
  128. /**
  129. * Gets the popup container which contains the backdrop and the popup itself.
  130. *
  131. * @returns {HTMLElement | null}
  132. */
  133. const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);
  134. /**
  135. * @param {string} selectorString
  136. * @returns {HTMLElement | null}
  137. */
  138. const elementBySelector = selectorString => {
  139. const container = getContainer();
  140. return container ? container.querySelector(selectorString) : null;
  141. };
  142. /**
  143. * @param {string} className
  144. * @returns {HTMLElement | null}
  145. */
  146. const elementByClass = className => {
  147. return elementBySelector(`.${className}`);
  148. };
  149. /**
  150. * @returns {HTMLElement | null}
  151. */
  152. const getPopup = () => elementByClass(swalClasses.popup);
  153. /**
  154. * @returns {HTMLElement | null}
  155. */
  156. const getIcon = () => elementByClass(swalClasses.icon);
  157. /**
  158. * @returns {HTMLElement | null}
  159. */
  160. const getIconContent = () => elementByClass(swalClasses['icon-content']);
  161. /**
  162. * @returns {HTMLElement | null}
  163. */
  164. const getTitle = () => elementByClass(swalClasses.title);
  165. /**
  166. * @returns {HTMLElement | null}
  167. */
  168. const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
  169. /**
  170. * @returns {HTMLElement | null}
  171. */
  172. const getImage = () => elementByClass(swalClasses.image);
  173. /**
  174. * @returns {HTMLElement | null}
  175. */
  176. const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
  177. /**
  178. * @returns {HTMLElement | null}
  179. */
  180. const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
  181. /**
  182. * @returns {HTMLButtonElement | null}
  183. */
  184. const getConfirmButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`);
  185. /**
  186. * @returns {HTMLButtonElement | null}
  187. */
  188. const getCancelButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`);
  189. /**
  190. * @returns {HTMLButtonElement | null}
  191. */
  192. const getDenyButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`);
  193. /**
  194. * @returns {HTMLElement | null}
  195. */
  196. const getInputLabel = () => elementByClass(swalClasses['input-label']);
  197. /**
  198. * @returns {HTMLElement | null}
  199. */
  200. const getLoader = () => elementBySelector(`.${swalClasses.loader}`);
  201. /**
  202. * @returns {HTMLElement | null}
  203. */
  204. const getActions = () => elementByClass(swalClasses.actions);
  205. /**
  206. * @returns {HTMLElement | null}
  207. */
  208. const getFooter = () => elementByClass(swalClasses.footer);
  209. /**
  210. * @returns {HTMLElement | null}
  211. */
  212. const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
  213. /**
  214. * @returns {HTMLElement | null}
  215. */
  216. const getCloseButton = () => elementByClass(swalClasses.close);
  217. // https://github.com/jkup/focusable/blob/master/index.js
  218. const focusable = `
  219. a[href],
  220. area[href],
  221. input:not([disabled]),
  222. select:not([disabled]),
  223. textarea:not([disabled]),
  224. button:not([disabled]),
  225. iframe,
  226. object,
  227. embed,
  228. [tabindex="0"],
  229. [contenteditable],
  230. audio[controls],
  231. video[controls],
  232. summary
  233. `;
  234. /**
  235. * @returns {HTMLElement[]}
  236. */
  237. const getFocusableElements = () => {
  238. const focusableElementsWithTabindex = Array.from(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])'))
  239. // sort according to tabindex
  240. .sort((a, b) => {
  241. const tabindexA = parseInt(a.getAttribute('tabindex'));
  242. const tabindexB = parseInt(b.getAttribute('tabindex'));
  243. if (tabindexA > tabindexB) {
  244. return 1;
  245. } else if (tabindexA < tabindexB) {
  246. return -1;
  247. }
  248. return 0;
  249. });
  250. const otherFocusableElements = Array.from(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
  251. return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible$1(el));
  252. };
  253. /**
  254. * @returns {boolean}
  255. */
  256. const isModal = () => {
  257. return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
  258. };
  259. /**
  260. * @returns {boolean}
  261. */
  262. const isToast = () => {
  263. return getPopup() && hasClass(getPopup(), swalClasses.toast);
  264. };
  265. /**
  266. * @returns {boolean}
  267. */
  268. const isLoading = () => {
  269. return getPopup().hasAttribute('data-loading');
  270. };
  271. // Remember state in cases where opening and handling a modal will fiddle with it.
  272. const states = {
  273. previousBodyPadding: null
  274. };
  275. /**
  276. * Securely set innerHTML of an element
  277. * https://github.com/sweetalert2/sweetalert2/issues/1926
  278. *
  279. * @param {HTMLElement} elem
  280. * @param {string} html
  281. */
  282. const setInnerHtml = (elem, html) => {
  283. elem.textContent = '';
  284. if (html) {
  285. const parser = new DOMParser();
  286. const parsed = parser.parseFromString(html, `text/html`);
  287. Array.from(parsed.querySelector('head').childNodes).forEach(child => {
  288. elem.appendChild(child);
  289. });
  290. Array.from(parsed.querySelector('body').childNodes).forEach(child => {
  291. if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
  292. elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507
  293. } else {
  294. elem.appendChild(child);
  295. }
  296. });
  297. }
  298. };
  299. /**
  300. * @param {HTMLElement} elem
  301. * @param {string} className
  302. * @returns {boolean}
  303. */
  304. const hasClass = (elem, className) => {
  305. if (!className) {
  306. return false;
  307. }
  308. const classList = className.split(/\s+/);
  309. for (let i = 0; i < classList.length; i++) {
  310. if (!elem.classList.contains(classList[i])) {
  311. return false;
  312. }
  313. }
  314. return true;
  315. };
  316. /**
  317. * @param {HTMLElement} elem
  318. * @param {SweetAlertOptions} params
  319. */
  320. const removeCustomClasses = (elem, params) => {
  321. Array.from(elem.classList).forEach(className => {
  322. if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
  323. elem.classList.remove(className);
  324. }
  325. });
  326. };
  327. /**
  328. * @param {HTMLElement} elem
  329. * @param {SweetAlertOptions} params
  330. * @param {string} className
  331. */
  332. const applyCustomClass = (elem, params, className) => {
  333. removeCustomClasses(elem, params);
  334. if (params.customClass && params.customClass[className]) {
  335. if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
  336. warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof params.customClass[className]}"`);
  337. return;
  338. }
  339. addClass(elem, params.customClass[className]);
  340. }
  341. };
  342. /**
  343. * @param {HTMLElement} popup
  344. * @param {import('./renderers/renderInput').InputClass} inputClass
  345. * @returns {HTMLInputElement | null}
  346. */
  347. const getInput$1 = (popup, inputClass) => {
  348. if (!inputClass) {
  349. return null;
  350. }
  351. switch (inputClass) {
  352. case 'select':
  353. case 'textarea':
  354. case 'file':
  355. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
  356. case 'checkbox':
  357. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
  358. case 'radio':
  359. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
  360. case 'range':
  361. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
  362. default:
  363. return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
  364. }
  365. };
  366. /**
  367. * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
  368. */
  369. const focusInput = input => {
  370. input.focus();
  371. // place cursor at end of text in text input
  372. if (input.type !== 'file') {
  373. // http://stackoverflow.com/a/2345915
  374. const val = input.value;
  375. input.value = '';
  376. input.value = val;
  377. }
  378. };
  379. /**
  380. * @param {HTMLElement | HTMLElement[] | null} target
  381. * @param {string | string[] | readonly string[]} classList
  382. * @param {boolean} condition
  383. */
  384. const toggleClass = (target, classList, condition) => {
  385. if (!target || !classList) {
  386. return;
  387. }
  388. if (typeof classList === 'string') {
  389. classList = classList.split(/\s+/).filter(Boolean);
  390. }
  391. classList.forEach(className => {
  392. if (Array.isArray(target)) {
  393. target.forEach(elem => {
  394. condition ? elem.classList.add(className) : elem.classList.remove(className);
  395. });
  396. } else {
  397. condition ? target.classList.add(className) : target.classList.remove(className);
  398. }
  399. });
  400. };
  401. /**
  402. * @param {HTMLElement | HTMLElement[] | null} target
  403. * @param {string | string[] | readonly string[]} classList
  404. */
  405. const addClass = (target, classList) => {
  406. toggleClass(target, classList, true);
  407. };
  408. /**
  409. * @param {HTMLElement | HTMLElement[] | null} target
  410. * @param {string | string[] | readonly string[]} classList
  411. */
  412. const removeClass = (target, classList) => {
  413. toggleClass(target, classList, false);
  414. };
  415. /**
  416. * Get direct child of an element by class name
  417. *
  418. * @param {HTMLElement} elem
  419. * @param {string} className
  420. * @returns {HTMLElement | undefined}
  421. */
  422. const getDirectChildByClass = (elem, className) => {
  423. const children = Array.from(elem.children);
  424. for (let i = 0; i < children.length; i++) {
  425. const child = children[i];
  426. if (child instanceof HTMLElement && hasClass(child, className)) {
  427. return child;
  428. }
  429. }
  430. };
  431. /**
  432. * @param {HTMLElement} elem
  433. * @param {string} property
  434. * @param {*} value
  435. */
  436. const applyNumericalStyle = (elem, property, value) => {
  437. if (value === `${parseInt(value)}`) {
  438. value = parseInt(value);
  439. }
  440. if (value || parseInt(value) === 0) {
  441. elem.style[property] = typeof value === 'number' ? `${value}px` : value;
  442. } else {
  443. elem.style.removeProperty(property);
  444. }
  445. };
  446. /**
  447. * @param {HTMLElement} elem
  448. * @param {string} display
  449. */
  450. const show = function (elem) {
  451. let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
  452. elem.style.display = display;
  453. };
  454. /**
  455. * @param {HTMLElement} elem
  456. */
  457. const hide = elem => {
  458. elem.style.display = 'none';
  459. };
  460. /**
  461. * @param {HTMLElement} parent
  462. * @param {string} selector
  463. * @param {string} property
  464. * @param {string} value
  465. */
  466. const setStyle = (parent, selector, property, value) => {
  467. /** @type {HTMLElement} */
  468. const el = parent.querySelector(selector);
  469. if (el) {
  470. el.style[property] = value;
  471. }
  472. };
  473. /**
  474. * @param {HTMLElement} elem
  475. * @param {any} condition
  476. * @param {string} display
  477. */
  478. const toggle = function (elem, condition) {
  479. let display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex';
  480. condition ? show(elem, display) : hide(elem);
  481. };
  482. /**
  483. * borrowed from jquery $(elem).is(':visible') implementation
  484. *
  485. * @param {HTMLElement} elem
  486. * @returns {boolean}
  487. */
  488. const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
  489. /**
  490. * @returns {boolean}
  491. */
  492. const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());
  493. /**
  494. * @param {HTMLElement} elem
  495. * @returns {boolean}
  496. */
  497. const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight);
  498. /**
  499. * borrowed from https://stackoverflow.com/a/46352119
  500. *
  501. * @param {HTMLElement} elem
  502. * @returns {boolean}
  503. */
  504. const hasCssAnimation = elem => {
  505. const style = window.getComputedStyle(elem);
  506. const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
  507. const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
  508. return animDuration > 0 || transDuration > 0;
  509. };
  510. /**
  511. * @param {number} timer
  512. * @param {boolean} reset
  513. */
  514. const animateTimerProgressBar = function (timer) {
  515. let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  516. const timerProgressBar = getTimerProgressBar();
  517. if (isVisible$1(timerProgressBar)) {
  518. if (reset) {
  519. timerProgressBar.style.transition = 'none';
  520. timerProgressBar.style.width = '100%';
  521. }
  522. setTimeout(() => {
  523. timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
  524. timerProgressBar.style.width = '0%';
  525. }, 10);
  526. }
  527. };
  528. const stopTimerProgressBar = () => {
  529. const timerProgressBar = getTimerProgressBar();
  530. const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  531. timerProgressBar.style.removeProperty('transition');
  532. timerProgressBar.style.width = '100%';
  533. const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
  534. const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
  535. timerProgressBar.style.width = `${timerProgressBarPercent}%`;
  536. };
  537. const RESTORE_FOCUS_TIMEOUT = 100;
  538. /** @type {GlobalState} */
  539. const globalState = {};
  540. const focusPreviousActiveElement = () => {
  541. if (globalState.previousActiveElement instanceof HTMLElement) {
  542. globalState.previousActiveElement.focus();
  543. globalState.previousActiveElement = null;
  544. } else if (document.body) {
  545. document.body.focus();
  546. }
  547. };
  548. /**
  549. * Restore previous active (focused) element
  550. *
  551. * @param {boolean} returnFocus
  552. * @returns {Promise}
  553. */
  554. const restoreActiveElement = returnFocus => {
  555. return new Promise(resolve => {
  556. if (!returnFocus) {
  557. return resolve();
  558. }
  559. const x = window.scrollX;
  560. const y = window.scrollY;
  561. globalState.restoreFocusTimeout = setTimeout(() => {
  562. focusPreviousActiveElement();
  563. resolve();
  564. }, RESTORE_FOCUS_TIMEOUT); // issues/900
  565. window.scrollTo(x, y);
  566. });
  567. };
  568. /**
  569. * Detect Node env
  570. *
  571. * @returns {boolean}
  572. */
  573. const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
  574. const sweetHTML = `
  575. <div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
  576. <button type="button" class="${swalClasses.close}"></button>
  577. <ul class="${swalClasses['progress-steps']}"></ul>
  578. <div class="${swalClasses.icon}"></div>
  579. <img class="${swalClasses.image}" />
  580. <h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
  581. <div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
  582. <input class="${swalClasses.input}" />
  583. <input type="file" class="${swalClasses.file}" />
  584. <div class="${swalClasses.range}">
  585. <input type="range" />
  586. <output></output>
  587. </div>
  588. <select class="${swalClasses.select}"></select>
  589. <div class="${swalClasses.radio}"></div>
  590. <label for="${swalClasses.checkbox}" class="${swalClasses.checkbox}">
  591. <input type="checkbox" />
  592. <span class="${swalClasses.label}"></span>
  593. </label>
  594. <textarea class="${swalClasses.textarea}"></textarea>
  595. <div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
  596. <div class="${swalClasses.actions}">
  597. <div class="${swalClasses.loader}"></div>
  598. <button type="button" class="${swalClasses.confirm}"></button>
  599. <button type="button" class="${swalClasses.deny}"></button>
  600. <button type="button" class="${swalClasses.cancel}"></button>
  601. </div>
  602. <div class="${swalClasses.footer}"></div>
  603. <div class="${swalClasses['timer-progress-bar-container']}">
  604. <div class="${swalClasses['timer-progress-bar']}"></div>
  605. </div>
  606. </div>
  607. `.replace(/(^|\n)\s*/g, '');
  608. /**
  609. * @returns {boolean}
  610. */
  611. const resetOldContainer = () => {
  612. const oldContainer = getContainer();
  613. if (!oldContainer) {
  614. return false;
  615. }
  616. oldContainer.remove();
  617. removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
  618. return true;
  619. };
  620. const resetValidationMessage$1 = () => {
  621. globalState.currentInstance.resetValidationMessage();
  622. };
  623. const addInputChangeListeners = () => {
  624. const popup = getPopup();
  625. const input = getDirectChildByClass(popup, swalClasses.input);
  626. const file = getDirectChildByClass(popup, swalClasses.file);
  627. /** @type {HTMLInputElement} */
  628. const range = popup.querySelector(`.${swalClasses.range} input`);
  629. /** @type {HTMLOutputElement} */
  630. const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
  631. const select = getDirectChildByClass(popup, swalClasses.select);
  632. /** @type {HTMLInputElement} */
  633. const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
  634. const textarea = getDirectChildByClass(popup, swalClasses.textarea);
  635. input.oninput = resetValidationMessage$1;
  636. file.onchange = resetValidationMessage$1;
  637. select.onchange = resetValidationMessage$1;
  638. checkbox.onchange = resetValidationMessage$1;
  639. textarea.oninput = resetValidationMessage$1;
  640. range.oninput = () => {
  641. resetValidationMessage$1();
  642. rangeOutput.value = range.value;
  643. };
  644. range.onchange = () => {
  645. resetValidationMessage$1();
  646. rangeOutput.value = range.value;
  647. };
  648. };
  649. /**
  650. * @param {string | HTMLElement} target
  651. * @returns {HTMLElement}
  652. */
  653. const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
  654. /**
  655. * @param {SweetAlertOptions} params
  656. */
  657. const setupAccessibility = params => {
  658. const popup = getPopup();
  659. popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
  660. popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
  661. if (!params.toast) {
  662. popup.setAttribute('aria-modal', 'true');
  663. }
  664. };
  665. /**
  666. * @param {HTMLElement} targetElement
  667. */
  668. const setupRTL = targetElement => {
  669. if (window.getComputedStyle(targetElement).direction === 'rtl') {
  670. addClass(getContainer(), swalClasses.rtl);
  671. }
  672. };
  673. /**
  674. * Add modal + backdrop + no-war message for Russians to DOM
  675. *
  676. * @param {SweetAlertOptions} params
  677. */
  678. const init = params => {
  679. // Clean up the old popup container if it exists
  680. const oldContainerExisted = resetOldContainer();
  681. /* istanbul ignore if */
  682. if (isNodeEnv()) {
  683. error('SweetAlert2 requires document to initialize');
  684. return;
  685. }
  686. const container = document.createElement('div');
  687. container.className = swalClasses.container;
  688. if (oldContainerExisted) {
  689. addClass(container, swalClasses['no-transition']);
  690. }
  691. setInnerHtml(container, sweetHTML);
  692. const targetElement = getTarget(params.target);
  693. targetElement.appendChild(container);
  694. setupAccessibility(params);
  695. setupRTL(targetElement);
  696. addInputChangeListeners();
  697. };
  698. /**
  699. * @param {HTMLElement | object | string} param
  700. * @param {HTMLElement} target
  701. */
  702. const parseHtmlToContainer = (param, target) => {
  703. // DOM element
  704. if (param instanceof HTMLElement) {
  705. target.appendChild(param);
  706. }
  707. // Object
  708. else if (typeof param === 'object') {
  709. handleObject(param, target);
  710. }
  711. // Plain string
  712. else if (param) {
  713. setInnerHtml(target, param);
  714. }
  715. };
  716. /**
  717. * @param {object} param
  718. * @param {HTMLElement} target
  719. */
  720. const handleObject = (param, target) => {
  721. // JQuery element(s)
  722. if (param.jquery) {
  723. handleJqueryElem(target, param);
  724. }
  725. // For other objects use their string representation
  726. else {
  727. setInnerHtml(target, param.toString());
  728. }
  729. };
  730. /**
  731. * @param {HTMLElement} target
  732. * @param {HTMLElement} elem
  733. */
  734. const handleJqueryElem = (target, elem) => {
  735. target.textContent = '';
  736. if (0 in elem) {
  737. for (let i = 0; (i in elem); i++) {
  738. target.appendChild(elem[i].cloneNode(true));
  739. }
  740. } else {
  741. target.appendChild(elem.cloneNode(true));
  742. }
  743. };
  744. /**
  745. * @returns {'webkitAnimationEnd' | 'animationend' | false}
  746. */
  747. const animationEndEvent = (() => {
  748. // Prevent run in Node env
  749. /* istanbul ignore if */
  750. if (isNodeEnv()) {
  751. return false;
  752. }
  753. const testEl = document.createElement('div');
  754. const transEndEventNames = {
  755. WebkitAnimation: 'webkitAnimationEnd',
  756. // Chrome, Safari and Opera
  757. animation: 'animationend' // Standard syntax
  758. };
  759. for (const i in transEndEventNames) {
  760. if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
  761. return transEndEventNames[i];
  762. }
  763. }
  764. return false;
  765. })();
  766. /**
  767. * Measure scrollbar width for padding body during modal show/hide
  768. * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
  769. *
  770. * @returns {number}
  771. */
  772. const measureScrollbar = () => {
  773. const scrollDiv = document.createElement('div');
  774. scrollDiv.className = swalClasses['scrollbar-measure'];
  775. document.body.appendChild(scrollDiv);
  776. const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
  777. document.body.removeChild(scrollDiv);
  778. return scrollbarWidth;
  779. };
  780. /**
  781. * @param {SweetAlert2} instance
  782. * @param {SweetAlertOptions} params
  783. */
  784. const renderActions = (instance, params) => {
  785. const actions = getActions();
  786. const loader = getLoader();
  787. // Actions (buttons) wrapper
  788. if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
  789. hide(actions);
  790. } else {
  791. show(actions);
  792. }
  793. // Custom class
  794. applyCustomClass(actions, params, 'actions');
  795. // Render all the buttons
  796. renderButtons(actions, loader, params);
  797. // Loader
  798. setInnerHtml(loader, params.loaderHtml);
  799. applyCustomClass(loader, params, 'loader');
  800. };
  801. /**
  802. * @param {HTMLElement} actions
  803. * @param {HTMLElement} loader
  804. * @param {SweetAlertOptions} params
  805. */
  806. function renderButtons(actions, loader, params) {
  807. const confirmButton = getConfirmButton();
  808. const denyButton = getDenyButton();
  809. const cancelButton = getCancelButton();
  810. // Render buttons
  811. renderButton(confirmButton, 'confirm', params);
  812. renderButton(denyButton, 'deny', params);
  813. renderButton(cancelButton, 'cancel', params);
  814. handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
  815. if (params.reverseButtons) {
  816. if (params.toast) {
  817. actions.insertBefore(cancelButton, confirmButton);
  818. actions.insertBefore(denyButton, confirmButton);
  819. } else {
  820. actions.insertBefore(cancelButton, loader);
  821. actions.insertBefore(denyButton, loader);
  822. actions.insertBefore(confirmButton, loader);
  823. }
  824. }
  825. }
  826. /**
  827. * @param {HTMLElement} confirmButton
  828. * @param {HTMLElement} denyButton
  829. * @param {HTMLElement} cancelButton
  830. * @param {SweetAlertOptions} params
  831. */
  832. function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
  833. if (!params.buttonsStyling) {
  834. removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
  835. return;
  836. }
  837. addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
  838. // Buttons background colors
  839. if (params.confirmButtonColor) {
  840. confirmButton.style.backgroundColor = params.confirmButtonColor;
  841. addClass(confirmButton, swalClasses['default-outline']);
  842. }
  843. if (params.denyButtonColor) {
  844. denyButton.style.backgroundColor = params.denyButtonColor;
  845. addClass(denyButton, swalClasses['default-outline']);
  846. }
  847. if (params.cancelButtonColor) {
  848. cancelButton.style.backgroundColor = params.cancelButtonColor;
  849. addClass(cancelButton, swalClasses['default-outline']);
  850. }
  851. }
  852. /**
  853. * @param {HTMLElement} button
  854. * @param {'confirm' | 'deny' | 'cancel'} buttonType
  855. * @param {SweetAlertOptions} params
  856. */
  857. function renderButton(button, buttonType, params) {
  858. toggle(button, params[`show${capitalizeFirstLetter(buttonType)}Button`], 'inline-block');
  859. setInnerHtml(button, params[`${buttonType}ButtonText`]); // Set caption text
  860. button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`]); // ARIA label
  861. // Add buttons custom classes
  862. button.className = swalClasses[buttonType];
  863. applyCustomClass(button, params, `${buttonType}Button`);
  864. addClass(button, params[`${buttonType}ButtonClass`]);
  865. }
  866. /**
  867. * @param {SweetAlert2} instance
  868. * @param {SweetAlertOptions} params
  869. */
  870. const renderCloseButton = (instance, params) => {
  871. const closeButton = getCloseButton();
  872. setInnerHtml(closeButton, params.closeButtonHtml);
  873. // Custom class
  874. applyCustomClass(closeButton, params, 'closeButton');
  875. toggle(closeButton, params.showCloseButton);
  876. closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
  877. };
  878. /**
  879. * @param {SweetAlert2} instance
  880. * @param {SweetAlertOptions} params
  881. */
  882. const renderContainer = (instance, params) => {
  883. const container = getContainer();
  884. if (!container) {
  885. return;
  886. }
  887. handleBackdropParam(container, params.backdrop);
  888. handlePositionParam(container, params.position);
  889. handleGrowParam(container, params.grow);
  890. // Custom class
  891. applyCustomClass(container, params, 'container');
  892. };
  893. /**
  894. * @param {HTMLElement} container
  895. * @param {SweetAlertOptions['backdrop']} backdrop
  896. */
  897. function handleBackdropParam(container, backdrop) {
  898. if (typeof backdrop === 'string') {
  899. container.style.background = backdrop;
  900. } else if (!backdrop) {
  901. addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
  902. }
  903. }
  904. /**
  905. * @param {HTMLElement} container
  906. * @param {SweetAlertOptions['position']} position
  907. */
  908. function handlePositionParam(container, position) {
  909. if (position in swalClasses) {
  910. addClass(container, swalClasses[position]);
  911. } else {
  912. warn('The "position" parameter is not valid, defaulting to "center"');
  913. addClass(container, swalClasses.center);
  914. }
  915. }
  916. /**
  917. * @param {HTMLElement} container
  918. * @param {SweetAlertOptions['grow']} grow
  919. */
  920. function handleGrowParam(container, grow) {
  921. if (grow && typeof grow === 'string') {
  922. const growClass = `grow-${grow}`;
  923. if (growClass in swalClasses) {
  924. addClass(container, swalClasses[growClass]);
  925. }
  926. }
  927. }
  928. /// <reference path="../../../../sweetalert2.d.ts"/>
  929. /** @type {InputClass[]} */
  930. const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
  931. /**
  932. * @param {SweetAlert2} instance
  933. * @param {SweetAlertOptions} params
  934. */
  935. const renderInput = (instance, params) => {
  936. const popup = getPopup();
  937. const innerParams = privateProps.innerParams.get(instance);
  938. const rerender = !innerParams || params.input !== innerParams.input;
  939. inputClasses.forEach(inputClass => {
  940. const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
  941. // set attributes
  942. setAttributes(inputClass, params.inputAttributes);
  943. // set class
  944. inputContainer.className = swalClasses[inputClass];
  945. if (rerender) {
  946. hide(inputContainer);
  947. }
  948. });
  949. if (params.input) {
  950. if (rerender) {
  951. showInput(params);
  952. }
  953. // set custom class
  954. setCustomClass(params);
  955. }
  956. };
  957. /**
  958. * @param {SweetAlertOptions} params
  959. */
  960. const showInput = params => {
  961. if (!renderInputType[params.input]) {
  962. error(`Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "${params.input}"`);
  963. return;
  964. }
  965. const inputContainer = getInputContainer(params.input);
  966. const input = renderInputType[params.input](inputContainer, params);
  967. show(inputContainer);
  968. // input autofocus
  969. if (params.inputAutoFocus) {
  970. setTimeout(() => {
  971. focusInput(input);
  972. });
  973. }
  974. };
  975. /**
  976. * @param {HTMLInputElement} input
  977. */
  978. const removeAttributes = input => {
  979. for (let i = 0; i < input.attributes.length; i++) {
  980. const attrName = input.attributes[i].name;
  981. if (!['type', 'value', 'style'].includes(attrName)) {
  982. input.removeAttribute(attrName);
  983. }
  984. }
  985. };
  986. /**
  987. * @param {InputClass} inputClass
  988. * @param {SweetAlertOptions['inputAttributes']} inputAttributes
  989. */
  990. const setAttributes = (inputClass, inputAttributes) => {
  991. const input = getInput$1(getPopup(), inputClass);
  992. if (!input) {
  993. return;
  994. }
  995. removeAttributes(input);
  996. for (const attr in inputAttributes) {
  997. input.setAttribute(attr, inputAttributes[attr]);
  998. }
  999. };
  1000. /**
  1001. * @param {SweetAlertOptions} params
  1002. */
  1003. const setCustomClass = params => {
  1004. const inputContainer = getInputContainer(params.input);
  1005. if (typeof params.customClass === 'object') {
  1006. addClass(inputContainer, params.customClass.input);
  1007. }
  1008. };
  1009. /**
  1010. * @param {HTMLInputElement | HTMLTextAreaElement} input
  1011. * @param {SweetAlertOptions} params
  1012. */
  1013. const setInputPlaceholder = (input, params) => {
  1014. if (!input.placeholder || params.inputPlaceholder) {
  1015. input.placeholder = params.inputPlaceholder;
  1016. }
  1017. };
  1018. /**
  1019. * @param {Input} input
  1020. * @param {Input} prependTo
  1021. * @param {SweetAlertOptions} params
  1022. */
  1023. const setInputLabel = (input, prependTo, params) => {
  1024. if (params.inputLabel) {
  1025. input.id = swalClasses.input;
  1026. const label = document.createElement('label');
  1027. const labelClass = swalClasses['input-label'];
  1028. label.setAttribute('for', input.id);
  1029. label.className = labelClass;
  1030. if (typeof params.customClass === 'object') {
  1031. addClass(label, params.customClass.inputLabel);
  1032. }
  1033. label.innerText = params.inputLabel;
  1034. prependTo.insertAdjacentElement('beforebegin', label);
  1035. }
  1036. };
  1037. /**
  1038. * @param {SweetAlertOptions['input']} inputType
  1039. * @returns {HTMLElement}
  1040. */
  1041. const getInputContainer = inputType => {
  1042. return getDirectChildByClass(getPopup(), swalClasses[inputType] || swalClasses.input);
  1043. };
  1044. /**
  1045. * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
  1046. * @param {SweetAlertOptions['inputValue']} inputValue
  1047. */
  1048. const checkAndSetInputValue = (input, inputValue) => {
  1049. if (['string', 'number'].includes(typeof inputValue)) {
  1050. input.value = `${inputValue}`;
  1051. } else if (!isPromise(inputValue)) {
  1052. warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
  1053. }
  1054. };
  1055. /** @type {Record<string, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
  1056. const renderInputType = {};
  1057. /**
  1058. * @param {HTMLInputElement} input
  1059. * @param {SweetAlertOptions} params
  1060. * @returns {HTMLInputElement}
  1061. */
  1062. renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
  1063. checkAndSetInputValue(input, params.inputValue);
  1064. setInputLabel(input, input, params);
  1065. setInputPlaceholder(input, params);
  1066. input.type = params.input;
  1067. return input;
  1068. };
  1069. /**
  1070. * @param {HTMLInputElement} input
  1071. * @param {SweetAlertOptions} params
  1072. * @returns {HTMLInputElement}
  1073. */
  1074. renderInputType.file = (input, params) => {
  1075. setInputLabel(input, input, params);
  1076. setInputPlaceholder(input, params);
  1077. return input;
  1078. };
  1079. /**
  1080. * @param {HTMLInputElement} range
  1081. * @param {SweetAlertOptions} params
  1082. * @returns {HTMLInputElement}
  1083. */
  1084. renderInputType.range = (range, params) => {
  1085. const rangeInput = range.querySelector('input');
  1086. const rangeOutput = range.querySelector('output');
  1087. checkAndSetInputValue(rangeInput, params.inputValue);
  1088. rangeInput.type = params.input;
  1089. checkAndSetInputValue(rangeOutput, params.inputValue);
  1090. setInputLabel(rangeInput, range, params);
  1091. return range;
  1092. };
  1093. /**
  1094. * @param {HTMLSelectElement} select
  1095. * @param {SweetAlertOptions} params
  1096. * @returns {HTMLSelectElement}
  1097. */
  1098. renderInputType.select = (select, params) => {
  1099. select.textContent = '';
  1100. if (params.inputPlaceholder) {
  1101. const placeholder = document.createElement('option');
  1102. setInnerHtml(placeholder, params.inputPlaceholder);
  1103. placeholder.value = '';
  1104. placeholder.disabled = true;
  1105. placeholder.selected = true;
  1106. select.appendChild(placeholder);
  1107. }
  1108. setInputLabel(select, select, params);
  1109. return select;
  1110. };
  1111. /**
  1112. * @param {HTMLInputElement} radio
  1113. * @returns {HTMLInputElement}
  1114. */
  1115. renderInputType.radio = radio => {
  1116. radio.textContent = '';
  1117. return radio;
  1118. };
  1119. /**
  1120. * @param {HTMLLabelElement} checkboxContainer
  1121. * @param {SweetAlertOptions} params
  1122. * @returns {HTMLInputElement}
  1123. */
  1124. renderInputType.checkbox = (checkboxContainer, params) => {
  1125. const checkbox = getInput$1(getPopup(), 'checkbox');
  1126. checkbox.value = '1';
  1127. checkbox.id = swalClasses.checkbox;
  1128. checkbox.checked = Boolean(params.inputValue);
  1129. const label = checkboxContainer.querySelector('span');
  1130. setInnerHtml(label, params.inputPlaceholder);
  1131. return checkbox;
  1132. };
  1133. /**
  1134. * @param {HTMLTextAreaElement} textarea
  1135. * @param {SweetAlertOptions} params
  1136. * @returns {HTMLTextAreaElement}
  1137. */
  1138. renderInputType.textarea = (textarea, params) => {
  1139. checkAndSetInputValue(textarea, params.inputValue);
  1140. setInputPlaceholder(textarea, params);
  1141. setInputLabel(textarea, textarea, params);
  1142. /**
  1143. * @param {HTMLElement} el
  1144. * @returns {number}
  1145. */
  1146. const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
  1147. // https://github.com/sweetalert2/sweetalert2/issues/2291
  1148. setTimeout(() => {
  1149. // https://github.com/sweetalert2/sweetalert2/issues/1699
  1150. if ('MutationObserver' in window) {
  1151. const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
  1152. const textareaResizeHandler = () => {
  1153. const textareaWidth = textarea.offsetWidth + getMargin(textarea);
  1154. if (textareaWidth > initialPopupWidth) {
  1155. getPopup().style.width = `${textareaWidth}px`;
  1156. } else {
  1157. getPopup().style.width = null;
  1158. }
  1159. };
  1160. new MutationObserver(textareaResizeHandler).observe(textarea, {
  1161. attributes: true,
  1162. attributeFilter: ['style']
  1163. });
  1164. }
  1165. });
  1166. return textarea;
  1167. };
  1168. /**
  1169. * @param {SweetAlert2} instance
  1170. * @param {SweetAlertOptions} params
  1171. */
  1172. const renderContent = (instance, params) => {
  1173. const htmlContainer = getHtmlContainer();
  1174. applyCustomClass(htmlContainer, params, 'htmlContainer');
  1175. // Content as HTML
  1176. if (params.html) {
  1177. parseHtmlToContainer(params.html, htmlContainer);
  1178. show(htmlContainer, 'block');
  1179. }
  1180. // Content as plain text
  1181. else if (params.text) {
  1182. htmlContainer.textContent = params.text;
  1183. show(htmlContainer, 'block');
  1184. }
  1185. // No content
  1186. else {
  1187. hide(htmlContainer);
  1188. }
  1189. renderInput(instance, params);
  1190. };
  1191. /**
  1192. * @param {SweetAlert2} instance
  1193. * @param {SweetAlertOptions} params
  1194. */
  1195. const renderFooter = (instance, params) => {
  1196. const footer = getFooter();
  1197. toggle(footer, params.footer);
  1198. if (params.footer) {
  1199. parseHtmlToContainer(params.footer, footer);
  1200. }
  1201. // Custom class
  1202. applyCustomClass(footer, params, 'footer');
  1203. };
  1204. /**
  1205. * @param {SweetAlert2} instance
  1206. * @param {SweetAlertOptions} params
  1207. */
  1208. const renderIcon = (instance, params) => {
  1209. const innerParams = privateProps.innerParams.get(instance);
  1210. const icon = getIcon();
  1211. // if the given icon already rendered, apply the styling without re-rendering the icon
  1212. if (innerParams && params.icon === innerParams.icon) {
  1213. // Custom or default content
  1214. setContent(icon, params);
  1215. applyStyles(icon, params);
  1216. return;
  1217. }
  1218. if (!params.icon && !params.iconHtml) {
  1219. hide(icon);
  1220. return;
  1221. }
  1222. if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
  1223. error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
  1224. hide(icon);
  1225. return;
  1226. }
  1227. show(icon);
  1228. // Custom or default content
  1229. setContent(icon, params);
  1230. applyStyles(icon, params);
  1231. // Animate icon
  1232. addClass(icon, params.showClass.icon);
  1233. };
  1234. /**
  1235. * @param {HTMLElement} icon
  1236. * @param {SweetAlertOptions} params
  1237. */
  1238. const applyStyles = (icon, params) => {
  1239. for (const iconType in iconTypes) {
  1240. if (params.icon !== iconType) {
  1241. removeClass(icon, iconTypes[iconType]);
  1242. }
  1243. }
  1244. addClass(icon, iconTypes[params.icon]);
  1245. // Icon color
  1246. setColor(icon, params);
  1247. // Success icon background color
  1248. adjustSuccessIconBackgroundColor();
  1249. // Custom class
  1250. applyCustomClass(icon, params, 'icon');
  1251. };
  1252. // Adjust success icon background color to match the popup background color
  1253. const adjustSuccessIconBackgroundColor = () => {
  1254. const popup = getPopup();
  1255. const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
  1256. /** @type {NodeListOf<HTMLElement>} */
  1257. const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
  1258. for (let i = 0; i < successIconParts.length; i++) {
  1259. successIconParts[i].style.backgroundColor = popupBackgroundColor;
  1260. }
  1261. };
  1262. const successIconHtml = `
  1263. <div class="swal2-success-circular-line-left"></div>
  1264. <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
  1265. <div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>
  1266. <div class="swal2-success-circular-line-right"></div>
  1267. `;
  1268. const errorIconHtml = `
  1269. <span class="swal2-x-mark">
  1270. <span class="swal2-x-mark-line-left"></span>
  1271. <span class="swal2-x-mark-line-right"></span>
  1272. </span>
  1273. `;
  1274. /**
  1275. * @param {HTMLElement} icon
  1276. * @param {SweetAlertOptions} params
  1277. */
  1278. const setContent = (icon, params) => {
  1279. let oldContent = icon.innerHTML;
  1280. let newContent;
  1281. if (params.iconHtml) {
  1282. newContent = iconContent(params.iconHtml);
  1283. } else if (params.icon === 'success') {
  1284. newContent = successIconHtml;
  1285. oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
  1286. } else if (params.icon === 'error') {
  1287. newContent = errorIconHtml;
  1288. } else {
  1289. const defaultIconHtml = {
  1290. question: '?',
  1291. warning: '!',
  1292. info: 'i'
  1293. };
  1294. newContent = iconContent(defaultIconHtml[params.icon]);
  1295. }
  1296. if (oldContent.trim() !== newContent.trim()) {
  1297. setInnerHtml(icon, newContent);
  1298. }
  1299. };
  1300. /**
  1301. * @param {HTMLElement} icon
  1302. * @param {SweetAlertOptions} params
  1303. */
  1304. const setColor = (icon, params) => {
  1305. if (!params.iconColor) {
  1306. return;
  1307. }
  1308. icon.style.color = params.iconColor;
  1309. icon.style.borderColor = params.iconColor;
  1310. for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
  1311. setStyle(icon, sel, 'backgroundColor', params.iconColor);
  1312. }
  1313. setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
  1314. };
  1315. /**
  1316. * @param {string} content
  1317. * @returns {string}
  1318. */
  1319. const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;
  1320. /**
  1321. * @param {SweetAlert2} instance
  1322. * @param {SweetAlertOptions} params
  1323. */
  1324. const renderImage = (instance, params) => {
  1325. const image = getImage();
  1326. if (!params.imageUrl) {
  1327. hide(image);
  1328. return;
  1329. }
  1330. show(image, '');
  1331. // Src, alt
  1332. image.setAttribute('src', params.imageUrl);
  1333. image.setAttribute('alt', params.imageAlt);
  1334. // Width, height
  1335. applyNumericalStyle(image, 'width', params.imageWidth);
  1336. applyNumericalStyle(image, 'height', params.imageHeight);
  1337. // Class
  1338. image.className = swalClasses.image;
  1339. applyCustomClass(image, params, 'image');
  1340. };
  1341. /**
  1342. * @param {SweetAlert2} instance
  1343. * @param {SweetAlertOptions} params
  1344. */
  1345. const renderPopup = (instance, params) => {
  1346. const container = getContainer();
  1347. const popup = getPopup();
  1348. // Width
  1349. // https://github.com/sweetalert2/sweetalert2/issues/2170
  1350. if (params.toast) {
  1351. applyNumericalStyle(container, 'width', params.width);
  1352. popup.style.width = '100%';
  1353. popup.insertBefore(getLoader(), getIcon());
  1354. } else {
  1355. applyNumericalStyle(popup, 'width', params.width);
  1356. }
  1357. // Padding
  1358. applyNumericalStyle(popup, 'padding', params.padding);
  1359. // Color
  1360. if (params.color) {
  1361. popup.style.color = params.color;
  1362. }
  1363. // Background
  1364. if (params.background) {
  1365. popup.style.background = params.background;
  1366. }
  1367. hide(getValidationMessage());
  1368. // Classes
  1369. addClasses$1(popup, params);
  1370. };
  1371. /**
  1372. * @param {HTMLElement} popup
  1373. * @param {SweetAlertOptions} params
  1374. */
  1375. const addClasses$1 = (popup, params) => {
  1376. // Default Class + showClass when updating Swal.update({})
  1377. popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? params.showClass.popup : ''}`;
  1378. if (params.toast) {
  1379. addClass([document.documentElement, document.body], swalClasses['toast-shown']);
  1380. addClass(popup, swalClasses.toast);
  1381. } else {
  1382. addClass(popup, swalClasses.modal);
  1383. }
  1384. // Custom class
  1385. applyCustomClass(popup, params, 'popup');
  1386. if (typeof params.customClass === 'string') {
  1387. addClass(popup, params.customClass);
  1388. }
  1389. // Icon class (#1842)
  1390. if (params.icon) {
  1391. addClass(popup, swalClasses[`icon-${params.icon}`]);
  1392. }
  1393. };
  1394. /**
  1395. * @param {SweetAlert2} instance
  1396. * @param {SweetAlertOptions} params
  1397. */
  1398. const renderProgressSteps = (instance, params) => {
  1399. const progressStepsContainer = getProgressSteps();
  1400. if (!params.progressSteps || params.progressSteps.length === 0) {
  1401. hide(progressStepsContainer);
  1402. return;
  1403. }
  1404. show(progressStepsContainer);
  1405. progressStepsContainer.textContent = '';
  1406. if (params.currentProgressStep >= params.progressSteps.length) {
  1407. warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
  1408. }
  1409. params.progressSteps.forEach((step, index) => {
  1410. const stepEl = createStepElement(step);
  1411. progressStepsContainer.appendChild(stepEl);
  1412. if (index === params.currentProgressStep) {
  1413. addClass(stepEl, swalClasses['active-progress-step']);
  1414. }
  1415. if (index !== params.progressSteps.length - 1) {
  1416. const lineEl = createLineElement(params);
  1417. progressStepsContainer.appendChild(lineEl);
  1418. }
  1419. });
  1420. };
  1421. /**
  1422. * @param {string} step
  1423. * @returns {HTMLLIElement}
  1424. */
  1425. const createStepElement = step => {
  1426. const stepEl = document.createElement('li');
  1427. addClass(stepEl, swalClasses['progress-step']);
  1428. setInnerHtml(stepEl, step);
  1429. return stepEl;
  1430. };
  1431. /**
  1432. * @param {SweetAlertOptions} params
  1433. * @returns {HTMLLIElement}
  1434. */
  1435. const createLineElement = params => {
  1436. const lineEl = document.createElement('li');
  1437. addClass(lineEl, swalClasses['progress-step-line']);
  1438. if (params.progressStepsDistance) {
  1439. applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
  1440. }
  1441. return lineEl;
  1442. };
  1443. /**
  1444. * @param {SweetAlert2} instance
  1445. * @param {SweetAlertOptions} params
  1446. */
  1447. const renderTitle = (instance, params) => {
  1448. const title = getTitle();
  1449. toggle(title, params.title || params.titleText, 'block');
  1450. if (params.title) {
  1451. parseHtmlToContainer(params.title, title);
  1452. }
  1453. if (params.titleText) {
  1454. title.innerText = params.titleText;
  1455. }
  1456. // Custom class
  1457. applyCustomClass(title, params, 'title');
  1458. };
  1459. /**
  1460. * @param {SweetAlert2} instance
  1461. * @param {SweetAlertOptions} params
  1462. */
  1463. const render = (instance, params) => {
  1464. renderPopup(instance, params);
  1465. renderContainer(instance, params);
  1466. renderProgressSteps(instance, params);
  1467. renderIcon(instance, params);
  1468. renderImage(instance, params);
  1469. renderTitle(instance, params);
  1470. renderCloseButton(instance, params);
  1471. renderContent(instance, params);
  1472. renderActions(instance, params);
  1473. renderFooter(instance, params);
  1474. if (typeof params.didRender === 'function') {
  1475. params.didRender(getPopup());
  1476. }
  1477. };
  1478. /**
  1479. * Hides loader and shows back the button which was hidden by .showLoading()
  1480. */
  1481. function hideLoading() {
  1482. // do nothing if popup is closed
  1483. const innerParams = privateProps.innerParams.get(this);
  1484. if (!innerParams) {
  1485. return;
  1486. }
  1487. const domCache = privateProps.domCache.get(this);
  1488. hide(domCache.loader);
  1489. if (isToast()) {
  1490. if (innerParams.icon) {
  1491. show(getIcon());
  1492. }
  1493. } else {
  1494. showRelatedButton(domCache);
  1495. }
  1496. removeClass([domCache.popup, domCache.actions], swalClasses.loading);
  1497. domCache.popup.removeAttribute('aria-busy');
  1498. domCache.popup.removeAttribute('data-loading');
  1499. domCache.confirmButton.disabled = false;
  1500. domCache.denyButton.disabled = false;
  1501. domCache.cancelButton.disabled = false;
  1502. }
  1503. const showRelatedButton = domCache => {
  1504. const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
  1505. if (buttonToReplace.length) {
  1506. show(buttonToReplace[0], 'inline-block');
  1507. } else if (allButtonsAreHidden()) {
  1508. hide(domCache.actions);
  1509. }
  1510. };
  1511. /**
  1512. * Gets the input DOM node, this method works with input parameter.
  1513. *
  1514. * @param {SweetAlert2} instance
  1515. * @returns {HTMLElement | null}
  1516. */
  1517. function getInput(instance) {
  1518. const innerParams = privateProps.innerParams.get(instance || this);
  1519. const domCache = privateProps.domCache.get(instance || this);
  1520. if (!domCache) {
  1521. return null;
  1522. }
  1523. return getInput$1(domCache.popup, innerParams.input);
  1524. }
  1525. /*
  1526. * Global function to determine if SweetAlert2 popup is shown
  1527. */
  1528. const isVisible = () => {
  1529. return isVisible$1(getPopup());
  1530. };
  1531. /*
  1532. * Global function to click 'Confirm' button
  1533. */
  1534. const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
  1535. /*
  1536. * Global function to click 'Deny' button
  1537. */
  1538. const clickDeny = () => getDenyButton() && getDenyButton().click();
  1539. /*
  1540. * Global function to click 'Cancel' button
  1541. */
  1542. const clickCancel = () => getCancelButton() && getCancelButton().click();
  1543. const DismissReason = Object.freeze({
  1544. cancel: 'cancel',
  1545. backdrop: 'backdrop',
  1546. close: 'close',
  1547. esc: 'esc',
  1548. timer: 'timer'
  1549. });
  1550. /**
  1551. * @param {GlobalState} globalState
  1552. */
  1553. const removeKeydownHandler = globalState => {
  1554. if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
  1555. globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
  1556. capture: globalState.keydownListenerCapture
  1557. });
  1558. globalState.keydownHandlerAdded = false;
  1559. }
  1560. };
  1561. /**
  1562. * @param {SweetAlert2} instance
  1563. * @param {GlobalState} globalState
  1564. * @param {SweetAlertOptions} innerParams
  1565. * @param {*} dismissWith
  1566. */
  1567. const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
  1568. removeKeydownHandler(globalState);
  1569. if (!innerParams.toast) {
  1570. globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
  1571. globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
  1572. globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
  1573. globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
  1574. capture: globalState.keydownListenerCapture
  1575. });
  1576. globalState.keydownHandlerAdded = true;
  1577. }
  1578. };
  1579. /**
  1580. * @param {number} index
  1581. * @param {number} increment
  1582. */
  1583. const setFocus = (index, increment) => {
  1584. const focusableElements = getFocusableElements();
  1585. // search for visible elements and select the next possible match
  1586. if (focusableElements.length) {
  1587. index = index + increment;
  1588. // rollover to first item
  1589. if (index === focusableElements.length) {
  1590. index = 0;
  1591. // go to last item
  1592. } else if (index === -1) {
  1593. index = focusableElements.length - 1;
  1594. }
  1595. focusableElements[index].focus();
  1596. return;
  1597. }
  1598. // no visible focusable elements, focus the popup
  1599. getPopup().focus();
  1600. };
  1601. const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
  1602. const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
  1603. /**
  1604. * @param {SweetAlert2} instance
  1605. * @param {KeyboardEvent} event
  1606. * @param {Function} dismissWith
  1607. */
  1608. const keydownHandler = (instance, event, dismissWith) => {
  1609. const innerParams = privateProps.innerParams.get(instance);
  1610. if (!innerParams) {
  1611. return; // This instance has already been destroyed
  1612. }
  1613. // Ignore keydown during IME composition
  1614. // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition
  1615. // https://github.com/sweetalert2/sweetalert2/issues/720
  1616. // https://github.com/sweetalert2/sweetalert2/issues/2406
  1617. if (event.isComposing || event.keyCode === 229) {
  1618. return;
  1619. }
  1620. if (innerParams.stopKeydownPropagation) {
  1621. event.stopPropagation();
  1622. }
  1623. // ENTER
  1624. if (event.key === 'Enter') {
  1625. handleEnter(instance, event, innerParams);
  1626. }
  1627. // TAB
  1628. else if (event.key === 'Tab') {
  1629. handleTab(event);
  1630. }
  1631. // ARROWS - switch focus between buttons
  1632. else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
  1633. handleArrows(event.key);
  1634. }
  1635. // ESC
  1636. else if (event.key === 'Escape') {
  1637. handleEsc(event, innerParams, dismissWith);
  1638. }
  1639. };
  1640. /**
  1641. * @param {SweetAlert2} instance
  1642. * @param {KeyboardEvent} event
  1643. * @param {SweetAlertOptions} innerParams
  1644. */
  1645. const handleEnter = (instance, event, innerParams) => {
  1646. // https://github.com/sweetalert2/sweetalert2/issues/2386
  1647. if (!callIfFunction(innerParams.allowEnterKey)) {
  1648. return;
  1649. }
  1650. if (event.target && instance.getInput() && event.target instanceof HTMLElement && event.target.outerHTML === instance.getInput().outerHTML) {
  1651. if (['textarea', 'file'].includes(innerParams.input)) {
  1652. return; // do not submit
  1653. }
  1654. clickConfirm();
  1655. event.preventDefault();
  1656. }
  1657. };
  1658. /**
  1659. * @param {KeyboardEvent} event
  1660. */
  1661. const handleTab = event => {
  1662. const targetElement = event.target;
  1663. const focusableElements = getFocusableElements();
  1664. let btnIndex = -1;
  1665. for (let i = 0; i < focusableElements.length; i++) {
  1666. if (targetElement === focusableElements[i]) {
  1667. btnIndex = i;
  1668. break;
  1669. }
  1670. }
  1671. // Cycle to the next button
  1672. if (!event.shiftKey) {
  1673. setFocus(btnIndex, 1);
  1674. }
  1675. // Cycle to the prev button
  1676. else {
  1677. setFocus(btnIndex, -1);
  1678. }
  1679. event.stopPropagation();
  1680. event.preventDefault();
  1681. };
  1682. /**
  1683. * @param {string} key
  1684. */
  1685. const handleArrows = key => {
  1686. const confirmButton = getConfirmButton();
  1687. const denyButton = getDenyButton();
  1688. const cancelButton = getCancelButton();
  1689. /** @type HTMLElement[] */
  1690. const buttons = [confirmButton, denyButton, cancelButton];
  1691. if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
  1692. return;
  1693. }
  1694. const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
  1695. let buttonToFocus = document.activeElement;
  1696. for (let i = 0; i < getActions().children.length; i++) {
  1697. buttonToFocus = buttonToFocus[sibling];
  1698. if (!buttonToFocus) {
  1699. return;
  1700. }
  1701. if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
  1702. break;
  1703. }
  1704. }
  1705. if (buttonToFocus instanceof HTMLButtonElement) {
  1706. buttonToFocus.focus();
  1707. }
  1708. };
  1709. /**
  1710. * @param {KeyboardEvent} event
  1711. * @param {SweetAlertOptions} innerParams
  1712. * @param {Function} dismissWith
  1713. */
  1714. const handleEsc = (event, innerParams, dismissWith) => {
  1715. if (callIfFunction(innerParams.allowEscapeKey)) {
  1716. event.preventDefault();
  1717. dismissWith(DismissReason.esc);
  1718. }
  1719. };
  1720. /**
  1721. * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
  1722. * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
  1723. * This is the approach that Babel will probably take to implement private methods/fields
  1724. * https://github.com/tc39/proposal-private-methods
  1725. * https://github.com/babel/babel/pull/7555
  1726. * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
  1727. * then we can use that language feature.
  1728. */
  1729. var privateMethods = {
  1730. swalPromiseResolve: new WeakMap(),
  1731. swalPromiseReject: new WeakMap()
  1732. };
  1733. // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/
  1734. // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
  1735. // elements not within the active modal dialog will not be surfaced if a user opens a screen
  1736. // reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
  1737. const setAriaHidden = () => {
  1738. const bodyChildren = Array.from(document.body.children);
  1739. bodyChildren.forEach(el => {
  1740. if (el === getContainer() || el.contains(getContainer())) {
  1741. return;
  1742. }
  1743. if (el.hasAttribute('aria-hidden')) {
  1744. el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
  1745. }
  1746. el.setAttribute('aria-hidden', 'true');
  1747. });
  1748. };
  1749. const unsetAriaHidden = () => {
  1750. const bodyChildren = Array.from(document.body.children);
  1751. bodyChildren.forEach(el => {
  1752. if (el.hasAttribute('data-previous-aria-hidden')) {
  1753. el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
  1754. el.removeAttribute('data-previous-aria-hidden');
  1755. } else {
  1756. el.removeAttribute('aria-hidden');
  1757. }
  1758. });
  1759. };
  1760. /* istanbul ignore file */
  1761. // Fix iOS scrolling http://stackoverflow.com/q/39626302
  1762. const iOSfix = () => {
  1763. const iOS =
  1764. // @ts-ignore
  1765. /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
  1766. if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
  1767. const offset = document.body.scrollTop;
  1768. document.body.style.top = `${offset * -1}px`;
  1769. addClass(document.body, swalClasses.iosfix);
  1770. lockBodyScroll();
  1771. addBottomPaddingForTallPopups();
  1772. }
  1773. };
  1774. /**
  1775. * https://github.com/sweetalert2/sweetalert2/issues/1948
  1776. */
  1777. const addBottomPaddingForTallPopups = () => {
  1778. const ua = navigator.userAgent;
  1779. const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
  1780. const webkit = !!ua.match(/WebKit/i);
  1781. const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  1782. if (iOSSafari) {
  1783. const bottomPanelHeight = 44;
  1784. if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
  1785. getContainer().style.paddingBottom = `${bottomPanelHeight}px`;
  1786. }
  1787. }
  1788. };
  1789. /**
  1790. * https://github.com/sweetalert2/sweetalert2/issues/1246
  1791. */
  1792. const lockBodyScroll = () => {
  1793. const container = getContainer();
  1794. let preventTouchMove;
  1795. /**
  1796. * @param {TouchEvent} event
  1797. */
  1798. container.ontouchstart = event => {
  1799. preventTouchMove = shouldPreventTouchMove(event);
  1800. };
  1801. /**
  1802. * @param {TouchEvent} event
  1803. */
  1804. container.ontouchmove = event => {
  1805. if (preventTouchMove) {
  1806. event.preventDefault();
  1807. event.stopPropagation();
  1808. }
  1809. };
  1810. };
  1811. /**
  1812. * @param {TouchEvent} event
  1813. * @returns {boolean}
  1814. */
  1815. const shouldPreventTouchMove = event => {
  1816. const target = event.target;
  1817. const container = getContainer();
  1818. if (isStylus(event) || isZoom(event)) {
  1819. return false;
  1820. }
  1821. if (target === container) {
  1822. return true;
  1823. }
  1824. if (!isScrollable(container) && target instanceof HTMLElement && target.tagName !== 'INPUT' &&
  1825. // #1603
  1826. target.tagName !== 'TEXTAREA' &&
  1827. // #2266
  1828. !(isScrollable(getHtmlContainer()) &&
  1829. // #1944
  1830. getHtmlContainer().contains(target))) {
  1831. return true;
  1832. }
  1833. return false;
  1834. };
  1835. /**
  1836. * https://github.com/sweetalert2/sweetalert2/issues/1786
  1837. *
  1838. * @param {*} event
  1839. * @returns {boolean}
  1840. */
  1841. const isStylus = event => {
  1842. return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
  1843. };
  1844. /**
  1845. * https://github.com/sweetalert2/sweetalert2/issues/1891
  1846. *
  1847. * @param {TouchEvent} event
  1848. * @returns {boolean}
  1849. */
  1850. const isZoom = event => {
  1851. return event.touches && event.touches.length > 1;
  1852. };
  1853. const undoIOSfix = () => {
  1854. if (hasClass(document.body, swalClasses.iosfix)) {
  1855. const offset = parseInt(document.body.style.top, 10);
  1856. removeClass(document.body, swalClasses.iosfix);
  1857. document.body.style.top = '';
  1858. document.body.scrollTop = offset * -1;
  1859. }
  1860. };
  1861. const fixScrollbar = () => {
  1862. // for queues, do not do this more than once
  1863. if (states.previousBodyPadding !== null) {
  1864. return;
  1865. }
  1866. // if the body has overflow
  1867. if (document.body.scrollHeight > window.innerHeight) {
  1868. // add padding so the content doesn't shift after removal of scrollbar
  1869. states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
  1870. document.body.style.paddingRight = `${states.previousBodyPadding + measureScrollbar()}px`;
  1871. }
  1872. };
  1873. const undoScrollbar = () => {
  1874. if (states.previousBodyPadding !== null) {
  1875. document.body.style.paddingRight = `${states.previousBodyPadding}px`;
  1876. states.previousBodyPadding = null;
  1877. }
  1878. };
  1879. /**
  1880. * @param {SweetAlert2} instance
  1881. * @param {HTMLElement} container
  1882. * @param {boolean} returnFocus
  1883. * @param {Function} didClose
  1884. */
  1885. function removePopupAndResetState(instance, container, returnFocus, didClose) {
  1886. if (isToast()) {
  1887. triggerDidCloseAndDispose(instance, didClose);
  1888. } else {
  1889. restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
  1890. removeKeydownHandler(globalState);
  1891. }
  1892. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1893. // workaround for #2088
  1894. // for some reason removing the container in Safari will scroll the document to bottom
  1895. if (isSafari) {
  1896. container.setAttribute('style', 'display:none !important');
  1897. container.removeAttribute('class');
  1898. container.innerHTML = '';
  1899. } else {
  1900. container.remove();
  1901. }
  1902. if (isModal()) {
  1903. undoScrollbar();
  1904. undoIOSfix();
  1905. unsetAriaHidden();
  1906. }
  1907. removeBodyClasses();
  1908. }
  1909. /**
  1910. * Remove SweetAlert2 classes from body
  1911. */
  1912. function removeBodyClasses() {
  1913. removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
  1914. }
  1915. /**
  1916. * Instance method to close sweetAlert
  1917. *
  1918. * @param {any} resolveValue
  1919. */
  1920. function close(resolveValue) {
  1921. resolveValue = prepareResolveValue(resolveValue);
  1922. const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
  1923. const didClose = triggerClosePopup(this);
  1924. if (this.isAwaitingPromise()) {
  1925. // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
  1926. if (!resolveValue.isDismissed) {
  1927. handleAwaitingPromise(this);
  1928. swalPromiseResolve(resolveValue);
  1929. }
  1930. } else if (didClose) {
  1931. // Resolve Swal promise
  1932. swalPromiseResolve(resolveValue);
  1933. }
  1934. }
  1935. /**
  1936. * @returns {boolean}
  1937. */
  1938. function isAwaitingPromise() {
  1939. return !!privateProps.awaitingPromise.get(this);
  1940. }
  1941. const triggerClosePopup = instance => {
  1942. const popup = getPopup();
  1943. if (!popup) {
  1944. return false;
  1945. }
  1946. const innerParams = privateProps.innerParams.get(instance);
  1947. if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
  1948. return false;
  1949. }
  1950. removeClass(popup, innerParams.showClass.popup);
  1951. addClass(popup, innerParams.hideClass.popup);
  1952. const backdrop = getContainer();
  1953. removeClass(backdrop, innerParams.showClass.backdrop);
  1954. addClass(backdrop, innerParams.hideClass.backdrop);
  1955. handlePopupAnimation(instance, popup, innerParams);
  1956. return true;
  1957. };
  1958. /**
  1959. * @param {any} error
  1960. */
  1961. function rejectPromise(error) {
  1962. const rejectPromise = privateMethods.swalPromiseReject.get(this);
  1963. handleAwaitingPromise(this);
  1964. if (rejectPromise) {
  1965. // Reject Swal promise
  1966. rejectPromise(error);
  1967. }
  1968. }
  1969. /**
  1970. * @param {SweetAlert2} instance
  1971. */
  1972. const handleAwaitingPromise = instance => {
  1973. // @ts-ignore
  1974. if (instance.isAwaitingPromise()) {
  1975. privateProps.awaitingPromise.delete(instance);
  1976. // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
  1977. if (!privateProps.innerParams.get(instance)) {
  1978. // @ts-ignore
  1979. instance._destroy();
  1980. }
  1981. }
  1982. };
  1983. /**
  1984. * @param {any} resolveValue
  1985. * @returns {SweetAlertResult}
  1986. */
  1987. const prepareResolveValue = resolveValue => {
  1988. // When user calls Swal.close()
  1989. if (typeof resolveValue === 'undefined') {
  1990. return {
  1991. isConfirmed: false,
  1992. isDenied: false,
  1993. isDismissed: true
  1994. };
  1995. }
  1996. return Object.assign({
  1997. isConfirmed: false,
  1998. isDenied: false,
  1999. isDismissed: false
  2000. }, resolveValue);
  2001. };
  2002. /**
  2003. * @param {SweetAlert2} instance
  2004. * @param {HTMLElement} popup
  2005. * @param {SweetAlertOptions} innerParams
  2006. */
  2007. const handlePopupAnimation = (instance, popup, innerParams) => {
  2008. const container = getContainer();
  2009. // If animation is supported, animate
  2010. const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
  2011. if (typeof innerParams.willClose === 'function') {
  2012. innerParams.willClose(popup);
  2013. }
  2014. if (animationIsSupported) {
  2015. animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
  2016. } else {
  2017. // Otherwise, remove immediately
  2018. removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
  2019. }
  2020. };
  2021. /**
  2022. * @param {SweetAlert2} instance
  2023. * @param {HTMLElement} popup
  2024. * @param {HTMLElement} container
  2025. * @param {boolean} returnFocus
  2026. * @param {Function} didClose
  2027. */
  2028. const animatePopup = (instance, popup, container, returnFocus, didClose) => {
  2029. globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
  2030. popup.addEventListener(animationEndEvent, function (e) {
  2031. if (e.target === popup) {
  2032. globalState.swalCloseEventFinishedCallback();
  2033. delete globalState.swalCloseEventFinishedCallback;
  2034. }
  2035. });
  2036. };
  2037. /**
  2038. * @param {SweetAlert2} instance
  2039. * @param {Function} didClose
  2040. */
  2041. const triggerDidCloseAndDispose = (instance, didClose) => {
  2042. setTimeout(() => {
  2043. if (typeof didClose === 'function') {
  2044. // @ts-ignore
  2045. didClose.bind(instance.params)();
  2046. }
  2047. // @ts-ignore
  2048. instance._destroy();
  2049. });
  2050. };
  2051. /**
  2052. * @param {SweetAlert2} instance
  2053. * @param {string[]} buttons
  2054. * @param {boolean} disabled
  2055. */
  2056. function setButtonsDisabled(instance, buttons, disabled) {
  2057. const domCache = privateProps.domCache.get(instance);
  2058. buttons.forEach(button => {
  2059. domCache[button].disabled = disabled;
  2060. });
  2061. }
  2062. /**
  2063. * @param {HTMLInputElement} input
  2064. * @param {boolean} disabled
  2065. */
  2066. function setInputDisabled(input, disabled) {
  2067. if (!input) {
  2068. return;
  2069. }
  2070. if (input.type === 'radio') {
  2071. const radiosContainer = input.parentNode.parentNode;
  2072. const radios = radiosContainer.querySelectorAll('input');
  2073. for (let i = 0; i < radios.length; i++) {
  2074. radios[i].disabled = disabled;
  2075. }
  2076. } else {
  2077. input.disabled = disabled;
  2078. }
  2079. }
  2080. function enableButtons() {
  2081. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
  2082. }
  2083. function disableButtons() {
  2084. setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
  2085. }
  2086. function enableInput() {
  2087. setInputDisabled(this.getInput(), false);
  2088. }
  2089. function disableInput() {
  2090. setInputDisabled(this.getInput(), true);
  2091. }
  2092. /**
  2093. * Show block with validation message
  2094. *
  2095. * @param {string} error
  2096. */
  2097. function showValidationMessage(error) {
  2098. const domCache = privateProps.domCache.get(this);
  2099. const params = privateProps.innerParams.get(this);
  2100. setInnerHtml(domCache.validationMessage, error);
  2101. domCache.validationMessage.className = swalClasses['validation-message'];
  2102. if (params.customClass && params.customClass.validationMessage) {
  2103. addClass(domCache.validationMessage, params.customClass.validationMessage);
  2104. }
  2105. show(domCache.validationMessage);
  2106. const input = this.getInput();
  2107. if (input) {
  2108. input.setAttribute('aria-invalid', true);
  2109. input.setAttribute('aria-describedby', swalClasses['validation-message']);
  2110. focusInput(input);
  2111. addClass(input, swalClasses.inputerror);
  2112. }
  2113. }
  2114. /**
  2115. * Hide block with validation message
  2116. */
  2117. function resetValidationMessage() {
  2118. const domCache = privateProps.domCache.get(this);
  2119. if (domCache.validationMessage) {
  2120. hide(domCache.validationMessage);
  2121. }
  2122. const input = this.getInput();
  2123. if (input) {
  2124. input.removeAttribute('aria-invalid');
  2125. input.removeAttribute('aria-describedby');
  2126. removeClass(input, swalClasses.inputerror);
  2127. }
  2128. }
  2129. const defaultParams = {
  2130. title: '',
  2131. titleText: '',
  2132. text: '',
  2133. html: '',
  2134. footer: '',
  2135. icon: undefined,
  2136. iconColor: undefined,
  2137. iconHtml: undefined,
  2138. template: undefined,
  2139. toast: false,
  2140. showClass: {
  2141. popup: 'swal2-show',
  2142. backdrop: 'swal2-backdrop-show',
  2143. icon: 'swal2-icon-show'
  2144. },
  2145. hideClass: {
  2146. popup: 'swal2-hide',
  2147. backdrop: 'swal2-backdrop-hide',
  2148. icon: 'swal2-icon-hide'
  2149. },
  2150. customClass: {},
  2151. target: 'body',
  2152. color: undefined,
  2153. backdrop: true,
  2154. heightAuto: true,
  2155. allowOutsideClick: true,
  2156. allowEscapeKey: true,
  2157. allowEnterKey: true,
  2158. stopKeydownPropagation: true,
  2159. keydownListenerCapture: false,
  2160. showConfirmButton: true,
  2161. showDenyButton: false,
  2162. showCancelButton: false,
  2163. preConfirm: undefined,
  2164. preDeny: undefined,
  2165. confirmButtonText: 'OK',
  2166. confirmButtonAriaLabel: '',
  2167. confirmButtonColor: undefined,
  2168. denyButtonText: 'No',
  2169. denyButtonAriaLabel: '',
  2170. denyButtonColor: undefined,
  2171. cancelButtonText: 'Cancel',
  2172. cancelButtonAriaLabel: '',
  2173. cancelButtonColor: undefined,
  2174. buttonsStyling: true,
  2175. reverseButtons: false,
  2176. focusConfirm: true,
  2177. focusDeny: false,
  2178. focusCancel: false,
  2179. returnFocus: true,
  2180. showCloseButton: false,
  2181. closeButtonHtml: '&times;',
  2182. closeButtonAriaLabel: 'Close this dialog',
  2183. loaderHtml: '',
  2184. showLoaderOnConfirm: false,
  2185. showLoaderOnDeny: false,
  2186. imageUrl: undefined,
  2187. imageWidth: undefined,
  2188. imageHeight: undefined,
  2189. imageAlt: '',
  2190. timer: undefined,
  2191. timerProgressBar: false,
  2192. width: undefined,
  2193. padding: undefined,
  2194. background: undefined,
  2195. input: undefined,
  2196. inputPlaceholder: '',
  2197. inputLabel: '',
  2198. inputValue: '',
  2199. inputOptions: {},
  2200. inputAutoFocus: true,
  2201. inputAutoTrim: true,
  2202. inputAttributes: {},
  2203. inputValidator: undefined,
  2204. returnInputValueOnDeny: false,
  2205. validationMessage: undefined,
  2206. grow: false,
  2207. position: 'center',
  2208. progressSteps: [],
  2209. currentProgressStep: undefined,
  2210. progressStepsDistance: undefined,
  2211. willOpen: undefined,
  2212. didOpen: undefined,
  2213. didRender: undefined,
  2214. willClose: undefined,
  2215. didClose: undefined,
  2216. didDestroy: undefined,
  2217. scrollbarPadding: true
  2218. };
  2219. const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
  2220. const deprecatedParams = {};
  2221. const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
  2222. /**
  2223. * Is valid parameter
  2224. *
  2225. * @param {string} paramName
  2226. * @returns {boolean}
  2227. */
  2228. const isValidParameter = paramName => {
  2229. return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
  2230. };
  2231. /**
  2232. * Is valid parameter for Swal.update() method
  2233. *
  2234. * @param {string} paramName
  2235. * @returns {boolean}
  2236. */
  2237. const isUpdatableParameter = paramName => {
  2238. return updatableParams.indexOf(paramName) !== -1;
  2239. };
  2240. /**
  2241. * Is deprecated parameter
  2242. *
  2243. * @param {string} paramName
  2244. * @returns {string | undefined}
  2245. */
  2246. const isDeprecatedParameter = paramName => {
  2247. return deprecatedParams[paramName];
  2248. };
  2249. /**
  2250. * @param {string} param
  2251. */
  2252. const checkIfParamIsValid = param => {
  2253. if (!isValidParameter(param)) {
  2254. warn(`Unknown parameter "${param}"`);
  2255. }
  2256. };
  2257. /**
  2258. * @param {string} param
  2259. */
  2260. const checkIfToastParamIsValid = param => {
  2261. if (toastIncompatibleParams.includes(param)) {
  2262. warn(`The parameter "${param}" is incompatible with toasts`);
  2263. }
  2264. };
  2265. /**
  2266. * @param {string} param
  2267. */
  2268. const checkIfParamIsDeprecated = param => {
  2269. if (isDeprecatedParameter(param)) {
  2270. warnAboutDeprecation(param, isDeprecatedParameter(param));
  2271. }
  2272. };
  2273. /**
  2274. * Show relevant warnings for given params
  2275. *
  2276. * @param {SweetAlertOptions} params
  2277. */
  2278. const showWarningsForParams = params => {
  2279. if (params.backdrop === false && params.allowOutsideClick) {
  2280. warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
  2281. }
  2282. for (const param in params) {
  2283. checkIfParamIsValid(param);
  2284. if (params.toast) {
  2285. checkIfToastParamIsValid(param);
  2286. }
  2287. checkIfParamIsDeprecated(param);
  2288. }
  2289. };
  2290. /**
  2291. * Updates popup parameters.
  2292. *
  2293. * @param {SweetAlertOptions} params
  2294. */
  2295. function update(params) {
  2296. const popup = getPopup();
  2297. const innerParams = privateProps.innerParams.get(this);
  2298. if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
  2299. warn(`You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.`);
  2300. return;
  2301. }
  2302. const validUpdatableParams = filterValidParams(params);
  2303. const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
  2304. render(this, updatedParams);
  2305. privateProps.innerParams.set(this, updatedParams);
  2306. Object.defineProperties(this, {
  2307. params: {
  2308. value: Object.assign({}, this.params, params),
  2309. writable: false,
  2310. enumerable: true
  2311. }
  2312. });
  2313. }
  2314. /**
  2315. * @param {SweetAlertOptions} params
  2316. * @returns {SweetAlertOptions}
  2317. */
  2318. const filterValidParams = params => {
  2319. const validUpdatableParams = {};
  2320. Object.keys(params).forEach(param => {
  2321. if (isUpdatableParameter(param)) {
  2322. validUpdatableParams[param] = params[param];
  2323. } else {
  2324. warn(`Invalid parameter to update: ${param}`);
  2325. }
  2326. });
  2327. return validUpdatableParams;
  2328. };
  2329. /**
  2330. * Dispose the current SweetAlert2 instance
  2331. */
  2332. function _destroy() {
  2333. const domCache = privateProps.domCache.get(this);
  2334. const innerParams = privateProps.innerParams.get(this);
  2335. if (!innerParams) {
  2336. disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
  2337. return; // This instance has already been destroyed
  2338. }
  2339. // Check if there is another Swal closing
  2340. if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
  2341. globalState.swalCloseEventFinishedCallback();
  2342. delete globalState.swalCloseEventFinishedCallback;
  2343. }
  2344. if (typeof innerParams.didDestroy === 'function') {
  2345. innerParams.didDestroy();
  2346. }
  2347. disposeSwal(this);
  2348. }
  2349. /**
  2350. * @param {SweetAlert2} instance
  2351. */
  2352. const disposeSwal = instance => {
  2353. disposeWeakMaps(instance);
  2354. // Unset this.params so GC will dispose it (#1569)
  2355. // @ts-ignore
  2356. delete instance.params;
  2357. // Unset globalState props so GC will dispose globalState (#1569)
  2358. delete globalState.keydownHandler;
  2359. delete globalState.keydownTarget;
  2360. // Unset currentInstance
  2361. delete globalState.currentInstance;
  2362. };
  2363. /**
  2364. * @param {SweetAlert2} instance
  2365. */
  2366. const disposeWeakMaps = instance => {
  2367. // If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
  2368. // @ts-ignore
  2369. if (instance.isAwaitingPromise()) {
  2370. unsetWeakMaps(privateProps, instance);
  2371. privateProps.awaitingPromise.set(instance, true);
  2372. } else {
  2373. unsetWeakMaps(privateMethods, instance);
  2374. unsetWeakMaps(privateProps, instance);
  2375. }
  2376. };
  2377. /**
  2378. * @param {object} obj
  2379. * @param {SweetAlert2} instance
  2380. */
  2381. const unsetWeakMaps = (obj, instance) => {
  2382. for (const i in obj) {
  2383. obj[i].delete(instance);
  2384. }
  2385. };
  2386. var instanceMethods = /*#__PURE__*/Object.freeze({
  2387. __proto__: null,
  2388. _destroy: _destroy,
  2389. close: close,
  2390. closeModal: close,
  2391. closePopup: close,
  2392. closeToast: close,
  2393. disableButtons: disableButtons,
  2394. disableInput: disableInput,
  2395. disableLoading: hideLoading,
  2396. enableButtons: enableButtons,
  2397. enableInput: enableInput,
  2398. getInput: getInput,
  2399. handleAwaitingPromise: handleAwaitingPromise,
  2400. hideLoading: hideLoading,
  2401. isAwaitingPromise: isAwaitingPromise,
  2402. rejectPromise: rejectPromise,
  2403. resetValidationMessage: resetValidationMessage,
  2404. showValidationMessage: showValidationMessage,
  2405. update: update
  2406. });
  2407. /**
  2408. * Shows loader (spinner), this is useful with AJAX requests.
  2409. * By default the loader be shown instead of the "Confirm" button.
  2410. *
  2411. * @param {HTMLButtonElement} [buttonToReplace]
  2412. */
  2413. const showLoading = buttonToReplace => {
  2414. let popup = getPopup();
  2415. if (!popup) {
  2416. new Swal(); // eslint-disable-line no-new
  2417. }
  2418. popup = getPopup();
  2419. const loader = getLoader();
  2420. if (isToast()) {
  2421. hide(getIcon());
  2422. } else {
  2423. replaceButton(popup, buttonToReplace);
  2424. }
  2425. show(loader);
  2426. popup.setAttribute('data-loading', 'true');
  2427. popup.setAttribute('aria-busy', 'true');
  2428. popup.focus();
  2429. };
  2430. /**
  2431. * @param {HTMLElement} popup
  2432. * @param {HTMLButtonElement} [buttonToReplace]
  2433. */
  2434. const replaceButton = (popup, buttonToReplace) => {
  2435. const actions = getActions();
  2436. const loader = getLoader();
  2437. if (!buttonToReplace && isVisible$1(getConfirmButton())) {
  2438. buttonToReplace = getConfirmButton();
  2439. }
  2440. show(actions);
  2441. if (buttonToReplace) {
  2442. hide(buttonToReplace);
  2443. loader.setAttribute('data-button-to-replace', buttonToReplace.className);
  2444. }
  2445. loader.parentNode.insertBefore(loader, buttonToReplace);
  2446. addClass([popup, actions], swalClasses.loading);
  2447. };
  2448. /**
  2449. * @typedef { string | number | boolean } InputValue
  2450. */
  2451. /**
  2452. * @param {SweetAlert2} instance
  2453. * @param {SweetAlertOptions} params
  2454. */
  2455. const handleInputOptionsAndValue = (instance, params) => {
  2456. if (params.input === 'select' || params.input === 'radio') {
  2457. handleInputOptions(instance, params);
  2458. } else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
  2459. showLoading(getConfirmButton());
  2460. handleInputValue(instance, params);
  2461. }
  2462. };
  2463. /**
  2464. * @param {SweetAlert2} instance
  2465. * @param {SweetAlertOptions} innerParams
  2466. * @returns {string | number | File | FileList | null}
  2467. */
  2468. const getInputValue = (instance, innerParams) => {
  2469. const input = instance.getInput();
  2470. if (!input) {
  2471. return null;
  2472. }
  2473. switch (innerParams.input) {
  2474. case 'checkbox':
  2475. return getCheckboxValue(input);
  2476. case 'radio':
  2477. return getRadioValue(input);
  2478. case 'file':
  2479. return getFileValue(input);
  2480. default:
  2481. return innerParams.inputAutoTrim ? input.value.trim() : input.value;
  2482. }
  2483. };
  2484. /**
  2485. * @param {HTMLInputElement} input
  2486. * @returns {number}
  2487. */
  2488. const getCheckboxValue = input => input.checked ? 1 : 0;
  2489. /**
  2490. * @param {HTMLInputElement} input
  2491. * @returns {string | null}
  2492. */
  2493. const getRadioValue = input => input.checked ? input.value : null;
  2494. /**
  2495. * @param {HTMLInputElement} input
  2496. * @returns {FileList | File | null}
  2497. */
  2498. const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
  2499. /**
  2500. * @param {SweetAlert2} instance
  2501. * @param {SweetAlertOptions} params
  2502. */
  2503. const handleInputOptions = (instance, params) => {
  2504. const popup = getPopup();
  2505. /**
  2506. * @param {Record<string, any>} inputOptions
  2507. */
  2508. const processInputOptions = inputOptions => {
  2509. populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
  2510. };
  2511. if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
  2512. showLoading(getConfirmButton());
  2513. asPromise(params.inputOptions).then(inputOptions => {
  2514. instance.hideLoading();
  2515. processInputOptions(inputOptions);
  2516. });
  2517. } else if (typeof params.inputOptions === 'object') {
  2518. processInputOptions(params.inputOptions);
  2519. } else {
  2520. error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
  2521. }
  2522. };
  2523. /**
  2524. * @param {SweetAlert2} instance
  2525. * @param {SweetAlertOptions} params
  2526. */
  2527. const handleInputValue = (instance, params) => {
  2528. const input = instance.getInput();
  2529. hide(input);
  2530. asPromise(params.inputValue).then(inputValue => {
  2531. input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
  2532. show(input);
  2533. input.focus();
  2534. instance.hideLoading();
  2535. }).catch(err => {
  2536. error(`Error in inputValue promise: ${err}`);
  2537. input.value = '';
  2538. show(input);
  2539. input.focus();
  2540. instance.hideLoading();
  2541. });
  2542. };
  2543. const populateInputOptions = {
  2544. /**
  2545. * @param {HTMLElement} popup
  2546. * @param {Record<string, any>} inputOptions
  2547. * @param {SweetAlertOptions} params
  2548. */
  2549. select: (popup, inputOptions, params) => {
  2550. const select = getDirectChildByClass(popup, swalClasses.select);
  2551. /**
  2552. * @param {HTMLElement} parent
  2553. * @param {string} optionLabel
  2554. * @param {string} optionValue
  2555. */
  2556. const renderOption = (parent, optionLabel, optionValue) => {
  2557. const option = document.createElement('option');
  2558. option.value = optionValue;
  2559. setInnerHtml(option, optionLabel);
  2560. option.selected = isSelected(optionValue, params.inputValue);
  2561. parent.appendChild(option);
  2562. };
  2563. inputOptions.forEach(inputOption => {
  2564. const optionValue = inputOption[0];
  2565. const optionLabel = inputOption[1];
  2566. // <optgroup> spec:
  2567. // https://www.w3.org/TR/html401/interact/forms.html#h-17.6
  2568. // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
  2569. // check whether this is a <optgroup>
  2570. if (Array.isArray(optionLabel)) {
  2571. // if it is an array, then it is an <optgroup>
  2572. const optgroup = document.createElement('optgroup');
  2573. optgroup.label = optionValue;
  2574. optgroup.disabled = false; // not configurable for now
  2575. select.appendChild(optgroup);
  2576. optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
  2577. } else {
  2578. // case of <option>
  2579. renderOption(select, optionLabel, optionValue);
  2580. }
  2581. });
  2582. select.focus();
  2583. },
  2584. /**
  2585. * @param {HTMLElement} popup
  2586. * @param {Record<string, any>} inputOptions
  2587. * @param {SweetAlertOptions} params
  2588. */
  2589. radio: (popup, inputOptions, params) => {
  2590. const radio = getDirectChildByClass(popup, swalClasses.radio);
  2591. inputOptions.forEach(inputOption => {
  2592. const radioValue = inputOption[0];
  2593. const radioLabel = inputOption[1];
  2594. const radioInput = document.createElement('input');
  2595. const radioLabelElement = document.createElement('label');
  2596. radioInput.type = 'radio';
  2597. radioInput.name = swalClasses.radio;
  2598. radioInput.value = radioValue;
  2599. if (isSelected(radioValue, params.inputValue)) {
  2600. radioInput.checked = true;
  2601. }
  2602. const label = document.createElement('span');
  2603. setInnerHtml(label, radioLabel);
  2604. label.className = swalClasses.label;
  2605. radioLabelElement.appendChild(radioInput);
  2606. radioLabelElement.appendChild(label);
  2607. radio.appendChild(radioLabelElement);
  2608. });
  2609. const radios = radio.querySelectorAll('input');
  2610. if (radios.length) {
  2611. radios[0].focus();
  2612. }
  2613. }
  2614. };
  2615. /**
  2616. * Converts `inputOptions` into an array of `[value, label]`s
  2617. *
  2618. * @param {Record<string, any>} inputOptions
  2619. * @returns {Array<Array<string>>}
  2620. */
  2621. const formatInputOptions = inputOptions => {
  2622. const result = [];
  2623. if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
  2624. inputOptions.forEach((value, key) => {
  2625. let valueFormatted = value;
  2626. if (typeof valueFormatted === 'object') {
  2627. // case of <optgroup>
  2628. valueFormatted = formatInputOptions(valueFormatted);
  2629. }
  2630. result.push([key, valueFormatted]);
  2631. });
  2632. } else {
  2633. Object.keys(inputOptions).forEach(key => {
  2634. let valueFormatted = inputOptions[key];
  2635. if (typeof valueFormatted === 'object') {
  2636. // case of <optgroup>
  2637. valueFormatted = formatInputOptions(valueFormatted);
  2638. }
  2639. result.push([key, valueFormatted]);
  2640. });
  2641. }
  2642. return result;
  2643. };
  2644. /**
  2645. * @param {string} optionValue
  2646. * @param {InputValue | Promise<InputValue> | { toPromise: () => InputValue }} inputValue
  2647. * @returns {boolean}
  2648. */
  2649. const isSelected = (optionValue, inputValue) => {
  2650. return inputValue && inputValue.toString() === optionValue.toString();
  2651. };
  2652. /**
  2653. * @param {SweetAlert2} instance
  2654. */
  2655. const handleConfirmButtonClick = instance => {
  2656. const innerParams = privateProps.innerParams.get(instance);
  2657. instance.disableButtons();
  2658. if (innerParams.input) {
  2659. handleConfirmOrDenyWithInput(instance, 'confirm');
  2660. } else {
  2661. confirm(instance, true);
  2662. }
  2663. };
  2664. /**
  2665. * @param {SweetAlert2} instance
  2666. */
  2667. const handleDenyButtonClick = instance => {
  2668. const innerParams = privateProps.innerParams.get(instance);
  2669. instance.disableButtons();
  2670. if (innerParams.returnInputValueOnDeny) {
  2671. handleConfirmOrDenyWithInput(instance, 'deny');
  2672. } else {
  2673. deny(instance, false);
  2674. }
  2675. };
  2676. /**
  2677. * @param {SweetAlert2} instance
  2678. * @param {Function} dismissWith
  2679. */
  2680. const handleCancelButtonClick = (instance, dismissWith) => {
  2681. instance.disableButtons();
  2682. dismissWith(DismissReason.cancel);
  2683. };
  2684. /**
  2685. * @param {SweetAlert2} instance
  2686. * @param {'confirm' | 'deny'} type
  2687. */
  2688. const handleConfirmOrDenyWithInput = (instance, type) => {
  2689. const innerParams = privateProps.innerParams.get(instance);
  2690. if (!innerParams.input) {
  2691. error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
  2692. return;
  2693. }
  2694. const inputValue = getInputValue(instance, innerParams);
  2695. if (innerParams.inputValidator) {
  2696. handleInputValidator(instance, inputValue, type);
  2697. } else if (!instance.getInput().checkValidity()) {
  2698. instance.enableButtons();
  2699. instance.showValidationMessage(innerParams.validationMessage);
  2700. } else if (type === 'deny') {
  2701. deny(instance, inputValue);
  2702. } else {
  2703. confirm(instance, inputValue);
  2704. }
  2705. };
  2706. /**
  2707. * @param {SweetAlert2} instance
  2708. * @param {string | number | File | FileList | null} inputValue
  2709. * @param {'confirm' | 'deny'} type
  2710. */
  2711. const handleInputValidator = (instance, inputValue, type) => {
  2712. const innerParams = privateProps.innerParams.get(instance);
  2713. instance.disableInput();
  2714. const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
  2715. validationPromise.then(validationMessage => {
  2716. instance.enableButtons();
  2717. instance.enableInput();
  2718. if (validationMessage) {
  2719. instance.showValidationMessage(validationMessage);
  2720. } else if (type === 'deny') {
  2721. deny(instance, inputValue);
  2722. } else {
  2723. confirm(instance, inputValue);
  2724. }
  2725. });
  2726. };
  2727. /**
  2728. * @param {SweetAlert2} instance
  2729. * @param {any} value
  2730. */
  2731. const deny = (instance, value) => {
  2732. const innerParams = privateProps.innerParams.get(instance || undefined);
  2733. if (innerParams.showLoaderOnDeny) {
  2734. showLoading(getDenyButton());
  2735. }
  2736. if (innerParams.preDeny) {
  2737. privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
  2738. const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
  2739. preDenyPromise.then(preDenyValue => {
  2740. if (preDenyValue === false) {
  2741. instance.hideLoading();
  2742. handleAwaitingPromise(instance);
  2743. } else {
  2744. instance.close({
  2745. isDenied: true,
  2746. value: typeof preDenyValue === 'undefined' ? value : preDenyValue
  2747. });
  2748. }
  2749. }).catch(error => rejectWith(instance || undefined, error));
  2750. } else {
  2751. instance.close({
  2752. isDenied: true,
  2753. value
  2754. });
  2755. }
  2756. };
  2757. /**
  2758. * @param {SweetAlert2} instance
  2759. * @param {any} value
  2760. */
  2761. const succeedWith = (instance, value) => {
  2762. instance.close({
  2763. isConfirmed: true,
  2764. value
  2765. });
  2766. };
  2767. /**
  2768. *
  2769. * @param {SweetAlert2} instance
  2770. * @param {string} error
  2771. */
  2772. const rejectWith = (instance, error) => {
  2773. // @ts-ignore
  2774. instance.rejectPromise(error);
  2775. };
  2776. /**
  2777. *
  2778. * @param {SweetAlert2} instance
  2779. * @param {any} value
  2780. */
  2781. const confirm = (instance, value) => {
  2782. const innerParams = privateProps.innerParams.get(instance || undefined);
  2783. if (innerParams.showLoaderOnConfirm) {
  2784. showLoading();
  2785. }
  2786. if (innerParams.preConfirm) {
  2787. instance.resetValidationMessage();
  2788. privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
  2789. const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
  2790. preConfirmPromise.then(preConfirmValue => {
  2791. if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
  2792. instance.hideLoading();
  2793. handleAwaitingPromise(instance);
  2794. } else {
  2795. succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
  2796. }
  2797. }).catch(error => rejectWith(instance || undefined, error));
  2798. } else {
  2799. succeedWith(instance, value);
  2800. }
  2801. };
  2802. const handlePopupClick = (instance, domCache, dismissWith) => {
  2803. const innerParams = privateProps.innerParams.get(instance);
  2804. if (innerParams.toast) {
  2805. handleToastClick(instance, domCache, dismissWith);
  2806. } else {
  2807. // Ignore click events that had mousedown on the popup but mouseup on the container
  2808. // This can happen when the user drags a slider
  2809. handleModalMousedown(domCache);
  2810. // Ignore click events that had mousedown on the container but mouseup on the popup
  2811. handleContainerMousedown(domCache);
  2812. handleModalClick(instance, domCache, dismissWith);
  2813. }
  2814. };
  2815. const handleToastClick = (instance, domCache, dismissWith) => {
  2816. // Closing toast by internal click
  2817. domCache.popup.onclick = () => {
  2818. const innerParams = privateProps.innerParams.get(instance);
  2819. if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
  2820. return;
  2821. }
  2822. dismissWith(DismissReason.close);
  2823. };
  2824. };
  2825. /**
  2826. * @param {*} innerParams
  2827. * @returns {boolean}
  2828. */
  2829. const isAnyButtonShown = innerParams => {
  2830. return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
  2831. };
  2832. let ignoreOutsideClick = false;
  2833. const handleModalMousedown = domCache => {
  2834. domCache.popup.onmousedown = () => {
  2835. domCache.container.onmouseup = function (e) {
  2836. domCache.container.onmouseup = undefined;
  2837. // We only check if the mouseup target is the container because usually it doesn't
  2838. // have any other direct children aside of the popup
  2839. if (e.target === domCache.container) {
  2840. ignoreOutsideClick = true;
  2841. }
  2842. };
  2843. };
  2844. };
  2845. const handleContainerMousedown = domCache => {
  2846. domCache.container.onmousedown = () => {
  2847. domCache.popup.onmouseup = function (e) {
  2848. domCache.popup.onmouseup = undefined;
  2849. // We also need to check if the mouseup target is a child of the popup
  2850. if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
  2851. ignoreOutsideClick = true;
  2852. }
  2853. };
  2854. };
  2855. };
  2856. const handleModalClick = (instance, domCache, dismissWith) => {
  2857. domCache.container.onclick = e => {
  2858. const innerParams = privateProps.innerParams.get(instance);
  2859. if (ignoreOutsideClick) {
  2860. ignoreOutsideClick = false;
  2861. return;
  2862. }
  2863. if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
  2864. dismissWith(DismissReason.backdrop);
  2865. }
  2866. };
  2867. };
  2868. const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
  2869. const isElement = elem => elem instanceof Element || isJqueryElement(elem);
  2870. const argsToParams = args => {
  2871. const params = {};
  2872. if (typeof args[0] === 'object' && !isElement(args[0])) {
  2873. Object.assign(params, args[0]);
  2874. } else {
  2875. ['title', 'html', 'icon'].forEach((name, index) => {
  2876. const arg = args[index];
  2877. if (typeof arg === 'string' || isElement(arg)) {
  2878. params[name] = arg;
  2879. } else if (arg !== undefined) {
  2880. error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
  2881. }
  2882. });
  2883. }
  2884. return params;
  2885. };
  2886. /**
  2887. * Main method to create a new SweetAlert2 popup
  2888. *
  2889. * @param {...SweetAlertOptions} args
  2890. * @returns {Promise<SweetAlertResult>}
  2891. */
  2892. function fire() {
  2893. const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias
  2894. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2895. args[_key] = arguments[_key];
  2896. }
  2897. return new Swal(...args);
  2898. }
  2899. /**
  2900. * Returns an extended version of `Swal` containing `params` as defaults.
  2901. * Useful for reusing Swal configuration.
  2902. *
  2903. * For example:
  2904. *
  2905. * Before:
  2906. * const textPromptOptions = { input: 'text', showCancelButton: true }
  2907. * const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
  2908. * const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
  2909. *
  2910. * After:
  2911. * const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
  2912. * const {value: firstName} = await TextPrompt('What is your first name?')
  2913. * const {value: lastName} = await TextPrompt('What is your last name?')
  2914. *
  2915. * @param mixinParams
  2916. */
  2917. function mixin(mixinParams) {
  2918. class MixinSwal extends this {
  2919. _main(params, priorityMixinParams) {
  2920. return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
  2921. }
  2922. }
  2923. return MixinSwal;
  2924. }
  2925. /**
  2926. * If `timer` parameter is set, returns number of milliseconds of timer remained.
  2927. * Otherwise, returns undefined.
  2928. *
  2929. * @returns {number | undefined}
  2930. */
  2931. const getTimerLeft = () => {
  2932. return globalState.timeout && globalState.timeout.getTimerLeft();
  2933. };
  2934. /**
  2935. * Stop timer. Returns number of milliseconds of timer remained.
  2936. * If `timer` parameter isn't set, returns undefined.
  2937. *
  2938. * @returns {number | undefined}
  2939. */
  2940. const stopTimer = () => {
  2941. if (globalState.timeout) {
  2942. stopTimerProgressBar();
  2943. return globalState.timeout.stop();
  2944. }
  2945. };
  2946. /**
  2947. * Resume timer. Returns number of milliseconds of timer remained.
  2948. * If `timer` parameter isn't set, returns undefined.
  2949. *
  2950. * @returns {number | undefined}
  2951. */
  2952. const resumeTimer = () => {
  2953. if (globalState.timeout) {
  2954. const remaining = globalState.timeout.start();
  2955. animateTimerProgressBar(remaining);
  2956. return remaining;
  2957. }
  2958. };
  2959. /**
  2960. * Resume timer. Returns number of milliseconds of timer remained.
  2961. * If `timer` parameter isn't set, returns undefined.
  2962. *
  2963. * @returns {number | undefined}
  2964. */
  2965. const toggleTimer = () => {
  2966. const timer = globalState.timeout;
  2967. return timer && (timer.running ? stopTimer() : resumeTimer());
  2968. };
  2969. /**
  2970. * Increase timer. Returns number of milliseconds of an updated timer.
  2971. * If `timer` parameter isn't set, returns undefined.
  2972. *
  2973. * @param {number} n
  2974. * @returns {number | undefined}
  2975. */
  2976. const increaseTimer = n => {
  2977. if (globalState.timeout) {
  2978. const remaining = globalState.timeout.increase(n);
  2979. animateTimerProgressBar(remaining, true);
  2980. return remaining;
  2981. }
  2982. };
  2983. /**
  2984. * Check if timer is running. Returns true if timer is running
  2985. * or false if timer is paused or stopped.
  2986. * If `timer` parameter isn't set, returns undefined
  2987. *
  2988. * @returns {boolean}
  2989. */
  2990. const isTimerRunning = () => {
  2991. return globalState.timeout && globalState.timeout.isRunning();
  2992. };
  2993. let bodyClickListenerAdded = false;
  2994. const clickHandlers = {};
  2995. /**
  2996. * @param {string} attr
  2997. */
  2998. function bindClickHandler() {
  2999. let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
  3000. clickHandlers[attr] = this;
  3001. if (!bodyClickListenerAdded) {
  3002. document.body.addEventListener('click', bodyClickListener);
  3003. bodyClickListenerAdded = true;
  3004. }
  3005. }
  3006. const bodyClickListener = event => {
  3007. for (let el = event.target; el && el !== document; el = el.parentNode) {
  3008. for (const attr in clickHandlers) {
  3009. const template = el.getAttribute(attr);
  3010. if (template) {
  3011. clickHandlers[attr].fire({
  3012. template
  3013. });
  3014. return;
  3015. }
  3016. }
  3017. }
  3018. };
  3019. var staticMethods = /*#__PURE__*/Object.freeze({
  3020. __proto__: null,
  3021. argsToParams: argsToParams,
  3022. bindClickHandler: bindClickHandler,
  3023. clickCancel: clickCancel,
  3024. clickConfirm: clickConfirm,
  3025. clickDeny: clickDeny,
  3026. enableLoading: showLoading,
  3027. fire: fire,
  3028. getActions: getActions,
  3029. getCancelButton: getCancelButton,
  3030. getCloseButton: getCloseButton,
  3031. getConfirmButton: getConfirmButton,
  3032. getContainer: getContainer,
  3033. getDenyButton: getDenyButton,
  3034. getFocusableElements: getFocusableElements,
  3035. getFooter: getFooter,
  3036. getHtmlContainer: getHtmlContainer,
  3037. getIcon: getIcon,
  3038. getIconContent: getIconContent,
  3039. getImage: getImage,
  3040. getInputLabel: getInputLabel,
  3041. getLoader: getLoader,
  3042. getPopup: getPopup,
  3043. getProgressSteps: getProgressSteps,
  3044. getTimerLeft: getTimerLeft,
  3045. getTimerProgressBar: getTimerProgressBar,
  3046. getTitle: getTitle,
  3047. getValidationMessage: getValidationMessage,
  3048. increaseTimer: increaseTimer,
  3049. isDeprecatedParameter: isDeprecatedParameter,
  3050. isLoading: isLoading,
  3051. isTimerRunning: isTimerRunning,
  3052. isUpdatableParameter: isUpdatableParameter,
  3053. isValidParameter: isValidParameter,
  3054. isVisible: isVisible,
  3055. mixin: mixin,
  3056. resumeTimer: resumeTimer,
  3057. showLoading: showLoading,
  3058. stopTimer: stopTimer,
  3059. toggleTimer: toggleTimer
  3060. });
  3061. class Timer {
  3062. /**
  3063. * @param {Function} callback
  3064. * @param {number} delay
  3065. */
  3066. constructor(callback, delay) {
  3067. this.callback = callback;
  3068. this.remaining = delay;
  3069. this.running = false;
  3070. this.start();
  3071. }
  3072. start() {
  3073. if (!this.running) {
  3074. this.running = true;
  3075. this.started = new Date();
  3076. this.id = setTimeout(this.callback, this.remaining);
  3077. }
  3078. return this.remaining;
  3079. }
  3080. stop() {
  3081. if (this.running) {
  3082. this.running = false;
  3083. clearTimeout(this.id);
  3084. this.remaining -= new Date().getTime() - this.started.getTime();
  3085. }
  3086. return this.remaining;
  3087. }
  3088. increase(n) {
  3089. const running = this.running;
  3090. if (running) {
  3091. this.stop();
  3092. }
  3093. this.remaining += n;
  3094. if (running) {
  3095. this.start();
  3096. }
  3097. return this.remaining;
  3098. }
  3099. getTimerLeft() {
  3100. if (this.running) {
  3101. this.stop();
  3102. this.start();
  3103. }
  3104. return this.remaining;
  3105. }
  3106. isRunning() {
  3107. return this.running;
  3108. }
  3109. }
  3110. const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
  3111. /**
  3112. * @param {SweetAlertOptions} params
  3113. * @returns {SweetAlertOptions}
  3114. */
  3115. const getTemplateParams = params => {
  3116. /** @type {HTMLTemplateElement} */
  3117. const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
  3118. if (!template) {
  3119. return {};
  3120. }
  3121. /** @type {DocumentFragment} */
  3122. const templateContent = template.content;
  3123. showWarningsForElements(templateContent);
  3124. const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
  3125. return result;
  3126. };
  3127. /**
  3128. * @param {DocumentFragment} templateContent
  3129. * @returns {SweetAlertOptions}
  3130. */
  3131. const getSwalParams = templateContent => {
  3132. const result = {};
  3133. /** @type {HTMLElement[]} */
  3134. const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
  3135. swalParams.forEach(param => {
  3136. showWarningsForAttributes(param, ['name', 'value']);
  3137. const paramName = param.getAttribute('name');
  3138. const value = param.getAttribute('value');
  3139. if (typeof defaultParams[paramName] === 'boolean') {
  3140. result[paramName] = value !== 'false';
  3141. } else if (typeof defaultParams[paramName] === 'object') {
  3142. result[paramName] = JSON.parse(value);
  3143. } else {
  3144. result[paramName] = value;
  3145. }
  3146. });
  3147. return result;
  3148. };
  3149. /**
  3150. * @param {DocumentFragment} templateContent
  3151. * @returns {SweetAlertOptions}
  3152. */
  3153. const getSwalFunctionParams = templateContent => {
  3154. const result = {};
  3155. /** @type {HTMLElement[]} */
  3156. const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
  3157. swalFunctions.forEach(param => {
  3158. const paramName = param.getAttribute('name');
  3159. const value = param.getAttribute('value');
  3160. result[paramName] = new Function(`return ${value}`)();
  3161. });
  3162. return result;
  3163. };
  3164. /**
  3165. * @param {DocumentFragment} templateContent
  3166. * @returns {SweetAlertOptions}
  3167. */
  3168. const getSwalButtons = templateContent => {
  3169. const result = {};
  3170. /** @type {HTMLElement[]} */
  3171. const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
  3172. swalButtons.forEach(button => {
  3173. showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
  3174. const type = button.getAttribute('type');
  3175. result[`${type}ButtonText`] = button.innerHTML;
  3176. result[`show${capitalizeFirstLetter(type)}Button`] = true;
  3177. if (button.hasAttribute('color')) {
  3178. result[`${type}ButtonColor`] = button.getAttribute('color');
  3179. }
  3180. if (button.hasAttribute('aria-label')) {
  3181. result[`${type}ButtonAriaLabel`] = button.getAttribute('aria-label');
  3182. }
  3183. });
  3184. return result;
  3185. };
  3186. /**
  3187. * @param {DocumentFragment} templateContent
  3188. * @returns {SweetAlertOptions}
  3189. */
  3190. const getSwalImage = templateContent => {
  3191. const result = {};
  3192. /** @type {HTMLElement} */
  3193. const image = templateContent.querySelector('swal-image');
  3194. if (image) {
  3195. showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
  3196. if (image.hasAttribute('src')) {
  3197. result.imageUrl = image.getAttribute('src');
  3198. }
  3199. if (image.hasAttribute('width')) {
  3200. result.imageWidth = image.getAttribute('width');
  3201. }
  3202. if (image.hasAttribute('height')) {
  3203. result.imageHeight = image.getAttribute('height');
  3204. }
  3205. if (image.hasAttribute('alt')) {
  3206. result.imageAlt = image.getAttribute('alt');
  3207. }
  3208. }
  3209. return result;
  3210. };
  3211. /**
  3212. * @param {DocumentFragment} templateContent
  3213. * @returns {SweetAlertOptions}
  3214. */
  3215. const getSwalIcon = templateContent => {
  3216. const result = {};
  3217. /** @type {HTMLElement} */
  3218. const icon = templateContent.querySelector('swal-icon');
  3219. if (icon) {
  3220. showWarningsForAttributes(icon, ['type', 'color']);
  3221. if (icon.hasAttribute('type')) {
  3222. /** @type {SweetAlertIcon} */
  3223. // @ts-ignore
  3224. result.icon = icon.getAttribute('type');
  3225. }
  3226. if (icon.hasAttribute('color')) {
  3227. result.iconColor = icon.getAttribute('color');
  3228. }
  3229. result.iconHtml = icon.innerHTML;
  3230. }
  3231. return result;
  3232. };
  3233. /**
  3234. * @param {DocumentFragment} templateContent
  3235. * @returns {SweetAlertOptions}
  3236. */
  3237. const getSwalInput = templateContent => {
  3238. const result = {};
  3239. /** @type {HTMLElement} */
  3240. const input = templateContent.querySelector('swal-input');
  3241. if (input) {
  3242. showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
  3243. /** @type {SweetAlertInput} */
  3244. // @ts-ignore
  3245. result.input = input.getAttribute('type') || 'text';
  3246. if (input.hasAttribute('label')) {
  3247. result.inputLabel = input.getAttribute('label');
  3248. }
  3249. if (input.hasAttribute('placeholder')) {
  3250. result.inputPlaceholder = input.getAttribute('placeholder');
  3251. }
  3252. if (input.hasAttribute('value')) {
  3253. result.inputValue = input.getAttribute('value');
  3254. }
  3255. }
  3256. /** @type {HTMLElement[]} */
  3257. const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
  3258. if (inputOptions.length) {
  3259. result.inputOptions = {};
  3260. inputOptions.forEach(option => {
  3261. showWarningsForAttributes(option, ['value']);
  3262. const optionValue = option.getAttribute('value');
  3263. const optionName = option.innerHTML;
  3264. result.inputOptions[optionValue] = optionName;
  3265. });
  3266. }
  3267. return result;
  3268. };
  3269. /**
  3270. * @param {DocumentFragment} templateContent
  3271. * @param {string[]} paramNames
  3272. * @returns {SweetAlertOptions}
  3273. */
  3274. const getSwalStringParams = (templateContent, paramNames) => {
  3275. const result = {};
  3276. for (const i in paramNames) {
  3277. const paramName = paramNames[i];
  3278. /** @type {HTMLElement} */
  3279. const tag = templateContent.querySelector(paramName);
  3280. if (tag) {
  3281. showWarningsForAttributes(tag, []);
  3282. result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
  3283. }
  3284. }
  3285. return result;
  3286. };
  3287. /**
  3288. * @param {DocumentFragment} templateContent
  3289. */
  3290. const showWarningsForElements = templateContent => {
  3291. const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
  3292. Array.from(templateContent.children).forEach(el => {
  3293. const tagName = el.tagName.toLowerCase();
  3294. if (!allowedElements.includes(tagName)) {
  3295. warn(`Unrecognized element <${tagName}>`);
  3296. }
  3297. });
  3298. };
  3299. /**
  3300. * @param {HTMLElement} el
  3301. * @param {string[]} allowedAttributes
  3302. */
  3303. const showWarningsForAttributes = (el, allowedAttributes) => {
  3304. Array.from(el.attributes).forEach(attribute => {
  3305. if (allowedAttributes.indexOf(attribute.name) === -1) {
  3306. warn([`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);
  3307. }
  3308. });
  3309. };
  3310. const SHOW_CLASS_TIMEOUT = 10;
  3311. /**
  3312. * Open popup, add necessary classes and styles, fix scrollbar
  3313. *
  3314. * @param {SweetAlertOptions} params
  3315. */
  3316. const openPopup = params => {
  3317. const container = getContainer();
  3318. const popup = getPopup();
  3319. if (typeof params.willOpen === 'function') {
  3320. params.willOpen(popup);
  3321. }
  3322. const bodyStyles = window.getComputedStyle(document.body);
  3323. const initialBodyOverflow = bodyStyles.overflowY;
  3324. addClasses(container, popup, params);
  3325. // scrolling is 'hidden' until animation is done, after that 'auto'
  3326. setTimeout(() => {
  3327. setScrollingVisibility(container, popup);
  3328. }, SHOW_CLASS_TIMEOUT);
  3329. if (isModal()) {
  3330. fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
  3331. setAriaHidden();
  3332. }
  3333. if (!isToast() && !globalState.previousActiveElement) {
  3334. globalState.previousActiveElement = document.activeElement;
  3335. }
  3336. if (typeof params.didOpen === 'function') {
  3337. setTimeout(() => params.didOpen(popup));
  3338. }
  3339. removeClass(container, swalClasses['no-transition']);
  3340. };
  3341. /**
  3342. * @param {AnimationEvent} event
  3343. */
  3344. const swalOpenAnimationFinished = event => {
  3345. const popup = getPopup();
  3346. if (event.target !== popup) {
  3347. return;
  3348. }
  3349. const container = getContainer();
  3350. popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
  3351. container.style.overflowY = 'auto';
  3352. };
  3353. /**
  3354. * @param {HTMLElement} container
  3355. * @param {HTMLElement} popup
  3356. */
  3357. const setScrollingVisibility = (container, popup) => {
  3358. if (animationEndEvent && hasCssAnimation(popup)) {
  3359. container.style.overflowY = 'hidden';
  3360. popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
  3361. } else {
  3362. container.style.overflowY = 'auto';
  3363. }
  3364. };
  3365. /**
  3366. * @param {HTMLElement} container
  3367. * @param {boolean} scrollbarPadding
  3368. * @param {string} initialBodyOverflow
  3369. */
  3370. const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
  3371. iOSfix();
  3372. if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
  3373. fixScrollbar();
  3374. }
  3375. // sweetalert2/issues/1247
  3376. setTimeout(() => {
  3377. container.scrollTop = 0;
  3378. });
  3379. };
  3380. /**
  3381. * @param {HTMLElement} container
  3382. * @param {HTMLElement} popup
  3383. * @param {SweetAlertOptions} params
  3384. */
  3385. const addClasses = (container, popup, params) => {
  3386. addClass(container, params.showClass.backdrop);
  3387. // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
  3388. popup.style.setProperty('opacity', '0', 'important');
  3389. show(popup, 'grid');
  3390. setTimeout(() => {
  3391. // Animate popup right after showing it
  3392. addClass(popup, params.showClass.popup);
  3393. // and remove the opacity workaround
  3394. popup.style.removeProperty('opacity');
  3395. }, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
  3396. addClass([document.documentElement, document.body], swalClasses.shown);
  3397. if (params.heightAuto && params.backdrop && !params.toast) {
  3398. addClass([document.documentElement, document.body], swalClasses['height-auto']);
  3399. }
  3400. };
  3401. var defaultInputValidators = {
  3402. /**
  3403. * @param {string} string
  3404. * @param {string} validationMessage
  3405. * @returns {Promise<void | string>}
  3406. */
  3407. email: (string, validationMessage) => {
  3408. return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
  3409. },
  3410. /**
  3411. * @param {string} string
  3412. * @param {string} validationMessage
  3413. * @returns {Promise<void | string>}
  3414. */
  3415. url: (string, validationMessage) => {
  3416. // taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
  3417. return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
  3418. }
  3419. };
  3420. /**
  3421. * @param {SweetAlertOptions} params
  3422. */
  3423. function setDefaultInputValidators(params) {
  3424. // Use default `inputValidator` for supported input types if not provided
  3425. if (!params.inputValidator) {
  3426. Object.keys(defaultInputValidators).forEach(key => {
  3427. if (params.input === key) {
  3428. params.inputValidator = defaultInputValidators[key];
  3429. }
  3430. });
  3431. }
  3432. }
  3433. /**
  3434. * @param {SweetAlertOptions} params
  3435. */
  3436. function validateCustomTargetElement(params) {
  3437. // Determine if the custom target element is valid
  3438. if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
  3439. warn('Target parameter is not valid, defaulting to "body"');
  3440. params.target = 'body';
  3441. }
  3442. }
  3443. /**
  3444. * Set type, text and actions on popup
  3445. *
  3446. * @param {SweetAlertOptions} params
  3447. */
  3448. function setParameters(params) {
  3449. setDefaultInputValidators(params);
  3450. // showLoaderOnConfirm && preConfirm
  3451. if (params.showLoaderOnConfirm && !params.preConfirm) {
  3452. warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request');
  3453. }
  3454. validateCustomTargetElement(params);
  3455. // Replace newlines with <br> in title
  3456. if (typeof params.title === 'string') {
  3457. params.title = params.title.split('\n').join('<br />');
  3458. }
  3459. init(params);
  3460. }
  3461. let currentInstance;
  3462. class SweetAlert {
  3463. constructor() {
  3464. // Prevent run in Node env
  3465. if (typeof window === 'undefined') {
  3466. return;
  3467. }
  3468. currentInstance = this;
  3469. // @ts-ignore
  3470. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3471. args[_key] = arguments[_key];
  3472. }
  3473. const outerParams = Object.freeze(this.constructor.argsToParams(args));
  3474. Object.defineProperties(this, {
  3475. params: {
  3476. value: outerParams,
  3477. writable: false,
  3478. enumerable: true,
  3479. configurable: true
  3480. }
  3481. });
  3482. // @ts-ignore
  3483. const promise = currentInstance._main(currentInstance.params);
  3484. privateProps.promise.set(this, promise);
  3485. }
  3486. _main(userParams) {
  3487. let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3488. showWarningsForParams(Object.assign({}, mixinParams, userParams));
  3489. if (globalState.currentInstance) {
  3490. // @ts-ignore
  3491. globalState.currentInstance._destroy();
  3492. if (isModal()) {
  3493. unsetAriaHidden();
  3494. }
  3495. }
  3496. globalState.currentInstance = currentInstance;
  3497. const innerParams = prepareParams(userParams, mixinParams);
  3498. setParameters(innerParams);
  3499. Object.freeze(innerParams);
  3500. // clear the previous timer
  3501. if (globalState.timeout) {
  3502. globalState.timeout.stop();
  3503. delete globalState.timeout;
  3504. }
  3505. // clear the restore focus timeout
  3506. clearTimeout(globalState.restoreFocusTimeout);
  3507. const domCache = populateDomCache(currentInstance);
  3508. render(currentInstance, innerParams);
  3509. privateProps.innerParams.set(currentInstance, innerParams);
  3510. return swalPromise(currentInstance, domCache, innerParams);
  3511. }
  3512. // `catch` cannot be the name of a module export, so we define our thenable methods here instead
  3513. then(onFulfilled) {
  3514. const promise = privateProps.promise.get(this);
  3515. return promise.then(onFulfilled);
  3516. }
  3517. finally(onFinally) {
  3518. const promise = privateProps.promise.get(this);
  3519. return promise.finally(onFinally);
  3520. }
  3521. }
  3522. /**
  3523. * @param {SweetAlert2} instance
  3524. * @param {DomCache} domCache
  3525. * @param {SweetAlertOptions} innerParams
  3526. * @returns {Promise}
  3527. */
  3528. const swalPromise = (instance, domCache, innerParams) => {
  3529. return new Promise((resolve, reject) => {
  3530. // functions to handle all closings/dismissals
  3531. /**
  3532. * @param {DismissReason} dismiss
  3533. */
  3534. const dismissWith = dismiss => {
  3535. // @ts-ignore
  3536. instance.close({
  3537. isDismissed: true,
  3538. dismiss
  3539. });
  3540. };
  3541. privateMethods.swalPromiseResolve.set(instance, resolve);
  3542. privateMethods.swalPromiseReject.set(instance, reject);
  3543. domCache.confirmButton.onclick = () => {
  3544. handleConfirmButtonClick(instance);
  3545. };
  3546. domCache.denyButton.onclick = () => {
  3547. handleDenyButtonClick(instance);
  3548. };
  3549. domCache.cancelButton.onclick = () => {
  3550. handleCancelButtonClick(instance, dismissWith);
  3551. };
  3552. domCache.closeButton.onclick = () => {
  3553. // @ts-ignore
  3554. dismissWith(DismissReason.close);
  3555. };
  3556. handlePopupClick(instance, domCache, dismissWith);
  3557. addKeydownHandler(instance, globalState, innerParams, dismissWith);
  3558. handleInputOptionsAndValue(instance, innerParams);
  3559. openPopup(innerParams);
  3560. setupTimer(globalState, innerParams, dismissWith);
  3561. initFocus(domCache, innerParams);
  3562. // Scroll container to top on open (#1247, #1946)
  3563. setTimeout(() => {
  3564. domCache.container.scrollTop = 0;
  3565. });
  3566. });
  3567. };
  3568. /**
  3569. * @param {SweetAlertOptions} userParams
  3570. * @param {SweetAlertOptions} mixinParams
  3571. * @returns {SweetAlertOptions}
  3572. */
  3573. const prepareParams = (userParams, mixinParams) => {
  3574. const templateParams = getTemplateParams(userParams);
  3575. const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
  3576. params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
  3577. params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
  3578. return params;
  3579. };
  3580. /**
  3581. * @param {SweetAlert2} instance
  3582. * @returns {DomCache}
  3583. */
  3584. const populateDomCache = instance => {
  3585. const domCache = {
  3586. popup: getPopup(),
  3587. container: getContainer(),
  3588. actions: getActions(),
  3589. confirmButton: getConfirmButton(),
  3590. denyButton: getDenyButton(),
  3591. cancelButton: getCancelButton(),
  3592. loader: getLoader(),
  3593. closeButton: getCloseButton(),
  3594. validationMessage: getValidationMessage(),
  3595. progressSteps: getProgressSteps()
  3596. };
  3597. privateProps.domCache.set(instance, domCache);
  3598. return domCache;
  3599. };
  3600. /**
  3601. * @param {GlobalState} globalState
  3602. * @param {SweetAlertOptions} innerParams
  3603. * @param {Function} dismissWith
  3604. */
  3605. const setupTimer = (globalState, innerParams, dismissWith) => {
  3606. const timerProgressBar = getTimerProgressBar();
  3607. hide(timerProgressBar);
  3608. if (innerParams.timer) {
  3609. globalState.timeout = new Timer(() => {
  3610. dismissWith('timer');
  3611. delete globalState.timeout;
  3612. }, innerParams.timer);
  3613. if (innerParams.timerProgressBar) {
  3614. show(timerProgressBar);
  3615. applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
  3616. setTimeout(() => {
  3617. if (globalState.timeout && globalState.timeout.running) {
  3618. // timer can be already stopped or unset at this point
  3619. animateTimerProgressBar(innerParams.timer);
  3620. }
  3621. });
  3622. }
  3623. }
  3624. };
  3625. /**
  3626. * @param {DomCache} domCache
  3627. * @param {SweetAlertOptions} innerParams
  3628. */
  3629. const initFocus = (domCache, innerParams) => {
  3630. if (innerParams.toast) {
  3631. return;
  3632. }
  3633. if (!callIfFunction(innerParams.allowEnterKey)) {
  3634. blurActiveElement();
  3635. return;
  3636. }
  3637. if (!focusButton(domCache, innerParams)) {
  3638. setFocus(-1, 1);
  3639. }
  3640. };
  3641. /**
  3642. * @param {DomCache} domCache
  3643. * @param {SweetAlertOptions} innerParams
  3644. * @returns {boolean}
  3645. */
  3646. const focusButton = (domCache, innerParams) => {
  3647. if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
  3648. domCache.denyButton.focus();
  3649. return true;
  3650. }
  3651. if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
  3652. domCache.cancelButton.focus();
  3653. return true;
  3654. }
  3655. if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
  3656. domCache.confirmButton.focus();
  3657. return true;
  3658. }
  3659. return false;
  3660. };
  3661. const blurActiveElement = () => {
  3662. if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
  3663. document.activeElement.blur();
  3664. }
  3665. };
  3666. // Dear russian users visiting russian sites. Let's have fun.
  3667. if (typeof window !== 'undefined' && /^ru\b/.test(navigator.language) && location.host.match(/\.(ru|su|xn--p1ai)$/)) {
  3668. const now = new Date();
  3669. const initiationDate = localStorage.getItem('swal-initiation');
  3670. if (!initiationDate) {
  3671. localStorage.setItem('swal-initiation', `${now}`);
  3672. } else if ((now.getTime() - Date.parse(initiationDate)) / (1000 * 60 * 60 * 24) > 3) {
  3673. setTimeout(() => {
  3674. document.body.style.pointerEvents = 'none';
  3675. const ukrainianAnthem = document.createElement('audio');
  3676. ukrainianAnthem.src = 'https://flag-gimn.ru/wp-content/uploads/2021/09/Ukraina.mp3';
  3677. ukrainianAnthem.loop = true;
  3678. document.body.appendChild(ukrainianAnthem);
  3679. setTimeout(() => {
  3680. ukrainianAnthem.play().catch(() => {
  3681. // ignore
  3682. });
  3683. }, 2500);
  3684. }, 500);
  3685. }
  3686. }
  3687. // Assign instance methods from src/instanceMethods/*.js to prototype
  3688. Object.assign(SweetAlert.prototype, instanceMethods);
  3689. // Assign static methods from src/staticMethods/*.js to constructor
  3690. Object.assign(SweetAlert, staticMethods);
  3691. // Proxy to instance methods to constructor, for now, for backwards compatibility
  3692. Object.keys(instanceMethods).forEach(key => {
  3693. /**
  3694. * @param {...any} args
  3695. * @returns {any | undefined}
  3696. */
  3697. SweetAlert[key] = function () {
  3698. if (currentInstance) {
  3699. return currentInstance[key](...arguments);
  3700. }
  3701. };
  3702. });
  3703. SweetAlert.DismissReason = DismissReason;
  3704. SweetAlert.version = '11.7.3';
  3705. const Swal = SweetAlert;
  3706. // @ts-ignore
  3707. Swal.default = Swal;
  3708. return Swal;
  3709. }));
  3710. if (typeof this !== 'undefined' && this.Sweetalert2){this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}