sweetalert2.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. /*!
  2. * sweetalert2 v5.3.5
  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.Sweetalert2 = factory());
  9. }(this, function() {
  10. 'use strict';
  11. var swalPrefix = 'swal2-'
  12. var prefix = function(items) {
  13. var result = {}
  14. for (var i in items) {
  15. result[items[i]] = swalPrefix + items[i]
  16. }
  17. return result
  18. }
  19. var swalClasses = prefix([
  20. 'container',
  21. 'in',
  22. 'iosfix',
  23. 'modal',
  24. 'overlay',
  25. 'fade',
  26. 'show',
  27. 'hide',
  28. 'noanimation',
  29. 'close',
  30. 'content',
  31. 'spacer',
  32. 'confirm',
  33. 'cancel',
  34. 'icon',
  35. 'image',
  36. 'input',
  37. 'file',
  38. 'range',
  39. 'select',
  40. 'radio',
  41. 'checkbox',
  42. 'textarea',
  43. 'inputerror',
  44. 'validationerror',
  45. 'progresssteps',
  46. 'activeprogressstep',
  47. 'progresscircle',
  48. 'progressline',
  49. 'loading',
  50. 'styled'
  51. ])
  52. var iconTypes = prefix([
  53. 'success',
  54. 'warning',
  55. 'info',
  56. 'question',
  57. 'error'
  58. ])
  59. var defaultParams = {
  60. title: '',
  61. text: '',
  62. html: '',
  63. type: null,
  64. customClass: '',
  65. animation: true,
  66. allowOutsideClick: true,
  67. allowEscapeKey: true,
  68. showConfirmButton: true,
  69. showCancelButton: false,
  70. preConfirm: null,
  71. confirmButtonText: 'OK',
  72. confirmButtonColor: '#3085d6',
  73. confirmButtonClass: null,
  74. cancelButtonText: 'Cancel',
  75. cancelButtonColor: '#aaa',
  76. cancelButtonClass: null,
  77. buttonsStyling: true,
  78. reverseButtons: false,
  79. focusCancel: false,
  80. showCloseButton: false,
  81. showLoaderOnConfirm: false,
  82. imageUrl: null,
  83. imageWidth: null,
  84. imageHeight: null,
  85. imageClass: null,
  86. timer: null,
  87. width: 500,
  88. padding: 20,
  89. background: '#fff',
  90. input: null,
  91. inputPlaceholder: '',
  92. inputValue: '',
  93. inputOptions: {},
  94. inputAutoTrim: true,
  95. inputClass: null,
  96. inputAttributes: {},
  97. inputValidator: null,
  98. progressSteps: [],
  99. currentProgressStep: null,
  100. progressStepsDistance: '40px',
  101. onOpen: null,
  102. onClose: null
  103. }
  104. var sweetHTML = '<div class="' + swalClasses.modal + '" style="display: none" tabIndex="-1">' +
  105. '<ul class="' + swalClasses.progresssteps + '"></ul>' +
  106. '<div class="' + swalClasses.icon + ' ' + iconTypes.error + '">' +
  107. '<span class="x-mark"><span class="line left"></span><span class="line right"></span></span>' +
  108. '</div>' +
  109. '<div class="' + swalClasses.icon + ' ' + iconTypes.question + '">?</div>' +
  110. '<div class="' + swalClasses.icon + ' ' + iconTypes.warning + '">!</div>' +
  111. '<div class="' + swalClasses.icon + ' ' + iconTypes.info + '">i</div>' +
  112. '<div class="' + swalClasses.icon + ' ' + iconTypes.success + '">' +
  113. '<span class="line tip"></span> <span class="line long"></span>' +
  114. '<div class="placeholder"></div> <div class="fix"></div>' +
  115. '</div>' +
  116. '<img class="' + swalClasses.image + '">' +
  117. '<h2></h2>' +
  118. '<div class="' + swalClasses.content + '"></div>' +
  119. '<input class="' + swalClasses.input + '">' +
  120. '<input type="file" class="' + swalClasses.file + '">' +
  121. '<div class="' + swalClasses.range + '">' +
  122. '<output></output>' +
  123. '<input type="range">' +
  124. '</div>' +
  125. '<select class="' + swalClasses.select + '"></select>' +
  126. '<div class="' + swalClasses.radio + '"></div>' +
  127. '<label for="' + swalClasses.checkbox + '" class="' + swalClasses.checkbox + '">' +
  128. '<input type="checkbox">' +
  129. '</label>' +
  130. '<textarea class="' + swalClasses.textarea + '"></textarea>' +
  131. '<div class="' + swalClasses.validationerror + '"></div>' +
  132. '<hr class="' + swalClasses.spacer + '">' +
  133. '<button type="button" class="' + swalClasses.confirm + '">OK</button>' +
  134. '<button type="button" class="' + swalClasses.cancel + '">Cancel</button>' +
  135. '<span class="' + swalClasses.close + '">&times;</span>' +
  136. '</div>'
  137. var sweetContainer
  138. var existingSweetContainers = document.getElementsByClassName(swalClasses.container)
  139. if (existingSweetContainers.length) {
  140. sweetContainer = existingSweetContainers[0]
  141. } else {
  142. sweetContainer = document.createElement('div')
  143. sweetContainer.className = swalClasses.container
  144. sweetContainer.innerHTML = sweetHTML
  145. }
  146. var extend = function(a, b) {
  147. for (var key in b) {
  148. if (b.hasOwnProperty(key)) {
  149. a[key] = b[key]
  150. }
  151. }
  152. return a
  153. }
  154. /*
  155. * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color)
  156. */
  157. var colorLuminance = function(hex, lum) {
  158. // Validate hex string
  159. hex = String(hex).replace(/[^0-9a-f]/gi, '')
  160. if (hex.length < 6) {
  161. hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
  162. }
  163. lum = lum || 0
  164. // Convert to decimal and change luminosity
  165. var rgb = '#'
  166. for (var i = 0; i < 3; i++) {
  167. var c = parseInt(hex.substr(i * 2, 2), 16)
  168. c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16)
  169. rgb += ('00' + c).substr(c.length)
  170. }
  171. return rgb
  172. }
  173. // Remember state in cases where opening and handling a modal will fiddle with it.
  174. var states = {
  175. previousWindowKeyDown: null,
  176. previousActiveElement: null,
  177. previousBodyPadding: null
  178. }
  179. /*
  180. * Add modal + overlay to DOM
  181. */
  182. var init = function() {
  183. if (typeof document === 'undefined') {
  184. console.error('SweetAlert2 requires document to initialize')
  185. return
  186. } else if (document.getElementsByClassName(swalClasses.container).length) {
  187. return
  188. }
  189. document.body.appendChild(sweetContainer)
  190. var modal = getModal()
  191. var input = getChildByClass(modal, swalClasses.input)
  192. var file = getChildByClass(modal, swalClasses.file)
  193. var range = modal.querySelector('.' + swalClasses.range + ' input')
  194. var select = getChildByClass(modal, swalClasses.select)
  195. var checkbox = modal.querySelector('.' + swalClasses.checkbox + ' input')
  196. var textarea = getChildByClass(modal, swalClasses.textarea)
  197. input.oninput = function() {
  198. sweetAlert.resetValidationError()
  199. }
  200. input.onkeyup = function(event) {
  201. event.stopPropagation()
  202. if (event.keyCode === 13) {
  203. sweetAlert.clickConfirm()
  204. }
  205. }
  206. file.onchange = function() {
  207. sweetAlert.resetValidationError()
  208. }
  209. range.oninput = function() {
  210. sweetAlert.resetValidationError()
  211. range.previousSibling.value = range.value
  212. }
  213. range.onchange = function() {
  214. sweetAlert.resetValidationError()
  215. range.previousSibling.value = range.value
  216. }
  217. select.onchange = function() {
  218. sweetAlert.resetValidationError()
  219. }
  220. checkbox.onchange = function() {
  221. sweetAlert.resetValidationError()
  222. }
  223. textarea.oninput = function() {
  224. sweetAlert.resetValidationError()
  225. }
  226. return modal
  227. }
  228. /*
  229. * Manipulate DOM
  230. */
  231. var elementByClass = function(className) {
  232. return sweetContainer.querySelector('.' + className)
  233. }
  234. var getModal = function() {
  235. return document.body.querySelector('.' + swalClasses.modal) || init()
  236. }
  237. var getIcons = function() {
  238. var modal = getModal()
  239. return modal.querySelectorAll('.' + swalClasses.icon)
  240. }
  241. var getSpacer = function() {
  242. return elementByClass(swalClasses.spacer)
  243. }
  244. var getProgressSteps = function() {
  245. return elementByClass(swalClasses.progresssteps)
  246. }
  247. var getValidationError = function() {
  248. return elementByClass(swalClasses.validationerror)
  249. }
  250. var getConfirmButton = function() {
  251. return elementByClass(swalClasses.confirm)
  252. }
  253. var getCancelButton = function() {
  254. return elementByClass(swalClasses.cancel)
  255. }
  256. var getCloseButton = function() {
  257. return elementByClass(swalClasses.close)
  258. }
  259. var getFocusableElements = function(focusCancel) {
  260. var buttons = [getConfirmButton(), getCancelButton()]
  261. if (focusCancel) {
  262. buttons.reverse()
  263. }
  264. return buttons.concat(Array.prototype.slice.call(
  265. getModal().querySelectorAll('button:not([class^=' + swalPrefix + ']), input:not([type=hidden]), textarea, select')
  266. ))
  267. }
  268. var hasClass = function(elem, className) {
  269. return elem.classList.contains(className)
  270. }
  271. var focusInput = function(input) {
  272. input.focus()
  273. // place cursor at end of text in text input
  274. if (input.type !== 'file') {
  275. // http://stackoverflow.com/a/2345915/1331425
  276. var val = input.value
  277. input.value = ''
  278. input.value = val
  279. }
  280. }
  281. var addClass = function(elem, className) {
  282. if (!elem || !className) {
  283. return
  284. }
  285. var classes = className.split(/\s+/)
  286. classes.forEach(function(className) {
  287. elem.classList.add(className)
  288. })
  289. }
  290. var removeClass = function(elem, className) {
  291. if (!elem || !className) {
  292. return
  293. }
  294. var classes = className.split(/\s+/)
  295. classes.forEach(function(className) {
  296. elem.classList.remove(className)
  297. })
  298. }
  299. var getChildByClass = function(elem, className) {
  300. for (var i = 0; i < elem.childNodes.length; i++) {
  301. if (hasClass(elem.childNodes[i], className)) {
  302. return elem.childNodes[i]
  303. }
  304. }
  305. }
  306. var show = function(elem, display) {
  307. if (!display) {
  308. display = 'block'
  309. }
  310. elem.style.opacity = ''
  311. elem.style.display = display
  312. }
  313. var hide = function(elem) {
  314. elem.style.opacity = ''
  315. elem.style.display = 'none'
  316. }
  317. var empty = function(elem) {
  318. while (elem.firstChild) {
  319. elem.removeChild(elem.firstChild)
  320. }
  321. }
  322. // borrowed from jqeury $(elem).is(':visible') implementation
  323. var isVisible = function(elem) {
  324. return elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length
  325. }
  326. var removeStyleProperty = function(elem, property) {
  327. if (elem.style.removeProperty) {
  328. elem.style.removeProperty(property)
  329. } else {
  330. elem.style.removeAttribute(property)
  331. }
  332. }
  333. var fireClick = function(node) {
  334. // Then fixed for today's Chrome browser.
  335. if (typeof MouseEvent === 'function') {
  336. // Up-to-date approach
  337. var mevt = new MouseEvent('click', {
  338. view: window,
  339. bubbles: false,
  340. cancelable: true
  341. })
  342. node.dispatchEvent(mevt)
  343. } else if (document.createEvent) {
  344. // Fallback
  345. var evt = document.createEvent('MouseEvents')
  346. evt.initEvent('click', false, false)
  347. node.dispatchEvent(evt)
  348. } else if (document.createEventObject) {
  349. node.fireEvent('onclick')
  350. } else if (typeof node.onclick === 'function') {
  351. node.onclick()
  352. }
  353. }
  354. var stopEventPropagation = function(e) {
  355. // In particular, make sure the space bar doesn't scroll the main window.
  356. if (typeof e.stopPropagation === 'function') {
  357. e.stopPropagation()
  358. e.preventDefault()
  359. } else if (window.event && window.event.hasOwnProperty('cancelBubble')) {
  360. window.event.cancelBubble = true
  361. }
  362. }
  363. var animationEndEvent = (function() {
  364. var testEl = document.createElement('div')
  365. var transEndEventNames = {
  366. 'WebkitAnimation': 'webkitAnimationEnd',
  367. 'OAnimation': 'oAnimationEnd oanimationend',
  368. 'msAnimation': 'MSAnimationEnd',
  369. 'animation': 'animationend'
  370. }
  371. for (var i in transEndEventNames) {
  372. if (transEndEventNames.hasOwnProperty(i) &&
  373. testEl.style[i] !== undefined) {
  374. return transEndEventNames[i]
  375. }
  376. }
  377. return false
  378. })()
  379. // Reset the page to its previous state
  380. var resetPrevState = function() {
  381. var modal = getModal()
  382. window.onkeydown = states.previousWindowKeyDown
  383. if (states.previousActiveElement && states.previousActiveElement.focus) {
  384. states.previousActiveElement.focus()
  385. }
  386. clearTimeout(modal.timeout)
  387. }
  388. // Measure width of scrollbar
  389. // https://github.com/twbs/bootstrap/blob/master/js/modal.js#L279-L286
  390. var measureScrollbar = function() {
  391. var scrollDiv = document.createElement('div')
  392. scrollDiv.style.width = '50px'
  393. scrollDiv.style.height = '50px'
  394. scrollDiv.style.overflow = 'scroll'
  395. document.body.appendChild(scrollDiv)
  396. var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
  397. document.body.removeChild(scrollDiv)
  398. return scrollbarWidth
  399. }
  400. // JavaScript Debounce Function
  401. // https://davidwalsh.name/javascript-debounce-function
  402. var debounce = function(func, wait, immediate) {
  403. var timeout
  404. return function() {
  405. var context = this
  406. var args = arguments
  407. var later = function() {
  408. timeout = null
  409. if (!immediate) func.apply(context, args)
  410. }
  411. var callNow = immediate && !timeout
  412. clearTimeout(timeout)
  413. timeout = setTimeout(later, wait)
  414. if (callNow) func.apply(context, args)
  415. }
  416. }
  417. var modalParams = extend({}, defaultParams)
  418. var queue = []
  419. var swal2Observer
  420. /*
  421. * Set type, text and actions on modal
  422. */
  423. var setParameters = function(params) {
  424. var modal = getModal()
  425. for (var param in params) {
  426. if (!defaultParams.hasOwnProperty(param) && param !== 'extraParams') {
  427. console.warn('SweetAlert2: Unknown parameter "' + param + '"')
  428. }
  429. }
  430. // set modal width and margin-left
  431. modal.style.width = (typeof params.width === 'number') ? params.width + 'px' : params.width
  432. modal.style.padding = params.padding + 'px'
  433. modal.style.background = params.background
  434. var $title = modal.querySelector('h2')
  435. var $content = modal.querySelector('.' + swalClasses.content)
  436. var $confirmBtn = getConfirmButton()
  437. var $cancelBtn = getCancelButton()
  438. var $closeButton = modal.querySelector('.' + swalClasses.close)
  439. // Title
  440. $title.innerHTML = params.title.split('\n').join('<br>')
  441. // Content
  442. var i
  443. if (params.text || params.html) {
  444. if (typeof params.html === 'object') {
  445. $content.innerHTML = ''
  446. if (0 in params.html) {
  447. for (i = 0; i in params.html; i++) {
  448. $content.appendChild(params.html[i].cloneNode(true))
  449. }
  450. } else {
  451. $content.appendChild(params.html.cloneNode(true))
  452. }
  453. } else {
  454. $content.innerHTML = params.html || (params.text.split('\n').join('<br>'))
  455. }
  456. show($content)
  457. } else {
  458. hide($content)
  459. }
  460. // Close button
  461. if (params.showCloseButton) {
  462. show($closeButton)
  463. } else {
  464. hide($closeButton)
  465. }
  466. // Custom Class
  467. modal.className = swalClasses.modal
  468. if (params.customClass) {
  469. addClass(modal, params.customClass)
  470. }
  471. // Progress steps
  472. var progressStepsContainer = getProgressSteps()
  473. var currentProgressStep = parseInt(params.currentProgressStep === null ? sweetAlert.getQueueStep() : params.currentProgressStep, 10)
  474. if (params.progressSteps.length) {
  475. show(progressStepsContainer)
  476. empty(progressStepsContainer)
  477. if (currentProgressStep >= params.progressSteps.length) {
  478. console.warn(
  479. 'SweetAlert2: Invalid currentProgressStep parameter, it should be less than progressSteps.length ' +
  480. '(currentProgressStep like JS arrays starts from 0)'
  481. )
  482. }
  483. params.progressSteps.forEach(function(step, index) {
  484. var circle = document.createElement('li')
  485. addClass(circle, swalClasses.progresscircle)
  486. circle.innerHTML = step
  487. if (index === currentProgressStep) {
  488. addClass(circle, swalClasses.activeprogressstep)
  489. }
  490. progressStepsContainer.appendChild(circle)
  491. if (index !== params.progressSteps.length - 1) {
  492. var line = document.createElement('li')
  493. addClass(line, swalClasses.progressline)
  494. line.style.width = params.progressStepsDistance
  495. progressStepsContainer.appendChild(line)
  496. }
  497. })
  498. } else {
  499. hide(progressStepsContainer)
  500. }
  501. // Icon
  502. var icons = getIcons()
  503. for (i = 0; i < icons.length; i++) {
  504. hide(icons[i])
  505. }
  506. if (params.type) {
  507. var validType = false
  508. for (var iconType in iconTypes) {
  509. if (params.type === iconType) {
  510. validType = true
  511. break
  512. }
  513. }
  514. if (!validType) {
  515. console.error('SweetAlert2: Unknown alert type: ' + params.type)
  516. return false
  517. }
  518. var $icon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes[params.type])
  519. show($icon)
  520. // Animate icon
  521. switch (params.type) {
  522. case 'success':
  523. addClass($icon, 'animate')
  524. addClass($icon.querySelector('.tip'), 'animate-success-tip')
  525. addClass($icon.querySelector('.long'), 'animate-success-long')
  526. break
  527. case 'error':
  528. addClass($icon, 'animate-error-icon')
  529. addClass($icon.querySelector('.x-mark'), 'animate-x-mark')
  530. break
  531. case 'warning':
  532. addClass($icon, 'pulse-warning')
  533. break
  534. default:
  535. break
  536. }
  537. }
  538. // Custom image
  539. var $customImage = modal.querySelector('.' + swalClasses.image)
  540. if (params.imageUrl) {
  541. $customImage.setAttribute('src', params.imageUrl)
  542. show($customImage)
  543. if (params.imageWidth) {
  544. $customImage.setAttribute('width', params.imageWidth)
  545. } else {
  546. $customImage.removeAttribute('width')
  547. }
  548. if (params.imageHeight) {
  549. $customImage.setAttribute('height', params.imageHeight)
  550. } else {
  551. $customImage.removeAttribute('height')
  552. }
  553. $customImage.className = swalClasses.image
  554. if (params.imageClass) {
  555. addClass($customImage, params.imageClass)
  556. }
  557. } else {
  558. hide($customImage)
  559. }
  560. // Cancel button
  561. if (params.showCancelButton) {
  562. $cancelBtn.style.display = 'inline-block'
  563. } else {
  564. hide($cancelBtn)
  565. }
  566. // Confirm button
  567. if (params.showConfirmButton) {
  568. removeStyleProperty($confirmBtn, 'display')
  569. } else {
  570. hide($confirmBtn)
  571. }
  572. // Buttons spacer
  573. var spacer = getSpacer()
  574. if (!params.showConfirmButton && !params.showCancelButton) {
  575. hide(spacer)
  576. } else {
  577. show(spacer)
  578. }
  579. // Edit text on cancel and confirm buttons
  580. $confirmBtn.innerHTML = params.confirmButtonText
  581. $cancelBtn.innerHTML = params.cancelButtonText
  582. // Set buttons to selected background colors
  583. if (params.buttonsStyling) {
  584. $confirmBtn.style.backgroundColor = params.confirmButtonColor
  585. $cancelBtn.style.backgroundColor = params.cancelButtonColor
  586. }
  587. // Add buttons custom classes
  588. $confirmBtn.className = swalClasses.confirm
  589. addClass($confirmBtn, params.confirmButtonClass)
  590. $cancelBtn.className = swalClasses.cancel
  591. addClass($cancelBtn, params.cancelButtonClass)
  592. // Buttons styling
  593. if (params.buttonsStyling) {
  594. addClass($confirmBtn, swalClasses.styled)
  595. addClass($cancelBtn, swalClasses.styled)
  596. } else {
  597. removeClass($confirmBtn, swalClasses.styled)
  598. removeClass($cancelBtn, swalClasses.styled)
  599. $confirmBtn.style.backgroundColor = $confirmBtn.style.borderLeftColor = $confirmBtn.style.borderRightColor = ''
  600. $cancelBtn.style.backgroundColor = $cancelBtn.style.borderLeftColor = $cancelBtn.style.borderRightColor = ''
  601. }
  602. // CSS animation
  603. if (params.animation === true) {
  604. removeClass(modal, swalClasses.noanimation)
  605. } else {
  606. addClass(modal, swalClasses.noanimation)
  607. }
  608. }
  609. /*
  610. * Animations
  611. */
  612. var openModal = function(animation, onComplete) {
  613. var modal = getModal()
  614. if (animation) {
  615. addClass(modal, swalClasses.show)
  616. addClass(sweetContainer, swalClasses.fade)
  617. removeClass(modal, swalClasses.hide)
  618. } else {
  619. removeClass(modal, swalClasses.fade)
  620. }
  621. show(modal)
  622. // scrolling is 'hidden' until animation is done, after that 'auto'
  623. sweetContainer.style.overflowY = 'hidden'
  624. if (animationEndEvent && !hasClass(modal, swalClasses.noanimation)) {
  625. modal.addEventListener(animationEndEvent, function swalCloseEventFinished() {
  626. modal.removeEventListener(animationEndEvent, swalCloseEventFinished)
  627. sweetContainer.style.overflowY = 'auto'
  628. })
  629. } else {
  630. sweetContainer.style.overflowY = 'auto'
  631. }
  632. addClass(sweetContainer, swalClasses.in)
  633. addClass(document.body, swalClasses.in)
  634. fixScrollbar()
  635. iOSfix()
  636. states.previousActiveElement = document.activeElement
  637. if (onComplete !== null && typeof onComplete === 'function') {
  638. onComplete.call(this, modal)
  639. }
  640. }
  641. function fixScrollbar() {
  642. // for queues, do not do this more than once
  643. if (states.previousBodyPadding !== null) {
  644. return
  645. }
  646. // if the body has overflow
  647. if (document.body.scrollHeight > window.innerHeight) {
  648. // add padding so the content doesn't shift after removal of scrollbar
  649. states.previousBodyPadding = document.body.style.paddingRight
  650. document.body.style.paddingRight = measureScrollbar() + 'px'
  651. }
  652. }
  653. function undoScrollbar() {
  654. if (states.previousBodyPadding !== null) {
  655. document.body.style.paddingRight = states.previousBodyPadding
  656. states.previousBodyPadding = null
  657. }
  658. }
  659. // Fix iOS scrolling http://stackoverflow.com/q/39626302/1331425
  660. function iOSfix() {
  661. var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream
  662. if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
  663. var offset = document.body.scrollTop
  664. document.body.style.top = (offset * -1) + 'px'
  665. addClass(document.body, swalClasses.iosfix)
  666. }
  667. }
  668. function undoIOSfix() {
  669. if (hasClass(document.body, swalClasses.iosfix)) {
  670. var offset = parseInt(document.body.style.top, 10)
  671. removeClass(document.body, swalClasses.iosfix)
  672. document.body.scrollTop = (offset * -1)
  673. }
  674. }
  675. function modalDependant() {
  676. if (arguments[0] === undefined) {
  677. console.error('SweetAlert2 expects at least 1 attribute!')
  678. return false
  679. }
  680. var params = extend({}, modalParams)
  681. switch (typeof arguments[0]) {
  682. case 'string':
  683. params.title = arguments[0]
  684. params.text = arguments[1] || ''
  685. params.type = arguments[2] || ''
  686. break
  687. case 'object':
  688. extend(params, arguments[0])
  689. params.extraParams = arguments[0].extraParams
  690. if (params.input === 'email' && params.inputValidator === null) {
  691. params.inputValidator = function(email) {
  692. return new Promise(function(resolve, reject) {
  693. var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
  694. if (emailRegex.test(email)) {
  695. resolve()
  696. } else {
  697. reject('Invalid email address')
  698. }
  699. })
  700. }
  701. }
  702. break
  703. default:
  704. console.error('SweetAlert2: Unexpected type of argument! Expected "string" or "object", got ' + typeof arguments[0])
  705. return false
  706. }
  707. setParameters(params)
  708. // Modal interactions
  709. var modal = getModal()
  710. return new Promise(function(resolve, reject) {
  711. // Close on timer
  712. if (params.timer) {
  713. modal.timeout = setTimeout(function() {
  714. sweetAlert.closeModal(params.onClose)
  715. reject('timer')
  716. }, params.timer)
  717. }
  718. // Get input element by specified type or, if type isn't specified, by params.input
  719. var getInput = function(inputType) {
  720. inputType = inputType || params.input
  721. switch (inputType) {
  722. case 'select':
  723. case 'textarea':
  724. case 'file':
  725. return getChildByClass(modal, swalClasses[inputType])
  726. case 'checkbox':
  727. return modal.querySelector('.' + swalClasses.checkbox + ' input')
  728. case 'radio':
  729. return modal.querySelector('.' + swalClasses.radio + ' input:checked') ||
  730. modal.querySelector('.' + swalClasses.radio + ' input:first-child')
  731. case 'range':
  732. return modal.querySelector('.' + swalClasses.range + ' input')
  733. default:
  734. return getChildByClass(modal, swalClasses.input)
  735. }
  736. }
  737. // Get the value of the modal input
  738. var getInputValue = function() {
  739. var input = getInput()
  740. if (!input) {
  741. return null
  742. }
  743. switch (params.input) {
  744. case 'checkbox':
  745. return input.checked ? 1 : 0
  746. case 'radio':
  747. return input.checked ? input.value : null
  748. case 'file':
  749. return input.files.length ? input.files[0] : null
  750. default:
  751. return params.inputAutoTrim ? input.value.trim() : input.value
  752. }
  753. }
  754. // input autofocus
  755. if (params.input) {
  756. setTimeout(function() {
  757. var input = getInput()
  758. if (input) {
  759. focusInput(input)
  760. }
  761. }, 0)
  762. }
  763. var confirm = function(value) {
  764. if (params.showLoaderOnConfirm) {
  765. sweetAlert.showLoading()
  766. }
  767. if (params.preConfirm) {
  768. params.preConfirm(value, params.extraParams).then(
  769. function(preConfirmValue) {
  770. sweetAlert.closeModal(params.onClose)
  771. resolve(preConfirmValue || value)
  772. },
  773. function(error) {
  774. sweetAlert.hideLoading()
  775. if (error) {
  776. sweetAlert.showValidationError(error)
  777. }
  778. }
  779. )
  780. } else {
  781. sweetAlert.closeModal(params.onClose)
  782. resolve(value)
  783. }
  784. }
  785. // Mouse interactions
  786. var onButtonEvent = function(event) {
  787. var e = event || window.event
  788. var target = e.target || e.srcElement
  789. var confirmBtn = getConfirmButton()
  790. var cancelBtn = getCancelButton()
  791. var targetedConfirm = confirmBtn === target || confirmBtn.contains(target)
  792. var targetedCancel = cancelBtn === target || cancelBtn.contains(target)
  793. switch (e.type) {
  794. case 'mouseover':
  795. case 'mouseup':
  796. if (params.buttonsStyling) {
  797. if (targetedConfirm) {
  798. confirmBtn.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.1)
  799. } else if (targetedCancel) {
  800. cancelBtn.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.1)
  801. }
  802. }
  803. break
  804. case 'mouseout':
  805. if (params.buttonsStyling) {
  806. if (targetedConfirm) {
  807. confirmBtn.style.backgroundColor = params.confirmButtonColor
  808. } else if (targetedCancel) {
  809. cancelBtn.style.backgroundColor = params.cancelButtonColor
  810. }
  811. }
  812. break
  813. case 'mousedown':
  814. if (params.buttonsStyling) {
  815. if (targetedConfirm) {
  816. confirmBtn.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.2)
  817. } else if (targetedCancel) {
  818. cancelBtn.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.2)
  819. }
  820. }
  821. break
  822. case 'click':
  823. // Clicked 'confirm'
  824. if (targetedConfirm && sweetAlert.isVisible()) {
  825. if (params.input) {
  826. var inputValue = getInputValue()
  827. if (params.inputValidator) {
  828. sweetAlert.disableInput()
  829. params.inputValidator(inputValue, params.extraParams).then(
  830. function() {
  831. sweetAlert.enableInput()
  832. confirm(inputValue)
  833. },
  834. function(error) {
  835. sweetAlert.enableInput()
  836. if (error) {
  837. sweetAlert.showValidationError(error)
  838. }
  839. }
  840. )
  841. } else {
  842. confirm(inputValue)
  843. }
  844. } else {
  845. confirm(true)
  846. }
  847. // Clicked 'cancel'
  848. } else if (targetedCancel && sweetAlert.isVisible()) {
  849. sweetAlert.closeModal(params.onClose)
  850. reject('cancel')
  851. }
  852. break
  853. default:
  854. }
  855. }
  856. var $buttons = modal.querySelectorAll('button')
  857. var i
  858. for (i = 0; i < $buttons.length; i++) {
  859. $buttons[i].onclick = onButtonEvent
  860. $buttons[i].onmouseover = onButtonEvent
  861. $buttons[i].onmouseout = onButtonEvent
  862. $buttons[i].onmousedown = onButtonEvent
  863. }
  864. // Closing modal by close button
  865. getCloseButton().onclick = function() {
  866. sweetAlert.closeModal(params.onClose)
  867. reject('close')
  868. }
  869. // Closing modal by overlay click
  870. sweetContainer.onclick = function(e) {
  871. if (e.target !== sweetContainer) {
  872. return
  873. }
  874. if (params.allowOutsideClick) {
  875. sweetAlert.closeModal(params.onClose)
  876. reject('overlay')
  877. }
  878. }
  879. var $confirmButton = getConfirmButton()
  880. var $cancelButton = getCancelButton()
  881. // Reverse buttons if neede d
  882. if (params.reverseButtons) {
  883. $confirmButton.parentNode.insertBefore($cancelButton, $confirmButton)
  884. } else {
  885. $confirmButton.parentNode.insertBefore($confirmButton, $cancelButton)
  886. }
  887. // Focus handling
  888. function setFocus(index, increment) {
  889. var focusableElements = getFocusableElements(params.focusCancel)
  890. // search for visible elements and select the next possible match
  891. for (var i = 0; i < focusableElements.length; i++) {
  892. index = index + increment
  893. // rollover to first item
  894. if (index === focusableElements.length) {
  895. index = 0
  896. // go to last item
  897. } else if (index === -1) {
  898. index = focusableElements.length - 1
  899. }
  900. // determine if element is visible
  901. var el = focusableElements[index]
  902. if (isVisible(el)) {
  903. return el.focus()
  904. }
  905. }
  906. }
  907. function handleKeyDown(event) {
  908. var e = event || window.event
  909. var keyCode = e.keyCode || e.which
  910. if ([9, 13, 32, 27].indexOf(keyCode) === -1) {
  911. // Don't do work on keys we don't care about.
  912. return
  913. }
  914. var $targetElement = e.target || e.srcElement
  915. var focusableElements = getFocusableElements(params.focusCancel)
  916. var btnIndex = -1 // Find the button - note, this is a nodelist, not an array.
  917. for (var i = 0; i < focusableElements.length; i++) {
  918. if ($targetElement === focusableElements[i]) {
  919. btnIndex = i
  920. break
  921. }
  922. }
  923. // TAB
  924. if (keyCode === 9) {
  925. if (!e.shiftKey) {
  926. // Cycle to the next button
  927. setFocus(btnIndex, 1)
  928. } else {
  929. // Cycle to the prev button
  930. setFocus(btnIndex, -1)
  931. }
  932. stopEventPropagation(e)
  933. } else {
  934. if (keyCode === 13 || keyCode === 32) {
  935. if (btnIndex === -1) {
  936. // ENTER/SPACE clicked outside of a button.
  937. if (params.focusCancel) {
  938. fireClick($cancelButton, e)
  939. } else {
  940. fireClick($confirmButton, e)
  941. }
  942. }
  943. } else if (keyCode === 27 && params.allowEscapeKey === true) {
  944. sweetAlert.closeModal(params.onClose)
  945. reject('esc')
  946. }
  947. }
  948. }
  949. states.previousWindowKeyDown = window.onkeydown
  950. window.onkeydown = handleKeyDown
  951. // Loading state
  952. if (params.buttonsStyling) {
  953. $confirmButton.style.borderLeftColor = params.confirmButtonColor
  954. $confirmButton.style.borderRightColor = params.confirmButtonColor
  955. }
  956. /**
  957. * Show spinner instead of Confirm button and disable Cancel button
  958. */
  959. sweetAlert.showLoading = sweetAlert.enableLoading = function() {
  960. show(getSpacer())
  961. show($confirmButton, 'inline-block')
  962. addClass($confirmButton, swalClasses.loading)
  963. addClass(modal, swalClasses.loading)
  964. $confirmButton.disabled = true
  965. $cancelButton.disabled = true
  966. }
  967. /**
  968. * Show spinner instead of Confirm button and disable Cancel button
  969. */
  970. sweetAlert.hideLoading = sweetAlert.disableLoading = function() {
  971. if (!params.showConfirmButton) {
  972. hide($confirmButton)
  973. if (!params.showCancelButton) {
  974. hide(getSpacer())
  975. }
  976. }
  977. removeClass($confirmButton, swalClasses.loading)
  978. removeClass(modal, swalClasses.loading)
  979. $confirmButton.disabled = false
  980. $cancelButton.disabled = false
  981. }
  982. sweetAlert.enableButtons = function() {
  983. $confirmButton.disabled = false
  984. $cancelButton.disabled = false
  985. }
  986. sweetAlert.disableButtons = function() {
  987. $confirmButton.disabled = true
  988. $cancelButton.disabled = true
  989. }
  990. sweetAlert.enableConfirmButton = function() {
  991. $confirmButton.disabled = false
  992. }
  993. sweetAlert.disableConfirmButton = function() {
  994. $confirmButton.disabled = true
  995. }
  996. sweetAlert.enableInput = function() {
  997. var input = getInput()
  998. if (!input) {
  999. return false
  1000. }
  1001. if (input.type === 'radio') {
  1002. var radiosContainer = input.parentNode.parentNode
  1003. var radios = radiosContainer.querySelectorAll('input')
  1004. for (var i = 0; i < radios.length; i++) {
  1005. radios[i].disabled = false
  1006. }
  1007. } else {
  1008. input.disabled = false
  1009. }
  1010. }
  1011. sweetAlert.disableInput = function() {
  1012. var input = getInput()
  1013. if (!input) {
  1014. return false
  1015. }
  1016. if (input && input.type === 'radio') {
  1017. var radiosContainer = input.parentNode.parentNode
  1018. var radios = radiosContainer.querySelectorAll('input')
  1019. for (var i = 0; i < radios.length; i++) {
  1020. radios[i].disabled = true
  1021. }
  1022. } else {
  1023. input.disabled = true
  1024. }
  1025. }
  1026. // Set modal min-height to disable scrolling inside the modal
  1027. sweetAlert.recalculateHeight = debounce(function() {
  1028. var modal = getModal()
  1029. var prevState = modal.style.display
  1030. modal.style.minHeight = ''
  1031. show(modal)
  1032. modal.style.minHeight = (modal.scrollHeight + 1) + 'px'
  1033. modal.style.display = prevState
  1034. }, 50)
  1035. // Show block with validation error
  1036. sweetAlert.showValidationError = function(error) {
  1037. var validationError = getValidationError()
  1038. validationError.innerHTML = error
  1039. show(validationError)
  1040. var input = getInput()
  1041. focusInput(input)
  1042. addClass(input, swalClasses.inputerror)
  1043. }
  1044. // Hide block with validation error
  1045. sweetAlert.resetValidationError = function() {
  1046. var validationError = getValidationError()
  1047. hide(validationError)
  1048. sweetAlert.recalculateHeight()
  1049. var input = getInput()
  1050. if (input) {
  1051. removeClass(input, swalClasses.inputerror)
  1052. }
  1053. }
  1054. sweetAlert.getProgressSteps = function() {
  1055. return params.progressSteps
  1056. }
  1057. sweetAlert.setProgressSteps = function(progressSteps) {
  1058. params.progressSteps = progressSteps
  1059. setParameters(params)
  1060. }
  1061. sweetAlert.showProgressSteps = function() {
  1062. show(getProgressSteps())
  1063. }
  1064. sweetAlert.hideProgressSteps = function() {
  1065. hide(getProgressSteps())
  1066. }
  1067. sweetAlert.enableButtons()
  1068. sweetAlert.hideLoading()
  1069. sweetAlert.resetValidationError()
  1070. // inputs
  1071. var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea']
  1072. var input
  1073. for (i = 0; i < inputTypes.length; i++) {
  1074. var inputClass = swalClasses[inputTypes[i]]
  1075. var inputContainer = getChildByClass(modal, inputClass)
  1076. input = getInput(inputTypes[i])
  1077. // set attributes
  1078. if (input) {
  1079. for (var j in input.attributes) {
  1080. if (input.attributes.hasOwnProperty(j)) {
  1081. var attrName = input.attributes[j].name
  1082. if (attrName !== 'type' && attrName !== 'value') {
  1083. input.removeAttribute(attrName)
  1084. }
  1085. }
  1086. }
  1087. for (var attr in params.inputAttributes) {
  1088. input.setAttribute(attr, params.inputAttributes[attr])
  1089. }
  1090. }
  1091. // set class
  1092. inputContainer.className = inputClass
  1093. if (params.inputClass) {
  1094. addClass(inputContainer, params.inputClass)
  1095. }
  1096. hide(inputContainer)
  1097. }
  1098. var populateInputOptions
  1099. switch (params.input) {
  1100. case 'text':
  1101. case 'email':
  1102. case 'password':
  1103. case 'number':
  1104. case 'tel':
  1105. input = getChildByClass(modal, swalClasses.input)
  1106. input.value = params.inputValue
  1107. input.placeholder = params.inputPlaceholder
  1108. input.type = params.input
  1109. show(input)
  1110. break
  1111. case 'file':
  1112. input = getChildByClass(modal, swalClasses.file)
  1113. input.placeholder = params.inputPlaceholder
  1114. input.type = params.input
  1115. show(input)
  1116. break
  1117. case 'range':
  1118. var range = getChildByClass(modal, swalClasses.range)
  1119. var rangeInput = range.querySelector('input')
  1120. var rangeOutput = range.querySelector('output')
  1121. rangeInput.value = params.inputValue
  1122. rangeInput.type = params.input
  1123. rangeOutput.value = params.inputValue
  1124. show(range)
  1125. break
  1126. case 'select':
  1127. var select = getChildByClass(modal, swalClasses.select)
  1128. select.innerHTML = ''
  1129. if (params.inputPlaceholder) {
  1130. var placeholder = document.createElement('option')
  1131. placeholder.innerHTML = params.inputPlaceholder
  1132. placeholder.value = ''
  1133. placeholder.disabled = true
  1134. placeholder.selected = true
  1135. select.appendChild(placeholder)
  1136. }
  1137. populateInputOptions = function(inputOptions) {
  1138. for (var optionValue in inputOptions) {
  1139. var option = document.createElement('option')
  1140. option.value = optionValue
  1141. option.innerHTML = inputOptions[optionValue]
  1142. if (params.inputValue === optionValue) {
  1143. option.selected = true
  1144. }
  1145. select.appendChild(option)
  1146. }
  1147. show(select)
  1148. select.focus()
  1149. }
  1150. break
  1151. case 'radio':
  1152. var radio = getChildByClass(modal, swalClasses.radio)
  1153. radio.innerHTML = ''
  1154. populateInputOptions = function(inputOptions) {
  1155. for (var radioValue in inputOptions) {
  1156. var id = 1
  1157. var radioInput = document.createElement('input')
  1158. var radioLabel = document.createElement('label')
  1159. var radioLabelSpan = document.createElement('span')
  1160. radioInput.type = 'radio'
  1161. radioInput.name = swalClasses.radio
  1162. radioInput.value = radioValue
  1163. radioInput.id = swalClasses.radio + '-' + (id++)
  1164. if (params.inputValue === radioValue) {
  1165. radioInput.checked = true
  1166. }
  1167. radioLabelSpan.innerHTML = inputOptions[radioValue]
  1168. radioLabel.appendChild(radioInput)
  1169. radioLabel.appendChild(radioLabelSpan)
  1170. radioLabel.for = radioInput.id
  1171. radio.appendChild(radioLabel)
  1172. }
  1173. show(radio)
  1174. var radios = radio.querySelectorAll('input')
  1175. if (radios.length) {
  1176. radios[0].focus()
  1177. }
  1178. }
  1179. break
  1180. case 'checkbox':
  1181. var checkbox = getChildByClass(modal, swalClasses.checkbox)
  1182. var checkboxInput = getInput('checkbox')
  1183. checkboxInput.type = 'checkbox'
  1184. checkboxInput.value = 1
  1185. checkboxInput.id = swalClasses.checkbox
  1186. checkboxInput.checked = Boolean(params.inputValue)
  1187. var label = checkbox.getElementsByTagName('span')
  1188. if (label.length) {
  1189. checkbox.removeChild(label[0])
  1190. }
  1191. label = document.createElement('span')
  1192. label.innerHTML = params.inputPlaceholder
  1193. checkbox.appendChild(label)
  1194. show(checkbox)
  1195. break
  1196. case 'textarea':
  1197. var textarea = getChildByClass(modal, swalClasses.textarea)
  1198. textarea.value = params.inputValue
  1199. textarea.placeholder = params.inputPlaceholder
  1200. show(textarea)
  1201. break
  1202. case null:
  1203. break
  1204. default:
  1205. console.error('SweetAlert2: Unexpected type of input! Expected "text" or "email" or "password", "select", "checkbox", "textarea" or "file", got "' + params.input + '"')
  1206. break
  1207. }
  1208. if (params.input === 'select' || params.input === 'radio') {
  1209. if (params.inputOptions instanceof Promise) {
  1210. sweetAlert.showLoading()
  1211. params.inputOptions.then(function(inputOptions) {
  1212. sweetAlert.hideLoading()
  1213. populateInputOptions(inputOptions)
  1214. })
  1215. } else if (typeof params.inputOptions === 'object') {
  1216. populateInputOptions(params.inputOptions)
  1217. } else {
  1218. console.error('SweetAlert2: Unexpected type of inputOptions! Expected object or Promise, got ' + typeof params.inputOptions)
  1219. }
  1220. }
  1221. openModal(params.animation, params.onOpen)
  1222. // Focus the first element (input or button)
  1223. setFocus(-1, 1)
  1224. // fix scroll
  1225. sweetContainer.scrollTop = 0
  1226. // Observe changes inside the modal and adjust height
  1227. if (typeof MutationObserver !== 'undefined' && !swal2Observer) {
  1228. swal2Observer = new MutationObserver(sweetAlert.recalculateHeight)
  1229. swal2Observer.observe(modal, {
  1230. childList: true,
  1231. characterData: true,
  1232. subtree: true
  1233. })
  1234. }
  1235. })
  1236. }
  1237. // SweetAlert function
  1238. function sweetAlert() {
  1239. // Copy arguments to the local args variable
  1240. var args = arguments
  1241. if (sweetAlert.isVisible()) {
  1242. sweetAlert.close()
  1243. }
  1244. return modalDependant.apply(this, args)
  1245. }
  1246. /*
  1247. * Global function to determine if swal2 modal is visible
  1248. */
  1249. sweetAlert.isVisible = function() {
  1250. var modal = getModal()
  1251. return isVisible(modal)
  1252. }
  1253. /*
  1254. * Global function for chaining sweetAlert modals
  1255. */
  1256. sweetAlert.queue = function(steps) {
  1257. queue = steps
  1258. var modal = getModal()
  1259. var resetQueue = function() {
  1260. queue = []
  1261. modal.removeAttribute('data-queue-step')
  1262. }
  1263. return new Promise(function(resolve, reject) {
  1264. (function step(i, callback) {
  1265. if (i < queue.length) {
  1266. modal.setAttribute('data-queue-step', i)
  1267. sweetAlert(queue[i]).then(function() {
  1268. step(i + 1, callback)
  1269. }, function(dismiss) {
  1270. resetQueue()
  1271. reject(dismiss)
  1272. })
  1273. } else {
  1274. resetQueue()
  1275. resolve()
  1276. }
  1277. })(0)
  1278. })
  1279. }
  1280. /*
  1281. * Global function for getting the index of current modal in queue
  1282. */
  1283. sweetAlert.getQueueStep = function() {
  1284. return getModal().getAttribute('data-queue-step')
  1285. }
  1286. /*
  1287. * Global function for inserting a modal to the queue
  1288. */
  1289. sweetAlert.insertQueueStep = function(step, index) {
  1290. if (index && index < queue.length) {
  1291. return queue.splice(index, 0, step)
  1292. }
  1293. return queue.push(step)
  1294. }
  1295. /*
  1296. * Global function for deleting a modal from the queue
  1297. */
  1298. sweetAlert.deleteQueueStep = function(index) {
  1299. if (typeof queue[index] !== 'undefined') {
  1300. queue.splice(index, 1)
  1301. }
  1302. }
  1303. /*
  1304. * Global function to close sweetAlert
  1305. */
  1306. sweetAlert.close = sweetAlert.closeModal = function(onComplete) {
  1307. var modal = getModal()
  1308. removeClass(modal, swalClasses.show)
  1309. addClass(modal, swalClasses.hide)
  1310. // Reset icon animations
  1311. var $successIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.success)
  1312. removeClass($successIcon, 'animate')
  1313. removeClass($successIcon.querySelector('.tip'), 'animate-success-tip')
  1314. removeClass($successIcon.querySelector('.long'), 'animate-success-long')
  1315. var $errorIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.error)
  1316. removeClass($errorIcon, 'animate-error-icon')
  1317. removeClass($errorIcon.querySelector('.x-mark'), 'animate-x-mark')
  1318. var $warningIcon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes.warning)
  1319. removeClass($warningIcon, 'pulse-warning')
  1320. resetPrevState()
  1321. var hideModalAndResetState = function() {
  1322. hide(modal)
  1323. modal.style.minHeight = ''
  1324. removeClass(sweetContainer, swalClasses.in)
  1325. removeClass(document.body, swalClasses.in)
  1326. undoScrollbar()
  1327. undoIOSfix()
  1328. }
  1329. // If animation is supported, animate
  1330. if (animationEndEvent && !hasClass(modal, swalClasses.noanimation)) {
  1331. modal.addEventListener(animationEndEvent, function swalCloseEventFinished() {
  1332. modal.removeEventListener(animationEndEvent, swalCloseEventFinished)
  1333. if (hasClass(modal, swalClasses.hide)) {
  1334. hideModalAndResetState()
  1335. }
  1336. })
  1337. } else {
  1338. // Otherwise, hide immediately
  1339. hideModalAndResetState()
  1340. }
  1341. if (onComplete !== null && typeof onComplete === 'function') {
  1342. onComplete.call(this, modal)
  1343. }
  1344. }
  1345. /*
  1346. * Global function to click 'Confirm' button
  1347. */
  1348. sweetAlert.clickConfirm = function() {
  1349. getConfirmButton().click()
  1350. }
  1351. /*
  1352. * Global function to click 'Cancel' button
  1353. */
  1354. sweetAlert.clickCancel = function() {
  1355. getCancelButton().click()
  1356. }
  1357. /**
  1358. * Set default params for each popup
  1359. * @param {Object} userParams
  1360. */
  1361. sweetAlert.setDefaults = function(userParams) {
  1362. if (!userParams) {
  1363. throw new Error('userParams is required')
  1364. }
  1365. if (typeof userParams !== 'object') {
  1366. throw new Error('userParams has to be a object')
  1367. }
  1368. extend(modalParams, userParams)
  1369. }
  1370. /**
  1371. * Reset default params for each popup
  1372. */
  1373. sweetAlert.resetDefaults = function() {
  1374. modalParams = extend({}, defaultParams)
  1375. }
  1376. sweetAlert.noop = function() {}
  1377. sweetAlert.version = '5.3.5'
  1378. if (typeof Promise === 'function') {
  1379. Promise.prototype.done = Promise.prototype.done || function() { // eslint-disable-line
  1380. return this.catch(function() {
  1381. // Catch promise rejections silently.
  1382. // https://github.com/limonte/sweetalert2/issues/177
  1383. })
  1384. }
  1385. } else {
  1386. console.warn('SweetAlert2: Please inlude Promise polyfill BEFORE including sweetalert2.js if IE10+ support needed.')
  1387. }
  1388. return sweetAlert;
  1389. }));
  1390. if (window.Sweetalert2) window.sweetAlert = window.swal = window.Sweetalert2;