From 21b17295f6dac0c97cce13bba89208ac5353a7cb Mon Sep 17 00:00:00 2001 From: adhimrahman Date: Tue, 7 May 2024 15:05:54 +0800 Subject: [PATCH] add: new modules --- node_modules/.package-lock.json | 37 +- node_modules/convert-source-map/README.md | 103 +- node_modules/convert-source-map/index.js | 104 +- node_modules/convert-source-map/package.json | 9 +- node_modules/cors/CONTRIBUTING.md | 33 + node_modules/cors/HISTORY.md | 58 + node_modules/cors/LICENSE | 22 + node_modules/cors/README.md | 243 ++ node_modules/cors/lib/index.js | 238 + node_modules/cors/package.json | 41 + node_modules/sweetalert2/README.md | 101 +- .../sweetalert2/dist/sweetalert2.all.js | 3859 +++++++---------- .../sweetalert2/dist/sweetalert2.all.min.js | 6 +- node_modules/sweetalert2/dist/sweetalert2.css | 407 +- node_modules/sweetalert2/dist/sweetalert2.js | 3857 +++++++--------- .../sweetalert2/dist/sweetalert2.min.css | 2 +- .../sweetalert2/dist/sweetalert2.min.js | 4 +- node_modules/sweetalert2/package.json | 26 +- node_modules/sweetalert2/src/SweetAlert.js | 89 +- .../sweetalert2/src/buttons-handlers.js | 32 +- node_modules/sweetalert2/src/globalState.js | 2 +- .../src/instanceMethods/_destroy.js | 34 +- .../sweetalert2/src/instanceMethods/close.js | 72 +- .../enable-disable-elements.js | 29 +- .../src/instanceMethods/getInput.js | 9 +- .../src/instanceMethods/validation-message.js | 5 +- .../sweetalert2/src/keydown-handler.js | 101 +- .../sweetalert2/src/popup-click-handler.js | 45 +- node_modules/sweetalert2/src/privateProps.js | 2 + node_modules/sweetalert2/src/scss/_core.scss | 952 ++-- .../sweetalert2/src/scss/_toasts-body.scss | 45 +- .../sweetalert2/src/scss/_toasts.scss | 1 + .../sweetalert2/src/staticMethods/dom.js | 6 +- .../sweetalert2/src/staticMethods/fire.js | 6 - .../sweetalert2/src/staticMethods/mixin.js | 5 +- .../src/staticMethods/showLoading.js | 14 +- .../sweetalert2/src/staticMethods/timer.js | 8 +- node_modules/sweetalert2/src/types.js | 8 +- .../sweetalert2/src/utils/DismissReason.js | 3 - node_modules/sweetalert2/src/utils/Timer.js | 18 +- node_modules/sweetalert2/src/utils/aria.js | 7 +- node_modules/sweetalert2/src/utils/classes.js | 104 +- .../src/utils/defaultInputValidators.js | 10 +- .../src/utils/dom/animationEndEvent.js | 16 +- .../sweetalert2/src/utils/dom/domUtils.js | 73 +- .../sweetalert2/src/utils/dom/getters.js | 54 +- .../sweetalert2/src/utils/dom/index.js | 1 + .../sweetalert2/src/utils/dom/init.js | 11 +- .../sweetalert2/src/utils/dom/inputUtils.js | 178 +- .../src/utils/dom/measureScrollbar.js | 16 + .../src/utils/dom/parseHtmlToContainer.js | 4 +- .../src/utils/dom/renderers/render.js | 7 +- .../src/utils/dom/renderers/renderActions.js | 19 +- .../utils/dom/renderers/renderCloseButton.js | 9 +- .../utils/dom/renderers/renderContainer.js | 13 +- .../src/utils/dom/renderers/renderContent.js | 7 +- .../src/utils/dom/renderers/renderFooter.js | 9 +- .../src/utils/dom/renderers/renderIcon.js | 27 +- .../src/utils/dom/renderers/renderImage.js | 7 +- .../src/utils/dom/renderers/renderInput.js | 43 +- .../src/utils/dom/renderers/renderPopup.js | 11 +- .../dom/renderers/renderProgressSteps.js | 18 +- .../src/utils/dom/renderers/renderTitle.js | 7 +- node_modules/sweetalert2/src/utils/iosFix.js | 57 +- .../sweetalert2/src/utils/openPopup.js | 28 +- node_modules/sweetalert2/src/utils/params.js | 8 +- .../sweetalert2/src/utils/scrollbarFix.js | 21 + .../sweetalert2/src/utils/setParameters.js | 14 +- node_modules/sweetalert2/src/utils/utils.js | 22 +- node_modules/sweetalert2/src/variables.scss | 29 +- node_modules/sweetalert2/sweetalert2.d.ts | 122 +- .../node_modules/convert-source-map/LICENSE | 23 + .../node_modules/convert-source-map/README.md | 206 + .../node_modules/convert-source-map/index.js | 233 + .../convert-source-map/package.json | 38 + package-lock.json | 43 +- package.json | 5 +- 77 files changed, 5915 insertions(+), 6221 deletions(-) create mode 100644 node_modules/cors/CONTRIBUTING.md create mode 100644 node_modules/cors/HISTORY.md create mode 100644 node_modules/cors/LICENSE create mode 100644 node_modules/cors/README.md create mode 100644 node_modules/cors/lib/index.js create mode 100644 node_modules/cors/package.json create mode 100644 node_modules/sweetalert2/src/utils/dom/measureScrollbar.js create mode 100644 node_modules/sweetalert2/src/utils/scrollbarFix.js create mode 100644 node_modules/vinyl-sourcemap/node_modules/convert-source-map/LICENSE create mode 100644 node_modules/vinyl-sourcemap/node_modules/convert-source-map/README.md create mode 100644 node_modules/vinyl-sourcemap/node_modules/convert-source-map/index.js create mode 100644 node_modules/vinyl-sourcemap/node_modules/convert-source-map/package.json diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 9637800a..c38f3caa 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,5 +1,6 @@ { - "name": "SpotitipV2", + "name": "spotitipv2", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { @@ -174,11 +175,6 @@ "stylis": "4.2.0" } }, - "node_modules/@emotion/babel-plugin/node_modules/convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==" - }, "node_modules/@emotion/cache": { "version": "11.11.0", "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.11.0.tgz", @@ -1276,9 +1272,9 @@ } }, "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==" }, "node_modules/cookie": { "version": "0.6.0", @@ -1310,6 +1306,18 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/cosmiconfig": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", @@ -4025,9 +4033,9 @@ } }, "node_modules/sweetalert2": { - "version": "11.10.7", - "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-11.10.7.tgz", - "integrity": "sha512-5Jlzrmaitay6KzU+2+LhYu9q+L4v/dZ8oZyEDH14ep0C/QilCnFLHmqAyD/Lhq/lm5DiwsOs6Tr58iv8k3wyGg==", + "version": "11.6.13", + "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-11.6.13.tgz", + "integrity": "sha512-n5yVF0FNx1lm4XzpPyb1HIaiptzODfVyeCzmB809tpK+1bPdoKoevKOxYjrtId75DV7xuIp4r6cjn8xUAB8dPQ==", "funding": { "type": "individual", "url": "https://github.com/sponsors/limonte" @@ -4324,6 +4332,11 @@ "node": ">=10.13.0" } }, + "node_modules/vinyl-sourcemap/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/node_modules/convert-source-map/README.md b/node_modules/convert-source-map/README.md index aa4d8048..7a3a9452 100644 --- a/node_modules/convert-source-map/README.md +++ b/node_modules/convert-source-map/README.md @@ -23,23 +23,6 @@ console.log(modified); {"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"} ``` -## Upgrading - -Prior to v2.0.0, the `fromMapFileComment` and `fromMapFileSource` functions took a String directory path and used that to resolve & read the source map file from the filesystem. However, this made the library limited to nodejs environments and broke on sources with querystrings. - -In v2.0.0, you now need to pass a function that does the file reading. It will receive the source filename as a String that you can resolve to a filesystem path, URL, or anything else. - -If you are using `convert-source-map` in nodejs and want the previous behavior, you'll use a function like such: - -```diff -+ var fs = require('fs'); // Import the fs module to read a file -+ var path = require('path'); // Import the path module to resolve a path against your directory -- var conv = convert.fromMapFileSource(css, '../my-dir'); -+ var conv = convert.fromMapFileSource(css, function (filename) { -+ return fs.readFileSync(path.resolve('../my-dir', filename), 'utf-8'); -+ }); -``` - ## API ### fromObject(obj) @@ -50,90 +33,32 @@ Returns source map converter from given object. Returns source map converter from given json string. -### fromURI(uri) - -Returns source map converter from given uri encoded json string. - ### fromBase64(base64) Returns source map converter from given base64 encoded json string. ### fromComment(comment) -Returns source map converter from given base64 or uri encoded json string prefixed with `//# sourceMappingURL=...`. +Returns source map converter from given base64 encoded json string prefixed with `//# sourceMappingURL=...`. -### fromMapFileComment(comment, readMap) +### fromMapFileComment(comment, mapFileDir) Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`. -`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). - -If `readMap` doesn't return a `Promise`, `fromMapFileComment` will return a source map converter synchronously. - -If `readMap` returns a `Promise`, `fromMapFileComment` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. - -#### Examples - -**Synchronous read in Node.js:** - -```js -var convert = require('convert-source-map'); -var fs = require('fs'); - -function readMap(filename) { - return fs.readFileSync(filename, 'utf8'); -} - -var json = convert - .fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) - .toJSON(); -console.log(json); -``` - - -**Asynchronous read in Node.js:** - -```js -var convert = require('convert-source-map'); -var { promises: fs } = require('fs'); // Notice the `promises` import - -function readMap(filename) { - return fs.readFile(filename, 'utf8'); -} - -var converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) -var json = converter.toJSON(); -console.log(json); -``` - -**Asynchronous read in the browser:** - -```js -var convert = require('convert-source-map'); - -async function readMap(url) { - const res = await fetch(url); - return res.text(); -} - -const converter = await convert.fromMapFileComment('//# sourceMappingURL=map-file-comment.css.map', readMap) -var json = converter.toJSON(); -console.log(json); -``` +`filename` must point to a file that is found inside the `mapFileDir`. Most tools store this file right next to the +generated file, i.e. the one containing the source map. ### fromSource(source) -Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. - -### fromMapFileSource(source, readMap) +Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. -Finds last sourcemap comment in file and returns source map converter or returns `null` if no source map comment was found. +### fromMapFileSource(source, mapFileDir) -`readMap` must be a function which receives the source map filename and returns either a String or Buffer of the source map (if read synchronously), or a `Promise` containing a String or Buffer of the source map (if read asynchronously). +Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was +found. -If `readMap` doesn't return a `Promise`, `fromMapFileSource` will return a source map converter synchronously. - -If `readMap` returns a `Promise`, `fromMapFileSource` will also return `Promise`. The `Promise` will be either resolved with the source map converter or rejected with an error. +The sourcemap will be read from the map file found by parsing `# sourceMappingURL=file` comment. For more info see +fromMapFileComment. ### toObject() @@ -145,10 +70,6 @@ Converts source map to json string. If `space` is given (optional), this will be [JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the JSON string is generated. -### toURI() - -Converts source map to uri encoded json string. - ### toBase64() Converts source map to base64 encoded json string. @@ -160,8 +81,6 @@ Converts source map to an inline comment that can be appended to the source-file By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. -When `options.encoding == 'uri'`, the data will be uri encoded, otherwise they will be base64 encoded. - When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. ### addProperty(key, value) @@ -188,8 +107,6 @@ Returns `src` with all source map comments pointing to map files removed. Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments. -Breaks down a source map comment into groups: Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. - ### mapFileCommentRegex Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files. diff --git a/node_modules/convert-source-map/index.js b/node_modules/convert-source-map/index.js index 2e8e916e..dc602d7c 100644 --- a/node_modules/convert-source-map/index.js +++ b/node_modules/convert-source-map/index.js @@ -1,17 +1,17 @@ 'use strict'; +var fs = require('fs'); +var path = require('path'); Object.defineProperty(exports, 'commentRegex', { get: function getCommentRegex () { - // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. - return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg; } }); - Object.defineProperty(exports, 'mapFileCommentRegex', { get: function getMapFileCommentRegex () { // Matches sourceMappingURL in either // or /* comment styles. - return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg; } }); @@ -45,43 +45,29 @@ function stripComment(sm) { return sm.split(',').pop(); } -function readFromFileMap(sm, read) { +function readFromFileMap(sm, dir) { + // NOTE: this will only work on the server since it attempts to read the map file + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 var filename = r[1] || r[2]; + var filepath = path.resolve(dir, filename); try { - var sm = read(filename); - if (sm != null && typeof sm.catch === 'function') { - return sm.catch(throwError); - } else { - return sm; - } + return fs.readFileSync(filepath, 'utf8'); } catch (e) { - throwError(e); - } - - function throwError(e) { - throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e); } } function Converter (sm, opts) { opts = opts || {}; - if (opts.hasComment) { - sm = stripComment(sm); - } - - if (opts.encoding === 'base64') { - sm = decodeBase64(sm); - } else if (opts.encoding === 'uri') { - sm = decodeURIComponent(sm); - } - - if (opts.isJSON || opts.encoding) { - sm = JSON.parse(sm); - } + if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir); + if (opts.hasComment) sm = stripComment(sm); + if (opts.isEncoded) sm = decodeBase64(sm); + if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm); this.sourcemap = sm; } @@ -118,22 +104,10 @@ function encodeBase64WithBtoa() { return btoa(unescape(encodeURIComponent(json))); } -Converter.prototype.toURI = function () { - var json = this.toJSON(); - return encodeURIComponent(json); -}; - Converter.prototype.toComment = function (options) { - var encoding, content, data; - if (options != null && options.encoding === 'uri') { - encoding = ''; - content = this.toURI(); - } else { - encoding = ';base64'; - content = this.toBase64(); - } - data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; - return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + var base64 = this.toBase64(); + var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; // returns copy instead of original @@ -163,42 +137,20 @@ exports.fromJSON = function (json) { return new Converter(json, { isJSON: true }); }; -exports.fromURI = function (uri) { - return new Converter(uri, { encoding: 'uri' }); -}; - exports.fromBase64 = function (base64) { - return new Converter(base64, { encoding: 'base64' }); + return new Converter(base64, { isEncoded: true }); }; exports.fromComment = function (comment) { - var m, encoding; comment = comment .replace(/^\/\*/g, '//') .replace(/\*\/$/g, ''); - m = exports.commentRegex.exec(comment); - encoding = m && m[4] || 'uri'; - return new Converter(comment, { encoding: encoding, hasComment: true }); -}; -function makeConverter(sm) { - return new Converter(sm, { isJSON: true }); -} - -exports.fromMapFileComment = function (comment, read) { - if (typeof read === 'string') { - throw new Error( - 'String directory paths are no longer supported with `fromMapFileComment`\n' + - 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' - ) - } + return new Converter(comment, { isEncoded: true, hasComment: true }); +}; - var sm = readFromFileMap(comment, read); - if (sm != null && typeof sm.then === 'function') { - return sm.then(makeConverter); - } else { - return makeConverter(sm); - } +exports.fromMapFileComment = function (comment, dir) { + return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true }); }; // Finds last sourcemap comment in file or returns null if none was found @@ -208,15 +160,9 @@ exports.fromSource = function (content) { }; // Finds last sourcemap comment in file or returns null if none was found -exports.fromMapFileSource = function (content, read) { - if (typeof read === 'string') { - throw new Error( - 'String directory paths are no longer supported with `fromMapFileSource`\n' + - 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' - ) - } +exports.fromMapFileSource = function (content, dir) { var m = content.match(exports.mapFileCommentRegex); - return m ? exports.fromMapFileComment(m.pop(), read) : null; + return m ? exports.fromMapFileComment(m.pop(), dir) : null; }; exports.removeComments = function (src) { diff --git a/node_modules/convert-source-map/package.json b/node_modules/convert-source-map/package.json index c38f29f7..0d796cac 100644 --- a/node_modules/convert-source-map/package.json +++ b/node_modules/convert-source-map/package.json @@ -1,6 +1,6 @@ { "name": "convert-source-map", - "version": "2.0.0", + "version": "1.9.0", "description": "Converts a source-map from/to different formats and allows adding/changing properties.", "main": "index.js", "scripts": { @@ -30,9 +30,12 @@ }, "license": "MIT", "engine": { - "node": ">=4" + "node": ">=0.6" }, "files": [ "index.js" - ] + ], + "browser": { + "fs": false + } } diff --git a/node_modules/cors/CONTRIBUTING.md b/node_modules/cors/CONTRIBUTING.md new file mode 100644 index 00000000..591b09a1 --- /dev/null +++ b/node_modules/cors/CONTRIBUTING.md @@ -0,0 +1,33 @@ +# contributing to `cors` + +CORS is a node.js package for providing a [connect](http://www.senchalabs.org/connect/)/[express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options. Learn more about the project in [the README](README.md). + +## The CORS Spec + +[http://www.w3.org/TR/cors/](http://www.w3.org/TR/cors/) + +## Pull Requests Welcome + +* Include `'use strict';` in every javascript file. +* 2 space indentation. +* Please run the testing steps below before submitting. + +## Testing + +```bash +$ npm install +$ npm test +``` + +## Interactive Testing Harness + +[http://node-cors-client.herokuapp.com](http://node-cors-client.herokuapp.com) + +Related git repositories: + +* [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server) +* [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client) + +## License + +[MIT License](http://www.opensource.org/licenses/mit-license.php) diff --git a/node_modules/cors/HISTORY.md b/node_modules/cors/HISTORY.md new file mode 100644 index 00000000..5762bce9 --- /dev/null +++ b/node_modules/cors/HISTORY.md @@ -0,0 +1,58 @@ +2.8.5 / 2018-11-04 +================== + + * Fix setting `maxAge` option to `0` + +2.8.4 / 2017-07-12 +================== + + * Work-around Safari bug in default pre-flight response + +2.8.3 / 2017-03-29 +================== + + * Fix error when options delegate missing `methods` option + +2.8.2 / 2017-03-28 +================== + + * Fix error when frozen options are passed + * Send "Vary: Origin" when using regular expressions + * Send "Vary: Access-Control-Request-Headers" when dynamic `allowedHeaders` + +2.8.1 / 2016-09-08 +================== + +This release only changed documentation. + +2.8.0 / 2016-08-23 +================== + + * Add `optionsSuccessStatus` option + +2.7.2 / 2016-08-23 +================== + + * Fix error when Node.js running in strict mode + +2.7.1 / 2015-05-28 +================== + + * Move module into expressjs organization + +2.7.0 / 2015-05-28 +================== + + * Allow array of matching condition as `origin` option + * Allow regular expression as `origin` option + +2.6.1 / 2015-05-28 +================== + + * Update `license` in package.json + +2.6.0 / 2015-04-27 +================== + + * Add `preflightContinue` option + * Fix "Vary: Origin" header added for "*" diff --git a/node_modules/cors/LICENSE b/node_modules/cors/LICENSE new file mode 100644 index 00000000..fd10c843 --- /dev/null +++ b/node_modules/cors/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Troy Goode + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/cors/README.md b/node_modules/cors/README.md new file mode 100644 index 00000000..732b847e --- /dev/null +++ b/node_modules/cors/README.md @@ -0,0 +1,243 @@ +# cors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options. + +**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** + +* [Installation](#installation) +* [Usage](#usage) + * [Simple Usage](#simple-usage-enable-all-cors-requests) + * [Enable CORS for a Single Route](#enable-cors-for-a-single-route) + * [Configuring CORS](#configuring-cors) + * [Configuring CORS Asynchronously](#configuring-cors-asynchronously) + * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight) +* [Configuration Options](#configuration-options) +* [Demo](#demo) +* [License](#license) +* [Author](#author) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cors +``` + +## Usage + +### Simple Usage (Enable *All* CORS Requests) + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +app.use(cors()) + +app.get('/products/:id', function (req, res, next) { + res.json({msg: 'This is CORS-enabled for all origins!'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +### Enable CORS for a Single Route + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +app.get('/products/:id', cors(), function (req, res, next) { + res.json({msg: 'This is CORS-enabled for a Single Route'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +### Configuring CORS + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +var corsOptions = { + origin: 'http://example.com', + optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 +} + +app.get('/products/:id', cors(corsOptions), function (req, res, next) { + res.json({msg: 'This is CORS-enabled for only example.com.'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +### Configuring CORS w/ Dynamic Origin + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +var whitelist = ['http://example1.com', 'http://example2.com'] +var corsOptions = { + origin: function (origin, callback) { + if (whitelist.indexOf(origin) !== -1) { + callback(null, true) + } else { + callback(new Error('Not allowed by CORS')) + } + } +} + +app.get('/products/:id', cors(corsOptions), function (req, res, next) { + res.json({msg: 'This is CORS-enabled for a whitelisted domain.'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +If you do not want to block REST tools or server-to-server requests, +add a `!origin` check in the origin function like so: + +```javascript +var corsOptions = { + origin: function (origin, callback) { + if (whitelist.indexOf(origin) !== -1 || !origin) { + callback(null, true) + } else { + callback(new Error('Not allowed by CORS')) + } + } +} +``` + +### Enabling CORS Pre-Flight + +Certain CORS requests are considered 'complex' and require an initial +`OPTIONS` request (called the "pre-flight request"). An example of a +'complex' CORS request is one that uses an HTTP verb other than +GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable +pre-flighting, you must add a new OPTIONS handler for the route you want +to support: + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +app.options('/products/:id', cors()) // enable pre-flight request for DELETE request +app.del('/products/:id', cors(), function (req, res, next) { + res.json({msg: 'This is CORS-enabled for all origins!'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +You can also enable pre-flight across-the-board like so: + +```javascript +app.options('*', cors()) // include before other routes +``` + +### Configuring CORS Asynchronously + +```javascript +var express = require('express') +var cors = require('cors') +var app = express() + +var whitelist = ['http://example1.com', 'http://example2.com'] +var corsOptionsDelegate = function (req, callback) { + var corsOptions; + if (whitelist.indexOf(req.header('Origin')) !== -1) { + corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response + } else { + corsOptions = { origin: false } // disable CORS for this request + } + callback(null, corsOptions) // callback expects two parameters: error and options +} + +app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) { + res.json({msg: 'This is CORS-enabled for a whitelisted domain.'}) +}) + +app.listen(80, function () { + console.log('CORS-enabled web server listening on port 80') +}) +``` + +## Configuration Options + +* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values: + - `Boolean` - set `origin` to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS. + - `String` - set `origin` to a specific origin. For example if you set it to `"http://example.com"` only requests from "http://example.com" will be allowed. + - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com". + - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com". + - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature `err [object], allow [bool]`) as the second. +* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`). +* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header. +* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed. +* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted. +* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted. +* `preflightContinue`: Pass the CORS preflight response to the next handler. +* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`. + +The default configuration is the equivalent of: + +```json +{ + "origin": "*", + "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", + "preflightContinue": false, + "optionsSuccessStatus": 204 +} +``` + +For details on the effect of each CORS header, read [this](http://www.html5rocks.com/en/tutorials/cors/) article on HTML5 Rocks. + +## Demo + +A demo that illustrates CORS working (and not working) using jQuery is available here: [http://node-cors-client.herokuapp.com/](http://node-cors-client.herokuapp.com/) + +Code for that demo can be found here: + +* Client: [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client) +* Server: [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server) + +## License + +[MIT License](http://www.opensource.org/licenses/mit-license.php) + +## Author + +[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) + +[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/cors.svg +[downloads-url]: https://npmjs.org/package/cors +[npm-image]: https://img.shields.io/npm/v/cors.svg +[npm-url]: https://npmjs.org/package/cors +[travis-image]: https://img.shields.io/travis/expressjs/cors/master.svg +[travis-url]: https://travis-ci.org/expressjs/cors diff --git a/node_modules/cors/lib/index.js b/node_modules/cors/lib/index.js new file mode 100644 index 00000000..5475aecd --- /dev/null +++ b/node_modules/cors/lib/index.js @@ -0,0 +1,238 @@ +(function () { + + 'use strict'; + + var assign = require('object-assign'); + var vary = require('vary'); + + var defaults = { + origin: '*', + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', + preflightContinue: false, + optionsSuccessStatus: 204 + }; + + function isString(s) { + return typeof s === 'string' || s instanceof String; + } + + function isOriginAllowed(origin, allowedOrigin) { + if (Array.isArray(allowedOrigin)) { + for (var i = 0; i < allowedOrigin.length; ++i) { + if (isOriginAllowed(origin, allowedOrigin[i])) { + return true; + } + } + return false; + } else if (isString(allowedOrigin)) { + return origin === allowedOrigin; + } else if (allowedOrigin instanceof RegExp) { + return allowedOrigin.test(origin); + } else { + return !!allowedOrigin; + } + } + + function configureOrigin(options, req) { + var requestOrigin = req.headers.origin, + headers = [], + isAllowed; + + if (!options.origin || options.origin === '*') { + // allow any origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: '*' + }]); + } else if (isString(options.origin)) { + // fixed origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: options.origin + }]); + headers.push([{ + key: 'Vary', + value: 'Origin' + }]); + } else { + isAllowed = isOriginAllowed(requestOrigin, options.origin); + // reflect origin + headers.push([{ + key: 'Access-Control-Allow-Origin', + value: isAllowed ? requestOrigin : false + }]); + headers.push([{ + key: 'Vary', + value: 'Origin' + }]); + } + + return headers; + } + + function configureMethods(options) { + var methods = options.methods; + if (methods.join) { + methods = options.methods.join(','); // .methods is an array, so turn it into a string + } + return { + key: 'Access-Control-Allow-Methods', + value: methods + }; + } + + function configureCredentials(options) { + if (options.credentials === true) { + return { + key: 'Access-Control-Allow-Credentials', + value: 'true' + }; + } + return null; + } + + function configureAllowedHeaders(options, req) { + var allowedHeaders = options.allowedHeaders || options.headers; + var headers = []; + + if (!allowedHeaders) { + allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers + headers.push([{ + key: 'Vary', + value: 'Access-Control-Request-Headers' + }]); + } else if (allowedHeaders.join) { + allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string + } + if (allowedHeaders && allowedHeaders.length) { + headers.push([{ + key: 'Access-Control-Allow-Headers', + value: allowedHeaders + }]); + } + + return headers; + } + + function configureExposedHeaders(options) { + var headers = options.exposedHeaders; + if (!headers) { + return null; + } else if (headers.join) { + headers = headers.join(','); // .headers is an array, so turn it into a string + } + if (headers && headers.length) { + return { + key: 'Access-Control-Expose-Headers', + value: headers + }; + } + return null; + } + + function configureMaxAge(options) { + var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString() + if (maxAge && maxAge.length) { + return { + key: 'Access-Control-Max-Age', + value: maxAge + }; + } + return null; + } + + function applyHeaders(headers, res) { + for (var i = 0, n = headers.length; i < n; i++) { + var header = headers[i]; + if (header) { + if (Array.isArray(header)) { + applyHeaders(header, res); + } else if (header.key === 'Vary' && header.value) { + vary(res, header.value); + } else if (header.value) { + res.setHeader(header.key, header.value); + } + } + } + } + + function cors(options, req, res, next) { + var headers = [], + method = req.method && req.method.toUpperCase && req.method.toUpperCase(); + + if (method === 'OPTIONS') { + // preflight + headers.push(configureOrigin(options, req)); + headers.push(configureCredentials(options, req)); + headers.push(configureMethods(options, req)); + headers.push(configureAllowedHeaders(options, req)); + headers.push(configureMaxAge(options, req)); + headers.push(configureExposedHeaders(options, req)); + applyHeaders(headers, res); + + if (options.preflightContinue) { + next(); + } else { + // Safari (and potentially other browsers) need content-length 0, + // for 204 or they just hang waiting for a body + res.statusCode = options.optionsSuccessStatus; + res.setHeader('Content-Length', '0'); + res.end(); + } + } else { + // actual response + headers.push(configureOrigin(options, req)); + headers.push(configureCredentials(options, req)); + headers.push(configureExposedHeaders(options, req)); + applyHeaders(headers, res); + next(); + } + } + + function middlewareWrapper(o) { + // if options are static (either via defaults or custom options passed in), wrap in a function + var optionsCallback = null; + if (typeof o === 'function') { + optionsCallback = o; + } else { + optionsCallback = function (req, cb) { + cb(null, o); + }; + } + + return function corsMiddleware(req, res, next) { + optionsCallback(req, function (err, options) { + if (err) { + next(err); + } else { + var corsOptions = assign({}, defaults, options); + var originCallback = null; + if (corsOptions.origin && typeof corsOptions.origin === 'function') { + originCallback = corsOptions.origin; + } else if (corsOptions.origin) { + originCallback = function (origin, cb) { + cb(null, corsOptions.origin); + }; + } + + if (originCallback) { + originCallback(req.headers.origin, function (err2, origin) { + if (err2 || !origin) { + next(err2); + } else { + corsOptions.origin = origin; + cors(corsOptions, req, res, next); + } + }); + } else { + next(); + } + } + }); + }; + } + + // can pass either an options hash, an options delegate, or nothing + module.exports = middlewareWrapper; + +}()); diff --git a/node_modules/cors/package.json b/node_modules/cors/package.json new file mode 100644 index 00000000..ff37d984 --- /dev/null +++ b/node_modules/cors/package.json @@ -0,0 +1,41 @@ +{ + "name": "cors", + "description": "Node.js CORS middleware", + "version": "2.8.5", + "author": "Troy Goode (https://github.com/troygoode/)", + "license": "MIT", + "keywords": [ + "cors", + "express", + "connect", + "middleware" + ], + "repository": "expressjs/cors", + "main": "./lib/index.js", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "devDependencies": { + "after": "0.8.2", + "eslint": "2.13.1", + "express": "4.16.3", + "mocha": "5.2.0", + "nyc": "13.1.0", + "supertest": "3.3.0" + }, + "files": [ + "lib/index.js", + "CONTRIBUTING.md", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "engines": { + "node": ">= 0.10" + }, + "scripts": { + "test": "npm run lint && nyc --reporter=html --reporter=text mocha --require test/support/env", + "lint": "eslint lib test" + } +} diff --git a/node_modules/sweetalert2/README.md b/node_modules/sweetalert2/README.md index d3f1083e..f437edfd 100644 --- a/node_modules/sweetalert2/README.md +++ b/node_modules/sweetalert2/README.md @@ -6,50 +6,56 @@ A beautiful, responsive, customizable, accessible (WAI-ARIA) replacement
fo --- -### [Installation](https://sweetalert2.github.io/#download) | [Usage](https://sweetalert2.github.io/#usage) | [Examples](https://sweetalert2.github.io/#examples) | [Recipe gallery](https://sweetalert2.github.io/recipe-gallery/) | [Themes](https://github.com/sweetalert2/sweetalert2-themes) | [React](https://github.com/sweetalert2/sweetalert2-react-content) | [Angular](https://github.com/sweetalert2/ngx-sweetalert2) +### [Installation](https://sweetalert2.github.io/#download) | [Usage](https://sweetalert2.github.io/#usage) | [Examples](https://sweetalert2.github.io/#examples) | [Recipe gallery](https://sweetalert2.github.io/recipe-gallery/) | [Themes](https://github.com/sweetalert2/sweetalert2-themes) | [React](https://github.com/sweetalert2/sweetalert2-react-content) | [Angular](https://github.com/sweetalert2/ngx-sweetalert2) | [:heart: Donate](https://sweetalert2.github.io/#donations) --- -:moneybag: [Get $200 in free credits with DigitalOcean!](https://m.do.co/c/12907f2ba0bf) +:moneybag: [Get $100 in free credits with DigitalOcean!](https://m.do.co/c/12907f2ba0bf) --- -> [!IMPORTANT] -> As a consequence of the illegal war in Ukraine, the behavior of this repository and related npm package [sweetalert2](https://www.npmjs.com/package/sweetalert2) is different for `.ru`, `.su`, `.by`, and `.рф` domain zones. -> -> Including this software in any domain in `.ru`, `.su`, `.by`, and `.рф` domain zones will block the website navigation and play the national anthem of Ukraine. -> -> This behavior is classified as [protestware](https://snyk.io/blog/protestware-open-source-types-impact/) and this project is listed in [GitHub Advisory Database](https://github.com/advisories/GHSA-mrr8-v49w-3333) and [Snyk Vulnerability DB](https://security.snyk.io/package/npm/sweetalert2/11.5.2). - Sponsors -------- -For all questions related to sponsorship please get in touch with me via email sweetalert2@gmail.com +For all questions related to sponsorship please contact me via email limon.monte@protonmail.com - - - -

