@formio/js 5.0.0-rc.94 → 5.0.0-rc.95

Sign up to get free protection for your applications and to get access to all the features.
Files changed (38) hide show
  1. package/dist/formio.embed.js +1 -1
  2. package/dist/formio.embed.min.js +1 -1
  3. package/dist/formio.embed.min.js.LICENSE.txt +1 -1
  4. package/dist/formio.form.js +20 -9
  5. package/dist/formio.form.min.js +1 -1
  6. package/dist/formio.form.min.js.LICENSE.txt +1 -1
  7. package/dist/formio.full.js +20 -9
  8. package/dist/formio.full.min.js +1 -1
  9. package/dist/formio.full.min.js.LICENSE.txt +1 -1
  10. package/dist/formio.js +195 -3
  11. package/dist/formio.min.js +1 -1
  12. package/dist/formio.min.js.LICENSE.txt +3 -1
  13. package/dist/formio.utils.js +14 -3
  14. package/dist/formio.utils.min.js +1 -1
  15. package/dist/formio.utils.min.js.LICENSE.txt +1 -1
  16. package/lib/cjs/components/editgrid/EditGrid.js +6 -8
  17. package/lib/cjs/components/editgrid/fixtures/comp20.d.ts +43 -0
  18. package/lib/cjs/components/editgrid/fixtures/comp20.js +44 -0
  19. package/lib/cjs/components/editgrid/fixtures/index.d.ts +2 -1
  20. package/lib/cjs/components/editgrid/fixtures/index.js +3 -1
  21. package/lib/cjs/components/number/Number.js +7 -1
  22. package/lib/cjs/components/number/fixtures/index.js +1 -1
  23. package/lib/cjs/components/number/fixtures/scientificNotation.d.ts +14 -0
  24. package/lib/cjs/components/number/fixtures/scientificNotation.js +15 -0
  25. package/lib/cjs/components/select/Select.d.ts +1 -1
  26. package/lib/cjs/components/select/Select.js +12 -5
  27. package/lib/mjs/components/editgrid/EditGrid.js +6 -8
  28. package/lib/mjs/components/editgrid/fixtures/comp20.d.ts +43 -0
  29. package/lib/mjs/components/editgrid/fixtures/comp20.js +42 -0
  30. package/lib/mjs/components/editgrid/fixtures/index.d.ts +2 -1
  31. package/lib/mjs/components/editgrid/fixtures/index.js +2 -1
  32. package/lib/mjs/components/number/Number.js +7 -1
  33. package/lib/mjs/components/number/fixtures/index.js +1 -1
  34. package/lib/mjs/components/number/fixtures/scientificNotation.d.ts +14 -0
  35. package/lib/mjs/components/number/fixtures/scientificNotation.js +13 -0
  36. package/lib/mjs/components/select/Select.d.ts +1 -1
  37. package/lib/mjs/components/select/Select.js +11 -4
  38. package/package.json +3 -3
@@ -1084,6 +1084,17 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n\n\n
1084
1084
 
1085
1085
  /***/ }),
1086
1086
 
1087
+ /***/ "./node_modules/@formio/core/lib/types/ResourceToDomOptions.js":
1088
+ /*!*********************************************************************!*\
1089
+ !*** ./node_modules/@formio/core/lib/types/ResourceToDomOptions.js ***!
1090
+ \*********************************************************************/
1091
+ /***/ (function(__unused_webpack_module, exports) {
1092
+
1093
+ "use strict";
1094
+ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/types/ResourceToDomOptions.js?");
1095
+
1096
+ /***/ }),
1097
+
1087
1098
  /***/ "./node_modules/@formio/core/lib/types/Role.js":
1088
1099
  /*!*****************************************************!*\
1089
1100
  !*** ./node_modules/@formio/core/lib/types/Role.js ***!
@@ -1135,7 +1146,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n\n\n
1135
1146
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
1136
1147
 
1137
1148
  "use strict";
1138
- eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n__exportStar(__webpack_require__(/*! ./project/Project */ \"./node_modules/@formio/core/lib/types/project/Project.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Form */ \"./node_modules/@formio/core/lib/types/Form.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Submission */ \"./node_modules/@formio/core/lib/types/Submission.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Role */ \"./node_modules/@formio/core/lib/types/Role.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Action */ \"./node_modules/@formio/core/lib/types/Action.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Access */ \"./node_modules/@formio/core/lib/types/Access.js\"), exports);\n__exportStar(__webpack_require__(/*! ./RuleFn */ \"./node_modules/@formio/core/lib/types/RuleFn.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Component */ \"./node_modules/@formio/core/lib/types/Component.js\"), exports);\n__exportStar(__webpack_require__(/*! ./process */ \"./node_modules/@formio/core/lib/types/process/index.js\"), exports);\n__exportStar(__webpack_require__(/*! ./DataObject */ \"./node_modules/@formio/core/lib/types/DataObject.js\"), exports);\n__exportStar(__webpack_require__(/*! ./formUtil */ \"./node_modules/@formio/core/lib/types/formUtil.js\"), exports);\n__exportStar(__webpack_require__(/*! ./PassedComponentInstance */ \"./node_modules/@formio/core/lib/types/PassedComponentInstance.js\"), exports);\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/types/index.js?");
1149
+ eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n__exportStar(__webpack_require__(/*! ./project/Project */ \"./node_modules/@formio/core/lib/types/project/Project.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Form */ \"./node_modules/@formio/core/lib/types/Form.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Submission */ \"./node_modules/@formio/core/lib/types/Submission.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Role */ \"./node_modules/@formio/core/lib/types/Role.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Action */ \"./node_modules/@formio/core/lib/types/Action.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Access */ \"./node_modules/@formio/core/lib/types/Access.js\"), exports);\n__exportStar(__webpack_require__(/*! ./RuleFn */ \"./node_modules/@formio/core/lib/types/RuleFn.js\"), exports);\n__exportStar(__webpack_require__(/*! ./Component */ \"./node_modules/@formio/core/lib/types/Component.js\"), exports);\n__exportStar(__webpack_require__(/*! ./process */ \"./node_modules/@formio/core/lib/types/process/index.js\"), exports);\n__exportStar(__webpack_require__(/*! ./DataObject */ \"./node_modules/@formio/core/lib/types/DataObject.js\"), exports);\n__exportStar(__webpack_require__(/*! ./formUtil */ \"./node_modules/@formio/core/lib/types/formUtil.js\"), exports);\n__exportStar(__webpack_require__(/*! ./PassedComponentInstance */ \"./node_modules/@formio/core/lib/types/PassedComponentInstance.js\"), exports);\n__exportStar(__webpack_require__(/*! ./ResourceToDomOptions */ \"./node_modules/@formio/core/lib/types/ResourceToDomOptions.js\"), exports);\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/types/index.js?");
1139
1150
 
1140
1151
  /***/ }),
1141
1152
 
@@ -1982,7 +1993,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
1982
1993
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
1983
1994
 
1984
1995
  "use strict";
1985
- eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.resetEphermalState = exports.registerEphermalState = exports.unescapeHTML = exports.boolValue = exports.escapeRegExCharacters = void 0;\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\n/**\n * Escapes RegEx characters in provided String value.\n *\n * @param {String} value\n * String for escaping RegEx characters.\n * @returns {string}\n * String with escaped RegEx characters.\n */\nfunction escapeRegExCharacters(value) {\n return value.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nexports.escapeRegExCharacters = escapeRegExCharacters;\n/**\n * Determines the boolean value of a setting.\n *\n * @param value\n * @return {boolean}\n */\nfunction boolValue(value) {\n if ((0, lodash_1.isBoolean)(value)) {\n return value;\n }\n else if ((0, lodash_1.isString)(value)) {\n return value.toLowerCase() === 'true';\n }\n else {\n return !!value;\n }\n}\nexports.boolValue = boolValue;\n/**\n * Unescape HTML characters like &lt, &gt, &amp and etc.\n * @param str\n * @returns {string}\n */\nfunction unescapeHTML(str) {\n if (typeof window === 'undefined' || !('DOMParser' in window)) {\n return str;\n }\n const doc = new window.DOMParser().parseFromString(str, 'text/html');\n return doc.documentElement.textContent;\n}\nexports.unescapeHTML = unescapeHTML;\nfunction registerEphermalState(component, name, value) {\n if (!component.ephermalState) {\n Object.defineProperty(component, 'ephermalState', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: {},\n });\n }\n Object.defineProperty(component.ephermalState, name, {\n enumerable: false,\n writable: false,\n configurable: true,\n value,\n });\n}\nexports.registerEphermalState = registerEphermalState;\nfunction resetEphermalState(component) {\n if (component.ephermalState) {\n delete component.ephermalState;\n }\n}\nexports.resetEphermalState = resetEphermalState;\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/utils/utils.js?");
1996
+ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.resetEphermalState = exports.attachResourceToDom = exports.registerEphermalState = exports.unescapeHTML = exports.boolValue = exports.escapeRegExCharacters = void 0;\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\n/**\n * Escapes RegEx characters in provided String value.\n *\n * @param {String} value\n * String for escaping RegEx characters.\n * @returns {string}\n * String with escaped RegEx characters.\n */\nfunction escapeRegExCharacters(value) {\n return value.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&');\n}\nexports.escapeRegExCharacters = escapeRegExCharacters;\n/**\n * Determines the boolean value of a setting.\n *\n * @param value\n * @return {boolean}\n */\nfunction boolValue(value) {\n if ((0, lodash_1.isBoolean)(value)) {\n return value;\n }\n else if ((0, lodash_1.isString)(value)) {\n return value.toLowerCase() === 'true';\n }\n else {\n return !!value;\n }\n}\nexports.boolValue = boolValue;\n/**\n * Unescape HTML characters like &lt, &gt, &amp and etc.\n * @param str\n * @returns {string}\n */\nfunction unescapeHTML(str) {\n if (typeof window === 'undefined' || !('DOMParser' in window)) {\n return str;\n }\n const doc = new window.DOMParser().parseFromString(str, 'text/html');\n return doc.documentElement.textContent;\n}\nexports.unescapeHTML = unescapeHTML;\nfunction registerEphermalState(component, name, value) {\n if (!component.ephermalState) {\n Object.defineProperty(component, 'ephermalState', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: {},\n });\n }\n Object.defineProperty(component.ephermalState, name, {\n enumerable: false,\n writable: false,\n configurable: true,\n value,\n });\n}\nexports.registerEphermalState = registerEphermalState;\nfunction attachResourceToDom(options) {\n const { name, formio, onload, rootElement } = options;\n let { src } = options;\n src = Array.isArray(src) ? src : [src];\n src.forEach((lib) => {\n let attrs = {};\n let elementType = '';\n if (typeof lib === 'string') {\n lib = {\n type: 'script',\n src: lib,\n };\n }\n switch (lib.type) {\n case 'script':\n elementType = 'script';\n attrs = {\n src: lib.src,\n type: 'text/javascript',\n defer: true,\n async: true,\n referrerpolicy: 'origin',\n };\n break;\n case 'styles':\n elementType = 'link';\n attrs = {\n href: lib.src,\n rel: 'stylesheet',\n };\n break;\n }\n // Add the script to the top of the page.\n const element = document.createElement(elementType);\n if (element.setAttribute) {\n for (const attr in attrs) {\n element.setAttribute(attr, attrs[attr]);\n }\n }\n if (onload) {\n element.addEventListener('load', () => {\n formio.libraries[name].loaded = true;\n onload(formio.libraries[name].ready);\n });\n }\n if (rootElement) {\n rootElement.insertAdjacentElement('afterend', element);\n return;\n }\n const { head } = document;\n if (head) {\n head.appendChild(element);\n }\n });\n}\nexports.attachResourceToDom = attachResourceToDom;\nfunction resetEphermalState(component) {\n if (component.ephermalState) {\n delete component.ephermalState;\n }\n}\nexports.resetEphermalState = resetEphermalState;\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/utils/utils.js?");
1986
1997
 
1987
1998
  /***/ }),
1988
1999
 
@@ -2002,7 +2013,7 @@ eval("/*!\n * dist/inputmask\n * https://github.com/RobinHerbots/Inputmask\n * C
2002
2013
  \**********************************************************************/
2003
2014
  /***/ (function(module) {
2004
2015
 
2005
- eval("!function(e,t){ true?module.exports=t():0}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p=\"\",t(0)}([function(e,t,n){\"use strict\";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,\"__esModule\",{value:!0});var i=n(1);Object.defineProperty(t,\"createAutoCorrectedDatePipe\",{enumerable:!0,get:function(){return r(i).default}});var o=n(2);Object.defineProperty(t,\"createNumberMask\",{enumerable:!0,get:function(){return r(o).default}});var u=n(3);Object.defineProperty(t,\"emailMask\",{enumerable:!0,get:function(){return r(u).default}})},function(e,t){\"use strict\";function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"mm dd yyyy\",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.minYear,o=void 0===n?1:n,u=t.maxYear,a=void 0===u?9999:u,c=e.split(/[^dmyHMS]+/).sort(function(e,t){return i.indexOf(e)-i.indexOf(t)});return function(t){var n=[],i={dd:31,mm:12,yy:99,yyyy:a,HH:23,MM:59,SS:59},u={dd:1,mm:1,yy:0,yyyy:o,HH:0,MM:0,SS:0},l=t.split(\"\");c.forEach(function(t){var r=e.indexOf(t),o=parseInt(i[t].toString().substr(0,1),10);parseInt(l[r],10)>o&&(l[r+1]=l[r],l[r]=0,n.push(r))});var s=0,d=c.some(function(n){var c=e.indexOf(n),l=n.length,d=t.substr(c,l).replace(/\\D/g,\"\"),f=parseInt(d,10);\"mm\"===n&&(s=f||0);var p=\"dd\"===n?r[s]:i[n];if(\"yyyy\"===n&&(1!==o||9999!==a)){var v=parseInt(i[n].toString().substring(0,d.length),10),y=parseInt(u[n].toString().substring(0,d.length),10);return f<y||f>v}return f>p||d.length===l&&f<u[n]});return!d&&{value:l.join(\"\"),indexesOfPipedChars:n}}}Object.defineProperty(t,\"__esModule\",{value:!0}),t.default=n;var r=[31,31,29,31,30,31,30,31,31,30,31,30,31],i=[\"yyyy\",\"yy\",\"mm\",\"dd\",\"HH\",\"MM\",\"SS\"]},function(e,t){\"use strict\";function n(){function e(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a,t=e.length;if(e===a||e[0]===g[0]&&1===t)return g.split(a).concat([v]).concat(h.split(a));if(e===P&&_)return g.split(a).concat([\"0\",P,v]).concat(h.split(a));var n=e[0]===s&&D;n&&(e=e.toString().substr(1));var u=e.lastIndexOf(P),c=u!==-1,l=void 0,m=void 0,b=void 0;if(e.slice($*-1)===h&&(e=e.slice(0,$*-1)),c&&(_||I)?(l=e.slice(e.slice(0,N)===g?N:0,u),m=e.slice(u+1,t),m=r(m.replace(f,a))):l=e.slice(0,N)===g?e.slice(N):e,L&&(\"undefined\"==typeof L?\"undefined\":o(L))===p){var O=\".\"===S?\"[.]\":\"\"+S,M=(l.match(new RegExp(O,\"g\"))||[]).length;l=l.slice(0,L+M*V)}return l=l.replace(f,a),R||(l=l.replace(/^0+(0$|[^0])/,\"$1\")),l=x?i(l,S):l,b=r(l),(c&&_||I===!0)&&(e[u-1]!==P&&b.push(y),b.push(P,y),m&&((\"undefined\"==typeof C?\"undefined\":o(C))===p&&(m=m.slice(0,C)),b=b.concat(m)),I===!0&&e[u-1]===P&&b.push(v)),N>0&&(b=g.split(a).concat(b)),n&&(b.length===N&&b.push(v),b=[d].concat(b)),h.length>0&&(b=b.concat(h.split(a))),b}var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.prefix,g=void 0===n?u:n,m=t.suffix,h=void 0===m?a:m,b=t.includeThousandsSeparator,x=void 0===b||b,O=t.thousandsSeparatorSymbol,S=void 0===O?c:O,M=t.allowDecimal,_=void 0!==M&&M,j=t.decimalSymbol,P=void 0===j?l:j,w=t.decimalLimit,C=void 0===w?2:w,H=t.requireDecimal,I=void 0!==H&&H,k=t.allowNegative,D=void 0!==k&&k,E=t.allowLeadingZeroes,R=void 0!==E&&E,A=t.integerLimit,L=void 0===A?null:A,N=g&&g.length||0,$=h&&h.length||0,V=S&&S.length||0;return e.instanceOf=\"createNumberMask\",e}function r(e){return e.split(a).map(function(e){return v.test(e)?v:e})}function i(e,t){return e.replace(/\\B(?=(\\d{3})+(?!\\d))/g,t)}Object.defineProperty(t,\"__esModule\",{value:!0});var o=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e};t.default=n;var u=\"$\",a=\"\",c=\",\",l=\".\",s=\"-\",d=/-/,f=/\\D+/g,p=\"number\",v=/\\d/,y=\"[]\"},function(e,t,n){\"use strict\";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){e=e.replace(O,v);var n=t.placeholderChar,r=t.currentCaretPosition,i=e.indexOf(y),s=e.lastIndexOf(p),d=s<i?-1:s,f=o(e,i+1,y),g=o(e,d-1,p),m=u(e,i,n),h=a(e,i,d,n),b=c(e,d,n,r);m=l(m),h=l(h),b=l(b,!0);var x=m.concat(f).concat(h).concat(g).concat(b);return x}function o(e,t,n){var r=[];return e[t]===n?r.push(n):r.push(g,n),r.push(g),r}function u(e,t){return t===-1?e:e.slice(0,t)}function a(e,t,n,r){var i=v;return t!==-1&&(i=n===-1?e.slice(t+1,e.length):e.slice(t+1,n)),i=i.replace(new RegExp(\"[\\\\s\"+r+\"]\",h),v),i===y?f:i.length<1?m:i[i.length-1]===p?i.slice(0,i.length-1):i}function c(e,t,n,r){var i=v;return t!==-1&&(i=e.slice(t+1,e.length)),i=i.replace(new RegExp(\"[\\\\s\"+n+\".]\",h),v),0===i.length?e[t-1]===p&&r!==e.length?f:v:i}function l(e,t){return e.split(v).map(function(e){return e===m?e:t?x:b})}Object.defineProperty(t,\"__esModule\",{value:!0});var s=n(4),d=r(s),f=\"*\",p=\".\",v=\"\",y=\"@\",g=\"[]\",m=\" \",h=\"g\",b=/[^\\s]/,x=/[^.\\s]/,O=/\\s/g;t.default={mask:i,pipe:d.default}},function(e,t){\"use strict\";function n(e,t){var n=t.currentCaretPosition,o=t.rawValue,f=t.previousConformedValue,p=t.placeholderChar,v=e;v=r(v);var y=v.indexOf(a),g=null===o.match(new RegExp(\"[^@\\\\s.\"+p+\"]\"));if(g)return u;if(v.indexOf(l)!==-1||y!==-1&&n!==y+1||o.indexOf(i)===-1&&f!==u&&o.indexOf(c)!==-1)return!1;var m=v.indexOf(i),h=v.slice(m+1,v.length);return(h.match(d)||s).length>1&&v.substr(-1)===c&&n!==o.length&&(v=v.slice(0,v.length-1)),v}function r(e){var t=0;return e.replace(o,function(){return t++,1===t?i:u})}Object.defineProperty(t,\"__esModule\",{value:!0}),t.default=n;var i=\"@\",o=/@/g,u=\"\",a=\"@.\",c=\".\",l=\"..\",s=[],d=/\\./g}])});\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/text-mask-addons/dist/textMaskAddons.js?");
2016
+ eval("!function(e,t){ true?module.exports=t():0}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p=\"\",t(0)}([function(e,t,n){\"use strict\";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,\"__esModule\",{value:!0});var i=n(1);Object.defineProperty(t,\"createAutoCorrectedDatePipe\",{enumerable:!0,get:function(){return r(i).default}});var o=n(2);Object.defineProperty(t,\"createNumberMask\",{enumerable:!0,get:function(){return r(o).default}});var u=n(3);Object.defineProperty(t,\"emailMask\",{enumerable:!0,get:function(){return r(u).default}})},function(e,t){\"use strict\";function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"mm dd yyyy\",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.minYear,o=void 0===n?1:n,u=t.maxYear,a=void 0===u?9999:u,c=e.split(/[^dmyHMS]+/).sort(function(e,t){return i.indexOf(e)-i.indexOf(t)});return function(t){var n=[],i={dd:31,mm:12,yy:99,yyyy:a,HH:23,MM:59,SS:59},u={dd:1,mm:1,yy:0,yyyy:o,HH:0,MM:0,SS:0},l=t.split(\"\");c.forEach(function(t){var r=e.indexOf(t),o=parseInt(i[t].toString().substr(0,1),10);parseInt(l[r],10)>o&&(l[r+1]=l[r],l[r]=0,n.push(r))});var s=0,f=c.some(function(n){var c=e.indexOf(n),l=n.length,f=t.substr(c,l).replace(/\\D/g,\"\"),d=parseInt(f,10);\"mm\"===n&&(s=d||0);var p=\"dd\"===n?r[s]:i[n];if(\"yyyy\"===n&&(1!==o||9999!==a)){var y=parseInt(i[n].toString().substring(0,f.length),10),v=parseInt(u[n].toString().substring(0,f.length),10);return d<v||d>y}return d>p||f.length===l&&d<u[n]});return!f&&{value:l.join(\"\"),indexesOfPipedChars:n}}}Object.defineProperty(t,\"__esModule\",{value:!0}),t.default=n;var r=[31,31,29,31,30,31,30,31,31,30,31,30,31],i=[\"yyyy\",\"yy\",\"mm\",\"dd\",\"HH\",\"MM\",\"SS\"]},function(e,t){\"use strict\";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function r(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,r=t.length;if(t===l||t[0]===m[0]&&1===r)return m.split(l).concat([h]).concat(x.split(l));if(t===A&&w)return m.split(l).concat([\"0\",A,h]).concat(x.split(l));var c=t[0]===d&&D;c&&(t=t.toString().substr(1));var s=t.lastIndexOf(A),f=s!==-1,b=void 0,O=void 0,M=void 0;if(t.slice(q*-1)===x&&(t=t.slice(0,q*-1)),f&&(w||H)?(b=t.slice(t.slice(0,Y)===m?Y:0,s),O=t.slice(s+1,r),O=i(O.replace(y,l))):b=t.slice(0,Y)===m?t.slice(Y):t,L&&(\"undefined\"==typeof L?\"undefined\":a(L))===v){var j=\".\"===_?\"[.]\":\"\"+_,P=(b.match(new RegExp(j,\"g\"))||[]).length;b=b.slice(0,L+P*B)}if(b=b.replace(y,l),R||(b=b.replace(/^0+(0$|[^0])/,\"$1\")),b=S?o(b,_):b,M=i(b),(f&&w||H===!0)&&(t[s-1]!==A&&M.push(g),M.push(A,g),O&&((\"undefined\"==typeof I?\"undefined\":a(I))===v&&(O=O.slice(0,I)),M=M.concat(O)),H===!0&&t[s-1]===A&&M.push(h)),Y>0&&(M=m.split(l).concat(M)),c&&(M.length===Y&&M.push(h),M=[p].concat(M)),x.length>0&&(M=M.concat(x.split(l))),V&&/[eE]/.test(t)){var E=t.split(/[eE]/),C=u(E,2),k=C[0],N=C[1],$=k.match(/^[-+]?[0-9]*\\.?[0-9]+/),T=N&&N.match(/^[-+]?[0-9]+$/);if($&&(!N||T)){var Z=e($[0]),z=T?i(T[0]):[];return[].concat(n(Z),[\"e\"],n(z))}}return M}var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.prefix,m=void 0===r?c:r,b=t.suffix,x=void 0===b?l:b,O=t.includeThousandsSeparator,S=void 0===O||O,M=t.thousandsSeparatorSymbol,_=void 0===M?s:M,j=t.allowDecimal,w=void 0!==j&&j,P=t.decimalSymbol,A=void 0===P?f:P,E=t.decimalLimit,I=void 0===E?2:E,C=t.requireDecimal,H=void 0!==C&&C,k=t.allowNegative,D=void 0!==k&&k,N=t.allowLeadingZeroes,R=void 0!==N&&N,$=t.integerLimit,L=void 0===$?null:$,T=t.allowScientificNotation,V=void 0!==T&&T,Y=m&&m.length||0,q=x&&x.length||0,B=_&&_.length||0;return e.instanceOf=\"createNumberMask\",e}function i(e){return e.split(l).map(function(e){return h.test(e)?h:e})}function o(e,t){return e.replace(/\\B(?=(\\d{3})+(?!\\d))/g,t)}Object.defineProperty(t,\"__esModule\",{value:!0});var u=function(){function e(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var u,a=e[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&a.return&&a.return()}finally{if(i)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError(\"Invalid attempt to destructure non-iterable instance\")}}(),a=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e};t.default=r;var c=\"$\",l=\"\",s=\",\",f=\".\",d=\"-\",p=/-/,y=/\\D+/g,v=\"number\",h=/\\d/,g=\"[]\"},function(e,t,n){\"use strict\";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){e=e.replace(O,y);var n=t.placeholderChar,r=t.currentCaretPosition,i=e.indexOf(v),s=e.lastIndexOf(p),f=s<i?-1:s,d=o(e,i+1,v),h=o(e,f-1,p),g=u(e,i,n),m=a(e,i,f,n),b=c(e,f,n,r);g=l(g),m=l(m),b=l(b,!0);var x=g.concat(d).concat(m).concat(h).concat(b);return x}function o(e,t,n){var r=[];return e[t]===n?r.push(n):r.push(h,n),r.push(h),r}function u(e,t){return t===-1?e:e.slice(0,t)}function a(e,t,n,r){var i=y;return t!==-1&&(i=n===-1?e.slice(t+1,e.length):e.slice(t+1,n)),i=i.replace(new RegExp(\"[\\\\s\"+r+\"]\",m),y),i===v?d:i.length<1?g:i[i.length-1]===p?i.slice(0,i.length-1):i}function c(e,t,n,r){var i=y;return t!==-1&&(i=e.slice(t+1,e.length)),i=i.replace(new RegExp(\"[\\\\s\"+n+\".]\",m),y),0===i.length?e[t-1]===p&&r!==e.length?d:y:i}function l(e,t){return e.split(y).map(function(e){return e===g?e:t?x:b})}Object.defineProperty(t,\"__esModule\",{value:!0});var s=n(4),f=r(s),d=\"*\",p=\".\",y=\"\",v=\"@\",h=\"[]\",g=\" \",m=\"g\",b=/[^\\s]/,x=/[^.\\s]/,O=/\\s/g;t.default={mask:i,pipe:f.default}},function(e,t){\"use strict\";function n(e,t){var n=t.currentCaretPosition,o=t.rawValue,d=t.previousConformedValue,p=t.placeholderChar,y=e;y=r(y);var v=y.indexOf(a),h=null===o.match(new RegExp(\"[^@\\\\s.\"+p+\"]\"));if(h)return u;if(y.indexOf(l)!==-1||v!==-1&&n!==v+1||o.indexOf(i)===-1&&d!==u&&o.indexOf(c)!==-1)return!1;var g=y.indexOf(i),m=y.slice(g+1,y.length);return(m.match(f)||s).length>1&&y.substr(-1)===c&&n!==o.length&&(y=y.slice(0,y.length-1)),y}function r(e){var t=0;return e.replace(o,function(){return t++,1===t?i:u})}Object.defineProperty(t,\"__esModule\",{value:!0}),t.default=n;var i=\"@\",o=/@/g,u=\"\",a=\"@.\",c=\".\",l=\"..\",s=[],f=/\\./g}])});\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/text-mask-addons/dist/textMaskAddons.js?");
2006
2017
 
2007
2018
  /***/ }),
2008
2019
 
@@ -5083,7 +5094,7 @@ eval("\n\nfunction hash(str) {\n var hash = 5381,\n i = str.length;\n\n
5083
5094
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5084
5095
 
5085
5096
  "use strict";
5086
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = exports.FormioPathType = void 0;\nconst fetch_ponyfill_1 = __importDefault(__webpack_require__(/*! fetch-ponyfill */ \"./node_modules/fetch-ponyfill/build/fetch-browser.js\"));\nconst fastCloneDeep_1 = __webpack_require__(/*! ../utils/fastCloneDeep */ \"./node_modules/@formio/core/lib/utils/fastCloneDeep.js\");\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\nconst formUtil_1 = __webpack_require__(/*! ../utils/formUtil */ \"./node_modules/@formio/core/lib/utils/formUtil/index.js\");\nconst jwtDecode_1 = __webpack_require__(/*! ../utils/jwtDecode */ \"./node_modules/@formio/core/lib/utils/jwtDecode.js\");\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst browser_cookies_1 = __importDefault(__webpack_require__(/*! browser-cookies */ \"./node_modules/browser-cookies/src/browser-cookies.js\"));\nconst { fetch, Headers } = (0, fetch_ponyfill_1.default)();\nconst Plugins_1 = __importDefault(__webpack_require__(/*! ./Plugins */ \"./node_modules/@formio/core/lib/sdk/Plugins.js\"));\n/**\n * The different path types for a project.\n */\nvar FormioPathType;\n(function (FormioPathType) {\n FormioPathType[\"Subdirectories\"] = \"Subdirectories\";\n FormioPathType[\"Subdomains\"] = \"Subdomains\";\n})(FormioPathType || (exports.FormioPathType = FormioPathType = {}));\n/**\n * The Formio interface class. This is a minimalistic API library that allows you to work with the Form.io API's within JavaScript.\n *\n * ## Usage\n * Creating an instance of Formio is simple, and takes only a path (URL String). The path can be different, depending on the desired output.\n * The Formio instance can also access higher level operations, depending on how granular of a path you start with.\n *\n * ```ts\n * var formio = new Formio(<endpoint>, [options]);\n * ```\n *\n * Where **endpoint** is any valid API endpoint within Form.io. These URL's can provide a number of different methods depending on the granularity of the endpoint. This allows you to use the same interface but have access to different methods depending on how granular the endpoint url is.\n * **options** is defined within the {link Formio.constructor} documentation.\n *\n * Here is an example of how this library can be used to load a form JSON from the Form.io API's\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n */\nclass Formio {\n /**\n * @constructor\n * @param {string} path - A project, form, and submission API Url.\n * @param {FormioOptions} options - Available options to configure the Javascript API.\n */\n constructor(path, options = {}) {\n this.path = path;\n this.options = options;\n /**\n * The base API url of the Form.io Platform. Example: https://api.form.io\n */\n this.base = '';\n /**\n * The Projects Endpoint derived from the provided source.\n *\n * @example https://api.form.io/project\n */\n this.projectsUrl = '';\n /**\n * A specific project endpoint derived from the provided source.\n *\n * @example https://examples.form.io\n */\n this.projectUrl = '';\n /**\n * The Project ID found within the provided source.\n */\n this.projectId = '';\n /**\n * A specific Role URL provided the source.\n *\n * @example https://examples.form.io/role/2342343234234234\n */\n this.roleUrl = '';\n /**\n * The roles endpoint derived from the provided source.\n *\n * @example https://examples.form.io/role\n */\n this.rolesUrl = '';\n /**\n * The roleID derieved from the provided source.\n */\n this.roleId = '';\n /**\n * A specific form url derived from the provided source.\n *\n * @example https://examples.form.io/example\n */\n this.formUrl = '';\n /**\n * The forms url derived from the provided source.\n *\n * @example https://example.form.io/form\n */\n this.formsUrl = '';\n /**\n * The Form ID derived from the provided source.\n */\n this.formId = '';\n /**\n * The submissions URL derived from the provided source.\n *\n * @example https://examples.form.io/example/submission\n */\n this.submissionsUrl = '';\n /**\n * A specific submissions URL derived from a provided source.\n *\n * @example https://examples.form.io/example/submission/223423423423\n */\n this.submissionUrl = '';\n /**\n * The submission ID provided a submission url.\n */\n this.submissionId = '';\n /**\n * The actions url provided a form url as the source.\n *\n * @example https://examples.form.io/example/action\n */\n this.actionsUrl = '';\n /**\n * The Action ID derived from a provided Action url.\n */\n this.actionId = '';\n /**\n * A specific action api endoint.\n */\n this.actionUrl = '';\n this.vsUrl = '';\n this.vId = '';\n this.vUrl = '';\n /**\n * The query string derived from the provided src url.\n */\n this.query = '';\n /**\n * If this is a non-project url, such is the case for Open Source API.\n */\n this.noProject = false;\n // Ensure we have an instance of Formio.\n if (!(this instanceof Formio)) {\n return new Formio(path);\n }\n if (options.useSessionToken) {\n Formio.useSessionToken(options);\n }\n if (options.hasOwnProperty('base') && options.base) {\n this.base = options.base;\n }\n else if (Formio.baseUrl) {\n this.base = Formio.baseUrl;\n }\n else if (window && window.location) {\n const match = window.location.href.match(/http[s]?:\\/\\/api./);\n this.base = match ? match[0] : window.location.origin;\n }\n if (!path) {\n // Allow user to create new projects if this was instantiated without\n // a url\n this.projectUrl = Formio.projectUrl || `${this.base}/project`;\n this.projectsUrl = `${this.base}/project`;\n this.projectId = '';\n this.query = '';\n return;\n }\n if (options.hasOwnProperty('project') && options.project) {\n this.projectUrl = options.project;\n }\n const project = this.projectUrl || Formio.projectUrl;\n const projectRegEx = /(^|\\/)(project)($|\\/[^/]+)/;\n const isProjectUrl = path.search(projectRegEx) !== -1;\n // The baseURL is the same as the projectUrl, and does not contain \"/project/MONGO_ID\" in\n // its domain. This is almost certainly against the Open Source server.\n if (project && this.base === project && !isProjectUrl) {\n this.noProject = true;\n this.projectUrl = this.base;\n }\n // Normalize to an absolute path.\n if (path.indexOf('http') !== 0 && path.indexOf('//') !== 0) {\n path = this.base + path;\n }\n const hostparts = this.getUrlParts(path);\n let hostName = '';\n let parts = [];\n if (hostparts) {\n hostName = hostparts[1] + hostparts[2];\n path = hostparts.length > 3 ? hostparts[3] : '';\n const queryparts = path.split('?');\n if (queryparts.length > 1) {\n path = queryparts[0];\n this.query = `?${queryparts[1]}`;\n }\n }\n // Register a specific path.\n const registerPath = (name, base) => {\n this[`${name}sUrl`] = `${base}/${name}`;\n const regex = new RegExp(`/${name}/([^/]+)`);\n if (path && path.search(regex) !== -1) {\n parts = path.match(regex);\n this[`${name}Url`] = parts ? base + parts[0] : '';\n this[`${name}Id`] = parts.length > 1 ? parts[1] : '';\n base += parts[0];\n }\n return base;\n };\n // Register an array of items.\n const registerItems = (items, base, staticBase) => {\n for (const i in items) {\n if (items.hasOwnProperty(i)) {\n const item = items[i];\n if (Array.isArray(item)) {\n registerItems(item, base, true);\n }\n else {\n const newBase = registerPath(item, base);\n base = staticBase ? base : newBase;\n }\n }\n }\n };\n if (!this.projectUrl || this.projectUrl === this.base) {\n // If a project uses Subdirectories path type, we need to specify a projectUrl\n if (!this.projectUrl && !isProjectUrl && Formio.pathType === 'Subdirectories') {\n const regex = `^${hostName.replace(/\\//g, '\\\\/')}.[^/]+`;\n const match = project.match(new RegExp(regex));\n this.projectUrl = match ? match[0] : hostName;\n }\n else {\n this.projectUrl = hostName;\n }\n }\n // Check if we have a specified path type.\n let isNotSubdomainType = false;\n if (Formio.pathType) {\n isNotSubdomainType = Formio.pathType !== 'Subdomains';\n }\n if (!this.noProject) {\n // Determine the projectUrl and projectId\n if (isProjectUrl) {\n // Get project id as project/:projectId.\n registerItems(['project'], hostName);\n path = path.replace(projectRegEx, '');\n }\n else if (hostName === this.base) {\n // Get project id as first part of path (subdirectory).\n if (hostparts && hostparts.length > 3 && path.split('/').length > 1) {\n const isFile = path.match(/.json/);\n const pathParts = path.split('/');\n if (isFile) {\n this.projectUrl = hostName;\n }\n else {\n pathParts.shift(); // Throw away the first /.\n const projectId = pathParts.shift();\n if (projectId) {\n this.projectId = projectId;\n path = `/${pathParts.join('/')}`;\n this.projectUrl = `${hostName}/${this.projectId}`;\n }\n }\n }\n }\n else {\n // Get project id from subdomain.\n if (hostparts &&\n hostparts.length > 2 &&\n (hostparts[2].split('.').length > 2 || hostName.includes('localhost')) &&\n !isNotSubdomainType) {\n this.projectUrl = hostName;\n this.projectId = hostparts[2].split('.')[0];\n }\n }\n this.projectsUrl = this.projectsUrl || `${this.base}/project`;\n }\n // Configure Role urls and role ids.\n registerItems(['role'], this.projectUrl);\n // Configure Form urls and form ids.\n if (/(^|\\/)(form)($|\\/)/.test(path)) {\n registerItems(['form', ['submission', 'action', 'v']], this.projectUrl);\n }\n else {\n const subRegEx = new RegExp('/(submission|action|v)($|/.*)');\n const subs = path.match(subRegEx);\n if (subs && subs.length > 1) {\n this.pathType = subs[1];\n }\n path = path.replace(subRegEx, '');\n path = path.replace(/\\/$/, '');\n this.formsUrl = `${this.projectUrl}/form`;\n this.formUrl = path ? this.projectUrl + path : '';\n this.formId = path.replace(/^\\/+|\\/+$/g, '');\n const items = ['submission', 'action', 'v'];\n for (const i in items) {\n if (items.hasOwnProperty(i)) {\n const item = items[i];\n this[`${item}sUrl`] = `${this.projectUrl + path}/${item}`;\n if (this.pathType === item && subs && subs.length > 2 && subs[2]) {\n this[`${item}Id`] = subs[2].replace(/^\\/+|\\/+$/g, '');\n this[`${item}Url`] = this.projectUrl + path + subs[0];\n }\n }\n }\n }\n // Set the app url if it is not set.\n if (!Formio.projectUrlSet) {\n Formio.projectUrl = this.projectUrl;\n }\n }\n /**\n * Deletes a remote resource of any provided type.\n *\n * @param {string} type - The type of resource to delete. \"submission\", \"form\", etc.\n * @param {object} options - The options passed to {@link Formio.request}\n * @return {Promise<Response>}\n */\n delete(type, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n if (!this[_id]) {\n return Promise.reject('Nothing to delete');\n }\n Formio.cache = {};\n return this.makeRequest(type, this[_url], 'delete', null, opts);\n }\n /**\n * Returns the index (array of records) for any provided type.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} query - A query object to pass to the request.\n * @param {object} query.params - A map (key-value pairs) of URL query parameters to add to the url.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n index(type, query, opts) {\n const _url = `${type}Url`;\n query = query || '';\n if (query && (0, lodash_1.isObject)(query)) {\n query = `?${Formio.serialize(query.params)}`;\n }\n return this.makeRequest(type, this[_url] + query, 'get', null, opts);\n }\n /**\n * Save a document record using \"upsert\". If the document does not exist, it will be created, if the _id is provided,\n * it will be updated.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} data - The resource data object.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n save(type, data, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n const method = this[_id] || data._id ? 'put' : 'post';\n let reqUrl = this[_id] ? this[_url] : this[`${type}sUrl`];\n if (!this[_id] && data._id && method === 'put' && !reqUrl.includes(data._id)) {\n reqUrl += `/${data._id}`;\n }\n Formio.cache = {};\n return this.makeRequest(type, reqUrl + this.query, method, data, opts);\n }\n /**\n * @summary Load (GET) a document record.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} query - A query object to pass to the request.\n * @param {object} query.params - A map (key-value pairs) of URL query parameters to add to the url.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n load(type, query, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n if (query && (0, lodash_1.isObject)(query)) {\n query = Formio.serialize(query.params);\n }\n if (query) {\n query = this.query ? `${this.query}&${query}` : `?${query}`;\n }\n else {\n query = this.query;\n }\n if (!this[_id]) {\n return Promise.reject(`Missing ${_id}`);\n }\n let url = this[_url] + query;\n if (type === 'form' && !isNaN(parseInt(this.vId))) {\n url += url.indexOf('?') === -1 ? '?' : '&';\n url += `formRevision=${this.vId}`;\n }\n return this.makeRequest(type, url, 'get', null, opts);\n }\n /**\n * @summary Call {@link Formio.makeRequest} for this Formio instance.\n *\n * @param {string} type - The request resource type. \"submission\", \"form\", etc.\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>}\n */\n makeRequest(type, url, method, data, opts) {\n return Formio.makeRequest(this, type, url, method, data, opts);\n }\n /**\n * @summary Loads a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadProject().then((project) => {\n * console.log(project);\n * });\n * ```\n *\n * @param {object} query - Query parameters to pass to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadProject(query, opts) {\n return this.load('project', query, opts);\n }\n /**\n * Saves or Updates a project.\n *\n * ### Create a new project\n * ```ts\n * const formio = new Formio();\n * formio.saveProject({\n * title: 'My Project',\n * path: 'myproject',\n * name: 'myproject'\n * });\n * ```\n *\n * ### Update an existing project\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadProject().then((project) => {\n * project.title = 'Title changed';\n * formio.saveProject(project).then(() => {\n * console.log('Done saving project!');\n * });\n * });\n * ```\n *\n * @param {object} data - The project JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveProject(data, opts) {\n return this.save('project', data, opts);\n }\n /**\n * Deletes a project\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.deleteProject();\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n deleteProject(opts) {\n return this.delete('project', opts);\n }\n /**\n * Loads a list of all projects.\n *\n * ```ts\n * Formio.loadProjects().then((projects) => {\n * console.log(projects);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {*}\n */\n static loadProjects(query, opts) {\n query = query || '';\n if ((0, lodash_1.isObject)(query)) {\n query = `?${Formio.serialize(query.params)}`;\n }\n return Formio.makeStaticRequest(`${Formio.baseUrl}/project${query}`, 'GET', null, opts);\n }\n /**\n * Loads a role within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/role/234234234234');\n * formio.loadRole().then((role) => {\n * console.log(role);\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadRole(opts) {\n return this.load('role', null, opts);\n }\n /**\n * Create a new or Update an existing role within a project.\n *\n * ### Create new Role example\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.saveRole({\n * title: 'Employee',\n * description: 'A person who belongs to a company.'\n * }).then((role) => {\n * console.log(role);\n * });\n * ```\n *\n * ### Update existing role example\n * ```ts\n * const formio = new Formio('https://examples.form.io/role/234234234234234');\n * formio.loadRole().then((role) => {\n * role.title = 'Manager';\n * formio.saveRole(role).then(() => {\n * console.log('DONE');\n * });\n * });\n * ```\n *\n * @param {object} role - The Role JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveRole(data, opts) {\n return this.save('role', data, opts);\n }\n /**\n * Deletes a role within a project.\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteRole(opts) {\n return this.delete('role', opts);\n }\n /**\n * Load all roles within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadRoles().then((roles) => {\n * console.log(roles);\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadRoles(opts) {\n return this.index('roles', null, opts);\n }\n /**\n * Loads a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n loadForm(query, opts) {\n return this.load('form', query, opts).then((currentForm) => {\n // Check to see if there isn't a number in vId.\n if (!currentForm.revisions || isNaN(parseInt(this.vId))) {\n return currentForm;\n }\n // If a submission already exists but form is marked to load current version of form.\n if (currentForm.revisions === 'current' && this.submissionId) {\n return currentForm;\n }\n if (currentForm._vid == this.vId || currentForm.revisionId === this.vId) {\n return currentForm;\n }\n // If they specified a revision form, load the revised form components.\n if (query && (0, lodash_1.isObject)(query)) {\n query = Formio.serialize(query.params);\n }\n if (query) {\n query = this.query ? `${this.query}&${query}` : `?${query}`;\n }\n else {\n query = this.query;\n }\n return (this.makeRequest('form', this.vUrl + query, 'get', null, opts)\n .then((revisionForm) => {\n currentForm._vid = revisionForm._vid;\n currentForm.components = revisionForm.components;\n currentForm.settings = revisionForm.settings;\n currentForm.revisionId = revisionForm.revisionId;\n // Using object.assign so we don't cross polinate multiple form loads.\n return Object.assign({}, currentForm);\n })\n // If we couldn't load the revision, just return the original form.\n .catch(() => Object.assign({}, currentForm)));\n });\n }\n /**\n * Create or Update a specific form.\n *\n * ### Create form example\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.saveForm({\n * title: 'Employee',\n * type: 'resource',\n * path: 'employee',\n * name: 'employee',\n * components: [\n * {\n * type: 'textfield',\n * key: 'firstName',\n * label: 'First Name'\n * },\n * {\n * type: 'textfield',\n * key: 'lastName',\n * label: 'Last Name'\n * }\n * ]\n * });\n * ```\n *\n * ### Update a form example\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * form.title = 'Changed Title';\n * formio.saveForm(form).then(() => {\n * console.log('DONE!!!');\n * });\n * });\n * ```\n *\n * @param {object} data - The Form JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveForm(data, opts) {\n return this.save('form', data, opts);\n }\n /**\n * Deletes a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.deleteForm().then(() => {\n * console.log('Deleted!');\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteForm(opts) {\n return this.delete('form', opts);\n }\n /**\n * Loads all forms within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadForms().then((forms) => {\n * console.log(forms);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadForms(query, opts) {\n return this.index('forms', query, opts);\n }\n /**\n * Loads a specific submissionn.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/23423423423423423');\n * formio.loadSubmission().then((submission) => {\n * console.log(submission);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n loadSubmission(query, opts) {\n return this.load('submission', query, opts).then((submission) => {\n this.vId = submission._frid || submission._fvid;\n this.vUrl = `${this.formUrl}/v/${this.vId}`;\n return submission;\n });\n }\n /**\n * Creates a new or Updates an existing submission.\n *\n * ### Create a new submission\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.saveSubmission({\n * data: {\n * firstName: 'Joe',\n * lastName: 'Smith'\n * }\n * }).then((submission) => {\n * // This will now be the complete submission object saved on the server.\n * console.log(submission);\n * });\n * ```\n *\n * ### Update an existing submission\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/23423423423423423');\n * formio.loadSubmission().then((submission) => {\n * submission.data.lastName = 'Thompson';\n * formio.saveSubmission(submission).then(() => {\n * console.log('DONE');\n * });\n * });\n * ```\n *\n * @param {object} data - The submission JSON object.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveSubmission(data, opts) {\n if (!isNaN(parseInt(this.vId)) && !data._fvid) {\n data._fvid = this.vId;\n }\n return this.save('submission', data, opts);\n }\n /**\n * Deletes a submission.\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteSubmission(opts) {\n return this.delete('submission', opts);\n }\n /**\n * Loads all submissions within a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadSubmissions({\n * params: {\n * limit: 25,\n * 'data.lastName__regex': 'smith'\n * }\n * }).then((submissions) => {\n * // Should print out 25 submissions where the last name contains \"smith\".\n * console.log(submissions);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadSubmissions(query, opts) {\n return this.index('submissions', query, opts);\n }\n /**\n * Loads a form action.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.loadAction().then((action) => {\n * console.log(action);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadAction(query, opts) {\n return this.load('action', query, opts);\n }\n /**\n * Create a new or update an existing action.\n *\n * ### Create a new action for a form.\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.saveAction({\n * data: {\n * name: 'webhook',\n * title: 'Webhook Action',\n * method: ['create', 'update', 'delete'],\n * handler: ['after'],\n * condition: {},\n * settings: {\n * url: 'https://example.com',\n * headers: [{}],\n * block: false,\n * forwardHeaders: false\n * }\n * }\n * }).then((action) => {\n * console.log(action);\n * });\n * ```\n *\n * ### Update an action\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.loadAction().then((action) => {\n * action.title = 'Updated title';\n * formio.saveAction(action).then(() => {\n * console.log('Done!');\n * });\n * });\n * ```\n *\n * @param {object} data - The action JSON\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveAction(data, opts) {\n return this.save('action', data, opts);\n }\n /**\n * Delete an action\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.deleteAction().then(() => {\n * console.log('Action was deleted.');\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteAction(opts) {\n return this.delete('action', opts);\n }\n /**\n * Loads all actions within a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadActions().then((actions) => {\n * console.log(actions);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadActions(query, opts) {\n return this.index('actions', query, opts);\n }\n /**\n * Returns a list of available actions\n *\n * @return {Promise<Response>}\n */\n availableActions() {\n return this.makeRequest('availableActions', `${this.formUrl}/actions`);\n }\n /**\n * Returns the action information for a specific action, such as \"save\".\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/actions/save');\n * formio.actionInfo().then((info) => {\n * console.log(info);\n * });\n * ```\n *\n * @param {string} name - The name of the action you would like to get information for. i.e. \"save\", \"webhook\", etc.\n * @return {Promise<Response>}\n */\n actionInfo(name) {\n return this.makeRequest('actionInfo', `${this.formUrl}/actions/${name}`);\n }\n /**\n * Determine if a string ID is a valid MongoID.\n *\n * @param {string} id - The id that should be tested if it is avalid id.\n * @return {boolean} - true if it is a valid MongoId, false otherwise.\n */\n isObjectId(id) {\n const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');\n return checkForHexRegExp.test(id);\n }\n /**\n * Get the project ID of project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.getProjectId().then((projectId) => {\n * console.log(projectId);\n * };\n * ```\n *\n * @return {Promise<string>}\n */\n getProjectId() {\n if (!this.projectId) {\n return Promise.resolve('');\n }\n if (this.isObjectId(this.projectId)) {\n return Promise.resolve(this.projectId);\n }\n else {\n return this.loadProject().then((project) => {\n return project._id;\n });\n }\n }\n /**\n * Get the ID of a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.getFormId().then((formId) => {\n * console.log(formId);\n * });\n * ```\n *\n * @return {Promise<string>}\n */\n getFormId() {\n if (!this.formId) {\n return Promise.resolve('');\n }\n if (this.isObjectId(this.formId)) {\n return Promise.resolve(this.formId);\n }\n else {\n return this.loadForm().then((form) => {\n return form._id;\n });\n }\n }\n /**\n * Instance method for {@link Formio.currentUser}\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n currentUser(options) {\n return Formio.currentUser(this, options);\n }\n /**\n * Instance method for {@link Formio.accessInfo}\n *\n * @return {Promise<Response>}\n */\n accessInfo() {\n return Formio.accessInfo(this);\n }\n /**\n * Sets OAuth Logout URL.\n *\n * @param {string} uri - Logout URL.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string}\n */\n oauthLogoutURI(uri, options) {\n return Formio.oauthLogoutURI(uri, Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Returns the JWT token for this instance.\n *\n * @param {object} options - The following options are provided.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string} - The JWT token for this user.\n */\n getToken(options) {\n return Formio.getToken(Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Sets the JWT token for this instance.\n *\n * @param {string} token - The JWT token to set.\n * @param {object} options - The following options are provided.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string} - The JWT token that was set.\n */\n setToken(token, options) {\n return Formio.setToken(token, Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Returns a temporary authentication token for single purpose token generation.\n *\n * @param {number|string} expire - The amount of seconds to wait before this temp token expires.\n * @param {string} allowed - The allowed path string inn the format GET:/path\n * @param {object} options - The options passed to {@link Formio#getToken}\n */\n getTempToken(expire, allowed, options) {\n const token = Formio.getToken(options);\n if (!token) {\n return Promise.reject('You must be authenticated to generate a temporary auth token.');\n }\n const authUrl = Formio.authUrl || this.projectUrl;\n return this.makeRequest('tempToken', `${authUrl}/token`, 'GET', null, {\n ignoreCache: true,\n header: new Headers({\n 'x-expire': expire,\n 'x-allow': allowed,\n }),\n });\n }\n /**\n * Get a PDF download url for a submission, which will generate a new PDF of the submission. This method will first\n * fetch a temporary download token, and then append this to the download url for this form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/324234234234234');\n * formio.getDownloadUrl().then((url) => {\n * console.log(url);\n * });\n * ```\n *\n * @param {object} [form] - The form JSON to fetch a download url for.\n * @return {Promise<string>} - The download url.\n */\n getDownloadUrl(form) {\n if (!this.submissionId) {\n return Promise.resolve('');\n }\n if (!form) {\n // Make sure to load the form first.\n return this.loadForm().then((_form) => {\n if (!_form) {\n return '';\n }\n return this.getDownloadUrl(_form);\n });\n }\n let apiUrl = `/project/${form.project}`;\n apiUrl += `/form/${form._id}`;\n apiUrl += `/submission/${this.submissionId}`;\n const postfix = form.submissionRevisions && form.settings.changeLog ? '/download/changelog' : '/download';\n apiUrl += postfix;\n let download = this.base + apiUrl;\n return new Promise((resolve, reject) => {\n this.getTempToken(3600, `GET:${apiUrl}`)\n .then((tempToken) => {\n download += `?token=${tempToken.key}`;\n resolve(download);\n }, () => {\n resolve(download);\n })\n .catch(reject);\n });\n }\n /**\n * Returns the user permissions to a form and submission.\n *\n * @param user - The user or current user if undefined. For anonymous, use \"null\"\n * @param form - The form or current form if undefined. For no form check, use \"null\"\n * @param submission - The submisison or \"index\" if undefined.\n *\n * @return {{create: boolean, read: boolean, edit: boolean, delete: boolean}}\n */\n userPermissions(user, form, submission) {\n return Promise.all([\n form !== undefined ? Promise.resolve(form) : this.loadForm(),\n user !== undefined ? Promise.resolve(user) : this.currentUser(),\n submission !== undefined || !this.submissionId\n ? Promise.resolve(submission)\n : this.loadSubmission(),\n this.accessInfo(),\n ]).then((results) => {\n const form = results.shift();\n const user = results.shift() || { _id: false, roles: [] };\n const submission = results.shift();\n const access = results.shift();\n const permMap = {\n create: 'create',\n read: 'read',\n update: 'edit',\n delete: 'delete',\n };\n const perms = {\n user: user,\n form: form,\n access: access,\n create: false,\n read: false,\n edit: false,\n delete: false,\n };\n for (const roleName in access.roles) {\n if (access.roles.hasOwnProperty(roleName)) {\n const role = access.roles[roleName];\n if (role.default && user._id === false) {\n // User is anonymous. Add the anonymous role.\n user.roles.push(role._id);\n }\n else if (role.admin && user.roles.indexOf(role._id) !== -1) {\n perms.create = true;\n perms.read = true;\n perms.delete = true;\n perms.edit = true;\n return perms;\n }\n }\n }\n if (form && form.submissionAccess) {\n for (let i = 0; i < form.submissionAccess.length; i++) {\n const permission = form.submissionAccess[i];\n const [perm, scope] = permission.type.split('_');\n if (['create', 'read', 'update', 'delete'].includes(perm)) {\n if ((0, lodash_1.intersection)(permission.roles, user.roles).length) {\n perms[permMap[perm]] =\n scope === 'all' || !submission || user._id === submission.owner;\n }\n }\n }\n }\n // check for Group Permissions\n if (submission) {\n // we would anyway need to loop through components for create permission, so we'll do that for all of them\n (0, formUtil_1.eachComponent)(form.components, (component, path) => {\n if (component && component.defaultPermission) {\n const value = (0, lodash_1.get)(submission.data, path);\n // make it work for single-select Group and multi-select Group\n const groups = Array.isArray(value) ? value : [value];\n groups.forEach((group) => {\n if (group &&\n group._id && // group id is present\n user.roles.indexOf(group._id) > -1 // user has group id in his roles\n ) {\n if (component.defaultPermission === 'read') {\n perms[permMap.read] = true;\n }\n if (component.defaultPermission === 'create') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n }\n if (component.defaultPermission === 'write') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n perms[permMap.update] = true;\n }\n if (component.defaultPermission === 'admin') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n perms[permMap.update] = true;\n perms[permMap.delete] = true;\n }\n }\n });\n }\n });\n }\n return perms;\n });\n }\n /**\n * `Determine if the current user can submit a form.\n * @return {*}\n */\n canSubmit() {\n return this.userPermissions().then((perms) => {\n // If there is user and they cannot create, then check anonymous user permissions.\n if (!perms.create && Formio.getUser()) {\n return this.userPermissions(null).then((anonPerms) => {\n if (anonPerms.create) {\n Formio.setUser(null);\n return true;\n }\n return false;\n });\n }\n return perms.create;\n });\n }\n getUrlParts(url) {\n return Formio.getUrlParts(url, this);\n }\n static getUrlParts(url, formio) {\n const base = formio && formio.base ? formio.base : Formio.baseUrl;\n let regex = '^(http[s]?:\\\\/\\\\/)';\n if (base && url.indexOf(base) === 0) {\n regex += `(${base.replace(/^http[s]?:\\/\\//, '')})`;\n }\n else {\n regex += '([^/]+)';\n }\n regex += '($|\\\\/.*)';\n return url.match(new RegExp(regex));\n }\n static serialize(obj, _interpolate) {\n const str = [];\n const interpolate = (item) => {\n return _interpolate ? _interpolate(item) : item;\n };\n for (const p in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, p)) {\n str.push(`${encodeURIComponent(p)}=${encodeURIComponent(interpolate(obj[p]))}`);\n }\n }\n return str.join('&');\n }\n static getRequestArgs(formio, type, url, method, data, opts) {\n method = (method || 'GET').toUpperCase();\n if (!opts || !(0, lodash_1.isObject)(opts)) {\n opts = {};\n }\n const requestArgs = {\n url,\n method,\n data: data || null,\n opts,\n };\n if (type) {\n requestArgs.type = type;\n }\n if (formio) {\n requestArgs.formio = formio;\n }\n return requestArgs;\n }\n static makeStaticRequest(url, method, data, opts) {\n const requestArgs = Formio.getRequestArgs(null, '', url, method, data, opts);\n const request = Plugins_1.default.pluginWait('preRequest', requestArgs).then(() => Plugins_1.default.pluginGet('staticRequest', requestArgs).then((result) => {\n if ((0, lodash_1.isNil)(result)) {\n return Formio.request(requestArgs.url, requestArgs.method, requestArgs.data, requestArgs.opts.header, requestArgs.opts);\n }\n return result;\n }));\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', request, requestArgs);\n }\n /**\n * Make an API request and wrap that request with the Form.io Request plugin system. This is very similar to the\n * {Formio.request} method with a difference being that it will pass the request through the Form.io request plugin.\n *\n * @param {Formio} formio - An instance of the Formio class.\n * @param {string} type - The request resource type. \"submission\", \"form\", etc.\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>}\n */\n static makeRequest(formio, type, url, method, data, opts) {\n if (!formio) {\n return Formio.makeStaticRequest(url, method, data, opts);\n }\n const requestArgs = Formio.getRequestArgs(formio, type, url, method, data, opts);\n requestArgs.opts = requestArgs.opts || {};\n requestArgs.opts.formio = formio;\n //for Formio requests default Accept and Content-type headers\n if (!requestArgs.opts.headers) {\n requestArgs.opts.headers = {};\n }\n requestArgs.opts.headers = (0, lodash_1.defaults)(requestArgs.opts.headers, {\n Accept: 'application/json',\n 'Content-type': 'application/json',\n });\n const request = Plugins_1.default.pluginWait('preRequest', requestArgs).then(() => Plugins_1.default.pluginGet('request', requestArgs).then((result) => {\n if ((0, lodash_1.isNil)(result)) {\n return Formio.request(requestArgs.url, requestArgs.method, requestArgs.data, requestArgs.opts.header, requestArgs.opts);\n }\n return result;\n }));\n return Plugins_1.default.pluginAlter('wrapRequestPromise', request, requestArgs);\n }\n /**\n * Execute an API request to any external system. This is a wrapper around the Web fetch method.\n *\n * ```ts\n * Formio.request('https://examples.form.io').then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {Headers} header - An object of headers to pass to the request.\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>|*}\n */\n static request(url, method, data, header, opts) {\n if (!url) {\n return Promise.reject('No url provided');\n }\n method = (method || 'GET').toUpperCase();\n // For reverse compatibility, if they provided the ignoreCache parameter,\n // then change it back to the options format where that is a parameter.\n if ((0, lodash_1.isBoolean)(opts)) {\n opts = { ignoreCache: opts };\n }\n if (!opts || !(0, lodash_1.isObject)(opts)) {\n opts = {};\n }\n // Generate a cachekey.\n const cacheKey = btoa(encodeURI(url));\n // Get the cached promise to save multiple loads.\n if (!opts.ignoreCache && method === 'GET' && Formio.cache.hasOwnProperty(cacheKey)) {\n return Promise.resolve(Formio.cloneResponse(Formio.cache[cacheKey]));\n }\n if (url[0] === '/') {\n url = Formio.baseUrl + url;\n }\n // Set up and fetch request\n const headers = header ||\n new Headers(opts.headers || {\n Accept: 'application/json',\n 'Content-type': 'application/json',\n });\n const token = Formio.getToken(opts);\n if (token && !opts.noToken) {\n headers.set('x-jwt-token', token);\n }\n // The fetch-ponyfill can't handle a proper Headers class anymore. Change it back to an object.\n const headerObj = {};\n headers.forEach(function (value, name) {\n headerObj[name] = value;\n });\n let options = {\n method: method,\n headers: headerObj,\n mode: 'cors',\n };\n if (data) {\n options.body = JSON.stringify(data);\n }\n // Allow plugins to alter the options.\n options = Plugins_1.default.pluginAlter('requestOptions', options, url);\n if (options.namespace || Formio.namespace) {\n opts.namespace = options.namespace || Formio.namespace;\n }\n const requestToken = options.headers['x-jwt-token'];\n const result = Plugins_1.default.pluginAlter('wrapFetchRequestPromise', Formio.fetch(url, options), {\n url,\n method,\n data,\n opts,\n })\n .then((response) => {\n // Allow plugins to respond.\n response = Plugins_1.default.pluginAlter('requestResponse', response, Formio, data);\n if (!response.ok) {\n if (response.status === 440) {\n Formio.setToken(null, opts);\n Formio.events.emit('formio.sessionExpired', response.body || response);\n }\n else if (response.status === 401) {\n Formio.events.emit('formio.unauthorized', response.body || response);\n }\n else if (response.status === 416) {\n Formio.events.emit('formio.rangeIsNotSatisfiable', response.body || response);\n }\n else if (response.status === 504) {\n return Promise.reject(new Error('Network request failed'));\n }\n // Parse and return the error as a rejected promise to reject this promise\n return (response.headers.get('content-type').includes('application/json')\n ? response.json()\n : response.text()).then((error) => {\n return Promise.reject(error);\n });\n }\n // Handle fetch results\n const respToken = response.headers.get('x-jwt-token');\n // In some strange cases, the fetch library will return an x-jwt-token without sending\n // one to the server. This has even been debugged on the server to verify that no token\n // was introduced with the request, but the response contains a token. This is an Invalid\n // case where we do not send an x-jwt-token and get one in return for any GET request.\n let tokenIntroduced = false;\n if (method === 'GET' &&\n !requestToken &&\n respToken &&\n !opts.external &&\n !url.includes('token=') &&\n !url.includes('x-jwt-token=')) {\n console.warn('Token was introduced in request.');\n tokenIntroduced = true;\n }\n if (response.status >= 200 &&\n response.status < 300 &&\n respToken &&\n respToken !== '' &&\n !tokenIntroduced) {\n Formio.setToken(respToken, Object.assign(Object.assign({}, opts), { fromCurrent: opts.fromCurrent || !!requestToken }));\n }\n // 204 is no content. Don't try to .json() it.\n if (response.status === 204) {\n return {};\n }\n const getResult = response.headers.get('content-type').includes('application/json')\n ? response.json()\n : response.text();\n return getResult.then((result) => {\n // Add some content-range metadata to the result here\n let range = response.headers.get('content-range');\n if (range && (0, lodash_1.isObject)(result)) {\n range = range.split('/');\n if (range[0] !== '*') {\n const skipLimit = range[0].split('-');\n result.skip = Number(skipLimit[0]);\n result.limit = skipLimit[1] - skipLimit[0] + 1;\n }\n result.serverCount = range[1] === '*' ? range[1] : Number(range[1]);\n }\n if (!opts.getHeaders) {\n return result;\n }\n const headers = {};\n response.headers.forEach((item, key) => {\n headers[key] = item;\n });\n // Return the result with the headers.\n return {\n result,\n headers,\n };\n });\n })\n .then((result) => {\n if (opts.getHeaders) {\n return result;\n }\n // Cache the response.\n if (method === 'GET') {\n Formio.cache[cacheKey] = result;\n }\n return Formio.cloneResponse(result);\n })\n .catch((err) => {\n if (err === 'Bad Token' && opts.noToken !== false) {\n Formio.setToken(null, opts);\n Formio.events.emit('formio.badToken', err);\n }\n if (err.message) {\n err = new Error(`Could not connect to API server (${err.message}): ${url}`);\n err.networkError = true;\n }\n if (method === 'GET') {\n delete Formio.cache[cacheKey];\n }\n return Promise.reject(err);\n });\n return result;\n }\n // Needed to maintain reverse compatability...\n static get token() {\n return Formio.tokens.formioToken || '';\n }\n // Needed to maintain reverse compatability...\n static set token(token) {\n Formio.tokens.formioToken = token || '';\n }\n static useSessionToken(options) {\n if (typeof localStorage === 'undefined') {\n return;\n }\n const namespace = options;\n if (typeof options === 'object') {\n options = options.namespace;\n }\n const tokenName = `${namespace || Formio.namespace || 'formio'}Token`;\n const token = localStorage.getItem(tokenName);\n if (token) {\n localStorage.removeItem(tokenName);\n sessionStorage.setItem(tokenName, token);\n }\n const userName = `${namespace || Formio.namespace || 'formio'}User`;\n const user = localStorage.getItem(userName);\n if (user) {\n localStorage.removeItem(userName);\n sessionStorage.setItem(userName, user);\n }\n localStorage.setItem('useSessionToken', 'true');\n }\n /**\n * Sets the JWT in storage to be used within an application.\n *\n * @param {string} token - The JWT token to set.\n * @param {object} options - Options as follows\n * @param {string} options.namespace - The namespace to save the token within. i.e. \"formio\"\n * @param {Formio} options.formio - The Formio instance.\n * @return {Promise<object>|void}\n */\n static setToken(token = '', opts = {}) {\n token = token || '';\n opts = typeof opts === 'string' ? { namespace: opts } : opts || {};\n const tokenName = `${opts.namespace || Formio.namespace || 'formio'}Token`;\n if (!Formio.tokens) {\n Formio.tokens = {};\n }\n const storage = localStorage.getItem('useSessionToken') ? sessionStorage : localStorage;\n if (!token) {\n if (!opts.fromUser) {\n opts.fromToken = true;\n Formio.setUser(null, opts);\n }\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.removeItem(tokenName);\n }\n catch (ignoreErr) {\n browser_cookies_1.default.erase(tokenName, { path: '/' });\n }\n Formio.tokens[tokenName] = token;\n return Promise.resolve(null);\n }\n if (Formio.tokens[tokenName] !== token) {\n Formio.tokens[tokenName] = token;\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.setItem(tokenName, token);\n }\n catch (ignoreErr) {\n browser_cookies_1.default.set(tokenName, token, { path: '/' });\n }\n }\n // Return or updates the current user\n return Formio.currentUser(opts.formio, opts);\n }\n /**\n * Returns the token set within the application for the user.\n *\n * @param {object} options - The options as follows.\n * @param {string} options.namespace - The namespace of the token you wish to fetch.\n * @param {boolean} options.decode - If you would like the token returned as decoded JSON.\n * @return {*}\n */\n static getToken(options) {\n options = typeof options === 'string' ? { namespace: options } : options || {};\n const tokenName = `${options.namespace || Formio.namespace || 'formio'}Token`;\n const decodedTokenName = options.decode ? `${tokenName}Decoded` : tokenName;\n if (!Formio.tokens) {\n Formio.tokens = {};\n }\n if (Formio.tokens[decodedTokenName]) {\n return Formio.tokens[decodedTokenName];\n }\n try {\n const token = localStorage.getItem('useSessionToken')\n ? sessionStorage.getItem(tokenName)\n : localStorage.getItem(tokenName);\n Formio.tokens[tokenName] = token || '';\n if (options.decode) {\n Formio.tokens[decodedTokenName] = Formio.tokens[tokenName]\n ? (0, jwtDecode_1.jwtDecode)(Formio.tokens[tokenName])\n : {};\n return Formio.tokens[decodedTokenName];\n }\n return Formio.tokens[tokenName];\n }\n catch (ignoreError) {\n Formio.tokens[tokenName] = browser_cookies_1.default.get(tokenName);\n return '';\n }\n }\n /**\n * Sets the current user within the application cache.\n *\n * @param {object} user - JSON object of the user you wish to set.\n * @param {object} options - Options as follows\n * @param {string} options.namespace - The namespace of the tokens\n */\n static setUser(user, opts = {}) {\n const userName = `${opts.namespace || Formio.namespace || 'formio'}User`;\n const storage = localStorage.getItem('useSessionToken') ? sessionStorage : localStorage;\n if (!user) {\n if (!opts.fromToken) {\n opts.fromUser = true;\n Formio.setToken(null, opts);\n }\n // Emit an event on the cleared user.\n Formio.events.emit('formio.user', null);\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n return storage.removeItem(userName);\n }\n catch (ignoreError) {\n return browser_cookies_1.default.erase(userName, { path: '/' });\n }\n }\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.setItem(userName, JSON.stringify(user));\n }\n catch (ignoreError) {\n browser_cookies_1.default.set(userName, JSON.stringify(user), { path: '/' });\n }\n // Emit an event on the authenticated user.\n Formio.events.emit('formio.user', user);\n }\n /**\n * Returns the user JSON.\n *\n * @param {object} options - Options as follows\n * @param {string} namespace - The namespace of the tokens stored within this application.\n * @return {object} - The user object.\n */\n static getUser(options) {\n options = options || {};\n const userName = `${options.namespace || Formio.namespace || 'formio'}User`;\n try {\n return JSON.parse((localStorage.getItem('useSessionToken') ? sessionStorage : localStorage).getItem(userName) || '');\n }\n catch (ignoreError) {\n return JSON.parse(browser_cookies_1.default.get(userName));\n }\n }\n /**\n * Sets the BaseURL for the application.\n *\n * @description Every application developed using the JavaScript SDK must set both the {@link Formio.setBaseUrl} and\n * {@link Formio.setProjectUrl} methods. These two functions ensure that every URL passed into the constructor of this\n * class can determine the \"project\" context for which the application is running.\n *\n * Any Open Source server applications will set both the {@link Formio.setBaseUrl} and {@link Formio.setProjectUrl}\n * values will be the same value.\n *\n * ```ts\n * Formio.setBaseUrl('https://yourwebsite.com/forms');\n * Formio.setProjectUrl('https://yourwebsite.com/forms/project');\n *\n * // Now the Formio constructor will know what is the \"project\" and what is the form alias name. Without setBaseUrl\n * // and setProjectUrl, this would throw an error.\n *\n * const formio = new Formio('https://yourwebsite.com/forms/project/user');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {string} url - The URL of the Base API url.\n */\n static setBaseUrl(url) {\n Formio.baseUrl = url;\n if (!Formio.projectUrlSet) {\n Formio.projectUrl = url;\n }\n }\n /**\n * Returns the current base url described at {@link Formio.setBaseUrl}\n *\n * @return {string} - The base url of the application.\n */\n static getBaseUrl() {\n return Formio.baseUrl;\n }\n static setApiUrl(url) {\n return Formio.setBaseUrl(url);\n }\n static getApiUrl() {\n return Formio.getBaseUrl();\n }\n static setAppUrl(url) {\n console.warn('Formio.setAppUrl() is deprecated. Use Formio.setProjectUrl instead.');\n Formio.projectUrl = url;\n Formio.projectUrlSet = true;\n }\n /**\n * Sets the Project Url for the application. This is an important method that needs to be set for all applications. It\n * is documented @ {@link Formio.setBaseUrl}.\n *\n * @param {string} url - The project api url.\n */\n static setProjectUrl(url) {\n Formio.projectUrl = url;\n Formio.projectUrlSet = true;\n }\n /**\n * The Auth URL can be set to customize the authentication requests made from an application. By default, this is\n * just the same value as {@link Formio.projectUrl}\n *\n * @param {string} url - The authentication url\n */\n static setAuthUrl(url) {\n Formio.authUrl = url;\n }\n static getAppUrl() {\n console.warn('Formio.getAppUrl() is deprecated. Use Formio.getProjectUrl instead.');\n return Formio.projectUrl;\n }\n /**\n * Returns the Project url described at {@link Formio.setProjectUrl}\n *\n * @return {string|string} - The Project Url.\n */\n static getProjectUrl() {\n return Formio.projectUrl;\n }\n /**\n * Clears the runtime internal API cache.\n *\n * @description By default, the Formio class will cache all API requests in memory so that any subsequent requests\n * using GET method will return the cached results as long as the API URl is the same as what was cached previously.\n * This cache can be cleared using this method as follows.\n *\n * ```ts\n * Formio.clearCache();\n * ```\n *\n * Or, if you just wish to clear a single request, then the {@link Formio.request#options.ignoreCache} option can be\n * provided when making an API request as follows.\n *\n * ```ts\n * Formio.loadForm({}, {\n * ignoreCache: true\n * }).then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * Both of the following will ensure that a new request is made to the API server and that the results will not be\n * from the cached result.\n */\n static clearCache() {\n Formio.cache = {};\n }\n /**\n * Return the access information about a Project, such as the Role ID's for that project, and if the server is\n * configured to do so, the Form and Resource access configurations that the authenticated user has access to.\n *\n * @description This is useful for an application to determine the UI for a specific user to identify which forms they have\n * access to submit or read.\n *\n * @param {Formio} formio - The Formio instance.\n * @return {Promise<Response>}\n */\n static accessInfo(formio) {\n const projectUrl = formio ? formio.projectUrl : Formio.projectUrl;\n return Formio.makeRequest(formio, 'accessInfo', `${projectUrl}/access`);\n }\n /**\n * Returns an array of roles for the project, which includes the ID's and names of those roles.\n *\n * @param {Formio} formio - The Formio instance.\n * @return {Promise<Response>}\n */\n static projectRoles(formio) {\n const projectUrl = formio ? formio.projectUrl : Formio.projectUrl;\n return Formio.makeRequest(formio, 'projectRoles', `${projectUrl}/role`);\n }\n /**\n * Return the currentUser object. This will fetch the user from the server and respond with the Submission JSON\n * of that user object.\n *\n * @param {Formio} formio - The Formio instance\n * @param {object} options - The options passed to {@link Formio.getUser}\n * @return {Promise<R>|*}\n */\n static currentUser(formio, options = {}) {\n let authUrl = Formio.authUrl;\n if (!authUrl) {\n authUrl = formio ? formio.projectUrl : Formio.projectUrl || Formio.baseUrl;\n }\n authUrl += '/current';\n if (!options.ignoreCache || options.fromCurrent) {\n const user = Formio.getUser(options);\n if (user) {\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', Promise.resolve(user), {\n url: authUrl,\n method: 'GET',\n options,\n });\n }\n }\n const token = Formio.getToken(options);\n if ((!options || !options.external) && !token) {\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', Promise.resolve(null), {\n url: authUrl,\n method: 'GET',\n options,\n });\n }\n options.fromCurrent = true;\n return Formio.makeRequest(formio, 'currentUser', authUrl, 'GET', null, options).then((response) => {\n Formio.setUser(response, options);\n return response;\n });\n }\n /**\n * Performs a logout of the Form.io application. This will reset all cache, as well as make a request to the logout\n * endpoint of the Form.io api platform.\n *\n * @param {Formio} formio - A Formio instance.\n * @param {object} options - Options passed to both {@link Formio.setToken} as well as {@link Formio.setUser}\n * @return {Promise<Response>}\n */\n static logout(formio, options = {}) {\n options.formio = formio;\n const projectUrl = Formio.authUrl\n ? Formio.authUrl\n : formio\n ? formio.projectUrl\n : Formio.baseUrl;\n const logout = () => {\n Formio.setToken(null, options);\n Formio.setUser(null, options);\n Formio.clearCache();\n localStorage.removeItem('useSessionToken');\n };\n return Formio.makeRequest(formio, 'logout', `${projectUrl}/logout`)\n .then(function (result) {\n logout();\n if (result.shouldRedirect && result.url) {\n window.location.href = result.url;\n }\n return result;\n })\n .catch(function (err) {\n logout();\n throw err;\n });\n }\n /**\n * Returns the query passed to a page in JSON object format.\n *\n * @description For example, lets say you visit your application using\n * the url as follows.\n *\n * ```\n * https://yourapplication.com/?token=23423423423&username=Joe\n * ```\n *\n * The following code will provide your application with the following.\n *\n * ```ts\n * const query Formio.pageQuery();\n * console.log(query.token); // Will print 23423423423\n * console.log(query.username); // Will print Joe\n * ```\n *\n * @return {{}} - A JSON object representation of the query that was passed to the URL of an application.\n */\n static pageQuery() {\n const pageQuery = {};\n pageQuery.paths = [];\n const hashes = location.hash.substr(1).replace(/\\?/g, '&').split('&');\n let parts = [];\n location.search\n .substr(1)\n .split('&')\n .forEach(function (item) {\n parts = item.split('=');\n if (parts.length > 1) {\n pageQuery[parts[0]] = parts[1] && decodeURIComponent(parts[1]);\n }\n });\n hashes.forEach(function (item) {\n parts = item.split('=');\n if (parts.length > 1) {\n pageQuery[parts[0]] = parts[1] && decodeURIComponent(parts[1]);\n }\n else if (item.indexOf('/') === 0) {\n pageQuery.paths = item.substr(1).split('/');\n }\n });\n return pageQuery;\n }\n /**\n * Much like {@link Formio.currentUser}, but instead automatically injects the Bearer tokens into the headers to\n * perform a Token swap of the OAuth token which will then return the JWT token for that user.\n *\n * @param {Formio} formio - The Formio instance\n * @param {string} token - An OAuth Bearer token to use for a token swap between the OAuth provider and Form.io\n * @return {Promise<R>|*}\n */\n static oAuthCurrentUser(formio, token) {\n return Formio.currentUser(formio, {\n external: true,\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n }\n static oauthLogoutURI(uri, options) {\n options = typeof options === 'string' ? { namespace: options } : options || {};\n const logoutURIName = `${options.namespace || Formio.namespace || 'formio'}LogoutAuthUrl`;\n localStorage.setItem(logoutURIName, uri);\n return Formio.tokens[logoutURIName];\n }\n /**\n * Perform a SAML initialization.\n *\n * @description Typically, you would use the {@link Formio.ssoInit} method to perform this function\n * since this method is an alias for the following.\n *\n * ```ts\n * Formio.samlInit();\n * Formio.ssoInit('saml'); // This is the exact same thing as calling Formio.samlInit\n * ```\n *\n * This method will return false if the process is just starting. The code below is a typical block of code that is\n * used to automatically trigger the SAML authentication process within your application using a Button component.\n *\n * ```ts\n * if (Formio.pageQuery().saml) {\n * const sso = Formio.samlInit();\n * if (sso) {\n * sso.then((user) => {\n * // The SSO user is now loaded!\n * console.log(user);\n * });\n * }\n * }\n * ```\n *\n * You can then place the following code withiin the \"Custom\" action of a Button component on your form.\n *\n * ```ts\n * Formio.samlInit();\n * ```\n *\n * Now when you click on this button, it will start the handshake process with SAML, and once it returns, will pass\n * a \"saml\" query parameter back to your application which will execute the code to load the current user from SAML.\n *\n * @param {object} options - Options to pass to the SAML initialization process.\n * @param {string} options.relay - The URL that will be used as the authentication \"relay\" that occurs during a SAML handshake process.\n * @return {boolean|Promise<Object>|void}\n */\n static samlInit(options = {}) {\n const query = Formio.pageQuery();\n if (query.saml) {\n Formio.setUser(null);\n const retVal = Formio.setToken(query.saml);\n let uri = window.location.toString();\n uri = uri.substring(0, uri.indexOf('?'));\n if (window.location.hash) {\n uri += window.location.hash;\n }\n window.history.replaceState({}, document.title, uri);\n return retVal;\n }\n // Set the relay if not provided.\n if (!options.relay) {\n options.relay = window.location.href;\n }\n // go to the saml sso endpoint for this project.\n const authUrl = Formio.authUrl || Formio.projectUrl;\n window.location.href = `${authUrl}/saml/sso?relay=${encodeURI(options.relay)}`;\n return false;\n }\n /**\n * Perform an Okta Authentication process using the {@link https://developer.okta.com/code/javascript/okta_auth_sdk|Okta SDK}.\n *\n * @description This method does require that you first include the Okta JavaScript SDK within your application as follows.\n *\n * First you need to include the Okta Authentication script.\n *\n * ```html\n * <script src=\"https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/2.0.1/okta-auth-js.min.js\" type=\"text/javascript\"></script>\n * ```\n *\n * Then you can call this method as follows.\n *\n * ```ts\n * Formio.oktaInit();\n * ```\n *\n * @param {object} options - Options that are passed directly to the {@link https://github.com/okta/okta-auth-js#configuration-reference|Okta SDK constructor}\n * @param {constructor} options.OktaAuth - If the OktaAuth constructor is not provided global to the application, it can be provided to this method using this property.\n * @param {Formio} options.formio - The Formio instance.\n * @param {Array<string>} options.scopes - Scopes that are passed to the {@link https://github.com/okta/okta-auth-js#tokengetwithredirectoptions|getWithRedirect} method from the Okta SDK.\n * @return {Promise<Object>}\n */\n static oktaInit(options = {}) {\n if (typeof OktaAuth !== 'undefined') {\n options.OktaAuth = OktaAuth;\n }\n if (typeof options.OktaAuth === 'undefined') {\n const errorMessage = 'Cannot find OktaAuth. Please include the Okta JavaScript SDK within your application. See https://developer.okta.com/code/javascript/okta_auth_sdk for an example.';\n console.warn(errorMessage);\n return Promise.reject(errorMessage);\n }\n return new Promise((resolve, reject) => {\n const Okta = options.OktaAuth;\n delete options.OktaAuth;\n const authClient = new Okta(options);\n authClient.tokenManager\n .get('accessToken')\n .then((accessToken) => {\n if (accessToken) {\n resolve(Formio.oAuthCurrentUser(options.formio, accessToken.accessToken));\n }\n else if (location.hash) {\n authClient.token\n .parseFromUrl()\n .then((token) => {\n authClient.tokenManager.add('accessToken', token);\n resolve(Formio.oAuthCurrentUser(options.formio, token.accessToken));\n })\n .catch((err) => {\n console.warn(err);\n reject(err);\n });\n }\n else {\n authClient.token.getWithRedirect({\n responseType: 'token',\n scopes: options.scopes,\n });\n resolve(false);\n }\n })\n .catch((error) => {\n reject(error);\n });\n });\n }\n /**\n * A common static method to trigger any SSO processes. This method is really just an alias for other static methods.\n *\n * @param {('saml'|'okta')} type - The type of SSO to trigger. 'saml' is an alias for {@link Formio.samlInit}, and 'okta' is an alias for {@link Formio.oktaInit}.\n * @param {object} options - Options to pass to the specific sso methods\n * @return {*|Promise<Object>|boolean|void}\n */\n static ssoInit(type, options = {}) {\n switch (type) {\n case 'saml':\n return Formio.samlInit(options);\n case 'okta':\n return Formio.oktaInit(options);\n default:\n console.warn('Unknown SSO type');\n return Promise.reject('Unknown SSO type');\n }\n }\n /**\n * Lazy load a remote library dependency.\n *\n * @description This is useful for components that wish to lazy load a required library\n * by adding that library to the <scripts> section of the HTML webpage, and then provide a promise that will resolve\n * when the library becomes available for use.\n *\n * @example Load Google Maps API.\n * ```ts\n * Formio.requireLibrary('googleMaps', 'google.maps.Map', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap', true).then(() => {\n * // Once the promise resolves, the following can now be used within your application.\n * const map = new google.maps.Map(document.getElementById(\"map\"), {...});\n * });\n * ```\n *\n * @param {string} name - The internal name to give to the library you are loading. This is useful for caching the library for later use.\n * @param {string} property - The name of the global property that will be added to the global namespace once the library has been loaded. This is used to check to see if the property exists before resolving the promise that the library is ready for use.\n * @param {string} src - The URL of the library to lazy load.\n * @param {boolean} polling - Determines if polling should be used to determine if they library is ready to use. If set to false, then it will rely on a global callback called ${name}Callback where \"name\" is the first property passed to this method. When this is called, that will indicate when the library is ready. In most cases, you will want to pass true to this parameter to initiate a polling method to check for the library availability in the global context.\n * @return {Promise<object>} - A promise that will resolve when the plugin is ready to be used.\n */\n static requireLibrary(name, property, src, polling = false, onload) {\n if (!Formio.libraries.hasOwnProperty(name)) {\n Formio.libraries[name] = {};\n Formio.libraries[name].ready = new Promise((resolve, reject) => {\n Formio.libraries[name].resolve = resolve;\n Formio.libraries[name].reject = reject;\n });\n const callbackName = `${name}Callback`;\n if (!polling && !window[callbackName]) {\n window[callbackName] = () => Formio.libraries[name].resolve();\n }\n // See if the plugin already exists.\n const plugin = (0, lodash_1.get)(window, property);\n if (plugin) {\n Formio.libraries[name].resolve(plugin);\n }\n else {\n src = Array.isArray(src) ? src : [src];\n src.forEach((lib) => {\n let attrs = {};\n let elementType = '';\n if (typeof lib === 'string') {\n lib = {\n type: 'script',\n src: lib,\n };\n }\n switch (lib.type) {\n case 'script':\n elementType = 'script';\n attrs = {\n src: lib.src,\n type: 'text/javascript',\n defer: true,\n async: true,\n referrerpolicy: 'origin',\n };\n break;\n case 'styles':\n elementType = 'link';\n attrs = {\n href: lib.src,\n rel: 'stylesheet',\n };\n break;\n }\n // Add the script to the top of the page.\n const element = document.createElement(elementType);\n if (element.setAttribute) {\n for (const attr in attrs) {\n element.setAttribute(attr, attrs[attr]);\n }\n }\n if (onload) {\n element.addEventListener('load', () => {\n Formio.libraries[name].loaded = true;\n onload(Formio.libraries[name].ready);\n });\n }\n const { head } = document;\n if (head) {\n head.appendChild(element);\n }\n });\n // if no callback is provided, then check periodically for the script.\n if (polling) {\n const interval = setInterval(() => {\n const plugin = (0, lodash_1.get)(window, property);\n if (plugin) {\n clearInterval(interval);\n Formio.libraries[name].resolve(plugin);\n }\n }, 200);\n }\n }\n }\n const lib = Formio.libraries[name];\n return onload && lib.loaded ? onload(lib.ready) : lib.ready;\n }\n /**\n * Determines if a lazy loaded library is ready to be used.\n *\n * @description Example: Let's assume that the example provided at {@link Formio.requireLibrary} was used elsewhere in your application.\n * You could now use the following within a separate place that will also resolve once the library is ready to be used.\n *\n * ```js\n * Formio.libraryReady('googleMaps').then(() => {\n * // Once the promise resolves, the following can now be used within your application.\n * const map = new google.maps.Map(document.getElementById(\"map\"), {...});\n * });\n * ```\n *\n * @param {string} name - The name of the library to check.\n * @return {Promise<object>} - A promise that will resolve when the library is ready to be used.\n */\n static libraryReady(name) {\n if (Formio.libraries.hasOwnProperty(name) && Formio.libraries[name].ready) {\n return Formio.libraries[name].ready;\n }\n return Promise.reject(`${name} library was not required.`);\n }\n /**\n * Clones the response from the API so that it cannot be mutated.\n *\n * @param response\n */\n static cloneResponse(response) {\n const copy = (0, fastCloneDeep_1.fastCloneDeep)(response);\n if (Array.isArray(response)) {\n copy.skip = response.skip;\n copy.limit = response.limit;\n copy.serverCount = response.serverCount;\n }\n return copy;\n }\n /**\n * Sets the project path type.\n *\n * @param type\n */\n static setPathType(type) {\n if (typeof type === 'string') {\n Formio.pathType = type;\n }\n }\n /**\n * Gets the project path type.\n */\n static getPathType() {\n return Formio.pathType;\n }\n}\nexports.Formio = Formio;\n/**\n * The base API url of the Form.io Platform. Example: https://api.form.io\n */\nFormio.baseUrl = 'https://api.form.io';\n/**\n * The project API url of the Form.io Project. Example: https://examples.form.io\n */\nFormio.projectUrl = '';\n/**\n * The project url to use for Authentication.\n */\nFormio.authUrl = '';\n/**\n * Set to true if the project url has been established with ```Formio.setProjectUrl()```\n */\nFormio.projectUrlSet = false;\n/**\n * The Form.io API Cache. This ensures that requests to the same API endpoint are cached.\n */\nFormio.cache = {};\n/**\n * The namespace used to save the Form.io Token's and variables within an application.\n */\nFormio.namespace = '';\n/**\n * Handles events fired within this SDK library.\n */\nFormio.events = new eventemitter3_1.default();\n/**\n * Stores all of the libraries lazy loaded with ```Formio.requireLibrary``` method.\n */\nFormio.libraries = {};\n/**\n * A direct interface to the Form.io fetch polyfill.\n */\nFormio.fetch = fetch;\n/**\n * A direct interface to the Form.io fetch Headers polyfill.\n */\nFormio.Headers = Headers;\n/**\n * All of the auth tokens for this session.\n */\nFormio.tokens = {};\n/**\n * The version of this library.\n */\nFormio.version = '---VERSION---';\n/**\n * The global options for the Formio library.\n */\nFormio.options = {};\n// Add Plugin methods.\nFormio.plugins = Plugins_1.default.plugins;\nFormio.deregisterPlugin = Plugins_1.default.deregisterPlugin;\nFormio.registerPlugin = Plugins_1.default.registerPlugin;\nFormio.getPlugin = Plugins_1.default.getPlugin;\nFormio.pluginWait = Plugins_1.default.pluginWait;\nFormio.pluginGet = Plugins_1.default.pluginGet;\nFormio.pluginAlter = Plugins_1.default.pluginAlter;\n// Adds Formio to the Plugins Interface.\nPlugins_1.default.Formio = Formio;\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/sdk/Formio.js?");
5097
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = exports.FormioPathType = void 0;\nconst fetch_ponyfill_1 = __importDefault(__webpack_require__(/*! fetch-ponyfill */ \"./node_modules/fetch-ponyfill/build/fetch-browser.js\"));\nconst fastCloneDeep_1 = __webpack_require__(/*! ../utils/fastCloneDeep */ \"./node_modules/@formio/core/lib/utils/fastCloneDeep.js\");\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\nconst formUtil_1 = __webpack_require__(/*! ../utils/formUtil */ \"./node_modules/@formio/core/lib/utils/formUtil/index.js\");\nconst jwtDecode_1 = __webpack_require__(/*! ../utils/jwtDecode */ \"./node_modules/@formio/core/lib/utils/jwtDecode.js\");\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst browser_cookies_1 = __importDefault(__webpack_require__(/*! browser-cookies */ \"./node_modules/browser-cookies/src/browser-cookies.js\"));\nconst { fetch, Headers } = (0, fetch_ponyfill_1.default)();\nconst Plugins_1 = __importDefault(__webpack_require__(/*! ./Plugins */ \"./node_modules/@formio/core/lib/sdk/Plugins.js\"));\nconst utils_1 = __webpack_require__(/*! ../utils */ \"./node_modules/@formio/core/lib/utils/index.js\");\n/**\n * The different path types for a project.\n */\nvar FormioPathType;\n(function (FormioPathType) {\n FormioPathType[\"Subdirectories\"] = \"Subdirectories\";\n FormioPathType[\"Subdomains\"] = \"Subdomains\";\n})(FormioPathType || (exports.FormioPathType = FormioPathType = {}));\n/**\n * The Formio interface class. This is a minimalistic API library that allows you to work with the Form.io API's within JavaScript.\n *\n * ## Usage\n * Creating an instance of Formio is simple, and takes only a path (URL String). The path can be different, depending on the desired output.\n * The Formio instance can also access higher level operations, depending on how granular of a path you start with.\n *\n * ```ts\n * var formio = new Formio(<endpoint>, [options]);\n * ```\n *\n * Where **endpoint** is any valid API endpoint within Form.io. These URL's can provide a number of different methods depending on the granularity of the endpoint. This allows you to use the same interface but have access to different methods depending on how granular the endpoint url is.\n * **options** is defined within the {link Formio.constructor} documentation.\n *\n * Here is an example of how this library can be used to load a form JSON from the Form.io API's\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n */\nclass Formio {\n /**\n * @constructor\n * @param {string} path - A project, form, and submission API Url.\n * @param {FormioOptions} options - Available options to configure the Javascript API.\n */\n constructor(path, options = {}) {\n this.path = path;\n this.options = options;\n /**\n * The base API url of the Form.io Platform. Example: https://api.form.io\n */\n this.base = '';\n /**\n * The Projects Endpoint derived from the provided source.\n *\n * @example https://api.form.io/project\n */\n this.projectsUrl = '';\n /**\n * A specific project endpoint derived from the provided source.\n *\n * @example https://examples.form.io\n */\n this.projectUrl = '';\n /**\n * The Project ID found within the provided source.\n */\n this.projectId = '';\n /**\n * A specific Role URL provided the source.\n *\n * @example https://examples.form.io/role/2342343234234234\n */\n this.roleUrl = '';\n /**\n * The roles endpoint derived from the provided source.\n *\n * @example https://examples.form.io/role\n */\n this.rolesUrl = '';\n /**\n * The roleID derieved from the provided source.\n */\n this.roleId = '';\n /**\n * A specific form url derived from the provided source.\n *\n * @example https://examples.form.io/example\n */\n this.formUrl = '';\n /**\n * The forms url derived from the provided source.\n *\n * @example https://example.form.io/form\n */\n this.formsUrl = '';\n /**\n * The Form ID derived from the provided source.\n */\n this.formId = '';\n /**\n * The submissions URL derived from the provided source.\n *\n * @example https://examples.form.io/example/submission\n */\n this.submissionsUrl = '';\n /**\n * A specific submissions URL derived from a provided source.\n *\n * @example https://examples.form.io/example/submission/223423423423\n */\n this.submissionUrl = '';\n /**\n * The submission ID provided a submission url.\n */\n this.submissionId = '';\n /**\n * The actions url provided a form url as the source.\n *\n * @example https://examples.form.io/example/action\n */\n this.actionsUrl = '';\n /**\n * The Action ID derived from a provided Action url.\n */\n this.actionId = '';\n /**\n * A specific action api endoint.\n */\n this.actionUrl = '';\n this.vsUrl = '';\n this.vId = '';\n this.vUrl = '';\n /**\n * The query string derived from the provided src url.\n */\n this.query = '';\n /**\n * If this is a non-project url, such is the case for Open Source API.\n */\n this.noProject = false;\n // Ensure we have an instance of Formio.\n if (!(this instanceof Formio)) {\n return new Formio(path);\n }\n if (options.useSessionToken) {\n Formio.useSessionToken(options);\n }\n if (options.hasOwnProperty('base') && options.base) {\n this.base = options.base;\n }\n else if (Formio.baseUrl) {\n this.base = Formio.baseUrl;\n }\n else if (window && window.location) {\n const match = window.location.href.match(/http[s]?:\\/\\/api./);\n this.base = match ? match[0] : window.location.origin;\n }\n if (!path) {\n // Allow user to create new projects if this was instantiated without\n // a url\n this.projectUrl = Formio.projectUrl || `${this.base}/project`;\n this.projectsUrl = `${this.base}/project`;\n this.projectId = '';\n this.query = '';\n return;\n }\n if (options.hasOwnProperty('project') && options.project) {\n this.projectUrl = options.project;\n }\n const project = this.projectUrl || Formio.projectUrl;\n const projectRegEx = /(^|\\/)(project)($|\\/[^/]+)/;\n const isProjectUrl = path.search(projectRegEx) !== -1;\n // The baseURL is the same as the projectUrl, and does not contain \"/project/MONGO_ID\" in\n // its domain. This is almost certainly against the Open Source server.\n if (project && this.base === project && !isProjectUrl) {\n this.noProject = true;\n this.projectUrl = this.base;\n }\n // Normalize to an absolute path.\n if (path.indexOf('http') !== 0 && path.indexOf('//') !== 0) {\n path = this.base + path;\n }\n const hostparts = this.getUrlParts(path);\n let hostName = '';\n let parts = [];\n if (hostparts) {\n hostName = hostparts[1] + hostparts[2];\n path = hostparts.length > 3 ? hostparts[3] : '';\n const queryparts = path.split('?');\n if (queryparts.length > 1) {\n path = queryparts[0];\n this.query = `?${queryparts[1]}`;\n }\n }\n // Register a specific path.\n const registerPath = (name, base) => {\n this[`${name}sUrl`] = `${base}/${name}`;\n const regex = new RegExp(`/${name}/([^/]+)`);\n if (path && path.search(regex) !== -1) {\n parts = path.match(regex);\n this[`${name}Url`] = parts ? base + parts[0] : '';\n this[`${name}Id`] = parts.length > 1 ? parts[1] : '';\n base += parts[0];\n }\n return base;\n };\n // Register an array of items.\n const registerItems = (items, base, staticBase) => {\n for (const i in items) {\n if (items.hasOwnProperty(i)) {\n const item = items[i];\n if (Array.isArray(item)) {\n registerItems(item, base, true);\n }\n else {\n const newBase = registerPath(item, base);\n base = staticBase ? base : newBase;\n }\n }\n }\n };\n if (!this.projectUrl || this.projectUrl === this.base) {\n // If a project uses Subdirectories path type, we need to specify a projectUrl\n if (!this.projectUrl && !isProjectUrl && Formio.pathType === 'Subdirectories') {\n const regex = `^${hostName.replace(/\\//g, '\\\\/')}.[^/]+`;\n const match = project.match(new RegExp(regex));\n this.projectUrl = match ? match[0] : hostName;\n }\n else {\n this.projectUrl = hostName;\n }\n }\n // Check if we have a specified path type.\n let isNotSubdomainType = false;\n if (Formio.pathType) {\n isNotSubdomainType = Formio.pathType !== 'Subdomains';\n }\n if (!this.noProject) {\n // Determine the projectUrl and projectId\n if (isProjectUrl) {\n // Get project id as project/:projectId.\n registerItems(['project'], hostName);\n path = path.replace(projectRegEx, '');\n }\n else if (hostName === this.base) {\n // Get project id as first part of path (subdirectory).\n if (hostparts && hostparts.length > 3 && path.split('/').length > 1) {\n const isFile = path.match(/.json/);\n const pathParts = path.split('/');\n if (isFile) {\n this.projectUrl = hostName;\n }\n else {\n pathParts.shift(); // Throw away the first /.\n const projectId = pathParts.shift();\n if (projectId) {\n this.projectId = projectId;\n path = `/${pathParts.join('/')}`;\n this.projectUrl = `${hostName}/${this.projectId}`;\n }\n }\n }\n }\n else {\n // Get project id from subdomain.\n if (hostparts &&\n hostparts.length > 2 &&\n (hostparts[2].split('.').length > 2 || hostName.includes('localhost')) &&\n !isNotSubdomainType) {\n this.projectUrl = hostName;\n this.projectId = hostparts[2].split('.')[0];\n }\n }\n this.projectsUrl = this.projectsUrl || `${this.base}/project`;\n }\n // Configure Role urls and role ids.\n registerItems(['role'], this.projectUrl);\n // Configure Form urls and form ids.\n if (/(^|\\/)(form)($|\\/)/.test(path)) {\n registerItems(['form', ['submission', 'action', 'v']], this.projectUrl);\n }\n else {\n const subRegEx = new RegExp('/(submission|action|v)($|/.*)');\n const subs = path.match(subRegEx);\n if (subs && subs.length > 1) {\n this.pathType = subs[1];\n }\n path = path.replace(subRegEx, '');\n path = path.replace(/\\/$/, '');\n this.formsUrl = `${this.projectUrl}/form`;\n this.formUrl = path ? this.projectUrl + path : '';\n this.formId = path.replace(/^\\/+|\\/+$/g, '');\n const items = ['submission', 'action', 'v'];\n for (const i in items) {\n if (items.hasOwnProperty(i)) {\n const item = items[i];\n this[`${item}sUrl`] = `${this.projectUrl + path}/${item}`;\n if (this.pathType === item && subs && subs.length > 2 && subs[2]) {\n this[`${item}Id`] = subs[2].replace(/^\\/+|\\/+$/g, '');\n this[`${item}Url`] = this.projectUrl + path + subs[0];\n }\n }\n }\n }\n // Set the app url if it is not set.\n if (!Formio.projectUrlSet) {\n Formio.projectUrl = this.projectUrl;\n }\n }\n /**\n * Deletes a remote resource of any provided type.\n *\n * @param {string} type - The type of resource to delete. \"submission\", \"form\", etc.\n * @param {object} options - The options passed to {@link Formio.request}\n * @return {Promise<Response>}\n */\n delete(type, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n if (!this[_id]) {\n return Promise.reject('Nothing to delete');\n }\n Formio.cache = {};\n return this.makeRequest(type, this[_url], 'delete', null, opts);\n }\n /**\n * Returns the index (array of records) for any provided type.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} query - A query object to pass to the request.\n * @param {object} query.params - A map (key-value pairs) of URL query parameters to add to the url.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n index(type, query, opts) {\n const _url = `${type}Url`;\n query = query || '';\n if (query && (0, lodash_1.isObject)(query)) {\n query = `?${Formio.serialize(query.params)}`;\n }\n return this.makeRequest(type, this[_url] + query, 'get', null, opts);\n }\n /**\n * Save a document record using \"upsert\". If the document does not exist, it will be created, if the _id is provided,\n * it will be updated.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} data - The resource data object.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n save(type, data, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n const method = this[_id] || data._id ? 'put' : 'post';\n let reqUrl = this[_id] ? this[_url] : this[`${type}sUrl`];\n if (!this[_id] && data._id && method === 'put' && !reqUrl.includes(data._id)) {\n reqUrl += `/${data._id}`;\n }\n Formio.cache = {};\n return this.makeRequest(type, reqUrl + this.query, method, data, opts);\n }\n /**\n * @summary Load (GET) a document record.\n *\n * @param {string} type - The type of resource to fetch the index of. \"submission\", \"form\", etc.\n * @param {object} query - A query object to pass to the request.\n * @param {object} query.params - A map (key-value pairs) of URL query parameters to add to the url.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n load(type, query, opts) {\n const _id = `${type}Id`;\n const _url = `${type}Url`;\n if (query && (0, lodash_1.isObject)(query)) {\n query = Formio.serialize(query.params);\n }\n if (query) {\n query = this.query ? `${this.query}&${query}` : `?${query}`;\n }\n else {\n query = this.query;\n }\n if (!this[_id]) {\n return Promise.reject(`Missing ${_id}`);\n }\n let url = this[_url] + query;\n if (type === 'form' && !isNaN(parseInt(this.vId))) {\n url += url.indexOf('?') === -1 ? '?' : '&';\n url += `formRevision=${this.vId}`;\n }\n return this.makeRequest(type, url, 'get', null, opts);\n }\n /**\n * @summary Call {@link Formio.makeRequest} for this Formio instance.\n *\n * @param {string} type - The request resource type. \"submission\", \"form\", etc.\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>}\n */\n makeRequest(type, url, method, data, opts) {\n return Formio.makeRequest(this, type, url, method, data, opts);\n }\n /**\n * @summary Loads a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadProject().then((project) => {\n * console.log(project);\n * });\n * ```\n *\n * @param {object} query - Query parameters to pass to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadProject(query, opts) {\n return this.load('project', query, opts);\n }\n /**\n * Saves or Updates a project.\n *\n * ### Create a new project\n * ```ts\n * const formio = new Formio();\n * formio.saveProject({\n * title: 'My Project',\n * path: 'myproject',\n * name: 'myproject'\n * });\n * ```\n *\n * ### Update an existing project\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadProject().then((project) => {\n * project.title = 'Title changed';\n * formio.saveProject(project).then(() => {\n * console.log('Done saving project!');\n * });\n * });\n * ```\n *\n * @param {object} data - The project JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveProject(data, opts) {\n return this.save('project', data, opts);\n }\n /**\n * Deletes a project\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.deleteProject();\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n deleteProject(opts) {\n return this.delete('project', opts);\n }\n /**\n * Loads a list of all projects.\n *\n * ```ts\n * Formio.loadProjects().then((projects) => {\n * console.log(projects);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {*}\n */\n static loadProjects(query, opts) {\n query = query || '';\n if ((0, lodash_1.isObject)(query)) {\n query = `?${Formio.serialize(query.params)}`;\n }\n return Formio.makeStaticRequest(`${Formio.baseUrl}/project${query}`, 'GET', null, opts);\n }\n /**\n * Loads a role within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/role/234234234234');\n * formio.loadRole().then((role) => {\n * console.log(role);\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadRole(opts) {\n return this.load('role', null, opts);\n }\n /**\n * Create a new or Update an existing role within a project.\n *\n * ### Create new Role example\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.saveRole({\n * title: 'Employee',\n * description: 'A person who belongs to a company.'\n * }).then((role) => {\n * console.log(role);\n * });\n * ```\n *\n * ### Update existing role example\n * ```ts\n * const formio = new Formio('https://examples.form.io/role/234234234234234');\n * formio.loadRole().then((role) => {\n * role.title = 'Manager';\n * formio.saveRole(role).then(() => {\n * console.log('DONE');\n * });\n * });\n * ```\n *\n * @param {object} role - The Role JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveRole(data, opts) {\n return this.save('role', data, opts);\n }\n /**\n * Deletes a role within a project.\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteRole(opts) {\n return this.delete('role', opts);\n }\n /**\n * Load all roles within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadRoles().then((roles) => {\n * console.log(roles);\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadRoles(opts) {\n return this.index('roles', null, opts);\n }\n /**\n * Loads a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n loadForm(query, opts) {\n return this.load('form', query, opts).then((currentForm) => {\n // Check to see if there isn't a number in vId.\n if (!currentForm.revisions || isNaN(parseInt(this.vId))) {\n return currentForm;\n }\n // If a submission already exists but form is marked to load current version of form.\n if (currentForm.revisions === 'current' && this.submissionId) {\n return currentForm;\n }\n if (currentForm._vid == this.vId || currentForm.revisionId === this.vId) {\n return currentForm;\n }\n // If they specified a revision form, load the revised form components.\n if (query && (0, lodash_1.isObject)(query)) {\n query = Formio.serialize(query.params);\n }\n if (query) {\n query = this.query ? `${this.query}&${query}` : `?${query}`;\n }\n else {\n query = this.query;\n }\n return (this.makeRequest('form', this.vUrl + query, 'get', null, opts)\n .then((revisionForm) => {\n currentForm._vid = revisionForm._vid;\n currentForm.components = revisionForm.components;\n currentForm.settings = revisionForm.settings;\n currentForm.revisionId = revisionForm.revisionId;\n // Using object.assign so we don't cross polinate multiple form loads.\n return Object.assign({}, currentForm);\n })\n // If we couldn't load the revision, just return the original form.\n .catch(() => Object.assign({}, currentForm)));\n });\n }\n /**\n * Create or Update a specific form.\n *\n * ### Create form example\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.saveForm({\n * title: 'Employee',\n * type: 'resource',\n * path: 'employee',\n * name: 'employee',\n * components: [\n * {\n * type: 'textfield',\n * key: 'firstName',\n * label: 'First Name'\n * },\n * {\n * type: 'textfield',\n * key: 'lastName',\n * label: 'Last Name'\n * }\n * ]\n * });\n * ```\n *\n * ### Update a form example\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadForm().then((form) => {\n * form.title = 'Changed Title';\n * formio.saveForm(form).then(() => {\n * console.log('DONE!!!');\n * });\n * });\n * ```\n *\n * @param {object} data - The Form JSON to create or update.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveForm(data, opts) {\n return this.save('form', data, opts);\n }\n /**\n * Deletes a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.deleteForm().then(() => {\n * console.log('Deleted!');\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteForm(opts) {\n return this.delete('form', opts);\n }\n /**\n * Loads all forms within a project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.loadForms().then((forms) => {\n * console.log(forms);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadForms(query, opts) {\n return this.index('forms', query, opts);\n }\n /**\n * Loads a specific submissionn.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/23423423423423423');\n * formio.loadSubmission().then((submission) => {\n * console.log(submission);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n loadSubmission(query, opts) {\n return this.load('submission', query, opts).then((submission) => {\n this.vId = submission._frid || submission._fvid;\n this.vUrl = `${this.formUrl}/v/${this.vId}`;\n return submission;\n });\n }\n /**\n * Creates a new or Updates an existing submission.\n *\n * ### Create a new submission\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.saveSubmission({\n * data: {\n * firstName: 'Joe',\n * lastName: 'Smith'\n * }\n * }).then((submission) => {\n * // This will now be the complete submission object saved on the server.\n * console.log(submission);\n * });\n * ```\n *\n * ### Update an existing submission\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/23423423423423423');\n * formio.loadSubmission().then((submission) => {\n * submission.data.lastName = 'Thompson';\n * formio.saveSubmission(submission).then(() => {\n * console.log('DONE');\n * });\n * });\n * ```\n *\n * @param {object} data - The submission JSON object.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveSubmission(data, opts) {\n if (!isNaN(parseInt(this.vId)) && !data._fvid) {\n data._fvid = this.vId;\n }\n return this.save('submission', data, opts);\n }\n /**\n * Deletes a submission.\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteSubmission(opts) {\n return this.delete('submission', opts);\n }\n /**\n * Loads all submissions within a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadSubmissions({\n * params: {\n * limit: 25,\n * 'data.lastName__regex': 'smith'\n * }\n * }).then((submissions) => {\n * // Should print out 25 submissions where the last name contains \"smith\".\n * console.log(submissions);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadSubmissions(query, opts) {\n return this.index('submissions', query, opts);\n }\n /**\n * Loads a form action.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.loadAction().then((action) => {\n * console.log(action);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n loadAction(query, opts) {\n return this.load('action', query, opts);\n }\n /**\n * Create a new or update an existing action.\n *\n * ### Create a new action for a form.\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.saveAction({\n * data: {\n * name: 'webhook',\n * title: 'Webhook Action',\n * method: ['create', 'update', 'delete'],\n * handler: ['after'],\n * condition: {},\n * settings: {\n * url: 'https://example.com',\n * headers: [{}],\n * block: false,\n * forwardHeaders: false\n * }\n * }\n * }).then((action) => {\n * console.log(action);\n * });\n * ```\n *\n * ### Update an action\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.loadAction().then((action) => {\n * action.title = 'Updated title';\n * formio.saveAction(action).then(() => {\n * console.log('Done!');\n * });\n * });\n * ```\n *\n * @param {object} data - The action JSON\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Object>}\n */\n saveAction(data, opts) {\n return this.save('action', data, opts);\n }\n /**\n * Delete an action\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/action/234234234234');\n * formio.deleteAction().then(() => {\n * console.log('Action was deleted.');\n * });\n * ```\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n deleteAction(opts) {\n return this.delete('action', opts);\n }\n /**\n * Loads all actions within a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.loadActions().then((actions) => {\n * console.log(actions);\n * });\n * ```\n *\n * @param {object} query - Query parameters similar to {@link Formio#load}.\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<Response>}\n */\n loadActions(query, opts) {\n return this.index('actions', query, opts);\n }\n /**\n * Returns a list of available actions\n *\n * @return {Promise<Response>}\n */\n availableActions() {\n return this.makeRequest('availableActions', `${this.formUrl}/actions`);\n }\n /**\n * Returns the action information for a specific action, such as \"save\".\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/actions/save');\n * formio.actionInfo().then((info) => {\n * console.log(info);\n * });\n * ```\n *\n * @param {string} name - The name of the action you would like to get information for. i.e. \"save\", \"webhook\", etc.\n * @return {Promise<Response>}\n */\n actionInfo(name) {\n return this.makeRequest('actionInfo', `${this.formUrl}/actions/${name}`);\n }\n /**\n * Determine if a string ID is a valid MongoID.\n *\n * @param {string} id - The id that should be tested if it is avalid id.\n * @return {boolean} - true if it is a valid MongoId, false otherwise.\n */\n isObjectId(id) {\n const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');\n return checkForHexRegExp.test(id);\n }\n /**\n * Get the project ID of project.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io');\n * formio.getProjectId().then((projectId) => {\n * console.log(projectId);\n * };\n * ```\n *\n * @return {Promise<string>}\n */\n getProjectId() {\n if (!this.projectId) {\n return Promise.resolve('');\n }\n if (this.isObjectId(this.projectId)) {\n return Promise.resolve(this.projectId);\n }\n else {\n return this.loadProject().then((project) => {\n return project._id;\n });\n }\n }\n /**\n * Get the ID of a form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example');\n * formio.getFormId().then((formId) => {\n * console.log(formId);\n * });\n * ```\n *\n * @return {Promise<string>}\n */\n getFormId() {\n if (!this.formId) {\n return Promise.resolve('');\n }\n if (this.isObjectId(this.formId)) {\n return Promise.resolve(this.formId);\n }\n else {\n return this.loadForm().then((form) => {\n return form._id;\n });\n }\n }\n /**\n * Instance method for {@link Formio.currentUser}\n *\n * @param {object} options - Options to pass to {@link Formio.request}\n * @return {Promise<object>}\n */\n currentUser(options) {\n return Formio.currentUser(this, options);\n }\n /**\n * Instance method for {@link Formio.accessInfo}\n *\n * @return {Promise<Response>}\n */\n accessInfo() {\n return Formio.accessInfo(this);\n }\n /**\n * Sets OAuth Logout URL.\n *\n * @param {string} uri - Logout URL.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string}\n */\n oauthLogoutURI(uri, options) {\n return Formio.oauthLogoutURI(uri, Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Returns the JWT token for this instance.\n *\n * @param {object} options - The following options are provided.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string} - The JWT token for this user.\n */\n getToken(options) {\n return Formio.getToken(Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Sets the JWT token for this instance.\n *\n * @param {string} token - The JWT token to set.\n * @param {object} options - The following options are provided.\n * @param {string} options.namespace - The localStorage namespace to use when retrieving tokens from storage.\n * @return {string} - The JWT token that was set.\n */\n setToken(token, options) {\n return Formio.setToken(token, Object.assign({ formio: this }, this.options, options));\n }\n /**\n * Returns a temporary authentication token for single purpose token generation.\n *\n * @param {number|string} expire - The amount of seconds to wait before this temp token expires.\n * @param {string} allowed - The allowed path string inn the format GET:/path\n * @param {object} options - The options passed to {@link Formio#getToken}\n */\n getTempToken(expire, allowed, options) {\n const token = Formio.getToken(options);\n if (!token) {\n return Promise.reject('You must be authenticated to generate a temporary auth token.');\n }\n const authUrl = Formio.authUrl || this.projectUrl;\n return this.makeRequest('tempToken', `${authUrl}/token`, 'GET', null, {\n ignoreCache: true,\n header: new Headers({\n 'x-expire': expire,\n 'x-allow': allowed,\n }),\n });\n }\n /**\n * Get a PDF download url for a submission, which will generate a new PDF of the submission. This method will first\n * fetch a temporary download token, and then append this to the download url for this form.\n *\n * ```ts\n * const formio = new Formio('https://examples.form.io/example/submission/324234234234234');\n * formio.getDownloadUrl().then((url) => {\n * console.log(url);\n * });\n * ```\n *\n * @param {object} [form] - The form JSON to fetch a download url for.\n * @return {Promise<string>} - The download url.\n */\n getDownloadUrl(form) {\n if (!this.submissionId) {\n return Promise.resolve('');\n }\n if (!form) {\n // Make sure to load the form first.\n return this.loadForm().then((_form) => {\n if (!_form) {\n return '';\n }\n return this.getDownloadUrl(_form);\n });\n }\n let apiUrl = `/project/${form.project}`;\n apiUrl += `/form/${form._id}`;\n apiUrl += `/submission/${this.submissionId}`;\n const postfix = form.submissionRevisions && form.settings.changeLog ? '/download/changelog' : '/download';\n apiUrl += postfix;\n let download = this.base + apiUrl;\n return new Promise((resolve, reject) => {\n this.getTempToken(3600, `GET:${apiUrl}`)\n .then((tempToken) => {\n download += `?token=${tempToken.key}`;\n resolve(download);\n }, () => {\n resolve(download);\n })\n .catch(reject);\n });\n }\n /**\n * Returns the user permissions to a form and submission.\n *\n * @param user - The user or current user if undefined. For anonymous, use \"null\"\n * @param form - The form or current form if undefined. For no form check, use \"null\"\n * @param submission - The submisison or \"index\" if undefined.\n *\n * @return {{create: boolean, read: boolean, edit: boolean, delete: boolean}}\n */\n userPermissions(user, form, submission) {\n return Promise.all([\n form !== undefined ? Promise.resolve(form) : this.loadForm(),\n user !== undefined ? Promise.resolve(user) : this.currentUser(),\n submission !== undefined || !this.submissionId\n ? Promise.resolve(submission)\n : this.loadSubmission(),\n this.accessInfo(),\n ]).then((results) => {\n const form = results.shift();\n const user = results.shift() || { _id: false, roles: [] };\n const submission = results.shift();\n const access = results.shift();\n const permMap = {\n create: 'create',\n read: 'read',\n update: 'edit',\n delete: 'delete',\n };\n const perms = {\n user: user,\n form: form,\n access: access,\n create: false,\n read: false,\n edit: false,\n delete: false,\n };\n for (const roleName in access.roles) {\n if (access.roles.hasOwnProperty(roleName)) {\n const role = access.roles[roleName];\n if (role.default && user._id === false) {\n // User is anonymous. Add the anonymous role.\n user.roles.push(role._id);\n }\n else if (role.admin && user.roles.indexOf(role._id) !== -1) {\n perms.create = true;\n perms.read = true;\n perms.delete = true;\n perms.edit = true;\n return perms;\n }\n }\n }\n if (form && form.submissionAccess) {\n for (let i = 0; i < form.submissionAccess.length; i++) {\n const permission = form.submissionAccess[i];\n const [perm, scope] = permission.type.split('_');\n if (['create', 'read', 'update', 'delete'].includes(perm)) {\n if ((0, lodash_1.intersection)(permission.roles, user.roles).length) {\n perms[permMap[perm]] =\n scope === 'all' || !submission || user._id === submission.owner;\n }\n }\n }\n }\n // check for Group Permissions\n if (submission) {\n // we would anyway need to loop through components for create permission, so we'll do that for all of them\n (0, formUtil_1.eachComponent)(form.components, (component, path) => {\n if (component && component.defaultPermission) {\n const value = (0, lodash_1.get)(submission.data, path);\n // make it work for single-select Group and multi-select Group\n const groups = Array.isArray(value) ? value : [value];\n groups.forEach((group) => {\n if (group &&\n group._id && // group id is present\n user.roles.indexOf(group._id) > -1 // user has group id in his roles\n ) {\n if (component.defaultPermission === 'read') {\n perms[permMap.read] = true;\n }\n if (component.defaultPermission === 'create') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n }\n if (component.defaultPermission === 'write') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n perms[permMap.update] = true;\n }\n if (component.defaultPermission === 'admin') {\n perms[permMap.create] = true;\n perms[permMap.read] = true;\n perms[permMap.update] = true;\n perms[permMap.delete] = true;\n }\n }\n });\n }\n });\n }\n return perms;\n });\n }\n /**\n * `Determine if the current user can submit a form.\n * @return {*}\n */\n canSubmit() {\n return this.userPermissions().then((perms) => {\n // If there is user and they cannot create, then check anonymous user permissions.\n if (!perms.create && Formio.getUser()) {\n return this.userPermissions(null).then((anonPerms) => {\n if (anonPerms.create) {\n Formio.setUser(null);\n return true;\n }\n return false;\n });\n }\n return perms.create;\n });\n }\n getUrlParts(url) {\n return Formio.getUrlParts(url, this);\n }\n static getUrlParts(url, formio) {\n const base = formio && formio.base ? formio.base : Formio.baseUrl;\n let regex = '^(http[s]?:\\\\/\\\\/)';\n if (base && url.indexOf(base) === 0) {\n regex += `(${base.replace(/^http[s]?:\\/\\//, '')})`;\n }\n else {\n regex += '([^/]+)';\n }\n regex += '($|\\\\/.*)';\n return url.match(new RegExp(regex));\n }\n static serialize(obj, _interpolate) {\n const str = [];\n const interpolate = (item) => {\n return _interpolate ? _interpolate(item) : item;\n };\n for (const p in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, p)) {\n str.push(`${encodeURIComponent(p)}=${encodeURIComponent(interpolate(obj[p]))}`);\n }\n }\n return str.join('&');\n }\n static getRequestArgs(formio, type, url, method, data, opts) {\n method = (method || 'GET').toUpperCase();\n if (!opts || !(0, lodash_1.isObject)(opts)) {\n opts = {};\n }\n const requestArgs = {\n url,\n method,\n data: data || null,\n opts,\n };\n if (type) {\n requestArgs.type = type;\n }\n if (formio) {\n requestArgs.formio = formio;\n }\n return requestArgs;\n }\n static makeStaticRequest(url, method, data, opts) {\n const requestArgs = Formio.getRequestArgs(null, '', url, method, data, opts);\n const request = Plugins_1.default.pluginWait('preRequest', requestArgs).then(() => Plugins_1.default.pluginGet('staticRequest', requestArgs).then((result) => {\n if ((0, lodash_1.isNil)(result)) {\n return Formio.request(requestArgs.url, requestArgs.method, requestArgs.data, requestArgs.opts.header, requestArgs.opts);\n }\n return result;\n }));\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', request, requestArgs);\n }\n /**\n * Make an API request and wrap that request with the Form.io Request plugin system. This is very similar to the\n * {Formio.request} method with a difference being that it will pass the request through the Form.io request plugin.\n *\n * @param {Formio} formio - An instance of the Formio class.\n * @param {string} type - The request resource type. \"submission\", \"form\", etc.\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>}\n */\n static makeRequest(formio, type, url, method, data, opts) {\n if (!formio) {\n return Formio.makeStaticRequest(url, method, data, opts);\n }\n const requestArgs = Formio.getRequestArgs(formio, type, url, method, data, opts);\n requestArgs.opts = requestArgs.opts || {};\n requestArgs.opts.formio = formio;\n //for Formio requests default Accept and Content-type headers\n if (!requestArgs.opts.headers) {\n requestArgs.opts.headers = {};\n }\n requestArgs.opts.headers = (0, lodash_1.defaults)(requestArgs.opts.headers, {\n Accept: 'application/json',\n 'Content-type': 'application/json',\n });\n const request = Plugins_1.default.pluginWait('preRequest', requestArgs).then(() => Plugins_1.default.pluginGet('request', requestArgs).then((result) => {\n if ((0, lodash_1.isNil)(result)) {\n return Formio.request(requestArgs.url, requestArgs.method, requestArgs.data, requestArgs.opts.header, requestArgs.opts);\n }\n return result;\n }));\n return Plugins_1.default.pluginAlter('wrapRequestPromise', request, requestArgs);\n }\n /**\n * Execute an API request to any external system. This is a wrapper around the Web fetch method.\n *\n * ```ts\n * Formio.request('https://examples.form.io').then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {string} url - The URL to request.\n * @param {string} method - The request method. GET, PUT, POST, DELETE, or PATCH\n * @param {object} data - The data to pass to the request (for PUT, POST, and PATCH methods)\n * @param {Headers} header - An object of headers to pass to the request.\n * @param {object} options - An object of options to pass to the request method.\n * @param {boolean} options.ignoreCache - To ignore internal caching of the request.\n * @param {object} options.headers - An object of headers to pass along to the request.\n * @param {boolean} options.noToken - If set to true, this will not include the Form.io x-jwt-token along with the request.\n * @param {string} options.namespace - The Form.io namespace to prepend to all LocalStorage variables such as formioToken.\n * @param {boolean} options.getHeaders - Set this if you wish to include the response headers with the return of this method.\n * @return {Promise<Response>|*}\n */\n static request(url, method, data, header, opts) {\n if (!url) {\n return Promise.reject('No url provided');\n }\n method = (method || 'GET').toUpperCase();\n // For reverse compatibility, if they provided the ignoreCache parameter,\n // then change it back to the options format where that is a parameter.\n if ((0, lodash_1.isBoolean)(opts)) {\n opts = { ignoreCache: opts };\n }\n if (!opts || !(0, lodash_1.isObject)(opts)) {\n opts = {};\n }\n // Generate a cachekey.\n const cacheKey = btoa(encodeURI(url));\n // Get the cached promise to save multiple loads.\n if (!opts.ignoreCache && method === 'GET' && Formio.cache.hasOwnProperty(cacheKey)) {\n return Promise.resolve(Formio.cloneResponse(Formio.cache[cacheKey]));\n }\n if (url[0] === '/') {\n url = Formio.baseUrl + url;\n }\n // Set up and fetch request\n const headers = header ||\n new Headers(opts.headers || {\n Accept: 'application/json',\n 'Content-type': 'application/json',\n });\n const token = Formio.getToken(opts);\n if (token && !opts.noToken) {\n headers.set('x-jwt-token', token);\n }\n // The fetch-ponyfill can't handle a proper Headers class anymore. Change it back to an object.\n const headerObj = {};\n headers.forEach(function (value, name) {\n headerObj[name] = value;\n });\n let options = {\n method: method,\n headers: headerObj,\n mode: 'cors',\n };\n if (data) {\n options.body = JSON.stringify(data);\n }\n // Allow plugins to alter the options.\n options = Plugins_1.default.pluginAlter('requestOptions', options, url);\n if (options.namespace || Formio.namespace) {\n opts.namespace = options.namespace || Formio.namespace;\n }\n const requestToken = options.headers['x-jwt-token'];\n const result = Plugins_1.default.pluginAlter('wrapFetchRequestPromise', Formio.fetch(url, options), {\n url,\n method,\n data,\n opts,\n })\n .then((response) => {\n // Allow plugins to respond.\n response = Plugins_1.default.pluginAlter('requestResponse', response, Formio, data);\n if (!response.ok) {\n if (response.status === 440) {\n Formio.setToken(null, opts);\n Formio.events.emit('formio.sessionExpired', response.body || response);\n }\n else if (response.status === 401) {\n Formio.events.emit('formio.unauthorized', response.body || response);\n }\n else if (response.status === 416) {\n Formio.events.emit('formio.rangeIsNotSatisfiable', response.body || response);\n }\n else if (response.status === 504) {\n return Promise.reject(new Error('Network request failed'));\n }\n // Parse and return the error as a rejected promise to reject this promise\n return (response.headers.get('content-type').includes('application/json')\n ? response.json()\n : response.text()).then((error) => {\n return Promise.reject(error);\n });\n }\n // Handle fetch results\n const respToken = response.headers.get('x-jwt-token');\n // In some strange cases, the fetch library will return an x-jwt-token without sending\n // one to the server. This has even been debugged on the server to verify that no token\n // was introduced with the request, but the response contains a token. This is an Invalid\n // case where we do not send an x-jwt-token and get one in return for any GET request.\n let tokenIntroduced = false;\n if (method === 'GET' &&\n !requestToken &&\n respToken &&\n !opts.external &&\n !url.includes('token=') &&\n !url.includes('x-jwt-token=')) {\n console.warn('Token was introduced in request.');\n tokenIntroduced = true;\n }\n if (response.status >= 200 &&\n response.status < 300 &&\n respToken &&\n respToken !== '' &&\n !tokenIntroduced) {\n Formio.setToken(respToken, Object.assign(Object.assign({}, opts), { fromCurrent: opts.fromCurrent || !!requestToken }));\n }\n // 204 is no content. Don't try to .json() it.\n if (response.status === 204) {\n return {};\n }\n const getResult = response.headers.get('content-type').includes('application/json')\n ? response.json()\n : response.text();\n return getResult.then((result) => {\n // Add some content-range metadata to the result here\n let range = response.headers.get('content-range');\n if (range && (0, lodash_1.isObject)(result)) {\n range = range.split('/');\n if (range[0] !== '*') {\n const skipLimit = range[0].split('-');\n result.skip = Number(skipLimit[0]);\n result.limit = skipLimit[1] - skipLimit[0] + 1;\n }\n result.serverCount = range[1] === '*' ? range[1] : Number(range[1]);\n }\n if (!opts.getHeaders) {\n return result;\n }\n const headers = {};\n response.headers.forEach((item, key) => {\n headers[key] = item;\n });\n // Return the result with the headers.\n return {\n result,\n headers,\n };\n });\n })\n .then((result) => {\n if (opts.getHeaders) {\n return result;\n }\n // Cache the response.\n if (method === 'GET') {\n Formio.cache[cacheKey] = result;\n }\n return Formio.cloneResponse(result);\n })\n .catch((err) => {\n if (err === 'Bad Token' && opts.noToken !== false) {\n Formio.setToken(null, opts);\n Formio.events.emit('formio.badToken', err);\n }\n if (err.message) {\n err = new Error(`Could not connect to API server (${err.message}): ${url}`);\n err.networkError = true;\n }\n if (method === 'GET') {\n delete Formio.cache[cacheKey];\n }\n return Promise.reject(err);\n });\n return result;\n }\n // Needed to maintain reverse compatability...\n static get token() {\n return Formio.tokens.formioToken || '';\n }\n // Needed to maintain reverse compatability...\n static set token(token) {\n Formio.tokens.formioToken = token || '';\n }\n static useSessionToken(options) {\n if (typeof localStorage === 'undefined') {\n return;\n }\n const namespace = options;\n if (typeof options === 'object') {\n options = options.namespace;\n }\n const tokenName = `${namespace || Formio.namespace || 'formio'}Token`;\n const token = localStorage.getItem(tokenName);\n if (token) {\n localStorage.removeItem(tokenName);\n sessionStorage.setItem(tokenName, token);\n }\n const userName = `${namespace || Formio.namespace || 'formio'}User`;\n const user = localStorage.getItem(userName);\n if (user) {\n localStorage.removeItem(userName);\n sessionStorage.setItem(userName, user);\n }\n localStorage.setItem('useSessionToken', 'true');\n }\n /**\n * Sets the JWT in storage to be used within an application.\n *\n * @param {string} token - The JWT token to set.\n * @param {object} options - Options as follows\n * @param {string} options.namespace - The namespace to save the token within. i.e. \"formio\"\n * @param {Formio} options.formio - The Formio instance.\n * @return {Promise<object>|void}\n */\n static setToken(token = '', opts = {}) {\n token = token || '';\n opts = typeof opts === 'string' ? { namespace: opts } : opts || {};\n const tokenName = `${opts.namespace || Formio.namespace || 'formio'}Token`;\n if (!Formio.tokens) {\n Formio.tokens = {};\n }\n const storage = localStorage.getItem('useSessionToken') ? sessionStorage : localStorage;\n if (!token) {\n if (!opts.fromUser) {\n opts.fromToken = true;\n Formio.setUser(null, opts);\n }\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.removeItem(tokenName);\n }\n catch (ignoreErr) {\n browser_cookies_1.default.erase(tokenName, { path: '/' });\n }\n Formio.tokens[tokenName] = token;\n return Promise.resolve(null);\n }\n if (Formio.tokens[tokenName] !== token) {\n Formio.tokens[tokenName] = token;\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.setItem(tokenName, token);\n }\n catch (ignoreErr) {\n browser_cookies_1.default.set(tokenName, token, { path: '/' });\n }\n }\n // Return or updates the current user\n return Formio.currentUser(opts.formio, opts);\n }\n /**\n * Returns the token set within the application for the user.\n *\n * @param {object} options - The options as follows.\n * @param {string} options.namespace - The namespace of the token you wish to fetch.\n * @param {boolean} options.decode - If you would like the token returned as decoded JSON.\n * @return {*}\n */\n static getToken(options) {\n options = typeof options === 'string' ? { namespace: options } : options || {};\n const tokenName = `${options.namespace || Formio.namespace || 'formio'}Token`;\n const decodedTokenName = options.decode ? `${tokenName}Decoded` : tokenName;\n if (!Formio.tokens) {\n Formio.tokens = {};\n }\n if (Formio.tokens[decodedTokenName]) {\n return Formio.tokens[decodedTokenName];\n }\n try {\n const token = localStorage.getItem('useSessionToken')\n ? sessionStorage.getItem(tokenName)\n : localStorage.getItem(tokenName);\n Formio.tokens[tokenName] = token || '';\n if (options.decode) {\n Formio.tokens[decodedTokenName] = Formio.tokens[tokenName]\n ? (0, jwtDecode_1.jwtDecode)(Formio.tokens[tokenName])\n : {};\n return Formio.tokens[decodedTokenName];\n }\n return Formio.tokens[tokenName];\n }\n catch (ignoreError) {\n Formio.tokens[tokenName] = browser_cookies_1.default.get(tokenName);\n return '';\n }\n }\n /**\n * Sets the current user within the application cache.\n *\n * @param {object} user - JSON object of the user you wish to set.\n * @param {object} options - Options as follows\n * @param {string} options.namespace - The namespace of the tokens\n */\n static setUser(user, opts = {}) {\n const userName = `${opts.namespace || Formio.namespace || 'formio'}User`;\n const storage = localStorage.getItem('useSessionToken') ? sessionStorage : localStorage;\n if (!user) {\n if (!opts.fromToken) {\n opts.fromUser = true;\n Formio.setToken(null, opts);\n }\n // Emit an event on the cleared user.\n Formio.events.emit('formio.user', null);\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n return storage.removeItem(userName);\n }\n catch (ignoreError) {\n return browser_cookies_1.default.erase(userName, { path: '/' });\n }\n }\n // iOS in private browse mode will throw an error but we can't detect ahead of time that we are in private mode.\n try {\n storage.setItem(userName, JSON.stringify(user));\n }\n catch (ignoreError) {\n browser_cookies_1.default.set(userName, JSON.stringify(user), { path: '/' });\n }\n // Emit an event on the authenticated user.\n Formio.events.emit('formio.user', user);\n }\n /**\n * Returns the user JSON.\n *\n * @param {object} options - Options as follows\n * @param {string} namespace - The namespace of the tokens stored within this application.\n * @return {object} - The user object.\n */\n static getUser(options) {\n options = options || {};\n const userName = `${options.namespace || Formio.namespace || 'formio'}User`;\n try {\n return JSON.parse((localStorage.getItem('useSessionToken') ? sessionStorage : localStorage).getItem(userName) || '');\n }\n catch (ignoreError) {\n return JSON.parse(browser_cookies_1.default.get(userName));\n }\n }\n /**\n * Sets the BaseURL for the application.\n *\n * @description Every application developed using the JavaScript SDK must set both the {@link Formio.setBaseUrl} and\n * {@link Formio.setProjectUrl} methods. These two functions ensure that every URL passed into the constructor of this\n * class can determine the \"project\" context for which the application is running.\n *\n * Any Open Source server applications will set both the {@link Formio.setBaseUrl} and {@link Formio.setProjectUrl}\n * values will be the same value.\n *\n * ```ts\n * Formio.setBaseUrl('https://yourwebsite.com/forms');\n * Formio.setProjectUrl('https://yourwebsite.com/forms/project');\n *\n * // Now the Formio constructor will know what is the \"project\" and what is the form alias name. Without setBaseUrl\n * // and setProjectUrl, this would throw an error.\n *\n * const formio = new Formio('https://yourwebsite.com/forms/project/user');\n * formio.loadForm().then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * @param {string} url - The URL of the Base API url.\n */\n static setBaseUrl(url) {\n Formio.baseUrl = url;\n if (!Formio.projectUrlSet) {\n Formio.projectUrl = url;\n }\n }\n /**\n * Returns the current base url described at {@link Formio.setBaseUrl}\n *\n * @return {string} - The base url of the application.\n */\n static getBaseUrl() {\n return Formio.baseUrl;\n }\n static setApiUrl(url) {\n return Formio.setBaseUrl(url);\n }\n static getApiUrl() {\n return Formio.getBaseUrl();\n }\n static setAppUrl(url) {\n console.warn('Formio.setAppUrl() is deprecated. Use Formio.setProjectUrl instead.');\n Formio.projectUrl = url;\n Formio.projectUrlSet = true;\n }\n /**\n * Sets the Project Url for the application. This is an important method that needs to be set for all applications. It\n * is documented @ {@link Formio.setBaseUrl}.\n *\n * @param {string} url - The project api url.\n */\n static setProjectUrl(url) {\n Formio.projectUrl = url;\n Formio.projectUrlSet = true;\n }\n /**\n * The Auth URL can be set to customize the authentication requests made from an application. By default, this is\n * just the same value as {@link Formio.projectUrl}\n *\n * @param {string} url - The authentication url\n */\n static setAuthUrl(url) {\n Formio.authUrl = url;\n }\n static getAppUrl() {\n console.warn('Formio.getAppUrl() is deprecated. Use Formio.getProjectUrl instead.');\n return Formio.projectUrl;\n }\n /**\n * Returns the Project url described at {@link Formio.setProjectUrl}\n *\n * @return {string|string} - The Project Url.\n */\n static getProjectUrl() {\n return Formio.projectUrl;\n }\n /**\n * Clears the runtime internal API cache.\n *\n * @description By default, the Formio class will cache all API requests in memory so that any subsequent requests\n * using GET method will return the cached results as long as the API URl is the same as what was cached previously.\n * This cache can be cleared using this method as follows.\n *\n * ```ts\n * Formio.clearCache();\n * ```\n *\n * Or, if you just wish to clear a single request, then the {@link Formio.request#options.ignoreCache} option can be\n * provided when making an API request as follows.\n *\n * ```ts\n * Formio.loadForm({}, {\n * ignoreCache: true\n * }).then((form) => {\n * console.log(form);\n * });\n * ```\n *\n * Both of the following will ensure that a new request is made to the API server and that the results will not be\n * from the cached result.\n */\n static clearCache() {\n Formio.cache = {};\n }\n /**\n * Return the access information about a Project, such as the Role ID's for that project, and if the server is\n * configured to do so, the Form and Resource access configurations that the authenticated user has access to.\n *\n * @description This is useful for an application to determine the UI for a specific user to identify which forms they have\n * access to submit or read.\n *\n * @param {Formio} formio - The Formio instance.\n * @return {Promise<Response>}\n */\n static accessInfo(formio) {\n const projectUrl = formio ? formio.projectUrl : Formio.projectUrl;\n return Formio.makeRequest(formio, 'accessInfo', `${projectUrl}/access`);\n }\n /**\n * Returns an array of roles for the project, which includes the ID's and names of those roles.\n *\n * @param {Formio} formio - The Formio instance.\n * @return {Promise<Response>}\n */\n static projectRoles(formio) {\n const projectUrl = formio ? formio.projectUrl : Formio.projectUrl;\n return Formio.makeRequest(formio, 'projectRoles', `${projectUrl}/role`);\n }\n /**\n * Return the currentUser object. This will fetch the user from the server and respond with the Submission JSON\n * of that user object.\n *\n * @param {Formio} formio - The Formio instance\n * @param {object} options - The options passed to {@link Formio.getUser}\n * @return {Promise<R>|*}\n */\n static currentUser(formio, options = {}) {\n let authUrl = Formio.authUrl;\n if (!authUrl) {\n authUrl = formio ? formio.projectUrl : Formio.projectUrl || Formio.baseUrl;\n }\n authUrl += '/current';\n if (!options.ignoreCache || options.fromCurrent) {\n const user = Formio.getUser(options);\n if (user) {\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', Promise.resolve(user), {\n url: authUrl,\n method: 'GET',\n options,\n });\n }\n }\n const token = Formio.getToken(options);\n if ((!options || !options.external) && !token) {\n return Plugins_1.default.pluginAlter('wrapStaticRequestPromise', Promise.resolve(null), {\n url: authUrl,\n method: 'GET',\n options,\n });\n }\n options.fromCurrent = true;\n return Formio.makeRequest(formio, 'currentUser', authUrl, 'GET', null, options).then((response) => {\n Formio.setUser(response, options);\n return response;\n });\n }\n /**\n * Performs a logout of the Form.io application. This will reset all cache, as well as make a request to the logout\n * endpoint of the Form.io api platform.\n *\n * @param {Formio} formio - A Formio instance.\n * @param {object} options - Options passed to both {@link Formio.setToken} as well as {@link Formio.setUser}\n * @return {Promise<Response>}\n */\n static logout(formio, options = {}) {\n options.formio = formio;\n const projectUrl = Formio.authUrl\n ? Formio.authUrl\n : formio\n ? formio.projectUrl\n : Formio.baseUrl;\n const logout = () => {\n Formio.setToken(null, options);\n Formio.setUser(null, options);\n Formio.clearCache();\n localStorage.removeItem('useSessionToken');\n };\n return Formio.makeRequest(formio, 'logout', `${projectUrl}/logout`)\n .then(function (result) {\n logout();\n if (result.shouldRedirect && result.url) {\n window.location.href = result.url;\n }\n return result;\n })\n .catch(function (err) {\n logout();\n throw err;\n });\n }\n /**\n * Returns the query passed to a page in JSON object format.\n *\n * @description For example, lets say you visit your application using\n * the url as follows.\n *\n * ```\n * https://yourapplication.com/?token=23423423423&username=Joe\n * ```\n *\n * The following code will provide your application with the following.\n *\n * ```ts\n * const query Formio.pageQuery();\n * console.log(query.token); // Will print 23423423423\n * console.log(query.username); // Will print Joe\n * ```\n *\n * @return {{}} - A JSON object representation of the query that was passed to the URL of an application.\n */\n static pageQuery() {\n const pageQuery = {};\n pageQuery.paths = [];\n const hashes = location.hash.substr(1).replace(/\\?/g, '&').split('&');\n let parts = [];\n location.search\n .substr(1)\n .split('&')\n .forEach(function (item) {\n parts = item.split('=');\n if (parts.length > 1) {\n pageQuery[parts[0]] = parts[1] && decodeURIComponent(parts[1]);\n }\n });\n hashes.forEach(function (item) {\n parts = item.split('=');\n if (parts.length > 1) {\n pageQuery[parts[0]] = parts[1] && decodeURIComponent(parts[1]);\n }\n else if (item.indexOf('/') === 0) {\n pageQuery.paths = item.substr(1).split('/');\n }\n });\n return pageQuery;\n }\n /**\n * Much like {@link Formio.currentUser}, but instead automatically injects the Bearer tokens into the headers to\n * perform a Token swap of the OAuth token which will then return the JWT token for that user.\n *\n * @param {Formio} formio - The Formio instance\n * @param {string} token - An OAuth Bearer token to use for a token swap between the OAuth provider and Form.io\n * @return {Promise<R>|*}\n */\n static oAuthCurrentUser(formio, token) {\n return Formio.currentUser(formio, {\n external: true,\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n }\n static oauthLogoutURI(uri, options) {\n options = typeof options === 'string' ? { namespace: options } : options || {};\n const logoutURIName = `${options.namespace || Formio.namespace || 'formio'}LogoutAuthUrl`;\n localStorage.setItem(logoutURIName, uri);\n return Formio.tokens[logoutURIName];\n }\n /**\n * Perform a SAML initialization.\n *\n * @description Typically, you would use the {@link Formio.ssoInit} method to perform this function\n * since this method is an alias for the following.\n *\n * ```ts\n * Formio.samlInit();\n * Formio.ssoInit('saml'); // This is the exact same thing as calling Formio.samlInit\n * ```\n *\n * This method will return false if the process is just starting. The code below is a typical block of code that is\n * used to automatically trigger the SAML authentication process within your application using a Button component.\n *\n * ```ts\n * if (Formio.pageQuery().saml) {\n * const sso = Formio.samlInit();\n * if (sso) {\n * sso.then((user) => {\n * // The SSO user is now loaded!\n * console.log(user);\n * });\n * }\n * }\n * ```\n *\n * You can then place the following code withiin the \"Custom\" action of a Button component on your form.\n *\n * ```ts\n * Formio.samlInit();\n * ```\n *\n * Now when you click on this button, it will start the handshake process with SAML, and once it returns, will pass\n * a \"saml\" query parameter back to your application which will execute the code to load the current user from SAML.\n *\n * @param {object} options - Options to pass to the SAML initialization process.\n * @param {string} options.relay - The URL that will be used as the authentication \"relay\" that occurs during a SAML handshake process.\n * @return {boolean|Promise<Object>|void}\n */\n static samlInit(options = {}) {\n const query = Formio.pageQuery();\n if (query.saml) {\n Formio.setUser(null);\n const retVal = Formio.setToken(query.saml);\n let uri = window.location.toString();\n uri = uri.substring(0, uri.indexOf('?'));\n if (window.location.hash) {\n uri += window.location.hash;\n }\n window.history.replaceState({}, document.title, uri);\n return retVal;\n }\n // Set the relay if not provided.\n if (!options.relay) {\n options.relay = window.location.href;\n }\n // go to the saml sso endpoint for this project.\n const authUrl = Formio.authUrl || Formio.projectUrl;\n window.location.href = `${authUrl}/saml/sso?relay=${encodeURI(options.relay)}`;\n return false;\n }\n /**\n * Perform an Okta Authentication process using the {@link https://developer.okta.com/code/javascript/okta_auth_sdk|Okta SDK}.\n *\n * @description This method does require that you first include the Okta JavaScript SDK within your application as follows.\n *\n * First you need to include the Okta Authentication script.\n *\n * ```html\n * <script src=\"https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/2.0.1/okta-auth-js.min.js\" type=\"text/javascript\"></script>\n * ```\n *\n * Then you can call this method as follows.\n *\n * ```ts\n * Formio.oktaInit();\n * ```\n *\n * @param {object} options - Options that are passed directly to the {@link https://github.com/okta/okta-auth-js#configuration-reference|Okta SDK constructor}\n * @param {constructor} options.OktaAuth - If the OktaAuth constructor is not provided global to the application, it can be provided to this method using this property.\n * @param {Formio} options.formio - The Formio instance.\n * @param {Array<string>} options.scopes - Scopes that are passed to the {@link https://github.com/okta/okta-auth-js#tokengetwithredirectoptions|getWithRedirect} method from the Okta SDK.\n * @return {Promise<Object>}\n */\n static oktaInit(options = {}) {\n if (typeof OktaAuth !== 'undefined') {\n options.OktaAuth = OktaAuth;\n }\n if (typeof options.OktaAuth === 'undefined') {\n const errorMessage = 'Cannot find OktaAuth. Please include the Okta JavaScript SDK within your application. See https://developer.okta.com/code/javascript/okta_auth_sdk for an example.';\n console.warn(errorMessage);\n return Promise.reject(errorMessage);\n }\n return new Promise((resolve, reject) => {\n const Okta = options.OktaAuth;\n delete options.OktaAuth;\n const authClient = new Okta(options);\n authClient.tokenManager\n .get('accessToken')\n .then((accessToken) => {\n if (accessToken) {\n resolve(Formio.oAuthCurrentUser(options.formio, accessToken.accessToken));\n }\n else if (location.hash) {\n authClient.token\n .parseFromUrl()\n .then((token) => {\n authClient.tokenManager.add('accessToken', token);\n resolve(Formio.oAuthCurrentUser(options.formio, token.accessToken));\n })\n .catch((err) => {\n console.warn(err);\n reject(err);\n });\n }\n else {\n authClient.token.getWithRedirect({\n responseType: 'token',\n scopes: options.scopes,\n });\n resolve(false);\n }\n })\n .catch((error) => {\n reject(error);\n });\n });\n }\n /**\n * A common static method to trigger any SSO processes. This method is really just an alias for other static methods.\n *\n * @param {('saml'|'okta')} type - The type of SSO to trigger. 'saml' is an alias for {@link Formio.samlInit}, and 'okta' is an alias for {@link Formio.oktaInit}.\n * @param {object} options - Options to pass to the specific sso methods\n * @return {*|Promise<Object>|boolean|void}\n */\n static ssoInit(type, options = {}) {\n switch (type) {\n case 'saml':\n return Formio.samlInit(options);\n case 'okta':\n return Formio.oktaInit(options);\n default:\n console.warn('Unknown SSO type');\n return Promise.reject('Unknown SSO type');\n }\n }\n /**\n * Lazy load a remote library dependency.\n *\n * @description This is useful for components that wish to lazy load a required library\n * by adding that library to the <scripts> section of the HTML webpage, and then provide a promise that will resolve\n * when the library becomes available for use.\n *\n * @example Load Google Maps API.\n * ```ts\n * Formio.requireLibrary('googleMaps', 'google.maps.Map', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap', true).then(() => {\n * // Once the promise resolves, the following can now be used within your application.\n * const map = new google.maps.Map(document.getElementById(\"map\"), {...});\n * });\n * ```\n *\n * @param {string} name - The internal name to give to the library you are loading. This is useful for caching the library for later use.\n * @param {string} property - The name of the global property that will be added to the global namespace once the library has been loaded. This is used to check to see if the property exists before resolving the promise that the library is ready for use.\n * @param {string} src - The URL of the library to lazy load.\n * @param {boolean} polling - Determines if polling should be used to determine if they library is ready to use. If set to false, then it will rely on a global callback called ${name}Callback where \"name\" is the first property passed to this method. When this is called, that will indicate when the library is ready. In most cases, you will want to pass true to this parameter to initiate a polling method to check for the library availability in the global context.\n * @param {HTMLElement} rootElement - The element after which the resource would be attached (useful when requiring resources from ShadowRoot).\n * @return {Promise<object>} - A promise that will resolve when the plugin is ready to be used.\n */\n static requireLibrary(name, property, src, polling = false, onload, rootElement) {\n const resourceToDomOptions = {\n name,\n src,\n formio: Formio,\n onload,\n rootElement,\n };\n let hasResourceBeenAdded = false;\n if (!Formio.libraries.hasOwnProperty(name)) {\n Formio.libraries[name] = {};\n Formio.libraries[name].ready = new Promise((resolve, reject) => {\n Formio.libraries[name].resolve = resolve;\n Formio.libraries[name].reject = reject;\n });\n const callbackName = `${name}Callback`;\n if (!polling && !window[callbackName]) {\n window[callbackName] = () => Formio.libraries[name].resolve();\n }\n // See if the plugin already exists.\n const plugin = (0, lodash_1.get)(window, property);\n if (plugin) {\n Formio.libraries[name].resolve(plugin);\n }\n else {\n (0, utils_1.attachResourceToDom)(resourceToDomOptions);\n hasResourceBeenAdded = true;\n // if no callback is provided, then check periodically for the script.\n if (polling) {\n const interval = setInterval(() => {\n const plugin = (0, lodash_1.get)(window, property);\n if (plugin) {\n clearInterval(interval);\n Formio.libraries[name].resolve(plugin);\n }\n }, 200);\n }\n }\n }\n const lib = Formio.libraries[name];\n if (rootElement && !hasResourceBeenAdded) {\n (0, utils_1.attachResourceToDom)(resourceToDomOptions);\n }\n return onload && lib.loaded ? onload(lib.ready) : lib.ready;\n }\n /**\n * Determines if a lazy loaded library is ready to be used.\n *\n * @description Example: Let's assume that the example provided at {@link Formio.requireLibrary} was used elsewhere in your application.\n * You could now use the following within a separate place that will also resolve once the library is ready to be used.\n *\n * ```js\n * Formio.libraryReady('googleMaps').then(() => {\n * // Once the promise resolves, the following can now be used within your application.\n * const map = new google.maps.Map(document.getElementById(\"map\"), {...});\n * });\n * ```\n *\n * @param {string} name - The name of the library to check.\n * @return {Promise<object>} - A promise that will resolve when the library is ready to be used.\n */\n static libraryReady(name) {\n if (Formio.libraries.hasOwnProperty(name) && Formio.libraries[name].ready) {\n return Formio.libraries[name].ready;\n }\n return Promise.reject(`${name} library was not required.`);\n }\n /**\n * Clones the response from the API so that it cannot be mutated.\n *\n * @param response\n */\n static cloneResponse(response) {\n const copy = (0, fastCloneDeep_1.fastCloneDeep)(response);\n if (Array.isArray(response)) {\n copy.skip = response.skip;\n copy.limit = response.limit;\n copy.serverCount = response.serverCount;\n }\n return copy;\n }\n /**\n * Sets the project path type.\n *\n * @param type\n */\n static setPathType(type) {\n if (typeof type === 'string') {\n Formio.pathType = type;\n }\n }\n /**\n * Gets the project path type.\n */\n static getPathType() {\n return Formio.pathType;\n }\n}\nexports.Formio = Formio;\n/**\n * The base API url of the Form.io Platform. Example: https://api.form.io\n */\nFormio.baseUrl = 'https://api.form.io';\n/**\n * The project API url of the Form.io Project. Example: https://examples.form.io\n */\nFormio.projectUrl = '';\n/**\n * The project url to use for Authentication.\n */\nFormio.authUrl = '';\n/**\n * Set to true if the project url has been established with ```Formio.setProjectUrl()```\n */\nFormio.projectUrlSet = false;\n/**\n * The Form.io API Cache. This ensures that requests to the same API endpoint are cached.\n */\nFormio.cache = {};\n/**\n * The namespace used to save the Form.io Token's and variables within an application.\n */\nFormio.namespace = '';\n/**\n * Handles events fired within this SDK library.\n */\nFormio.events = new eventemitter3_1.default();\n/**\n * Stores all of the libraries lazy loaded with ```Formio.requireLibrary``` method.\n */\nFormio.libraries = {};\n/**\n * A direct interface to the Form.io fetch polyfill.\n */\nFormio.fetch = fetch;\n/**\n * A direct interface to the Form.io fetch Headers polyfill.\n */\nFormio.Headers = Headers;\n/**\n * All of the auth tokens for this session.\n */\nFormio.tokens = {};\n/**\n * The version of this library.\n */\nFormio.version = '---VERSION---';\n/**\n * The global options for the Formio library.\n */\nFormio.options = {};\n// Add Plugin methods.\nFormio.plugins = Plugins_1.default.plugins;\nFormio.deregisterPlugin = Plugins_1.default.deregisterPlugin;\nFormio.registerPlugin = Plugins_1.default.registerPlugin;\nFormio.getPlugin = Plugins_1.default.getPlugin;\nFormio.pluginWait = Plugins_1.default.pluginWait;\nFormio.pluginGet = Plugins_1.default.pluginGet;\nFormio.pluginAlter = Plugins_1.default.pluginAlter;\n// Adds Formio to the Plugins Interface.\nPlugins_1.default.Formio = Formio;\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/sdk/Formio.js?");
5087
5098
 
5088
5099
  /***/ }),
5089
5100
 
@@ -6336,7 +6347,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6336
6347
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6337
6348
 
6338
6349
  "use strict";
6339
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst process_1 = __webpack_require__(/*! @formio/core/process */ \"./node_modules/@formio/core/lib/process/index.js\");\nconst components_1 = __webpack_require__(/*! @formio/bootstrap/components */ \"./node_modules/@formio/bootstrap/lib/cjs/templates/components/index.js\");\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst Alert_1 = __importDefault(__webpack_require__(/*! ../alert/Alert */ \"./lib/cjs/components/alert/Alert.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst EditRowState = {\n New: 'new',\n Editing: 'editing',\n Saving: 'saving',\n Saved: 'saved',\n Viewing: 'viewing',\n Removed: 'removed',\n Draft: 'draft',\n};\nclass EditGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n type: 'editgrid',\n label: 'Edit Grid',\n key: 'editGrid',\n clearOnHide: true,\n input: true,\n tree: true,\n removeRow: 'Cancel',\n defaultOpen: false,\n openWhenEmpty: false,\n modal: false,\n components: [],\n inlineEdit: false,\n templates: {\n header: EditGridComponent.defaultHeaderTemplate,\n row: EditGridComponent.defaultRowTemplate,\n tableHeader: EditGridComponent.defaultTableHeaderTemplate,\n tableRow: EditGridComponent.defaultTableRowTemplate,\n footer: '',\n },\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Edit Grid',\n icon: 'tasks',\n group: 'data',\n documentation: '/userguide/form-building/data-components#edit-grid',\n showPreview: false,\n weight: 30,\n schema: EditGridComponent.schema(),\n };\n }\n static get defaultHeaderTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">{{ t(component.label) }}</div>\n {% } %}\n {% }) %}\n </div>`;\n }\n static get defaultTableHeaderTemplate() {\n return `\n <tr>\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">{{ component.label }}</td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">Actions</td>\n {% } %}\n </tr>\n `;\n }\n static get defaultRowTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">\n {{ isVisibleInRow(component) ? getView(component, row[component.key]) : ''}}\n </div>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <div class=\"col-sm-2\">\n <div class=\"btn-group pull-right\">\n <button class=\"btn btn-default btn-light btn-sm editRow\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </div>\n {% } %}\n </div>`;\n }\n static get defaultTableRowTemplate() {\n return `\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">\n {{ getView(component, row[component.key]) }}\n </td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">\n <div class=\"btn-group\">\n <button class=\"btn btn-default btn-light btn-sm editRow\" aria-label=\"{{ t('Edit row') }}\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\" aria-label=\"{{ t('Remove row') }}\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </td>\n {% } %}\n `;\n }\n get defaultDialogTemplate() {\n return `\n <h3 ${this._referenceAttributeName}=\"dialogHeader\">${this.t('Do you want to clear data?')}</h3>\n <div style=\"display:flex; justify-content: flex-end;\">\n <button ${this._referenceAttributeName}=\"dialogCancelButton\" class=\"btn btn-secondary\" aria-label=\"${this.t('Cancel')}\">${this.t('Cancel')}</button>\n <button ${this._referenceAttributeName}=\"dialogYesButton\" class=\"btn btn-danger\" aria-label=\"${this.t('Yes, delete it')}\">${this.t('Yes, delete it')}</button>\n </div>\n `;\n }\n get defaultRowTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableRowTemplate\n : EditGridComponent.defaultRowTemplate;\n }\n get defaultHeaderTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableHeaderTemplate\n : EditGridComponent.defaultHeaderTemplate;\n }\n get rowTemplate() {\n let rowTemplate;\n if (utils_1.Evaluator.noeval) {\n rowTemplate = this.displayAsTable ?\n components_1.editgrid.tableRow\n : components_1.editgrid.row;\n }\n else {\n rowTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableRow', this.defaultRowTemplate)\n : lodash_1.default.get(this.component, 'templates.row', this.defaultRowTemplate);\n }\n return rowTemplate;\n }\n get headerTemplate() {\n let headerTemplate;\n if (utils_1.Evaluator.noeval) {\n headerTemplate = this.displayAsTable ?\n components_1.editgrid.tableHeader\n : components_1.editgrid.header;\n }\n else {\n headerTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableHeader', this.defaultHeaderTemplate)\n : lodash_1.default.get(this.component, 'templates.header', this.defaultHeaderTemplate);\n }\n return headerTemplate;\n }\n /**\n * @returns {boolean} - Returns true if the component has nested components which don't trigger changes on the root level\n */\n get hasScopedChildren() {\n return !this.inlineEditMode;\n }\n get defaultSchema() {\n return EditGridComponent.schema();\n }\n get emptyValue() {\n return [];\n }\n get editgridKey() {\n return `editgrid-${this.key}`;\n }\n get rowRef() {\n return `${this.editgridKey}-row`;\n }\n get rowElements() {\n return this.refs[this.rowRef];\n }\n get rowRefs() {\n return this.refs[`editgrid-${this.component.key}-row`];\n }\n get addRowRef() {\n return `${this.editgridKey}-addRow`;\n }\n get addRowElements() {\n return this.refs[this.addRowRef];\n }\n get saveRowRef() {\n return `${this.editgridKey}-saveRow`;\n }\n get saveRowElements() {\n return this.refs[this.saveRowRef];\n }\n get cancelRowRef() {\n return `${this.editgridKey}-cancelRow`;\n }\n get cancelRowElements() {\n return this.refs[this.cancelRowRef];\n }\n get inlineEditMode() {\n return this.component.inlineEdit;\n }\n get saveEditMode() {\n return !this.inlineEditMode;\n }\n get minLength() {\n return this.builderMode ? 0 : lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n get data() {\n return this._data;\n }\n get dataValue() {\n return super.dataValue || [];\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get displayAsTable() {\n return this.component.displayAsTable;\n }\n set data(value) {\n this._data = value;\n const data = this.dataValue;\n (this.editRows || []).forEach((row, index) => {\n if (!data[index] && row.state !== EditRowState.New) {\n data[index] = {};\n }\n const rowData = data[index] || {};\n row.data = rowData;\n row.components.forEach((component) => {\n component.data = rowData;\n });\n });\n }\n get iteratableRows() {\n return this.editRows;\n }\n get defaultValue() {\n const value = super.defaultValue;\n const defaultValue = Array.isArray(value) ? value : [];\n lodash_1.default.times(this.minLength - defaultValue.length, () => defaultValue.push({}));\n return defaultValue;\n }\n constructor(...args) {\n super(...args);\n this.type = 'editgrid';\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n init() {\n if (this.builderMode) {\n this.editRows = [];\n return super.init();\n }\n this.components = this.components || [];\n const dataValue = this.dataValue;\n const openWhenEmpty = !dataValue.length && this.component.openWhenEmpty;\n if (openWhenEmpty) {\n const dataObj = {};\n this.editRows = [];\n this.createRow(dataObj, 0);\n }\n else {\n this.editRows = dataValue.map((row, rowIndex) => ({\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n error: null,\n rowIndex,\n }));\n }\n this.prevHasAddButton = this.hasAddButton();\n this.checkData();\n this.setVariableTypeComponents();\n if (this.variableTypeComponentsIndexes.length) {\n lodash_1.default.each(this.editRows || [], (editRow, rowIndex) => this.checkRowVariableTypeComponents(editRow, rowIndex));\n }\n }\n checkRowVariableTypeComponents(editRow, rowIndex) {\n const rowComponents = editRow.components;\n if (lodash_1.default.some(this.variableTypeComponentsIndexes, (compIndex) => {\n const variableTypeComp = rowComponents[compIndex];\n return variableTypeComp.type !== variableTypeComp.component.type;\n })) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex, true);\n }\n }\n setVariableTypeComponents() {\n //set components which type is changing within a row (e.g.,by mergeComponentSchema action)\n this.variableTypeComponentsIndexes = [];\n lodash_1.default.each(this.component.components, (comp, index) => {\n if (comp.typeChangeEnabled) {\n this.variableTypeComponentsIndexes.push(index);\n }\n });\n }\n isOpen(editRow) {\n return [EditRowState.New, EditRowState.Editing, EditRowState.Viewing].includes(editRow.state);\n }\n isComponentVisibleInSomeRow(component) {\n const rows = this.editRows;\n const savedStates = [EditRowState.Saved, EditRowState.Editing, EditRowState.Draft];\n const savedRows = rows.filter(row => lodash_1.default.includes(savedStates, row.state));\n this.visibleInHeader = this.visibleInHeader || [];\n const changeVisibleInHeader = (component, isVisible) => {\n if (!isVisible) {\n lodash_1.default.remove(this.visibleInHeader, (key) => key === component.key);\n }\n if (isVisible && !lodash_1.default.includes(this.visibleInHeader, component.key)) {\n this.visibleInHeader.push(component.key);\n }\n };\n if (lodash_1.default.isEmpty(rows)) {\n const rowComponents = this.createRowComponents({}, 0);\n let checkComponent;\n (0, utils_1.eachComponent)(rowComponents, (comp) => {\n if (comp.component.key === component.key) {\n checkComponent = comp;\n }\n comp.checkConditions();\n });\n const isVisible = checkComponent ? checkComponent.visible : true;\n [...this.components].forEach((comp) => this.removeComponent(comp, this.components));\n changeVisibleInHeader(component, isVisible);\n return isVisible;\n }\n const isOpenRowWhenEmpty = lodash_1.default.get(this.component, 'openWhenEmpty') && rows.length === 1 && rows[0].state === EditRowState.New;\n if (!lodash_1.default.isEmpty(rows) && lodash_1.default.isEmpty(savedRows) && !isOpenRowWhenEmpty) {\n return lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return lodash_1.default.some(isOpenRowWhenEmpty ? rows : savedRows, (row, index) => {\n const editingRow = row.state === EditRowState.Editing;\n let isVisible;\n if (!editingRow) {\n const flattenedComponents = this.flattenComponents(index);\n const instance = flattenedComponents[component.key];\n isVisible = instance ? instance.visible : true;\n changeVisibleInHeader(component, isVisible);\n }\n else {\n isVisible = lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return isVisible;\n });\n }\n render(children) {\n if (this.builderMode) {\n return super.render();\n }\n const dataValue = this.dataValue;\n const headerTemplate = this.headerTemplate;\n const t = this.t.bind(this);\n const templateName = this.displayAsTable ? 'editgridTable' : 'editgrid';\n return super.render(children || this.renderTemplate(templateName, {\n ref: {\n row: this.rowRef,\n addRow: this.addRowRef,\n saveRow: this.saveRowRef,\n cancelRow: this.cancelRowRef,\n },\n header: this.renderString(headerTemplate, {\n displayValue: (component) => this.displayComponentValue(component, true),\n components: this.component.components,\n value: dataValue,\n t\n }),\n footer: this.renderString(lodash_1.default.get(this.component, 'templates.footer'), {\n components: this.component.components,\n value: dataValue,\n t\n }),\n rows: this.editRows.map(this.renderRow.bind(this)),\n openRows: this.editRows.map((row) => this.isOpen(row)),\n errors: this.editRows.map((row) => row.error),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons: this.hasRemoveButtons(),\n }));\n }\n renderComponents(components) {\n components = components || this.getComponents();\n const children = components.map(component => component.render());\n const templateName = this.displayAsTable && this.prevHasAddButton ? 'tableComponents' : 'components';\n return this.renderTemplate(templateName, {\n children,\n components,\n });\n }\n attach(element) {\n if (this.builderMode) {\n return super.attach(element);\n }\n this.loadRefs(element, {\n [this.addRowRef]: 'multiple',\n [this.saveRowRef]: 'multiple',\n [this.cancelRowRef]: 'multiple',\n [this.rowRef]: 'multiple',\n });\n this.addRowElements.forEach((addButton) => {\n this.addEventListener(addButton, 'click', () => this.addRow());\n });\n let openRowCount = 0;\n this.rowElements.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow === null || editRow === void 0 ? void 0 : editRow.isRowSelected) {\n row.classList.add('selected');\n }\n if (this.isOpen(editRow)) {\n this.attachComponents(row, editRow.components);\n this.addEventListener(this.saveRowElements[openRowCount], 'click', () => this.saveRow(rowIndex, true));\n this.addEventListener(this.cancelRowElements[openRowCount], 'click', () => this.cancelRow(rowIndex));\n openRowCount++;\n }\n else {\n // Attach edit and remove button events.\n [\n {\n className: 'removeRow',\n event: 'click',\n action: () => this.removeRow(rowIndex, true),\n },\n {\n className: 'editRow',\n event: 'click',\n action: () => {\n this.editRow(rowIndex).then(() => {\n var _a;\n if (this.component.rowDrafts) {\n const errors = this.validateRow(editRow, false);\n const shouldShowRowErrorsAlert = this.component.modal && errors.length && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted);\n if (shouldShowRowErrorsAlert) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n }\n });\n },\n },\n {\n className: 'row',\n event: 'click',\n action: () => {\n row.classList.toggle('selected');\n let eventName = 'editGridSelectRow';\n if (Array.from(row.classList).includes('selected')) {\n editRow.isRowSelected = true;\n }\n else {\n delete editRow.isRowSelected;\n eventName = 'editGridUnSelectRow';\n }\n this.emit(eventName, {\n component: this.component,\n data: this.dataValue[rowIndex]\n });\n },\n }\n ].forEach(({ className, event, action, }) => {\n const elements = row.getElementsByClassName(className);\n Array.prototype.forEach.call(elements, (element) => {\n if (this.options.pdf && lodash_1.default.intersection(element.classList, ['editRow', 'removeRow']).length) {\n element.style.display = 'none';\n }\n else {\n this.addEventListener(element, event, action);\n }\n });\n });\n }\n });\n // Add open class to the element if any edit grid row is open\n if (openRowCount) {\n this.addClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n else {\n this.removeClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n return super.attach(element);\n }\n flattenRowDataValue(dataValue) {\n const flattened = {};\n Object.keys(dataValue).forEach((key) => {\n if (lodash_1.default.isObject(dataValue[key]) && !lodash_1.default.isNil(dataValue[key])) {\n Object.assign(flattened, this.flattenRowDataValue(dataValue[key]));\n }\n else {\n flattened[key] = dataValue[key];\n }\n });\n return flattened;\n }\n isComponentVisibleInRow(component, flattenedComponents) {\n const instance = flattenedComponents[component.key];\n return instance ? instance.visible : true;\n }\n displayComponentValue(component, header) {\n return !!((!component.hasOwnProperty('tableView') || component.tableView)\n && header ? this.isComponentVisibleInSomeRow(component) : lodash_1.default.includes(this.visibleInHeader, component.key));\n }\n renderRow(row, rowIndex) {\n const dataValue = this.dataValue;\n if (this.isOpen(row)) {\n return this.renderComponents(row.components);\n }\n else {\n const flattenedComponents = this.flattenComponents(rowIndex);\n const rowTemplate = this.rowTemplate;\n return this.renderString(rowTemplate, {\n row: dataValue[rowIndex] || {},\n data: this.data,\n rowIndex,\n components: this.component.components,\n flattenedComponents,\n displayValue: (component) => this.displayComponentValue(component),\n isVisibleInRow: (component) => this.isComponentVisibleInRow(component, flattenedComponents),\n getView: (component, data) => {\n var _a, _b;\n const instance = flattenedComponents[component.key];\n const view = instance ? instance.getView(data || instance.dataValue) : '';\n // If there is an html tag in view, don't allow it to be injected in template\n const htmlTagRegExp = new RegExp('<(.*?)>');\n return typeof view === 'string' && view.length && !((_a = instance.component) === null || _a === void 0 ? void 0 : _a.template) && htmlTagRegExp.test(view) && ((_b = instance.component) === null || _b === void 0 ? void 0 : _b.inputFormat) !== 'html'\n ? `<input type=\"text\" value=\"${view.replace(/\"/g, '&quot;')}\" readonly/>`\n : view;\n },\n state: this.editRows[rowIndex].state,\n t: this.t.bind(this)\n });\n }\n }\n eachComponent(fn, rowIndex) {\n lodash_1.default.each(this.getComponents(rowIndex), (component, index) => {\n if (fn(component, index) === false) {\n return false;\n }\n });\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n var _a;\n const rowData = this.dataValue[component.rowIndex];\n const editRowData = (_a = this.editRows[component.rowIndex]) === null || _a === void 0 ? void 0 : _a.data;\n component.data = rowData || editRowData;\n });\n }\n flattenComponents(rowIndex) {\n const result = {};\n this.everyComponent((component) => {\n result[component.component.flattenAs || component.key] = component;\n }, rowIndex);\n return result;\n }\n getComponents(rowIndex) {\n var _a;\n // Ensure editrows is set.\n this.editRows = this.editRows || [];\n return this.builderMode\n ? super.getComponents()\n : lodash_1.default.isNumber(rowIndex)\n ? (((_a = this.editRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.components) || [])\n : this.editRows.reduce((result, row) => result.concat(row.components || []), []);\n }\n destroy(all = false) {\n this.calculatedValue = undefined;\n super.destroy(all);\n }\n destroyComponents(all = false, rowIndex = 0) {\n if (this.builderMode) {\n return super.destroyComponents(all);\n }\n const components = this.getComponents(rowIndex).slice();\n components.forEach((comp) => this.removeComponent(comp, this.components, all));\n }\n createRow(dataObj, rowIndex) {\n const editRow = {\n components: this.createRowComponents(dataObj, rowIndex),\n data: dataObj,\n state: EditRowState.New,\n backup: null,\n error: null,\n rowIndex,\n };\n this.editRows.push(editRow);\n if (this.inlineEditMode) {\n this.dataValue.push(dataObj);\n }\n return editRow;\n }\n addRow() {\n if (this.options.readOnly) {\n return;\n }\n const dataObj = {};\n const rowIndex = this.editRows.length;\n const editRow = this.createRow(dataObj, rowIndex);\n if (editRow.state === EditRowState.New) {\n this.emptyRow = (0, utils_1.fastCloneDeep)(editRow.data);\n }\n if (this.inlineEditMode) {\n this.triggerChange();\n }\n this.emit('editGridAddRow', {\n component: this.component,\n row: editRow,\n });\n this.processRow('checkData', null, {}, editRow.data, editRow.components);\n if (this.component.modal) {\n this.addRowModal(rowIndex);\n }\n else {\n this.redraw();\n }\n return editRow;\n }\n addRowModal(rowIndex) {\n const modalContent = this.ce('div');\n const editRow = this.editRows[rowIndex];\n editRow.willBeSaved = false;\n const { components } = editRow;\n modalContent.innerHTML = this.renderComponents(components);\n const dialog = this.component.modal ? this.createModal(modalContent, {}, () => this.showDialog(rowIndex)) : undefined;\n dialog.classList.add(`editgrid-row-modal-${this.id}`);\n editRow.dialog = dialog;\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n this.alert = new Alert_1.default(dialog.refs.dialogContents, this);\n this.addEventListener(dialog, 'close', () => {\n if (!editRow.willBeSaved) {\n if (this.editRows[rowIndex] && this.editRows[rowIndex].state !== EditRowState.New) {\n this.editRows[rowIndex].components.forEach((comp) => {\n comp.setPristine(true);\n });\n }\n this.cancelRow(rowIndex);\n }\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n // Remove references to dialog elements to prevent possible in some cases memory leaks\n delete editRow.confirmationDialog;\n delete editRow.dialog;\n });\n dialog.refs.dialogContents.appendChild(this.ce('button', {\n class: 'btn btn-primary',\n onClick: () => {\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!errors.length || this.component.rowDrafts) {\n editRow.willBeSaved = true;\n dialog.close();\n this.saveRow(rowIndex, true);\n }\n else {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n },\n }, this.component.saveRow || 'Save'));\n return this.attachComponents(modalContent, components);\n }\n showDialog(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow.state === EditRowState.New ? lodash_1.default.isEqual(this.emptyRow, editRow.data) : lodash_1.default.isEqual(editRow.backup, editRow.data)) {\n return Promise.resolve();\n }\n const wrapper = this.ce('div', { ref: 'confirmationDialog' });\n const dialogContent = this.component.dialogTemplate || this.defaultDialogTemplate;\n wrapper.innerHTML = dialogContent;\n wrapper.refs = {};\n this.loadRefs.call(wrapper, wrapper, {\n dialogHeader: 'single',\n dialogCancelButton: 'single',\n dialogYesButton: 'single',\n });\n const dialog = this.createModal(wrapper);\n dialog.classList.add(`editgrid-row-modal-confirmation-${this.id}`);\n const close = (event) => {\n event.preventDefault();\n dialog.close();\n };\n let dialogResult;\n const promise = new Promise((resolve, reject) => {\n dialogResult = { resolve, reject };\n });\n this.addEventListener(wrapper.refs.dialogYesButton, 'click', (event) => {\n close(event);\n dialogResult.resolve();\n });\n this.addEventListener(wrapper.refs.dialogCancelButton, 'click', (event) => {\n close(event);\n dialogResult.reject();\n });\n editRow.confirmationDialog = dialog;\n return promise;\n }\n editRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n const isAlreadyEditing = editRow.state === EditRowState.Editing || editRow.state === EditRowState.New;\n if (!editRow || isAlreadyEditing) {\n return Promise.resolve();\n }\n editRow.prevState = editRow.state;\n editRow.state = this.options.readOnly ? EditRowState.Viewing : EditRowState.Editing;\n if (this.lazyLoad && (editRow.components.length === 0)) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex);\n }\n const dataSnapshot = (0, utils_1.fastCloneDeep)(editRow.data);\n if (this.inlineEditMode) {\n editRow.backup = dataSnapshot;\n }\n else {\n editRow.backup = (0, utils_1.fastCloneDeep)(editRow.data);\n editRow.data = dataSnapshot;\n this.restoreRowContext(editRow);\n }\n if (this.component.modal) {\n return this.addRowModal(rowIndex);\n }\n return this.redraw();\n }\n clearErrors(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow && Array.isArray(editRow.components)) {\n editRow.components.forEach((comp) => {\n comp.setPristine(true);\n comp.setCustomValidity('');\n });\n }\n }\n cancelRow(rowIndex) {\n if (this.options.readOnly) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n switch (editRow.state) {\n case EditRowState.New: {\n editRow.state = EditRowState.Removed;\n this.clearErrors(rowIndex);\n this.destroyComponents(false, rowIndex);\n if (this.inlineEditMode) {\n this.splice(rowIndex);\n }\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n break;\n }\n case EditRowState.Editing: {\n editRow.state = editRow.prevState;\n if (this.inlineEditMode) {\n this.dataValue[rowIndex] = editRow.backup;\n }\n editRow.data = editRow.backup;\n editRow.backup = null;\n this.restoreRowContext(editRow);\n this.clearErrors(rowIndex);\n break;\n }\n }\n this.emit('editGridCancelRow', {\n instance: this,\n component: this.component,\n editRow,\n });\n this.checkValidity(null, true);\n this.redraw();\n if (this.component.rowDrafts) {\n this.checkValidity(this.data, false);\n }\n }\n saveRow(rowIndex, modified) {\n var _a, _b;\n const editRow = this.editRows[rowIndex];\n if (this.options.readOnly) {\n return;\n }\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n // Mark the row with a 'Saving' state to trigger validation for future row changes\n if (editRow.state === EditRowState.New) {\n editRow.state = EditRowState.Saving;\n }\n const errors = this.validateRow(editRow, true);\n if (!this.component.rowDrafts) {\n if (errors.length) {\n return false;\n }\n }\n if (this.saveEditMode) {\n const dataValue = this.dataValue;\n if ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a.focusedComponent) === null || _b === void 0 ? void 0 : _b.component.typeChangeEnabled) {\n this.root.focusedComponent = null;\n }\n switch (editRow.state) {\n case EditRowState.Saving: {\n const newIndex = dataValue.length;\n dataValue.push(editRow.data);\n editRow.components.forEach(component => component.rowIndex = newIndex);\n if (rowIndex !== newIndex) {\n this.editRows.splice(rowIndex, 1);\n this.editRows.splice(newIndex, 0, editRow);\n }\n break;\n }\n case EditRowState.Editing: {\n dataValue[rowIndex] = editRow.data;\n break;\n }\n }\n }\n editRow.state = this.component.rowDrafts && errors.length ? EditRowState.Draft : EditRowState.Saved;\n editRow.backup = null;\n this.updateValue();\n this.emit('editGridSaveRow', {\n component: this.component,\n row: editRow.data,\n instance: this\n });\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n if (this.component.rowDrafts) {\n editRow.components.forEach(comp => comp.setPristine(this.pristine));\n }\n this.checkValidity(null, true);\n this.redraw();\n if (editRow.alerts) {\n editRow.alerts = false;\n }\n return true;\n }\n beforeFocus(component) {\n if ('beforeFocus' in this.parent) {\n this.parent.beforeFocus(this);\n }\n const relativePath = this.getRelativePath(component.path);\n const arrayPath = (0, utils_1.getArrayFromComponentPath)(relativePath);\n const rowIndex = arrayPath[0];\n let rowToEditIndex = arrayPath[0];\n this.editRows.forEach((row, indexInArray) => {\n if (row.rowIndex === rowIndex) {\n rowToEditIndex = indexInArray;\n }\n });\n if (lodash_1.default.isNumber(rowToEditIndex)) {\n this.editRow(rowToEditIndex);\n }\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n });\n }\n updateRowsComponents(rowIndex) {\n this.editRows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(row.components, rowIndex + index);\n });\n }\n baseRemoveRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n editRow.state = EditRowState.Removed;\n this.destroyComponents(false, rowIndex);\n return editRow;\n }\n removeRow(rowIndex, modified) {\n if (this.options.readOnly) {\n return;\n }\n this.clearErrors(rowIndex);\n this.baseRemoveRow(rowIndex);\n this.removeSubmissionMetadataRow(rowIndex);\n this.splice(rowIndex);\n this.emit('editGridDeleteRow', {\n index: rowIndex\n });\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n this.updateRowsComponents(rowIndex);\n this.updateValue();\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n this.checkValidity(null, true);\n this.checkData();\n this.redraw();\n }\n createRowComponents(row, rowIndex, recreatePartially) {\n // Iterate through existing components and destroy the ones with the same rowIndex.\n if (this.components) {\n for (let i = 0; i < this.components.length; i++) {\n if (this.components[i].rowIndex === rowIndex) {\n this.components[i].destroy();\n this.components.splice(i, 1);\n }\n }\n }\n const currentRowComponents = lodash_1.default.get(this.editRows, `[${rowIndex}].components`, null);\n return this.component.components.map((col, colIndex) => {\n var _a;\n if (recreatePartially && currentRowComponents && this.variableTypeComponentsIndexes.length) {\n const currentComp = currentRowComponents[colIndex];\n const shouldRecreate = lodash_1.default.includes(this.variableTypeComponentsIndexes, colIndex) && (currentComp === null || currentComp === void 0 ? void 0 : currentComp.type) !== ((_a = currentComp === null || currentComp === void 0 ? void 0 : currentComp.component) === null || _a === void 0 ? void 0 : _a.type);\n if (!shouldRecreate) {\n return currentComp;\n }\n col = currentComp.component;\n }\n const column = lodash_1.default.clone(col);\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n options.onChange = (flags = {}, changed, modified) => {\n var _a, _b;\n if (((_a = changed.instance.root) === null || _a === void 0 ? void 0 : _a.id) && (((_b = this.root) === null || _b === void 0 ? void 0 : _b.id) !== changed.instance.root.id)) {\n changed.instance.root.triggerChange(flags, changed, modified);\n }\n else if (!this.component.modal) {\n this.triggerRootChange(flags, changed, modified);\n }\n if (this.inlineEditMode) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n this.processRow('checkData', null, Object.assign(Object.assign({}, flags), { changed }), editRow.data, editRow.components);\n this.validateRow(editRow, false);\n }\n if (this.variableTypeComponentsIndexes.length) {\n this.checkRowVariableTypeComponents(editRow, rowIndex);\n this.redraw();\n }\n };\n const comp = this.createComponent(lodash_1.default.assign({}, column, { row: options.row }), options, row, null, recreatePartially && currentRowComponents ? currentRowComponents[colIndex] : null);\n comp.rowIndex = rowIndex;\n comp.inEditGrid = true;\n return comp;\n });\n }\n hasOpenRows() {\n return this.editRows.some(row => this.isOpen(row));\n }\n getAttachedData(data = null) {\n const ourData = (0, utils_1.fastCloneDeep)(data || this._data || this.rootValue);\n lodash_1.default.set(ourData, this.key, this.editRows.map((row) => row.data));\n return ourData;\n }\n shouldValidateDraft(editRow) {\n var _a, _b;\n // Draft rows should be validated only when there was an attempt to submit a form\n return (editRow.state === EditRowState.Draft &&\n !this.pristine &&\n !((_a = this.root) === null || _a === void 0 ? void 0 : _a.pristine) &&\n !this.hasOpenRows()) ||\n ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted);\n }\n shouldValidateRow(editRow, dirty, fromSubmission) {\n return this.shouldValidateDraft(editRow) ||\n editRow.state === EditRowState.Saving ||\n editRow.state === EditRowState.Editing ||\n editRow.alerts ||\n fromSubmission ||\n dirty;\n }\n validateRow(editRow, dirty, forceSilentCheck, fromSubmission) {\n var _a;\n editRow.errors = [];\n if (this.shouldValidateRow(editRow, dirty, fromSubmission)) {\n const silentCheck = (this.component.rowDrafts && !this.shouldValidateDraft(editRow)) || forceSilentCheck;\n const rootValue = (0, utils_1.fastCloneDeep)(this.rootValue);\n const editGridValue = lodash_1.default.get(rootValue, this.path, []);\n editGridValue[editRow.rowIndex] = editRow.data;\n lodash_1.default.set(rootValue, this.path, editGridValue);\n const validationProcessorProcess = (context) => this.validationProcessor(context, { dirty, silentCheck });\n editRow.errors = (0, process_1.processSync)({\n components: (0, utils_1.fastCloneDeep)(this.component.components).map((component) => {\n component.parentPath = `${this.path}[${editRow.rowIndex}]`;\n return component;\n }),\n data: rootValue,\n row: editRow.data,\n process: 'validateRow',\n instances: this.componentsMap,\n scope: { errors: [] },\n processors: [\n {\n process: validationProcessorProcess,\n processSync: validationProcessorProcess\n }\n ]\n }).errors;\n }\n // TODO: this is essentially running its own custom validation and should be moved into a validation rule\n if (this.component.validate && this.component.validate.row) {\n const valid = this.evaluate(this.component.validate.row, {\n valid: (editRow.length === 0),\n row: editRow.data\n }, 'valid', true);\n if (valid.toString() !== 'true') {\n editRow.errors.push({\n type: 'error',\n rowError: true,\n message: valid.toString()\n });\n }\n if (valid === null) {\n editRow.errors.push({\n type: 'error',\n message: `Invalid row validation for ${this.key}`\n });\n }\n }\n if (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted)) {\n this.showRowErrorAlerts(editRow, editRow.errors);\n }\n return editRow.errors;\n }\n showRowErrorAlerts(editRow, errors) {\n if (editRow.alerts) {\n if (this.alert) {\n if (errors.length) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n else {\n this.alert.clear();\n this.alert = null;\n }\n }\n }\n }\n /**\n * @returns {boolean} - Return that this component processes its own validation.\n */\n get processOwnValidation() {\n return true;\n }\n checkComponentValidity(data, dirty, row, options = {}, errors = []) {\n var _a, _b;\n const { silentCheck, fromSubmission } = options;\n const superValid = super.checkComponentValidity(data, dirty, row, options, errors);\n // If super tells us that component invalid and there is no need to update alerts, just return false\n if (!superValid && (!this.alert && !this.hasOpenRows())) {\n return false;\n }\n let rowsEditing = false;\n const allRowErrors = [];\n this.editRows.forEach((editRow, index) => {\n // Trigger all errors on the row.\n const rowErrors = this.validateRow(editRow, dirty, silentCheck, fromSubmission);\n errors.push(...rowErrors);\n allRowErrors.push(...rowErrors);\n if (this.rowRefs) {\n const rowContainer = this.rowRefs[index];\n if (rowContainer) {\n const errorContainer = rowContainer.querySelector('.editgrid-row-error');\n if (rowErrors.length && errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n const rowError = rowErrors.find(error => error.rowError);\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(rowError ? rowError.message : this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n this.removeClass(errorContainer, 'help-block');\n }\n }\n }\n // If this is a dirty check, and any rows are still editing, we need to throw validation error.\n rowsEditing |= (dirty && this.isOpen(editRow));\n });\n if (allRowErrors.length) {\n if (!silentCheck && (dirty || this.dirty) && (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted))) {\n this.setCustomValidity(this.t(this.errorMessage('invalidRowsError')), dirty);\n this.removeClass(this.element, 'has-error');\n }\n return false;\n }\n else if (rowsEditing && this.saveEditMode && !this.component.openWhenEmpty) {\n this._errors = this.setCustomValidity(this.t(this.errorMessage('unsavedRowsError')), dirty);\n errors.push(...this._errors);\n return false;\n }\n const message = this.invalid || this.invalidMessage(data, dirty, false, row);\n if (allRowErrors.length && ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted) && !message) {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n this.root.showErrors([message]);\n }\n else {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n }\n return superValid;\n }\n setRowInvalid(ref, index) {\n const editRow = this.editRows[index];\n const errorContainer = ref.querySelector('.editgrid-row-error');\n if (errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n changeState(changed, flags) {\n if (this.visible && (changed || (flags.resetValue && this.component.modalEdit))) {\n this.rebuild();\n }\n else {\n this.redraw();\n }\n }\n setValue(value, flags = {}) {\n if (!value) {\n value = this.defaultValue;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n return false;\n }\n }\n const changed = this.hasChanged(value, this.dataValue);\n if (this.parent && !this.options.server) {\n this.parent.checkComponentConditions();\n }\n this.dataValue = value;\n // Refresh editRow data when data changes.\n this.dataValue.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n editRow.data = row;\n this.restoreRowContext(editRow, flags);\n editRow.state = EditRowState.Saved;\n editRow.backup = null;\n editRow.errors = [];\n }\n else {\n this.editRows[rowIndex] = {\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n errors: [],\n };\n }\n });\n let { length: dataLength } = this.dataValue;\n // If the last row is a new row, then do not remove it.\n if (this.editRows[dataLength] && (this.editRows[dataLength].state === EditRowState.New)) {\n dataLength = (dataLength + 1);\n }\n this.editRows.slice(dataLength).forEach((editRow, index) => this.baseRemoveRow(dataLength + index));\n this.editRows = this.editRows.slice(0, dataLength);\n this.openWhenEmpty();\n this.updateOnChange(flags, changed);\n // do not call checkData with server option, it is called when change is triggered in updateOnChange\n if (!this.options.server) {\n this.checkData();\n }\n this.changeState(changed, flags);\n return changed;\n }\n openWhenEmpty() {\n const shouldBeOpened = !this.dataValue.length && this.component.openWhenEmpty;\n const hasNoRows = !this.editRows.length;\n if (hasNoRows && shouldBeOpened && !this.builderMode) {\n const dataObj = {};\n this.createRow(dataObj, 0);\n }\n }\n restoreRowContext(editRow, flags = {}) {\n editRow.components.forEach((component) => {\n component.data = editRow.data;\n this.setNestedValue(component, editRow.data, flags);\n });\n }\n emptyRows() {\n this.editRows.forEach((editRow, index) => this.destroyComponents(false, index));\n this.editRows = [];\n }\n resetValue() {\n super.resetValue();\n this.emptyRows();\n }\n}\nexports[\"default\"] = EditGridComponent;\nEditGridComponent.prototype.hasChanged = Component_1.default.prototype.hasChanged;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/editgrid/EditGrid.js?");
6350
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst process_1 = __webpack_require__(/*! @formio/core/process */ \"./node_modules/@formio/core/lib/process/index.js\");\nconst components_1 = __webpack_require__(/*! @formio/bootstrap/components */ \"./node_modules/@formio/bootstrap/lib/cjs/templates/components/index.js\");\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst Alert_1 = __importDefault(__webpack_require__(/*! ../alert/Alert */ \"./lib/cjs/components/alert/Alert.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst EditRowState = {\n New: 'new',\n Editing: 'editing',\n Saved: 'saved',\n Viewing: 'viewing',\n Removed: 'removed',\n Draft: 'draft',\n};\nclass EditGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n type: 'editgrid',\n label: 'Edit Grid',\n key: 'editGrid',\n clearOnHide: true,\n input: true,\n tree: true,\n removeRow: 'Cancel',\n defaultOpen: false,\n openWhenEmpty: false,\n modal: false,\n components: [],\n inlineEdit: false,\n templates: {\n header: EditGridComponent.defaultHeaderTemplate,\n row: EditGridComponent.defaultRowTemplate,\n tableHeader: EditGridComponent.defaultTableHeaderTemplate,\n tableRow: EditGridComponent.defaultTableRowTemplate,\n footer: '',\n },\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Edit Grid',\n icon: 'tasks',\n group: 'data',\n documentation: '/userguide/form-building/data-components#edit-grid',\n showPreview: false,\n weight: 30,\n schema: EditGridComponent.schema(),\n };\n }\n static get defaultHeaderTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">{{ t(component.label) }}</div>\n {% } %}\n {% }) %}\n </div>`;\n }\n static get defaultTableHeaderTemplate() {\n return `\n <tr>\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">{{ component.label }}</td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">Actions</td>\n {% } %}\n </tr>\n `;\n }\n static get defaultRowTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">\n {{ isVisibleInRow(component) ? getView(component, row[component.key]) : ''}}\n </div>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <div class=\"col-sm-2\">\n <div class=\"btn-group pull-right\">\n <button class=\"btn btn-default btn-light btn-sm editRow\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </div>\n {% } %}\n </div>`;\n }\n static get defaultTableRowTemplate() {\n return `\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">\n {{ getView(component, row[component.key]) }}\n </td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">\n <div class=\"btn-group\">\n <button class=\"btn btn-default btn-light btn-sm editRow\" aria-label=\"{{ t('Edit row') }}\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\" aria-label=\"{{ t('Remove row') }}\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </td>\n {% } %}\n `;\n }\n get defaultDialogTemplate() {\n return `\n <h3 ${this._referenceAttributeName}=\"dialogHeader\">${this.t('Do you want to clear data?')}</h3>\n <div style=\"display:flex; justify-content: flex-end;\">\n <button ${this._referenceAttributeName}=\"dialogCancelButton\" class=\"btn btn-secondary\" aria-label=\"${this.t('Cancel')}\">${this.t('Cancel')}</button>\n <button ${this._referenceAttributeName}=\"dialogYesButton\" class=\"btn btn-danger\" aria-label=\"${this.t('Yes, delete it')}\">${this.t('Yes, delete it')}</button>\n </div>\n `;\n }\n get defaultRowTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableRowTemplate\n : EditGridComponent.defaultRowTemplate;\n }\n get defaultHeaderTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableHeaderTemplate\n : EditGridComponent.defaultHeaderTemplate;\n }\n get rowTemplate() {\n let rowTemplate;\n if (utils_1.Evaluator.noeval) {\n rowTemplate = this.displayAsTable ?\n components_1.editgrid.tableRow\n : components_1.editgrid.row;\n }\n else {\n rowTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableRow', this.defaultRowTemplate)\n : lodash_1.default.get(this.component, 'templates.row', this.defaultRowTemplate);\n }\n return rowTemplate;\n }\n get headerTemplate() {\n let headerTemplate;\n if (utils_1.Evaluator.noeval) {\n headerTemplate = this.displayAsTable ?\n components_1.editgrid.tableHeader\n : components_1.editgrid.header;\n }\n else {\n headerTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableHeader', this.defaultHeaderTemplate)\n : lodash_1.default.get(this.component, 'templates.header', this.defaultHeaderTemplate);\n }\n return headerTemplate;\n }\n /**\n * @returns {boolean} - Returns true if the component has nested components which don't trigger changes on the root level\n */\n get hasScopedChildren() {\n return !this.inlineEditMode;\n }\n get defaultSchema() {\n return EditGridComponent.schema();\n }\n get emptyValue() {\n return [];\n }\n get editgridKey() {\n return `editgrid-${this.key}`;\n }\n get rowRef() {\n return `${this.editgridKey}-row`;\n }\n get rowElements() {\n return this.refs[this.rowRef];\n }\n get rowRefs() {\n return this.refs[`editgrid-${this.component.key}-row`];\n }\n get addRowRef() {\n return `${this.editgridKey}-addRow`;\n }\n get addRowElements() {\n return this.refs[this.addRowRef];\n }\n get saveRowRef() {\n return `${this.editgridKey}-saveRow`;\n }\n get saveRowElements() {\n return this.refs[this.saveRowRef];\n }\n get cancelRowRef() {\n return `${this.editgridKey}-cancelRow`;\n }\n get cancelRowElements() {\n return this.refs[this.cancelRowRef];\n }\n get inlineEditMode() {\n return this.component.inlineEdit;\n }\n get saveEditMode() {\n return !this.inlineEditMode;\n }\n get minLength() {\n return this.builderMode ? 0 : lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n get data() {\n return this._data;\n }\n get dataValue() {\n return super.dataValue || [];\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get displayAsTable() {\n return this.component.displayAsTable;\n }\n set data(value) {\n this._data = value;\n const data = this.dataValue;\n (this.editRows || []).forEach((row, index) => {\n if (!data[index] && row.state !== EditRowState.New) {\n data[index] = {};\n }\n const rowData = data[index] || {};\n row.data = rowData;\n row.components.forEach((component) => {\n component.data = rowData;\n });\n });\n }\n get iteratableRows() {\n return this.editRows;\n }\n get defaultValue() {\n const value = super.defaultValue;\n const defaultValue = Array.isArray(value) ? value : [];\n lodash_1.default.times(this.minLength - defaultValue.length, () => defaultValue.push({}));\n return defaultValue;\n }\n constructor(...args) {\n super(...args);\n this.type = 'editgrid';\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n init() {\n if (this.builderMode) {\n this.editRows = [];\n return super.init();\n }\n this.components = this.components || [];\n const dataValue = this.dataValue;\n const openWhenEmpty = !dataValue.length && this.component.openWhenEmpty;\n if (openWhenEmpty) {\n const dataObj = {};\n this.editRows = [];\n this.createRow(dataObj, 0);\n }\n else {\n this.editRows = dataValue.map((row, rowIndex) => ({\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n error: null,\n rowIndex,\n }));\n }\n this.prevHasAddButton = this.hasAddButton();\n this.checkData();\n this.setVariableTypeComponents();\n if (this.variableTypeComponentsIndexes.length) {\n lodash_1.default.each(this.editRows || [], (editRow, rowIndex) => this.checkRowVariableTypeComponents(editRow, rowIndex));\n }\n }\n checkRowVariableTypeComponents(editRow, rowIndex) {\n const rowComponents = editRow.components;\n if (lodash_1.default.some(this.variableTypeComponentsIndexes, (compIndex) => {\n const variableTypeComp = rowComponents[compIndex];\n return variableTypeComp.type !== variableTypeComp.component.type;\n })) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex, true);\n }\n }\n setVariableTypeComponents() {\n //set components which type is changing within a row (e.g.,by mergeComponentSchema action)\n this.variableTypeComponentsIndexes = [];\n lodash_1.default.each(this.component.components, (comp, index) => {\n if (comp.typeChangeEnabled) {\n this.variableTypeComponentsIndexes.push(index);\n }\n });\n }\n isOpen(editRow) {\n return [EditRowState.New, EditRowState.Editing, EditRowState.Viewing].includes(editRow.state);\n }\n isComponentVisibleInSomeRow(component) {\n const rows = this.editRows;\n const savedStates = [EditRowState.Saved, EditRowState.Editing, EditRowState.Draft];\n const savedRows = rows.filter(row => lodash_1.default.includes(savedStates, row.state));\n this.visibleInHeader = this.visibleInHeader || [];\n const changeVisibleInHeader = (component, isVisible) => {\n if (!isVisible) {\n lodash_1.default.remove(this.visibleInHeader, (key) => key === component.key);\n }\n if (isVisible && !lodash_1.default.includes(this.visibleInHeader, component.key)) {\n this.visibleInHeader.push(component.key);\n }\n };\n if (lodash_1.default.isEmpty(rows)) {\n const rowComponents = this.createRowComponents({}, 0);\n let checkComponent;\n (0, utils_1.eachComponent)(rowComponents, (comp) => {\n if (comp.component.key === component.key) {\n checkComponent = comp;\n }\n comp.checkConditions();\n });\n const isVisible = checkComponent ? checkComponent.visible : true;\n [...this.components].forEach((comp) => this.removeComponent(comp, this.components));\n changeVisibleInHeader(component, isVisible);\n return isVisible;\n }\n const isOpenRowWhenEmpty = lodash_1.default.get(this.component, 'openWhenEmpty') && rows.length === 1 && rows[0].state === EditRowState.New;\n if (!lodash_1.default.isEmpty(rows) && lodash_1.default.isEmpty(savedRows) && !isOpenRowWhenEmpty) {\n return lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return lodash_1.default.some(isOpenRowWhenEmpty ? rows : savedRows, (row, index) => {\n const editingRow = row.state === EditRowState.Editing;\n let isVisible;\n if (!editingRow) {\n const flattenedComponents = this.flattenComponents(index);\n const instance = flattenedComponents[component.key];\n isVisible = instance ? instance.visible : true;\n changeVisibleInHeader(component, isVisible);\n }\n else {\n isVisible = lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return isVisible;\n });\n }\n render(children) {\n if (this.builderMode) {\n return super.render();\n }\n const dataValue = this.dataValue;\n const headerTemplate = this.headerTemplate;\n const t = this.t.bind(this);\n const templateName = this.displayAsTable ? 'editgridTable' : 'editgrid';\n return super.render(children || this.renderTemplate(templateName, {\n ref: {\n row: this.rowRef,\n addRow: this.addRowRef,\n saveRow: this.saveRowRef,\n cancelRow: this.cancelRowRef,\n },\n header: this.renderString(headerTemplate, {\n displayValue: (component) => this.displayComponentValue(component, true),\n components: this.component.components,\n value: dataValue,\n t\n }),\n footer: this.renderString(lodash_1.default.get(this.component, 'templates.footer'), {\n components: this.component.components,\n value: dataValue,\n t\n }),\n rows: this.editRows.map(this.renderRow.bind(this)),\n openRows: this.editRows.map((row) => this.isOpen(row)),\n errors: this.editRows.map((row) => row.error),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons: this.hasRemoveButtons(),\n }));\n }\n renderComponents(components) {\n components = components || this.getComponents();\n const children = components.map(component => component.render());\n const templateName = this.displayAsTable && this.prevHasAddButton ? 'tableComponents' : 'components';\n return this.renderTemplate(templateName, {\n children,\n components,\n });\n }\n attach(element) {\n if (this.builderMode) {\n return super.attach(element);\n }\n this.loadRefs(element, {\n [this.addRowRef]: 'multiple',\n [this.saveRowRef]: 'multiple',\n [this.cancelRowRef]: 'multiple',\n [this.rowRef]: 'multiple',\n });\n this.addRowElements.forEach((addButton) => {\n this.addEventListener(addButton, 'click', () => this.addRow());\n });\n let openRowCount = 0;\n this.rowElements.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow === null || editRow === void 0 ? void 0 : editRow.isRowSelected) {\n row.classList.add('selected');\n }\n if (this.isOpen(editRow)) {\n this.attachComponents(row, editRow.components);\n this.addEventListener(this.saveRowElements[openRowCount], 'click', () => this.saveRow(rowIndex, true));\n this.addEventListener(this.cancelRowElements[openRowCount], 'click', () => this.cancelRow(rowIndex));\n openRowCount++;\n }\n else {\n // Attach edit and remove button events.\n [\n {\n className: 'removeRow',\n event: 'click',\n action: () => this.removeRow(rowIndex, true),\n },\n {\n className: 'editRow',\n event: 'click',\n action: () => {\n this.editRow(rowIndex).then(() => {\n var _a;\n if (this.component.rowDrafts) {\n const errors = this.validateRow(editRow, false);\n const shouldShowRowErrorsAlert = this.component.modal && errors.length && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted);\n if (shouldShowRowErrorsAlert) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n }\n });\n },\n },\n {\n className: 'row',\n event: 'click',\n action: () => {\n row.classList.toggle('selected');\n let eventName = 'editGridSelectRow';\n if (Array.from(row.classList).includes('selected')) {\n editRow.isRowSelected = true;\n }\n else {\n delete editRow.isRowSelected;\n eventName = 'editGridUnSelectRow';\n }\n this.emit(eventName, {\n component: this.component,\n data: this.dataValue[rowIndex]\n });\n },\n }\n ].forEach(({ className, event, action, }) => {\n const elements = row.getElementsByClassName(className);\n Array.prototype.forEach.call(elements, (element) => {\n if (this.options.pdf && lodash_1.default.intersection(element.classList, ['editRow', 'removeRow']).length) {\n element.style.display = 'none';\n }\n else {\n this.addEventListener(element, event, action);\n }\n });\n });\n }\n });\n // Add open class to the element if any edit grid row is open\n if (openRowCount) {\n this.addClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n else {\n this.removeClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n return super.attach(element);\n }\n flattenRowDataValue(dataValue) {\n const flattened = {};\n Object.keys(dataValue).forEach((key) => {\n if (lodash_1.default.isObject(dataValue[key]) && !lodash_1.default.isNil(dataValue[key])) {\n Object.assign(flattened, this.flattenRowDataValue(dataValue[key]));\n }\n else {\n flattened[key] = dataValue[key];\n }\n });\n return flattened;\n }\n isComponentVisibleInRow(component, flattenedComponents) {\n const instance = flattenedComponents[component.key];\n return instance ? instance.visible : true;\n }\n displayComponentValue(component, header) {\n return !!((!component.hasOwnProperty('tableView') || component.tableView)\n && header ? this.isComponentVisibleInSomeRow(component) : lodash_1.default.includes(this.visibleInHeader, component.key));\n }\n renderRow(row, rowIndex) {\n const dataValue = this.dataValue;\n if (this.isOpen(row)) {\n return this.renderComponents(row.components);\n }\n else {\n const flattenedComponents = this.flattenComponents(rowIndex);\n const rowTemplate = this.rowTemplate;\n return this.renderString(rowTemplate, {\n row: dataValue[rowIndex] || {},\n data: this.data,\n rowIndex,\n components: this.component.components,\n flattenedComponents,\n displayValue: (component) => this.displayComponentValue(component),\n isVisibleInRow: (component) => this.isComponentVisibleInRow(component, flattenedComponents),\n getView: (component, data) => {\n var _a, _b;\n const instance = flattenedComponents[component.key];\n const view = instance ? instance.getView(data || instance.dataValue) : '';\n // If there is an html tag in view, don't allow it to be injected in template\n const htmlTagRegExp = new RegExp('<(.*?)>');\n return typeof view === 'string' && view.length && !((_a = instance.component) === null || _a === void 0 ? void 0 : _a.template) && htmlTagRegExp.test(view) && ((_b = instance.component) === null || _b === void 0 ? void 0 : _b.inputFormat) !== 'html'\n ? `<input type=\"text\" value=\"${view.replace(/\"/g, '&quot;')}\" readonly/>`\n : view;\n },\n state: this.editRows[rowIndex].state,\n t: this.t.bind(this)\n });\n }\n }\n eachComponent(fn, rowIndex) {\n lodash_1.default.each(this.getComponents(rowIndex), (component, index) => {\n if (fn(component, index) === false) {\n return false;\n }\n });\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n var _a;\n const rowData = this.dataValue[component.rowIndex];\n const editRowData = (_a = this.editRows[component.rowIndex]) === null || _a === void 0 ? void 0 : _a.data;\n component.data = rowData || editRowData;\n });\n }\n flattenComponents(rowIndex) {\n const result = {};\n this.everyComponent((component) => {\n result[component.component.flattenAs || component.key] = component;\n }, rowIndex);\n return result;\n }\n getComponents(rowIndex) {\n var _a;\n // Ensure editrows is set.\n this.editRows = this.editRows || [];\n return this.builderMode\n ? super.getComponents()\n : lodash_1.default.isNumber(rowIndex)\n ? (((_a = this.editRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.components) || [])\n : this.editRows.reduce((result, row) => result.concat(row.components || []), []);\n }\n destroy(all = false) {\n this.calculatedValue = undefined;\n super.destroy(all);\n }\n destroyComponents(all = false, rowIndex = 0) {\n if (this.builderMode) {\n return super.destroyComponents(all);\n }\n const components = this.getComponents(rowIndex).slice();\n components.forEach((comp) => this.removeComponent(comp, this.components, all));\n }\n createRow(dataObj, rowIndex) {\n const editRow = {\n components: this.createRowComponents(dataObj, rowIndex),\n data: dataObj,\n state: EditRowState.New,\n backup: null,\n error: null,\n rowIndex,\n };\n this.editRows.push(editRow);\n if (this.inlineEditMode) {\n this.dataValue.push(dataObj);\n }\n return editRow;\n }\n addRow() {\n if (this.options.readOnly) {\n return;\n }\n const dataObj = {};\n const rowIndex = this.editRows.length;\n const editRow = this.createRow(dataObj, rowIndex);\n if (editRow.state === EditRowState.New) {\n this.emptyRow = (0, utils_1.fastCloneDeep)(editRow.data);\n }\n if (this.inlineEditMode) {\n this.triggerChange();\n }\n this.emit('editGridAddRow', {\n component: this.component,\n row: editRow,\n });\n this.processRow('checkData', null, {}, editRow.data, editRow.components);\n if (this.component.modal) {\n this.addRowModal(rowIndex);\n }\n else {\n this.redraw();\n }\n return editRow;\n }\n addRowModal(rowIndex) {\n const modalContent = this.ce('div');\n const editRow = this.editRows[rowIndex];\n editRow.willBeSaved = false;\n const { components } = editRow;\n modalContent.innerHTML = this.renderComponents(components);\n const dialog = this.component.modal ? this.createModal(modalContent, {}, () => this.showDialog(rowIndex)) : undefined;\n dialog.classList.add(`editgrid-row-modal-${this.id}`);\n editRow.dialog = dialog;\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n this.alert = new Alert_1.default(dialog.refs.dialogContents, this);\n this.addEventListener(dialog, 'close', () => {\n if (!editRow.willBeSaved) {\n if (this.editRows[rowIndex] && this.editRows[rowIndex].state !== EditRowState.New) {\n this.editRows[rowIndex].components.forEach((comp) => {\n comp.setPristine(true);\n });\n }\n this.cancelRow(rowIndex);\n }\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n // Remove references to dialog elements to prevent possible in some cases memory leaks\n delete editRow.confirmationDialog;\n delete editRow.dialog;\n });\n dialog.refs.dialogContents.appendChild(this.ce('button', {\n class: 'btn btn-primary',\n onClick: () => {\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!errors.length || this.component.rowDrafts) {\n editRow.willBeSaved = true;\n dialog.close();\n this.saveRow(rowIndex, true);\n }\n else {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n },\n }, this.component.saveRow || 'Save'));\n return this.attachComponents(modalContent, components);\n }\n showDialog(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow.state === EditRowState.New ? lodash_1.default.isEqual(this.emptyRow, editRow.data) : lodash_1.default.isEqual(editRow.backup, editRow.data)) {\n return Promise.resolve();\n }\n const wrapper = this.ce('div', { ref: 'confirmationDialog' });\n const dialogContent = this.component.dialogTemplate || this.defaultDialogTemplate;\n wrapper.innerHTML = dialogContent;\n wrapper.refs = {};\n this.loadRefs.call(wrapper, wrapper, {\n dialogHeader: 'single',\n dialogCancelButton: 'single',\n dialogYesButton: 'single',\n });\n const dialog = this.createModal(wrapper);\n dialog.classList.add(`editgrid-row-modal-confirmation-${this.id}`);\n const close = (event) => {\n event.preventDefault();\n dialog.close();\n };\n let dialogResult;\n const promise = new Promise((resolve, reject) => {\n dialogResult = { resolve, reject };\n });\n this.addEventListener(wrapper.refs.dialogYesButton, 'click', (event) => {\n close(event);\n dialogResult.resolve();\n });\n this.addEventListener(wrapper.refs.dialogCancelButton, 'click', (event) => {\n close(event);\n dialogResult.reject();\n });\n editRow.confirmationDialog = dialog;\n return promise;\n }\n editRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n const isAlreadyEditing = editRow.state === EditRowState.Editing || editRow.state === EditRowState.New;\n if (!editRow || isAlreadyEditing) {\n return Promise.resolve();\n }\n editRow.prevState = editRow.state;\n editRow.state = this.options.readOnly ? EditRowState.Viewing : EditRowState.Editing;\n if (this.lazyLoad && (editRow.components.length === 0)) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex);\n }\n const dataSnapshot = (0, utils_1.fastCloneDeep)(editRow.data);\n if (this.inlineEditMode) {\n editRow.backup = dataSnapshot;\n }\n else {\n editRow.backup = (0, utils_1.fastCloneDeep)(editRow.data);\n editRow.data = dataSnapshot;\n this.restoreRowContext(editRow);\n }\n if (this.component.modal) {\n return this.addRowModal(rowIndex);\n }\n return this.redraw();\n }\n clearErrors(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow && Array.isArray(editRow.components)) {\n editRow.components.forEach((comp) => {\n comp.setPristine(true);\n comp.setCustomValidity('');\n });\n }\n }\n cancelRow(rowIndex) {\n if (this.options.readOnly) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n switch (editRow.state) {\n case EditRowState.New: {\n editRow.state = EditRowState.Removed;\n this.clearErrors(rowIndex);\n this.destroyComponents(false, rowIndex);\n if (this.inlineEditMode) {\n this.splice(rowIndex);\n }\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n break;\n }\n case EditRowState.Editing: {\n editRow.state = editRow.prevState;\n if (this.inlineEditMode) {\n this.dataValue[rowIndex] = editRow.backup;\n }\n editRow.data = editRow.backup;\n editRow.backup = null;\n this.restoreRowContext(editRow);\n this.clearErrors(rowIndex);\n break;\n }\n }\n this.emit('editGridCancelRow', {\n instance: this,\n component: this.component,\n editRow,\n });\n this.checkValidity(null, true);\n this.redraw();\n if (this.component.rowDrafts) {\n this.checkValidity(this.data, false);\n }\n }\n saveRow(rowIndex, modified) {\n var _a, _b;\n const editRow = this.editRows[rowIndex];\n if (this.options.readOnly) {\n return;\n }\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!this.component.rowDrafts) {\n if (errors.length) {\n return false;\n }\n }\n if (this.saveEditMode) {\n const dataValue = this.dataValue;\n if ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a.focusedComponent) === null || _b === void 0 ? void 0 : _b.component.typeChangeEnabled) {\n this.root.focusedComponent = null;\n }\n switch (editRow.state) {\n case EditRowState.New: {\n const newIndex = dataValue.length;\n dataValue.push(editRow.data);\n editRow.components.forEach(component => component.rowIndex = newIndex);\n if (rowIndex !== newIndex) {\n this.editRows.splice(rowIndex, 1);\n this.editRows.splice(newIndex, 0, editRow);\n }\n break;\n }\n case EditRowState.Editing: {\n dataValue[rowIndex] = editRow.data;\n break;\n }\n }\n }\n editRow.state = this.component.rowDrafts && errors.length ? EditRowState.Draft : EditRowState.Saved;\n editRow.backup = null;\n this.updateValue();\n this.emit('editGridSaveRow', {\n component: this.component,\n row: editRow.data,\n instance: this\n });\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n if (this.component.rowDrafts) {\n editRow.components.forEach(comp => comp.setPristine(this.pristine));\n }\n this.checkValidity(null, true);\n this.redraw();\n if (editRow.alerts) {\n editRow.alerts = false;\n }\n return true;\n }\n beforeFocus(component) {\n if ('beforeFocus' in this.parent) {\n this.parent.beforeFocus(this);\n }\n const relativePath = this.getRelativePath(component.path);\n const arrayPath = (0, utils_1.getArrayFromComponentPath)(relativePath);\n const rowIndex = arrayPath[0];\n let rowToEditIndex = arrayPath[0];\n this.editRows.forEach((row, indexInArray) => {\n if (row.rowIndex === rowIndex) {\n rowToEditIndex = indexInArray;\n }\n });\n if (lodash_1.default.isNumber(rowToEditIndex)) {\n this.editRow(rowToEditIndex);\n }\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n });\n }\n updateRowsComponents(rowIndex) {\n this.editRows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(row.components, rowIndex + index);\n });\n }\n baseRemoveRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n editRow.state = EditRowState.Removed;\n this.destroyComponents(false, rowIndex);\n return editRow;\n }\n removeRow(rowIndex, modified) {\n if (this.options.readOnly) {\n return;\n }\n this.clearErrors(rowIndex);\n this.baseRemoveRow(rowIndex);\n this.removeSubmissionMetadataRow(rowIndex);\n this.splice(rowIndex);\n this.emit('editGridDeleteRow', {\n index: rowIndex\n });\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n this.updateRowsComponents(rowIndex);\n this.updateValue();\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n this.checkValidity(null, true);\n this.checkData();\n this.redraw();\n }\n createRowComponents(row, rowIndex, recreatePartially) {\n // Iterate through existing components and destroy the ones with the same rowIndex.\n if (this.components) {\n for (let i = 0; i < this.components.length; i++) {\n if (this.components[i].rowIndex === rowIndex) {\n this.components[i].destroy();\n this.components.splice(i, 1);\n }\n }\n }\n const currentRowComponents = lodash_1.default.get(this.editRows, `[${rowIndex}].components`, null);\n return this.component.components.map((col, colIndex) => {\n var _a;\n if (recreatePartially && currentRowComponents && this.variableTypeComponentsIndexes.length) {\n const currentComp = currentRowComponents[colIndex];\n const shouldRecreate = lodash_1.default.includes(this.variableTypeComponentsIndexes, colIndex) && (currentComp === null || currentComp === void 0 ? void 0 : currentComp.type) !== ((_a = currentComp === null || currentComp === void 0 ? void 0 : currentComp.component) === null || _a === void 0 ? void 0 : _a.type);\n if (!shouldRecreate) {\n return currentComp;\n }\n col = currentComp.component;\n }\n const column = lodash_1.default.clone(col);\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n options.onChange = (flags = {}, changed, modified) => {\n var _a, _b;\n if (((_a = changed.instance.root) === null || _a === void 0 ? void 0 : _a.id) && (((_b = this.root) === null || _b === void 0 ? void 0 : _b.id) !== changed.instance.root.id)) {\n changed.instance.root.triggerChange(flags, changed, modified);\n }\n else if (!this.component.modal) {\n this.triggerRootChange(flags, changed, modified);\n }\n if (this.inlineEditMode) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n this.processRow('checkData', null, Object.assign(Object.assign({}, flags), { changed }), editRow.data, editRow.components);\n this.validateRow(editRow, false);\n }\n if (this.variableTypeComponentsIndexes.length) {\n this.checkRowVariableTypeComponents(editRow, rowIndex);\n this.redraw();\n }\n };\n const comp = this.createComponent(lodash_1.default.assign({}, column, { row: options.row }), options, row, null, recreatePartially && currentRowComponents ? currentRowComponents[colIndex] : null);\n comp.rowIndex = rowIndex;\n comp.inEditGrid = true;\n return comp;\n });\n }\n hasOpenRows() {\n return this.editRows.some(row => this.isOpen(row));\n }\n getAttachedData(data = null) {\n const ourData = (0, utils_1.fastCloneDeep)(data || this._data || this.rootValue);\n lodash_1.default.set(ourData, this.key, this.editRows.map((row) => row.data));\n return ourData;\n }\n shouldValidateDraft(editRow) {\n var _a, _b;\n // Draft rows should be validated only when there was an attempt to submit a form\n return (editRow.state === EditRowState.Draft &&\n !this.pristine &&\n !((_a = this.root) === null || _a === void 0 ? void 0 : _a.pristine) &&\n !this.hasOpenRows()) ||\n ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted);\n }\n shouldValidateRow(editRow, dirty, fromSubmission) {\n return this.shouldValidateDraft(editRow) ||\n editRow.state === EditRowState.New ||\n editRow.state === EditRowState.Editing ||\n editRow.alerts ||\n fromSubmission ||\n dirty;\n }\n validateRow(editRow, dirty, forceSilentCheck, fromSubmission) {\n var _a;\n editRow.errors = [];\n if (this.shouldValidateRow(editRow, dirty, fromSubmission)) {\n const silentCheck = (this.component.rowDrafts && !this.shouldValidateDraft(editRow)) || forceSilentCheck;\n const rootValue = (0, utils_1.fastCloneDeep)(this.rootValue);\n const editGridValue = lodash_1.default.get(rootValue, this.path, []);\n editGridValue[editRow.rowIndex] = editRow.data;\n lodash_1.default.set(rootValue, this.path, editGridValue);\n const validationProcessorProcess = (context) => this.validationProcessor(context, { dirty, silentCheck });\n const errors = (0, process_1.processSync)({\n components: (0, utils_1.fastCloneDeep)(this.component.components).map((component) => {\n component.parentPath = `${this.path}[${editRow.rowIndex}]`;\n return component;\n }),\n data: rootValue,\n row: editRow.data,\n process: 'validateRow',\n instances: this.componentsMap,\n scope: { errors: [] },\n processors: [\n {\n process: validationProcessorProcess,\n processSync: validationProcessorProcess\n }\n ]\n }).errors;\n editRow.errors = (this.component.modal || this.component.rowDrafts)\n ? errors\n : errors.filter((err) => lodash_1.default.find(this.visibleErrors, ['component.id', err.component.id]));\n }\n // TODO: this is essentially running its own custom validation and should be moved into a validation rule\n if (this.component.validate && this.component.validate.row) {\n const valid = this.evaluate(this.component.validate.row, {\n valid: (editRow.length === 0),\n row: editRow.data\n }, 'valid', true);\n if (valid.toString() !== 'true') {\n editRow.errors.push({\n type: 'error',\n rowError: true,\n message: valid.toString()\n });\n }\n if (valid === null) {\n editRow.errors.push({\n type: 'error',\n message: `Invalid row validation for ${this.key}`\n });\n }\n }\n if (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted)) {\n this.showRowErrorAlerts(editRow, editRow.errors);\n }\n return editRow.errors;\n }\n showRowErrorAlerts(editRow, errors) {\n if (editRow.alerts) {\n if (this.alert) {\n if (errors.length) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n else {\n this.alert.clear();\n this.alert = null;\n }\n }\n }\n }\n /**\n * @returns {boolean} - Return that this component processes its own validation.\n */\n get processOwnValidation() {\n return true;\n }\n checkComponentValidity(data, dirty, row, options = {}, errors = []) {\n var _a, _b;\n const { silentCheck, fromSubmission } = options;\n const superValid = super.checkComponentValidity(data, dirty, row, options, errors);\n // If super tells us that component invalid and there is no need to update alerts, just return false\n if (!superValid && (!this.alert && !this.hasOpenRows())) {\n return false;\n }\n let rowsEditing = false;\n const allRowErrors = [];\n this.editRows.forEach((editRow, index) => {\n // Trigger all errors on the row.\n const rowErrors = this.validateRow(editRow, dirty, silentCheck, fromSubmission);\n errors.push(...rowErrors);\n allRowErrors.push(...rowErrors);\n if (this.rowRefs) {\n const rowContainer = this.rowRefs[index];\n if (rowContainer) {\n const errorContainer = rowContainer.querySelector('.editgrid-row-error');\n if (rowErrors.length && errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n const rowError = rowErrors.find(error => error.rowError);\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(rowError ? rowError.message : this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n this.removeClass(errorContainer, 'help-block');\n }\n }\n }\n // If this is a dirty check, and any rows are still editing, we need to throw validation error.\n rowsEditing |= (dirty && this.isOpen(editRow));\n });\n if (allRowErrors.length) {\n if (!silentCheck && (dirty || this.dirty) && (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted))) {\n this.setCustomValidity(this.t(this.errorMessage('invalidRowsError')), dirty);\n this.removeClass(this.element, 'has-error');\n }\n return false;\n }\n else if (rowsEditing && this.saveEditMode && !this.component.openWhenEmpty) {\n this._errors = this.setCustomValidity(this.t(this.errorMessage('unsavedRowsError')), dirty);\n errors.push(...this._errors);\n return false;\n }\n const message = this.invalid || this.invalidMessage(data, dirty, false, row);\n if (allRowErrors.length && ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted) && !message) {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n this.root.showErrors([message]);\n }\n else {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n }\n return superValid;\n }\n setRowInvalid(ref, index) {\n const editRow = this.editRows[index];\n const errorContainer = ref.querySelector('.editgrid-row-error');\n if (errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n changeState(changed, flags) {\n if (this.visible && (changed || (flags.resetValue && this.component.modalEdit))) {\n this.rebuild();\n }\n else {\n this.redraw();\n }\n }\n setValue(value, flags = {}) {\n if (!value) {\n value = this.defaultValue;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n return false;\n }\n }\n const changed = this.hasChanged(value, this.dataValue);\n if (this.parent && !this.options.server) {\n this.parent.checkComponentConditions();\n }\n this.dataValue = value;\n // Refresh editRow data when data changes.\n this.dataValue.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n editRow.data = row;\n this.restoreRowContext(editRow, flags);\n editRow.state = EditRowState.Saved;\n editRow.backup = null;\n editRow.errors = [];\n }\n else {\n this.editRows[rowIndex] = {\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n errors: [],\n };\n }\n });\n let { length: dataLength } = this.dataValue;\n // If the last row is a new row, then do not remove it.\n if (this.editRows[dataLength] && (this.editRows[dataLength].state === EditRowState.New)) {\n dataLength = (dataLength + 1);\n }\n this.editRows.slice(dataLength).forEach((editRow, index) => this.baseRemoveRow(dataLength + index));\n this.editRows = this.editRows.slice(0, dataLength);\n this.openWhenEmpty();\n this.updateOnChange(flags, changed);\n // do not call checkData with server option, it is called when change is triggered in updateOnChange\n if (!this.options.server) {\n this.checkData();\n }\n this.changeState(changed, flags);\n return changed;\n }\n openWhenEmpty() {\n const shouldBeOpened = !this.dataValue.length && this.component.openWhenEmpty;\n const hasNoRows = !this.editRows.length;\n if (hasNoRows && shouldBeOpened && !this.builderMode) {\n const dataObj = {};\n this.createRow(dataObj, 0);\n }\n }\n restoreRowContext(editRow, flags = {}) {\n editRow.components.forEach((component) => {\n component.data = editRow.data;\n this.setNestedValue(component, editRow.data, flags);\n });\n }\n emptyRows() {\n this.editRows.forEach((editRow, index) => this.destroyComponents(false, index));\n this.editRows = [];\n }\n resetValue() {\n super.resetValue();\n this.emptyRows();\n }\n}\nexports[\"default\"] = EditGridComponent;\nEditGridComponent.prototype.hasChanged = Component_1.default.prototype.hasChanged;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/editgrid/EditGrid.js?");
6340
6351
 
6341
6352
  /***/ }),
6342
6353
 
@@ -6699,7 +6710,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6699
6710
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6700
6711
 
6701
6712
  "use strict";
6702
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst text_mask_addons_1 = __webpack_require__(/*! @formio/text-mask-addons */ \"./node_modules/@formio/text-mask-addons/dist/textMaskAddons.js\");\nconst vanilla_text_mask_1 = __webpack_require__(/*! @formio/vanilla-text-mask */ \"./node_modules/@formio/vanilla-text-mask/dist/vanillaTextMask.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass NumberComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'number',\n label: 'Number',\n key: 'number',\n validate: {\n min: '',\n max: '',\n step: 'any',\n integer: ''\n }\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Number',\n icon: 'hashtag',\n group: 'basic',\n documentation: '/userguide/form-building/form-components#number',\n weight: 30,\n schema: NumberComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return NumberComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: [...super.conditionOperatorsSettings.operators, 'lessThan', 'greaterThan', 'lessThanOrEqual', 'greaterThanOrEqual'], valueComponent(classComp) {\n return Object.assign(Object.assign({}, classComp), { type: 'number' });\n } });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.number];\n }\n constructor(...args) {\n var _a, _b, _c;\n super(...args);\n const separators = (0, utils_1.getNumberSeparators)(this.options.language || navigator.language);\n this.decimalSeparator = this.options.decimalSeparator = this.component.decimalSymbol || this.options.decimalSeparator\n || ((_a = this.options.properties) === null || _a === void 0 ? void 0 : _a.decimalSeparator)\n || separators.decimalSeparator;\n if (this.component.delimiter) {\n this.delimiter = this.component.thousandsSeparator || ((_b = this.options.properties) === null || _b === void 0 ? void 0 : _b.thousandsSeparator) || this.options.thousandsSeparator || separators.delimiter;\n }\n else {\n if (this.component.thousandsSeparator || ((_c = this.options.properties) === null || _c === void 0 ? void 0 : _c.thousandsSeparator) || this.options.thousandsSeparator) {\n console.warn('In order for thousands separator to work properly, you must set the delimiter to true in the component json');\n }\n this.delimiter = '';\n }\n const requireDecimal = lodash_1.default.get(this.component, 'requireDecimal', false);\n this.decimalLimit = (0, utils_1.getNumberDecimalLimit)(this.component, requireDecimal ? 2 : 20);\n // Currencies to override BrowserLanguage Config. Object key {}\n if (lodash_1.default.has(this.options, `languageOverride.${this.options.language}`)) {\n const override = lodash_1.default.get(this.options, `languageOverride.${this.options.language}`);\n this.decimalSeparator = override.decimalSeparator;\n this.delimiter = override.delimiter;\n }\n this.numberMask = this.createNumberMask();\n }\n /**\n * Creates the number mask for normal numbers.\n * @returns {*} - The number mask.\n */\n createNumberMask() {\n return (0, text_mask_addons_1.createNumberMask)({\n prefix: '',\n suffix: '',\n requireDecimal: lodash_1.default.get(this.component, 'requireDecimal', false),\n thousandsSeparatorSymbol: this.delimiter || '',\n decimalSymbol: lodash_1.default.get(this.component, 'decimalSymbol', this.decimalSeparator),\n decimalLimit: lodash_1.default.get(this.component, 'decimalLimit', this.decimalLimit),\n allowNegative: lodash_1.default.get(this.component, 'allowNegative', true),\n allowDecimal: this.isDecimalAllowed(),\n });\n }\n get defaultSchema() {\n return NumberComponent.schema();\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (typeof defaultValue === 'string') {\n // Default value may be a string or have custom thousands separators or decimal symbols, so we need to call\n // parseNumber on it\n defaultValue = this.parseNumber(defaultValue);\n }\n if (!defaultValue && this.component.defaultValue === 0) {\n defaultValue = this.component.defaultValue;\n }\n if (!this.component.multiple && lodash_1.default.isArray(defaultValue)) {\n defaultValue = !defaultValue[0] && defaultValue[0] !== 0 ? null : defaultValue[0];\n }\n return defaultValue;\n }\n isDecimalAllowed() {\n return lodash_1.default.get(this.component, 'allowDecimal', !(this.component.validate && this.component.validate.integer));\n }\n /**\n * parses a numeric string by removing the delimiters and replacing the decimal separator back to '.' so that it can\n * be processed by either parseInt or parseFloat\n * @param {string} value the value to be parsed\n * @returns {number} a parsed number\n */\n parseNumber(value) {\n // Remove delimiters and convert decimal separator to dot.\n value = value.split(this.delimiter).join('').replace(this.decimalSeparator, '.');\n if (this.component.validate && this.component.validate.integer) {\n return parseInt(value, 10);\n }\n else {\n return parseFloat(value);\n }\n }\n setInputMask(input) {\n let numberPattern = '[0-9';\n numberPattern += this.decimalSeparator || '';\n numberPattern += this.delimiter || '';\n numberPattern += ']*';\n input.setAttribute('pattern', numberPattern);\n input.mask = (0, vanilla_text_mask_1.maskInput)({\n inputElement: input,\n mask: this.numberMask,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n });\n }\n get inputInfo() {\n const info = super.inputInfo;\n if (this.component.mask) {\n info.attr.type = 'password';\n }\n else {\n info.attr.type = 'text';\n }\n info.attr.inputmode = this.isDecimalAllowed() ? 'decimal' : 'numeric';\n info.changeEvent = 'input';\n return info;\n }\n getValueAt(index) {\n if (!this.refs.input.length || !this.refs.input[index]) {\n return null;\n }\n const val = this.refs.input[index].value;\n return val && val !== '-_' ? this.parseNumber(val) : null;\n }\n setValueAt(index, value, flags = {}) {\n return super.setValueAt(index, this.formatValue(this.parseValue(value)), flags);\n }\n /**\n * Converts a string to a floating point number, formats the number based on the parsed float function\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) and then returns the\n * formatted number back as a string\n * Example Input: \"123.456,22\"\n * Example Output: \"123456,22\"\n * @param {string | number} input the numeric string to parse\n * @returns {string | null} a parsed string\n */\n parseValue(input) {\n if (typeof input === 'string') {\n input = input.split(this.delimiter).join('').replace(this.decimalSeparator, '.');\n }\n let value = parseFloat(input);\n if (!lodash_1.default.isNaN(value)) {\n value = String(value).replace('.', this.decimalSeparator);\n }\n else {\n value = null;\n }\n return value;\n }\n formatValue(value) {\n if (this.component.requireDecimal && value && !value.includes(this.decimalSeparator)) {\n return `${value}${this.decimalSeparator}${lodash_1.default.repeat('0', this.decimalLimit)}`;\n }\n else if (this.component.requireDecimal && value && value.includes(this.decimalSeparator)) {\n return `${value}${lodash_1.default.repeat('0', this.decimalLimit - value.split(this.decimalSeparator)[1].length)}`;\n }\n return value;\n }\n focus() {\n const input = this.refs.input[0];\n if (input) {\n super.focus.call(this);\n input.setSelectionRange(0, input.value.length);\n }\n }\n getMaskedValue(value) {\n value = value === null ? '0' : value.toString();\n if (value.includes('.') && '.' !== this.decimalSeparator) {\n value = value.replace('.', this.decimalSeparator);\n }\n return (0, vanilla_text_mask_1.conformToMask)(this.formatValue(value), this.numberMask).conformedValue;\n }\n getValueAsString(value, options) {\n if (!value && value !== 0) {\n return '';\n }\n value = this.getWidgetValueAsString(value, options);\n if (Array.isArray(value)) {\n return value.map((val) => this.getMaskedValue(val)).join(', ');\n }\n return this.getMaskedValue(value);\n }\n addFocusBlurEvents(element) {\n super.addFocusBlurEvents(element);\n this.addEventListener(element, 'blur', () => {\n element.value = this.getValueAsString(this.formatValue(this.parseValue(element.value)));\n });\n }\n}\nexports[\"default\"] = NumberComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/number/Number.js?");
6713
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst text_mask_addons_1 = __webpack_require__(/*! @formio/text-mask-addons */ \"./node_modules/@formio/text-mask-addons/dist/textMaskAddons.js\");\nconst vanilla_text_mask_1 = __webpack_require__(/*! @formio/vanilla-text-mask */ \"./node_modules/@formio/vanilla-text-mask/dist/vanillaTextMask.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass NumberComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'number',\n label: 'Number',\n key: 'number',\n validate: {\n min: '',\n max: '',\n step: 'any',\n integer: ''\n }\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Number',\n icon: 'hashtag',\n group: 'basic',\n documentation: '/userguide/form-building/form-components#number',\n weight: 30,\n schema: NumberComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return NumberComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: [...super.conditionOperatorsSettings.operators, 'lessThan', 'greaterThan', 'lessThanOrEqual', 'greaterThanOrEqual'], valueComponent(classComp) {\n return Object.assign(Object.assign({}, classComp), { type: 'number' });\n } });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.number];\n }\n constructor(...args) {\n var _a, _b, _c;\n super(...args);\n const separators = (0, utils_1.getNumberSeparators)(this.options.language || navigator.language);\n this.decimalSeparator = this.options.decimalSeparator = this.component.decimalSymbol || this.options.decimalSeparator\n || ((_a = this.options.properties) === null || _a === void 0 ? void 0 : _a.decimalSeparator)\n || separators.decimalSeparator;\n if (this.component.delimiter) {\n this.delimiter = this.component.thousandsSeparator || ((_b = this.options.properties) === null || _b === void 0 ? void 0 : _b.thousandsSeparator) || this.options.thousandsSeparator || separators.delimiter;\n }\n else {\n if (this.component.thousandsSeparator || ((_c = this.options.properties) === null || _c === void 0 ? void 0 : _c.thousandsSeparator) || this.options.thousandsSeparator) {\n console.warn('In order for thousands separator to work properly, you must set the delimiter to true in the component json');\n }\n this.delimiter = '';\n }\n const requireDecimal = lodash_1.default.get(this.component, 'requireDecimal', false);\n this.decimalLimit = (0, utils_1.getNumberDecimalLimit)(this.component, requireDecimal ? 2 : 20);\n // Currencies to override BrowserLanguage Config. Object key {}\n if (lodash_1.default.has(this.options, `languageOverride.${this.options.language}`)) {\n const override = lodash_1.default.get(this.options, `languageOverride.${this.options.language}`);\n this.decimalSeparator = override.decimalSeparator;\n this.delimiter = override.delimiter;\n }\n this.numberMask = this.createNumberMask();\n }\n /**\n * Creates the number mask for normal numbers.\n * @returns {*} - The number mask.\n */\n createNumberMask() {\n return (0, text_mask_addons_1.createNumberMask)({\n prefix: '',\n suffix: '',\n requireDecimal: lodash_1.default.get(this.component, 'requireDecimal', false),\n thousandsSeparatorSymbol: this.delimiter || '',\n decimalSymbol: lodash_1.default.get(this.component, 'decimalSymbol', this.decimalSeparator),\n decimalLimit: lodash_1.default.get(this.component, 'decimalLimit', this.decimalLimit),\n allowNegative: lodash_1.default.get(this.component, 'allowNegative', true),\n allowDecimal: this.isDecimalAllowed(),\n });\n }\n get defaultSchema() {\n return NumberComponent.schema();\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (typeof defaultValue === 'string') {\n // Default value may be a string or have custom thousands separators or decimal symbols, so we need to call\n // parseNumber on it\n defaultValue = this.parseNumber(defaultValue);\n }\n if (!defaultValue && this.component.defaultValue === 0) {\n defaultValue = this.component.defaultValue;\n }\n if (!this.component.multiple && lodash_1.default.isArray(defaultValue)) {\n defaultValue = !defaultValue[0] && defaultValue[0] !== 0 ? null : defaultValue[0];\n }\n return defaultValue;\n }\n isDecimalAllowed() {\n return lodash_1.default.get(this.component, 'allowDecimal', !(this.component.validate && this.component.validate.integer));\n }\n /**\n * parses a numeric string by removing the delimiters and replacing the decimal separator back to '.' so that it can\n * be processed by either parseInt or parseFloat\n * @param {string} value the value to be parsed\n * @returns {number} a parsed number\n */\n parseNumber(value) {\n // Remove delimiters and convert decimal separator to dot.\n value = value.split(this.delimiter).join('').replace(this.decimalSeparator, '.');\n if (this.component.validate && this.component.validate.integer) {\n return parseInt(value, 10);\n }\n else {\n return parseFloat(value);\n }\n }\n setInputMask(input) {\n let numberPattern = '[0-9';\n numberPattern += this.decimalSeparator || '';\n numberPattern += this.delimiter || '';\n numberPattern += ']*';\n input.setAttribute('pattern', numberPattern);\n input.mask = (0, vanilla_text_mask_1.maskInput)({\n inputElement: input,\n mask: this.numberMask,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n });\n }\n get inputInfo() {\n const info = super.inputInfo;\n if (this.component.mask) {\n info.attr.type = 'password';\n }\n else {\n info.attr.type = 'text';\n }\n info.attr.inputmode = this.isDecimalAllowed() ? 'decimal' : 'numeric';\n info.changeEvent = 'input';\n return info;\n }\n getValueAt(index) {\n if (!this.refs.input.length || !this.refs.input[index]) {\n return null;\n }\n const val = this.refs.input[index].value;\n return val && val !== '-_' ? this.parseNumber(val) : null;\n }\n setValueAt(index, value, flags = {}) {\n return super.setValueAt(index, this.formatValue(this.parseValue(value)), flags);\n }\n /**\n * Converts a string to a floating point number, formats the number based on the parsed float function\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) and then returns the\n * formatted number back as a string\n * Example Input: \"123.456,22\"\n * Example Output: \"123456,22\"\n * @param {string | number} input the numeric string to parse\n * @returns {string | null} a parsed string\n */\n parseValue(input) {\n if (typeof input === 'string') {\n input = input.split(this.delimiter).join('').replace(this.decimalSeparator, '.');\n }\n let value = parseFloat(input);\n if (!lodash_1.default.isNaN(value)) {\n // Format scientific notation\n if (/e/i.test(String(value))) {\n value = value.toExponential(this.decimalLimit);\n }\n else {\n value = String(value).replace('.', this.decimalSeparator);\n }\n }\n else {\n value = null;\n }\n return value;\n }\n formatValue(value) {\n if (this.component.requireDecimal && value && !value.includes(this.decimalSeparator)) {\n return `${value}${this.decimalSeparator}${lodash_1.default.repeat('0', this.decimalLimit)}`;\n }\n else if (this.component.requireDecimal && value && value.includes(this.decimalSeparator)) {\n return `${value}${lodash_1.default.repeat('0', this.decimalLimit - value.split(this.decimalSeparator)[1].length)}`;\n }\n return value;\n }\n focus() {\n const input = this.refs.input[0];\n if (input) {\n super.focus.call(this);\n input.setSelectionRange(0, input.value.length);\n }\n }\n getMaskedValue(value) {\n value = value === null ? '0' : value.toString();\n if (value.includes('.') && '.' !== this.decimalSeparator) {\n value = value.replace('.', this.decimalSeparator);\n }\n return (0, vanilla_text_mask_1.conformToMask)(this.formatValue(value), this.numberMask).conformedValue;\n }\n getValueAsString(value, options) {\n if (!value && value !== 0) {\n return '';\n }\n value = this.getWidgetValueAsString(value, options);\n if (Array.isArray(value)) {\n return value.map((val) => this.getMaskedValue(val)).join(', ');\n }\n return this.getMaskedValue(value);\n }\n addFocusBlurEvents(element) {\n super.addFocusBlurEvents(element);\n this.addEventListener(element, 'blur', () => {\n element.value = this.getValueAsString(this.formatValue(this.parseValue(element.value)));\n });\n }\n}\nexports[\"default\"] = NumberComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/number/Number.js?");
6703
6714
 
6704
6715
  /***/ }),
6705
6716
 
@@ -6974,7 +6985,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6974
6985
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6975
6986
 
6976
6987
  "use strict";
6977
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst ChoicesWrapper_1 = __importDefault(__webpack_require__(/*! ../../utils/ChoicesWrapper */ \"./lib/cjs/utils/ChoicesWrapper.js\"));\nclass SelectComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'select',\n label: 'Select',\n key: 'select',\n idPath: 'id',\n data: {\n values: [{ label: '', value: '' }],\n json: '',\n url: '',\n resource: '',\n custom: ''\n },\n clearOnRefresh: false,\n limit: 100,\n valueProperty: '',\n lazyLoad: true,\n filter: '',\n searchEnabled: true,\n searchDebounce: 0.3,\n searchField: '',\n minSearch: 0,\n readOnlyValue: false,\n selectFields: '',\n selectThreshold: 0.3,\n uniqueOptions: false,\n tableView: true,\n fuseOptions: {\n include: 'score',\n threshold: 0.3,\n },\n indexeddb: {\n filter: {}\n },\n customOptions: {},\n useExactSearch: false,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select',\n group: 'basic',\n icon: 'th-list',\n weight: 70,\n documentation: '/userguide/form-building/form-components#select',\n schema: SelectComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SelectComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n const numberType = () => ({ type: 'number' });\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n const valueComp = Object.assign(Object.assign({}, classComp), { type: 'select' });\n if ((0, utils_1.isSelectResourceWithObjectValue)(classComp)) {\n valueComp.reference = false;\n valueComp.onSetItems = `\n var templateKeys = utils.getItemTemplateKeys(component.template) || [];\n items = _.map(items || [], i => {\n var item = {};\n _.each(templateKeys, k => _.set(item, k, _.get(i, k)));\n return item;\n })\n `;\n }\n return valueComp;\n }, dataTypeOperators: {\n number: ['lessThan', 'greaterThan', 'lessThanOrEqual', 'greaterThanOrEqual'],\n }, dataTypeValueComponents: {\n number: {\n lessThan: numberType,\n greaterThan: numberType,\n lessThanOrEqual: numberType,\n greaterThanOrEqual: numberType,\n },\n } });\n }\n static savedValueTypes(schema) {\n const { boolean, string, number, object, array } = utils_1.componentValueTypes;\n const { dataType, reference } = schema;\n const types = (0, utils_1.getComponentSavedTypes)(schema);\n if (types) {\n return types;\n }\n if (reference) {\n return [object];\n }\n if (dataType === 'object') {\n return [object, array];\n }\n if (utils_1.componentValueTypes[dataType]) {\n return [utils_1.componentValueTypes[dataType]];\n }\n return [boolean, string, number, object, array];\n }\n init() {\n super.init();\n this.templateData = {};\n // Trigger an update.\n let updateArgs = [];\n const triggerUpdate = lodash_1.default.debounce((...args) => {\n updateArgs = [];\n return this.updateItems.apply(this, args);\n }, 100);\n this.triggerUpdate = (...args) => {\n // Make sure we always resolve the previous promise before reassign it\n if (typeof this.itemsLoadedResolve === 'function') {\n this.itemsLoadedResolve();\n }\n this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (args.length) {\n updateArgs = args;\n }\n return triggerUpdate(...updateArgs);\n };\n // Keep track of the select options.\n this.selectOptions = [];\n if (this.itemsFromUrl) {\n this.isFromSearch = false;\n this.searchServerCount = null;\n this.defaultServerCount = null;\n this.isScrollLoading = false;\n this.searchDownloadedResources = [];\n this.defaultDownloadedResources = [];\n }\n // If this component has been activated.//\n this.activated = false;\n this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n this.shouldPositionDropdown = this.hasDataGridAncestor();\n if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get defaultSchema() {\n return SelectComponent.schema();\n }\n get emptyValue() {\n if (this.component.multiple) {\n return [];\n }\n // if select has JSON data source type, we are defining if empty value would be an object or a string by checking JSON's first item\n if (this.component.dataSrc === 'json' && this.component.data.json) {\n const firstItem = this.component.data.json[0];\n let firstValue;\n if (this.valueProperty) {\n firstValue = lodash_1.default.get(firstItem, this.valueProperty);\n }\n else {\n firstValue = firstItem;\n }\n if (firstValue && typeof firstValue === 'string') {\n return '';\n }\n else {\n return {};\n }\n }\n if (this.valueProperty) {\n return '';\n }\n return {};\n }\n get valueProperty() {\n if (this.component.valueProperty) {\n return this.component.valueProperty;\n }\n // Force values datasource to use values without actually setting it on the component settings.\n if (this.component.dataSrc === 'values') {\n return 'value';\n }\n return '';\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'select';\n info.changeEvent = 'change';\n return info;\n }\n get isSelectResource() {\n return this.component.dataSrc === 'resource';\n }\n get itemsFromUrl() {\n return this.isSelectResource || this.isSelectURL;\n }\n get isInfiniteScrollProvided() {\n return this.itemsFromUrl;\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n get shouldInitialLoad() {\n if (this.component.widget === 'html5' &&\n this.isEntireObjectDisplay() &&\n this.component.searchField &&\n this.dataValue) {\n return false;\n }\n return super.shouldLoad;\n }\n get selectMetadata() {\n return super.selectData;\n }\n get selectData() {\n return this.selectMetadata || this.component.selectData;\n }\n isEntireObjectDisplay() {\n return this.component.dataSrc === 'resource' && this.valueProperty === 'data';\n }\n selectValueAndLabel(data) {\n const value = this.getOptionValue((this.isEntireObjectDisplay() && !this.itemValue(data)) ? data : this.itemValue(data));\n return {\n value,\n label: this.itemTemplate((this.isEntireObjectDisplay() && !lodash_1.default.isObject(data.data)) ? { data: data } : data, value)\n };\n }\n itemTemplate(data, value) {\n if (!lodash_1.default.isNumber(data) && lodash_1.default.isEmpty(data)) {\n return '';\n }\n // If they wish to show the value in read only mode, then just return the itemValue here.\n if (this.options.readOnly && this.component.readOnlyValue) {\n return this.itemValue(data);\n }\n // Perform a fast interpretation if we should not use the template.\n if (data && !this.component.template) {\n const itemLabel = data.label || data;\n const value = (typeof itemLabel === 'string') ? this.t(itemLabel, { _userInput: true }) : itemLabel;\n return this.sanitize(value, this.shouldSanitizeValue);\n }\n // Inside DataTable component won't have dataValue set\n const shouldUseSelectData = (this.component.multiple && lodash_1.default.isArray(this.dataValue)\n ? this.dataValue.find((val) => this.normalizeSingleValue(value) === val)\n : (this.dataValue === this.normalizeSingleValue(value))) || this.inDataTable;\n if (shouldUseSelectData) {\n const selectData = this.selectData;\n if (selectData) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (!this.templateData || !this.templateData[templateValue]) {\n this.getOptionTemplate(data, value);\n }\n if (this.component.multiple) {\n if (selectData[templateValue]) {\n data = selectData[templateValue];\n }\n }\n else {\n data = selectData;\n }\n }\n }\n if (typeof data === 'string' || typeof data === 'number') {\n return this.sanitize(this.t(data, { _userInput: true }), this.shouldSanitizeValue);\n }\n if (Array.isArray(data)) {\n return data.map((val) => {\n if (typeof val === 'string' || typeof val === 'number') {\n return this.sanitize(this.t(val, { _userInput: true }), this.shouldSanitizeValue);\n }\n return val;\n });\n }\n if (data.data) {\n // checking additional fields in the template for the selected Entire Object option\n const hasNestedFields = /item\\.data\\.\\w*/g.test(this.component.template);\n data.data = this.isEntireObjectDisplay() && lodash_1.default.isObject(data.data) && !hasNestedFields\n ? JSON.stringify(data.data)\n : data.data;\n }\n return super.itemTemplate(data, value);\n }\n /**\n * Adds an option to the select dropdown.\n * @param {*} value - The value of the new option.\n * @param {string} label - The label of the new option.\n * @param {object} [attrs] - Additional value attributes. Defaults to {}.\n * @param {string} [id] - An id. Defaults to a random string.\n */\n addOption(value, label, attrs = {}, id = (0, utils_1.getRandomComponentId)()) {\n if (lodash_1.default.isNil(label))\n return;\n const idPath = this.component.idPath\n ? this.component.idPath.split('.').reduceRight((obj, key) => ({ [key]: obj }), id)\n : {};\n const option = Object.assign({ value: this.getOptionValue(value), label }, idPath);\n const skipOption = this.component.uniqueOptions\n ? !!this.selectOptions.find((selectOption) => lodash_1.default.isEqual(selectOption.value, option.value))\n : false;\n if (skipOption) {\n return;\n }\n if (value) {\n this.selectOptions.push(option);\n }\n if (this.refs.selectContainer && (this.component.widget === 'html5')) {\n // Replace an empty Object value to an empty String.\n if (option.value && lodash_1.default.isObject(option.value) && lodash_1.default.isEmpty(option.value)) {\n option.value = '';\n }\n // Add element to option so we can reference it later.\n const div = document.createElement('div');\n div.innerHTML = this.sanitize(this.renderTemplate('selectOption', {\n selected: lodash_1.default.isEqual(this.getOptionValue(this.dataValue), option.value),\n option,\n attrs,\n id,\n useId: (this.valueProperty === '' || this.isEntireObjectDisplay()) && lodash_1.default.isObject(value) && id,\n }), this.shouldSanitizeValue).trim();\n option.element = div.firstChild;\n this.refs.selectContainer.appendChild(option.element);\n }\n }\n addValueOptions(items) {\n items = items || [];\n let added = false;\n let data = this.dataValue;\n // preset submission value with value property before request.\n if (this.options.pdf && !items.length && this.component.dataSrc === 'url' && this.valueProperty) {\n data = Array.isArray(data)\n ? data.map(item => lodash_1.default.set({}, this.valueProperty, item))\n : lodash_1.default.set({}, this.valueProperty, data);\n }\n if (!this.selectOptions.length) {\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(data) && this.component.multiple ? data : [data];\n added = this.addCurrentChoices(currentChoices, items);\n if (!added && !this.component.multiple) {\n this.addPlaceholder();\n }\n }\n return added;\n }\n disableInfiniteScroll() {\n if (!this.downloadedResources) {\n return;\n }\n this.downloadedResources.serverCount = this.downloadedResources.length;\n this.serverCount = this.downloadedResources.length;\n }\n /* eslint-disable max-statements */\n setItems(items, fromSearch) {\n var _a, _b;\n this.selectItems = items;\n // If the items is a string, then parse as JSON.\n if (typeof items == 'string') {\n try {\n items = JSON.parse(items);\n }\n catch (err) {\n console.warn(err.message);\n items = [];\n }\n }\n // Allow js processing (needed for form builder)\n if (this.component.onSetItems) {\n const newItems = typeof this.component.onSetItems === 'function'\n ? this.component.onSetItems(this, items)\n : this.evaluate(this.component.onSetItems, { items: items }, 'items');\n if (newItems) {\n items = newItems;\n }\n }\n if (!this.choices && this.refs.selectContainer) {\n this.empty(this.refs.selectContainer);\n }\n // If they provided select values, then we need to get them instead.\n if (this.component.selectValues) {\n items = lodash_1.default.get(items, this.component.selectValues, items) || [];\n }\n let areItemsEqual;\n if (this.itemsFromUrl) {\n areItemsEqual = this.isSelectURL ? lodash_1.default.isEqual(items, this.downloadedResources) : false;\n const areItemsEnded = this.component.limit > items.length;\n const areItemsDownloaded = areItemsEqual\n && this.downloadedResources\n && this.downloadedResources.length === items.length;\n if (areItemsEnded) {\n this.disableInfiniteScroll();\n }\n else if (areItemsDownloaded) {\n this.selectOptions = [];\n }\n else {\n this.serverCount = items.serverCount;\n }\n }\n if (this.isScrollLoading && items) {\n if (!areItemsEqual) {\n this.downloadedResources = this.downloadedResources\n ? this.downloadedResources.concat(items)\n : items;\n }\n this.downloadedResources.serverCount = items.serverCount || this.downloadedResources.serverCount;\n }\n else {\n this.downloadedResources = items || [];\n this.selectOptions = [];\n // If there is new select option with same id as already selected, set the new one\n if (!lodash_1.default.isEmpty(this.dataValue) && this.component.idPath) {\n const selectedOptionId = lodash_1.default.get(this.dataValue, this.component.idPath, null);\n const newOptionWithSameId = !lodash_1.default.isNil(selectedOptionId) && items.find(item => {\n const itemId = lodash_1.default.get(item, this.component.idPath);\n return itemId === selectedOptionId;\n });\n if (newOptionWithSameId) {\n this.setValue(newOptionWithSameId);\n }\n }\n }\n // Add the value options.\n if (!fromSearch) {\n this.addValueOptions(items);\n }\n if (this.component.widget === 'html5' && !this.component.placeholder) {\n this.addOption(null, '');\n }\n // Iterate through each of the items.\n lodash_1.default.each(items, (item, index) => {\n // preventing references of the components inside the form to the parent form when building forms\n if (this.root && this.root.options.editForm && this.root.options.editForm._id && this.root.options.editForm._id === item._id)\n return;\n const itemValueAndLabel = this.selectValueAndLabel(item);\n this.addOption(itemValueAndLabel.value, itemValueAndLabel.label, {}, lodash_1.default.get(item, this.component.idPath, String(index)));\n });\n if (this.choices) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n else if (this.loading) {\n // Re-attach select input.\n // this.appendTo(this.refs.input[0], this.selectContainer);\n }\n // We are no longer loading.\n this.isScrollLoading = false;\n this.loading = false;\n const searching = fromSearch && ((_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.isFocussed);\n if (!searching) {\n // If a value is provided, then select it.\n if (!this.isEmpty() || this.isRemoveButtonPressed) {\n this.setValue(this.dataValue, {\n noUpdateEvent: true\n });\n }\n else if (this.shouldAddDefaultValue && !this.options.readOnly) {\n // If a default value is provided then select it.\n const defaultValue = this.defaultValue;\n if (!this.isEmpty(defaultValue)) {\n this.setValue(defaultValue);\n }\n }\n }\n // Say we are done loading the items.\n this.itemsLoadedResolve();\n }\n getSingleItemValueForHTMLMode(data) {\n var _a;\n const option = (_a = this.selectOptions) === null || _a === void 0 ? void 0 : _a.find(({ value }) => lodash_1.default.isEqual(value, data));\n if (option) {\n return option.label || data;\n }\n return data;\n }\n itemValueForHTMLMode(value) {\n if (!this.isHtmlRenderMode()) {\n return super.itemValueForHTMLMode(value);\n }\n if (Array.isArray(value)) {\n const values = value.map(item => Array.isArray(item)\n ? this.itemValueForHTMLMode(item)\n : this.getSingleItemValueForHTMLMode(item));\n return values.join(', ');\n }\n return this.getSingleItemValueForHTMLMode(value);\n }\n /* eslint-enable max-statements */\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && (this.component.defaultValue === false || this.component.defaultValue === 0)) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n get loadingError() {\n return !this.component.refreshOn && !this.component.refreshOnBlur && this.networkError;\n }\n loadItems(url, search, headers, options, method, body) {\n options = options || {};\n // See if we should load items or not.\n if (!this.shouldLoad || (!this.itemsFromUrl && this.options.readOnly)) {\n this.isScrollLoading = false;\n this.loading = false;\n this.itemsLoadedResolve();\n return;\n }\n // See if they have not met the minimum search requirements.\n const minSearch = parseInt(this.component.minSearch, 10);\n if (this.component.searchField &&\n (minSearch > 0) &&\n (!search || (search.length < minSearch))) {\n // Set empty items.\n return this.setItems([]);\n }\n // Ensure we have a method and remove any body if method is get\n method = method || 'GET';\n if (method.toUpperCase() === 'GET') {\n body = null;\n }\n const limit = this.component.limit || 100;\n const skip = this.isScrollLoading ? this.selectOptions.length : 0;\n const query = this.component.disableLimit ? {} : {\n limit,\n skip,\n };\n // Allow for url interpolation.\n url = this.interpolate(url, {\n formioBase: Formio_1.Formio.getBaseUrl(),\n search,\n limit,\n skip,\n page: Math.abs(Math.floor(skip / limit))\n });\n // Add search capability.\n if (this.component.searchField && search) {\n const searchValue = Array.isArray(search)\n ? search.join(',')\n : typeof search === 'object'\n ? JSON.stringify(search)\n : search;\n query[this.component.searchField] = this.component.searchField.endsWith('__regex')\n ? lodash_1.default.escapeRegExp(searchValue)\n : searchValue;\n }\n // If they wish to return only some fields.\n if (this.component.selectFields) {\n query.select = this.component.selectFields;\n }\n // Add sort capability\n if (this.component.sort) {\n query.sort = this.component.sort;\n }\n if (!lodash_1.default.isEmpty(query)) {\n // Add the query string.\n url += (!url.includes('?') ? '?' : '&') + Formio_1.Formio.serialize(query, (item) => this.interpolate(item));\n }\n // Add filter capability\n if (this.component.filter) {\n url += (!url.includes('?') ? '?' : '&') + this.interpolate(this.component.filter);\n }\n // Set ignoreCache if it is\n options.ignoreCache = this.component.ignoreCache;\n // Make the request.\n options.header = headers;\n this.loading = true;\n Formio_1.Formio.makeRequest(this.options.formio, 'select', url, method, body, options)\n .then((response) => {\n this.loading = false;\n this.setItems(response, !!search);\n })\n .catch((err) => {\n if (this.itemsFromUrl) {\n this.setItems([]);\n this.disableInfiniteScroll();\n }\n this.isScrollLoading = false;\n this.handleLoadingError(err);\n });\n }\n handleLoadingError(err) {\n this.loading = false;\n if (err.networkError) {\n this.networkError = true;\n }\n this.itemsLoadedResolve();\n this.emit('componentError', {\n component: this.component,\n message: err.toString(),\n });\n console.warn(`Unable to load resources for ${this.key}`);\n }\n /**\n * Get the request headers for this select dropdown.\n * @returns {*} - Returns the request headers for this select dropdown.\n */\n get requestHeaders() {\n // Create the headers object.\n const headers = new Formio_1.Formio.Headers();\n // Add custom headers to the url.\n if (this.component.data && this.component.data.headers) {\n try {\n lodash_1.default.each(this.component.data.headers, (header) => {\n if (header.key) {\n headers.set(header.key, this.interpolate(header.value));\n }\n });\n }\n catch (err) {\n console.warn(err.message);\n }\n }\n return headers;\n }\n getCustomItems() {\n const customItems = this.evaluate(this.component.data.custom, {\n values: []\n }, 'values');\n this.asyncValues = (0, utils_1.isPromise)(customItems);\n return customItems;\n }\n asyncCustomValues() {\n if (!lodash_1.default.isBoolean(this.asyncValues)) {\n this.getCustomItems();\n }\n return this.asyncValues;\n }\n updateCustomItems(forceUpdate) {\n if (this.asyncCustomValues()) {\n if (!forceUpdate && !this.active) {\n this.itemsLoadedResolve();\n return;\n }\n this.loading = true;\n this.getCustomItems()\n .then(items => {\n this.loading = false;\n this.setItems(items || []);\n })\n .catch(err => {\n this.handleLoadingError(err);\n });\n }\n else {\n this.setItems(this.getCustomItems() || []);\n }\n }\n isEmpty(value = this.dataValue) {\n return super.isEmpty(value) || value === undefined;\n }\n refresh(value, { instance }) {\n if (this.component.clearOnRefresh && (instance && !instance.pristine)) {\n this.setValue(this.emptyValue);\n }\n this.updateItems(null, true);\n }\n get additionalResourcesAvailable() {\n return lodash_1.default.isNil(this.serverCount) || (this.serverCount > this.downloadedResources.length);\n }\n get serverCount() {\n if (this.isFromSearch) {\n return this.searchServerCount;\n }\n return this.defaultServerCount;\n }\n set serverCount(value) {\n if (this.isFromSearch) {\n this.searchServerCount = value;\n }\n else {\n this.defaultServerCount = value;\n }\n }\n get downloadedResources() {\n if (this.isFromSearch) {\n return this.searchDownloadedResources;\n }\n return this.defaultDownloadedResources;\n }\n set downloadedResources(value) {\n if (this.isFromSearch) {\n this.searchDownloadedResources = value;\n }\n else {\n this.defaultDownloadedResources = value;\n }\n }\n addPlaceholder() {\n if (!this.component.placeholder) {\n return;\n }\n this.addOption('', this.component.placeholder, { placeholder: true });\n }\n /**\n * Activate this select control.\n */\n activate() {\n if (this.loading || !this.active) {\n this.setLoadingItem();\n }\n if (this.active) {\n return;\n }\n this.activated = true;\n this.triggerUpdate();\n }\n setLoadingItem(addToCurrentList = false) {\n if (this.choices) {\n if (addToCurrentList) {\n this.choices.setChoices([{\n value: `${this.id}-loading`,\n label: 'Loading...',\n disabled: true,\n }], 'value', 'label');\n }\n else {\n this.choices.setChoices([{\n value: '',\n label: `<i class=\"${this.iconClass('refresh')}\" style=\"font-size:1.3em;\"></i>`,\n disabled: true,\n }], 'value', 'label', true);\n }\n }\n else if (this.component.dataSrc === 'url' || this.component.dataSrc === 'resource') {\n this.addOption('', this.t('loading...'));\n }\n }\n get active() {\n return !this.component.lazyLoad || this.activated;\n }\n render() {\n const info = this.inputInfo;\n info.attr = info.attr || {};\n info.multiple = this.component.multiple;\n return super.render(this.wrapElement(this.renderTemplate('select', {\n input: info,\n selectOptions: '',\n index: null,\n })));\n }\n wrapElement(element) {\n return this.component.addResource && !this.options.readOnly\n ? (this.renderTemplate('resourceAdd', {\n element\n }))\n : element;\n }\n choicesOptions() {\n const useSearch = this.component.hasOwnProperty('searchEnabled') ? this.component.searchEnabled : true;\n const placeholderValue = this.t(this.component.placeholder, { _userInput: true });\n let customOptions = this.component.customOptions || {};\n if (typeof customOptions == 'string') {\n try {\n customOptions = JSON.parse(customOptions);\n }\n catch (err) {\n console.warn(err.message);\n customOptions = {};\n }\n }\n const commonFuseOptions = {\n maxPatternLength: 1000,\n distance: 1000,\n };\n return Object.assign({ removeItemButton: this.component.disabled ? false : lodash_1.default.get(this.component, 'removeItemButton', true), itemSelectText: '', classNames: {\n containerOuter: 'choices form-group formio-choices',\n containerInner: this.transform('class', 'form-control ui fluid selection dropdown')\n }, addItemText: false, allowHTML: true, placeholder: !!this.component.placeholder, placeholderValue: placeholderValue, noResultsText: this.t('No results found'), noChoicesText: this.t('No choices to choose from'), searchPlaceholderValue: this.t('Type to search'), shouldSort: false, position: (this.component.dropdown || 'auto'), searchEnabled: useSearch, searchChoices: !this.component.searchField, searchFields: lodash_1.default.get(this, 'component.searchFields', ['label']), shadowRoot: this.root ? this.root.shadowRoot : null, fuseOptions: this.component.useExactSearch\n ? Object.assign({ tokenize: true, matchAllTokens: true }, commonFuseOptions) : Object.assign({}, lodash_1.default.get(this, 'component.fuseOptions', {}), Object.assign({ include: 'score', threshold: lodash_1.default.get(this, 'component.selectThreshold', 0.3) }, commonFuseOptions)), valueComparer: lodash_1.default.isEqual, resetScrollPosition: false }, customOptions);\n }\n /* eslint-disable max-statements */\n attach(element) {\n var _a, _b, _c;\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n selectContainer: 'single',\n addResource: 'single',\n autocompleteInput: 'single'\n });\n //enable autocomplete for select\n const autocompleteInput = this.refs.autocompleteInput;\n if (autocompleteInput) {\n this.addEventListener(autocompleteInput, 'change', (event) => {\n this.setValue(event.target.value);\n });\n }\n const input = this.refs.selectContainer;\n if (!input) {\n return;\n }\n this.addEventListener(input, this.inputInfo.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n this.attachRefreshOnBlur();\n if (this.component.widget === 'html5') {\n this.addFocusBlurEvents(input);\n this.triggerUpdate(null, true);\n if (this.visible) {\n this.setItems(this.selectItems || []);\n }\n this.focusableElement = input;\n if (this.component.dataSrc === 'custom') {\n this.addEventListener(input, 'focus', () => this.updateCustomItems());\n }\n this.addEventListener(input, 'keydown', (event) => {\n const { key } = event;\n if (['Backspace', 'Delete'].includes(key)) {\n this.setValue(this.emptyValue);\n }\n });\n return;\n }\n const tabIndex = input.tabIndex;\n this.addPlaceholder();\n if (this.i18next) {\n input.setAttribute('dir', this.i18next.dir());\n }\n if ((_c = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.containerOuter) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.parentNode) {\n this.choices.destroy();\n }\n const choicesOptions = this.choicesOptions();\n if (ChoicesWrapper_1.default) {\n this.choices = new ChoicesWrapper_1.default(input, choicesOptions);\n if (this.selectOptions && this.selectOptions.length) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n if (this.component.multiple) {\n this.focusableElement = this.choices.input.element;\n }\n else {\n this.focusableElement = this.choices.containerInner.element;\n this.choices.containerOuter.element.setAttribute('tabIndex', '-1');\n this.addEventListener(this.choices.containerOuter.element, 'focus', () => this.focusableElement.focus());\n }\n Input_1.default.prototype.addFocusBlurEvents.call(this, this.focusableElement);\n if (this.itemsFromUrl && !this.component.noRefreshOnScroll) {\n this.scrollList = this.choices.choiceList.element;\n this.addEventListener(this.scrollList, 'scroll', () => this.onScroll());\n }\n if (choicesOptions.removeItemButton) {\n this.addEventListener(input, 'removeItem', () => {\n this.isRemoveButtonPressed = true;\n });\n }\n }\n if (window && this.choices && this.shouldPositionDropdown) {\n this.addEventListener(window.document, 'scroll', () => {\n this.positionDropdown(true);\n }, false, true);\n }\n this.focusableElement.setAttribute('tabIndex', tabIndex);\n // If a search field is provided, then add an event listener to update items on search.\n if (this.component.searchField) {\n // Make sure to clear the search when no value is provided.\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.addEventListener(this.choices.input.element, 'input', (event) => {\n this.isFromSearch = !!event.target.value;\n if (!event.target.value) {\n this.triggerUpdate();\n }\n else {\n this.serverCount = null;\n this.downloadedResources = [];\n }\n });\n }\n this.addEventListener(input, 'choice', () => {\n if (this.component.multiple && this.component.dataSrc === 'resource' && this.isFromSearch) {\n this.triggerUpdate();\n }\n this.isFromSearch = false;\n });\n // avoid spamming the resource/url endpoint when we have server side filtering enabled.\n const debounceTimeout = this.component.searchField && (this.isSelectResource || this.isSelectURL) ?\n (this.component.searchDebounce === 0 ? 0 : this.component.searchDebounce || this.defaultSchema.searchDebounce) * 1000\n : 0;\n const updateComponent = (evt) => {\n this.triggerUpdate(evt.detail.value);\n };\n this.addEventListener(input, 'search', lodash_1.default.debounce((e) => {\n updateComponent(e);\n this.positionDropdown();\n }, debounceTimeout));\n this.addEventListener(input, 'stopSearch', () => this.triggerUpdate());\n this.addEventListener(input, 'hideDropdown', () => {\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.choices.input.element.value = '';\n }\n this.updateItems(null, true);\n });\n }\n this.addEventListener(input, 'showDropdown', () => {\n this.update();\n this.positionDropdown();\n });\n if (this.shouldPositionDropdown) {\n this.addEventListener(input, 'highlightChoice', () => {\n this.positionDropdown();\n });\n }\n if (this.choices && choicesOptions.placeholderValue && this.choices._isSelectOneElement) {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n this.addEventListener(input, 'removeItem', () => {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n });\n }\n // Add value options.\n this.addValueOptions();\n this.setChoicesValue(this.dataValue);\n if (this.isSelectResource && this.refs.addResource) {\n this.addEventListener(this.refs.addResource, 'click', (event) => {\n event.preventDefault();\n const formioForm = this.ce('div');\n const dialog = this.createModal(formioForm);\n const projectUrl = lodash_1.default.get(this.root, 'formio.projectUrl', Formio_1.Formio.getProjectUrl());\n const formUrl = `${projectUrl}/form/${this.component.data.resource}`;\n new Form_1.default(formioForm, formUrl, {}).ready\n .then((form) => {\n form.on('submit', (submission) => {\n // If valueProperty is set, replace the submission with the corresponding value\n let value = this.valueProperty ? lodash_1.default.get(submission, this.valueProperty) : submission;\n if (this.component.multiple) {\n value = [...this.dataValue, value];\n }\n this.setValue(value);\n this.triggerUpdate();\n dialog.close();\n });\n });\n });\n }\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n this.triggerUpdate();\n return superAttach;\n }\n setDropdownPosition() {\n var _a, _b, _c, _d;\n const dropdown = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.dropdown) === null || _b === void 0 ? void 0 : _b.element;\n const container = (_d = (_c = this.choices) === null || _c === void 0 ? void 0 : _c.containerOuter) === null || _d === void 0 ? void 0 : _d.element;\n if (!dropdown || !container) {\n return;\n }\n const containerPosition = container.getBoundingClientRect();\n const isFlipped = container.classList.contains('is-flipped');\n lodash_1.default.assign(dropdown.style, {\n top: `${isFlipped ? containerPosition.top - dropdown.offsetHeight : containerPosition.top + containerPosition.height}px`,\n left: `${containerPosition.left}px`,\n width: `${containerPosition.width}px`,\n position: 'fixed',\n bottom: 'unset',\n right: 'unset',\n });\n }\n hasDataGridAncestor(comp) {\n comp = comp || this;\n if (comp.inDataGrid || comp.type === 'datagrid') {\n return true;\n }\n else if (comp.parent) {\n return this.hasDataGridAncestor(comp.parent);\n }\n else {\n return false;\n }\n }\n positionDropdown(scroll) {\n var _a;\n if (!this.shouldPositionDropdown || !this.choices || (!((_a = this.choices.dropdown) === null || _a === void 0 ? void 0 : _a.isActive) && scroll)) {\n return;\n }\n this.setDropdownPosition();\n this.itemsLoaded.then(() => {\n this.setDropdownPosition();\n });\n }\n get isLoadingAvailable() {\n return !this.isScrollLoading && this.additionalResourcesAvailable;\n }\n onScroll() {\n if (this.isLoadingAvailable) {\n this.isScrollLoading = true;\n this.setLoadingItem(true);\n this.triggerUpdate(this.choices.input.element.value);\n }\n }\n attachRefreshOnBlur() {\n if (this.component.refreshOnBlur) {\n this.on('blur', (instance) => {\n this.checkRefreshOn([{ instance, value: instance.dataValue }], { fromBlur: true });\n });\n }\n }\n addPlaceholderItem(placeholderValue) {\n const items = this.choices._store.activeItems;\n if (!items.length) {\n this.choices._addItem({\n value: '',\n label: placeholderValue,\n choiceId: 0,\n groupId: -1,\n customProperties: null,\n placeholder: true,\n keyCode: null\n });\n }\n }\n /* eslint-enable max-statements */\n update() {\n if (this.component.dataSrc === 'custom') {\n this.updateCustomItems();\n }\n // Activate the control.\n this.activate();\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.setDisabled(this.choices.containerInner.element, true);\n this.focusableElement.removeAttribute('tabIndex');\n this.choices.disable();\n }\n else {\n this.setDisabled(this.choices.containerInner.element, false);\n this.focusableElement.setAttribute('tabIndex', this.component.tabindex || 0);\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n set visible(value) {\n // If we go from hidden to visible, trigger a refresh.\n if (value && (!this._visible !== !value)) {\n this.triggerUpdate();\n }\n super.visible = value;\n }\n get visible() {\n return super.visible;\n }\n addCurrentChoices(values, items, keyValue) {\n if (!values) {\n return false;\n }\n const notFoundValuesToAdd = [];\n const added = values.reduce((defaultAdded, value) => {\n if (!value || lodash_1.default.isEmpty(value)) {\n return defaultAdded;\n }\n let found = false;\n // Make sure that `items` and `this.selectOptions` points\n // to the same reference. Because `this.selectOptions` is\n // internal property and all items are populated by\n // `this.addOption` method, we assume that items has\n // 'label' and 'value' properties. This assumption allows\n // us to read correct value from the item.\n const isSelectOptions = items === this.selectOptions;\n if (items && items.length) {\n lodash_1.default.each(items, (choice) => {\n if (choice._id && value._id && (choice._id === value._id)) {\n found = true;\n return false;\n }\n const itemValue = keyValue ? choice.value : this.itemValue(choice, isSelectOptions);\n found |= lodash_1.default.isEqual(itemValue, value);\n return found ? false : true;\n });\n }\n // Add the default option if no item is found.\n if (!found) {\n notFoundValuesToAdd.push(this.selectValueAndLabel(value));\n return true;\n }\n return found || defaultAdded;\n }, false);\n if (notFoundValuesToAdd.length) {\n if (this.choices) {\n this.choices.setChoices(notFoundValuesToAdd, 'value', 'label');\n }\n notFoundValuesToAdd.map(notFoundValue => {\n this.addOption(notFoundValue.value, notFoundValue.label);\n });\n }\n return added;\n }\n getValueAsString(data, options) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map((v) => this.asString(v, options)).join(', ')\n : this.asString(data, options);\n }\n getValue() {\n // If the widget isn't active.\n if (this.viewOnly || this.loading\n || (!this.component.lazyLoad && !this.selectOptions.length)\n || !this.element) {\n return this.dataValue;\n }\n let value = this.emptyValue;\n if (this.choices) {\n value = this.choices.getValue(true);\n // Make sure we don't get the placeholder\n if (!this.component.multiple &&\n this.component.placeholder &&\n (value === this.t(this.component.placeholder, { _userInput: true }))) {\n value = this.emptyValue;\n }\n }\n else if (this.refs.selectContainer) {\n value = this.refs.selectContainer.value;\n if (this.valueProperty === '' || this.isEntireObjectDisplay()) {\n if (value === '') {\n return {};\n }\n const option = this.selectOptions[value] ||\n this.selectOptions.find(option => option.id === value);\n if (option && lodash_1.default.isObject(option.value)) {\n value = option.value;\n }\n }\n }\n else {\n value = this.dataValue;\n }\n // Choices will return undefined if nothing is selected. We really want '' to be empty.\n if (value === undefined || value === null) {\n value = '';\n }\n return value;\n }\n redraw() {\n const done = super.redraw();\n this.triggerUpdate();\n return done;\n }\n normalizeSingleValue(value) {\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n const dataType = this.component.dataType || 'auto';\n const normalize = {\n value,\n number() {\n const numberValue = Number(this.value);\n const isEquivalent = value.toString() === numberValue.toString();\n if (!Number.isNaN(numberValue) && Number.isFinite(numberValue) && value !== '' && isEquivalent) {\n this.value = numberValue;\n }\n return this;\n },\n boolean() {\n if (lodash_1.default.isString(this.value)\n && (this.value.toLowerCase() === 'true'\n || this.value.toLowerCase() === 'false')) {\n this.value = (this.value.toLowerCase() === 'true');\n }\n return this;\n },\n string() {\n this.value = String(this.value);\n return this;\n },\n object() {\n return this;\n },\n auto() {\n if (lodash_1.default.isObject(this.value)) {\n this.value = this.object().value;\n }\n else {\n this.value = this.string().number().boolean().value;\n }\n return this;\n }\n };\n try {\n return normalize[dataType]().value;\n }\n catch (err) {\n console.warn('Failed to normalize value', err);\n return value;\n }\n }\n /**\n * Normalize values coming into updateValue. For example, depending on the configuration, string value `\"true\"` will be normalized to boolean `true`.\n * @param {*} value - The value to normalize\n * @returns {*} - Returns the normalized value\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue));\n }\n return super.normalizeValue(this.normalizeSingleValue(value));\n }\n setMetadata(value) {\n var _a;\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n // Check to see if we need to save off the template data into our metadata.\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n const shouldSaveData = !valueIsObject || this.component.reference;\n if (!lodash_1.default.isNil(templateValue) && shouldSaveData && this.templateData && this.templateData[templateValue] && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submission)) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n let templateData = this.templateData[templateValue];\n if (this.component.multiple) {\n templateData = {};\n const dataValue = this.dataValue;\n if (dataValue && lodash_1.default.isArray(dataValue) && dataValue.length) {\n dataValue.forEach((dataValueItem) => {\n const dataValueItemValue = this.component.reference ? dataValueItem._id.toString() : dataValueItem;\n templateData[dataValueItemValue] = this.templateData[dataValueItemValue];\n });\n }\n templateData[value] = this.templateData[value];\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\n }\n updateValue(value, flags) {\n const changed = super.updateValue(value, flags);\n if (changed || !this.selectMetadata) {\n if (this.component.multiple && Array.isArray(this.dataValue)) {\n this.dataValue.forEach(singleValue => this.setMetadata(singleValue));\n }\n else {\n this.setMetadata(this.dataValue);\n }\n }\n return changed;\n }\n undoValueTyping(value) {\n let untypedValue = value;\n if (this.component.multiple && Array.isArray(value)) {\n untypedValue = value.map(v => {\n if (typeof v === 'boolean' || typeof v === 'number') {\n return v.toString();\n }\n return v;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n untypedValue = value.toString();\n }\n }\n return untypedValue;\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\n const changed = this.updateValue(value, flags);\n if (this.component.widget === 'html5' && (lodash_1.default.isEqual(value, previousValue) || lodash_1.default.isEqual(previousValue, {}) && lodash_1.default.isEqual(flags, {})) && !flags.fromSubmission) {\n return false;\n }\n value = this.dataValue;\n const hasPreviousValue = !this.isEmpty(previousValue);\n const hasValue = !this.isEmpty(value);\n // Undo typing when searching to set the value.\n value = this.undoValueTyping(value);\n if (this.isHtmlRenderMode() && flags && flags.fromSubmission && changed) {\n this.itemsLoaded.then(() => {\n this.redraw();\n });\n return changed;\n }\n // Do not set the value if we are loading... that will happen after it is done.\n if (this.loading) {\n return changed;\n }\n // Determine if we need to perform an initial lazyLoad api call if searchField is provided.\n if (this.isInitApiCallNeeded(hasValue)) {\n this.loading = true;\n this.lazyLoadInit = true;\n const searchProperty = this.component.searchField || this.component.valueProperty;\n this.triggerUpdate(lodash_1.default.get(value.data || value, searchProperty, value), true);\n return changed;\n }\n // Add the value options.\n this.itemsLoaded.then(() => {\n this.addValueOptions();\n this.setChoicesValue(value, hasPreviousValue, flags);\n });\n return changed;\n }\n isInitApiCallNeeded(hasValue) {\n return this.component.lazyLoad &&\n !this.lazyLoadInit &&\n !this.active &&\n !this.selectOptions.length &&\n hasValue &&\n this.shouldInitialLoad &&\n this.visible && (this.component.searchField || this.component.valueProperty);\n }\n setChoicesValue(value, hasPreviousValue, flags = {}) {\n const hasValue = !this.isEmpty(value) || flags.fromSubmission;\n hasPreviousValue = (hasPreviousValue === undefined) ? true : hasPreviousValue;\n if (this.choices) {\n // Now set the value.\n if (hasValue) {\n this.choices.removeActiveItems();\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(value) && this.component.multiple ? value : [value];\n if (!this.addCurrentChoices(currentChoices, this.selectOptions, true)) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n this.choices.setChoiceByValue(currentChoices);\n }\n else if (hasPreviousValue || flags.resetValue) {\n this.choices.removeActiveItems();\n }\n }\n else {\n if (hasValue) {\n const values = Array.isArray(value) ? value : [value];\n if (!lodash_1.default.isEqual(this.dataValue, this.defaultValue) && this.selectOptions.length < 2\n || (this.selectData && flags.fromSubmission)) {\n const { value, label } = this.selectValueAndLabel(this.dataValue);\n this.addOption(value, label);\n }\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n lodash_1.default.each(values, (val) => {\n if (selectOption.value === '') {\n selectOption.value = {};\n }\n if (lodash_1.default.isEqual(val, selectOption.value) && selectOption.element) {\n selectOption.element.selected = true;\n selectOption.element.setAttribute('selected', 'selected');\n return false;\n }\n });\n });\n }\n else {\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n if (selectOption.element) {\n selectOption.element.selected = false;\n selectOption.element.removeAttribute('selected');\n }\n });\n }\n }\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.getOptionsValues();\n if (values) {\n if (lodash_1.default.isObject(value)) {\n const compareComplexValues = (optionValue) => {\n const normalizedOptionValue = this.normalizeSingleValue(optionValue);\n if (!lodash_1.default.isObject(normalizedOptionValue)) {\n return false;\n }\n try {\n return (JSON.stringify(normalizedOptionValue) === JSON.stringify(value));\n }\n catch (err) {\n console.warn.error('Error while comparing items', err);\n return false;\n }\n };\n return values.findIndex((optionValue) => compareComplexValues(optionValue)) !== -1;\n }\n return values.findIndex((optionValue) => this.normalizeSingleValue(optionValue) === value) !== -1;\n }\n return false;\n }\n /**\n * Performs required transformations on the initial value to use in selectOptions\n * @param {*} value - The value to transform.\n * @returns {*} - Returns the options value.\n */\n getOptionValue(value) {\n return lodash_1.default.isObject(value) && this.isEntireObjectDisplay()\n ? this.normalizeSingleValue(value)\n : lodash_1.default.isObject(value) && (this.valueProperty || this.component.key !== 'resource')\n ? value\n : lodash_1.default.isObject(value) && !this.valueProperty\n ? this.interpolate(this.component.template, { item: value }).replace(/<\\/?[^>]+(>|$)/g, '')\n : lodash_1.default.isNull(value)\n ? this.emptyValue\n : String(this.normalizeSingleValue(value));\n }\n /**\n * If component has static values (values, json) or custom values, returns an array of them\n * @returns {Array<*>|undefined} - Returns an array of the static or custom values.\n */\n getOptionsValues() {\n let rawItems = [];\n switch (this.component.dataSrc) {\n case 'values':\n rawItems = this.component.data.values;\n break;\n case 'json':\n rawItems = this.component.data.json;\n break;\n case 'custom':\n rawItems = this.getCustomItems();\n break;\n case 'url':\n rawItems = this.selectItems;\n break;\n }\n if (typeof rawItems === 'string') {\n try {\n rawItems = JSON.parse(rawItems);\n }\n catch (err) {\n console.warn(err.message);\n rawItems = [];\n }\n }\n if (!Array.isArray(rawItems)) {\n return;\n }\n return rawItems.map((item) => this.getOptionValue(this.itemValue(item)));\n }\n /**\n * Deletes the value of the component.\n */\n deleteValue() {\n this.setValue('', {\n noUpdateEvent: true\n });\n this.unset();\n }\n /**\n * Check if a component is eligible for multiple validation\n * @returns {boolean} - Returns FALSE for select components.\n */\n validateMultiple() {\n // Select component will contain one input when flagged as multiple.\n return false;\n }\n /**\n * Output this select dropdown as a string value.\n * @returns {*}\n */\n isBooleanOrNumber(value) {\n return typeof value === 'number' || typeof value === 'boolean';\n }\n getNormalizedValues() {\n if (!this.component || !this.component.data || !this.component.data.values) {\n return;\n }\n return this.component.data.values.map(value => ({ label: value.label, value: String(this.normalizeSingleValue(value.value)) }));\n }\n asString(value, options = {}) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\n if (options.modalPreview || this.inDataTable) {\n if (this.inDataTable) {\n value = this.undoValueTyping(value);\n }\n const templateValue = (this.isEntireObjectDisplay() && !lodash_1.default.isObject(value.data)) ? { data: value } : value;\n const template = this.itemTemplate(templateValue, value, options);\n return template;\n }\n //need to convert values to strings to be able to compare values with available options that are strings\n const convertToString = (data, valueProperty) => {\n if (valueProperty) {\n if (Array.isArray(data)) {\n data.forEach((item) => item[valueProperty] = item[valueProperty].toString());\n }\n else if (lodash_1.default.isObject(data)) {\n data[valueProperty] = data[valueProperty].toString();\n }\n return data;\n }\n if (this.isBooleanOrNumber(data)) {\n data = data.toString();\n }\n if (Array.isArray(data) && data.some(item => this.isBooleanOrNumber(item))) {\n data = data.map(item => this.isBooleanOrNumber(item) ? item.toString() : item);\n }\n return data;\n };\n value = convertToString(value);\n if (['values', 'custom'].includes(this.component.dataSrc) && !this.asyncCustomValues()) {\n const { items, valueProperty, } = this.component.dataSrc === 'values'\n ? {\n items: convertToString(this.getNormalizedValues(), 'value'),\n valueProperty: 'value',\n }\n : {\n items: convertToString(this.getCustomItems(), this.valueProperty),\n valueProperty: this.valueProperty,\n };\n const getFromValues = () => {\n const initialValue = lodash_1.default.find(items, [valueProperty, value]);\n const values = this.defaultSchema.data.values || [];\n return lodash_1.default.isEqual(initialValue, values[0]) ? '-' : initialValue;\n };\n value = (this.component.multiple && Array.isArray(value))\n ? lodash_1.default.filter(items, (item) => value.includes(item.value))\n : (valueProperty && items)\n ? (_a = getFromValues()) !== null && _a !== void 0 ? _a : { value, label: value }\n : value;\n }\n if (lodash_1.default.isString(value)) {\n return value;\n }\n const getTemplateValue = (v) => {\n const itemTemplate = this.itemTemplate(v);\n return options.csv && itemTemplate\n ? (0, utils_1.removeHTML)(itemTemplate)\n : itemTemplate;\n };\n if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(getTemplateValue(item)));\n if (this.component.dataSrc === 'resource' && items.length > 0) {\n return items.join(', ');\n }\n else if (items.length > 0) {\n return items.join('<br />');\n }\n else {\n return '-';\n }\n }\n if (this.isEntireObjectDisplay() && lodash_1.default.isObject(value)) {\n return JSON.stringify(value);\n }\n return !lodash_1.default.isNil(value)\n ? getTemplateValue(value)\n : '-';\n }\n detach() {\n var _a, _b;\n this.off('blur');\n if (this.choices) {\n if ((_b = (_a = this.choices.containerOuter) === null || _a === void 0 ? void 0 : _a.element) === null || _b === void 0 ? void 0 : _b.parentNode) {\n this.choices.destroy();\n }\n this.choices = null;\n }\n super.detach();\n }\n focus() {\n super.focus.call(this);\n if (this.focusableElement) {\n this.focusableElement.focus();\n }\n }\n setErrorClasses(elements, dirty, hasError, hasMessages, element = this.element) {\n super.setErrorClasses(elements, dirty, hasError, hasMessages, element);\n if (this.choices) {\n super.setErrorClasses([this.choices.containerInner.element], dirty, hasError, hasMessages, element);\n }\n else {\n super.setErrorClasses([this.refs.selectContainer], dirty, hasError, hasMessages, element);\n }\n }\n}\nexports[\"default\"] = SelectComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/select/Select.js?");
6988
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst ChoicesWrapper_1 = __importDefault(__webpack_require__(/*! ../../utils/ChoicesWrapper */ \"./lib/cjs/utils/ChoicesWrapper.js\"));\nclass SelectComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'select',\n label: 'Select',\n key: 'select',\n idPath: 'id',\n data: {\n values: [{ label: '', value: '' }],\n json: '',\n url: '',\n resource: '',\n custom: ''\n },\n clearOnRefresh: false,\n limit: 100,\n valueProperty: '',\n lazyLoad: true,\n filter: '',\n searchEnabled: true,\n searchDebounce: 0.3,\n searchField: '',\n minSearch: 0,\n readOnlyValue: false,\n selectFields: '',\n selectThreshold: 0.3,\n uniqueOptions: false,\n tableView: true,\n fuseOptions: {\n include: 'score',\n threshold: 0.3,\n },\n indexeddb: {\n filter: {}\n },\n customOptions: {},\n useExactSearch: false,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select',\n group: 'basic',\n icon: 'th-list',\n weight: 70,\n documentation: '/userguide/form-building/form-components#select',\n schema: SelectComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SelectComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n const numberType = () => ({ type: 'number' });\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n const valueComp = Object.assign(Object.assign({}, classComp), { type: 'select' });\n if ((0, utils_1.isSelectResourceWithObjectValue)(classComp)) {\n valueComp.reference = false;\n valueComp.onSetItems = `\n var templateKeys = utils.getItemTemplateKeys(component.template) || [];\n items = _.map(items || [], i => {\n var item = {};\n _.each(templateKeys, k => _.set(item, k, _.get(i, k)));\n return item;\n })\n `;\n }\n return valueComp;\n }, dataTypeOperators: {\n number: ['lessThan', 'greaterThan', 'lessThanOrEqual', 'greaterThanOrEqual'],\n }, dataTypeValueComponents: {\n number: {\n lessThan: numberType,\n greaterThan: numberType,\n lessThanOrEqual: numberType,\n greaterThanOrEqual: numberType,\n },\n } });\n }\n static savedValueTypes(schema) {\n const { boolean, string, number, object, array } = utils_1.componentValueTypes;\n const { dataType, reference } = schema;\n const types = (0, utils_1.getComponentSavedTypes)(schema);\n if (types) {\n return types;\n }\n if (reference) {\n return [object];\n }\n if (dataType === 'object') {\n return [object, array];\n }\n if (utils_1.componentValueTypes[dataType]) {\n return [utils_1.componentValueTypes[dataType]];\n }\n return [boolean, string, number, object, array];\n }\n init() {\n super.init();\n this.templateData = {};\n // Trigger an update.\n let updateArgs = [];\n const triggerUpdate = lodash_1.default.debounce((...args) => {\n updateArgs = [];\n return this.updateItems.apply(this, args);\n }, 100);\n this.triggerUpdate = (...args) => {\n // Make sure we always resolve the previous promise before reassign it\n if (typeof this.itemsLoadedResolve === 'function') {\n this.itemsLoadedResolve();\n }\n this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n if (args.length) {\n updateArgs = args;\n }\n return triggerUpdate(...updateArgs);\n };\n // Keep track of the select options.\n this.selectOptions = [];\n if (this.itemsFromUrl) {\n this.isFromSearch = false;\n this.searchServerCount = null;\n this.defaultServerCount = null;\n this.isScrollLoading = false;\n this.searchDownloadedResources = [];\n this.defaultDownloadedResources = [];\n }\n // If this component has been activated.//\n this.activated = false;\n this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n this.shouldPositionDropdown = this.hasDataGridAncestor();\n if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get defaultSchema() {\n return SelectComponent.schema();\n }\n get emptyValue() {\n if (this.component.multiple) {\n return [];\n }\n // if select has JSON data source type, we are defining if empty value would be an object or a string by checking JSON's first item\n if (this.component.dataSrc === 'json' && this.component.data.json) {\n const firstItem = this.component.data.json[0];\n let firstValue;\n if (this.valueProperty) {\n firstValue = lodash_1.default.get(firstItem, this.valueProperty);\n }\n else {\n firstValue = firstItem;\n }\n if (firstValue && typeof firstValue === 'string') {\n return '';\n }\n else {\n return {};\n }\n }\n if (this.valueProperty) {\n return '';\n }\n return {};\n }\n get valueProperty() {\n if (this.component.valueProperty) {\n return this.component.valueProperty;\n }\n // Force values datasource to use values without actually setting it on the component settings.\n if (this.component.dataSrc === 'values') {\n return 'value';\n }\n return '';\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'select';\n info.changeEvent = 'change';\n return info;\n }\n get isSelectResource() {\n return this.component.dataSrc === 'resource';\n }\n get itemsFromUrl() {\n return this.isSelectResource || this.isSelectURL;\n }\n get isInfiniteScrollProvided() {\n return this.itemsFromUrl;\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n get shouldInitialLoad() {\n if (this.component.widget === 'html5' &&\n this.isEntireObjectDisplay() &&\n this.component.searchField &&\n this.dataValue) {\n return false;\n }\n return super.shouldLoad;\n }\n get selectMetadata() {\n return super.selectData;\n }\n get selectData() {\n return this.selectMetadata || this.component.selectData;\n }\n isEntireObjectDisplay() {\n return this.component.dataSrc === 'resource' && this.valueProperty === 'data';\n }\n selectValueAndLabel(data) {\n const value = this.getOptionValue((this.isEntireObjectDisplay() && !this.itemValue(data)) ? data : this.itemValue(data));\n return {\n value,\n label: this.itemTemplate((this.isEntireObjectDisplay() && !lodash_1.default.isObject(data.data)) ? { data: data } : data, value)\n };\n }\n itemTemplate(data, value) {\n if (!lodash_1.default.isNumber(data) && lodash_1.default.isEmpty(data)) {\n return '';\n }\n // If they wish to show the value in read only mode, then just return the itemValue here.\n if (this.options.readOnly && this.component.readOnlyValue) {\n return this.itemValue(data);\n }\n // Perform a fast interpretation if we should not use the template.\n if (data && !this.component.template) {\n const itemLabel = data.label || data;\n const value = (typeof itemLabel === 'string') ? this.t(itemLabel, { _userInput: true }) : itemLabel;\n return this.sanitize(value, this.shouldSanitizeValue);\n }\n // Inside DataTable component won't have dataValue set\n const shouldUseSelectData = (this.component.multiple && lodash_1.default.isArray(this.dataValue)\n ? this.dataValue.find((val) => this.normalizeSingleValue(value) === val)\n : (this.dataValue === this.normalizeSingleValue(value))) || this.inDataTable;\n if (shouldUseSelectData) {\n const selectData = this.selectData;\n if (selectData) {\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (!this.templateData || !this.templateData[templateValue]) {\n this.getOptionTemplate(data, value);\n }\n if (this.component.multiple) {\n if (selectData[templateValue]) {\n data = selectData[templateValue];\n }\n }\n else {\n data = selectData;\n }\n }\n }\n if (typeof data === 'string' || typeof data === 'number') {\n return this.sanitize(this.t(data, { _userInput: true }), this.shouldSanitizeValue);\n }\n if (Array.isArray(data)) {\n return data.map((val) => {\n if (typeof val === 'string' || typeof val === 'number') {\n return this.sanitize(this.t(val, { _userInput: true }), this.shouldSanitizeValue);\n }\n return val;\n });\n }\n if (data.data) {\n // checking additional fields in the template for the selected Entire Object option\n const hasNestedFields = /item\\.data\\.\\w*/g.test(this.component.template);\n data.data = this.isEntireObjectDisplay() && lodash_1.default.isObject(data.data) && !hasNestedFields\n ? JSON.stringify(data.data)\n : data.data;\n }\n return super.itemTemplate(data, value);\n }\n /**\n * Adds an option to the select dropdown.\n * @param {*} value - The value of the new option.\n * @param {string} label - The label of the new option.\n * @param {object} [attrs] - Additional value attributes. Defaults to {}.\n * @param {string} [id] - An id. Defaults to a random string.\n */\n addOption(value, label, attrs = {}, id = (0, utils_1.getRandomComponentId)()) {\n if (lodash_1.default.isNil(label))\n return;\n const idPath = this.component.idPath\n ? this.component.idPath.split('.').reduceRight((obj, key) => ({ [key]: obj }), id)\n : {};\n const option = Object.assign({ value: this.getOptionValue(value), label }, idPath);\n const skipOption = this.component.uniqueOptions\n ? !!this.selectOptions.find((selectOption) => lodash_1.default.isEqual(selectOption.value, option.value))\n : false;\n if (skipOption) {\n return;\n }\n if (value) {\n this.selectOptions.push(option);\n }\n if (this.refs.selectContainer && (this.component.widget === 'html5')) {\n // Replace an empty Object value to an empty String.\n if (option.value && lodash_1.default.isObject(option.value) && lodash_1.default.isEmpty(option.value)) {\n option.value = '';\n }\n // Add element to option so we can reference it later.\n const div = document.createElement('div');\n div.innerHTML = this.sanitize(this.renderTemplate('selectOption', {\n selected: lodash_1.default.isEqual(this.getOptionValue(this.dataValue), option.value),\n option,\n attrs,\n id,\n useId: (this.valueProperty === '' || this.isEntireObjectDisplay()) && lodash_1.default.isObject(value) && id,\n }), this.shouldSanitizeValue).trim();\n option.element = div.firstChild;\n this.refs.selectContainer.appendChild(option.element);\n }\n }\n addValueOptions(items) {\n items = items || [];\n let added = false;\n let data = this.dataValue;\n // preset submission value with value property before request.\n if (this.options.pdf && !items.length && this.component.dataSrc === 'url' && this.valueProperty) {\n data = Array.isArray(data)\n ? data.map(item => lodash_1.default.set({}, this.valueProperty, item))\n : lodash_1.default.set({}, this.valueProperty, data);\n }\n if (!this.selectOptions.length) {\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(data) && this.component.multiple ? data : [data];\n added = this.addCurrentChoices(currentChoices, items);\n if (!added && !this.component.multiple) {\n this.addPlaceholder();\n }\n }\n return added;\n }\n disableInfiniteScroll() {\n if (!this.downloadedResources) {\n return;\n }\n this.downloadedResources.serverCount = this.downloadedResources.length;\n this.serverCount = this.downloadedResources.length;\n }\n /* eslint-disable max-statements */\n setItems(items, fromSearch) {\n var _a, _b;\n this.selectItems = items;\n // If the items is a string, then parse as JSON.\n if (typeof items == 'string') {\n try {\n items = JSON.parse(items);\n }\n catch (err) {\n console.warn(err.message);\n items = [];\n }\n }\n // Allow js processing (needed for form builder)\n if (this.component.onSetItems) {\n const newItems = typeof this.component.onSetItems === 'function'\n ? this.component.onSetItems(this, items)\n : this.evaluate(this.component.onSetItems, { items: items }, 'items');\n if (newItems) {\n items = newItems;\n }\n }\n if (!this.choices && this.refs.selectContainer) {\n this.empty(this.refs.selectContainer);\n }\n // If they provided select values, then we need to get them instead.\n if (this.component.selectValues) {\n items = lodash_1.default.get(items, this.component.selectValues, items) || [];\n }\n let areItemsEqual;\n if (this.itemsFromUrl) {\n areItemsEqual = this.isSelectURL ? lodash_1.default.isEqual(items, this.downloadedResources) : false;\n const areItemsEnded = this.component.limit > items.length;\n const areItemsDownloaded = areItemsEqual\n && this.downloadedResources\n && this.downloadedResources.length === items.length;\n if (areItemsEnded) {\n this.disableInfiniteScroll();\n }\n else if (areItemsDownloaded) {\n this.selectOptions = [];\n }\n else {\n this.serverCount = items.serverCount;\n }\n }\n if (this.isScrollLoading && items) {\n if (!areItemsEqual) {\n this.downloadedResources = this.downloadedResources\n ? this.downloadedResources.concat(items)\n : items;\n }\n this.downloadedResources.serverCount = items.serverCount || this.downloadedResources.serverCount;\n }\n else {\n this.downloadedResources = items || [];\n this.selectOptions = [];\n // If there is new select option with same id as already selected, set the new one\n if (!lodash_1.default.isEmpty(this.dataValue) && this.component.idPath) {\n const selectedOptionId = lodash_1.default.get(this.dataValue, this.component.idPath, null);\n const newOptionWithSameId = !lodash_1.default.isNil(selectedOptionId) && items.find(item => {\n const itemId = lodash_1.default.get(item, this.component.idPath);\n return itemId === selectedOptionId;\n });\n if (newOptionWithSameId) {\n this.setValue(newOptionWithSameId);\n }\n }\n }\n // Add the value options.\n if (!fromSearch) {\n this.addValueOptions(items);\n }\n if (this.component.widget === 'html5' && !this.component.placeholder) {\n this.addOption(null, '');\n }\n // Iterate through each of the items.\n lodash_1.default.each(items, (item, index) => {\n // preventing references of the components inside the form to the parent form when building forms\n if (this.root && this.root.options.editForm && this.root.options.editForm._id && this.root.options.editForm._id === item._id)\n return;\n const itemValueAndLabel = this.selectValueAndLabel(item);\n this.addOption(itemValueAndLabel.value, itemValueAndLabel.label, {}, lodash_1.default.get(item, this.component.idPath, String(index)));\n });\n if (this.choices) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n else if (this.loading) {\n // Re-attach select input.\n // this.appendTo(this.refs.input[0], this.selectContainer);\n }\n // We are no longer loading.\n this.isScrollLoading = false;\n this.loading = false;\n const searching = fromSearch && ((_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.input) === null || _b === void 0 ? void 0 : _b.isFocussed);\n if (!searching) {\n // If a value is provided, then select it.\n if (!this.isEmpty() || this.isRemoveButtonPressed) {\n this.setValue(this.dataValue, {\n noUpdateEvent: true\n });\n }\n else if (this.shouldAddDefaultValue && !this.options.readOnly) {\n // If a default value is provided then select it.\n const defaultValue = this.defaultValue;\n if (!this.isEmpty(defaultValue)) {\n this.setValue(defaultValue);\n }\n }\n }\n // Say we are done loading the items.\n this.itemsLoadedResolve();\n }\n getSingleItemValueForHTMLMode(data) {\n var _a;\n const option = (_a = this.selectOptions) === null || _a === void 0 ? void 0 : _a.find(({ value }) => lodash_1.default.isEqual(value, data));\n if (option) {\n return option.label || data;\n }\n return data;\n }\n itemValueForHTMLMode(value) {\n if (!this.isHtmlRenderMode()) {\n return super.itemValueForHTMLMode(value);\n }\n if (Array.isArray(value)) {\n const values = value.map(item => Array.isArray(item)\n ? this.itemValueForHTMLMode(item)\n : this.getSingleItemValueForHTMLMode(item));\n return values.join(', ');\n }\n return this.getSingleItemValueForHTMLMode(value);\n }\n /* eslint-enable max-statements */\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && (this.component.defaultValue === false || this.component.defaultValue === 0)) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n get loadingError() {\n return !this.component.refreshOn && !this.component.refreshOnBlur && this.networkError;\n }\n loadItems(url, search, headers, options, method, body) {\n options = options || {};\n // See if we should load items or not.\n if (!this.shouldLoad || (!this.itemsFromUrl && this.options.readOnly)) {\n this.isScrollLoading = false;\n this.loading = false;\n this.itemsLoadedResolve();\n return;\n }\n // See if they have not met the minimum search requirements.\n const minSearch = parseInt(this.component.minSearch, 10);\n if (this.component.searchField &&\n (minSearch > 0) &&\n (!search || (search.length < minSearch))) {\n // Set empty items.\n return this.setItems([]);\n }\n // Ensure we have a method and remove any body if method is get\n method = method || 'GET';\n if (method.toUpperCase() === 'GET') {\n body = null;\n }\n const limit = this.component.limit || 100;\n const skip = this.isScrollLoading ? this.selectOptions.length : 0;\n const query = this.component.disableLimit ? {} : {\n limit,\n skip,\n };\n // Allow for url interpolation.\n url = this.interpolate(url, {\n formioBase: Formio_1.Formio.getBaseUrl(),\n search,\n limit,\n skip,\n page: Math.abs(Math.floor(skip / limit))\n });\n // Add search capability.\n if (this.component.searchField && search) {\n const searchValue = Array.isArray(search)\n ? search.join(',')\n : typeof search === 'object'\n ? JSON.stringify(search)\n : search;\n query[this.component.searchField] = this.component.searchField.endsWith('__regex')\n ? lodash_1.default.escapeRegExp(searchValue)\n : searchValue;\n }\n // If they wish to return only some fields.\n if (this.component.selectFields) {\n query.select = this.component.selectFields;\n }\n // Add sort capability\n if (this.component.sort) {\n query.sort = this.component.sort;\n }\n if (!lodash_1.default.isEmpty(query)) {\n // Add the query string.\n url += (!url.includes('?') ? '?' : '&') + Formio_1.Formio.serialize(query, (item) => this.interpolate(item));\n }\n // Add filter capability\n if (this.component.filter) {\n url += (!url.includes('?') ? '?' : '&') + this.interpolate(this.component.filter);\n }\n // Set ignoreCache if it is\n options.ignoreCache = this.component.ignoreCache;\n // Make the request.\n options.header = headers;\n this.loading = true;\n Formio_1.Formio.makeRequest(this.options.formio, 'select', url, method, body, options)\n .then((response) => {\n this.loading = false;\n this.setItems(response, !!search);\n })\n .catch((err) => {\n if (this.itemsFromUrl) {\n this.setItems([]);\n this.disableInfiniteScroll();\n }\n this.isScrollLoading = false;\n this.handleLoadingError(err);\n });\n }\n handleLoadingError(err) {\n this.loading = false;\n if (err.networkError) {\n this.networkError = true;\n }\n this.itemsLoadedResolve();\n this.emit('componentError', {\n component: this.component,\n message: err.toString(),\n });\n console.warn(`Unable to load resources for ${this.key}`);\n }\n /**\n * Get the request headers for this select dropdown.\n * @returns {*} - Returns the request headers for this select dropdown.\n */\n get requestHeaders() {\n // Create the headers object.\n const headers = new Formio_1.Formio.Headers();\n // Add custom headers to the url.\n if (this.component.data && this.component.data.headers) {\n try {\n lodash_1.default.each(this.component.data.headers, (header) => {\n if (header.key) {\n headers.set(header.key, this.interpolate(header.value));\n }\n });\n }\n catch (err) {\n console.warn(err.message);\n }\n }\n return headers;\n }\n getCustomItems() {\n const customItems = this.evaluate(this.component.data.custom, {\n values: []\n }, 'values');\n this.asyncValues = (0, utils_1.isPromise)(customItems);\n return customItems;\n }\n asyncCustomValues() {\n if (!lodash_1.default.isBoolean(this.asyncValues)) {\n this.getCustomItems();\n }\n return this.asyncValues;\n }\n updateCustomItems(forceUpdate) {\n if (this.asyncCustomValues()) {\n if (!forceUpdate && !this.active) {\n this.itemsLoadedResolve();\n return;\n }\n this.loading = true;\n this.getCustomItems()\n .then(items => {\n this.loading = false;\n this.setItems(items || []);\n })\n .catch(err => {\n this.handleLoadingError(err);\n });\n }\n else {\n this.setItems(this.getCustomItems() || []);\n }\n }\n isEmpty(value = this.dataValue) {\n return super.isEmpty(value) || value === undefined;\n }\n refresh(value, { instance }) {\n if (this.component.clearOnRefresh && (instance && !instance.pristine)) {\n this.setValue(this.emptyValue);\n }\n this.updateItems(null, true);\n }\n get additionalResourcesAvailable() {\n return lodash_1.default.isNil(this.serverCount) || (this.serverCount > this.downloadedResources.length);\n }\n get serverCount() {\n if (this.isFromSearch) {\n return this.searchServerCount;\n }\n return this.defaultServerCount;\n }\n set serverCount(value) {\n if (this.isFromSearch) {\n this.searchServerCount = value;\n }\n else {\n this.defaultServerCount = value;\n }\n }\n get downloadedResources() {\n if (this.isFromSearch) {\n return this.searchDownloadedResources;\n }\n return this.defaultDownloadedResources;\n }\n set downloadedResources(value) {\n if (this.isFromSearch) {\n this.searchDownloadedResources = value;\n }\n else {\n this.defaultDownloadedResources = value;\n }\n }\n addPlaceholder() {\n if (!this.component.placeholder) {\n return;\n }\n this.addOption('', this.component.placeholder, { placeholder: true });\n }\n /**\n * Activate this select control.\n */\n activate() {\n if (this.loading || !this.active) {\n this.setLoadingItem();\n }\n if (this.active) {\n return;\n }\n this.activated = true;\n this.triggerUpdate();\n }\n setLoadingItem(addToCurrentList = false) {\n if (this.choices) {\n if (addToCurrentList) {\n this.choices.setChoices([{\n value: `${this.id}-loading`,\n label: 'Loading...',\n disabled: true,\n }], 'value', 'label');\n }\n else {\n this.choices.setChoices([{\n value: '',\n label: `<i class=\"${this.iconClass('refresh')}\" style=\"font-size:1.3em;\"></i>`,\n disabled: true,\n }], 'value', 'label', true);\n }\n }\n else if (this.component.dataSrc === 'url' || this.component.dataSrc === 'resource') {\n this.addOption('', this.t('loading...'));\n }\n }\n get active() {\n return !this.component.lazyLoad || this.activated;\n }\n render() {\n const info = this.inputInfo;\n info.attr = info.attr || {};\n info.multiple = this.component.multiple;\n return super.render(this.wrapElement(this.renderTemplate('select', {\n input: info,\n selectOptions: '',\n index: null,\n })));\n }\n wrapElement(element) {\n return this.component.addResource && !this.options.readOnly\n ? (this.renderTemplate('resourceAdd', {\n element\n }))\n : element;\n }\n choicesOptions() {\n const useSearch = this.component.hasOwnProperty('searchEnabled') ? this.component.searchEnabled : true;\n const placeholderValue = this.t(this.component.placeholder, { _userInput: true });\n let customOptions = this.component.customOptions || {};\n if (typeof customOptions == 'string') {\n try {\n customOptions = JSON.parse(customOptions);\n }\n catch (err) {\n console.warn(err.message);\n customOptions = {};\n }\n }\n const commonFuseOptions = {\n maxPatternLength: 1000,\n distance: 1000,\n };\n return Object.assign({ removeItemButton: this.component.disabled ? false : lodash_1.default.get(this.component, 'removeItemButton', true), itemSelectText: '', classNames: {\n containerOuter: 'choices form-group formio-choices',\n containerInner: this.transform('class', 'form-control ui fluid selection dropdown')\n }, addItemText: false, allowHTML: true, placeholder: !!this.component.placeholder, placeholderValue: placeholderValue, noResultsText: this.t('No results found'), noChoicesText: this.t('No choices to choose from'), searchPlaceholderValue: this.t('Type to search'), shouldSort: false, position: (this.component.dropdown || 'auto'), searchEnabled: useSearch, searchChoices: !this.component.searchField, searchFields: lodash_1.default.get(this, 'component.searchFields', ['label']), shadowRoot: this.root ? this.root.shadowRoot : null, fuseOptions: this.component.useExactSearch\n ? Object.assign({ tokenize: true, matchAllTokens: true }, commonFuseOptions) : Object.assign({}, lodash_1.default.get(this, 'component.fuseOptions', {}), Object.assign({ include: 'score', threshold: lodash_1.default.get(this, 'component.selectThreshold', 0.3) }, commonFuseOptions)), valueComparer: lodash_1.default.isEqual, resetScrollPosition: false }, customOptions);\n }\n /* eslint-disable max-statements */\n attach(element) {\n var _a, _b, _c;\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n selectContainer: 'single',\n addResource: 'single',\n autocompleteInput: 'single'\n });\n //enable autocomplete for select\n const autocompleteInput = this.refs.autocompleteInput;\n if (autocompleteInput) {\n this.addEventListener(autocompleteInput, 'change', (event) => {\n this.setValue(event.target.value);\n });\n }\n const input = this.refs.selectContainer;\n if (!input) {\n return;\n }\n this.addEventListener(input, this.inputInfo.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n this.attachRefreshOnBlur();\n if (this.component.widget === 'html5') {\n this.addFocusBlurEvents(input);\n this.triggerUpdate(null, true);\n if (this.visible) {\n this.setItems(this.selectItems || []);\n }\n this.focusableElement = input;\n if (this.component.dataSrc === 'custom') {\n this.addEventListener(input, 'focus', () => this.updateCustomItems());\n }\n this.addEventListener(input, 'keydown', (event) => {\n const { key } = event;\n if (['Backspace', 'Delete'].includes(key)) {\n this.setValue(this.emptyValue);\n }\n });\n return;\n }\n const tabIndex = input.tabIndex;\n this.addPlaceholder();\n if (this.i18next) {\n input.setAttribute('dir', this.i18next.dir());\n }\n if ((_c = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.containerOuter) === null || _b === void 0 ? void 0 : _b.element) === null || _c === void 0 ? void 0 : _c.parentNode) {\n this.choices.destroy();\n }\n const choicesOptions = this.choicesOptions();\n if (ChoicesWrapper_1.default) {\n this.choices = new ChoicesWrapper_1.default(input, choicesOptions);\n if (this.selectOptions && this.selectOptions.length) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n if (this.component.multiple) {\n this.focusableElement = this.choices.input.element;\n }\n else {\n this.focusableElement = this.choices.containerInner.element;\n this.choices.containerOuter.element.setAttribute('tabIndex', '-1');\n this.addEventListener(this.choices.containerOuter.element, 'focus', () => this.focusableElement.focus());\n }\n Input_1.default.prototype.addFocusBlurEvents.call(this, this.focusableElement);\n if (this.itemsFromUrl && !this.component.noRefreshOnScroll) {\n this.scrollList = this.choices.choiceList.element;\n this.addEventListener(this.scrollList, 'scroll', () => this.onScroll());\n }\n if (choicesOptions.removeItemButton) {\n this.addEventListener(input, 'removeItem', () => {\n this.isRemoveButtonPressed = true;\n });\n }\n }\n if (window && this.choices && this.shouldPositionDropdown) {\n this.addEventListener(window.document, 'scroll', () => {\n this.positionDropdown(true);\n }, false, true);\n }\n this.focusableElement.setAttribute('tabIndex', tabIndex);\n // If a search field is provided, then add an event listener to update items on search.\n if (this.component.searchField) {\n // Make sure to clear the search when no value is provided.\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.addEventListener(this.choices.input.element, 'input', (event) => {\n this.isFromSearch = !!event.target.value;\n if (!event.target.value) {\n this.triggerUpdate();\n }\n else {\n this.serverCount = null;\n this.downloadedResources = [];\n }\n });\n }\n this.addEventListener(input, 'choice', () => {\n if (this.component.multiple && this.component.dataSrc === 'resource' && this.isFromSearch) {\n this.triggerUpdate();\n }\n this.isFromSearch = false;\n });\n // avoid spamming the resource/url endpoint when we have server side filtering enabled.\n const debounceTimeout = this.component.searchField && (this.isSelectResource || this.isSelectURL) ?\n (this.component.searchDebounce === 0 ? 0 : this.component.searchDebounce || this.defaultSchema.searchDebounce) * 1000\n : 0;\n const updateComponent = (evt) => {\n this.triggerUpdate(evt.detail.value);\n };\n this.addEventListener(input, 'search', lodash_1.default.debounce((e) => {\n updateComponent(e);\n this.positionDropdown();\n }, debounceTimeout));\n this.addEventListener(input, 'stopSearch', () => this.triggerUpdate());\n this.addEventListener(input, 'hideDropdown', () => {\n if (this.choices && this.choices.input && this.choices.input.element) {\n this.choices.input.element.value = '';\n }\n this.updateItems(null, true);\n });\n }\n this.addEventListener(input, 'showDropdown', () => {\n this.update();\n this.positionDropdown();\n });\n if (this.shouldPositionDropdown) {\n this.addEventListener(input, 'highlightChoice', () => {\n this.positionDropdown();\n });\n }\n if (this.choices && choicesOptions.placeholderValue && this.choices._isSelectOneElement) {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n this.addEventListener(input, 'removeItem', () => {\n this.addPlaceholderItem(choicesOptions.placeholderValue);\n });\n }\n // Add value options.\n this.addValueOptions();\n this.setChoicesValue(this.dataValue);\n if (this.isSelectResource && this.refs.addResource) {\n this.addEventListener(this.refs.addResource, 'click', (event) => {\n event.preventDefault();\n const formioForm = this.ce('div');\n const dialog = this.createModal(formioForm);\n const projectUrl = lodash_1.default.get(this.root, 'formio.projectUrl', Formio_1.Formio.getProjectUrl());\n const formUrl = `${projectUrl}/form/${this.component.data.resource}`;\n new Form_1.default(formioForm, formUrl, {}).ready\n .then((form) => {\n form.on('submit', (submission) => {\n // If valueProperty is set, replace the submission with the corresponding value\n let value = this.valueProperty ? lodash_1.default.get(submission, this.valueProperty) : submission;\n if (this.component.multiple) {\n value = [...this.dataValue, value];\n }\n this.setValue(value);\n this.triggerUpdate();\n dialog.close();\n });\n });\n });\n }\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n this.triggerUpdate();\n return superAttach;\n }\n setDropdownPosition() {\n var _a, _b, _c, _d;\n const dropdown = (_b = (_a = this.choices) === null || _a === void 0 ? void 0 : _a.dropdown) === null || _b === void 0 ? void 0 : _b.element;\n const container = (_d = (_c = this.choices) === null || _c === void 0 ? void 0 : _c.containerOuter) === null || _d === void 0 ? void 0 : _d.element;\n if (!dropdown || !container) {\n return;\n }\n const containerPosition = container.getBoundingClientRect();\n const isFlipped = container.classList.contains('is-flipped');\n lodash_1.default.assign(dropdown.style, {\n top: `${isFlipped ? containerPosition.top - dropdown.offsetHeight : containerPosition.top + containerPosition.height}px`,\n left: `${containerPosition.left}px`,\n width: `${containerPosition.width}px`,\n position: 'fixed',\n bottom: 'unset',\n right: 'unset',\n });\n }\n hasDataGridAncestor(comp) {\n comp = comp || this;\n if (comp.inDataGrid || comp.type === 'datagrid') {\n return true;\n }\n else if (comp.parent) {\n return this.hasDataGridAncestor(comp.parent);\n }\n else {\n return false;\n }\n }\n positionDropdown(scroll) {\n var _a;\n if (!this.shouldPositionDropdown || !this.choices || (!((_a = this.choices.dropdown) === null || _a === void 0 ? void 0 : _a.isActive) && scroll)) {\n return;\n }\n this.setDropdownPosition();\n this.itemsLoaded.then(() => {\n this.setDropdownPosition();\n });\n }\n get isLoadingAvailable() {\n return !this.isScrollLoading && this.additionalResourcesAvailable;\n }\n onScroll() {\n if (this.isLoadingAvailable) {\n this.isScrollLoading = true;\n this.setLoadingItem(true);\n this.triggerUpdate(this.choices.input.element.value);\n }\n }\n attachRefreshOnBlur() {\n if (this.component.refreshOnBlur) {\n this.on('blur', (instance) => {\n this.checkRefreshOn([{ instance, value: instance.dataValue }], { fromBlur: true });\n });\n }\n }\n addPlaceholderItem(placeholderValue) {\n const items = this.choices._store.activeItems;\n if (!items.length) {\n this.choices._addItem({\n value: '',\n label: placeholderValue,\n choiceId: 0,\n groupId: -1,\n customProperties: null,\n placeholder: true,\n keyCode: null\n });\n }\n }\n /* eslint-enable max-statements */\n update() {\n if (this.component.dataSrc === 'custom') {\n this.updateCustomItems();\n }\n // Activate the control.\n this.activate();\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.setDisabled(this.choices.containerInner.element, true);\n this.focusableElement.removeAttribute('tabIndex');\n this.choices.disable();\n }\n else {\n this.setDisabled(this.choices.containerInner.element, false);\n this.focusableElement.setAttribute('tabIndex', this.component.tabindex || 0);\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n set visible(value) {\n // If we go from hidden to visible, trigger a refresh.\n if (value && (!this._visible !== !value)) {\n this.triggerUpdate();\n }\n super.visible = value;\n }\n get visible() {\n return super.visible;\n }\n addCurrentChoices(values, items, keyValue) {\n if (!values) {\n return false;\n }\n const notFoundValuesToAdd = [];\n const added = values.reduce((defaultAdded, value) => {\n if (!value || lodash_1.default.isEmpty(value)) {\n return defaultAdded;\n }\n let found = false;\n // Make sure that `items` and `this.selectOptions` points\n // to the same reference. Because `this.selectOptions` is\n // internal property and all items are populated by\n // `this.addOption` method, we assume that items has\n // 'label' and 'value' properties. This assumption allows\n // us to read correct value from the item.\n const isSelectOptions = items === this.selectOptions;\n if (items && items.length) {\n lodash_1.default.each(items, (choice) => {\n if (choice._id && value._id && (choice._id === value._id)) {\n found = true;\n return false;\n }\n const itemValue = keyValue ? choice.value : this.itemValue(choice, isSelectOptions);\n found |= lodash_1.default.isEqual(itemValue, value);\n return found ? false : true;\n });\n }\n // Add the default option if no item is found.\n if (!found) {\n notFoundValuesToAdd.push(this.selectValueAndLabel(value));\n return true;\n }\n return found || defaultAdded;\n }, false);\n if (notFoundValuesToAdd.length) {\n if (this.choices) {\n this.choices.setChoices(notFoundValuesToAdd, 'value', 'label');\n }\n notFoundValuesToAdd.map(notFoundValue => {\n this.addOption(notFoundValue.value, notFoundValue.label);\n });\n }\n return added;\n }\n getValueAsString(data, options) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map((v) => this.asString(v, options)).join(', ')\n : this.asString(data, options);\n }\n getValue() {\n // If the widget isn't active.\n if (this.viewOnly || this.loading\n || (!this.component.lazyLoad && !this.selectOptions.length)\n || !this.element) {\n return this.dataValue;\n }\n let value = this.emptyValue;\n if (this.choices) {\n value = this.choices.getValue(true);\n // Make sure we don't get the placeholder\n if (!this.component.multiple &&\n this.component.placeholder &&\n (value === this.t(this.component.placeholder, { _userInput: true }))) {\n value = this.emptyValue;\n }\n }\n else if (this.refs.selectContainer) {\n value = this.refs.selectContainer.value;\n if (this.valueProperty === '' || this.isEntireObjectDisplay()) {\n if (value === '') {\n return {};\n }\n const option = this.selectOptions[value] ||\n this.selectOptions.find(option => option.id === value);\n if (option && lodash_1.default.isObject(option.value)) {\n value = option.value;\n }\n }\n }\n else {\n value = this.dataValue;\n }\n // Choices will return undefined if nothing is selected. We really want '' to be empty.\n if (value === undefined || value === null) {\n value = '';\n }\n return value;\n }\n redraw() {\n const done = super.redraw();\n this.triggerUpdate();\n return done;\n }\n normalizeSingleValue(value) {\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n const dataType = this.component.dataType || 'auto';\n const normalize = {\n value,\n number() {\n const numberValue = Number(this.value);\n const isEquivalent = value.toString() === numberValue.toString();\n if (!Number.isNaN(numberValue) && Number.isFinite(numberValue) && value !== '' && isEquivalent) {\n this.value = numberValue;\n }\n return this;\n },\n boolean() {\n if (lodash_1.default.isString(this.value)\n && (this.value.toLowerCase() === 'true'\n || this.value.toLowerCase() === 'false')) {\n this.value = (this.value.toLowerCase() === 'true');\n }\n return this;\n },\n string() {\n this.value = String(this.value);\n return this;\n },\n object() {\n return this;\n },\n auto() {\n if (lodash_1.default.isObject(this.value)) {\n this.value = this.object().value;\n }\n else {\n this.value = this.string().number().boolean().value;\n }\n return this;\n }\n };\n try {\n return normalize[dataType]().value;\n }\n catch (err) {\n console.warn('Failed to normalize value', err);\n return value;\n }\n }\n /**\n * Normalize values coming into updateValue. For example, depending on the configuration, string value `\"true\"` will be normalized to boolean `true`.\n * @param {*} value - The value to normalize\n * @returns {*} - Returns the normalized value\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue));\n }\n return super.normalizeValue(this.normalizeSingleValue(value));\n }\n setMetadata(value, flags = {}) {\n var _a, _b;\n if (lodash_1.default.isNil(value)) {\n return;\n }\n const valueIsObject = lodash_1.default.isObject(value);\n //check if value equals to default emptyValue\n if (valueIsObject && Object.keys(value).length === 0) {\n return value;\n }\n // Check to see if we need to save off the template data into our metadata.\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n const shouldSaveData = !valueIsObject || this.component.reference;\n if (!lodash_1.default.isNil(templateValue) && shouldSaveData && this.templateData && this.templateData[templateValue] && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submission)) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n let templateData = this.templateData[templateValue];\n if (this.component.multiple) {\n templateData = {};\n const dataValue = this.dataValue;\n if (dataValue && lodash_1.default.isArray(dataValue) && dataValue.length) {\n dataValue.forEach((dataValueItem) => {\n const dataValueItemValue = this.component.reference ? dataValueItem._id.toString() : dataValueItem;\n templateData[dataValueItemValue] = this.templateData[dataValueItemValue];\n });\n }\n templateData[value] = this.templateData[value];\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\n if (flags.resetValue && ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submission)) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n submission.metadata.selectData = {};\n }\n }\n updateValue(value, flags) {\n const changed = super.updateValue(value, flags);\n if (changed || !this.selectMetadata || flags.resetValue) {\n if (this.component.multiple && Array.isArray(this.dataValue)) {\n this.dataValue.forEach(singleValue => this.setMetadata(singleValue, flags));\n }\n else {\n this.setMetadata(this.dataValue, flags);\n }\n }\n return changed;\n }\n undoValueTyping(value) {\n let untypedValue = value;\n if (this.component.multiple && Array.isArray(value)) {\n untypedValue = value.map(v => {\n if (typeof v === 'boolean' || typeof v === 'number') {\n return v.toString();\n }\n return v;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n untypedValue = value.toString();\n }\n }\n return untypedValue;\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\n const changed = this.updateValue(value, flags);\n if (this.component.widget === 'html5' && (lodash_1.default.isEqual(value, previousValue) || lodash_1.default.isEqual(previousValue, {}) && lodash_1.default.isEqual(flags, {})) && !flags.fromSubmission) {\n return false;\n }\n value = this.dataValue;\n const hasPreviousValue = !this.isEmpty(previousValue);\n const hasValue = !this.isEmpty(value);\n // Undo typing when searching to set the value.\n value = this.undoValueTyping(value);\n if (this.isHtmlRenderMode() && flags && flags.fromSubmission && changed) {\n this.itemsLoaded.then(() => {\n this.redraw();\n });\n return changed;\n }\n // Do not set the value if we are loading... that will happen after it is done.\n if (this.loading) {\n return changed;\n }\n // Determine if we need to perform an initial lazyLoad api call if searchField is provided.\n if (this.isInitApiCallNeeded(hasValue)) {\n this.loading = true;\n this.lazyLoadInit = true;\n const searchProperty = this.component.searchField || this.component.valueProperty;\n this.triggerUpdate(lodash_1.default.get(value.data || value, searchProperty, value), true);\n return changed;\n }\n // Add the value options.\n this.itemsLoaded.then(() => {\n this.addValueOptions();\n this.setChoicesValue(value, hasPreviousValue, flags);\n });\n return changed;\n }\n isInitApiCallNeeded(hasValue) {\n return this.component.lazyLoad &&\n !this.lazyLoadInit &&\n !this.active &&\n !this.selectOptions.length &&\n hasValue &&\n this.shouldInitialLoad &&\n this.visible && (this.component.searchField || this.component.valueProperty);\n }\n setChoicesValue(value, hasPreviousValue, flags = {}) {\n const hasValue = !this.isEmpty(value) || flags.fromSubmission;\n hasPreviousValue = (hasPreviousValue === undefined) ? true : hasPreviousValue;\n if (this.choices) {\n // Now set the value.\n if (hasValue) {\n this.choices.removeActiveItems();\n // Add the currently selected choices if they don't already exist.\n const currentChoices = Array.isArray(value) && this.component.multiple ? value : [value];\n if (!this.addCurrentChoices(currentChoices, this.selectOptions, true)) {\n this.choices.setChoices(this.selectOptions, 'value', 'label', true);\n }\n this.choices.setChoiceByValue(currentChoices);\n }\n else if (hasPreviousValue || flags.resetValue) {\n this.choices.removeActiveItems();\n }\n }\n else {\n if (hasValue) {\n const values = Array.isArray(value) ? value : [value];\n if (!lodash_1.default.isEqual(this.dataValue, this.defaultValue) && this.selectOptions.length < 2\n || (this.selectData && flags.fromSubmission)) {\n const { value, label } = this.selectValueAndLabel(this.dataValue);\n this.addOption(value, label);\n }\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n lodash_1.default.each(values, (val) => {\n if (selectOption.value === '') {\n selectOption.value = {};\n }\n if (lodash_1.default.isEqual(val, selectOption.value) && selectOption.element) {\n selectOption.element.selected = true;\n selectOption.element.setAttribute('selected', 'selected');\n return false;\n }\n });\n });\n }\n else {\n lodash_1.default.each(this.selectOptions, (selectOption) => {\n if (selectOption.element) {\n selectOption.element.selected = false;\n selectOption.element.removeAttribute('selected');\n }\n });\n }\n }\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.getOptionsValues();\n if (values) {\n if (lodash_1.default.isObject(value)) {\n const compareComplexValues = (optionValue) => {\n const normalizedOptionValue = this.normalizeSingleValue(optionValue);\n if (!lodash_1.default.isObject(normalizedOptionValue)) {\n return false;\n }\n try {\n return (JSON.stringify(normalizedOptionValue) === JSON.stringify(value));\n }\n catch (err) {\n console.warn.error('Error while comparing items', err);\n return false;\n }\n };\n return values.findIndex((optionValue) => compareComplexValues(optionValue)) !== -1;\n }\n return values.findIndex((optionValue) => this.normalizeSingleValue(optionValue) === value) !== -1;\n }\n return false;\n }\n /**\n * Performs required transformations on the initial value to use in selectOptions\n * @param {*} value - The value to transform.\n * @returns {*} - Returns the options value.\n */\n getOptionValue(value) {\n return lodash_1.default.isObject(value) && this.isEntireObjectDisplay()\n ? this.normalizeSingleValue(value)\n : lodash_1.default.isObject(value) && (this.valueProperty || this.component.key !== 'resource')\n ? value\n : lodash_1.default.isObject(value) && !this.valueProperty\n ? this.interpolate(this.component.template, { item: value }).replace(/<\\/?[^>]+(>|$)/g, '')\n : lodash_1.default.isNull(value)\n ? this.emptyValue\n : String(this.normalizeSingleValue(value));\n }\n /**\n * If component has static values (values, json) or custom values, returns an array of them\n * @returns {Array<*>|undefined} - Returns an array of the static or custom values.\n */\n getOptionsValues() {\n let rawItems = [];\n switch (this.component.dataSrc) {\n case 'values':\n rawItems = this.component.data.values;\n break;\n case 'json':\n rawItems = this.component.data.json;\n break;\n case 'custom':\n rawItems = this.getCustomItems();\n break;\n case 'url':\n rawItems = this.selectItems;\n break;\n }\n if (typeof rawItems === 'string') {\n try {\n rawItems = JSON.parse(rawItems);\n }\n catch (err) {\n console.warn(err.message);\n rawItems = [];\n }\n }\n if (!Array.isArray(rawItems)) {\n return;\n }\n return rawItems.map((item) => this.getOptionValue(this.itemValue(item)));\n }\n /**\n * Deletes the value of the component.\n */\n deleteValue() {\n this.setValue('', {\n noUpdateEvent: true\n });\n this.unset();\n }\n /**\n * Check if a component is eligible for multiple validation\n * @returns {boolean} - Returns FALSE for select components.\n */\n validateMultiple() {\n // Select component will contain one input when flagged as multiple.\n return false;\n }\n /**\n * Output this select dropdown as a string value.\n * @returns {*}\n */\n isBooleanOrNumber(value) {\n return typeof value === 'number' || typeof value === 'boolean';\n }\n getNormalizedValues() {\n if (!this.component || !this.component.data || !this.component.data.values) {\n return;\n }\n return this.component.data.values.map(value => ({ label: value.label, value: String(this.normalizeSingleValue(value.value)) }));\n }\n asString(value, options = {}) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\n if (options.modalPreview || this.inDataTable) {\n if (this.inDataTable) {\n value = this.undoValueTyping(value);\n }\n const templateValue = (this.isEntireObjectDisplay() && !lodash_1.default.isObject(value.data)) ? { data: value } : value;\n const template = this.itemTemplate(templateValue, value, options);\n return template;\n }\n //need to convert values to strings to be able to compare values with available options that are strings\n const convertToString = (data, valueProperty) => {\n if (valueProperty) {\n if (Array.isArray(data)) {\n data.forEach((item) => item[valueProperty] = item[valueProperty].toString());\n }\n else if (lodash_1.default.isObject(data)) {\n data[valueProperty] = data[valueProperty].toString();\n }\n return data;\n }\n if (this.isBooleanOrNumber(data)) {\n data = data.toString();\n }\n if (Array.isArray(data) && data.some(item => this.isBooleanOrNumber(item))) {\n data = data.map(item => this.isBooleanOrNumber(item) ? item.toString() : item);\n }\n return data;\n };\n value = convertToString(value);\n if (['values', 'custom'].includes(this.component.dataSrc) && !this.asyncCustomValues()) {\n const { items, valueProperty, } = this.component.dataSrc === 'values'\n ? {\n items: convertToString(this.getNormalizedValues(), 'value'),\n valueProperty: 'value',\n }\n : {\n items: convertToString(this.getCustomItems(), this.valueProperty),\n valueProperty: this.valueProperty,\n };\n const getFromValues = () => {\n const initialValue = lodash_1.default.find(items, [valueProperty, value]);\n const values = this.defaultSchema.data.values || [];\n return lodash_1.default.isEqual(initialValue, values[0]) ? '-' : initialValue;\n };\n value = (this.component.multiple && Array.isArray(value))\n ? lodash_1.default.filter(items, (item) => value.includes(item.value))\n : (valueProperty && items)\n ? (_a = getFromValues()) !== null && _a !== void 0 ? _a : { value, label: value }\n : value;\n }\n if (lodash_1.default.isString(value)) {\n return value;\n }\n const getTemplateValue = (v) => {\n const itemTemplate = this.itemTemplate(v);\n return options.csv && itemTemplate\n ? (0, utils_1.removeHTML)(itemTemplate)\n : itemTemplate;\n };\n if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(getTemplateValue(item)));\n if (this.component.dataSrc === 'resource' && items.length > 0) {\n return items.join(', ');\n }\n else if (items.length > 0) {\n return items.join('<br />');\n }\n else {\n return '-';\n }\n }\n if (this.isEntireObjectDisplay() && lodash_1.default.isObject(value)) {\n return JSON.stringify(value);\n }\n return !lodash_1.default.isNil(value)\n ? getTemplateValue(value)\n : '-';\n }\n detach() {\n var _a, _b;\n this.off('blur');\n if (this.choices) {\n if ((_b = (_a = this.choices.containerOuter) === null || _a === void 0 ? void 0 : _a.element) === null || _b === void 0 ? void 0 : _b.parentNode) {\n this.choices.destroy();\n }\n this.choices = null;\n }\n super.detach();\n }\n focus() {\n super.focus.call(this);\n if (this.focusableElement) {\n this.focusableElement.focus();\n }\n }\n setErrorClasses(elements, dirty, hasError, hasMessages, element = this.element) {\n super.setErrorClasses(elements, dirty, hasError, hasMessages, element);\n if (this.choices) {\n super.setErrorClasses([this.choices.containerInner.element], dirty, hasError, hasMessages, element);\n }\n else {\n super.setErrorClasses([this.refs.selectContainer], dirty, hasError, hasMessages, element);\n }\n }\n}\nexports[\"default\"] = SelectComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/select/Select.js?");
6978
6989
 
6979
6990
  /***/ }),
6980
6991
 
@@ -10886,7 +10897,7 @@ eval("\nvar parent = __webpack_require__(/*! ../../es/object/from-entries */ \".
10886
10897
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
10887
10898
 
10888
10899
  "use strict";
10889
- eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.FormBuilder = exports.Form = exports.Formio = void 0;\nconst CDN_js_1 = __importDefault(__webpack_require__(/*! ./CDN.js */ \"./lib/cjs/CDN.js\"));\nclass Formio {\n static setLicense(license, norecurse = false) {\n _a.license = license;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setLicense(license);\n }\n }\n static setBaseUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setBaseUrl(url);\n }\n }\n static setApiUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setApiUrl(url);\n }\n }\n static setProjectUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setProjectUrl(url);\n }\n }\n static setAppUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setAppUrl(url);\n }\n }\n static setPathType(type, norecurse = false) {\n _a.pathType = type;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setPathType(type);\n }\n }\n static debug(...args) {\n if (_a.config.debug) {\n console.log(...args);\n }\n }\n static clearCache() {\n if (_a.FormioClass) {\n _a.FormioClass.clearCache();\n }\n }\n static global(prop, flag = '') {\n const globalValue = window[prop];\n if (flag && globalValue && !globalValue[flag]) {\n return null;\n }\n _a.debug(`Getting global ${prop}`, globalValue);\n return globalValue;\n }\n static use(module) {\n if (_a.FormioClass && _a.FormioClass.isRenderer) {\n _a.FormioClass.use(module);\n }\n else {\n _a.modules.push(module);\n }\n }\n static createElement(type, attrs, children) {\n const element = document.createElement(type);\n if (!attrs) {\n return element;\n }\n Object.keys(attrs).forEach(key => {\n element.setAttribute(key, attrs[key]);\n });\n (children || []).forEach(child => {\n element.appendChild(_a.createElement(child.tag, child.attrs, child.children));\n });\n return element;\n }\n static addScript(wrapper, src, name, flag = '') {\n return __awaiter(this, void 0, void 0, function* () {\n if (!src) {\n return Promise.resolve();\n }\n if (typeof src !== 'string' && src.length) {\n return Promise.all(src.map(ref => _a.addScript(wrapper, ref)));\n }\n if (name && _a.global(name, flag)) {\n _a.debug(`${name} already loaded.`);\n return Promise.resolve(_a.global(name));\n }\n _a.debug('Adding Script', src);\n try {\n wrapper.appendChild(_a.createElement('script', {\n src\n }));\n }\n catch (err) {\n _a.debug(err);\n return Promise.resolve();\n }\n if (!name) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n _a.debug(`Waiting to load ${name}`);\n const wait = setInterval(() => {\n if (_a.global(name, flag)) {\n clearInterval(wait);\n _a.debug(`${name} loaded.`);\n resolve(_a.global(name));\n }\n }, 100);\n });\n });\n }\n static addStyles(wrapper, href) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!href) {\n return;\n }\n if (typeof href !== 'string' && href.length) {\n href.forEach(ref => _a.addStyles(wrapper, ref));\n return;\n }\n _a.debug('Adding Styles', href);\n wrapper.appendChild(_a.createElement('link', {\n rel: 'stylesheet',\n href\n }));\n });\n }\n static submitDone(instance, submission) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.debug('Submision Complete', submission);\n if (_a.config.submitDone) {\n _a.config.submitDone(submission, instance);\n }\n const successMessage = (_a.config.success || '').toString();\n if (successMessage && successMessage.toLowerCase() !== 'false' && instance.element) {\n instance.element.innerHTML = `<div class=\"alert-success\" role=\"alert\">${successMessage}</div>`;\n }\n let returnUrl = _a.config.redirect;\n // Allow form based configuration for return url.\n if (!returnUrl &&\n (instance._form &&\n instance._form.settings &&\n (instance._form.settings.returnUrl ||\n instance._form.settings.redirect))) {\n _a.debug('Return url found in form configuration');\n returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;\n }\n if (returnUrl) {\n const formSrc = instance.formio ? instance.formio.formUrl : '';\n const hasQuery = !!returnUrl.match(/\\?/);\n const isOrigin = returnUrl.indexOf(location.origin) === 0;\n returnUrl += hasQuery ? '&' : '?';\n returnUrl += `sub=${submission._id}`;\n if (!isOrigin && formSrc) {\n returnUrl += `&form=${encodeURIComponent(formSrc)}`;\n }\n _a.debug('Return URL', returnUrl);\n window.location.href = returnUrl;\n if (isOrigin) {\n window.location.reload();\n }\n }\n });\n }\n // Return the full script if the builder is being used.\n static formioScript(script, builder) {\n builder = builder || _a.config.includeBuilder;\n if (_a.fullAdded || builder) {\n _a.fullAdded = true;\n return script.replace('formio.form', 'formio.full');\n }\n return script;\n }\n static addLibrary(libWrapper, lib, name) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!lib) {\n return;\n }\n if (lib.dependencies) {\n for (let i = 0; i < lib.dependencies.length; i++) {\n const libName = lib.dependencies[i];\n yield _a.addLibrary(libWrapper, _a.config.libs[libName], libName);\n }\n }\n if (lib.css) {\n yield _a.addStyles((lib.global ? document.body : libWrapper), lib.css);\n }\n if (lib.js) {\n const module = yield _a.addScript((lib.global ? document.body : libWrapper), lib.js, lib.use ? name : false);\n if (lib.use) {\n _a.debug(`Using ${name}`);\n const options = lib.options || {};\n if (!options.license && _a.license) {\n options.license = _a.license;\n }\n _a.use((typeof lib.use === 'function' ? lib.use(module) : module), options);\n }\n }\n if (lib.globalStyle) {\n const style = _a.createElement('style');\n style.type = 'text/css';\n style.innerHTML = lib.globalStyle;\n document.body.appendChild(style);\n }\n });\n }\n static addLoader(wrapper) {\n return __awaiter(this, void 0, void 0, function* () {\n wrapper.appendChild(_a.createElement('div', {\n 'class': 'formio-loader'\n }, [{\n tag: 'div',\n attrs: {\n class: 'loader-wrapper'\n },\n children: [{\n tag: 'div',\n attrs: {\n class: 'loader text-center'\n }\n }]\n }]));\n });\n }\n // eslint-disable-next-line max-statements\n static init(element, options = {}, builder = false) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.cdn = new CDN_js_1.default(_a.config.cdn, _a.config.cdnUrls || {});\n _a.config.libs = _a.config.libs || {\n uswds: {\n dependencies: ['fontawesome'],\n js: `${_a.cdn.uswds}/uswds.min.js`,\n css: `${_a.cdn.uswds}/uswds.min.css`,\n use: true\n },\n fontawesome: {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: `https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css`,\n globalStyle: `@font-face {\n font-family: 'FontAwesome';\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0');\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');\n font-weight: normal;\n font-style: normal;\n }`\n },\n bootstrap4: {\n dependencies: ['fontawesome'],\n css: `${_a.cdn.bootstrap4}/css/bootstrap.min.css`\n },\n bootstrap: {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootstrap}/css/bootstrap.min.css`\n },\n 'bootstrap-icons': {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: 'https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.min.css',\n globalStyle: `@font-face {\n font-display: block;\n font-family: \"bootstrap-icons\";\n src: url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6\") format(\"woff2\"),\n url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6\") format(\"woff\");\n }`\n }\n };\n // Add all bootswatch templates.\n ['cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', 'litera', 'lumen', 'lux', 'materia', 'minty', 'pulse', 'sandstone', 'simplex', 'sketchy', 'slate', 'solar', 'spacelab', 'superhero', 'united', 'yeti'].forEach((template) => {\n _a.config.libs[template] = {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootswatch}/dist/${template}/bootstrap.min.css`\n };\n });\n const id = _a.config.id || `formio-${Math.random().toString(36).substring(7)}`;\n // Create a new wrapper and add the element inside of a new wrapper.\n let wrapper = _a.createElement('div', {\n 'id': `${id}-wrapper`\n });\n element.parentNode.insertBefore(wrapper, element);\n // If we include the libraries, then we will attempt to run this in shadow dom.\n const useShadowDom = _a.config.includeLibs && !_a.config.noshadow && (typeof wrapper.attachShadow === 'function');\n if (useShadowDom) {\n wrapper = wrapper.attachShadow({\n mode: 'open'\n });\n options.shadowRoot = wrapper;\n }\n element.parentNode.removeChild(element);\n wrapper.appendChild(element);\n // If this is inside of shadow dom, then we need to add the styles and scripts to the shadow dom.\n const libWrapper = useShadowDom ? wrapper : document.body;\n // Load the renderer styles.\n yield _a.addStyles(libWrapper, _a.config.embedCSS || `${_a.cdn.js}/formio.embed.css`);\n // Add a loader.\n _a.addLoader(wrapper);\n const formioSrc = _a.config.full ? 'formio.full' : 'formio.form';\n const renderer = _a.config.debug ? formioSrc : `${formioSrc}.min`;\n _a.FormioClass = yield _a.addScript(libWrapper, _a.formioScript(_a.config.script || `${_a.cdn.js}/${renderer}.js`, builder), 'Formio', builder ? 'isBuilder' : 'isRenderer');\n _a.FormioClass.cdn = _a.cdn;\n _a.FormioClass.setBaseUrl(options.baseUrl || _a.baseUrl || _a.config.base);\n _a.FormioClass.setProjectUrl(options.projectUrl || _a.projectUrl || _a.config.project);\n _a.FormioClass.language = _a.language;\n _a.setLicense(_a.license || _a.config.license || false);\n _a.modules.forEach((module) => {\n _a.FormioClass.use(module);\n });\n if (_a.icons) {\n _a.FormioClass.icons = _a.icons;\n }\n if (_a.pathType) {\n _a.FormioClass.setPathType(_a.pathType);\n }\n // Add libraries if they wish to include the libs.\n if (_a.config.template && _a.config.includeLibs) {\n yield _a.addLibrary(libWrapper, _a.config.libs[_a.config.template], _a.config.template);\n }\n if (!_a.config.libraries) {\n _a.config.libraries = _a.config.modules || {};\n }\n // Adding premium if it is provided via the config.\n if (_a.config.premium) {\n _a.config.libraries.premium = _a.config.premium;\n }\n // Allow adding dynamic modules.\n if (_a.config.libraries) {\n for (const name in _a.config.libraries) {\n const lib = _a.config.libraries[name];\n lib.use = lib.use || true;\n yield _a.addLibrary(libWrapper, lib, name);\n }\n }\n yield _a.addStyles(libWrapper, _a.formioScript(_a.config.style || `${_a.cdn.js}/${renderer}.css`, builder));\n if (_a.config.before) {\n yield _a.config.before(_a.FormioClass, element, _a.config);\n }\n _a.FormioClass.license = true;\n _a._formioReady(_a.FormioClass);\n return wrapper;\n });\n }\n // Called after an instance has been created.\n static afterCreate(instance, wrapper, readyEvent) {\n return __awaiter(this, void 0, void 0, function* () {\n const loader = wrapper.querySelector('.formio-loader');\n if (loader) {\n wrapper.removeChild(loader);\n }\n _a.FormioClass.events.emit(readyEvent, instance);\n if (_a.config.after) {\n _a.debug('Calling ready callback');\n _a.config.after(instance, _a.config);\n }\n return instance;\n });\n }\n // Create a new form.\n static createForm(element, form, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (_a.FormioClass) {\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true }));\n }\n const wrapper = yield _a.init(element, options);\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true })).then((instance) => {\n // Set the default submission data.\n if (_a.config.submission) {\n _a.debug('Setting submission', _a.config.submission);\n instance.submission = _a.config.submission;\n }\n // Call the after create method.\n _a.afterCreate(instance, wrapper, 'formEmbedded');\n return instance;\n });\n });\n }\n // Create a form builder.\n static builder(element, form, options = {}) {\n var _b;\n return __awaiter(this, void 0, void 0, function* () {\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.builder) {\n return _a.FormioClass.builder(element, form, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.builder(element, form, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'builderEmbedded');\n return instance;\n });\n });\n }\n}\nexports.Formio = Formio;\n_a = Formio;\nFormio.FormioClass = null;\nFormio.config = {};\nFormio.modules = [];\nFormio.icons = '';\nFormio.license = '';\nFormio.formioReady = new Promise((ready, reject) => {\n _a._formioReady = ready;\n _a._formioReadyReject = reject;\n});\nFormio.version = '5.0.0-rc.94';\n// Create a report.\nFormio.Report = {\n create: (element, submission, options = {}) => __awaiter(void 0, void 0, void 0, function* () {\n var _b;\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.Report) {\n return _a.FormioClass.Report.create(element, submission, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.Report.create(element, submission, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'reportEmbedded');\n return instance;\n });\n })\n};\nCDN_js_1.default.defaultCDN = Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nclass Form {\n constructor(element, form, options) {\n this.form = form;\n this.element = element;\n this.options = options || {};\n this.init();\n this.instance = {\n proxy: true,\n ready: this.ready,\n destroy: () => { }\n };\n }\n init() {\n if (this.instance && !this.instance.proxy) {\n this.instance.destroy();\n }\n this.element.innerHTML = '';\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.form = instance.form;\n return instance;\n });\n }\n create() {\n return Formio.createForm(this.element, this.form, this.options);\n }\n setForm(form) {\n this.form = form;\n if (this.instance) {\n this.instance.setForm(form);\n }\n }\n setDisplay(display) {\n if (this.instance.proxy) {\n return this.ready;\n }\n this.form.display = display;\n this.instance.destroy();\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.setForm(this.form);\n });\n return this.ready;\n }\n}\nexports.Form = Form;\nclass FormBuilder extends Form {\n create() {\n return Formio.builder(this.element, this.form, this.options);\n }\n}\nexports.FormBuilder = FormBuilder;\nFormio.Form = Form;\nFormio.FormBuilder = FormBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Embed.js?");
10900
+ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.FormBuilder = exports.Form = exports.Formio = void 0;\nconst CDN_js_1 = __importDefault(__webpack_require__(/*! ./CDN.js */ \"./lib/cjs/CDN.js\"));\nclass Formio {\n static setLicense(license, norecurse = false) {\n _a.license = license;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setLicense(license);\n }\n }\n static setBaseUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setBaseUrl(url);\n }\n }\n static setApiUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setApiUrl(url);\n }\n }\n static setProjectUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setProjectUrl(url);\n }\n }\n static setAppUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setAppUrl(url);\n }\n }\n static setPathType(type, norecurse = false) {\n _a.pathType = type;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setPathType(type);\n }\n }\n static debug(...args) {\n if (_a.config.debug) {\n console.log(...args);\n }\n }\n static clearCache() {\n if (_a.FormioClass) {\n _a.FormioClass.clearCache();\n }\n }\n static global(prop, flag = '') {\n const globalValue = window[prop];\n if (flag && globalValue && !globalValue[flag]) {\n return null;\n }\n _a.debug(`Getting global ${prop}`, globalValue);\n return globalValue;\n }\n static use(module) {\n if (_a.FormioClass && _a.FormioClass.isRenderer) {\n _a.FormioClass.use(module);\n }\n else {\n _a.modules.push(module);\n }\n }\n static createElement(type, attrs, children) {\n const element = document.createElement(type);\n if (!attrs) {\n return element;\n }\n Object.keys(attrs).forEach(key => {\n element.setAttribute(key, attrs[key]);\n });\n (children || []).forEach(child => {\n element.appendChild(_a.createElement(child.tag, child.attrs, child.children));\n });\n return element;\n }\n static addScript(wrapper, src, name, flag = '') {\n return __awaiter(this, void 0, void 0, function* () {\n if (!src) {\n return Promise.resolve();\n }\n if (typeof src !== 'string' && src.length) {\n return Promise.all(src.map(ref => _a.addScript(wrapper, ref)));\n }\n if (name && _a.global(name, flag)) {\n _a.debug(`${name} already loaded.`);\n return Promise.resolve(_a.global(name));\n }\n _a.debug('Adding Script', src);\n try {\n wrapper.appendChild(_a.createElement('script', {\n src\n }));\n }\n catch (err) {\n _a.debug(err);\n return Promise.resolve();\n }\n if (!name) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n _a.debug(`Waiting to load ${name}`);\n const wait = setInterval(() => {\n if (_a.global(name, flag)) {\n clearInterval(wait);\n _a.debug(`${name} loaded.`);\n resolve(_a.global(name));\n }\n }, 100);\n });\n });\n }\n static addStyles(wrapper, href) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!href) {\n return;\n }\n if (typeof href !== 'string' && href.length) {\n href.forEach(ref => _a.addStyles(wrapper, ref));\n return;\n }\n _a.debug('Adding Styles', href);\n wrapper.appendChild(_a.createElement('link', {\n rel: 'stylesheet',\n href\n }));\n });\n }\n static submitDone(instance, submission) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.debug('Submision Complete', submission);\n if (_a.config.submitDone) {\n _a.config.submitDone(submission, instance);\n }\n const successMessage = (_a.config.success || '').toString();\n if (successMessage && successMessage.toLowerCase() !== 'false' && instance.element) {\n instance.element.innerHTML = `<div class=\"alert-success\" role=\"alert\">${successMessage}</div>`;\n }\n let returnUrl = _a.config.redirect;\n // Allow form based configuration for return url.\n if (!returnUrl &&\n (instance._form &&\n instance._form.settings &&\n (instance._form.settings.returnUrl ||\n instance._form.settings.redirect))) {\n _a.debug('Return url found in form configuration');\n returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;\n }\n if (returnUrl) {\n const formSrc = instance.formio ? instance.formio.formUrl : '';\n const hasQuery = !!returnUrl.match(/\\?/);\n const isOrigin = returnUrl.indexOf(location.origin) === 0;\n returnUrl += hasQuery ? '&' : '?';\n returnUrl += `sub=${submission._id}`;\n if (!isOrigin && formSrc) {\n returnUrl += `&form=${encodeURIComponent(formSrc)}`;\n }\n _a.debug('Return URL', returnUrl);\n window.location.href = returnUrl;\n if (isOrigin) {\n window.location.reload();\n }\n }\n });\n }\n // Return the full script if the builder is being used.\n static formioScript(script, builder) {\n builder = builder || _a.config.includeBuilder;\n if (_a.fullAdded || builder) {\n _a.fullAdded = true;\n return script.replace('formio.form', 'formio.full');\n }\n return script;\n }\n static addLibrary(libWrapper, lib, name) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!lib) {\n return;\n }\n if (lib.dependencies) {\n for (let i = 0; i < lib.dependencies.length; i++) {\n const libName = lib.dependencies[i];\n yield _a.addLibrary(libWrapper, _a.config.libs[libName], libName);\n }\n }\n if (lib.css) {\n yield _a.addStyles((lib.global ? document.body : libWrapper), lib.css);\n }\n if (lib.js) {\n const module = yield _a.addScript((lib.global ? document.body : libWrapper), lib.js, lib.use ? name : false);\n if (lib.use) {\n _a.debug(`Using ${name}`);\n const options = lib.options || {};\n if (!options.license && _a.license) {\n options.license = _a.license;\n }\n _a.use((typeof lib.use === 'function' ? lib.use(module) : module), options);\n }\n }\n if (lib.globalStyle) {\n const style = _a.createElement('style');\n style.type = 'text/css';\n style.innerHTML = lib.globalStyle;\n document.body.appendChild(style);\n }\n });\n }\n static addLoader(wrapper) {\n return __awaiter(this, void 0, void 0, function* () {\n wrapper.appendChild(_a.createElement('div', {\n 'class': 'formio-loader'\n }, [{\n tag: 'div',\n attrs: {\n class: 'loader-wrapper'\n },\n children: [{\n tag: 'div',\n attrs: {\n class: 'loader text-center'\n }\n }]\n }]));\n });\n }\n // eslint-disable-next-line max-statements\n static init(element, options = {}, builder = false) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.cdn = new CDN_js_1.default(_a.config.cdn, _a.config.cdnUrls || {});\n _a.config.libs = _a.config.libs || {\n uswds: {\n dependencies: ['fontawesome'],\n js: `${_a.cdn.uswds}/uswds.min.js`,\n css: `${_a.cdn.uswds}/uswds.min.css`,\n use: true\n },\n fontawesome: {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: `https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css`,\n globalStyle: `@font-face {\n font-family: 'FontAwesome';\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0');\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');\n font-weight: normal;\n font-style: normal;\n }`\n },\n bootstrap4: {\n dependencies: ['fontawesome'],\n css: `${_a.cdn.bootstrap4}/css/bootstrap.min.css`\n },\n bootstrap: {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootstrap}/css/bootstrap.min.css`\n },\n 'bootstrap-icons': {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: 'https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.min.css',\n globalStyle: `@font-face {\n font-display: block;\n font-family: \"bootstrap-icons\";\n src: url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6\") format(\"woff2\"),\n url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6\") format(\"woff\");\n }`\n }\n };\n // Add all bootswatch templates.\n ['cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', 'litera', 'lumen', 'lux', 'materia', 'minty', 'pulse', 'sandstone', 'simplex', 'sketchy', 'slate', 'solar', 'spacelab', 'superhero', 'united', 'yeti'].forEach((template) => {\n _a.config.libs[template] = {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootswatch}/dist/${template}/bootstrap.min.css`\n };\n });\n const id = _a.config.id || `formio-${Math.random().toString(36).substring(7)}`;\n // Create a new wrapper and add the element inside of a new wrapper.\n let wrapper = _a.createElement('div', {\n 'id': `${id}-wrapper`\n });\n element.parentNode.insertBefore(wrapper, element);\n // If we include the libraries, then we will attempt to run this in shadow dom.\n const useShadowDom = _a.config.includeLibs && !_a.config.noshadow && (typeof wrapper.attachShadow === 'function');\n if (useShadowDom) {\n wrapper = wrapper.attachShadow({\n mode: 'open'\n });\n options.shadowRoot = wrapper;\n }\n element.parentNode.removeChild(element);\n wrapper.appendChild(element);\n // If this is inside of shadow dom, then we need to add the styles and scripts to the shadow dom.\n const libWrapper = useShadowDom ? wrapper : document.body;\n // Load the renderer styles.\n yield _a.addStyles(libWrapper, _a.config.embedCSS || `${_a.cdn.js}/formio.embed.css`);\n // Add a loader.\n _a.addLoader(wrapper);\n const formioSrc = _a.config.full ? 'formio.full' : 'formio.form';\n const renderer = _a.config.debug ? formioSrc : `${formioSrc}.min`;\n _a.FormioClass = yield _a.addScript(libWrapper, _a.formioScript(_a.config.script || `${_a.cdn.js}/${renderer}.js`, builder), 'Formio', builder ? 'isBuilder' : 'isRenderer');\n _a.FormioClass.cdn = _a.cdn;\n _a.FormioClass.setBaseUrl(options.baseUrl || _a.baseUrl || _a.config.base);\n _a.FormioClass.setProjectUrl(options.projectUrl || _a.projectUrl || _a.config.project);\n _a.FormioClass.language = _a.language;\n _a.setLicense(_a.license || _a.config.license || false);\n _a.modules.forEach((module) => {\n _a.FormioClass.use(module);\n });\n if (_a.icons) {\n _a.FormioClass.icons = _a.icons;\n }\n if (_a.pathType) {\n _a.FormioClass.setPathType(_a.pathType);\n }\n // Add libraries if they wish to include the libs.\n if (_a.config.template && _a.config.includeLibs) {\n yield _a.addLibrary(libWrapper, _a.config.libs[_a.config.template], _a.config.template);\n }\n if (!_a.config.libraries) {\n _a.config.libraries = _a.config.modules || {};\n }\n // Adding premium if it is provided via the config.\n if (_a.config.premium) {\n _a.config.libraries.premium = _a.config.premium;\n }\n // Allow adding dynamic modules.\n if (_a.config.libraries) {\n for (const name in _a.config.libraries) {\n const lib = _a.config.libraries[name];\n lib.use = lib.use || true;\n yield _a.addLibrary(libWrapper, lib, name);\n }\n }\n yield _a.addStyles(libWrapper, _a.formioScript(_a.config.style || `${_a.cdn.js}/${renderer}.css`, builder));\n if (_a.config.before) {\n yield _a.config.before(_a.FormioClass, element, _a.config);\n }\n _a.FormioClass.license = true;\n _a._formioReady(_a.FormioClass);\n return wrapper;\n });\n }\n // Called after an instance has been created.\n static afterCreate(instance, wrapper, readyEvent) {\n return __awaiter(this, void 0, void 0, function* () {\n const loader = wrapper.querySelector('.formio-loader');\n if (loader) {\n wrapper.removeChild(loader);\n }\n _a.FormioClass.events.emit(readyEvent, instance);\n if (_a.config.after) {\n _a.debug('Calling ready callback');\n _a.config.after(instance, _a.config);\n }\n return instance;\n });\n }\n // Create a new form.\n static createForm(element, form, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (_a.FormioClass) {\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true }));\n }\n const wrapper = yield _a.init(element, options);\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true })).then((instance) => {\n // Set the default submission data.\n if (_a.config.submission) {\n _a.debug('Setting submission', _a.config.submission);\n instance.submission = _a.config.submission;\n }\n // Call the after create method.\n _a.afterCreate(instance, wrapper, 'formEmbedded');\n return instance;\n });\n });\n }\n // Create a form builder.\n static builder(element, form, options = {}) {\n var _b;\n return __awaiter(this, void 0, void 0, function* () {\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.builder) {\n return _a.FormioClass.builder(element, form, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.builder(element, form, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'builderEmbedded');\n return instance;\n });\n });\n }\n}\nexports.Formio = Formio;\n_a = Formio;\nFormio.FormioClass = null;\nFormio.config = {};\nFormio.modules = [];\nFormio.icons = '';\nFormio.license = '';\nFormio.formioReady = new Promise((ready, reject) => {\n _a._formioReady = ready;\n _a._formioReadyReject = reject;\n});\nFormio.version = '5.0.0-rc.95';\n// Create a report.\nFormio.Report = {\n create: (element, submission, options = {}) => __awaiter(void 0, void 0, void 0, function* () {\n var _b;\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.Report) {\n return _a.FormioClass.Report.create(element, submission, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.Report.create(element, submission, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'reportEmbedded');\n return instance;\n });\n })\n};\nCDN_js_1.default.defaultCDN = Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nclass Form {\n constructor(element, form, options) {\n this.form = form;\n this.element = element;\n this.options = options || {};\n this.init();\n this.instance = {\n proxy: true,\n ready: this.ready,\n destroy: () => { }\n };\n }\n init() {\n if (this.instance && !this.instance.proxy) {\n this.instance.destroy();\n }\n this.element.innerHTML = '';\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.form = instance.form;\n return instance;\n });\n }\n create() {\n return Formio.createForm(this.element, this.form, this.options);\n }\n setForm(form) {\n this.form = form;\n if (this.instance) {\n this.instance.setForm(form);\n }\n }\n setDisplay(display) {\n if (this.instance.proxy) {\n return this.ready;\n }\n this.form.display = display;\n this.instance.destroy();\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.setForm(this.form);\n });\n return this.ready;\n }\n}\nexports.Form = Form;\nclass FormBuilder extends Form {\n create() {\n return Formio.builder(this.element, this.form, this.options);\n }\n}\nexports.FormBuilder = FormBuilder;\nFormio.Form = Form;\nFormio.FormBuilder = FormBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Embed.js?");
10890
10901
 
10891
10902
  /***/ }),
10892
10903
 
@@ -10897,7 +10908,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument
10897
10908
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
10898
10909
 
10899
10910
  "use strict";
10900
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst sdk_1 = __webpack_require__(/*! @formio/core/sdk */ \"./node_modules/@formio/core/lib/sdk/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return sdk_1.Formio; } }));\nconst Embed_1 = __webpack_require__(/*! ./Embed */ \"./lib/cjs/Embed.js\");\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\nsdk_1.Formio.cdn = new CDN_1.default();\nsdk_1.Formio.Providers = providers_1.default;\nsdk_1.Formio.version = '5.0.0-rc.94';\nCDN_1.default.defaultCDN = sdk_1.Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nconst isNil = (val) => val === null || val === undefined;\nsdk_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback, multipartOptions) {\n const requestArgs = {\n provider: storage,\n method: 'upload',\n file: file,\n fileName: fileName,\n dir: dir\n };\n fileKey = fileKey || 'file';\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', storage);\n if (Provider) {\n const provider = new Provider(this);\n if (uploadStartCallback) {\n uploadStartCallback();\n }\n return provider.uploadFile(file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, abortCallback, multipartOptions);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.downloadFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.deleteFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// Esnure we proxy the following methods to the FormioEmbed class.\n['setBaseUrl', 'setApiUrl', 'setAppUrl', 'setProjectUrl', 'setPathType', 'setLicense'].forEach((fn) => {\n const baseFn = sdk_1.Formio[fn];\n sdk_1.Formio[fn] = function (arg) {\n const retVal = Embed_1.Formio[fn](arg, true);\n return baseFn ? baseFn.call(this, arg) : retVal;\n };\n});\n// For reverse compatability.\nsdk_1.Formio.Promise = Promise;\nsdk_1.Formio.formioReady = Embed_1.Formio.formioReady;\nsdk_1.Formio.config = Embed_1.Formio.config;\nsdk_1.Formio.builder = Embed_1.Formio.builder;\nsdk_1.Formio.Report = Embed_1.Formio.Report;\nsdk_1.Formio.Form = Embed_1.Formio.Form;\nsdk_1.Formio.FormBuilder = Embed_1.Formio.FormBuilder;\nsdk_1.Formio.use = Embed_1.Formio.use;\nsdk_1.Formio.createForm = Embed_1.Formio.createForm;\nsdk_1.Formio.submitDone = Embed_1.Formio.submitDone;\nsdk_1.Formio.addLibrary = Embed_1.Formio.addLibrary;\nsdk_1.Formio.addLoader = Embed_1.Formio.addLoader;\nsdk_1.Formio.addToGlobal = (global) => {\n if (typeof global === 'object' && !global.Formio) {\n global.Formio = sdk_1.Formio;\n }\n};\nif (typeof __webpack_require__.g !== 'undefined') {\n sdk_1.Formio.addToGlobal(__webpack_require__.g);\n}\nif (typeof window !== 'undefined') {\n sdk_1.Formio.addToGlobal(window);\n}\nEmbed_1.Formio._formioReady(sdk_1.Formio);\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10911
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst sdk_1 = __webpack_require__(/*! @formio/core/sdk */ \"./node_modules/@formio/core/lib/sdk/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return sdk_1.Formio; } }));\nconst Embed_1 = __webpack_require__(/*! ./Embed */ \"./lib/cjs/Embed.js\");\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\nsdk_1.Formio.cdn = new CDN_1.default();\nsdk_1.Formio.Providers = providers_1.default;\nsdk_1.Formio.version = '5.0.0-rc.95';\nCDN_1.default.defaultCDN = sdk_1.Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nconst isNil = (val) => val === null || val === undefined;\nsdk_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback, multipartOptions) {\n const requestArgs = {\n provider: storage,\n method: 'upload',\n file: file,\n fileName: fileName,\n dir: dir\n };\n fileKey = fileKey || 'file';\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', storage);\n if (Provider) {\n const provider = new Provider(this);\n if (uploadStartCallback) {\n uploadStartCallback();\n }\n return provider.uploadFile(file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, abortCallback, multipartOptions);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.downloadFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.deleteFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// Esnure we proxy the following methods to the FormioEmbed class.\n['setBaseUrl', 'setApiUrl', 'setAppUrl', 'setProjectUrl', 'setPathType', 'setLicense'].forEach((fn) => {\n const baseFn = sdk_1.Formio[fn];\n sdk_1.Formio[fn] = function (arg) {\n const retVal = Embed_1.Formio[fn](arg, true);\n return baseFn ? baseFn.call(this, arg) : retVal;\n };\n});\n// For reverse compatability.\nsdk_1.Formio.Promise = Promise;\nsdk_1.Formio.formioReady = Embed_1.Formio.formioReady;\nsdk_1.Formio.config = Embed_1.Formio.config;\nsdk_1.Formio.builder = Embed_1.Formio.builder;\nsdk_1.Formio.Report = Embed_1.Formio.Report;\nsdk_1.Formio.Form = Embed_1.Formio.Form;\nsdk_1.Formio.FormBuilder = Embed_1.Formio.FormBuilder;\nsdk_1.Formio.use = Embed_1.Formio.use;\nsdk_1.Formio.createForm = Embed_1.Formio.createForm;\nsdk_1.Formio.submitDone = Embed_1.Formio.submitDone;\nsdk_1.Formio.addLibrary = Embed_1.Formio.addLibrary;\nsdk_1.Formio.addLoader = Embed_1.Formio.addLoader;\nsdk_1.Formio.addToGlobal = (global) => {\n if (typeof global === 'object' && !global.Formio) {\n global.Formio = sdk_1.Formio;\n }\n};\nif (typeof __webpack_require__.g !== 'undefined') {\n sdk_1.Formio.addToGlobal(__webpack_require__.g);\n}\nif (typeof window !== 'undefined') {\n sdk_1.Formio.addToGlobal(window);\n}\nEmbed_1.Formio._formioReady(sdk_1.Formio);\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10901
10912
 
10902
10913
  /***/ }),
10903
10914