sweet-alert.js 29 KB

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