Become a sponsor

InsaDown

DLX Plugins

Tiago de Oliveira Stutz

Refermate
+

AN1
+

Fortnite Redeem
Code (Today)
+

My Betting Canada
+

Kasyno Online Blik
- +

Roboflow
-

ZezeLife
-

SERP Empire
+

W88YES
+

RushRadar: Articles,
Reviews, and Discounts
+

IgAnony

Real Spy Apps
-

Phone Tracking Apps

iStarTips
+ + + +

EvGuru EV Chargers

Best For Android

Phone Tracking Apps

FlowCrypt

My Bitcoin slots

Metal Raised Garden Bed
+ + + + + + + + +

Pure Essential Oil

TorcStark

Code Rubik

Halvin Laina

Tiago de Oliveira Stutz
NSFW Sponsors ------------- @@ -57,26 +63,10 @@ NSFW Sponsors - - - - - -

Become a NSFW sponsor

The Pink Rabbits

SexDollPartner

ChatGPT for Sex

XspaceCup - Top Male
Masturbator Brand
- - - - - - - -

Vlixa

Sexsi Toys

CheapestSexDolls

Best Blowjob Machines
- - - + - +

NakeDoll

hentai sex toys

Nake Doll

Inflatable sex doll

Sex Doll Torso

Sex Doll Torso

