sweet-alert.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. // SweetAlert
  2. // 2014 (c) - Tristan Edwards
  3. // github.com/t4t5/sweetalert
  4. ;(function(window, document, undefined) {
  5. var modalClass = '.sweet-alert',
  6. overlayClass = '.sweet-overlay',
  7. alertTypes = ['error', 'warning', 'info', 'success'],
  8. defaultParams = {
  9. title: '',
  10. text: '',
  11. type: null,
  12. allowOutsideClick: false,
  13. showConfirmButton: true,
  14. showCancelButton: false,
  15. closeOnConfirm: true,
  16. closeOnCancel: true,
  17. confirmButtonText: 'OK',
  18. confirmButtonColor: '#AEDEF4',
  19. cancelButtonText: 'Cancel',
  20. imageUrl: null,
  21. imageSize: null,
  22. timer: null,
  23. customClass: '',
  24. html: false,
  25. animation: true,
  26. allowEscapeKey: true
  27. };
  28. /*
  29. * Manipulate DOM
  30. */
  31. var getModal = function() {
  32. var $modal = document.querySelector(modalClass);
  33. if (!$modal) {
  34. sweetAlertInitialize();
  35. $modal = getModal();
  36. }
  37. return $modal;
  38. },
  39. getOverlay = function() {
  40. return document.querySelector(overlayClass);
  41. },
  42. hasClass = function(elem, className) {
  43. return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
  44. },
  45. addClass = function(elem, className) {
  46. if (!hasClass(elem, className)) {
  47. elem.className += ' ' + className;
  48. }
  49. },
  50. removeClass = function(elem, className) {
  51. var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' ';
  52. if (hasClass(elem, className)) {
  53. while (newClass.indexOf(' ' + className + ' ') >= 0) {
  54. newClass = newClass.replace(' ' + className + ' ', ' ');
  55. }
  56. elem.className = newClass.replace(/^\s+|\s+$/g, '');
  57. }
  58. },
  59. escapeHtml = function(str) {
  60. var div = document.createElement('div');
  61. div.appendChild(document.createTextNode(str));
  62. return div.innerHTML;
  63. },
  64. _show = function(elem) {
  65. elem.style.opacity = '';
  66. elem.style.display = 'block';
  67. },
  68. show = function(elems) {
  69. if (elems && !elems.length) {
  70. return _show(elems);
  71. }
  72. for (var i = 0; i < elems.length; ++i) {
  73. _show(elems[i]);
  74. }
  75. },
  76. _hide = function(elem) {
  77. elem.style.opacity = '';
  78. elem.style.display = 'none';
  79. },
  80. hide = function(elems) {
  81. if (elems && !elems.length) {
  82. return _hide(elems);
  83. }
  84. for (var i = 0; i < elems.length; ++i) {
  85. _hide(elems[i]);
  86. }
  87. },
  88. isDescendant = function(parent, child) {
  89. var node = child.parentNode;
  90. while (node !== null) {
  91. if (node === parent) {
  92. return true;
  93. }
  94. node = node.parentNode;
  95. }
  96. return false;
  97. },
  98. getTopMargin = function(elem) {
  99. elem.style.left = '-9999px';
  100. elem.style.display = 'block';
  101. var height = elem.clientHeight,
  102. padding;
  103. if (typeof getComputedStyle !== "undefined") { /* IE 8 */
  104. padding = parseInt(getComputedStyle(elem).getPropertyValue('padding'), 10);
  105. } else {
  106. padding = parseInt(elem.currentStyle.padding);
  107. }
  108. elem.style.left = '';
  109. elem.style.display = 'none';
  110. return ('-' + parseInt(height / 2 + padding) + 'px');
  111. },
  112. fadeIn = function(elem, interval) {
  113. if (+elem.style.opacity < 1) {
  114. interval = interval || 16;
  115. elem.style.opacity = 0;
  116. elem.style.display = 'block';
  117. var last = +new Date();
  118. var tick = function() {
  119. elem.style.opacity = +elem.style.opacity + (new Date() - last) / 100;
  120. last = +new Date();
  121. if (+elem.style.opacity < 1) {
  122. setTimeout(tick, interval);
  123. }
  124. };
  125. tick();
  126. }
  127. elem.style.display = 'block'; //fallback IE8
  128. },
  129. fadeOut = function(elem, interval) {
  130. interval = interval || 16;
  131. elem.style.opacity = 1;
  132. var last = +new Date();
  133. var tick = function() {
  134. elem.style.opacity = +elem.style.opacity - (new Date() - last) / 100;
  135. last = +new Date();
  136. if (+elem.style.opacity > 0) {
  137. setTimeout(tick, interval);
  138. } else {
  139. elem.style.display = 'none';
  140. }
  141. };
  142. tick();
  143. },
  144. fireClick = function(node) {
  145. // Taken from http://www.nonobtrusive.com/2011/11/29/programatically-fire-crossbrowser-click-event-with-javascript/
  146. // Then fixed for today's Chrome browser.
  147. if (typeof MouseEvent === 'function') {
  148. // Up-to-date approach
  149. var mevt = new MouseEvent('click', {
  150. view: window,
  151. bubbles: false,
  152. cancelable: true
  153. });
  154. node.dispatchEvent(mevt);
  155. } else if ( document.createEvent ) {
  156. // Fallback
  157. var evt = document.createEvent('MouseEvents');
  158. evt.initEvent('click', false, false);
  159. node.dispatchEvent(evt);
  160. } else if( document.createEventObject ) {
  161. node.fireEvent('onclick') ;
  162. } else if (typeof node.onclick === 'function' ) {
  163. node.onclick();
  164. }
  165. },
  166. stopEventPropagation = function(e) {
  167. // In particular, make sure the space bar doesn't scroll the main window.
  168. if (typeof e.stopPropagation === 'function') {
  169. e.stopPropagation();
  170. e.preventDefault();
  171. } else if (window.event && window.event.hasOwnProperty('cancelBubble')) {
  172. window.event.cancelBubble = true;
  173. }
  174. };
  175. // Remember state in cases where opening and handling a modal will fiddle with it.
  176. var previousActiveElement,
  177. previousDocumentClick,
  178. previousWindowKeyDown,
  179. lastFocusedButton;
  180. /*
  181. * Add modal + overlay to DOM
  182. */
  183. var sweetAlertInitialize = function() {
  184. var sweetHTML = '<div class="sweet-overlay" tabIndex="-1"></div><div class="sweet-alert" tabIndex="-1"><div class="sa-icon sa-error"><span class="sa-x-mark"><span class="sa-line sa-left"></span><span class="sa-line sa-right"></span></span></div><div class="sa-icon sa-warning"> <span class="sa-body"></span> <span class="sa-dot"></span> </div> <div class="sa-icon sa-info"></div> <div class="sa-icon sa-success"> <span class="sa-line sa-tip"></span> <span class="sa-line sa-long"></span> <div class="sa-placeholder"></div> <div class="sa-fix"></div> </div> <div class="sa-icon sa-custom"></div> <h2>Title</h2><p>Text</p><button class="cancel" tabIndex="2">Cancel</button><button class="confirm" tabIndex="1">OK</button></div>',
  185. sweetWrap = document.createElement('div');
  186. sweetWrap.innerHTML = sweetHTML;
  187. // Append elements to body
  188. while (sweetWrap.firstChild) {
  189. document.body.appendChild(sweetWrap.firstChild);
  190. }
  191. };
  192. /*
  193. * Global sweetAlert function
  194. */
  195. var sweetAlert, swal;
  196. sweetAlert = swal = function() {
  197. var customizations = arguments[0];
  198. /*
  199. * Use argument if defined or default value from params object otherwise.
  200. * Supports the case where a default value is boolean true and should be
  201. * overridden by a corresponding explicit argument which is boolean false.
  202. */
  203. function argumentOrDefault(key) {
  204. var args = customizations;
  205. if (typeof args[key] !== 'undefined') {
  206. return args[key];
  207. } else {
  208. return defaultParams[key];
  209. }
  210. }
  211. if (arguments[0] === undefined) {
  212. logStr('SweetAlert expects at least 1 attribute!');
  213. return false;
  214. }
  215. var params = extend({}, defaultParams);
  216. switch (typeof arguments[0]) {
  217. // Ex: swal("Hello", "Just testing", "info");
  218. case 'string':
  219. params.title = arguments[0];
  220. params.text = arguments[1] || '';
  221. params.type = arguments[2] || '';
  222. break;
  223. // Ex: swal({title:"Hello", text: "Just testing", type: "info"});
  224. case 'object':
  225. if (arguments[0].title === undefined) {
  226. logStr('Missing "title" argument!');
  227. return false;
  228. }
  229. params.title = arguments[0].title;
  230. var availableCustoms = [
  231. 'text',
  232. 'type',
  233. 'customClass',
  234. 'allowOutsideClick',
  235. 'showConfirmButton',
  236. 'showCancelButton',
  237. 'closeOnConfirm',
  238. 'closeOnCancel',
  239. 'timer',
  240. 'confirmButtonColor',
  241. 'cancelButtonText',
  242. 'imageUrl',
  243. 'imageSize',
  244. 'html',
  245. 'animation',
  246. 'allowEscapeKey'];
  247. // It would be nice to just use .forEach here, but IE8... :(
  248. var numCustoms = availableCustoms.length;
  249. for (var customIndex = 0; customIndex < numCustoms; customIndex++) {
  250. var customName = availableCustoms[customIndex];
  251. params[customName] = argumentOrDefault(customName);
  252. }
  253. // Show "Confirm" instead of "OK" if cancel button is visible
  254. params.confirmButtonText = (params.showCancelButton) ? 'Confirm' : defaultParams.confirmButtonText;
  255. params.confirmButtonText = argumentOrDefault('confirmButtonText');
  256. // Function to call when clicking on cancel/OK
  257. params.doneFunction = arguments[1] || null;
  258. break;
  259. default:
  260. logStr('Unexpected type of argument! Expected "string" or "object", got ' + typeof arguments[0]);
  261. return false;
  262. }
  263. setParameters(params);
  264. fixVerticalPosition();
  265. openModal();
  266. // Modal interactions
  267. var modal = getModal();
  268. // Mouse interactions
  269. var onButtonEvent = function(event) {
  270. var e = event || window.event;
  271. var target = e.target || e.srcElement,
  272. targetedConfirm = (target.className.indexOf("confirm") !== -1),
  273. modalIsVisible = hasClass(modal, 'visible'),
  274. doneFunctionExists = (params.doneFunction && modal.getAttribute('data-has-done-function') === 'true');
  275. switch (e.type) {
  276. case ("mouseover"):
  277. if (targetedConfirm) {
  278. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.04);
  279. }
  280. break;
  281. case ("mouseout"):
  282. if (targetedConfirm) {
  283. target.style.backgroundColor = params.confirmButtonColor;
  284. }
  285. break;
  286. case ("mousedown"):
  287. if (targetedConfirm) {
  288. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.14);
  289. }
  290. break;
  291. case ("mouseup"):
  292. if (targetedConfirm) {
  293. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.04);
  294. }
  295. break;
  296. case ("focus"):
  297. var $confirmButton = modal.querySelector('button.confirm'),
  298. $cancelButton = modal.querySelector('button.cancel');
  299. if (targetedConfirm) {
  300. $cancelButton.style.boxShadow = 'none';
  301. } else {
  302. $confirmButton.style.boxShadow = 'none';
  303. }
  304. break;
  305. case ("click"):
  306. if (targetedConfirm && doneFunctionExists && modalIsVisible) { // Clicked "confirm"
  307. params.doneFunction(true);
  308. if (params.closeOnConfirm) {
  309. sweetAlert.close();
  310. }
  311. } else if (doneFunctionExists && modalIsVisible) { // Clicked "cancel"
  312. // Check if callback function expects a parameter (to track cancel actions)
  313. var functionAsStr = String(params.doneFunction).replace(/\s/g, '');
  314. var functionHandlesCancel = functionAsStr.substring(0, 9) === "function(" && functionAsStr.substring(9, 10) !== ")";
  315. if (functionHandlesCancel) {
  316. params.doneFunction(false);
  317. }
  318. if (params.closeOnCancel) {
  319. sweetAlert.close();
  320. }
  321. } else {
  322. sweetAlert.close();
  323. }
  324. break;
  325. }
  326. };
  327. var $buttons = modal.querySelectorAll('button');
  328. for (var i = 0; i < $buttons.length; i++) {
  329. $buttons[i].onclick = onButtonEvent;
  330. $buttons[i].onmouseover = onButtonEvent;
  331. $buttons[i].onmouseout = onButtonEvent;
  332. $buttons[i].onmousedown = onButtonEvent;
  333. //$buttons[i].onmouseup = onButtonEvent;
  334. $buttons[i].onfocus = onButtonEvent;
  335. }
  336. // Remember the current document.onclick event.
  337. previousDocumentClick = document.onclick;
  338. document.onclick = function(event) {
  339. var e = event || window.event;
  340. var target = e.target || e.srcElement;
  341. var clickedOnModal = (modal === target),
  342. clickedOnModalChild = isDescendant(modal, target),
  343. modalIsVisible = hasClass(modal, 'visible'),
  344. outsideClickIsAllowed = modal.getAttribute('data-allow-ouside-click') === 'true';
  345. if (!clickedOnModal && !clickedOnModalChild && modalIsVisible && outsideClickIsAllowed) {
  346. sweetAlert.close();
  347. }
  348. };
  349. // Keyboard interactions
  350. var $okButton = modal.querySelector('button.confirm'),
  351. $cancelButton = modal.querySelector('button.cancel'),
  352. $modalButtons = modal.querySelectorAll('button[tabindex]');
  353. function handleKeyDown(event) {
  354. var e = event || window.event;
  355. var keyCode = e.keyCode || e.which;
  356. if ([9,13,32,27].indexOf(keyCode) === -1) {
  357. // Don't do work on keys we don't care about.
  358. return;
  359. }
  360. var $targetElement = e.target || e.srcElement;
  361. var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
  362. for (var i = 0; i < $modalButtons.length; i++) {
  363. if ($targetElement === $modalButtons[i]) {
  364. btnIndex = i;
  365. break;
  366. }
  367. }
  368. if (keyCode === 9) {
  369. // TAB
  370. if (btnIndex === -1) {
  371. // No button focused. Jump to the confirm button.
  372. $targetElement = $okButton;
  373. } else {
  374. // Cycle to the next button
  375. if (btnIndex === $modalButtons.length - 1) {
  376. $targetElement = $modalButtons[0];
  377. } else {
  378. $targetElement = $modalButtons[btnIndex + 1];
  379. }
  380. }
  381. stopEventPropagation(e);
  382. $targetElement.focus();
  383. setFocusStyle($targetElement, params.confirmButtonColor); // TODO
  384. } else {
  385. if (keyCode === 13 || keyCode === 32) {
  386. if (btnIndex === -1) {
  387. // ENTER/SPACE clicked outside of a button.
  388. $targetElement = $okButton;
  389. } else {
  390. // Do nothing - let the browser handle it.
  391. $targetElement = undefined;
  392. }
  393. } else if (keyCode === 27 && params.allowEscapeKey === true) {
  394. $targetElement = $cancelButton;
  395. } else {
  396. // Fallback - let the browser handle it.
  397. $targetElement = undefined;
  398. }
  399. if ($targetElement !== undefined) {
  400. fireClick($targetElement, e);
  401. }
  402. }
  403. }
  404. previousWindowKeyDown = window.onkeydown;
  405. window.onkeydown = handleKeyDown;
  406. function handleOnBlur(event) {
  407. var e = event || window.event;
  408. var $targetElement = e.target || e.srcElement,
  409. $focusElement = e.relatedTarget,
  410. modalIsVisible = hasClass(modal, 'visible');
  411. if (modalIsVisible) {
  412. var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
  413. if ($focusElement !== null) {
  414. // If we picked something in the DOM to focus to, let's see if it was a button.
  415. for (var i = 0; i < $modalButtons.length; i++) {
  416. if ($focusElement === $modalButtons[i]) {
  417. btnIndex = i;
  418. break;
  419. }
  420. }
  421. if (btnIndex === -1) {
  422. // Something in the dom, but not a visible button. Focus back on the button.
  423. $targetElement.focus();
  424. }
  425. } else {
  426. // Exiting the DOM (e.g. clicked in the URL bar);
  427. lastFocusedButton = $targetElement;
  428. }
  429. }
  430. }
  431. $okButton.onblur = handleOnBlur;
  432. $cancelButton.onblur = handleOnBlur;
  433. window.onfocus = function() {
  434. // When the user has focused away and focused back from the whole window.
  435. window.setTimeout(function() {
  436. // Put in a timeout to jump out of the event sequence. Calling focus() in the event
  437. // sequence confuses things.
  438. if (lastFocusedButton !== undefined) {
  439. lastFocusedButton.focus();
  440. lastFocusedButton = undefined;
  441. }
  442. }, 0);
  443. };
  444. };
  445. /*
  446. * Set default params for each popup
  447. * @param {Object} userParams
  448. */
  449. sweetAlert.setDefaults = swal.setDefaults = function(userParams) {
  450. if (!userParams) {
  451. throw new Error('userParams is required');
  452. }
  453. if (typeof userParams !== 'object') {
  454. throw new Error('userParams has to be a object');
  455. }
  456. extend(defaultParams, userParams);
  457. };
  458. /*
  459. * Set type, text and actions on modal
  460. */
  461. function setParameters(params) {
  462. var modal = getModal();
  463. var $title = modal.querySelector('h2'),
  464. $text = modal.querySelector('p'),
  465. $cancelBtn = modal.querySelector('button.cancel'),
  466. $confirmBtn = modal.querySelector('button.confirm');
  467. // Title
  468. $title.innerHTML = (params.html) ? params.title : escapeHtml(params.title).split("\n").join("<br>");
  469. // Text
  470. $text.innerHTML = (params.html) ? params.text : escapeHtml(params.text || '').split("\n").join("<br>");
  471. if (params.text) {
  472. show($text);
  473. }
  474. //Custom Class
  475. if (params.customClass) {
  476. addClass(modal, params.customClass);
  477. modal.setAttribute('data-custom-class', params.customClass);
  478. } else {
  479. // Find previously set classes and remove them
  480. var customClass = modal.getAttribute('data-custom-class');
  481. removeClass(modal, customClass);
  482. modal.setAttribute('data-custom-class', "");
  483. }
  484. // Icon
  485. hide(modal.querySelectorAll('.sa-icon'));
  486. if (params.type && !isIE8()) {
  487. var validType = false;
  488. for (var i = 0; i < alertTypes.length; i++) {
  489. if (params.type === alertTypes[i]) {
  490. validType = true;
  491. break;
  492. }
  493. }
  494. if (!validType) {
  495. logStr('Unknown alert type: ' + params.type);
  496. return false;
  497. }
  498. var $icon = modal.querySelector('.sa-icon.' + 'sa-' + params.type);
  499. show($icon);
  500. // Animate icon
  501. switch (params.type) {
  502. case "success":
  503. addClass($icon, 'animate');
  504. addClass($icon.querySelector('.sa-tip'), 'animateSuccessTip');
  505. addClass($icon.querySelector('.sa-long'), 'animateSuccessLong');
  506. break;
  507. case "error":
  508. addClass($icon, 'animateErrorIcon');
  509. addClass($icon.querySelector('.sa-x-mark'), 'animateXMark');
  510. break;
  511. case "warning":
  512. addClass($icon, 'pulseWarning');
  513. addClass($icon.querySelector('.sa-body'), 'pulseWarningIns');
  514. addClass($icon.querySelector('.sa-dot'), 'pulseWarningIns');
  515. break;
  516. }
  517. }
  518. // Custom image
  519. if (params.imageUrl) {
  520. var $customIcon = modal.querySelector('.sa-icon.sa-custom');
  521. $customIcon.style.backgroundImage = 'url(' + params.imageUrl + ')';
  522. show($customIcon);
  523. var _imgWidth = 80,
  524. _imgHeight = 80;
  525. if (params.imageSize) {
  526. var dimensions = params.imageSize.toString().split('x');
  527. var imgWidth = dimensions[0];
  528. var imgHeight = dimensions[1];
  529. if (!imgWidth || !imgHeight) {
  530. logStr("Parameter imageSize expects value with format WIDTHxHEIGHT, got " + params.imageSize);
  531. } else {
  532. _imgWidth = imgWidth;
  533. _imgHeight = imgHeight;
  534. }
  535. }
  536. $customIcon.setAttribute('style', $customIcon.getAttribute('style') + 'width:' + _imgWidth + 'px; height:' + _imgHeight + 'px');
  537. }
  538. // Show cancel button?
  539. modal.setAttribute('data-has-cancel-button', params.showCancelButton);
  540. if (params.showCancelButton) {
  541. $cancelBtn.style.display = 'inline-block';
  542. } else {
  543. hide($cancelBtn);
  544. }
  545. // Show confirm button?
  546. modal.setAttribute('data-has-confirm-button', params.showConfirmButton);
  547. if (params.showConfirmButton) {
  548. $confirmBtn.style.display = 'inline-block';
  549. } else {
  550. hide($confirmBtn);
  551. }
  552. // Edit text on cancel and confirm buttons
  553. if (params.cancelButtonText) {
  554. $cancelBtn.innerHTML = escapeHtml(params.cancelButtonText);
  555. }
  556. if (params.confirmButtonText) {
  557. $confirmBtn.innerHTML = escapeHtml(params.confirmButtonText);
  558. }
  559. // Set confirm button to selected background color
  560. $confirmBtn.style.backgroundColor = params.confirmButtonColor;
  561. // Set box-shadow to default focused button
  562. setFocusStyle($confirmBtn, params.confirmButtonColor);
  563. // Allow outside click?
  564. modal.setAttribute('data-allow-ouside-click', params.allowOutsideClick);
  565. // Done-function
  566. var hasDoneFunction = (params.doneFunction) ? true : false;
  567. modal.setAttribute('data-has-done-function', hasDoneFunction);
  568. // Prevent modal from animating
  569. if (!params.animation){
  570. modal.setAttribute('data-animation', 'none');
  571. } else{
  572. modal.setAttribute('data-animation', 'pop');
  573. }
  574. // Close timer
  575. modal.setAttribute('data-timer', params.timer);
  576. }
  577. /*
  578. * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color)
  579. */
  580. function colorLuminance(hex, lum) {
  581. // Validate hex string
  582. hex = String(hex).replace(/[^0-9a-f]/gi, '');
  583. if (hex.length < 6) {
  584. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  585. }
  586. lum = lum || 0;
  587. // Convert to decimal and change luminosity
  588. var rgb = "#", c, i;
  589. for (i = 0; i < 3; i++) {
  590. c = parseInt(hex.substr(i*2,2), 16);
  591. c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
  592. rgb += ("00"+c).substr(c.length);
  593. }
  594. return rgb;
  595. }
  596. function extend(a, b){
  597. for (var key in b) {
  598. if (b.hasOwnProperty(key)) {
  599. a[key] = b[key];
  600. }
  601. }
  602. return a;
  603. }
  604. function hexToRgb(hex) {
  605. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  606. return result ? parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) : null;
  607. }
  608. // Add box-shadow style to button (depending on its chosen bg-color)
  609. function setFocusStyle($button, bgColor) {
  610. var rgbColor = hexToRgb(bgColor);
  611. $button.style.boxShadow = '0 0 2px rgba(' + rgbColor +', 0.8), inset 0 0 0 1px rgba(0, 0, 0, 0.05)';
  612. }
  613. // Animation when opening modal
  614. function openModal() {
  615. var modal = getModal();
  616. fadeIn(getOverlay(), 10);
  617. show(modal);
  618. addClass(modal, 'showSweetAlert');
  619. removeClass(modal, 'hideSweetAlert');
  620. previousActiveElement = document.activeElement;
  621. var $okButton = modal.querySelector('button.confirm');
  622. $okButton.focus();
  623. setTimeout(function() {
  624. addClass(modal, 'visible');
  625. }, 500);
  626. var timer = modal.getAttribute('data-timer');
  627. if (timer !== "null" && timer !== "") {
  628. modal.timeout = setTimeout(function() {
  629. sweetAlert.close();
  630. }, timer);
  631. }
  632. }
  633. // Aninmation when closing modal
  634. sweetAlert.close = swal.close = function() {
  635. var modal = getModal();
  636. fadeOut(getOverlay(), 5);
  637. fadeOut(modal, 5);
  638. removeClass(modal, 'showSweetAlert');
  639. addClass(modal, 'hideSweetAlert');
  640. removeClass(modal, 'visible');
  641. // Reset icon animations
  642. var $successIcon = modal.querySelector('.sa-icon.sa-success');
  643. removeClass($successIcon, 'animate');
  644. removeClass($successIcon.querySelector('.sa-tip'), 'animateSuccessTip');
  645. removeClass($successIcon.querySelector('.sa-long'), 'animateSuccessLong');
  646. var $errorIcon = modal.querySelector('.sa-icon.sa-error');
  647. removeClass($errorIcon, 'animateErrorIcon');
  648. removeClass($errorIcon.querySelector('.sa-x-mark'), 'animateXMark');
  649. var $warningIcon = modal.querySelector('.sa-icon.sa-warning');
  650. removeClass($warningIcon, 'pulseWarning');
  651. removeClass($warningIcon.querySelector('.sa-body'), 'pulseWarningIns');
  652. removeClass($warningIcon.querySelector('.sa-dot'), 'pulseWarningIns');
  653. // Reset the page to its previous state
  654. window.onkeydown = previousWindowKeyDown;
  655. document.onclick = previousDocumentClick;
  656. if (previousActiveElement) {
  657. previousActiveElement.focus();
  658. }
  659. lastFocusedButton = undefined;
  660. clearTimeout(modal.timeout);
  661. };
  662. /*
  663. * Set "margin-top"-property on modal based on its computed height
  664. */
  665. function fixVerticalPosition() {
  666. var modal = getModal();
  667. modal.style.marginTop = getTopMargin(getModal());
  668. }
  669. // If browser is Internet Explorer 8
  670. function isIE8() {
  671. if (window.attachEvent && !window.addEventListener) {
  672. return true;
  673. } else {
  674. return false;
  675. }
  676. }
  677. // Error messages for developers
  678. function logStr(string) {
  679. if (window.console) { // IE...
  680. window.console.log("SweetAlert: " + string);
  681. }
  682. }
  683. if (typeof define === 'function' && define.amd) {
  684. define(function() { return sweetAlert; });
  685. } else if (typeof module !== 'undefined' && module.exports) {
  686. module.exports = sweetAlert;
  687. } else if (typeof window !== 'undefined') {
  688. window.sweetAlert = window.swal = sweetAlert;
  689. }
  690. })(window, document);