/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/@tannin/compile/index.js": /*!***********************************************!*\ !*** ./node_modules/@tannin/compile/index.js ***! \***********************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ compile) /* harmony export */ }); /* harmony import */ var _tannin_postfix__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @tannin/postfix */ "./node_modules/@tannin/postfix/index.js"); /* harmony import */ var _tannin_evaluate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @tannin/evaluate */ "./node_modules/@tannin/evaluate/index.js"); /** * Given a C expression, returns a function which can be called to evaluate its * result. * * @example * * ```js * import compile from '@tannin/compile'; * * const evaluate = compile( 'n > 1' ); * * evaluate( { n: 2 } ); * // ⇒ true * ``` * * @param {string} expression C expression. * * @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator. */ function compile( expression ) { var terms = (0,_tannin_postfix__WEBPACK_IMPORTED_MODULE_0__["default"])( expression ); return function( variables ) { return (0,_tannin_evaluate__WEBPACK_IMPORTED_MODULE_1__["default"])( terms, variables ); }; } /***/ }), /***/ "./node_modules/@tannin/evaluate/index.js": /*!************************************************!*\ !*** ./node_modules/@tannin/evaluate/index.js ***! \************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ evaluate) /* harmony export */ }); /** * Operator callback functions. * * @type {Object} */ var OPERATORS = { '!': function( a ) { return ! a; }, '*': function( a, b ) { return a * b; }, '/': function( a, b ) { return a / b; }, '%': function( a, b ) { return a % b; }, '+': function( a, b ) { return a + b; }, '-': function( a, b ) { return a - b; }, '<': function( a, b ) { return a < b; }, '<=': function( a, b ) { return a <= b; }, '>': function( a, b ) { return a > b; }, '>=': function( a, b ) { return a >= b; }, '==': function( a, b ) { return a === b; }, '!=': function( a, b ) { return a !== b; }, '&&': function( a, b ) { return a && b; }, '||': function( a, b ) { return a || b; }, '?:': function( a, b, c ) { if ( a ) { throw b; } return c; }, }; /** * Given an array of postfix terms and operand variables, returns the result of * the postfix evaluation. * * @example * * ```js * import evaluate from '@tannin/evaluate'; * * // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +' * const terms = [ '3', '4', '5', '*', '6', '/', '+' ]; * * evaluate( terms, {} ); * // ⇒ 6.333333333333334 * ``` * * @param {string[]} postfix Postfix terms. * @param {Object} variables Operand variables. * * @return {*} Result of evaluation. */ function evaluate( postfix, variables ) { var stack = [], i, j, args, getOperatorResult, term, value; for ( i = 0; i < postfix.length; i++ ) { term = postfix[ i ]; getOperatorResult = OPERATORS[ term ]; if ( getOperatorResult ) { // Pop from stack by number of function arguments. j = getOperatorResult.length; args = Array( j ); while ( j-- ) { args[ j ] = stack.pop(); } try { value = getOperatorResult.apply( null, args ); } catch ( earlyReturn ) { return earlyReturn; } } else if ( variables.hasOwnProperty( term ) ) { value = variables[ term ]; } else { value = +term; } stack.push( value ); } return stack[ 0 ]; } /***/ }), /***/ "./node_modules/@tannin/plural-forms/index.js": /*!****************************************************!*\ !*** ./node_modules/@tannin/plural-forms/index.js ***! \****************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ pluralForms) /* harmony export */ }); /* harmony import */ var _tannin_compile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @tannin/compile */ "./node_modules/@tannin/compile/index.js"); /** * Given a C expression, returns a function which, when called with a value, * evaluates the result with the value assumed to be the "n" variable of the * expression. The result will be coerced to its numeric equivalent. * * @param {string} expression C expression. * * @return {Function} Evaluator function. */ function pluralForms( expression ) { var evaluate = (0,_tannin_compile__WEBPACK_IMPORTED_MODULE_0__["default"])( expression ); return function( n ) { return +evaluate( { n: n } ); }; } /***/ }), /***/ "./node_modules/@tannin/postfix/index.js": /*!***********************************************!*\ !*** ./node_modules/@tannin/postfix/index.js ***! \***********************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ postfix) /* harmony export */ }); var PRECEDENCE, OPENERS, TERMINATORS, PATTERN; /** * Operator precedence mapping. * * @type {Object} */ PRECEDENCE = { '(': 9, '!': 8, '*': 7, '/': 7, '%': 7, '+': 6, '-': 6, '<': 5, '<=': 5, '>': 5, '>=': 5, '==': 4, '!=': 4, '&&': 3, '||': 2, '?': 1, '?:': 1, }; /** * Characters which signal pair opening, to be terminated by terminators. * * @type {string[]} */ OPENERS = [ '(', '?' ]; /** * Characters which signal pair termination, the value an array with the * opener as its first member. The second member is an optional operator * replacement to push to the stack. * * @type {string[]} */ TERMINATORS = { ')': [ '(' ], ':': [ '?', '?:' ], }; /** * Pattern matching operators and openers. * * @type {RegExp} */ PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/; /** * Given a C expression, returns the equivalent postfix (Reverse Polish) * notation terms as an array. * * If a postfix string is desired, simply `.join( ' ' )` the result. * * @example * * ```js * import postfix from '@tannin/postfix'; * * postfix( 'n > 1' ); * // ⇒ [ 'n', '1', '>' ] * ``` * * @param {string} expression C expression. * * @return {string[]} Postfix terms. */ function postfix( expression ) { var terms = [], stack = [], match, operator, term, element; while ( ( match = expression.match( PATTERN ) ) ) { operator = match[ 0 ]; // Term is the string preceding the operator match. It may contain // whitespace, and may be empty (if operator is at beginning). term = expression.substr( 0, match.index ).trim(); if ( term ) { terms.push( term ); } while ( ( element = stack.pop() ) ) { if ( TERMINATORS[ operator ] ) { if ( TERMINATORS[ operator ][ 0 ] === element ) { // Substitution works here under assumption that because // the assigned operator will no longer be a terminator, it // will be pushed to the stack during the condition below. operator = TERMINATORS[ operator ][ 1 ] || operator; break; } } else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) { // Push to stack if either an opener or when pop reveals an // element of lower precedence. stack.push( element ); break; } // For each popped from stack, push to terms. terms.push( element ); } if ( ! TERMINATORS[ operator ] ) { stack.push( operator ); } // Slice matched fragment from expression to continue match. expression = expression.substr( match.index + operator.length ); } // Push remainder of operand, if exists, to terms. expression = expression.trim(); if ( expression ) { terms.push( expression ); } // Pop remaining items from stack into terms. return terms.concat( stack.reverse() ); } /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createAddHook.js": /*!*********************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createAddHook.js ***! \*********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _validateNamespace_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./validateNamespace.js */ "./node_modules/@wordpress/hooks/build-module/validateNamespace.js"); /* harmony import */ var _validateHookName_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./validateHookName.js */ "./node_modules/@wordpress/hooks/build-module/validateHookName.js"); /** * Internal dependencies */ /** * @callback AddHook * * Adds the hook to the appropriate hooks container. * * @param {string} hookName Name of hook to add * @param {string} namespace The unique namespace identifying the callback in the form `vendor/plugin/function`. * @param {import('.').Callback} callback Function to call when the hook is run * @param {number} [priority=10] Priority of this hook */ /** * Returns a function which, when invoked, will add a hook. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * * @return {AddHook} Function that adds a new hook. */ function createAddHook(hooks, storeKey) { return function addHook(hookName, namespace, callback, priority = 10) { const hooksStore = hooks[storeKey]; if (!(0,_validateHookName_js__WEBPACK_IMPORTED_MODULE_1__["default"])(hookName)) { return; } if (!(0,_validateNamespace_js__WEBPACK_IMPORTED_MODULE_0__["default"])(namespace)) { return; } if ('function' !== typeof callback) { // eslint-disable-next-line no-console console.error('The hook callback must be a function.'); return; } // Validate numeric priority if ('number' !== typeof priority) { // eslint-disable-next-line no-console console.error('If specified, the hook priority must be a number.'); return; } const handler = { callback, priority, namespace }; if (hooksStore[hookName]) { // Find the correct insert index of the new hook. const handlers = hooksStore[hookName].handlers; /** @type {number} */ let i; for (i = handlers.length; i > 0; i--) { if (priority >= handlers[i - 1].priority) { break; } } if (i === handlers.length) { // If append, operate via direct assignment. handlers[i] = handler; } else { // Otherwise, insert before index via splice. handlers.splice(i, 0, handler); } // We may also be currently executing this hook. If the callback // we're adding would come after the current callback, there's no // problem; otherwise we need to increase the execution index of // any other runs by 1 to account for the added element. hooksStore.__current.forEach(hookInfo => { if (hookInfo.name === hookName && hookInfo.currentIndex >= i) { hookInfo.currentIndex++; } }); } else { // This is the first hook of its type. hooksStore[hookName] = { handlers: [handler], runs: 0 }; } if (hookName !== 'hookAdded') { hooks.doAction('hookAdded', hookName, namespace, callback, priority); } }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createAddHook); //# sourceMappingURL=createAddHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createCurrentHook.js": /*!*************************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createCurrentHook.js ***! \*************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Returns a function which, when invoked, will return the name of the * currently running hook, or `null` if no hook of the given type is currently * running. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * * @return {() => string | null} Function that returns the current hook name or null. */ function createCurrentHook(hooks, storeKey) { return function currentHook() { var _hooksStore$__current; const hooksStore = hooks[storeKey]; return (_hooksStore$__current = hooksStore.__current[hooksStore.__current.length - 1]?.name) !== null && _hooksStore$__current !== void 0 ? _hooksStore$__current : null; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createCurrentHook); //# sourceMappingURL=createCurrentHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createDidHook.js": /*!*********************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createDidHook.js ***! \*********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _validateHookName_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./validateHookName.js */ "./node_modules/@wordpress/hooks/build-module/validateHookName.js"); /** * Internal dependencies */ /** * @callback DidHook * * Returns the number of times an action has been fired. * * @param {string} hookName The hook name to check. * * @return {number | undefined} The number of times the hook has run. */ /** * Returns a function which, when invoked, will return the number of times a * hook has been called. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * * @return {DidHook} Function that returns a hook's call count. */ function createDidHook(hooks, storeKey) { return function didHook(hookName) { const hooksStore = hooks[storeKey]; if (!(0,_validateHookName_js__WEBPACK_IMPORTED_MODULE_0__["default"])(hookName)) { return; } return hooksStore[hookName] && hooksStore[hookName].runs ? hooksStore[hookName].runs : 0; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createDidHook); //# sourceMappingURL=createDidHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createDoingHook.js": /*!***********************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createDoingHook.js ***! \***********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * @callback DoingHook * Returns whether a hook is currently being executed. * * @param {string} [hookName] The name of the hook to check for. If * omitted, will check for any hook being executed. * * @return {boolean} Whether the hook is being executed. */ /** * Returns a function which, when invoked, will return whether a hook is * currently being executed. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * * @return {DoingHook} Function that returns whether a hook is currently * being executed. */ function createDoingHook(hooks, storeKey) { return function doingHook(hookName) { const hooksStore = hooks[storeKey]; // If the hookName was not passed, check for any current hook. if ('undefined' === typeof hookName) { return 'undefined' !== typeof hooksStore.__current[0]; } // Return the __current hook. return hooksStore.__current[0] ? hookName === hooksStore.__current[0].name : false; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createDoingHook); //# sourceMappingURL=createDoingHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createHasHook.js": /*!*********************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createHasHook.js ***! \*********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * @callback HasHook * * Returns whether any handlers are attached for the given hookName and optional namespace. * * @param {string} hookName The name of the hook to check for. * @param {string} [namespace] Optional. The unique namespace identifying the callback * in the form `vendor/plugin/function`. * * @return {boolean} Whether there are handlers that are attached to the given hook. */ /** * Returns a function which, when invoked, will return whether any handlers are * attached to a particular hook. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * * @return {HasHook} Function that returns whether any handlers are * attached to a particular hook and optional namespace. */ function createHasHook(hooks, storeKey) { return function hasHook(hookName, namespace) { const hooksStore = hooks[storeKey]; // Use the namespace if provided. if ('undefined' !== typeof namespace) { return hookName in hooksStore && hooksStore[hookName].handlers.some(hook => hook.namespace === namespace); } return hookName in hooksStore; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createHasHook); //# sourceMappingURL=createHasHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createHooks.js": /*!*******************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createHooks.js ***! \*******************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ _Hooks: () => (/* binding */ _Hooks), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _createAddHook__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createAddHook */ "./node_modules/@wordpress/hooks/build-module/createAddHook.js"); /* harmony import */ var _createRemoveHook__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./createRemoveHook */ "./node_modules/@wordpress/hooks/build-module/createRemoveHook.js"); /* harmony import */ var _createHasHook__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./createHasHook */ "./node_modules/@wordpress/hooks/build-module/createHasHook.js"); /* harmony import */ var _createRunHook__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./createRunHook */ "./node_modules/@wordpress/hooks/build-module/createRunHook.js"); /* harmony import */ var _createCurrentHook__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./createCurrentHook */ "./node_modules/@wordpress/hooks/build-module/createCurrentHook.js"); /* harmony import */ var _createDoingHook__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./createDoingHook */ "./node_modules/@wordpress/hooks/build-module/createDoingHook.js"); /* harmony import */ var _createDidHook__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./createDidHook */ "./node_modules/@wordpress/hooks/build-module/createDidHook.js"); /** * Internal dependencies */ /** * Internal class for constructing hooks. Use `createHooks()` function * * Note, it is necessary to expose this class to make its type public. * * @private */ class _Hooks { constructor() { /** @type {import('.').Store} actions */ this.actions = Object.create(null); this.actions.__current = []; /** @type {import('.').Store} filters */ this.filters = Object.create(null); this.filters.__current = []; this.addAction = (0,_createAddHook__WEBPACK_IMPORTED_MODULE_0__["default"])(this, 'actions'); this.addFilter = (0,_createAddHook__WEBPACK_IMPORTED_MODULE_0__["default"])(this, 'filters'); this.removeAction = (0,_createRemoveHook__WEBPACK_IMPORTED_MODULE_1__["default"])(this, 'actions'); this.removeFilter = (0,_createRemoveHook__WEBPACK_IMPORTED_MODULE_1__["default"])(this, 'filters'); this.hasAction = (0,_createHasHook__WEBPACK_IMPORTED_MODULE_2__["default"])(this, 'actions'); this.hasFilter = (0,_createHasHook__WEBPACK_IMPORTED_MODULE_2__["default"])(this, 'filters'); this.removeAllActions = (0,_createRemoveHook__WEBPACK_IMPORTED_MODULE_1__["default"])(this, 'actions', true); this.removeAllFilters = (0,_createRemoveHook__WEBPACK_IMPORTED_MODULE_1__["default"])(this, 'filters', true); this.doAction = (0,_createRunHook__WEBPACK_IMPORTED_MODULE_3__["default"])(this, 'actions'); this.applyFilters = (0,_createRunHook__WEBPACK_IMPORTED_MODULE_3__["default"])(this, 'filters', true); this.currentAction = (0,_createCurrentHook__WEBPACK_IMPORTED_MODULE_4__["default"])(this, 'actions'); this.currentFilter = (0,_createCurrentHook__WEBPACK_IMPORTED_MODULE_4__["default"])(this, 'filters'); this.doingAction = (0,_createDoingHook__WEBPACK_IMPORTED_MODULE_5__["default"])(this, 'actions'); this.doingFilter = (0,_createDoingHook__WEBPACK_IMPORTED_MODULE_5__["default"])(this, 'filters'); this.didAction = (0,_createDidHook__WEBPACK_IMPORTED_MODULE_6__["default"])(this, 'actions'); this.didFilter = (0,_createDidHook__WEBPACK_IMPORTED_MODULE_6__["default"])(this, 'filters'); } } /** @typedef {_Hooks} Hooks */ /** * Returns an instance of the hooks object. * * @return {Hooks} A Hooks instance. */ function createHooks() { return new _Hooks(); } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createHooks); //# sourceMappingURL=createHooks.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createRemoveHook.js": /*!************************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createRemoveHook.js ***! \************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _validateNamespace_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./validateNamespace.js */ "./node_modules/@wordpress/hooks/build-module/validateNamespace.js"); /* harmony import */ var _validateHookName_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./validateHookName.js */ "./node_modules/@wordpress/hooks/build-module/validateHookName.js"); /** * Internal dependencies */ /** * @callback RemoveHook * Removes the specified callback (or all callbacks) from the hook with a given hookName * and namespace. * * @param {string} hookName The name of the hook to modify. * @param {string} namespace The unique namespace identifying the callback in the * form `vendor/plugin/function`. * * @return {number | undefined} The number of callbacks removed. */ /** * Returns a function which, when invoked, will remove a specified hook or all * hooks by the given name. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * @param {boolean} [removeAll=false] Whether to remove all callbacks for a hookName, * without regard to namespace. Used to create * `removeAll*` functions. * * @return {RemoveHook} Function that removes hooks. */ function createRemoveHook(hooks, storeKey, removeAll = false) { return function removeHook(hookName, namespace) { const hooksStore = hooks[storeKey]; if (!(0,_validateHookName_js__WEBPACK_IMPORTED_MODULE_1__["default"])(hookName)) { return; } if (!removeAll && !(0,_validateNamespace_js__WEBPACK_IMPORTED_MODULE_0__["default"])(namespace)) { return; } // Bail if no hooks exist by this name. if (!hooksStore[hookName]) { return 0; } let handlersRemoved = 0; if (removeAll) { handlersRemoved = hooksStore[hookName].handlers.length; hooksStore[hookName] = { runs: hooksStore[hookName].runs, handlers: [] }; } else { // Try to find the specified callback to remove. const handlers = hooksStore[hookName].handlers; for (let i = handlers.length - 1; i >= 0; i--) { if (handlers[i].namespace === namespace) { handlers.splice(i, 1); handlersRemoved++; // This callback may also be part of a hook that is // currently executing. If the callback we're removing // comes after the current callback, there's no problem; // otherwise we need to decrease the execution index of any // other runs by 1 to account for the removed element. hooksStore.__current.forEach(hookInfo => { if (hookInfo.name === hookName && hookInfo.currentIndex >= i) { hookInfo.currentIndex--; } }); } } } if (hookName !== 'hookRemoved') { hooks.doAction('hookRemoved', hookName, namespace); } return handlersRemoved; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createRemoveHook); //# sourceMappingURL=createRemoveHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/createRunHook.js": /*!*********************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/createRunHook.js ***! \*********************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Returns a function which, when invoked, will execute all callbacks * registered to a hook of the specified type, optionally returning the final * value of the call chain. * * @param {import('.').Hooks} hooks Hooks instance. * @param {import('.').StoreKey} storeKey * @param {boolean} [returnFirstArg=false] Whether each hook callback is expected to * return its first argument. * * @return {(hookName:string, ...args: unknown[]) => undefined|unknown} Function that runs hook callbacks. */ function createRunHook(hooks, storeKey, returnFirstArg = false) { return function runHooks(hookName, ...args) { const hooksStore = hooks[storeKey]; if (!hooksStore[hookName]) { hooksStore[hookName] = { handlers: [], runs: 0 }; } hooksStore[hookName].runs++; const handlers = hooksStore[hookName].handlers; // The following code is stripped from production builds. if (true) { // Handle any 'all' hooks registered. if ('hookAdded' !== hookName && hooksStore.all) { handlers.push(...hooksStore.all.handlers); } } if (!handlers || !handlers.length) { return returnFirstArg ? args[0] : undefined; } const hookInfo = { name: hookName, currentIndex: 0 }; hooksStore.__current.push(hookInfo); while (hookInfo.currentIndex < handlers.length) { const handler = handlers[hookInfo.currentIndex]; const result = handler.callback.apply(null, args); if (returnFirstArg) { args[0] = result; } hookInfo.currentIndex++; } hooksStore.__current.pop(); if (returnFirstArg) { return args[0]; } return undefined; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createRunHook); //# sourceMappingURL=createRunHook.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/index.js": /*!*************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/index.js ***! \*************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ actions: () => (/* binding */ actions), /* harmony export */ addAction: () => (/* binding */ addAction), /* harmony export */ addFilter: () => (/* binding */ addFilter), /* harmony export */ applyFilters: () => (/* binding */ applyFilters), /* harmony export */ createHooks: () => (/* reexport safe */ _createHooks__WEBPACK_IMPORTED_MODULE_0__["default"]), /* harmony export */ currentAction: () => (/* binding */ currentAction), /* harmony export */ currentFilter: () => (/* binding */ currentFilter), /* harmony export */ defaultHooks: () => (/* binding */ defaultHooks), /* harmony export */ didAction: () => (/* binding */ didAction), /* harmony export */ didFilter: () => (/* binding */ didFilter), /* harmony export */ doAction: () => (/* binding */ doAction), /* harmony export */ doingAction: () => (/* binding */ doingAction), /* harmony export */ doingFilter: () => (/* binding */ doingFilter), /* harmony export */ filters: () => (/* binding */ filters), /* harmony export */ hasAction: () => (/* binding */ hasAction), /* harmony export */ hasFilter: () => (/* binding */ hasFilter), /* harmony export */ removeAction: () => (/* binding */ removeAction), /* harmony export */ removeAllActions: () => (/* binding */ removeAllActions), /* harmony export */ removeAllFilters: () => (/* binding */ removeAllFilters), /* harmony export */ removeFilter: () => (/* binding */ removeFilter) /* harmony export */ }); /* harmony import */ var _createHooks__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createHooks */ "./node_modules/@wordpress/hooks/build-module/createHooks.js"); /** * Internal dependencies */ /** @typedef {(...args: any[])=>any} Callback */ /** * @typedef Handler * @property {Callback} callback The callback * @property {string} namespace The namespace * @property {number} priority The namespace */ /** * @typedef Hook * @property {Handler[]} handlers Array of handlers * @property {number} runs Run counter */ /** * @typedef Current * @property {string} name Hook name * @property {number} currentIndex The index */ /** * @typedef {Record & {__current: Current[]}} Store */ /** * @typedef {'actions' | 'filters'} StoreKey */ /** * @typedef {import('./createHooks').Hooks} Hooks */ const defaultHooks = (0,_createHooks__WEBPACK_IMPORTED_MODULE_0__["default"])(); const { addAction, addFilter, removeAction, removeFilter, hasAction, hasFilter, removeAllActions, removeAllFilters, doAction, applyFilters, currentAction, currentFilter, doingAction, doingFilter, didAction, didFilter, actions, filters } = defaultHooks; //# sourceMappingURL=index.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/validateHookName.js": /*!************************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/validateHookName.js ***! \************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Validate a hookName string. * * @param {string} hookName The hook name to validate. Should be a non empty string containing * only numbers, letters, dashes, periods and underscores. Also, * the hook name cannot begin with `__`. * * @return {boolean} Whether the hook name is valid. */ function validateHookName(hookName) { if ('string' !== typeof hookName || '' === hookName) { // eslint-disable-next-line no-console console.error('The hook name must be a non-empty string.'); return false; } if (/^__/.test(hookName)) { // eslint-disable-next-line no-console console.error('The hook name cannot begin with `__`.'); return false; } if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(hookName)) { // eslint-disable-next-line no-console console.error('The hook name can only contain numbers, letters, dashes, periods and underscores.'); return false; } return true; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validateHookName); //# sourceMappingURL=validateHookName.js.map /***/ }), /***/ "./node_modules/@wordpress/hooks/build-module/validateNamespace.js": /*!*************************************************************************!*\ !*** ./node_modules/@wordpress/hooks/build-module/validateNamespace.js ***! \*************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Validate a namespace string. * * @param {string} namespace The namespace to validate - should take the form * `vendor/plugin/function`. * * @return {boolean} Whether the namespace is valid. */ function validateNamespace(namespace) { if ('string' !== typeof namespace || '' === namespace) { // eslint-disable-next-line no-console console.error('The namespace must be a non-empty string.'); return false; } if (!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(namespace)) { // eslint-disable-next-line no-console console.error('The namespace can only contain numbers, letters, dashes, periods, underscores and slashes.'); return false; } return true; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validateNamespace); //# sourceMappingURL=validateNamespace.js.map /***/ }), /***/ "./node_modules/@wordpress/i18n/build-module/create-i18n.js": /*!******************************************************************!*\ !*** ./node_modules/@wordpress/i18n/build-module/create-i18n.js ***! \******************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ createI18n: () => (/* binding */ createI18n) /* harmony export */ }); /* harmony import */ var tannin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tannin */ "./node_modules/tannin/index.js"); /** * External dependencies */ /** * @typedef {Record} LocaleData */ /** * Default locale data to use for Tannin domain when not otherwise provided. * Assumes an English plural forms expression. * * @type {LocaleData} */ const DEFAULT_LOCALE_DATA = { '': { /** @param {number} n */ plural_forms(n) { return n === 1 ? 0 : 1; } } }; /* * Regular expression that matches i18n hooks like `i18n.gettext`, `i18n.ngettext`, * `i18n.gettext_domain` or `i18n.ngettext_with_context` or `i18n.has_translation`. */ const I18N_HOOK_REGEXP = /^i18n\.(n?gettext|has_translation)(_|$)/; /** * @typedef {(domain?: string) => LocaleData} GetLocaleData * * Returns locale data by domain in a * Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ */ /** * @typedef {(data?: LocaleData, domain?: string) => void} SetLocaleData * * Merges locale data into the Tannin instance by domain. Note that this * function will overwrite the domain configuration. Accepts data in a * Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ */ /** * @typedef {(data?: LocaleData, domain?: string) => void} AddLocaleData * * Merges locale data into the Tannin instance by domain. Note that this * function will also merge the domain configuration. Accepts data in a * Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ */ /** * @typedef {(data?: LocaleData, domain?: string) => void} ResetLocaleData * * Resets all current Tannin instance locale data and sets the specified * locale data for the domain. Accepts data in a Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ */ /** @typedef {() => void} SubscribeCallback */ /** @typedef {() => void} UnsubscribeCallback */ /** * @typedef {(callback: SubscribeCallback) => UnsubscribeCallback} Subscribe * * Subscribes to changes of locale data */ /** * @typedef {(domain?: string) => string} GetFilterDomain * Retrieve the domain to use when calling domain-specific filters. */ /** * @typedef {(text: string, domain?: string) => string} __ * * Retrieve the translation of text. * * @see https://developer.wordpress.org/reference/functions/__/ */ /** * @typedef {(text: string, context: string, domain?: string) => string} _x * * Retrieve translated string with gettext context. * * @see https://developer.wordpress.org/reference/functions/_x/ */ /** * @typedef {(single: string, plural: string, number: number, domain?: string) => string} _n * * Translates and retrieves the singular or plural form based on the supplied * number. * * @see https://developer.wordpress.org/reference/functions/_n/ */ /** * @typedef {(single: string, plural: string, number: number, context: string, domain?: string) => string} _nx * * Translates and retrieves the singular or plural form based on the supplied * number, with gettext context. * * @see https://developer.wordpress.org/reference/functions/_nx/ */ /** * @typedef {() => boolean} IsRtl * * Check if current locale is RTL. * * **RTL (Right To Left)** is a locale property indicating that text is written from right to left. * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages, * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`). */ /** * @typedef {(single: string, context?: string, domain?: string) => boolean} HasTranslation * * Check if there is a translation for a given string in singular form. */ /** @typedef {import('@wordpress/hooks').Hooks} Hooks */ /** * An i18n instance * * @typedef I18n * @property {GetLocaleData} getLocaleData Returns locale data by domain in a Jed-formatted JSON object shape. * @property {SetLocaleData} setLocaleData Merges locale data into the Tannin instance by domain. Note that this * function will overwrite the domain configuration. Accepts data in a * Jed-formatted JSON object shape. * @property {AddLocaleData} addLocaleData Merges locale data into the Tannin instance by domain. Note that this * function will also merge the domain configuration. Accepts data in a * Jed-formatted JSON object shape. * @property {ResetLocaleData} resetLocaleData Resets all current Tannin instance locale data and sets the specified * locale data for the domain. Accepts data in a Jed-formatted JSON object shape. * @property {Subscribe} subscribe Subscribes to changes of Tannin locale data. * @property {__} __ Retrieve the translation of text. * @property {_x} _x Retrieve translated string with gettext context. * @property {_n} _n Translates and retrieves the singular or plural form based on the supplied * number. * @property {_nx} _nx Translates and retrieves the singular or plural form based on the supplied * number, with gettext context. * @property {IsRtl} isRTL Check if current locale is RTL. * @property {HasTranslation} hasTranslation Check if there is a translation for a given string. */ /** * Create an i18n instance * * @param {LocaleData} [initialData] Locale data configuration. * @param {string} [initialDomain] Domain for which configuration applies. * @param {Hooks} [hooks] Hooks implementation. * * @return {I18n} I18n instance. */ const createI18n = (initialData, initialDomain, hooks) => { /** * The underlying instance of Tannin to which exported functions interface. * * @type {Tannin} */ const tannin = new tannin__WEBPACK_IMPORTED_MODULE_0__["default"]({}); const listeners = new Set(); const notifyListeners = () => { listeners.forEach(listener => listener()); }; /** * Subscribe to changes of locale data. * * @param {SubscribeCallback} callback Subscription callback. * @return {UnsubscribeCallback} Unsubscribe callback. */ const subscribe = callback => { listeners.add(callback); return () => listeners.delete(callback); }; /** @type {GetLocaleData} */ const getLocaleData = (domain = 'default') => tannin.data[domain]; /** * @param {LocaleData} [data] * @param {string} [domain] */ const doSetLocaleData = (data, domain = 'default') => { tannin.data[domain] = { ...tannin.data[domain], ...data }; // Populate default domain configuration (supported locale date which omits // a plural forms expression). tannin.data[domain][''] = { ...DEFAULT_LOCALE_DATA[''], ...tannin.data[domain]?.[''] }; // Clean up cached plural forms functions cache as it might be updated. delete tannin.pluralForms[domain]; }; /** @type {SetLocaleData} */ const setLocaleData = (data, domain) => { doSetLocaleData(data, domain); notifyListeners(); }; /** @type {AddLocaleData} */ const addLocaleData = (data, domain = 'default') => { tannin.data[domain] = { ...tannin.data[domain], ...data, // Populate default domain configuration (supported locale date which omits // a plural forms expression). '': { ...DEFAULT_LOCALE_DATA[''], ...tannin.data[domain]?.[''], ...data?.[''] } }; // Clean up cached plural forms functions cache as it might be updated. delete tannin.pluralForms[domain]; notifyListeners(); }; /** @type {ResetLocaleData} */ const resetLocaleData = (data, domain) => { // Reset all current Tannin locale data. tannin.data = {}; // Reset cached plural forms functions cache. tannin.pluralForms = {}; setLocaleData(data, domain); }; /** * Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not * otherwise previously assigned. * * @param {string|undefined} domain Domain to retrieve the translated text. * @param {string|undefined} context Context information for the translators. * @param {string} single Text to translate if non-plural. Used as * fallback return value on a caught error. * @param {string} [plural] The text to be used if the number is * plural. * @param {number} [number] The number to compare against to use * either the singular or plural form. * * @return {string} The translated string. */ const dcnpgettext = (domain = 'default', context, single, plural, number) => { if (!tannin.data[domain]) { // Use `doSetLocaleData` to set silently, without notifying listeners. doSetLocaleData(undefined, domain); } return tannin.dcnpgettext(domain, context, single, plural, number); }; /** @type {GetFilterDomain} */ const getFilterDomain = (domain = 'default') => domain; /** @type {__} */ const __ = (text, domain) => { let translation = dcnpgettext(domain, undefined, text); if (!hooks) { return translation; } /** * Filters text with its translation. * * @param {string} translation Translated text. * @param {string} text Text to translate. * @param {string} domain Text domain. Unique identifier for retrieving translated strings. */ translation = /** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.gettext', translation, text, domain); return (/** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.gettext_' + getFilterDomain(domain), translation, text, domain) ); }; /** @type {_x} */ const _x = (text, context, domain) => { let translation = dcnpgettext(domain, context, text); if (!hooks) { return translation; } /** * Filters text with its translation based on context information. * * @param {string} translation Translated text. * @param {string} text Text to translate. * @param {string} context Context information for the translators. * @param {string} domain Text domain. Unique identifier for retrieving translated strings. */ translation = /** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.gettext_with_context', translation, text, context, domain); return (/** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.gettext_with_context_' + getFilterDomain(domain), translation, text, context, domain) ); }; /** @type {_n} */ const _n = (single, plural, number, domain) => { let translation = dcnpgettext(domain, undefined, single, plural, number); if (!hooks) { return translation; } /** * Filters the singular or plural form of a string. * * @param {string} translation Translated text. * @param {string} single The text to be used if the number is singular. * @param {string} plural The text to be used if the number is plural. * @param {string} number The number to compare against to use either the singular or plural form. * @param {string} domain Text domain. Unique identifier for retrieving translated strings. */ translation = /** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.ngettext', translation, single, plural, number, domain); return (/** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.ngettext_' + getFilterDomain(domain), translation, single, plural, number, domain) ); }; /** @type {_nx} */ const _nx = (single, plural, number, context, domain) => { let translation = dcnpgettext(domain, context, single, plural, number); if (!hooks) { return translation; } /** * Filters the singular or plural form of a string with gettext context. * * @param {string} translation Translated text. * @param {string} single The text to be used if the number is singular. * @param {string} plural The text to be used if the number is plural. * @param {string} number The number to compare against to use either the singular or plural form. * @param {string} context Context information for the translators. * @param {string} domain Text domain. Unique identifier for retrieving translated strings. */ translation = /** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.ngettext_with_context', translation, single, plural, number, context, domain); return (/** @type {string} */ /** @type {*} */hooks.applyFilters('i18n.ngettext_with_context_' + getFilterDomain(domain), translation, single, plural, number, context, domain) ); }; /** @type {IsRtl} */ const isRTL = () => { return 'rtl' === _x('ltr', 'text direction'); }; /** @type {HasTranslation} */ const hasTranslation = (single, context, domain) => { const key = context ? context + '\u0004' + single : single; let result = !!tannin.data?.[domain !== null && domain !== void 0 ? domain : 'default']?.[key]; if (hooks) { /** * Filters the presence of a translation in the locale data. * * @param {boolean} hasTranslation Whether the translation is present or not.. * @param {string} single The singular form of the translated text (used as key in locale data) * @param {string} context Context information for the translators. * @param {string} domain Text domain. Unique identifier for retrieving translated strings. */ result = /** @type { boolean } */ /** @type {*} */hooks.applyFilters('i18n.has_translation', result, single, context, domain); result = /** @type { boolean } */ /** @type {*} */hooks.applyFilters('i18n.has_translation_' + getFilterDomain(domain), result, single, context, domain); } return result; }; if (initialData) { setLocaleData(initialData, initialDomain); } if (hooks) { /** * @param {string} hookName */ const onHookAddedOrRemoved = hookName => { if (I18N_HOOK_REGEXP.test(hookName)) { notifyListeners(); } }; hooks.addAction('hookAdded', 'core/i18n', onHookAddedOrRemoved); hooks.addAction('hookRemoved', 'core/i18n', onHookAddedOrRemoved); } return { getLocaleData, setLocaleData, addLocaleData, resetLocaleData, subscribe, __, _x, _n, _nx, isRTL, hasTranslation }; }; //# sourceMappingURL=create-i18n.js.map /***/ }), /***/ "./node_modules/@wordpress/i18n/build-module/default-i18n.js": /*!*******************************************************************!*\ !*** ./node_modules/@wordpress/i18n/build-module/default-i18n.js ***! \*******************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ __: () => (/* binding */ __), /* harmony export */ _n: () => (/* binding */ _n), /* harmony export */ _nx: () => (/* binding */ _nx), /* harmony export */ _x: () => (/* binding */ _x), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), /* harmony export */ getLocaleData: () => (/* binding */ getLocaleData), /* harmony export */ hasTranslation: () => (/* binding */ hasTranslation), /* harmony export */ isRTL: () => (/* binding */ isRTL), /* harmony export */ resetLocaleData: () => (/* binding */ resetLocaleData), /* harmony export */ setLocaleData: () => (/* binding */ setLocaleData), /* harmony export */ subscribe: () => (/* binding */ subscribe) /* harmony export */ }); /* harmony import */ var _create_i18n__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./create-i18n */ "./node_modules/@wordpress/i18n/build-module/create-i18n.js"); /* harmony import */ var _wordpress_hooks__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @wordpress/hooks */ "./node_modules/@wordpress/hooks/build-module/index.js"); /** * Internal dependencies */ /** * WordPress dependencies */ const i18n = (0,_create_i18n__WEBPACK_IMPORTED_MODULE_0__.createI18n)(undefined, undefined, _wordpress_hooks__WEBPACK_IMPORTED_MODULE_1__.defaultHooks); /** * Default, singleton instance of `I18n`. */ /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (i18n); /* * Comments in this file are duplicated from ./i18n due to * https://github.com/WordPress/gutenberg/pull/20318#issuecomment-590837722 */ /** * @typedef {import('./create-i18n').LocaleData} LocaleData * @typedef {import('./create-i18n').SubscribeCallback} SubscribeCallback * @typedef {import('./create-i18n').UnsubscribeCallback} UnsubscribeCallback */ /** * Returns locale data by domain in a Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ * * @param {string} [domain] Domain for which to get the data. * @return {LocaleData} Locale data. */ const getLocaleData = i18n.getLocaleData.bind(i18n); /** * Merges locale data into the Tannin instance by domain. Accepts data in a * Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ * * @param {LocaleData} [data] Locale data configuration. * @param {string} [domain] Domain for which configuration applies. */ const setLocaleData = i18n.setLocaleData.bind(i18n); /** * Resets all current Tannin instance locale data and sets the specified * locale data for the domain. Accepts data in a Jed-formatted JSON object shape. * * @see http://messageformat.github.io/Jed/ * * @param {LocaleData} [data] Locale data configuration. * @param {string} [domain] Domain for which configuration applies. */ const resetLocaleData = i18n.resetLocaleData.bind(i18n); /** * Subscribes to changes of locale data * * @param {SubscribeCallback} callback Subscription callback * @return {UnsubscribeCallback} Unsubscribe callback */ const subscribe = i18n.subscribe.bind(i18n); /** * Retrieve the translation of text. * * @see https://developer.wordpress.org/reference/functions/__/ * * @param {string} text Text to translate. * @param {string} [domain] Domain to retrieve the translated text. * * @return {string} Translated text. */ const __ = i18n.__.bind(i18n); /** * Retrieve translated string with gettext context. * * @see https://developer.wordpress.org/reference/functions/_x/ * * @param {string} text Text to translate. * @param {string} context Context information for the translators. * @param {string} [domain] Domain to retrieve the translated text. * * @return {string} Translated context string without pipe. */ const _x = i18n._x.bind(i18n); /** * Translates and retrieves the singular or plural form based on the supplied * number. * * @see https://developer.wordpress.org/reference/functions/_n/ * * @param {string} single The text to be used if the number is singular. * @param {string} plural The text to be used if the number is plural. * @param {number} number The number to compare against to use either the * singular or plural form. * @param {string} [domain] Domain to retrieve the translated text. * * @return {string} The translated singular or plural form. */ const _n = i18n._n.bind(i18n); /** * Translates and retrieves the singular or plural form based on the supplied * number, with gettext context. * * @see https://developer.wordpress.org/reference/functions/_nx/ * * @param {string} single The text to be used if the number is singular. * @param {string} plural The text to be used if the number is plural. * @param {number} number The number to compare against to use either the * singular or plural form. * @param {string} context Context information for the translators. * @param {string} [domain] Domain to retrieve the translated text. * * @return {string} The translated singular or plural form. */ const _nx = i18n._nx.bind(i18n); /** * Check if current locale is RTL. * * **RTL (Right To Left)** is a locale property indicating that text is written from right to left. * For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common * language written RTL. The opposite of RTL, LTR (Left To Right) is used in other languages, * including English (`en`, `en-US`, `en-GB`, etc.), Spanish (`es`), and French (`fr`). * * @return {boolean} Whether locale is RTL. */ const isRTL = i18n.isRTL.bind(i18n); /** * Check if there is a translation for a given string (in singular form). * * @param {string} single Singular form of the string to look up. * @param {string} [context] Context information for the translators. * @param {string} [domain] Domain to retrieve the translated text. * @return {boolean} Whether the translation exists or not. */ const hasTranslation = i18n.hasTranslation.bind(i18n); //# sourceMappingURL=default-i18n.js.map /***/ }), /***/ "./node_modules/@wordpress/i18n/build-module/index.js": /*!************************************************************!*\ !*** ./node_modules/@wordpress/i18n/build-module/index.js ***! \************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ __: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.__), /* harmony export */ _n: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__._n), /* harmony export */ _nx: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__._nx), /* harmony export */ _x: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__._x), /* harmony export */ createI18n: () => (/* reexport safe */ _create_i18n__WEBPACK_IMPORTED_MODULE_1__.createI18n), /* harmony export */ defaultI18n: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__["default"]), /* harmony export */ getLocaleData: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.getLocaleData), /* harmony export */ hasTranslation: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.hasTranslation), /* harmony export */ isRTL: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.isRTL), /* harmony export */ resetLocaleData: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.resetLocaleData), /* harmony export */ setLocaleData: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.setLocaleData), /* harmony export */ sprintf: () => (/* reexport safe */ _sprintf__WEBPACK_IMPORTED_MODULE_0__.sprintf), /* harmony export */ subscribe: () => (/* reexport safe */ _default_i18n__WEBPACK_IMPORTED_MODULE_2__.subscribe) /* harmony export */ }); /* harmony import */ var _sprintf__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sprintf */ "./node_modules/@wordpress/i18n/build-module/sprintf.js"); /* harmony import */ var _create_i18n__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./create-i18n */ "./node_modules/@wordpress/i18n/build-module/create-i18n.js"); /* harmony import */ var _default_i18n__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./default-i18n */ "./node_modules/@wordpress/i18n/build-module/default-i18n.js"); //# sourceMappingURL=index.js.map /***/ }), /***/ "./node_modules/@wordpress/i18n/build-module/sprintf.js": /*!**************************************************************!*\ !*** ./node_modules/@wordpress/i18n/build-module/sprintf.js ***! \**************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ sprintf: () => (/* binding */ sprintf) /* harmony export */ }); /* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! memize */ "./node_modules/memize/dist/index.js"); /* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sprintf-js */ "./node_modules/sprintf-js/src/sprintf.js"); /* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sprintf_js__WEBPACK_IMPORTED_MODULE_1__); /** * External dependencies */ /** * Log to console, once per message; or more precisely, per referentially equal * argument set. Because Jed throws errors, we log these to the console instead * to avoid crashing the application. * * @param {...*} args Arguments to pass to `console.error` */ const logErrorOnce = (0,memize__WEBPACK_IMPORTED_MODULE_0__["default"])(console.error); // eslint-disable-line no-console /** * Returns a formatted string. If an error occurs in applying the format, the * original format string is returned. * * @param {string} format The format of the string to generate. * @param {...*} args Arguments to apply to the format. * * @see https://www.npmjs.com/package/sprintf-js * * @return {string} The formatted string. */ function sprintf(format, ...args) { try { return sprintf_js__WEBPACK_IMPORTED_MODULE_1___default().sprintf(format, ...args); } catch (error) { if (error instanceof Error) { logErrorOnce('sprintf error: \n\n' + error.toString()); } return format; } } //# sourceMappingURL=sprintf.js.map /***/ }), /***/ "./node_modules/sprintf-js/src/sprintf.js": /*!************************************************!*\ !*** ./node_modules/sprintf-js/src/sprintf.js ***! \************************************************/ /***/ ((module, exports, __webpack_require__) => { var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */ !function() { 'use strict' var re = { not_string: /[^s]/, not_bool: /[^t]/, not_type: /[^T]/, not_primitive: /[^v]/, number: /[diefg]/, numeric_arg: /[bcdiefguxX]/, json: /[j]/, not_json: /[^j]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, sign: /^[+-]/ } function sprintf(key) { // `arguments` is not an array, but should be fine for this call return sprintf_format(sprintf_parse(key), arguments) } function vsprintf(fmt, argv) { return sprintf.apply(null, [fmt].concat(argv || [])) } function sprintf_format(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign for (i = 0; i < tree_length; i++) { if (typeof parse_tree[i] === 'string') { output += parse_tree[i] } else if (typeof parse_tree[i] === 'object') { ph = parse_tree[i] // convenience purposes only if (ph.keys) { // keyword argument arg = argv[cursor] for (k = 0; k < ph.keys.length; k++) { if (arg == undefined) { throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1])) } arg = arg[ph.keys[k]] } } else if (ph.param_no) { // positional argument (explicit) arg = argv[ph.param_no] } else { // positional argument (implicit) arg = argv[cursor++] } if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) { arg = arg() } if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) { throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) } if (re.number.test(ph.type)) { is_positive = arg >= 0 } switch (ph.type) { case 'b': arg = parseInt(arg, 10).toString(2) break case 'c': arg = String.fromCharCode(parseInt(arg, 10)) break case 'd': case 'i': arg = parseInt(arg, 10) break case 'j': arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0) break case 'e': arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential() break case 'f': arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg) break case 'g': arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg) break case 'o': arg = (parseInt(arg, 10) >>> 0).toString(8) break case 's': arg = String(arg) arg = (ph.precision ? arg.substring(0, ph.precision) : arg) break case 't': arg = String(!!arg) arg = (ph.precision ? arg.substring(0, ph.precision) : arg) break case 'T': arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() arg = (ph.precision ? arg.substring(0, ph.precision) : arg) break case 'u': arg = parseInt(arg, 10) >>> 0 break case 'v': arg = arg.valueOf() arg = (ph.precision ? arg.substring(0, ph.precision) : arg) break case 'x': arg = (parseInt(arg, 10) >>> 0).toString(16) break case 'X': arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() break } if (re.json.test(ph.type)) { output += arg } else { if (re.number.test(ph.type) && (!is_positive || ph.sign)) { sign = is_positive ? '+' : '-' arg = arg.toString().replace(re.sign, '') } else { sign = '' } pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ' pad_length = ph.width - (sign + arg).length pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) } } } return output } var sprintf_cache = Object.create(null) function sprintf_parse(fmt) { if (sprintf_cache[fmt]) { return sprintf_cache[fmt] } var _fmt = fmt, match, parse_tree = [], arg_names = 0 while (_fmt) { if ((match = re.text.exec(_fmt)) !== null) { parse_tree.push(match[0]) } else if ((match = re.modulo.exec(_fmt)) !== null) { parse_tree.push('%') } else if ((match = re.placeholder.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1 var field_list = [], replacement_field = match[2], field_match = [] if ((field_match = re.key.exec(replacement_field)) !== null) { field_list.push(field_match[1]) while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = re.key_access.exec(replacement_field)) !== null) { field_list.push(field_match[1]) } else if ((field_match = re.index_access.exec(replacement_field)) !== null) { field_list.push(field_match[1]) } else { throw new SyntaxError('[sprintf] failed to parse named argument key') } } } else { throw new SyntaxError('[sprintf] failed to parse named argument key') } match[2] = field_list } else { arg_names |= 2 } if (arg_names === 3) { throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') } parse_tree.push( { placeholder: match[0], param_no: match[1], keys: match[2], sign: match[3], pad_char: match[4], align: match[5], width: match[6], precision: match[7], type: match[8] } ) } else { throw new SyntaxError('[sprintf] unexpected placeholder') } _fmt = _fmt.substring(match[0].length) } return sprintf_cache[fmt] = parse_tree } /** * export to either browser or node.js */ /* eslint-disable quote-props */ if (true) { exports.sprintf = sprintf exports.vsprintf = vsprintf } if (typeof window !== 'undefined') { window['sprintf'] = sprintf window['vsprintf'] = vsprintf if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return { 'sprintf': sprintf, 'vsprintf': vsprintf } }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) } } /* eslint-enable quote-props */ }(); // eslint-disable-line /***/ }), /***/ "./node_modules/sweetalert2/dist/sweetalert2.all.js": /*!**********************************************************!*\ !*** ./node_modules/sweetalert2/dist/sweetalert2.all.js ***! \**********************************************************/ /***/ (function(module) { /*! * sweetalert2 v11.7.27 * Released under the MIT License. */ (function (global, factory) { true ? module.exports = factory() : 0; })(this, (function () { 'use strict'; function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); } function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; } function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); } function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } } 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); } 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(); } }; /** * Restore previous active (focused) element * * @param {boolean} returnFocus * @returns {Promise} */ 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); }); }; /** * 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() }; const 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[]} */ const 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']; const swalClasses = classNames.reduce((acc, className) => { acc[className] = swalPrefix + className; return acc; }, /** @type {SwalClasses} */{}); /** @type {SwalIcon[]} */ const icons = ['success', 'warning', 'info', 'question', 'error']; const iconTypes = icons.reduce((acc, icon) => { acc[icon] = swalPrefix + icon; return acc; }, /** @type {SwalIcons} */{}); const consolePrefix = 'SweetAlert2:'; /** * Capitalize the first letter of a string * * @param {string} str * @returns {string} */ const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1); /** * Standardize console warnings * * @param {string | string[]} message */ const warn = message => { console.warn("".concat(consolePrefix, " ").concat(typeof message === 'object' ? message.join(' ') : message)); }; /** * Standardize console errors * * @param {string} message */ const error = message => { console.error("".concat(consolePrefix, " ").concat(message)); }; /** * Private global state for `warnOnce` * * @type {string[]} * @private */ const previousWarnOnceMessages = []; /** * Show a console warning, but only if it hasn't already been shown * * @param {string} message */ const warnOnce = message => { if (!previousWarnOnceMessages.includes(message)) { previousWarnOnceMessages.push(message); warn(message); } }; /** * Show a one-time console warning about deprecated params/methods * * @param {string} deprecatedParam * @param {string} useInstead */ const warnAboutDeprecation = (deprecatedParam, useInstead) => { warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead.")); }; /** * If `arg` is a function, call it (with no arguments or context) and return the result. * Otherwise, just pass the value through * * @param {Function | any} arg * @returns {any} */ const callIfFunction = arg => typeof arg === 'function' ? arg() : arg; /** * @param {any} arg * @returns {boolean} */ const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function'; /** * @param {any} arg * @returns {Promise} */ const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg); /** * @param {any} arg * @returns {boolean} */ const isPromise = arg => arg && Promise.resolve(arg) === arg; /** * Gets the popup container which contains the backdrop and the popup itself. * * @returns {HTMLElement | null} */ const getContainer = () => document.body.querySelector(".".concat(swalClasses.container)); /** * @param {string} selectorString * @returns {HTMLElement | null} */ const elementBySelector = selectorString => { const container = getContainer(); return container ? container.querySelector(selectorString) : null; }; /** * @param {string} className * @returns {HTMLElement | null} */ const elementByClass = className => { return elementBySelector(".".concat(className)); }; /** * @returns {HTMLElement | null} */ const getPopup = () => elementByClass(swalClasses.popup); /** * @returns {HTMLElement | null} */ const getIcon = () => elementByClass(swalClasses.icon); /** * @returns {HTMLElement | null} */ const getIconContent = () => elementByClass(swalClasses['icon-content']); /** * @returns {HTMLElement | null} */ const getTitle = () => elementByClass(swalClasses.title); /** * @returns {HTMLElement | null} */ const getHtmlContainer = () => elementByClass(swalClasses['html-container']); /** * @returns {HTMLElement | null} */ const getImage = () => elementByClass(swalClasses.image); /** * @returns {HTMLElement | null} */ const getProgressSteps = () => elementByClass(swalClasses['progress-steps']); /** * @returns {HTMLElement | null} */ const getValidationMessage = () => elementByClass(swalClasses['validation-message']); /** * @returns {HTMLButtonElement | null} */ const getConfirmButton = () => /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm)); /** * @returns {HTMLButtonElement | null} */ const getCancelButton = () => /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel)); /** * @returns {HTMLButtonElement | null} */ const getDenyButton = () => /** @type {HTMLButtonElement} */elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny)); /** * @returns {HTMLElement | null} */ const getInputLabel = () => elementByClass(swalClasses['input-label']); /** * @returns {HTMLElement | null} */ const getLoader = () => elementBySelector(".".concat(swalClasses.loader)); /** * @returns {HTMLElement | null} */ const getActions = () => elementByClass(swalClasses.actions); /** * @returns {HTMLElement | null} */ const getFooter = () => elementByClass(swalClasses.footer); /** * @returns {HTMLElement | null} */ const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']); /** * @returns {HTMLElement | null} */ const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js const 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"; /** * @returns {HTMLElement[]} */ const getFocusableElements = () => { const popup = getPopup(); if (!popup) { return []; } /** @type {NodeListOf} */ const focusableElementsWithTabindex = popup.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])'); const focusableElementsWithTabindexSorted = Array.from(focusableElementsWithTabindex) // sort according to tabindex .sort((a, b) => { const tabindexA = parseInt(a.getAttribute('tabindex') || '0'); const tabindexB = parseInt(b.getAttribute('tabindex') || '0'); if (tabindexA > tabindexB) { return 1; } else if (tabindexA < tabindexB) { return -1; } return 0; }); /** @type {NodeListOf} */ const otherFocusableElements = popup.querySelectorAll(focusable); const otherFocusableElementsFiltered = Array.from(otherFocusableElements).filter(el => el.getAttribute('tabindex') !== '-1'); return [...new Set(focusableElementsWithTabindexSorted.concat(otherFocusableElementsFiltered))].filter(el => isVisible$1(el)); }; /** * @returns {boolean} */ const isModal = () => { return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']); }; /** * @returns {boolean} */ const isToast = () => { const popup = getPopup(); if (!popup) { return false; } return hasClass(popup, swalClasses.toast); }; /** * @returns {boolean} */ const isLoading = () => { const popup = getPopup(); if (!popup) { return false; } return popup.hasAttribute('data-loading'); }; /** * Securely set innerHTML of an element * https://github.com/sweetalert2/sweetalert2/issues/1926 * * @param {HTMLElement} elem * @param {string} html */ const setInnerHtml = (elem, html) => { elem.textContent = ''; if (html) { const parser = new DOMParser(); const parsed = parser.parseFromString(html, "text/html"); const head = parsed.querySelector('head'); head && Array.from(head.childNodes).forEach(child => { elem.appendChild(child); }); const body = parsed.querySelector('body'); body && Array.from(body.childNodes).forEach(child => { if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) { elem.appendChild(child.cloneNode(true)); // https://github.com/sweetalert2/sweetalert2/issues/2507 } else { elem.appendChild(child); } }); } }; /** * @param {HTMLElement} elem * @param {string} className * @returns {boolean} */ const hasClass = (elem, className) => { if (!className) { return false; } const classList = className.split(/\s+/); for (let i = 0; i < classList.length; i++) { if (!elem.classList.contains(classList[i])) { return false; } } return true; }; /** * @param {HTMLElement} elem * @param {SweetAlertOptions} params */ 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); } }); }; /** * @param {HTMLElement} elem * @param {SweetAlertOptions} params * @param {string} 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], "\"")); return; } addClass(elem, params.customClass[className]); } }; /** * @param {HTMLElement} popup * @param {import('./renderers/renderInput').InputClass} inputClass * @returns {HTMLInputElement | null} */ const getInput$1 = (popup, inputClass) => { if (!inputClass) { return null; } switch (inputClass) { case 'select': case 'textarea': case 'file': return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputClass])); case 'checkbox': return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(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")); case 'range': return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input")); default: return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input)); } }; /** * @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input */ const focusInput = input => { input.focus(); // place cursor at end of text in text input if (input.type !== 'file') { // http://stackoverflow.com/a/2345915 const val = input.value; input.value = ''; input.value = val; } }; /** * @param {HTMLElement | HTMLElement[] | null} target * @param {string | string[] | readonly string[] | undefined} classList * @param {boolean} condition */ const toggleClass = (target, classList, condition) => { if (!target || !classList) { return; } if (typeof classList === 'string') { classList = classList.split(/\s+/).filter(Boolean); } classList.forEach(className => { if (Array.isArray(target)) { target.forEach(elem => { condition ? elem.classList.add(className) : elem.classList.remove(className); }); } else { condition ? target.classList.add(className) : target.classList.remove(className); } }); }; /** * @param {HTMLElement | HTMLElement[] | null} target * @param {string | string[] | readonly string[] | undefined} classList */ const addClass = (target, classList) => { toggleClass(target, classList, true); }; /** * @param {HTMLElement | HTMLElement[] | null} target * @param {string | string[] | readonly string[] | undefined} classList */ const removeClass = (target, classList) => { toggleClass(target, classList, false); }; /** * Get direct child of an element by class name * * @param {HTMLElement} elem * @param {string} className * @returns {HTMLElement | undefined} */ 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; } } }; /** * @param {HTMLElement} elem * @param {string} property * @param {*} value */ const applyNumericalStyle = (elem, property, value) => { if (value === "".concat(parseInt(value))) { value = parseInt(value); } if (value || parseInt(value) === 0) { elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value; } else { elem.style.removeProperty(property); } }; /** * @param {HTMLElement | null} elem * @param {string} display */ const show = function (elem) { let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex'; elem && (elem.style.display = display); }; /** * @param {HTMLElement | null} elem */ const hide = elem => { elem && (elem.style.display = 'none'); }; /** * @param {HTMLElement} parent * @param {string} selector * @param {string} property * @param {string} value */ const setStyle = (parent, selector, property, value) => { /** @type {HTMLElement} */ const el = parent.querySelector(selector); if (el) { el.style[property] = value; } }; /** * @param {HTMLElement} elem * @param {any} condition * @param {string} display */ 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 * @returns {boolean} */ const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length)); /** * @returns {boolean} */ const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton()); /** * @param {HTMLElement} elem * @returns {boolean} */ const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); /** * borrowed from https://stackoverflow.com/a/46352119 * * @param {HTMLElement} elem * @returns {boolean} */ 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; }; /** * @param {number} timer * @param {boolean} reset */ const animateTimerProgressBar = function (timer) { let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; const timerProgressBar = getTimerProgressBar(); if (!timerProgressBar) { return; } if (isVisible$1(timerProgressBar)) { if (reset) { timerProgressBar.style.transition = 'none'; timerProgressBar.style.width = '100%'; } setTimeout(() => { timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear"); timerProgressBar.style.width = '0%'; }, 10); } }; const stopTimerProgressBar = () => { const timerProgressBar = getTimerProgressBar(); if (!timerProgressBar) { return; } const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width); timerProgressBar.style.removeProperty('transition'); timerProgressBar.style.width = '100%'; const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width); const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100; timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%"); }; /** * Detect Node env * * @returns {boolean} */ const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined'; const 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, ''); /** * @returns {boolean} */ const resetOldContainer = () => { const oldContainer = getContainer(); if (!oldContainer) { return false; } oldContainer.remove(); removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]); return true; }; const resetValidationMessage$1 = () => { globalState.currentInstance.resetValidationMessage(); }; const addInputChangeListeners = () => { const popup = getPopup(); const input = getDirectChildByClass(popup, swalClasses.input); const file = getDirectChildByClass(popup, swalClasses.file); /** @type {HTMLInputElement} */ const range = popup.querySelector(".".concat(swalClasses.range, " input")); /** @type {HTMLOutputElement} */ const rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output")); const select = getDirectChildByClass(popup, swalClasses.select); /** @type {HTMLInputElement} */ const checkbox = popup.querySelector(".".concat(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 = () => { resetValidationMessage$1(); rangeOutput.value = range.value; }; range.onchange = () => { resetValidationMessage$1(); rangeOutput.value = range.value; }; }; /** * @param {string | HTMLElement} target * @returns {HTMLElement} */ const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target; /** * @param {SweetAlertOptions} params */ const setupAccessibility = params => { const popup = getPopup(); popup.setAttribute('role', params.toast ? 'alert' : 'dialog'); popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive'); if (!params.toast) { popup.setAttribute('aria-modal', 'true'); } }; /** * @param {HTMLElement} targetElement */ const setupRTL = targetElement => { if (window.getComputedStyle(targetElement).direction === 'rtl') { addClass(getContainer(), swalClasses.rtl); } }; /** * Add modal + backdrop + no-war message for Russians to DOM * * @param {SweetAlertOptions} params */ const init = params => { // Clean up the old popup container if it exists const oldContainerExisted = resetOldContainer(); if (isNodeEnv()) { error('SweetAlert2 requires document to initialize'); return; } const container = document.createElement('div'); container.className = swalClasses.container; if (oldContainerExisted) { addClass(container, swalClasses['no-transition']); } setInnerHtml(container, sweetHTML); const targetElement = getTarget(params.target); targetElement.appendChild(container); setupAccessibility(params); setupRTL(targetElement); addInputChangeListeners(); }; /** * @param {HTMLElement | object | string} param * @param {HTMLElement} target */ const parseHtmlToContainer = (param, target) => { // DOM element if (param instanceof HTMLElement) { target.appendChild(param); } // Object else if (typeof param === 'object') { handleObject(param, target); } // Plain string else if (param) { setInnerHtml(target, param); } }; /** * @param {any} param * @param {HTMLElement} target */ const handleObject = (param, target) => { // JQuery element(s) if (param.jquery) { handleJqueryElem(target, param); } // For other objects use their string representation else { setInnerHtml(target, param.toString()); } }; /** * @param {HTMLElement} target * @param {any} elem */ const handleJqueryElem = (target, elem) => { target.textContent = ''; if (0 in elem) { for (let i = 0; (i in elem); i++) { target.appendChild(elem[i].cloneNode(true)); } } else { target.appendChild(elem.cloneNode(true)); } }; /** * @returns {'webkitAnimationEnd' | 'animationend' | false} */ const animationEndEvent = (() => { // Prevent run in Node env if (isNodeEnv()) { return false; } const testEl = document.createElement('div'); // Chrome, Safari and Opera if (typeof testEl.style.webkitAnimation !== 'undefined') { return 'webkitAnimationEnd'; } // Standard syntax if (typeof testEl.style.animation !== 'undefined') { return 'animationend'; } return false; })(); /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderActions = (instance, params) => { const actions = getActions(); const loader = getLoader(); if (!actions || !loader) { return; } // Actions (buttons) wrapper if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) { hide(actions); } else { show(actions); } // Custom class applyCustomClass(actions, params, 'actions'); // Render all the buttons renderButtons(actions, loader, params); // Loader setInnerHtml(loader, params.loaderHtml || ''); applyCustomClass(loader, params, 'loader'); }; /** * @param {HTMLElement} actions * @param {HTMLElement} loader * @param {SweetAlertOptions} params */ function renderButtons(actions, loader, params) { const confirmButton = getConfirmButton(); const denyButton = getDenyButton(); const cancelButton = getCancelButton(); if (!confirmButton || !denyButton || !cancelButton) { return; } // Render buttons renderButton(confirmButton, 'confirm', params); renderButton(denyButton, 'deny', params); renderButton(cancelButton, 'cancel', params); handleButtonsStyling(confirmButton, denyButton, cancelButton, params); if (params.reverseButtons) { if (params.toast) { actions.insertBefore(cancelButton, confirmButton); actions.insertBefore(denyButton, confirmButton); } else { actions.insertBefore(cancelButton, loader); actions.insertBefore(denyButton, loader); actions.insertBefore(confirmButton, loader); } } } /** * @param {HTMLElement} confirmButton * @param {HTMLElement} denyButton * @param {HTMLElement} cancelButton * @param {SweetAlertOptions} params */ function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) { if (!params.buttonsStyling) { removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled); return; } addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors if (params.confirmButtonColor) { confirmButton.style.backgroundColor = params.confirmButtonColor; addClass(confirmButton, swalClasses['default-outline']); } if (params.denyButtonColor) { denyButton.style.backgroundColor = params.denyButtonColor; addClass(denyButton, swalClasses['default-outline']); } if (params.cancelButtonColor) { cancelButton.style.backgroundColor = params.cancelButtonColor; addClass(cancelButton, swalClasses['default-outline']); } } /** * @param {HTMLElement} button * @param {'confirm' | 'deny' | 'cancel'} buttonType * @param {SweetAlertOptions} params */ function renderButton(button, buttonType, params) { const 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 // Add buttons custom classes button.className = swalClasses[buttonType]; applyCustomClass(button, params, "".concat(buttonType, "Button")); } /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderCloseButton = (instance, params) => { const closeButton = getCloseButton(); if (!closeButton) { return; } setInnerHtml(closeButton, params.closeButtonHtml || ''); // Custom class applyCustomClass(closeButton, params, 'closeButton'); toggle(closeButton, params.showCloseButton); closeButton.setAttribute('aria-label', params.closeButtonAriaLabel || ''); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderContainer = (instance, params) => { const container = getContainer(); if (!container) { return; } handleBackdropParam(container, params.backdrop); handlePositionParam(container, params.position); handleGrowParam(container, params.grow); // Custom class applyCustomClass(container, params, 'container'); }; /** * @param {HTMLElement} container * @param {SweetAlertOptions['backdrop']} backdrop */ function handleBackdropParam(container, backdrop) { if (typeof backdrop === 'string') { container.style.background = backdrop; } else if (!backdrop) { addClass([document.documentElement, document.body], swalClasses['no-backdrop']); } } /** * @param {HTMLElement} container * @param {SweetAlertOptions['position']} position */ function handlePositionParam(container, position) { if (!position) { return; } if (position in swalClasses) { addClass(container, swalClasses[position]); } else { warn('The "position" parameter is not valid, defaulting to "center"'); addClass(container, swalClasses.center); } } /** * @param {HTMLElement} container * @param {SweetAlertOptions['grow']} grow */ function handleGrowParam(container, grow) { if (!grow) { return; } addClass(container, swalClasses["grow-".concat(grow)]); } /// /** @type {InputClass[]} */ const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea']; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderInput = (instance, params) => { const popup = getPopup(); if (!popup) { return; } const innerParams = privateProps.innerParams.get(instance); const rerender = !innerParams || params.input !== innerParams.input; inputClasses.forEach(inputClass => { const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]); if (!inputContainer) { return; } // set attributes setAttributes(inputClass, params.inputAttributes); // set class inputContainer.className = swalClasses[inputClass]; if (rerender) { hide(inputContainer); } }); if (params.input) { if (rerender) { showInput(params); } // set custom class setCustomClass(params); } }; /** * @param {SweetAlertOptions} params */ const showInput = params => { if (!params.input) { return; } if (!renderInputType[params.input]) { error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\"")); return; } const inputContainer = getInputContainer(params.input); const input = renderInputType[params.input](inputContainer, params); show(inputContainer); // input autofocus if (params.inputAutoFocus) { setTimeout(() => { focusInput(input); }); } }; /** * @param {HTMLInputElement} input */ const removeAttributes = input => { for (let i = 0; i < input.attributes.length; i++) { const attrName = input.attributes[i].name; if (!['id', 'type', 'value', 'style'].includes(attrName)) { input.removeAttribute(attrName); } } }; /** * @param {InputClass} inputClass * @param {SweetAlertOptions['inputAttributes']} inputAttributes */ const setAttributes = (inputClass, inputAttributes) => { const input = getInput$1(getPopup(), inputClass); if (!input) { return; } removeAttributes(input); for (const attr in inputAttributes) { input.setAttribute(attr, inputAttributes[attr]); } }; /** * @param {SweetAlertOptions} params */ const setCustomClass = params => { const inputContainer = getInputContainer(params.input); if (typeof params.customClass === 'object') { addClass(inputContainer, params.customClass.input); } }; /** * @param {HTMLInputElement | HTMLTextAreaElement} input * @param {SweetAlertOptions} params */ const setInputPlaceholder = (input, params) => { if (!input.placeholder || params.inputPlaceholder) { input.placeholder = params.inputPlaceholder; } }; /** * @param {Input} input * @param {Input} prependTo * @param {SweetAlertOptions} params */ const setInputLabel = (input, prependTo, params) => { if (params.inputLabel) { const label = document.createElement('label'); const labelClass = swalClasses['input-label']; label.setAttribute('for', input.id); label.className = labelClass; if (typeof params.customClass === 'object') { addClass(label, params.customClass.inputLabel); } label.innerText = params.inputLabel; prependTo.insertAdjacentElement('beforebegin', label); } }; /** * @param {SweetAlertOptions['input']} inputType * @returns {HTMLElement} */ const getInputContainer = inputType => { return getDirectChildByClass(getPopup(), swalClasses[inputType] || swalClasses.input); }; /** * @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input * @param {SweetAlertOptions['inputValue']} inputValue */ const checkAndSetInputValue = (input, inputValue) => { if (['string', 'number'].includes(typeof inputValue)) { input.value = "".concat(inputValue); } else if (!isPromise(inputValue)) { warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(typeof inputValue, "\"")); } }; /** @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 = (input, params) => { checkAndSetInputValue(input, params.inputValue); setInputLabel(input, input, params); setInputPlaceholder(input, params); input.type = params.input; return input; }; /** * @param {HTMLInputElement} input * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ renderInputType.file = (input, params) => { setInputLabel(input, input, params); setInputPlaceholder(input, params); return input; }; /** * @param {HTMLInputElement} range * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ 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); setInputLabel(rangeInput, range, params); return range; }; /** * @param {HTMLSelectElement} select * @param {SweetAlertOptions} params * @returns {HTMLSelectElement} */ renderInputType.select = (select, params) => { select.textContent = ''; if (params.inputPlaceholder) { const placeholder = document.createElement('option'); setInnerHtml(placeholder, params.inputPlaceholder); placeholder.value = ''; placeholder.disabled = true; placeholder.selected = true; select.appendChild(placeholder); } setInputLabel(select, select, params); return select; }; /** * @param {HTMLInputElement} radio * @returns {HTMLInputElement} */ renderInputType.radio = radio => { radio.textContent = ''; return radio; }; /** * @param {HTMLLabelElement} checkboxContainer * @param {SweetAlertOptions} params * @returns {HTMLInputElement} */ renderInputType.checkbox = (checkboxContainer, params) => { const checkbox = getInput$1(getPopup(), 'checkbox'); checkbox.value = '1'; checkbox.checked = Boolean(params.inputValue); const label = checkboxContainer.querySelector('span'); setInnerHtml(label, params.inputPlaceholder); return checkbox; }; /** * @param {HTMLTextAreaElement} textarea * @param {SweetAlertOptions} params * @returns {HTMLTextAreaElement} */ renderInputType.textarea = (textarea, params) => { checkAndSetInputValue(textarea, params.inputValue); setInputPlaceholder(textarea, params); setInputLabel(textarea, textarea, params); /** * @param {HTMLElement} el * @returns {number} */ const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291 setTimeout(() => { // https://github.com/sweetalert2/sweetalert2/issues/1699 if ('MutationObserver' in window) { const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width); const textareaResizeHandler = () => { // check if texarea is still in document (i.e. popup wasn't closed in the meantime) if (!document.body.contains(textarea)) { return; } const textareaWidth = textarea.offsetWidth + getMargin(textarea); if (textareaWidth > initialPopupWidth) { getPopup().style.width = "".concat(textareaWidth, "px"); } else { applyNumericalStyle(getPopup(), 'width', params.width); } }; new MutationObserver(textareaResizeHandler).observe(textarea, { attributes: true, attributeFilter: ['style'] }); } }); return textarea; }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderContent = (instance, params) => { const htmlContainer = getHtmlContainer(); if (!htmlContainer) { return; } applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML if (params.html) { parseHtmlToContainer(params.html, htmlContainer); show(htmlContainer, 'block'); } // Content as plain text else if (params.text) { htmlContainer.textContent = params.text; show(htmlContainer, 'block'); } // No content else { hide(htmlContainer); } renderInput(instance, params); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderFooter = (instance, params) => { const footer = getFooter(); if (!footer) { return; } toggle(footer, params.footer, 'block'); if (params.footer) { parseHtmlToContainer(params.footer, footer); } // Custom class applyCustomClass(footer, params, 'footer'); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderIcon = (instance, params) => { const innerParams = privateProps.innerParams.get(instance); const icon = getIcon(); if (!icon) { return; } // if the given icon already rendered, apply the styling without re-rendering the icon if (innerParams && params.icon === innerParams.icon) { // Custom or default content setContent(icon, params); applyStyles(icon, params); return; } if (!params.icon && !params.iconHtml) { hide(icon); 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, "\"")); hide(icon); return; } show(icon); // Custom or default content setContent(icon, params); applyStyles(icon, params); // Animate icon addClass(icon, params.showClass && params.showClass.icon); }; /** * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ const applyStyles = (icon, params) => { for (const [iconType, iconClassName] of Object.entries(iconTypes)) { if (params.icon !== iconType) { removeClass(icon, iconClassName); } } addClass(icon, params.icon && iconTypes[params.icon]); // Icon color setColor(icon, params); // Success icon background color adjustSuccessIconBackgroundColor(); // Custom class applyCustomClass(icon, params, 'icon'); }; // Adjust success icon background color to match the popup background color const adjustSuccessIconBackgroundColor = () => { const popup = getPopup(); if (!popup) { return; } const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color'); /** @type {NodeListOf} */ 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; } }; const successIconHtml = "\n
    \n \n
    \n
    \n"; const errorIconHtml = "\n \n \n \n \n"; /** * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ const setContent = (icon, params) => { if (!params.icon && !params.iconHtml) { return; } let oldContent = icon.innerHTML; let newContent = ''; if (params.iconHtml) { newContent = iconContent(params.iconHtml); } else if (params.icon === 'success') { newContent = successIconHtml; oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor() } else if (params.icon === 'error') { newContent = errorIconHtml; } else if (params.icon) { const defaultIconHtml = { question: '?', warning: '!', info: 'i' }; newContent = iconContent(defaultIconHtml[params.icon]); } if (oldContent.trim() !== newContent.trim()) { setInnerHtml(icon, newContent); } }; /** * @param {HTMLElement} icon * @param {SweetAlertOptions} params */ const setColor = (icon, params) => { if (!params.iconColor) { return; } icon.style.color = params.iconColor; icon.style.borderColor = 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', 'borderColor', params.iconColor); }; /** * @param {string} content * @returns {string} */ const iconContent = content => "
    ").concat(content, "
    "); /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderImage = (instance, params) => { const image = getImage(); if (!image) { return; } if (!params.imageUrl) { hide(image); return; } show(image, ''); // Src, alt image.setAttribute('src', params.imageUrl); image.setAttribute('alt', params.imageAlt || ''); // Width, height applyNumericalStyle(image, 'width', params.imageWidth); applyNumericalStyle(image, 'height', params.imageHeight); // Class image.className = swalClasses.image; applyCustomClass(image, params, 'image'); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderPopup = (instance, params) => { const container = getContainer(); const popup = getPopup(); if (!container || !popup) { return; } // Width // https://github.com/sweetalert2/sweetalert2/issues/2170 if (params.toast) { applyNumericalStyle(container, 'width', params.width); popup.style.width = '100%'; const loader = getLoader(); loader && popup.insertBefore(loader, getIcon()); } else { applyNumericalStyle(popup, 'width', params.width); } // Padding applyNumericalStyle(popup, 'padding', params.padding); // Color if (params.color) { popup.style.color = params.color; } // Background if (params.background) { popup.style.background = params.background; } hide(getValidationMessage()); // Classes addClasses$1(popup, params); }; /** * @param {HTMLElement} popup * @param {SweetAlertOptions} params */ const addClasses$1 = (popup, params) => { const showClass = params.showClass || {}; // Default Class + showClass when updating Swal.update({}) popup.className = "".concat(swalClasses.popup, " ").concat(isVisible$1(popup) ? showClass.popup : ''); if (params.toast) { addClass([document.documentElement, document.body], swalClasses['toast-shown']); addClass(popup, swalClasses.toast); } else { addClass(popup, swalClasses.modal); } // Custom class applyCustomClass(popup, params, 'popup'); if (typeof params.customClass === 'string') { addClass(popup, params.customClass); } // Icon class (#1842) if (params.icon) { addClass(popup, swalClasses["icon-".concat(params.icon)]); } }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderProgressSteps = (instance, params) => { const progressStepsContainer = getProgressSteps(); if (!progressStepsContainer) { return; } const { progressSteps, currentProgressStep } = params; if (!progressSteps || progressSteps.length === 0 || currentProgressStep === undefined) { hide(progressStepsContainer); return; } show(progressStepsContainer); progressStepsContainer.textContent = ''; if (currentProgressStep >= progressSteps.length) { warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)'); } progressSteps.forEach((step, index) => { const stepEl = createStepElement(step); progressStepsContainer.appendChild(stepEl); if (index === currentProgressStep) { addClass(stepEl, swalClasses['active-progress-step']); } if (index !== progressSteps.length - 1) { const lineEl = createLineElement(params); progressStepsContainer.appendChild(lineEl); } }); }; /** * @param {string} step * @returns {HTMLLIElement} */ const createStepElement = step => { const stepEl = document.createElement('li'); addClass(stepEl, swalClasses['progress-step']); setInnerHtml(stepEl, step); return stepEl; }; /** * @param {SweetAlertOptions} params * @returns {HTMLLIElement} */ const createLineElement = params => { const lineEl = document.createElement('li'); addClass(lineEl, swalClasses['progress-step-line']); if (params.progressStepsDistance) { applyNumericalStyle(lineEl, 'width', params.progressStepsDistance); } return lineEl; }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const renderTitle = (instance, params) => { const title = getTitle(); if (!title) { return; } toggle(title, params.title || params.titleText, 'block'); if (params.title) { parseHtmlToContainer(params.title, title); } if (params.titleText) { title.innerText = params.titleText; } // Custom class applyCustomClass(title, params, 'title'); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const render = (instance, params) => { renderPopup(instance, params); renderContainer(instance, params); renderProgressSteps(instance, params); renderIcon(instance, params); renderImage(instance, params); renderTitle(instance, params); renderCloseButton(instance, params); renderContent(instance, params); renderActions(instance, params); renderFooter(instance, params); const popup = getPopup(); if (typeof params.didRender === 'function' && popup) { params.didRender(popup); } }; /* * Global function to determine if SweetAlert2 popup is shown */ const isVisible = () => { return isVisible$1(getPopup()); }; /* * Global function to click 'Confirm' button */ const clickConfirm = () => { var _dom$getConfirmButton; return (_dom$getConfirmButton = getConfirmButton()) === null || _dom$getConfirmButton === void 0 ? void 0 : _dom$getConfirmButton.click(); }; /* * Global function to click 'Deny' button */ const clickDeny = () => { var _dom$getDenyButton; return (_dom$getDenyButton = getDenyButton()) === null || _dom$getDenyButton === void 0 ? void 0 : _dom$getDenyButton.click(); }; /* * Global function to click 'Cancel' button */ const clickCancel = () => { var _dom$getCancelButton; return (_dom$getCancelButton = getCancelButton()) === null || _dom$getCancelButton === void 0 ? void 0 : _dom$getCancelButton.click(); }; /** @typedef {'cancel' | 'backdrop' | 'close' | 'esc' | 'timer'} DismissReason */ /** @type {Record} */ const DismissReason = Object.freeze({ cancel: 'cancel', backdrop: 'backdrop', close: 'close', esc: 'esc', timer: 'timer' }); /** * @param {GlobalState} globalState */ const removeKeydownHandler = globalState => { if (globalState.keydownTarget && globalState.keydownHandlerAdded) { globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture }); globalState.keydownHandlerAdded = false; } }; /** * @param {SweetAlert} instance * @param {GlobalState} globalState * @param {SweetAlertOptions} innerParams * @param {*} dismissWith */ const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => { removeKeydownHandler(globalState); if (!innerParams.toast) { globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith); globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup(); globalState.keydownListenerCapture = innerParams.keydownListenerCapture; globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture }); globalState.keydownHandlerAdded = true; } }; /** * @param {number} index * @param {number} increment */ const setFocus = (index, increment) => { const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match if (focusableElements.length) { index = index + increment; // rollover to first item if (index === focusableElements.length) { index = 0; // go to last item } else if (index === -1) { index = focusableElements.length - 1; } focusableElements[index].focus(); return; } // no visible focusable elements, focus the popup getPopup().focus(); }; const arrowKeysNextButton = ['ArrowRight', 'ArrowDown']; const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp']; /** * @param {SweetAlert} instance * @param {KeyboardEvent} event * @param {Function} dismissWith */ const keydownHandler = (instance, event, dismissWith) => { const innerParams = privateProps.innerParams.get(instance); if (!innerParams) { return; // This instance has already been destroyed } // Ignore keydown during IME composition // 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) { return; } if (innerParams.stopKeydownPropagation) { event.stopPropagation(); } // ENTER if (event.key === 'Enter') { handleEnter(instance, event, innerParams); } // TAB else if (event.key === 'Tab') { handleTab(event); } // ARROWS - switch focus between buttons else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) { handleArrows(event.key); } // ESC else if (event.key === 'Escape') { handleEsc(event, innerParams, dismissWith); } }; /** * @param {SweetAlert} instance * @param {KeyboardEvent} event * @param {SweetAlertOptions} innerParams */ const handleEnter = (instance, event, innerParams) => { // https://github.com/sweetalert2/sweetalert2/issues/2386 if (!callIfFunction(innerParams.allowEnterKey)) { return; } if (event.target && instance.getInput() && event.target instanceof HTMLElement && event.target.outerHTML === instance.getInput().outerHTML) { if (['textarea', 'file'].includes(innerParams.input)) { return; // do not submit } clickConfirm(); event.preventDefault(); } }; /** * @param {KeyboardEvent} event */ const handleTab = event => { const targetElement = event.target; const focusableElements = getFocusableElements(); let btnIndex = -1; for (let i = 0; i < focusableElements.length; i++) { if (targetElement === focusableElements[i]) { btnIndex = i; break; } } // Cycle to the next button if (!event.shiftKey) { setFocus(btnIndex, 1); } // Cycle to the prev button else { setFocus(btnIndex, -1); } event.stopPropagation(); event.preventDefault(); }; /** * @param {string} key */ const handleArrows = key => { const confirmButton = getConfirmButton(); const denyButton = getDenyButton(); const cancelButton = getCancelButton(); /** @type HTMLElement[] */ const buttons = [confirmButton, denyButton, cancelButton]; if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) { return; } 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; } if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) { break; } } if (buttonToFocus instanceof HTMLButtonElement) { buttonToFocus.focus(); } }; /** * @param {KeyboardEvent} event * @param {SweetAlertOptions} innerParams * @param {Function} dismissWith */ const handleEsc = (event, innerParams, dismissWith) => { if (callIfFunction(innerParams.allowEscapeKey)) { event.preventDefault(); dismissWith(DismissReason.esc); } }; /** * 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 privateMethods = { swalPromiseResolve: new WeakMap(), swalPromiseReject: new WeakMap() }; // From https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/ // Adding aria-hidden="true" to elements outside of the active modal dialog ensures that // 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. 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('aria-hidden', 'true'); }); }; 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.removeAttribute('data-previous-aria-hidden'); } else { el.removeAttribute('aria-hidden'); } }); }; // @ts-ignore const isSafariOrIOS = typeof window !== 'undefined' && !!window.GestureEvent; // true for Safari desktop + all iOS browsers https://stackoverflow.com/a/70585394 /** * Fix iOS scrolling * http://stackoverflow.com/q/39626302 */ const iOSfix = () => { if (isSafariOrIOS && !hasClass(document.body, swalClasses.iosfix)) { const offset = document.body.scrollTop; document.body.style.top = "".concat(offset * -1, "px"); addClass(document.body, swalClasses.iosfix); lockBodyScroll(); } }; /** * https://github.com/sweetalert2/sweetalert2/issues/1246 */ const lockBodyScroll = () => { const container = getContainer(); if (!container) { return; } /** @type {boolean} */ let preventTouchMove; /** * @param {TouchEvent} event */ container.ontouchstart = event => { preventTouchMove = shouldPreventTouchMove(event); }; /** * @param {TouchEvent} event */ container.ontouchmove = event => { if (preventTouchMove) { event.preventDefault(); event.stopPropagation(); } }; }; /** * @param {TouchEvent} event * @returns {boolean} */ const shouldPreventTouchMove = event => { const target = event.target; const container = getContainer(); const htmlContainer = getHtmlContainer(); if (!container || !htmlContainer) { return false; } if (isStylus(event) || isZoom(event)) { return false; } if (target === container) { return true; } if (!isScrollable(container) && target instanceof HTMLElement && target.tagName !== 'INPUT' && // #1603 target.tagName !== 'TEXTAREA' && // #2266 !(isScrollable(htmlContainer) && // #1944 htmlContainer.contains(target))) { return true; } return false; }; /** * https://github.com/sweetalert2/sweetalert2/issues/1786 * * @param {*} event * @returns {boolean} */ const isStylus = event => { return event.touches && event.touches.length && event.touches[0].touchType === 'stylus'; }; /** * https://github.com/sweetalert2/sweetalert2/issues/1891 * * @param {TouchEvent} event * @returns {boolean} */ const isZoom = event => { return event.touches && event.touches.length > 1; }; const undoIOSfix = () => { if (hasClass(document.body, swalClasses.iosfix)) { 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} */ 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; }; /** * Remember state in cases where opening and handling a modal will fiddle with it. * @type {number | null} */ let previousBodyPadding = null; /** * @param {string} initialBodyOverflow */ const replaceScrollbarWithPadding = initialBodyOverflow => { // for queues, do not do this more than once if (previousBodyPadding !== null) { return; } // if the body has overflow if (document.body.scrollHeight > window.innerHeight || initialBodyOverflow === 'scroll' // https://github.com/sweetalert2/sweetalert2/issues/2663 ) { // 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"); } }; const undoReplaceScrollbarWithPadding = () => { if (previousBodyPadding !== null) { document.body.style.paddingRight = "".concat(previousBodyPadding, "px"); previousBodyPadding = null; } }; /** * @param {SweetAlert} instance * @param {HTMLElement} container * @param {boolean} returnFocus * @param {Function} didClose */ function removePopupAndResetState(instance, container, returnFocus, didClose) { if (isToast()) { triggerDidCloseAndDispose(instance, didClose); } else { restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose)); removeKeydownHandler(globalState); } // workaround for https://github.com/sweetalert2/sweetalert2/issues/2088 // for some reason removing the container in Safari will scroll the document to bottom if (isSafariOrIOS) { container.setAttribute('style', 'display:none !important'); container.removeAttribute('class'); container.innerHTML = ''; } else { container.remove(); } if (isModal()) { undoReplaceScrollbarWithPadding(); 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); 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); swalPromiseResolve(resolveValue); } } else if (didClose) { // Resolve Swal promise swalPromiseResolve(resolveValue); } } const triggerClosePopup = instance => { const popup = getPopup(); if (!popup) { return false; } 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); 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) { const rejectPromise = privateMethods.swalPromiseReject.get(this); handleAwaitingPromise(this); if (rejectPromise) { // Reject Swal promise rejectPromise(error); } } /** * @param {SweetAlert} instance */ const handleAwaitingPromise = instance => { if (instance.isAwaitingPromise) { delete instance.isAwaitingPromise; // 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} */ const prepareResolveValue = resolveValue => { // When user calls Swal.close() if (typeof resolveValue === 'undefined') { return { isConfirmed: false, isDenied: false, isDismissed: true }; } return Object.assign({ isConfirmed: false, isDenied: false, isDismissed: false }, resolveValue); }; /** * @param {SweetAlert} instance * @param {HTMLElement} popup * @param {SweetAlertOptions} innerParams */ const handlePopupAnimation = (instance, popup, innerParams) => { const container = getContainer(); // If animation is supported, animate const animationIsSupported = animationEndEvent && hasCssAnimation(popup); if (typeof innerParams.willClose === 'function') { innerParams.willClose(popup); } if (animationIsSupported) { animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose); } else { // Otherwise, remove immediately removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose); } }; /** * @param {SweetAlert} instance * @param {HTMLElement} popup * @param {HTMLElement} container * @param {boolean} returnFocus * @param {Function} didClose */ const animatePopup = (instance, popup, container, returnFocus, didClose) => { if (!animationEndEvent) { return; } globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose); popup.addEventListener(animationEndEvent, function (e) { if (e.target === popup) { globalState.swalCloseEventFinishedCallback(); delete globalState.swalCloseEventFinishedCallback; } }); }; /** * @param {SweetAlert} instance * @param {Function} didClose */ const triggerDidCloseAndDispose = (instance, didClose) => { setTimeout(() => { if (typeof didClose === 'function') { didClose.bind(instance.params)(); } // instance might have been destroyed already if (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] */ const showLoading = buttonToReplace => { let popup = getPopup(); if (!popup) { new Swal(); // eslint-disable-line no-new } popup = getPopup(); if (!popup) { return; } const loader = getLoader(); if (isToast()) { hide(getIcon()); } else { replaceButton(popup, buttonToReplace); } show(loader); popup.setAttribute('data-loading', 'true'); popup.setAttribute('aria-busy', 'true'); popup.focus(); }; /** * @param {HTMLElement} popup * @param {HTMLButtonElement | null} [buttonToReplace] */ const replaceButton = (popup, buttonToReplace) => { const actions = getActions(); const loader = getLoader(); if (!actions || !loader) { 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); } addClass([popup, actions], swalClasses.loading); }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const handleInputOptionsAndValue = (instance, params) => { if (params.input === 'select' || params.input === 'radio') { handleInputOptions(instance, params); } else if (['text', 'email', 'number', 'tel', 'textarea'].some(i => i === params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) { showLoading(getConfirmButton()); handleInputValue(instance, params); } }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} innerParams * @returns {SweetAlertInputValue} */ const getInputValue = (instance, innerParams) => { const input = instance.getInput(); if (!input) { return null; } 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; } }; /** * @param {HTMLInputElement} input * @returns {number} */ const getCheckboxValue = input => input.checked ? 1 : 0; /** * @param {HTMLInputElement} input * @returns {string | null} */ const getRadioValue = input => input.checked ? input.value : null; /** * @param {HTMLInputElement} input * @returns {FileList | File | null} */ const getFileValue = input => input.files && input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const handleInputOptions = (instance, params) => { const popup = getPopup(); if (!popup) { return; } /** * @param {Record} inputOptions */ const 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(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)); } }; /** * @param {SweetAlert} instance * @param {SweetAlertOptions} params */ const handleInputValue = (instance, params) => { const input = instance.getInput(); if (!input) { return; } hide(input); asPromise(params.inputValue).then(inputValue => { input.value = params.input === 'number' ? "".concat(parseFloat(inputValue) || 0) : "".concat(inputValue); show(input); input.focus(); instance.hideLoading(); }).catch(err => { error("Error in inputValue promise: ".concat(err)); input.value = ''; show(input); input.focus(); instance.hideLoading(); }); }; /** * @param {HTMLElement} popup * @param {InputOptionFlattened[]} inputOptions * @param {SweetAlertOptions} params */ function populateSelectOptions(popup, inputOptions, params) { const select = getDirectChildByClass(popup, swalClasses.select); if (!select) { return; } /** * @param {HTMLElement} parent * @param {string} optionLabel * @param {string} optionValue */ const renderOption = (parent, optionLabel, optionValue) => { const option = document.createElement('option'); option.value = optionValue; setInnerHtml(option, optionLabel); option.selected = isSelected(optionValue, params.inputValue); parent.appendChild(option); }; inputOptions.forEach(inputOption => { const optionValue = inputOption[0]; const 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 const optgroup = document.createElement('optgroup'); optgroup.label = optionValue; optgroup.disabled = false; // not configurable for now select.appendChild(optgroup); optionLabel.forEach(o => renderOption(optgroup, o[1], o[0])); } else { // case of