porn sexdoll
@@ -84,47 +74,72 @@ NSFW Sponsors
cheap sex doll

BULULU
-
VSDoll

XNDOLL
+
Sexsi Toys

sexdoll torso

anime sexdoll
- + - +

cheap sexdoll

cheap sexdoll

huge dildo

sexdoll

Cute Sex Doll

best pocket pussy

female torso sex doll
- - + + + +

female torso sex doll

male masturbator

penis pump

BestRealDoll

Cute Sex Doll

Adult Toys

Sexy Sex Doll

Cheap Sex Doll
+ + + + + + +

Sex Vibrators

Viva Awa

Sensual Dolls

BestRealDoll

SexDollTech

Rose Wives
+ + +

SexDollsOff

RealSexDoll

Your Doll

Annie's Dollhouse

Sex Doll Center
+ + + + + +

VSDoll

SexAngelbaby

The Adult Toy Finder

My Sex Toy Guide
+ + + - +

Best Blowjob Machines

STC

DoctorClimax

BSDoll

BedBible
Support and Donations --------------------- -Has SweetAlert2 helped you create a fantastic application? You can show your support via [GitHub Sponsors](https://github.com/sponsors/limonte) +Has SweetAlert2 helped you create an amazing application? You can show your support via [GitHub Sponsors](https://github.com/sponsors/limonte) + +Alternative ways for donations (PayPal, cryptocurrencies, etc.) are listed here: https://sweetalert2.github.io/#donations + +### [Hall of Donators :trophy:](DONATIONS.md) diff --git a/node_modules/sweetalert2/dist/sweetalert2.all.js b/node_modules/sweetalert2/dist/sweetalert2.all.js index 42b98318..0339e119 100644 --- a/node_modules/sweetalert2/dist/sweetalert2.all.js +++ b/node_modules/sweetalert2/dist/sweetalert2.all.js @@ -1,5 +1,5 @@ /*! -* sweetalert2 v11.10.7 +* sweetalert2 v11.6.13 * Released under the MIT License. */ (function (global, factory) { @@ -8,366 +8,72 @@ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Sweetalert2 = factory()); })(this, (function () { 'use strict'; - function _assertClassBrand(e, t, n) { - if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; - throw new TypeError("Private element is not present on this object"); - } - function _callSuper(t, o, e) { - return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); - } - function _classPrivateFieldGet2(s, a) { - return s.get(_assertClassBrand(s, a)); - } - function _classPrivateFieldSet2(s, a, r) { - return s.set(_assertClassBrand(s, a), r), r; - } - function _construct(t, e, r) { - if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); - var o = [null]; - o.push.apply(o, e); - var p = new (t.bind.apply(t, o))(); - return r && _setPrototypeOf(p, r.prototype), p; - } - function _isNativeReflectConstruct() { - try { - var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - } catch (t) {} - return (_isNativeReflectConstruct = function () { - return !!t; - })(); - } - function _iterableToArrayLimit(r, l) { - var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; - if (null != t) { - var e, - n, - i, - u, - a = [], - f = !0, - o = !1; - try { - if (i = (t = t.call(r)).next, 0 === l) { - if (Object(t) !== t) return; - f = !1; - } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); - } catch (r) { - o = !0, n = r; - } finally { - try { - if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; - } finally { - if (o) throw n; - } - } - return a; - } - } - function _toPrimitive(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r || "default"); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); - } - function _toPropertyKey(t) { - var i = _toPrimitive(t, "string"); - return "symbol" == typeof i ? i : String(i); - } - function _typeof(o) { - "@babel/helpers - typeof"; - - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { - return typeof o; - } : function (o) { - return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; - }, _typeof(o); - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; - } - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - Object.defineProperty(subClass, "prototype", { - writable: false - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - return self; - } - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - return _assertThisInitialized(self); - } - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - return object; - } - function _get() { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get.bind(); - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - if (desc.get) { - return desc.get.call(arguments.length < 3 ? target : receiver); - } - return desc.value; - }; - } - return _get.apply(this, arguments); - } - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); - } - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; - } - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - function _checkPrivateRedeclaration(obj, privateCollection) { - if (privateCollection.has(obj)) { - throw new TypeError("Cannot initialize the same private elements twice on an object"); - } - } - function _classPrivateFieldInitSpec(obj, privateMap, value) { - _checkPrivateRedeclaration(obj, privateMap); - privateMap.set(obj, value); - } + /** + * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has. + * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')` + * This is the approach that Babel will probably take to implement private methods/fields + * https://github.com/tc39/proposal-private-methods + * https://github.com/babel/babel/pull/7555 + * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module* + * then we can use that language feature. + */ - var RESTORE_FOCUS_TIMEOUT = 100; + var privateProps = { + awaitingPromise: new WeakMap(), + promise: new WeakMap(), + innerParams: new WeakMap(), + domCache: new WeakMap() + }; - /** @type {GlobalState} */ - var globalState = {}; - var focusPreviousActiveElement = function focusPreviousActiveElement() { - if (globalState.previousActiveElement instanceof HTMLElement) { - globalState.previousActiveElement.focus(); - globalState.previousActiveElement = null; - } else if (document.body) { - document.body.focus(); + const swalPrefix = 'swal2-'; + + /** + * @param {string[]} items + * @returns {object} + */ + const prefix = items => { + const result = {}; + for (const i in items) { + result[items[i]] = swalPrefix + items[i]; } + return result; }; + const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']); + const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']); + + const consolePrefix = 'SweetAlert2:'; /** - * Restore previous active (focused) element + * Filter the unique values into a new array * - * @param {boolean} returnFocus - * @returns {Promise} + * @param {Array} arr + * @returns {Array} */ - var restoreActiveElement = function restoreActiveElement(returnFocus) { - return new Promise(function (resolve) { - if (!returnFocus) { - return resolve(); + const uniqueArray = arr => { + const result = []; + for (let i = 0; i < arr.length; i++) { + if (result.indexOf(arr[i]) === -1) { + result.push(arr[i]); } - var x = window.scrollX; - var y = window.scrollY; - globalState.restoreFocusTimeout = setTimeout(function () { - focusPreviousActiveElement(); - resolve(); - }, RESTORE_FOCUS_TIMEOUT); // issues/900 - - window.scrollTo(x, y); - }); + } + return result; }; - var swalPrefix = 'swal2-'; - - /** - * @typedef - * { | 'container' - * | 'shown' - * | 'height-auto' - * | 'iosfix' - * | 'popup' - * | 'modal' - * | 'no-backdrop' - * | 'no-transition' - * | 'toast' - * | 'toast-shown' - * | 'show' - * | 'hide' - * | 'close' - * | 'title' - * | 'html-container' - * | 'actions' - * | 'confirm' - * | 'deny' - * | 'cancel' - * | 'default-outline' - * | 'footer' - * | 'icon' - * | 'icon-content' - * | 'image' - * | 'input' - * | 'file' - * | 'range' - * | 'select' - * | 'radio' - * | 'checkbox' - * | 'label' - * | 'textarea' - * | 'inputerror' - * | 'input-label' - * | 'validation-message' - * | 'progress-steps' - * | 'active-progress-step' - * | 'progress-step' - * | 'progress-step-line' - * | 'loader' - * | 'loading' - * | 'styled' - * | 'top' - * | 'top-start' - * | 'top-end' - * | 'top-left' - * | 'top-right' - * | 'center' - * | 'center-start' - * | 'center-end' - * | 'center-left' - * | 'center-right' - * | 'bottom' - * | 'bottom-start' - * | 'bottom-end' - * | 'bottom-left' - * | 'bottom-right' - * | 'grow-row' - * | 'grow-column' - * | 'grow-fullscreen' - * | 'rtl' - * | 'timer-progress-bar' - * | 'timer-progress-bar-container' - * | 'scrollbar-measure' - * | 'icon-success' - * | 'icon-warning' - * | 'icon-info' - * | 'icon-question' - * | 'icon-error' - * } SwalClass - * @typedef {Record} SwalClasses - */ - - /** - * @typedef {'success' | 'warning' | 'info' | 'question' | 'error'} SwalIcon - * @typedef {Record} SwalIcons - */ - - /** @type {SwalClass[]} */ - var classNames = ['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']; - var swalClasses = classNames.reduce(function (acc, className) { - acc[className] = swalPrefix + className; - return acc; - }, /** @type {SwalClasses} */{}); - - /** @type {SwalIcon[]} */ - var icons = ['success', 'warning', 'info', 'question', 'error']; - var iconTypes = icons.reduce(function (acc, icon) { - acc[icon] = swalPrefix + icon; - return acc; - }, /** @type {SwalIcons} */{}); - - var consolePrefix = 'SweetAlert2:'; - /** * Capitalize the first letter of a string * * @param {string} str * @returns {string} */ - var capitalizeFirstLetter = function capitalizeFirstLetter(str) { - return str.charAt(0).toUpperCase() + str.slice(1); - }; + const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1); /** * Standardize console warnings * - * @param {string | string[]} message + * @param {string | Array} message */ - var warn = function warn(message) { - console.warn("".concat(consolePrefix, " ").concat(_typeof(message) === 'object' ? message.join(' ') : message)); + const warn = message => { + console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`); }; /** @@ -375,24 +81,24 @@ * * @param {string} message */ - var error = function error(message) { - console.error("".concat(consolePrefix, " ").concat(message)); + const error = message => { + console.error(`${consolePrefix} ${message}`); }; /** * Private global state for `warnOnce` * - * @type {string[]} + * @type {Array} * @private */ - var previousWarnOnceMessages = []; + const previousWarnOnceMessages = []; /** * Show a console warning, but only if it hasn't already been shown * * @param {string} message */ - var warnOnce = function warnOnce(message) { + const warnOnce = message => { if (!previousWarnOnceMessages.includes(message)) { previousWarnOnceMessages.push(message); warn(message); @@ -405,8 +111,8 @@ * @param {string} deprecatedParam * @param {string} useInstead */ - var warnAboutDeprecation = function warnAboutDeprecation(deprecatedParam, useInstead) { - warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead.")); + const warnAboutDeprecation = (deprecatedParam, useInstead) => { + warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release. Please use "${useInstead}" instead.`); }; /** @@ -416,49 +122,39 @@ * @param {Function | any} arg * @returns {any} */ - var callIfFunction = function callIfFunction(arg) { - return typeof arg === 'function' ? arg() : arg; - }; + const callIfFunction = arg => typeof arg === 'function' ? arg() : arg; /** * @param {any} arg * @returns {boolean} */ - var hasToPromiseFn = function hasToPromiseFn(arg) { - return arg && typeof arg.toPromise === 'function'; - }; + const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function'; /** * @param {any} arg - * @returns {Promise} + * @returns {Promise} */ - var asPromise = function asPromise(arg) { - return hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg); - }; + const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg); /** * @param {any} arg * @returns {boolean} */ - var isPromise = function isPromise(arg) { - return arg && Promise.resolve(arg) === arg; - }; + const isPromise = arg => arg && Promise.resolve(arg) === arg; /** * Gets the popup container which contains the backdrop and the popup itself. * * @returns {HTMLElement | null} */ - var getContainer = function getContainer() { - return document.body.querySelector(".".concat(swalClasses.container)); - }; + const getContainer = () => document.body.querySelector(`.${swalClasses.container}`); /** * @param {string} selectorString * @returns {HTMLElement | null} */ - var elementBySelector = function elementBySelector(selectorString) { - var container = getContainer(); + const elementBySelector = selectorString => { + const container = getContainer(); return container ? container.querySelector(selectorString) : null; }; @@ -466,146 +162,121 @@ * @param {string} className * @returns {HTMLElement | null} */ - var elementByClass = function elementByClass(className) { - return elementBySelector(".".concat(className)); + const elementByClass = className => { + return elementBySelector(`.${className}`); }; /** * @returns {HTMLElement | null} */ - var getPopup = function getPopup() { - return elementByClass(swalClasses.popup); - }; + const getPopup = () => elementByClass(swalClasses.popup); /** * @returns {HTMLElement | null} */ - var getIcon = function getIcon() { - return elementByClass(swalClasses.icon); - }; + const getIcon = () => elementByClass(swalClasses.icon); /** * @returns {HTMLElement | null} */ - var getIconContent = function getIconContent() { - return elementByClass(swalClasses['icon-content']); - }; + const getIconContent = () => elementByClass(swalClasses['icon-content']); /** * @returns {HTMLElement | null} */ - var getTitle = function getTitle() { - return elementByClass(swalClasses.title); - }; + const getTitle = () => elementByClass(swalClasses.title); /** * @returns {HTMLElement | null} */ - var getHtmlContainer = function getHtmlContainer() { - return elementByClass(swalClasses['html-container']); - }; + const getHtmlContainer = () => elementByClass(swalClasses['html-container']); /** * @returns {HTMLElement | null} */ - var getImage = function getImage() { - return elementByClass(swalClasses.image); - }; + const getImage = () => elementByClass(swalClasses.image); /** * @returns {HTMLElement | null} */ - var getProgressSteps = function getProgressSteps() { - return elementByClass(swalClasses['progress-steps']); - }; + const getProgressSteps = () => elementByClass(swalClasses['progress-steps']); /** * @returns {HTMLElement | null} */ - var getValidationMessage = function getValidationMessage() { - return elementByClass(swalClasses['validation-message']); - }; + const getValidationMessage = () => elementByClass(swalClasses['validation-message']); /** - * @returns {HTMLButtonElement | null} + * @returns {HTMLElement | null} */ - var getConfirmButton = function getConfirmButton() { - return /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm)); - }; + const getConfirmButton = () => elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`); /** - * @returns {HTMLButtonElement | null} + * @returns {HTMLElement | null} */ - var getCancelButton = function getCancelButton() { - return /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel)); - }; + const getDenyButton = () => elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`); /** - * @returns {HTMLButtonElement | null} + * @returns {HTMLElement | null} */ - var getDenyButton = function getDenyButton() { - return /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny)); - }; + const getInputLabel = () => elementByClass(swalClasses['input-label']); /** * @returns {HTMLElement | null} */ - var getInputLabel = function getInputLabel() { - return elementByClass(swalClasses['input-label']); - }; + const getLoader = () => elementBySelector(`.${swalClasses.loader}`); /** * @returns {HTMLElement | null} */ - var getLoader = function getLoader() { - return elementBySelector(".".concat(swalClasses.loader)); - }; + const getCancelButton = () => elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`); /** * @returns {HTMLElement | null} */ - var getActions = function getActions() { - return elementByClass(swalClasses.actions); - }; + const getActions = () => elementByClass(swalClasses.actions); /** * @returns {HTMLElement | null} */ - var getFooter = function getFooter() { - return elementByClass(swalClasses.footer); - }; + const getFooter = () => elementByClass(swalClasses.footer); /** * @returns {HTMLElement | null} */ - var getTimerProgressBar = function getTimerProgressBar() { - return elementByClass(swalClasses['timer-progress-bar']); - }; + const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']); /** * @returns {HTMLElement | null} */ - var getCloseButton = function getCloseButton() { - return elementByClass(swalClasses.close); - }; + const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js - var focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n"; + const focusable = ` + a[href], + area[href], + input:not([disabled]), + select:not([disabled]), + textarea:not([disabled]), + button:not([disabled]), + iframe, + object, + embed, + [tabindex="0"], + [contenteditable], + audio[controls], + video[controls], + summary +`; /** * @returns {HTMLElement[]} */ - var getFocusableElements = function getFocusableElements() { - var popup = getPopup(); - if (!popup) { - return []; - } - /** @type {NodeListOf} */ - var focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])'); - var focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex) + const getFocusableElements = () => { + const focusableElementsWithTabindex = Array.from(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex - .sort(function (a, b) { - var tabindexA = parseInt(a.getAttribute('tabindex') || '0'); - var tabindexB = parseInt(b.getAttribute('tabindex') || '0'); + .sort((a, b) => { + const tabindexA = parseInt(a.getAttribute('tabindex')); + const tabindexB = parseInt(b.getAttribute('tabindex')); if (tabindexA > tabindexB) { return 1; } else if (tabindexA < tabindexB) { @@ -613,44 +284,34 @@ } return 0; }); - - /** @type {NodeListOf} */ - var otherFocusableElements = popup.querySelectorAll(focusable); - var otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(function (el) { - return el.getAttribute('tabindex') !== '-1'; - }); - return _toConsumableArray(new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))).filter(function (el) { - return isVisible$1(el); - }); + const otherFocusableElements = Array.from(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1'); + return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible$1(el)); }; /** * @returns {boolean} */ - var isModal = function isModal() { + const isModal = () => { return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']); }; /** * @returns {boolean} */ - var isToast = function isToast() { - var popup = getPopup(); - if (!popup) { - return false; - } - return hasClass(popup, swalClasses.toast); + const isToast = () => { + return getPopup() && hasClass(getPopup(), swalClasses.toast); }; /** * @returns {boolean} */ - var isLoading = function isLoading() { - var popup = getPopup(); - if (!popup) { - return false; - } - return popup.hasAttribute('data-loading'); + const isLoading = () => { + return getPopup().hasAttribute('data-loading'); + }; + + // Remember state in cases where opening and handling a modal will fiddle with it. + const states = { + previousBodyPadding: null }; /** @@ -660,17 +321,15 @@ * @param {HTMLElement} elem * @param {string} html */ - var setInnerHtml = function setInnerHtml(elem, html) { + const setInnerHtml = (elem, html) => { elem.textContent = ''; if (html) { - var parser = new DOMParser(); - var parsed = parser.parseFromString(html, "text/html"); - var head = parsed.querySelector('head'); - head && Array.from(head.childNodes).forEach(function (child) { + const parser = new DOMParser(); + const parsed = parser.parseFromString(html, `text/html`); + Array.from(parsed.querySelector('head').childNodes).forEach(child => { elem.appendChild(child); }); - var body = parsed.querySelector('body'); - body && Array.from(body.childNodes).forEach(function (child) { + Array.from(parsed.querySelector('body').childNodes).forEach(child => { if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) { elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507 } else { @@ -685,12 +344,12 @@ * @param {string} className * @returns {boolean} */ - var hasClass = function hasClass(elem, className) { + const hasClass = (elem, className) => { if (!className) { return false; } - var classList = className.split(/\s+/); - for (var i = 0; i < classList.length; i++) { + const classList = className.split(/\s+/); + for (let i = 0; i < classList.length; i++) { if (!elem.classList.contains(classList[i])) { return false; } @@ -702,9 +361,9 @@ * @param {HTMLElement} elem * @param {SweetAlertOptions} params */ - var removeCustomClasses = function removeCustomClasses(elem, params) { - Array.from(elem.classList).forEach(function (className) { - if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass || {}).includes(className)) { + const removeCustomClasses = (elem, params) => { + Array.from(elem.classList).forEach(className => { + if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) { elem.classList.remove(className); } }); @@ -715,11 +374,11 @@ * @param {SweetAlertOptions} params * @param {string} className */ - var applyCustomClass = function applyCustomClass(elem, params, className) { + const applyCustomClass = (elem, params, className) => { removeCustomClasses(elem, params); if (params.customClass && params.customClass[className]) { if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) { - warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(_typeof(params.customClass[className]), "\"")); + warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof params.customClass[className]}"`); return; } addClass(elem, params.customClass[className]); @@ -728,10 +387,10 @@ /** * @param {HTMLElement} popup - * @param {import('./renderers/renderInput').InputClass | SweetAlertInput} inputClass + * @param {import('./renderers/renderInput').InputClass} inputClass * @returns {HTMLInputElement | null} */ - var getInput$1 = function getInput(popup, inputClass) { + const getInput$1 = (popup, inputClass) => { if (!inputClass) { return null; } @@ -739,28 +398,28 @@ case 'select': case 'textarea': case 'file': - return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputClass])); + return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`); case 'checkbox': - return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.checkbox, " input")); + return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`); case 'radio': - return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:checked")) || popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:first-child")); + return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`); case 'range': - return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input")); + return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`); default: - return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input)); + return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`); } }; /** * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input */ - var focusInput = function focusInput(input) { + const focusInput = input => { input.focus(); // place cursor at end of text in text input if (input.type !== 'file') { // http://stackoverflow.com/a/2345915 - var val = input.value; + const val = input.value; input.value = ''; input.value = val; } @@ -768,19 +427,19 @@ /** * @param {HTMLElement | HTMLElement[] | null} target - * @param {string | string[] | readonly string[] | undefined} classList + * @param {string | string[] | readonly string[]} classList * @param {boolean} condition */ - var toggleClass = function toggleClass(target, classList, condition) { + const toggleClass = (target, classList, condition) => { if (!target || !classList) { return; } if (typeof classList === 'string') { classList = classList.split(/\s+/).filter(Boolean); } - classList.forEach(function (className) { + classList.forEach(className => { if (Array.isArray(target)) { - target.forEach(function (elem) { + target.forEach(elem => { condition ? elem.classList.add(className) : elem.classList.remove(className); }); } else { @@ -791,17 +450,17 @@ /** * @param {HTMLElement | HTMLElement[] | null} target - * @param {string | string[] | readonly string[] | undefined} classList + * @param {string | string[] | readonly string[]} classList */ - var addClass = function addClass(target, classList) { + const addClass = (target, classList) => { toggleClass(target, classList, true); }; /** * @param {HTMLElement | HTMLElement[] | null} target - * @param {string | string[] | readonly string[] | undefined} classList + * @param {string | string[] | readonly string[]} classList */ - var removeClass = function removeClass(target, classList) { + const removeClass = (target, classList) => { toggleClass(target, classList, false); }; @@ -812,10 +471,10 @@ * @param {string} className * @returns {HTMLElement | undefined} */ - var getDirectChildByClass = function getDirectChildByClass(elem, className) { - var children = Array.from(elem.children); - for (var i = 0; i < children.length; i++) { - var child = children[i]; + const getDirectChildByClass = (elem, className) => { + const children = Array.from(elem.children); + for (let i = 0; i < children.length; i++) { + const child = children[i]; if (child instanceof HTMLElement && hasClass(child, className)) { return child; } @@ -827,48 +486,31 @@ * @param {string} property * @param {*} value */ - var applyNumericalStyle = function applyNumericalStyle(elem, property, value) { - if (value === "".concat(parseInt(value))) { + const applyNumericalStyle = (elem, property, value) => { + if (value === `${parseInt(value)}`) { value = parseInt(value); } if (value || parseInt(value) === 0) { - elem.style.setProperty(property, typeof value === 'number' ? "".concat(value, "px") : value); + elem.style[property] = typeof value === 'number' ? `${value}px` : value; } else { elem.style.removeProperty(property); } }; /** - * @param {HTMLElement | null} elem + * @param {HTMLElement} elem * @param {string} display */ - var show = function show(elem) { - var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex'; - elem && (elem.style.display = display); - }; - - /** - * @param {HTMLElement | null} elem - */ - var hide = function hide(elem) { - elem && (elem.style.display = 'none'); + const show = function (elem) { + let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex'; + elem.style.display = display; }; /** - * @param {HTMLElement | null} elem - * @param {string} display + * @param {HTMLElement} elem */ - var showWhenInnerHtmlPresent = function showWhenInnerHtmlPresent(elem) { - var display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'block'; - if (!elem) { - return; - } - new MutationObserver(function () { - toggle(elem, elem.innerHTML, display); - }).observe(elem, { - childList: true, - subtree: true - }); + const hide = elem => { + elem.style.display = 'none'; }; /** @@ -877,11 +519,11 @@ * @param {string} property * @param {string} value */ - var setStyle = function setStyle(parent, selector, property, value) { - /** @type {HTMLElement | null} */ - var el = parent.querySelector(selector); + const setStyle = (parent, selector, property, value) => { + /** @type {HTMLElement} */ + const el = parent.querySelector(selector); if (el) { - el.style.setProperty(property, value); + el.style[property] = value; } }; @@ -890,35 +532,29 @@ * @param {any} condition * @param {string} display */ - var toggle = function toggle(elem, condition) { - var display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex'; + const toggle = function (elem, condition) { + let display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex'; condition ? show(elem, display) : hide(elem); }; /** * borrowed from jquery $(elem).is(':visible') implementation * - * @param {HTMLElement | null} elem + * @param {HTMLElement} elem * @returns {boolean} */ - var isVisible$1 = function isVisible(elem) { - return !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length)); - }; + const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length)); /** * @returns {boolean} */ - var allButtonsAreHidden = function allButtonsAreHidden() { - return !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton()); - }; + const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton()); /** * @param {HTMLElement} elem * @returns {boolean} */ - var isScrollable = function isScrollable(elem) { - return !!(elem.scrollHeight > elem.clientHeight); - }; + const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); /** * borrowed from https://stackoverflow.com/a/46352119 @@ -926,10 +562,10 @@ * @param {HTMLElement} elem * @returns {boolean} */ - var hasCssAnimation = function hasCssAnimation(elem) { - var style = window.getComputedStyle(elem); - var animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0'); - var transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0'); + const hasCssAnimation = elem => { + const style = window.getComputedStyle(elem); + const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0'); + const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0'); return animDuration > 0 || transDuration > 0; }; @@ -937,52 +573,113 @@ * @param {number} timer * @param {boolean} reset */ - var animateTimerProgressBar = function animateTimerProgressBar(timer) { - var reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var timerProgressBar = getTimerProgressBar(); - if (!timerProgressBar) { - return; - } + const animateTimerProgressBar = function (timer) { + let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + const timerProgressBar = getTimerProgressBar(); if (isVisible$1(timerProgressBar)) { if (reset) { timerProgressBar.style.transition = 'none'; timerProgressBar.style.width = '100%'; } - setTimeout(function () { - timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear"); + setTimeout(() => { + timerProgressBar.style.transition = `width ${timer / 1000}s linear`; timerProgressBar.style.width = '0%'; }, 10); } }; - var stopTimerProgressBar = function stopTimerProgressBar() { - var timerProgressBar = getTimerProgressBar(); - if (!timerProgressBar) { - return; - } - var timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width); + const stopTimerProgressBar = () => { + const timerProgressBar = getTimerProgressBar(); + const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width); timerProgressBar.style.removeProperty('transition'); timerProgressBar.style.width = '100%'; - var timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width); - var timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100; - timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%"); + const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width); + const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100; + timerProgressBar.style.removeProperty('transition'); + timerProgressBar.style.width = `${timerProgressBarPercent}%`; + }; + + const RESTORE_FOCUS_TIMEOUT = 100; + + /** @type {GlobalState} */ + const globalState = {}; + const focusPreviousActiveElement = () => { + if (globalState.previousActiveElement instanceof HTMLElement) { + globalState.previousActiveElement.focus(); + globalState.previousActiveElement = null; + } else if (document.body) { + document.body.focus(); + } }; /** - * Detect Node env + * Restore previous active (focused) element * - * @returns {boolean} + * @param {boolean} returnFocus + * @returns {Promise} */ - var isNodeEnv = function isNodeEnv() { - return typeof window === 'undefined' || typeof document === 'undefined'; + const restoreActiveElement = returnFocus => { + return new Promise(resolve => { + if (!returnFocus) { + return resolve(); + } + const x = window.scrollX; + const y = window.scrollY; + globalState.restoreFocusTimeout = setTimeout(() => { + focusPreviousActiveElement(); + resolve(); + }, RESTORE_FOCUS_TIMEOUT); // issues/900 + + window.scrollTo(x, y); + }); }; - var sweetHTML = "\n
\n \n
    \n
    \n \n

    \n
    \n \n \n
    \n \n \n
    \n \n
    \n \n \n
    \n
    \n
    \n \n \n \n
    \n
    \n
    \n
    \n
    \n
    \n").replace(/(^|\n)\s*/g, ''); + /** + * Detect Node env + * + * @returns {boolean} + */ + const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined'; + + const sweetHTML = ` +
    + +
      +
      + +

      +
      + + +
      + + +
      + +
      + + +
      +
      +
      + + + +
      +
      +
      +
      +
      +
      +`.replace(/(^|\n)\s*/g, ''); /** * @returns {boolean} */ - var resetOldContainer = function resetOldContainer() { - var oldContainer = getContainer(); + const resetOldContainer = () => { + const oldContainer = getContainer(); if (!oldContainer) { return false; } @@ -990,31 +687,31 @@ removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]); return true; }; - var resetValidationMessage$1 = function resetValidationMessage() { + const resetValidationMessage$1 = () => { globalState.currentInstance.resetValidationMessage(); }; - var addInputChangeListeners = function addInputChangeListeners() { - var popup = getPopup(); - var input = getDirectChildByClass(popup, swalClasses.input); - var file = getDirectChildByClass(popup, swalClasses.file); + const addInputChangeListeners = () => { + const popup = getPopup(); + const input = getDirectChildByClass(popup, swalClasses.input); + const file = getDirectChildByClass(popup, swalClasses.file); /** @type {HTMLInputElement} */ - var range = popup.querySelector(".".concat(swalClasses.range, " input")); + const range = popup.querySelector(`.${swalClasses.range} input`); /** @type {HTMLOutputElement} */ - var rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output")); - var select = getDirectChildByClass(popup, swalClasses.select); + const rangeOutput = popup.querySelector(`.${swalClasses.range} output`); + const select = getDirectChildByClass(popup, swalClasses.select); /** @type {HTMLInputElement} */ - var checkbox = popup.querySelector(".".concat(swalClasses.checkbox, " input")); - var textarea = getDirectChildByClass(popup, swalClasses.textarea); + const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`); + const textarea = getDirectChildByClass(popup, swalClasses.textarea); input.oninput = resetValidationMessage$1; file.onchange = resetValidationMessage$1; select.onchange = resetValidationMessage$1; checkbox.onchange = resetValidationMessage$1; textarea.oninput = resetValidationMessage$1; - range.oninput = function () { + range.oninput = () => { resetValidationMessage$1(); rangeOutput.value = range.value; }; - range.onchange = function () { + range.onchange = () => { resetValidationMessage$1(); rangeOutput.value = range.value; }; @@ -1024,15 +721,13 @@ * @param {string | HTMLElement} target * @returns {HTMLElement} */ - var getTarget = function getTarget(target) { - return typeof target === 'string' ? document.querySelector(target) : target; - }; + const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target; /** * @param {SweetAlertOptions} params */ - var setupAccessibility = function setupAccessibility(params) { - var popup = getPopup(); + const setupAccessibility = params => { + const popup = getPopup(); popup.setAttribute('role', params.toast ? 'alert' : 'dialog'); popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive'); if (!params.toast) { @@ -1043,7 +738,7 @@ /** * @param {HTMLElement} targetElement */ - var setupRTL = function setupRTL(targetElement) { + const setupRTL = targetElement => { if (window.getComputedStyle(targetElement).direction === 'rtl') { addClass(getContainer(), swalClasses.rtl); } @@ -1054,20 +749,22 @@ * * @param {SweetAlertOptions} params */ - var init = function init(params) { + const init = params => { // Clean up the old popup container if it exists - var oldContainerExisted = resetOldContainer(); + const oldContainerExisted = resetOldContainer(); + + /* istanbul ignore if */ if (isNodeEnv()) { error('SweetAlert2 requires document to initialize'); return; } - var container = document.createElement('div'); + const container = document.createElement('div'); container.className = swalClasses.container; if (oldContainerExisted) { addClass(container, swalClasses['no-transition']); } setInnerHtml(container, sweetHTML); - var targetElement = getTarget(params.target); + const targetElement = getTarget(params.target); targetElement.appendChild(container); setupAccessibility(params); setupRTL(targetElement); @@ -1078,14 +775,14 @@ * @param {HTMLElement | object | string} param * @param {HTMLElement} target */ - var parseHtmlToContainer = function parseHtmlToContainer(param, target) { + const parseHtmlToContainer = (param, target) => { // DOM element if (param instanceof HTMLElement) { target.appendChild(param); } // Object - else if (_typeof(param) === 'object') { + else if (typeof param === 'object') { handleObject(param, target); } @@ -1096,10 +793,10 @@ }; /** - * @param {any} param + * @param {object} param * @param {HTMLElement} target */ - var handleObject = function handleObject(param, target) { + const handleObject = (param, target) => { // JQuery element(s) if (param.jquery) { handleJqueryElem(target, param); @@ -1113,12 +810,12 @@ /** * @param {HTMLElement} target - * @param {any} elem + * @param {HTMLElement} elem */ - var handleJqueryElem = function handleJqueryElem(target, elem) { + const handleJqueryElem = (target, elem) => { target.textContent = ''; if (0 in elem) { - for (var i = 0; (i in elem); i++) { + for (let i = 0; (i in elem); i++) { target.appendChild(elem[i].cloneNode(true)); } } else { @@ -1129,35 +826,49 @@ /** * @returns {'webkitAnimationEnd' | 'animationend' | false} */ - var animationEndEvent = function () { + const animationEndEvent = (() => { // Prevent run in Node env + /* istanbul ignore if */ if (isNodeEnv()) { return false; } - var testEl = document.createElement('div'); - - // Chrome, Safari and Opera - if (typeof testEl.style.webkitAnimation !== 'undefined') { - return 'webkitAnimationEnd'; - } + const testEl = document.createElement('div'); + const transEndEventNames = { + WebkitAnimation: 'webkitAnimationEnd', + // Chrome, Safari and Opera + animation: 'animationend' // Standard syntax + }; - // Standard syntax - if (typeof testEl.style.animation !== 'undefined') { - return 'animationend'; + for (const i in transEndEventNames) { + if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') { + return transEndEventNames[i]; + } } return false; - }(); + })(); + + /** + * Measure scrollbar width for padding body during modal show/hide + * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js + * + * @returns {number} + */ + const measureScrollbar = () => { + const scrollDiv = document.createElement('div'); + scrollDiv.className = swalClasses['scrollbar-measure']; + document.body.appendChild(scrollDiv); + const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth; + document.body.removeChild(scrollDiv); + return scrollbarWidth; + }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderActions = function renderActions(instance, params) { - var actions = getActions(); - var loader = getLoader(); - if (!actions || !loader) { - return; - } + const renderActions = (instance, params) => { + const actions = getActions(); + const loader = getLoader(); // Actions (buttons) wrapper if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) { @@ -1173,7 +884,7 @@ renderButtons(actions, loader, params); // Loader - setInnerHtml(loader, params.loaderHtml || ''); + setInnerHtml(loader, params.loaderHtml); applyCustomClass(loader, params, 'loader'); }; @@ -1183,12 +894,9 @@ * @param {SweetAlertOptions} params */ function renderButtons(actions, loader, params) { - var confirmButton = getConfirmButton(); - var denyButton = getDenyButton(); - var cancelButton = getCancelButton(); - if (!confirmButton || !denyButton || !cancelButton) { - return; - } + const confirmButton = getConfirmButton(); + const denyButton = getDenyButton(); + const cancelButton = getCancelButton(); // Render buttons renderButton(confirmButton, 'confirm', params); @@ -1241,39 +949,36 @@ * @param {SweetAlertOptions} params */ function renderButton(button, buttonType, params) { - var buttonName = /** @type {'Confirm' | 'Deny' | 'Cancel'} */capitalizeFirstLetter(buttonType); - toggle(button, params["show".concat(buttonName, "Button")], 'inline-block'); - setInnerHtml(button, params["".concat(buttonType, "ButtonText")] || ''); // Set caption text - button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")] || ''); // ARIA label + toggle(button, params[`show${capitalizeFirstLetter(buttonType)}Button`], 'inline-block'); + setInnerHtml(button, params[`${buttonType}ButtonText`]); // Set caption text + button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`]); // ARIA label // Add buttons custom classes button.className = swalClasses[buttonType]; - applyCustomClass(button, params, "".concat(buttonType, "Button")); + applyCustomClass(button, params, `${buttonType}Button`); + addClass(button, params[`${buttonType}ButtonClass`]); } /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderCloseButton = function renderCloseButton(instance, params) { - var closeButton = getCloseButton(); - if (!closeButton) { - return; - } - setInnerHtml(closeButton, params.closeButtonHtml || ''); + const renderCloseButton = (instance, params) => { + const closeButton = getCloseButton(); + setInnerHtml(closeButton, params.closeButtonHtml); // Custom class applyCustomClass(closeButton, params, 'closeButton'); toggle(closeButton, params.showCloseButton); - closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || ''); + closeButton.setAttribute('aria-label', params.closeButtonAriaLabel); }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderContainer = function renderContainer(instance, params) { - var container = getContainer(); + const renderContainer = (instance, params) => { + const container = getContainer(); if (!container) { return; } @@ -1302,9 +1007,6 @@ * @param {SweetAlertOptions['position']} position */ function handlePositionParam(container, position) { - if (!position) { - return; - } if (position in swalClasses) { addClass(container, swalClasses[position]); } else { @@ -1318,46 +1020,29 @@ * @param {SweetAlertOptions['grow']} grow */ function handleGrowParam(container, grow) { - if (!grow) { - return; + if (grow && typeof grow === 'string') { + const growClass = `grow-${grow}`; + if (growClass in swalClasses) { + addClass(container, swalClasses[growClass]); + } } - addClass(container, swalClasses["grow-".concat(grow)]); } - /** - * This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has. - * For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')` - * This is the approach that Babel will probably take to implement private methods/fields - * https://github.com/tc39/proposal-private-methods - * https://github.com/babel/babel/pull/7555 - * Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module* - * then we can use that language feature. - */ - - var privateProps = { - innerParams: new WeakMap(), - domCache: new WeakMap() - }; + /// /** @type {InputClass[]} */ - var inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea']; + const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea']; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderInput = function renderInput(instance, params) { - var popup = getPopup(); - if (!popup) { - return; - } - var innerParams = privateProps.innerParams.get(instance); - var rerender = !innerParams || params.input !== innerParams.input; - inputClasses.forEach(function (inputClass) { - var inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]); - if (!inputContainer) { - return; - } + const renderInput = (instance, params) => { + const popup = getPopup(); + const innerParams = privateProps.innerParams.get(instance); + const rerender = !innerParams || params.input !== innerParams.input; + inputClasses.forEach(inputClass => { + const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]); // set attributes setAttributes(inputClass, params.inputAttributes); @@ -1380,33 +1065,28 @@ /** * @param {SweetAlertOptions} params */ - var showInput = function showInput(params) { - if (!params.input) { - return; - } + const showInput = params => { if (!renderInputType[params.input]) { - error("Unexpected type of input! Expected ".concat(Object.keys(renderInputType).join(' | '), ", got \"").concat(params.input, "\"")); + error(`Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "${params.input}"`); return; } - var inputContainer = getInputContainer(params.input); - var input = renderInputType[params.input](inputContainer, params); + const inputContainer = getInputContainer(params.input); + const input = renderInputType[params.input](inputContainer, params); show(inputContainer); // input autofocus - if (params.inputAutoFocus) { - setTimeout(function () { - focusInput(input); - }); - } + setTimeout(() => { + focusInput(input); + }); }; /** * @param {HTMLInputElement} input */ - var removeAttributes = function removeAttributes(input) { - for (var i = 0; i < input.attributes.length; i++) { - var attrName = input.attributes[i].name; - if (!['id', 'type', 'value', 'style'].includes(attrName)) { + const removeAttributes = input => { + for (let i = 0; i < input.attributes.length; i++) { + const attrName = input.attributes[i].name; + if (!['type', 'value', 'style'].includes(attrName)) { input.removeAttribute(attrName); } } @@ -1416,13 +1096,13 @@ * @param {InputClass} inputClass * @param {SweetAlertOptions['inputAttributes']} inputAttributes */ - var setAttributes = function setAttributes(inputClass, inputAttributes) { - var input = getInput$1(getPopup(), inputClass); + const setAttributes = (inputClass, inputAttributes) => { + const input = getInput$1(getPopup(), inputClass); if (!input) { return; } removeAttributes(input); - for (var attr in inputAttributes) { + for (const attr in inputAttributes) { input.setAttribute(attr, inputAttributes[attr]); } }; @@ -1430,9 +1110,9 @@ /** * @param {SweetAlertOptions} params */ - var setCustomClass = function setCustomClass(params) { - var inputContainer = getInputContainer(params.input); - if (_typeof(params.customClass) === 'object') { + const setCustomClass = params => { + const inputContainer = getInputContainer(params.input); + if (typeof params.customClass === 'object') { addClass(inputContainer, params.customClass.input); } }; @@ -1441,7 +1121,7 @@ * @param {HTMLInputElement | HTMLTextAreaElement} input * @param {SweetAlertOptions} params */ - var setInputPlaceholder = function setInputPlaceholder(input, params) { + const setInputPlaceholder = (input, params) => { if (!input.placeholder || params.inputPlaceholder) { input.placeholder = params.inputPlaceholder; } @@ -1452,13 +1132,14 @@ * @param {Input} prependTo * @param {SweetAlertOptions} params */ - var setInputLabel = function setInputLabel(input, prependTo, params) { + const setInputLabel = (input, prependTo, params) => { if (params.inputLabel) { - var label = document.createElement('label'); - var labelClass = swalClasses['input-label']; + input.id = swalClasses.input; + const label = document.createElement('label'); + const labelClass = swalClasses['input-label']; label.setAttribute('for', input.id); label.className = labelClass; - if (_typeof(params.customClass) === 'object') { + if (typeof params.customClass === 'object') { addClass(label, params.customClass.inputLabel); } label.innerText = params.inputLabel; @@ -1470,7 +1151,7 @@ * @param {SweetAlertOptions['input']} inputType * @returns {HTMLElement} */ - var getInputContainer = function getInputContainer(inputType) { + const getInputContainer = inputType => { return getDirectChildByClass(getPopup(), swalClasses[inputType] || swalClasses.input); }; @@ -1478,23 +1159,23 @@ * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input * @param {SweetAlertOptions['inputValue']} inputValue */ - var checkAndSetInputValue = function checkAndSetInputValue(input, inputValue) { - if (['string', 'number'].includes(_typeof(inputValue))) { - input.value = "".concat(inputValue); + const checkAndSetInputValue = (input, inputValue) => { + if (['string', 'number'].includes(typeof inputValue)) { + input.value = `${inputValue}`; } else if (!isPromise(inputValue)) { - warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(_typeof(inputValue), "\"")); + warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`); } }; - /** @type {Record Input>} */ - var renderInputType = {}; + /** @type {Record Input>} */ + const renderInputType = {}; /** * @param {HTMLInputElement} input * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ - renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = renderInputType.search = renderInputType.date = renderInputType['datetime-local'] = renderInputType.time = renderInputType.week = renderInputType.month = function (input, params) { + renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => { checkAndSetInputValue(input, params.inputValue); setInputLabel(input, input, params); setInputPlaceholder(input, params); @@ -1507,7 +1188,7 @@ * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ - renderInputType.file = function (input, params) { + renderInputType.file = (input, params) => { setInputLabel(input, input, params); setInputPlaceholder(input, params); return input; @@ -1518,9 +1199,9 @@ * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ - renderInputType.range = function (range, params) { - var rangeInput = range.querySelector('input'); - var rangeOutput = range.querySelector('output'); + renderInputType.range = (range, params) => { + const rangeInput = range.querySelector('input'); + const rangeOutput = range.querySelector('output'); checkAndSetInputValue(rangeInput, params.inputValue); rangeInput.type = params.input; checkAndSetInputValue(rangeOutput, params.inputValue); @@ -1533,10 +1214,10 @@ * @param {SweetAlertOptions} params * @returns {HTMLSelectElement} */ - renderInputType.select = function (select, params) { + renderInputType.select = (select, params) => { select.textContent = ''; if (params.inputPlaceholder) { - var placeholder = document.createElement('option'); + const placeholder = document.createElement('option'); setInnerHtml(placeholder, params.inputPlaceholder); placeholder.value = ''; placeholder.disabled = true; @@ -1551,7 +1232,7 @@ * @param {HTMLInputElement} radio * @returns {HTMLInputElement} */ - renderInputType.radio = function (radio) { + renderInputType.radio = radio => { radio.textContent = ''; return radio; }; @@ -1561,11 +1242,12 @@ * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ - renderInputType.checkbox = function (checkboxContainer, params) { - var checkbox = getInput$1(getPopup(), 'checkbox'); + renderInputType.checkbox = (checkboxContainer, params) => { + const checkbox = getInput$1(getPopup(), 'checkbox'); checkbox.value = '1'; + checkbox.id = swalClasses.checkbox; checkbox.checked = Boolean(params.inputValue); - var label = checkboxContainer.querySelector('span'); + const label = checkboxContainer.querySelector('span'); setInnerHtml(label, params.inputPlaceholder); return checkbox; }; @@ -1575,7 +1257,7 @@ * @param {SweetAlertOptions} params * @returns {HTMLTextAreaElement} */ - renderInputType.textarea = function (textarea, params) { + renderInputType.textarea = (textarea, params) => { checkAndSetInputValue(textarea, params.inputValue); setInputPlaceholder(textarea, params); setInputLabel(textarea, textarea, params); @@ -1584,25 +1266,19 @@ * @param {HTMLElement} el * @returns {number} */ - var getMargin = function getMargin(el) { - return parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); - }; + const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291 - setTimeout(function () { + setTimeout(() => { // https://github.com/sweetalert2/sweetalert2/issues/1699 if ('MutationObserver' in window) { - var initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width); - var textareaResizeHandler = function textareaResizeHandler() { - // check if texarea is still in document (i.e. popup wasn't closed in the meantime) - if (!document.body.contains(textarea)) { - return; - } - var textareaWidth = textarea.offsetWidth + getMargin(textarea); + const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width); + const textareaResizeHandler = () => { + const textareaWidth = textarea.offsetWidth + getMargin(textarea); if (textareaWidth > initialPopupWidth) { - getPopup().style.width = "".concat(textareaWidth, "px"); + getPopup().style.width = `${textareaWidth}px`; } else { - applyNumericalStyle(getPopup(), 'width', params.width); + getPopup().style.width = null; } }; new MutationObserver(textareaResizeHandler).observe(textarea, { @@ -1615,15 +1291,11 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderContent = function renderContent(instance, params) { - var htmlContainer = getHtmlContainer(); - if (!htmlContainer) { - return; - } - showWhenInnerHtmlPresent(htmlContainer); + const renderContent = (instance, params) => { + const htmlContainer = getHtmlContainer(); applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML @@ -1646,16 +1318,12 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderFooter = function renderFooter(instance, params) { - var footer = getFooter(); - if (!footer) { - return; - } - showWhenInnerHtmlPresent(footer); - toggle(footer, params.footer, 'block'); + const renderFooter = (instance, params) => { + const footer = getFooter(); + toggle(footer, params.footer); if (params.footer) { parseHtmlToContainer(params.footer, footer); } @@ -1665,15 +1333,12 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderIcon = function renderIcon(instance, params) { - var innerParams = privateProps.innerParams.get(instance); - var icon = getIcon(); - if (!icon) { - return; - } + const renderIcon = (instance, params) => { + const innerParams = privateProps.innerParams.get(instance); + const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon if (innerParams && params.icon === innerParams.icon) { @@ -1687,7 +1352,7 @@ return; } if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) { - error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\"")); + error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`); hide(icon); return; } @@ -1698,23 +1363,20 @@ applyStyles(icon, params); // Animate icon - addClass(icon, params.showClass && params.showClass.icon); + addClass(icon, params.showClass.icon); }; /** * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ - var applyStyles = function applyStyles(icon, params) { - for (var _i = 0, _Object$entries = Object.entries(iconTypes); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), - iconType = _Object$entries$_i[0], - iconClassName = _Object$entries$_i[1]; + const applyStyles = (icon, params) => { + for (const iconType in iconTypes) { if (params.icon !== iconType) { - removeClass(icon, iconClassName); + removeClass(icon, iconTypes[iconType]); } } - addClass(icon, params.icon && iconTypes[params.icon]); + addClass(icon, iconTypes[params.icon]); // Icon color setColor(icon, params); @@ -1727,31 +1389,35 @@ }; // Adjust success icon background color to match the popup background color - var adjustSuccessIconBackgroundColor = function adjustSuccessIconBackgroundColor() { - var popup = getPopup(); - if (!popup) { - return; - } - var popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color'); + const adjustSuccessIconBackgroundColor = () => { + const popup = getPopup(); + const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color'); /** @type {NodeListOf} */ - var successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix'); - for (var i = 0; i < successIconParts.length; i++) { + const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix'); + for (let i = 0; i < successIconParts.length; i++) { successIconParts[i].style.backgroundColor = popupBackgroundColor; } }; - var successIconHtml = "\n
      \n \n
      \n
      \n"; - var errorIconHtml = "\n \n \n \n \n"; + const successIconHtml = ` +
      + +
      +
      +`; + const errorIconHtml = ` + + + + +`; /** * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ - var setContent = function setContent(icon, params) { - if (!params.icon && !params.iconHtml) { - return; - } - var oldContent = icon.innerHTML; - var newContent = ''; + const setContent = (icon, params) => { + let oldContent = icon.innerHTML; + let newContent; if (params.iconHtml) { newContent = iconContent(params.iconHtml); } else if (params.icon === 'success') { @@ -1759,8 +1425,8 @@ oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor() } else if (params.icon === 'error') { newContent = errorIconHtml; - } else if (params.icon) { - var defaultIconHtml = { + } else { + const defaultIconHtml = { question: '?', warning: '!', info: 'i' @@ -1776,36 +1442,30 @@ * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ - var setColor = function setColor(icon, params) { + const setColor = (icon, params) => { if (!params.iconColor) { return; } icon.style.color = params.iconColor; icon.style.borderColor = params.iconColor; - for (var _i2 = 0, _arr = ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']; _i2 < _arr.length; _i2++) { - var sel = _arr[_i2]; - setStyle(icon, sel, 'background-color', params.iconColor); + for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) { + setStyle(icon, sel, 'backgroundColor', params.iconColor); } - setStyle(icon, '.swal2-success-ring', 'border-color', params.iconColor); + setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor); }; /** * @param {string} content * @returns {string} */ - var iconContent = function iconContent(content) { - return "
      ").concat(content, "
      "); - }; + const iconContent = content => `
      ${content}
      `; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderImage = function renderImage(instance, params) { - var image = getImage(); - if (!image) { - return; - } + const renderImage = (instance, params) => { + const image = getImage(); if (!params.imageUrl) { hide(image); return; @@ -1814,7 +1474,7 @@ // Src, alt image.setAttribute('src', params.imageUrl); - image.setAttribute('alt', params.imageAlt || ''); + image.setAttribute('alt', params.imageAlt); // Width, height applyNumericalStyle(image, 'width', params.imageWidth); @@ -1826,23 +1486,19 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderPopup = function renderPopup(instance, params) { - var container = getContainer(); - var popup = getPopup(); - if (!container || !popup) { - return; - } + const renderPopup = (instance, params) => { + const container = getContainer(); + const popup = getPopup(); // Width // https://github.com/sweetalert2/sweetalert2/issues/2170 if (params.toast) { applyNumericalStyle(container, 'width', params.width); popup.style.width = '100%'; - var loader = getLoader(); - loader && popup.insertBefore(loader, getIcon()); + popup.insertBefore(getLoader(), getIcon()); } else { applyNumericalStyle(popup, 'width', params.width); } @@ -1869,10 +1525,9 @@ * @param {HTMLElement} popup * @param {SweetAlertOptions} params */ - var addClasses$1 = function addClasses(popup, params) { - var showClass = params.showClass || {}; + const addClasses$1 = (popup, params) => { // Default Class + showClass when updating Swal.update({}) - popup.className = "".concat(swalClasses.popup, " ").concat(isVisible$1(popup) ? showClass.popup : ''); + popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? params.showClass.popup : ''}`; if (params.toast) { addClass([document.documentElement, document.body], swalClasses['toast-shown']); addClass(popup, swalClasses.toast); @@ -1888,38 +1543,33 @@ // Icon class (#1842) if (params.icon) { - addClass(popup, swalClasses["icon-".concat(params.icon)]); + addClass(popup, swalClasses[`icon-${params.icon}`]); } }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderProgressSteps = function renderProgressSteps(instance, params) { - var progressStepsContainer = getProgressSteps(); - if (!progressStepsContainer) { - return; - } - var progressSteps = params.progressSteps, - currentProgressStep = params.currentProgressStep; - if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) { + const renderProgressSteps = (instance, params) => { + const progressStepsContainer = getProgressSteps(); + if (!params.progressSteps || params.progressSteps.length === 0) { hide(progressStepsContainer); return; } show(progressStepsContainer); progressStepsContainer.textContent = ''; - if (currentProgressStep >= progressSteps.length) { + if (params.currentProgressStep >= params.progressSteps.length) { warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)'); } - progressSteps.forEach(function (step, index) { - var stepEl = createStepElement(step); + params.progressSteps.forEach((step, index) => { + const stepEl = createStepElement(step); progressStepsContainer.appendChild(stepEl); - if (index === currentProgressStep) { + if (index === params.currentProgressStep) { addClass(stepEl, swalClasses['active-progress-step']); } - if (index !== progressSteps.length - 1) { - var lineEl = createLineElement(params); + if (index !== params.progressSteps.length - 1) { + const lineEl = createLineElement(params); progressStepsContainer.appendChild(lineEl); } }); @@ -1929,8 +1579,8 @@ * @param {string} step * @returns {HTMLLIElement} */ - var createStepElement = function createStepElement(step) { - var stepEl = document.createElement('li'); + const createStepElement = step => { + const stepEl = document.createElement('li'); addClass(stepEl, swalClasses['progress-step']); setInnerHtml(stepEl, step); return stepEl; @@ -1940,8 +1590,8 @@ * @param {SweetAlertOptions} params * @returns {HTMLLIElement} */ - var createLineElement = function createLineElement(params) { - var lineEl = document.createElement('li'); + const createLineElement = params => { + const lineEl = document.createElement('li'); addClass(lineEl, swalClasses['progress-step-line']); if (params.progressStepsDistance) { applyNumericalStyle(lineEl, 'width', params.progressStepsDistance); @@ -1950,15 +1600,11 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var renderTitle = function renderTitle(instance, params) { - var title = getTitle(); - if (!title) { - return; - } - showWhenInnerHtmlPresent(title); + const renderTitle = (instance, params) => { + const title = getTitle(); toggle(title, params.title || params.titleText, 'block'); if (params.title) { parseHtmlToContainer(params.title, title); @@ -1972,10 +1618,10 @@ }; /** - * @param {SweetAlert} instance + * @param {SweetAlert2} instance * @param {SweetAlertOptions} params */ - var render = function render(instance, params) { + const render = (instance, params) => { renderPopup(instance, params); renderContainer(instance, params); renderProgressSteps(instance, params); @@ -1986,47 +1632,83 @@ renderContent(instance, params); renderActions(instance, params); renderFooter(instance, params); - var popup = getPopup(); - if (typeof params.didRender === 'function' && popup) { - params.didRender(popup); + if (typeof params.didRender === 'function') { + params.didRender(getPopup()); } }; + /** + * Hides loader and shows back the button which was hidden by .showLoading() + */ + function hideLoading() { + // do nothing if popup is closed + const innerParams = privateProps.innerParams.get(this); + if (!innerParams) { + return; + } + const domCache = privateProps.domCache.get(this); + hide(domCache.loader); + if (isToast()) { + if (innerParams.icon) { + show(getIcon()); + } + } else { + showRelatedButton(domCache); + } + removeClass([domCache.popup, domCache.actions], swalClasses.loading); + domCache.popup.removeAttribute('aria-busy'); + domCache.popup.removeAttribute('data-loading'); + domCache.confirmButton.disabled = false; + domCache.denyButton.disabled = false; + domCache.cancelButton.disabled = false; + } + const showRelatedButton = domCache => { + const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace')); + if (buttonToReplace.length) { + show(buttonToReplace[0], 'inline-block'); + } else if (allButtonsAreHidden()) { + hide(domCache.actions); + } + }; + + /** + * Gets the input DOM node, this method works with input parameter. + * + * @param {SweetAlert2} instance + * @returns {HTMLElement | null} + */ + function getInput(instance) { + const innerParams = privateProps.innerParams.get(instance || this); + const domCache = privateProps.domCache.get(instance || this); + if (!domCache) { + return null; + } + return getInput$1(domCache.popup, innerParams.input); + } + /* * Global function to determine if SweetAlert2 popup is shown */ - var isVisible = function isVisible() { + const isVisible = () => { return isVisible$1(getPopup()); }; /* * Global function to click 'Confirm' button */ - var clickConfirm = function clickConfirm() { - var _dom$getConfirmButton; - return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click(); - }; + const clickConfirm = () => getConfirmButton() && getConfirmButton().click(); /* * Global function to click 'Deny' button */ - var clickDeny = function clickDeny() { - var _dom$getDenyButton; - return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click(); - }; + const clickDeny = () => getDenyButton() && getDenyButton().click(); /* * Global function to click 'Cancel' button */ - var clickCancel = function clickCancel() { - var _dom$getCancelButton; - return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click(); - }; + const clickCancel = () => getCancelButton() && getCancelButton().click(); - /** @typedef {'cancel' | 'backdrop' | 'close' | 'esc' | 'timer'} DismissReason */ - - /** @type {Record} */ - var DismissReason = Object.freeze({ + const DismissReason = Object.freeze({ cancel: 'cancel', backdrop: 'backdrop', close: 'close', @@ -2037,7 +1719,7 @@ /** * @param {GlobalState} globalState */ - var removeKeydownHandler = function removeKeydownHandler(globalState) { + const removeKeydownHandler = globalState => { if (globalState.keydownTarget && globalState.keydownHandlerAdded) { globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture @@ -2047,16 +1729,15 @@ }; /** + * @param {SweetAlert2} instance * @param {GlobalState} globalState * @param {SweetAlertOptions} innerParams * @param {*} dismissWith */ - var addKeydownHandler = function addKeydownHandler(globalState, innerParams, dismissWith) { + const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => { removeKeydownHandler(globalState); if (!innerParams.toast) { - globalState.keydownHandler = function (e) { - return keydownHandler(innerParams, e, dismissWith); - }; + globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith); globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup(); globalState.keydownListenerCapture = innerParams.keydownListenerCapture; globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, { @@ -2067,12 +1748,12 @@ }; /** + * @param {SweetAlertOptions} innerParams * @param {number} index * @param {number} increment */ - var setFocus = function setFocus(index, increment) { - var _dom$getPopup; - var focusableElements = getFocusableElements(); + const setFocus = (innerParams, index, increment) => { + const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match if (focusableElements.length) { index = index + increment; @@ -2085,21 +1766,21 @@ } else if (index === -1) { index = focusableElements.length - 1; } - focusableElements[index].focus(); - return; + return focusableElements[index].focus(); } // no visible focusable elements, focus the popup - (_dom$getPopup = getPopup()) === null || _dom$getPopup === void 0 || _dom$getPopup.focus(); + getPopup().focus(); }; - var arrowKeysNextButton = ['ArrowRight', 'ArrowDown']; - var arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp']; + const arrowKeysNextButton = ['ArrowRight', 'ArrowDown']; + const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp']; /** - * @param {SweetAlertOptions} innerParams - * @param {KeyboardEvent} event - * @param {Function} dismissWith + * @param {SweetAlert2} instance + * @param {KeyboardEvent} e + * @param {function} dismissWith */ - var keydownHandler = function keydownHandler(innerParams, event, dismissWith) { + const keydownHandler = (instance, e, dismissWith) => { + const innerParams = privateProps.innerParams.get(instance); if (!innerParams) { return; // This instance has already been destroyed } @@ -2108,61 +1789,63 @@ // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition // https://github.com/sweetalert2/sweetalert2/issues/720 // https://github.com/sweetalert2/sweetalert2/issues/2406 - if (event.isComposing || event.keyCode === 229) { + if (e.isComposing || e.keyCode === 229) { return; } if (innerParams.stopKeydownPropagation) { - event.stopPropagation(); + e.stopPropagation(); } // ENTER - if (event.key === 'Enter') { - handleEnter(event, innerParams); + if (e.key === 'Enter') { + handleEnter(instance, e, innerParams); } // TAB - else if (event.key === 'Tab') { - handleTab(event); + else if (e.key === 'Tab') { + handleTab(e, innerParams); } // ARROWS - switch focus between buttons - else if ([].concat(arrowKeysNextButton, arrowKeysPreviousButton).includes(event.key)) { - handleArrows(event.key); + else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) { + handleArrows(e.key); } // ESC - else if (event.key === 'Escape') { - handleEsc(event, innerParams, dismissWith); + else if (e.key === 'Escape') { + handleEsc(e, innerParams, dismissWith); } }; /** - * @param {KeyboardEvent} event + * @param {SweetAlert2} instance + * @param {KeyboardEvent} e * @param {SweetAlertOptions} innerParams */ - var handleEnter = function handleEnter(event, innerParams) { + const handleEnter = (instance, e, innerParams) => { // https://github.com/sweetalert2/sweetalert2/issues/2386 if (!callIfFunction(innerParams.allowEnterKey)) { return; } - var input = getInput$1(getPopup(), innerParams.input); - if (event.target && input && event.target instanceof HTMLElement && event.target.outerHTML === input.outerHTML) { + if (e.target && instance.getInput() && e.target instanceof HTMLElement && e.target.outerHTML === instance.getInput().outerHTML) { if (['textarea', 'file'].includes(innerParams.input)) { return; // do not submit } + clickConfirm(); - event.preventDefault(); + e.preventDefault(); } }; /** - * @param {KeyboardEvent} event + * @param {KeyboardEvent} e + * @param {SweetAlertOptions} innerParams */ - var handleTab = function handleTab(event) { - var targetElement = event.target; - var focusableElements = getFocusableElements(); - var btnIndex = -1; - for (var i = 0; i < focusableElements.length; i++) { + const handleTab = (e, innerParams) => { + const targetElement = e.target; + const focusableElements = getFocusableElements(); + let btnIndex = -1; + for (let i = 0; i < focusableElements.length; i++) { if (targetElement === focusableElements[i]) { btnIndex = i; break; @@ -2170,40 +1853,31 @@ } // Cycle to the next button - if (!event.shiftKey) { - setFocus(btnIndex, 1); + if (!e.shiftKey) { + setFocus(innerParams, btnIndex, 1); } // Cycle to the prev button else { - setFocus(btnIndex, -1); + setFocus(innerParams, btnIndex, -1); } - event.stopPropagation(); - event.preventDefault(); + e.stopPropagation(); + e.preventDefault(); }; /** * @param {string} key */ - var handleArrows = function handleArrows(key) { - var actions = getActions(); - var confirmButton = getConfirmButton(); - var denyButton = getDenyButton(); - var cancelButton = getCancelButton(); - if (!actions || !confirmButton || !denyButton || !cancelButton) { - return; - } - /** @type HTMLElement[] */ - var buttons = [confirmButton, denyButton, cancelButton]; - if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) { - return; - } - var sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling'; - var buttonToFocus = document.activeElement; - if (!buttonToFocus) { + const handleArrows = key => { + const confirmButton = getConfirmButton(); + const denyButton = getDenyButton(); + const cancelButton = getCancelButton(); + if (document.activeElement instanceof HTMLElement && ![confirmButton, denyButton, cancelButton].includes(document.activeElement)) { return; } - for (var i = 0; i < actions.children.length; i++) { + const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling'; + let buttonToFocus = document.activeElement; + for (let i = 0; i < getActions().children.length; i++) { buttonToFocus = buttonToFocus[sibling]; if (!buttonToFocus) { return; @@ -2218,13 +1892,13 @@ }; /** - * @param {KeyboardEvent} event + * @param {KeyboardEvent} e * @param {SweetAlertOptions} innerParams - * @param {Function} dismissWith + * @param {function} dismissWith */ - var handleEsc = function handleEsc(event, innerParams, dismissWith) { + const handleEsc = (e, innerParams, dismissWith) => { if (callIfFunction(innerParams.allowEscapeKey)) { - event.preventDefault(); + e.preventDefault(); dismissWith(DismissReason.esc); } }; @@ -2249,24 +1923,23 @@ // elements not within the active modal dialog will not be surfaced if a user opens a screen // reader’s list of elements (headings, form controls, landmarks, etc.) in the document. - var setAriaHidden = function setAriaHidden() { - var container = getContainer(); - var bodyChildren = Array.from(document.body.children); - bodyChildren.forEach(function (el) { - if (el.contains(container)) { + const setAriaHidden = () => { + const bodyChildren = Array.from(document.body.children); + bodyChildren.forEach(el => { + if (el === getContainer() || el.contains(getContainer())) { return; } if (el.hasAttribute('aria-hidden')) { - el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden') || ''); + el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden')); } el.setAttribute('aria-hidden', 'true'); }); }; - var unsetAriaHidden = function unsetAriaHidden() { - var bodyChildren = Array.from(document.body.children); - bodyChildren.forEach(function (el) { + const unsetAriaHidden = () => { + const bodyChildren = Array.from(document.body.children); + bodyChildren.forEach(el => { if (el.hasAttribute('data-previous-aria-hidden')) { - el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden') || ''); + el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden')); el.removeAttribute('data-previous-aria-hidden'); } else { el.removeAttribute('aria-hidden'); @@ -2274,45 +1947,58 @@ }); }; - // @ts-ignore - var isSafariOrIOS = typeof window !== 'undefined' && !!window.GestureEvent; // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394 + /* istanbul ignore file */ - /** - * Fix iOS scrolling - * http://stackoverflow.com/q/39626302 - */ - var iOSfix = function iOSfix() { - if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) { - var offset = document.body.scrollTop; - document.body.style.top = "".concat(offset * -1, "px"); + // Fix iOS scrolling http://stackoverflow.com/q/39626302 + + const iOSfix = () => { + const iOS = + // @ts-ignore + /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1; + if (iOS && !hasClass(document.body, swalClasses.iosfix)) { + const offset = document.body.scrollTop; + document.body.style.top = `${offset * -1}px`; addClass(document.body, swalClasses.iosfix); lockBodyScroll(); + addBottomPaddingForTallPopups(); } }; /** - * https://github.com/sweetalert2/sweetalert2/issues/1246 + * https://github.com/sweetalert2/sweetalert2/issues/1948 */ - var lockBodyScroll = function lockBodyScroll() { - var container = getContainer(); - if (!container) { - return; + const addBottomPaddingForTallPopups = () => { + const ua = navigator.userAgent; + const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i); + const webkit = !!ua.match(/WebKit/i); + const iOSSafari = iOS && webkit && !ua.match(/CriOS/i); + if (iOSSafari) { + const bottomPanelHeight = 44; + if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) { + getContainer().style.paddingBottom = `${bottomPanelHeight}px`; + } } - /** @type {boolean} */ - var preventTouchMove; + }; + + /** + * https://github.com/sweetalert2/sweetalert2/issues/1246 + */ + const lockBodyScroll = () => { + const container = getContainer(); + let preventTouchMove; /** - * @param {TouchEvent} event + * @param {TouchEvent} e */ - container.ontouchstart = function (event) { - preventTouchMove = shouldPreventTouchMove(event); + container.ontouchstart = e => { + preventTouchMove = shouldPreventTouchMove(e); }; /** - * @param {TouchEvent} event + * @param {TouchEvent} e */ - container.ontouchmove = function (event) { + container.ontouchmove = e => { if (preventTouchMove) { - event.preventDefault(); - event.stopPropagation(); + e.preventDefault(); + e.stopPropagation(); } }; }; @@ -2321,13 +2007,9 @@ * @param {TouchEvent} event * @returns {boolean} */ - var shouldPreventTouchMove = function shouldPreventTouchMove(event) { - var target = event.target; - var container = getContainer(); - var htmlContainer = getHtmlContainer(); - if (!container || !htmlContainer) { - return false; - } + const shouldPreventTouchMove = event => { + const target = event.target; + const container = getContainer(); if (isStylus(event) || isZoom(event)) { return false; } @@ -2338,9 +2020,9 @@ // #1603 target.tagName !== 'TEXTAREA' && // #2266 - !(isScrollable(htmlContainer) && + !(isScrollable(getHtmlContainer()) && // #1944 - htmlContainer.contains(target))) { + getHtmlContainer().contains(target))) { return true; } return false; @@ -2352,7 +2034,7 @@ * @param {*} event * @returns {boolean} */ - var isStylus = function isStylus(event) { + const isStylus = event => { return event.touches && event.touches.length && event.touches[0].touchType === 'stylus'; }; @@ -2362,81 +2044,52 @@ * @param {TouchEvent} event * @returns {boolean} */ - var isZoom = function isZoom(event) { + const isZoom = event => { return event.touches && event.touches.length > 1; }; - var undoIOSfix = function undoIOSfix() { + const undoIOSfix = () => { if (hasClass(document.body, swalClasses.iosfix)) { - var offset = parseInt(document.body.style.top, 10); + const offset = parseInt(document.body.style.top, 10); removeClass(document.body, swalClasses.iosfix); document.body.style.top = ''; document.body.scrollTop = offset * -1; } }; - /** - * Measure scrollbar width for padding body during modal show/hide - * https://github.com/twbs/bootstrap/blob/master/js/src/modal.js - * - * @returns {number} - */ - var measureScrollbar = function measureScrollbar() { - var scrollDiv = document.createElement('div'); - scrollDiv.className = swalClasses['scrollbar-measure']; - document.body.appendChild(scrollDiv); - var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth; - document.body.removeChild(scrollDiv); - return scrollbarWidth; - }; - - /** - * Remember state in cases where opening and handling a modal will fiddle with it. - * @type {number | null} - */ - var previousBodyPadding = null; - - /** - * @param {string} initialBodyOverflow - */ - var replaceScrollbarWithPadding = function replaceScrollbarWithPadding(initialBodyOverflow) { + const fixScrollbar = () => { // for queues, do not do this more than once - if (previousBodyPadding !== null) { + if (states.previousBodyPadding !== null) { return; } // if the body has overflow - if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663 - ) { + if (document.body.scrollHeight > window.innerHeight) { // add padding so the content doesn't shift after removal of scrollbar - previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right')); - document.body.style.paddingRight = "".concat(previousBodyPadding + measureScrollbar(), "px"); + states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right')); + document.body.style.paddingRight = `${states.previousBodyPadding + measureScrollbar()}px`; } }; - var undoReplaceScrollbarWithPadding = function undoReplaceScrollbarWithPadding() { - if (previousBodyPadding !== null) { - document.body.style.paddingRight = "".concat(previousBodyPadding, "px"); - previousBodyPadding = null; + const undoScrollbar = () => { + if (states.previousBodyPadding !== null) { + document.body.style.paddingRight = `${states.previousBodyPadding}px`; + states.previousBodyPadding = null; } }; - /** - * @param {SweetAlert} instance - * @param {HTMLElement} container - * @param {boolean} returnFocus - * @param {Function} didClose + /* + * Instance method to close sweetAlert */ + function removePopupAndResetState(instance, container, returnFocus, didClose) { if (isToast()) { triggerDidCloseAndDispose(instance, didClose); } else { - restoreActiveElement(returnFocus).then(function () { - return triggerDidCloseAndDispose(instance, didClose); - }); + restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose)); removeKeydownHandler(globalState); } - - // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088 + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + // workaround for #2088 // for some reason removing the container in Safari will scroll the document to bottom - if (isSafariOrIOS) { + if (isSafari) { container.setAttribute('style', 'display:none !important'); container.removeAttribute('class'); container.innerHTML = ''; @@ -2444,30 +2097,20 @@ container.remove(); } if (isModal()) { - undoReplaceScrollbarWithPadding(); + undoScrollbar(); undoIOSfix(); unsetAriaHidden(); } removeBodyClasses(); } - - /** - * Remove SweetAlert2 classes from body - */ function removeBodyClasses() { removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]); } - - /** - * Instance method to close sweetAlert - * - * @param {any} resolveValue - */ function close(resolveValue) { resolveValue = prepareResolveValue(resolveValue); - var swalPromiseResolve = privateMethods.swalPromiseResolve.get(this); - var didClose = triggerClosePopup(this); - if (this.isAwaitingPromise) { + const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this); + const didClose = triggerClosePopup(this); + if (this.isAwaitingPromise()) { // A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335 if (!resolveValue.isDismissed) { handleAwaitingPromise(this); @@ -2478,54 +2121,44 @@ swalPromiseResolve(resolveValue); } } - var triggerClosePopup = function triggerClosePopup(instance) { - var popup = getPopup(); + function isAwaitingPromise() { + return !!privateProps.awaitingPromise.get(this); + } + const triggerClosePopup = instance => { + const popup = getPopup(); if (!popup) { return false; } - var innerParams = privateProps.innerParams.get(instance); + const innerParams = privateProps.innerParams.get(instance); if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) { return false; } removeClass(popup, innerParams.showClass.popup); addClass(popup, innerParams.hideClass.popup); - var backdrop = getContainer(); + const backdrop = getContainer(); removeClass(backdrop, innerParams.showClass.backdrop); addClass(backdrop, innerParams.hideClass.backdrop); handlePopupAnimation(instance, popup, innerParams); return true; }; - - /** - * @param {any} error - */ function rejectPromise(error) { - var rejectPromise = privateMethods.swalPromiseReject.get(this); + const rejectPromise = privateMethods.swalPromiseReject.get(this); handleAwaitingPromise(this); if (rejectPromise) { // Reject Swal promise rejectPromise(error); } } - - /** - * @param {SweetAlert} instance - */ - var handleAwaitingPromise = function handleAwaitingPromise(instance) { - if (instance.isAwaitingPromise) { - delete instance.isAwaitingPromise; + const handleAwaitingPromise = instance => { + if (instance.isAwaitingPromise()) { + privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335 if (!privateProps.innerParams.get(instance)) { instance._destroy(); } } }; - - /** - * @param {any} resolveValue - * @returns {SweetAlertResult} - */ - var prepareResolveValue = function prepareResolveValue(resolveValue) { + const prepareResolveValue = resolveValue => { // When user calls Swal.close() if (typeof resolveValue === 'undefined') { return { @@ -2540,16 +2173,10 @@ isDismissed: false }, resolveValue); }; - - /** - * @param {SweetAlert} instance - * @param {HTMLElement} popup - * @param {SweetAlertOptions} innerParams - */ - var handlePopupAnimation = function handlePopupAnimation(instance, popup, innerParams) { - var container = getContainer(); + const handlePopupAnimation = (instance, popup, innerParams) => { + const container = getContainer(); // If animation is supported, animate - var animationIsSupported = animationEndEvent && hasCssAnimation(popup); + const animationIsSupported = animationEndEvent && hasCssAnimation(popup); if (typeof innerParams.willClose === 'function') { innerParams.willClose(popup); } @@ -2560,18 +2187,7 @@ removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose); } }; - - /** - * @param {SweetAlert} instance - * @param {HTMLElement} popup - * @param {HTMLElement} container - * @param {boolean} returnFocus - * @param {Function} didClose - */ - var animatePopup = function animatePopup(instance, popup, container, returnFocus, didClose) { - if (!animationEndEvent) { - return; - } + const animatePopup = (instance, popup, container, returnFocus, didClose) => { globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose); popup.addEventListener(animationEndEvent, function (e) { if (e.target === popup) { @@ -2580,956 +2196,801 @@ } }); }; - - /** - * @param {SweetAlert} instance - * @param {Function} didClose - */ - var triggerDidCloseAndDispose = function triggerDidCloseAndDispose(instance, didClose) { - setTimeout(function () { + const triggerDidCloseAndDispose = (instance, didClose) => { + setTimeout(() => { if (typeof didClose === 'function') { didClose.bind(instance.params)(); } - // instance might have been destroyed already - if (instance._destroy) { - instance._destroy(); - } + instance._destroy(); }); }; /** - * Shows loader (spinner), this is useful with AJAX requests. - * By default the loader be shown instead of the "Confirm" button. - * - * @param {HTMLButtonElement | null} [buttonToReplace] + * @param {SweetAlert2} instance + * @param {string[]} buttons + * @param {boolean} disabled */ - var showLoading = function showLoading(buttonToReplace) { - var popup = getPopup(); - if (!popup) { - new Swal(); // eslint-disable-line no-new - } - popup = getPopup(); - if (!popup) { - return; - } - var loader = getLoader(); - if (isToast()) { - hide(getIcon()); - } else { - replaceButton(popup, buttonToReplace); - } - show(loader); - popup.setAttribute('data-loading', 'true'); - popup.setAttribute('aria-busy', 'true'); - popup.focus(); - }; + function setButtonsDisabled(instance, buttons, disabled) { + const domCache = privateProps.domCache.get(instance); + buttons.forEach(button => { + domCache[button].disabled = disabled; + }); + } /** - * @param {HTMLElement} popup - * @param {HTMLButtonElement | null} [buttonToReplace] + * @param {HTMLInputElement} input + * @param {boolean} disabled */ - var replaceButton = function replaceButton(popup, buttonToReplace) { - var actions = getActions(); - var loader = getLoader(); - if (!actions || !loader) { + function setInputDisabled(input, disabled) { + if (!input) { return; } - if (!buttonToReplace && isVisible$1(getConfirmButton())) { - buttonToReplace = getConfirmButton(); - } - show(actions); - if (buttonToReplace) { - hide(buttonToReplace); - loader.setAttribute('data-button-to-replace', buttonToReplace.className); - actions.insertBefore(loader, buttonToReplace); + if (input.type === 'radio') { + const radiosContainer = input.parentNode.parentNode; + const radios = radiosContainer.querySelectorAll('input'); + for (let i = 0; i < radios.length; i++) { + radios[i].disabled = disabled; + } + } else { + input.disabled = disabled; } - addClass([popup, actions], swalClasses.loading); - }; + } + function enableButtons() { + setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false); + } + function disableButtons() { + setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true); + } + function enableInput() { + setInputDisabled(this.getInput(), false); + } + function disableInput() { + setInputDisabled(this.getInput(), true); + } /** - * @param {SweetAlert} instance - * @param {SweetAlertOptions} params + * Show block with validation message + * + * @param {string} error */ - var handleInputOptionsAndValue = function handleInputOptionsAndValue(instance, params) { - if (params.input === 'select' || params.input === 'radio') { - handleInputOptions(instance, params); - } else if (['text', 'email', 'number', 'tel', 'textarea'].some(function (i) { - return i === params.input; - }) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) { - showLoading(getConfirmButton()); - handleInputValue(instance, params); + function showValidationMessage(error) { + const domCache = privateProps.domCache.get(this); + const params = privateProps.innerParams.get(this); + setInnerHtml(domCache.validationMessage, error); + domCache.validationMessage.className = swalClasses['validation-message']; + if (params.customClass && params.customClass.validationMessage) { + addClass(domCache.validationMessage, params.customClass.validationMessage); } - }; + show(domCache.validationMessage); + const input = this.getInput(); + if (input) { + input.setAttribute('aria-invalid', true); + input.setAttribute('aria-describedby', swalClasses['validation-message']); + focusInput(input); + addClass(input, swalClasses.inputerror); + } + } /** - * @param {SweetAlert} instance - * @param {SweetAlertOptions} innerParams - * @returns {SweetAlertInputValue} + * Hide block with validation message */ - var getInputValue = function getInputValue(instance, innerParams) { - var input = instance.getInput(); - if (!input) { - return null; + function resetValidationMessage() { + const domCache = privateProps.domCache.get(this); + if (domCache.validationMessage) { + hide(domCache.validationMessage); } - switch (innerParams.input) { - case 'checkbox': - return getCheckboxValue(input); - case 'radio': - return getRadioValue(input); - case 'file': - return getFileValue(input); - default: - return innerParams.inputAutoTrim ? input.value.trim() : input.value; + const input = this.getInput(); + if (input) { + input.removeAttribute('aria-invalid'); + input.removeAttribute('aria-describedby'); + removeClass(input, swalClasses.inputerror); } - }; - - /** - * @param {HTMLInputElement} input - * @returns {number} - */ - var getCheckboxValue = function getCheckboxValue(input) { - return input.checked ? 1 : 0; - }; - - /** - * @param {HTMLInputElement} input - * @returns {string | null} - */ - var getRadioValue = function getRadioValue(input) { - return input.checked ? input.value : null; - }; - - /** - * @param {HTMLInputElement} input - * @returns {FileList | File | null} - */ - var getFileValue = function getFileValue(input) { - return input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null; - }; + } - /** - * @param {SweetAlert} instance - * @param {SweetAlertOptions} params - */ - var handleInputOptions = function handleInputOptions(instance, params) { - var popup = getPopup(); - if (!popup) { - return; - } - /** - * @param {Record} inputOptions - */ - var processInputOptions = function processInputOptions(inputOptions) { - if (params.input === 'select') { - populateSelectOptions(popup, formatInputOptions(inputOptions), params); - } else if (params.input === 'radio') { - populateRadioOptions(popup, formatInputOptions(inputOptions), params); - } - }; - if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) { - showLoading(getConfirmButton()); - asPromise(params.inputOptions).then(function (inputOptions) { - instance.hideLoading(); - processInputOptions(inputOptions); - }); - } else if (_typeof(params.inputOptions) === 'object') { - processInputOptions(params.inputOptions); - } else { - error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(_typeof(params.inputOptions))); - } + const defaultParams = { + title: '', + titleText: '', + text: '', + html: '', + footer: '', + icon: undefined, + iconColor: undefined, + iconHtml: undefined, + template: undefined, + toast: false, + showClass: { + popup: 'swal2-show', + backdrop: 'swal2-backdrop-show', + icon: 'swal2-icon-show' + }, + hideClass: { + popup: 'swal2-hide', + backdrop: 'swal2-backdrop-hide', + icon: 'swal2-icon-hide' + }, + customClass: {}, + target: 'body', + color: undefined, + backdrop: true, + heightAuto: true, + allowOutsideClick: true, + allowEscapeKey: true, + allowEnterKey: true, + stopKeydownPropagation: true, + keydownListenerCapture: false, + showConfirmButton: true, + showDenyButton: false, + showCancelButton: false, + preConfirm: undefined, + preDeny: undefined, + confirmButtonText: 'OK', + confirmButtonAriaLabel: '', + confirmButtonColor: undefined, + denyButtonText: 'No', + denyButtonAriaLabel: '', + denyButtonColor: undefined, + cancelButtonText: 'Cancel', + cancelButtonAriaLabel: '', + cancelButtonColor: undefined, + buttonsStyling: true, + reverseButtons: false, + focusConfirm: true, + focusDeny: false, + focusCancel: false, + returnFocus: true, + showCloseButton: false, + closeButtonHtml: '×', + closeButtonAriaLabel: 'Close this dialog', + loaderHtml: '', + showLoaderOnConfirm: false, + showLoaderOnDeny: false, + imageUrl: undefined, + imageWidth: undefined, + imageHeight: undefined, + imageAlt: '', + timer: undefined, + timerProgressBar: false, + width: undefined, + padding: undefined, + background: undefined, + input: undefined, + inputPlaceholder: '', + inputLabel: '', + inputValue: '', + inputOptions: {}, + inputAutoTrim: true, + inputAttributes: {}, + inputValidator: undefined, + returnInputValueOnDeny: false, + validationMessage: undefined, + grow: false, + position: 'center', + progressSteps: [], + currentProgressStep: undefined, + progressStepsDistance: undefined, + willOpen: undefined, + didOpen: undefined, + didRender: undefined, + willClose: undefined, + didClose: undefined, + didDestroy: undefined, + scrollbarPadding: true }; + const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose']; + const deprecatedParams = {}; + const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture']; /** - * @param {SweetAlert} instance - * @param {SweetAlertOptions} params + * Is valid parameter + * + * @param {string} paramName + * @returns {boolean} */ - var handleInputValue = function handleInputValue(instance, params) { - var input = instance.getInput(); - if (!input) { - return; - } - hide(input); - asPromise(params.inputValue).then(function (inputValue) { - input.value = params.input === 'number' ? "".concat(parseFloat(inputValue) || 0) : "".concat(inputValue); - show(input); - input.focus(); - instance.hideLoading(); - })["catch"](function (err) { - error("Error in inputValue promise: ".concat(err)); - input.value = ''; - show(input); - input.focus(); - instance.hideLoading(); - }); + const isValidParameter = paramName => { + return Object.prototype.hasOwnProperty.call(defaultParams, paramName); }; /** - * @param {HTMLElement} popup - * @param {InputOptionFlattened[]} inputOptions - * @param {SweetAlertOptions} params - */ - function populateSelectOptions(popup, inputOptions, params) { - var select = getDirectChildByClass(popup, swalClasses.select); - if (!select) { - return; - } - /** - * @param {HTMLElement} parent - * @param {string} optionLabel - * @param {string} optionValue - */ - var renderOption = function renderOption(parent, optionLabel, optionValue) { - var option = document.createElement('option'); - option.value = optionValue; - setInnerHtml(option, optionLabel); - option.selected = isSelected(optionValue, params.inputValue); - parent.appendChild(option); - }; - inputOptions.forEach(function (inputOption) { - var optionValue = inputOption[0]; - var optionLabel = inputOption[1]; - // spec: - // https://www.w3.org/TR/html401/interact/forms.html#h-17.6 - // "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..." - // check whether this is a - if (Array.isArray(optionLabel)) { - // if it is an array, then it is an - var optgroup = document.createElement('optgroup'); - optgroup.label = optionValue; - optgroup.disabled = false; // not configurable for now - select.appendChild(optgroup); - optionLabel.forEach(function (o) { - return renderOption(optgroup, o[1], o[0]); - }); - } else { - // case of