@formio/js 5.0.0-rc.23 → 5.0.0-rc.24

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. package/README.md +24 -30
  2. package/dist/formio.embed.js +1 -1
  3. package/dist/formio.embed.min.js +1 -1
  4. package/dist/formio.embed.min.js.LICENSE.txt +1 -1
  5. package/dist/formio.form.js +7 -18
  6. package/dist/formio.form.min.js +1 -1
  7. package/dist/formio.form.min.js.LICENSE.txt +1 -1
  8. package/dist/formio.full.js +8 -19
  9. package/dist/formio.full.min.js +1 -1
  10. package/dist/formio.full.min.js.LICENSE.txt +1 -1
  11. package/dist/formio.js +1 -1
  12. package/dist/formio.min.js +1 -1
  13. package/dist/formio.min.js.LICENSE.txt +1 -1
  14. package/dist/formio.utils.min.js.LICENSE.txt +1 -1
  15. package/lib/cjs/Embed.d.ts +4 -2
  16. package/lib/cjs/Embed.js +55 -42
  17. package/lib/cjs/WebformBuilder.js +1 -1
  18. package/lib/cjs/components/_classes/list/ListComponent.d.ts +2 -2
  19. package/lib/cjs/components/_classes/list/ListComponent.js +6 -3
  20. package/lib/cjs/components/radio/Radio.js +22 -12
  21. package/lib/cjs/components/select/Select.d.ts +2 -0
  22. package/lib/cjs/components/select/Select.js +6 -1
  23. package/lib/cjs/components/selectboxes/SelectBoxes.js +9 -0
  24. package/lib/cjs/components/selectboxes/fixtures/comp7.d.ts +18 -0
  25. package/lib/cjs/components/selectboxes/fixtures/comp7.js +31 -0
  26. package/lib/cjs/components/selectboxes/fixtures/index.d.ts +2 -1
  27. package/lib/cjs/components/selectboxes/fixtures/index.js +3 -1
  28. package/lib/cjs/components/signature/Signature.d.ts +1 -2
  29. package/lib/cjs/components/signature/Signature.js +1 -2
  30. package/lib/cjs/utils/ChoicesWrapper.d.ts +1 -0
  31. package/lib/cjs/utils/ChoicesWrapper.js +19 -0
  32. package/lib/mjs/Embed.d.ts +4 -2
  33. package/lib/mjs/Embed.js +54 -43
  34. package/lib/mjs/WebformBuilder.js +1 -1
  35. package/lib/mjs/components/_classes/list/ListComponent.d.ts +2 -2
  36. package/lib/mjs/components/_classes/list/ListComponent.js +6 -3
  37. package/lib/mjs/components/radio/Radio.js +22 -12
  38. package/lib/mjs/components/select/Select.d.ts +2 -0
  39. package/lib/mjs/components/select/Select.js +6 -1
  40. package/lib/mjs/components/selectboxes/SelectBoxes.js +10 -1
  41. package/lib/mjs/components/selectboxes/fixtures/comp7.d.ts +18 -0
  42. package/lib/mjs/components/selectboxes/fixtures/comp7.js +29 -0
  43. package/lib/mjs/components/selectboxes/fixtures/index.d.ts +2 -1
  44. package/lib/mjs/components/selectboxes/fixtures/index.js +2 -1
  45. package/lib/mjs/components/signature/Signature.d.ts +1 -2
  46. package/lib/mjs/components/signature/Signature.js +1 -2
  47. package/lib/mjs/utils/ChoicesWrapper.d.ts +1 -0
  48. package/lib/mjs/utils/ChoicesWrapper.js +19 -0
  49. package/package.json +2 -3
@@ -5009,17 +5009,6 @@ eval("/* module decorator */ module = __webpack_require__.nmd(module);\n//! mome
5009
5009
 
5010
5010
  /***/ }),
5011
5011
 
5012
- /***/ "./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js":
5013
- /*!*************************************************************************!*\
5014
- !*** ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js ***!
5015
- \*************************************************************************/
5016
- /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
5017
-
5018
- "use strict";
5019
- eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": function() { return __WEBPACK_DEFAULT_EXPORT__; }\n/* harmony export */ });\n/**\r\n * A collection of shims that provide minimal functionality of the ES6 collections.\r\n *\r\n * These implementations are not meant to be used outside of the ResizeObserver\r\n * modules as they cover only a limited range of use cases.\r\n */\r\n/* eslint-disable require-jsdoc, valid-jsdoc */\r\nvar MapShim = (function () {\r\n if (typeof Map !== 'undefined') {\r\n return Map;\r\n }\r\n /**\r\n * Returns index in provided array that matches the specified key.\r\n *\r\n * @param {Array<Array>} arr\r\n * @param {*} key\r\n * @returns {number}\r\n */\r\n function getIndex(arr, key) {\r\n var result = -1;\r\n arr.some(function (entry, index) {\r\n if (entry[0] === key) {\r\n result = index;\r\n return true;\r\n }\r\n return false;\r\n });\r\n return result;\r\n }\r\n return /** @class */ (function () {\r\n function class_1() {\r\n this.__entries__ = [];\r\n }\r\n Object.defineProperty(class_1.prototype, \"size\", {\r\n /**\r\n * @returns {boolean}\r\n */\r\n get: function () {\r\n return this.__entries__.length;\r\n },\r\n enumerable: true,\r\n configurable: true\r\n });\r\n /**\r\n * @param {*} key\r\n * @returns {*}\r\n */\r\n class_1.prototype.get = function (key) {\r\n var index = getIndex(this.__entries__, key);\r\n var entry = this.__entries__[index];\r\n return entry && entry[1];\r\n };\r\n /**\r\n * @param {*} key\r\n * @param {*} value\r\n * @returns {void}\r\n */\r\n class_1.prototype.set = function (key, value) {\r\n var index = getIndex(this.__entries__, key);\r\n if (~index) {\r\n this.__entries__[index][1] = value;\r\n }\r\n else {\r\n this.__entries__.push([key, value]);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.delete = function (key) {\r\n var entries = this.__entries__;\r\n var index = getIndex(entries, key);\r\n if (~index) {\r\n entries.splice(index, 1);\r\n }\r\n };\r\n /**\r\n * @param {*} key\r\n * @returns {void}\r\n */\r\n class_1.prototype.has = function (key) {\r\n return !!~getIndex(this.__entries__, key);\r\n };\r\n /**\r\n * @returns {void}\r\n */\r\n class_1.prototype.clear = function () {\r\n this.__entries__.splice(0);\r\n };\r\n /**\r\n * @param {Function} callback\r\n * @param {*} [ctx=null]\r\n * @returns {void}\r\n */\r\n class_1.prototype.forEach = function (callback, ctx) {\r\n if (ctx === void 0) { ctx = null; }\r\n for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {\r\n var entry = _a[_i];\r\n callback.call(ctx, entry[1], entry[0]);\r\n }\r\n };\r\n return class_1;\r\n }());\r\n})();\n\n/**\r\n * Detects whether window and document objects are available in current environment.\r\n */\r\nvar isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;\n\n// Returns global object of a current environment.\r\nvar global$1 = (function () {\r\n if (typeof __webpack_require__.g !== 'undefined' && __webpack_require__.g.Math === Math) {\r\n return __webpack_require__.g;\r\n }\r\n if (typeof self !== 'undefined' && self.Math === Math) {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined' && window.Math === Math) {\r\n return window;\r\n }\r\n // eslint-disable-next-line no-new-func\r\n return Function('return this')();\r\n})();\n\n/**\r\n * A shim for the requestAnimationFrame which falls back to the setTimeout if\r\n * first one is not supported.\r\n *\r\n * @returns {number} Requests' identifier.\r\n */\r\nvar requestAnimationFrame$1 = (function () {\r\n if (typeof requestAnimationFrame === 'function') {\r\n // It's required to use a bounded function because IE sometimes throws\r\n // an \"Invalid calling object\" error if rAF is invoked without the global\r\n // object on the left hand side.\r\n return requestAnimationFrame.bind(global$1);\r\n }\r\n return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };\r\n})();\n\n// Defines minimum timeout before adding a trailing call.\r\nvar trailingTimeout = 2;\r\n/**\r\n * Creates a wrapper function which ensures that provided callback will be\r\n * invoked only once during the specified delay period.\r\n *\r\n * @param {Function} callback - Function to be invoked after the delay period.\r\n * @param {number} delay - Delay after which to invoke callback.\r\n * @returns {Function}\r\n */\r\nfunction throttle (callback, delay) {\r\n var leadingCall = false, trailingCall = false, lastCallTime = 0;\r\n /**\r\n * Invokes the original callback function and schedules new invocation if\r\n * the \"proxy\" was called during current request.\r\n *\r\n * @returns {void}\r\n */\r\n function resolvePending() {\r\n if (leadingCall) {\r\n leadingCall = false;\r\n callback();\r\n }\r\n if (trailingCall) {\r\n proxy();\r\n }\r\n }\r\n /**\r\n * Callback invoked after the specified delay. It will further postpone\r\n * invocation of the original function delegating it to the\r\n * requestAnimationFrame.\r\n *\r\n * @returns {void}\r\n */\r\n function timeoutCallback() {\r\n requestAnimationFrame$1(resolvePending);\r\n }\r\n /**\r\n * Schedules invocation of the original function.\r\n *\r\n * @returns {void}\r\n */\r\n function proxy() {\r\n var timeStamp = Date.now();\r\n if (leadingCall) {\r\n // Reject immediately following calls.\r\n if (timeStamp - lastCallTime < trailingTimeout) {\r\n return;\r\n }\r\n // Schedule new call to be in invoked when the pending one is resolved.\r\n // This is important for \"transitions\" which never actually start\r\n // immediately so there is a chance that we might miss one if change\r\n // happens amids the pending invocation.\r\n trailingCall = true;\r\n }\r\n else {\r\n leadingCall = true;\r\n trailingCall = false;\r\n setTimeout(timeoutCallback, delay);\r\n }\r\n lastCallTime = timeStamp;\r\n }\r\n return proxy;\r\n}\n\n// Minimum delay before invoking the update of observers.\r\nvar REFRESH_DELAY = 20;\r\n// A list of substrings of CSS properties used to find transition events that\r\n// might affect dimensions of observed elements.\r\nvar transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];\r\n// Check if MutationObserver is available.\r\nvar mutationObserverSupported = typeof MutationObserver !== 'undefined';\r\n/**\r\n * Singleton controller class which handles updates of ResizeObserver instances.\r\n */\r\nvar ResizeObserverController = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserverController.\r\n *\r\n * @private\r\n */\r\n function ResizeObserverController() {\r\n /**\r\n * Indicates whether DOM listeners have been added.\r\n *\r\n * @private {boolean}\r\n */\r\n this.connected_ = false;\r\n /**\r\n * Tells that controller has subscribed for Mutation Events.\r\n *\r\n * @private {boolean}\r\n */\r\n this.mutationEventsAdded_ = false;\r\n /**\r\n * Keeps reference to the instance of MutationObserver.\r\n *\r\n * @private {MutationObserver}\r\n */\r\n this.mutationsObserver_ = null;\r\n /**\r\n * A list of connected observers.\r\n *\r\n * @private {Array<ResizeObserverSPI>}\r\n */\r\n this.observers_ = [];\r\n this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);\r\n this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);\r\n }\r\n /**\r\n * Adds observer to observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be added.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.addObserver = function (observer) {\r\n if (!~this.observers_.indexOf(observer)) {\r\n this.observers_.push(observer);\r\n }\r\n // Add listeners if they haven't been added yet.\r\n if (!this.connected_) {\r\n this.connect_();\r\n }\r\n };\r\n /**\r\n * Removes observer from observers list.\r\n *\r\n * @param {ResizeObserverSPI} observer - Observer to be removed.\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.removeObserver = function (observer) {\r\n var observers = this.observers_;\r\n var index = observers.indexOf(observer);\r\n // Remove observer if it's present in registry.\r\n if (~index) {\r\n observers.splice(index, 1);\r\n }\r\n // Remove listeners if controller has no connected observers.\r\n if (!observers.length && this.connected_) {\r\n this.disconnect_();\r\n }\r\n };\r\n /**\r\n * Invokes the update of observers. It will continue running updates insofar\r\n * it detects changes.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.refresh = function () {\r\n var changesDetected = this.updateObservers_();\r\n // Continue running updates if changes have been detected as there might\r\n // be future ones caused by CSS transitions.\r\n if (changesDetected) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Updates every observer from observers list and notifies them of queued\r\n * entries.\r\n *\r\n * @private\r\n * @returns {boolean} Returns \"true\" if any observer has detected changes in\r\n * dimensions of it's elements.\r\n */\r\n ResizeObserverController.prototype.updateObservers_ = function () {\r\n // Collect observers that have active observations.\r\n var activeObservers = this.observers_.filter(function (observer) {\r\n return observer.gatherActive(), observer.hasActive();\r\n });\r\n // Deliver notifications in a separate cycle in order to avoid any\r\n // collisions between observers, e.g. when multiple instances of\r\n // ResizeObserver are tracking the same element and the callback of one\r\n // of them changes content dimensions of the observed target. Sometimes\r\n // this may result in notifications being blocked for the rest of observers.\r\n activeObservers.forEach(function (observer) { return observer.broadcastActive(); });\r\n return activeObservers.length > 0;\r\n };\r\n /**\r\n * Initializes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.connect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already added.\r\n if (!isBrowser || this.connected_) {\r\n return;\r\n }\r\n // Subscription to the \"Transitionend\" event is used as a workaround for\r\n // delayed transitions. This way it's possible to capture at least the\r\n // final state of an element.\r\n document.addEventListener('transitionend', this.onTransitionEnd_);\r\n window.addEventListener('resize', this.refresh);\r\n if (mutationObserverSupported) {\r\n this.mutationsObserver_ = new MutationObserver(this.refresh);\r\n this.mutationsObserver_.observe(document, {\r\n attributes: true,\r\n childList: true,\r\n characterData: true,\r\n subtree: true\r\n });\r\n }\r\n else {\r\n document.addEventListener('DOMSubtreeModified', this.refresh);\r\n this.mutationEventsAdded_ = true;\r\n }\r\n this.connected_ = true;\r\n };\r\n /**\r\n * Removes DOM listeners.\r\n *\r\n * @private\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.disconnect_ = function () {\r\n // Do nothing if running in a non-browser environment or if listeners\r\n // have been already removed.\r\n if (!isBrowser || !this.connected_) {\r\n return;\r\n }\r\n document.removeEventListener('transitionend', this.onTransitionEnd_);\r\n window.removeEventListener('resize', this.refresh);\r\n if (this.mutationsObserver_) {\r\n this.mutationsObserver_.disconnect();\r\n }\r\n if (this.mutationEventsAdded_) {\r\n document.removeEventListener('DOMSubtreeModified', this.refresh);\r\n }\r\n this.mutationsObserver_ = null;\r\n this.mutationEventsAdded_ = false;\r\n this.connected_ = false;\r\n };\r\n /**\r\n * \"Transitionend\" event handler.\r\n *\r\n * @private\r\n * @param {TransitionEvent} event\r\n * @returns {void}\r\n */\r\n ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {\r\n var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;\r\n // Detect whether transition may affect dimensions of an element.\r\n var isReflowProperty = transitionKeys.some(function (key) {\r\n return !!~propertyName.indexOf(key);\r\n });\r\n if (isReflowProperty) {\r\n this.refresh();\r\n }\r\n };\r\n /**\r\n * Returns instance of the ResizeObserverController.\r\n *\r\n * @returns {ResizeObserverController}\r\n */\r\n ResizeObserverController.getInstance = function () {\r\n if (!this.instance_) {\r\n this.instance_ = new ResizeObserverController();\r\n }\r\n return this.instance_;\r\n };\r\n /**\r\n * Holds reference to the controller's instance.\r\n *\r\n * @private {ResizeObserverController}\r\n */\r\n ResizeObserverController.instance_ = null;\r\n return ResizeObserverController;\r\n}());\n\n/**\r\n * Defines non-writable/enumerable properties of the provided target object.\r\n *\r\n * @param {Object} target - Object for which to define properties.\r\n * @param {Object} props - Properties to be defined.\r\n * @returns {Object} Target object.\r\n */\r\nvar defineConfigurable = (function (target, props) {\r\n for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {\r\n var key = _a[_i];\r\n Object.defineProperty(target, key, {\r\n value: props[key],\r\n enumerable: false,\r\n writable: false,\r\n configurable: true\r\n });\r\n }\r\n return target;\r\n});\n\n/**\r\n * Returns the global object associated with provided element.\r\n *\r\n * @param {Object} target\r\n * @returns {Object}\r\n */\r\nvar getWindowOf = (function (target) {\r\n // Assume that the element is an instance of Node, which means that it\r\n // has the \"ownerDocument\" property from which we can retrieve a\r\n // corresponding global object.\r\n var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;\r\n // Return the local global object if it's not possible extract one from\r\n // provided element.\r\n return ownerGlobal || global$1;\r\n});\n\n// Placeholder of an empty content rectangle.\r\nvar emptyRect = createRectInit(0, 0, 0, 0);\r\n/**\r\n * Converts provided string to a number.\r\n *\r\n * @param {number|string} value\r\n * @returns {number}\r\n */\r\nfunction toFloat(value) {\r\n return parseFloat(value) || 0;\r\n}\r\n/**\r\n * Extracts borders size from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @param {...string} positions - Borders positions (top, right, ...)\r\n * @returns {number}\r\n */\r\nfunction getBordersSize(styles) {\r\n var positions = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n positions[_i - 1] = arguments[_i];\r\n }\r\n return positions.reduce(function (size, position) {\r\n var value = styles['border-' + position + '-width'];\r\n return size + toFloat(value);\r\n }, 0);\r\n}\r\n/**\r\n * Extracts paddings sizes from provided styles.\r\n *\r\n * @param {CSSStyleDeclaration} styles\r\n * @returns {Object} Paddings box.\r\n */\r\nfunction getPaddings(styles) {\r\n var positions = ['top', 'right', 'bottom', 'left'];\r\n var paddings = {};\r\n for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {\r\n var position = positions_1[_i];\r\n var value = styles['padding-' + position];\r\n paddings[position] = toFloat(value);\r\n }\r\n return paddings;\r\n}\r\n/**\r\n * Calculates content rectangle of provided SVG element.\r\n *\r\n * @param {SVGGraphicsElement} target - Element content rectangle of which needs\r\n * to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getSVGContentRect(target) {\r\n var bbox = target.getBBox();\r\n return createRectInit(0, 0, bbox.width, bbox.height);\r\n}\r\n/**\r\n * Calculates content rectangle of provided HTMLElement.\r\n *\r\n * @param {HTMLElement} target - Element for which to calculate the content rectangle.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getHTMLElementContentRect(target) {\r\n // Client width & height properties can't be\r\n // used exclusively as they provide rounded values.\r\n var clientWidth = target.clientWidth, clientHeight = target.clientHeight;\r\n // By this condition we can catch all non-replaced inline, hidden and\r\n // detached elements. Though elements with width & height properties less\r\n // than 0.5 will be discarded as well.\r\n //\r\n // Without it we would need to implement separate methods for each of\r\n // those cases and it's not possible to perform a precise and performance\r\n // effective test for hidden elements. E.g. even jQuery's ':visible' filter\r\n // gives wrong results for elements with width & height less than 0.5.\r\n if (!clientWidth && !clientHeight) {\r\n return emptyRect;\r\n }\r\n var styles = getWindowOf(target).getComputedStyle(target);\r\n var paddings = getPaddings(styles);\r\n var horizPad = paddings.left + paddings.right;\r\n var vertPad = paddings.top + paddings.bottom;\r\n // Computed styles of width & height are being used because they are the\r\n // only dimensions available to JS that contain non-rounded values. It could\r\n // be possible to utilize the getBoundingClientRect if only it's data wasn't\r\n // affected by CSS transformations let alone paddings, borders and scroll bars.\r\n var width = toFloat(styles.width), height = toFloat(styles.height);\r\n // Width & height include paddings and borders when the 'border-box' box\r\n // model is applied (except for IE).\r\n if (styles.boxSizing === 'border-box') {\r\n // Following conditions are required to handle Internet Explorer which\r\n // doesn't include paddings and borders to computed CSS dimensions.\r\n //\r\n // We can say that if CSS dimensions + paddings are equal to the \"client\"\r\n // properties then it's either IE, and thus we don't need to subtract\r\n // anything, or an element merely doesn't have paddings/borders styles.\r\n if (Math.round(width + horizPad) !== clientWidth) {\r\n width -= getBordersSize(styles, 'left', 'right') + horizPad;\r\n }\r\n if (Math.round(height + vertPad) !== clientHeight) {\r\n height -= getBordersSize(styles, 'top', 'bottom') + vertPad;\r\n }\r\n }\r\n // Following steps can't be applied to the document's root element as its\r\n // client[Width/Height] properties represent viewport area of the window.\r\n // Besides, it's as well not necessary as the <html> itself neither has\r\n // rendered scroll bars nor it can be clipped.\r\n if (!isDocumentElement(target)) {\r\n // In some browsers (only in Firefox, actually) CSS width & height\r\n // include scroll bars size which can be removed at this step as scroll\r\n // bars are the only difference between rounded dimensions + paddings\r\n // and \"client\" properties, though that is not always true in Chrome.\r\n var vertScrollbar = Math.round(width + horizPad) - clientWidth;\r\n var horizScrollbar = Math.round(height + vertPad) - clientHeight;\r\n // Chrome has a rather weird rounding of \"client\" properties.\r\n // E.g. for an element with content width of 314.2px it sometimes gives\r\n // the client width of 315px and for the width of 314.7px it may give\r\n // 314px. And it doesn't happen all the time. So just ignore this delta\r\n // as a non-relevant.\r\n if (Math.abs(vertScrollbar) !== 1) {\r\n width -= vertScrollbar;\r\n }\r\n if (Math.abs(horizScrollbar) !== 1) {\r\n height -= horizScrollbar;\r\n }\r\n }\r\n return createRectInit(paddings.left, paddings.top, width, height);\r\n}\r\n/**\r\n * Checks whether provided element is an instance of the SVGGraphicsElement.\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nvar isSVGGraphicsElement = (function () {\r\n // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement\r\n // interface.\r\n if (typeof SVGGraphicsElement !== 'undefined') {\r\n return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };\r\n }\r\n // If it's so, then check that element is at least an instance of the\r\n // SVGElement and that it has the \"getBBox\" method.\r\n // eslint-disable-next-line no-extra-parens\r\n return function (target) { return (target instanceof getWindowOf(target).SVGElement &&\r\n typeof target.getBBox === 'function'); };\r\n})();\r\n/**\r\n * Checks whether provided element is a document element (<html>).\r\n *\r\n * @param {Element} target - Element to be checked.\r\n * @returns {boolean}\r\n */\r\nfunction isDocumentElement(target) {\r\n return target === getWindowOf(target).document.documentElement;\r\n}\r\n/**\r\n * Calculates an appropriate content rectangle for provided html or svg element.\r\n *\r\n * @param {Element} target - Element content rectangle of which needs to be calculated.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction getContentRect(target) {\r\n if (!isBrowser) {\r\n return emptyRect;\r\n }\r\n if (isSVGGraphicsElement(target)) {\r\n return getSVGContentRect(target);\r\n }\r\n return getHTMLElementContentRect(target);\r\n}\r\n/**\r\n * Creates rectangle with an interface of the DOMRectReadOnly.\r\n * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly\r\n *\r\n * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.\r\n * @returns {DOMRectReadOnly}\r\n */\r\nfunction createReadOnlyRect(_a) {\r\n var x = _a.x, y = _a.y, width = _a.width, height = _a.height;\r\n // If DOMRectReadOnly is available use it as a prototype for the rectangle.\r\n var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;\r\n var rect = Object.create(Constr.prototype);\r\n // Rectangle's properties are not writable and non-enumerable.\r\n defineConfigurable(rect, {\r\n x: x, y: y, width: width, height: height,\r\n top: y,\r\n right: x + width,\r\n bottom: height + y,\r\n left: x\r\n });\r\n return rect;\r\n}\r\n/**\r\n * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.\r\n * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit\r\n *\r\n * @param {number} x - X coordinate.\r\n * @param {number} y - Y coordinate.\r\n * @param {number} width - Rectangle's width.\r\n * @param {number} height - Rectangle's height.\r\n * @returns {DOMRectInit}\r\n */\r\nfunction createRectInit(x, y, width, height) {\r\n return { x: x, y: y, width: width, height: height };\r\n}\n\n/**\r\n * Class that is responsible for computations of the content rectangle of\r\n * provided DOM element and for keeping track of it's changes.\r\n */\r\nvar ResizeObservation = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObservation.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n */\r\n function ResizeObservation(target) {\r\n /**\r\n * Broadcasted width of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastWidth = 0;\r\n /**\r\n * Broadcasted height of content rectangle.\r\n *\r\n * @type {number}\r\n */\r\n this.broadcastHeight = 0;\r\n /**\r\n * Reference to the last observed content rectangle.\r\n *\r\n * @private {DOMRectInit}\r\n */\r\n this.contentRect_ = createRectInit(0, 0, 0, 0);\r\n this.target = target;\r\n }\r\n /**\r\n * Updates content rectangle and tells whether it's width or height properties\r\n * have changed since the last broadcast.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObservation.prototype.isActive = function () {\r\n var rect = getContentRect(this.target);\r\n this.contentRect_ = rect;\r\n return (rect.width !== this.broadcastWidth ||\r\n rect.height !== this.broadcastHeight);\r\n };\r\n /**\r\n * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data\r\n * from the corresponding properties of the last observed content rectangle.\r\n *\r\n * @returns {DOMRectInit} Last observed content rectangle.\r\n */\r\n ResizeObservation.prototype.broadcastRect = function () {\r\n var rect = this.contentRect_;\r\n this.broadcastWidth = rect.width;\r\n this.broadcastHeight = rect.height;\r\n return rect;\r\n };\r\n return ResizeObservation;\r\n}());\n\nvar ResizeObserverEntry = /** @class */ (function () {\r\n /**\r\n * Creates an instance of ResizeObserverEntry.\r\n *\r\n * @param {Element} target - Element that is being observed.\r\n * @param {DOMRectInit} rectInit - Data of the element's content rectangle.\r\n */\r\n function ResizeObserverEntry(target, rectInit) {\r\n var contentRect = createReadOnlyRect(rectInit);\r\n // According to the specification following properties are not writable\r\n // and are also not enumerable in the native implementation.\r\n //\r\n // Property accessors are not being used as they'd require to define a\r\n // private WeakMap storage which may cause memory leaks in browsers that\r\n // don't support this type of collections.\r\n defineConfigurable(this, { target: target, contentRect: contentRect });\r\n }\r\n return ResizeObserverEntry;\r\n}());\n\nvar ResizeObserverSPI = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback function that is invoked\r\n * when one of the observed elements changes it's content dimensions.\r\n * @param {ResizeObserverController} controller - Controller instance which\r\n * is responsible for the updates of observer.\r\n * @param {ResizeObserver} callbackCtx - Reference to the public\r\n * ResizeObserver instance which will be passed to callback function.\r\n */\r\n function ResizeObserverSPI(callback, controller, callbackCtx) {\r\n /**\r\n * Collection of resize observations that have detected changes in dimensions\r\n * of elements.\r\n *\r\n * @private {Array<ResizeObservation>}\r\n */\r\n this.activeObservations_ = [];\r\n /**\r\n * Registry of the ResizeObservation instances.\r\n *\r\n * @private {Map<Element, ResizeObservation>}\r\n */\r\n this.observations_ = new MapShim();\r\n if (typeof callback !== 'function') {\r\n throw new TypeError('The callback provided as parameter 1 is not a function.');\r\n }\r\n this.callback_ = callback;\r\n this.controller_ = controller;\r\n this.callbackCtx_ = callbackCtx;\r\n }\r\n /**\r\n * Starts observing provided element.\r\n *\r\n * @param {Element} target - Element to be observed.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.observe = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is already being observed.\r\n if (observations.has(target)) {\r\n return;\r\n }\r\n observations.set(target, new ResizeObservation(target));\r\n this.controller_.addObserver(this);\r\n // Force the update of observations.\r\n this.controller_.refresh();\r\n };\r\n /**\r\n * Stops observing provided element.\r\n *\r\n * @param {Element} target - Element to stop observing.\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.unobserve = function (target) {\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n // Do nothing if current environment doesn't have the Element interface.\r\n if (typeof Element === 'undefined' || !(Element instanceof Object)) {\r\n return;\r\n }\r\n if (!(target instanceof getWindowOf(target).Element)) {\r\n throw new TypeError('parameter 1 is not of type \"Element\".');\r\n }\r\n var observations = this.observations_;\r\n // Do nothing if element is not being observed.\r\n if (!observations.has(target)) {\r\n return;\r\n }\r\n observations.delete(target);\r\n if (!observations.size) {\r\n this.controller_.removeObserver(this);\r\n }\r\n };\r\n /**\r\n * Stops observing all elements.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.disconnect = function () {\r\n this.clearActive();\r\n this.observations_.clear();\r\n this.controller_.removeObserver(this);\r\n };\r\n /**\r\n * Collects observation instances the associated element of which has changed\r\n * it's content rectangle.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.gatherActive = function () {\r\n var _this = this;\r\n this.clearActive();\r\n this.observations_.forEach(function (observation) {\r\n if (observation.isActive()) {\r\n _this.activeObservations_.push(observation);\r\n }\r\n });\r\n };\r\n /**\r\n * Invokes initial callback function with a list of ResizeObserverEntry\r\n * instances collected from active resize observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.broadcastActive = function () {\r\n // Do nothing if observer doesn't have active observations.\r\n if (!this.hasActive()) {\r\n return;\r\n }\r\n var ctx = this.callbackCtx_;\r\n // Create ResizeObserverEntry instance for every active observation.\r\n var entries = this.activeObservations_.map(function (observation) {\r\n return new ResizeObserverEntry(observation.target, observation.broadcastRect());\r\n });\r\n this.callback_.call(ctx, entries, ctx);\r\n this.clearActive();\r\n };\r\n /**\r\n * Clears the collection of active observations.\r\n *\r\n * @returns {void}\r\n */\r\n ResizeObserverSPI.prototype.clearActive = function () {\r\n this.activeObservations_.splice(0);\r\n };\r\n /**\r\n * Tells whether observer has active observations.\r\n *\r\n * @returns {boolean}\r\n */\r\n ResizeObserverSPI.prototype.hasActive = function () {\r\n return this.activeObservations_.length > 0;\r\n };\r\n return ResizeObserverSPI;\r\n}());\n\n// Registry of internal observers. If WeakMap is not available use current shim\r\n// for the Map collection as it has all required methods and because WeakMap\r\n// can't be fully polyfilled anyway.\r\nvar observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();\r\n/**\r\n * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation\r\n * exposing only those methods and properties that are defined in the spec.\r\n */\r\nvar ResizeObserver = /** @class */ (function () {\r\n /**\r\n * Creates a new instance of ResizeObserver.\r\n *\r\n * @param {ResizeObserverCallback} callback - Callback that is invoked when\r\n * dimensions of the observed elements change.\r\n */\r\n function ResizeObserver(callback) {\r\n if (!(this instanceof ResizeObserver)) {\r\n throw new TypeError('Cannot call a class as a function.');\r\n }\r\n if (!arguments.length) {\r\n throw new TypeError('1 argument required, but only 0 present.');\r\n }\r\n var controller = ResizeObserverController.getInstance();\r\n var observer = new ResizeObserverSPI(callback, controller, this);\r\n observers.set(this, observer);\r\n }\r\n return ResizeObserver;\r\n}());\r\n// Expose public methods of ResizeObserver.\r\n[\r\n 'observe',\r\n 'unobserve',\r\n 'disconnect'\r\n].forEach(function (method) {\r\n ResizeObserver.prototype[method] = function () {\r\n var _a;\r\n return (_a = observers.get(this))[method].apply(_a, arguments);\r\n };\r\n});\n\nvar index = (function () {\r\n // Export existing implementation if available.\r\n if (typeof global$1.ResizeObserver !== 'undefined') {\r\n return global$1.ResizeObserver;\r\n }\r\n return ResizeObserver;\r\n})();\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (index);\n\n\n//# sourceURL=webpack://Formio/./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js?");
5020
-
5021
- /***/ }),
5022
-
5023
5012
  /***/ "./node_modules/signature_pad/dist/signature_pad.js":
5024
5013
  /*!**********************************************************!*\
5025
5014
  !*** ./node_modules/signature_pad/dist/signature_pad.js ***!
@@ -5346,7 +5335,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
5346
5335
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5347
5336
 
5348
5337
  "use strict";
5349
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Webform_1 = __importDefault(__webpack_require__(/*! ./Webform */ \"./lib/cjs/Webform.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ./components/_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst tippy_js_1 = __importDefault(__webpack_require__(/*! tippy.js */ \"./node_modules/tippy.js/dist/tippy.esm.js\"));\nconst Components_1 = __importDefault(__webpack_require__(/*! ./components/Components */ \"./lib/cjs/components/Components.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst formUtils_1 = __webpack_require__(/*! ./utils/formUtils */ \"./lib/cjs/utils/formUtils.js\");\nconst builder_1 = __importDefault(__webpack_require__(/*! ./utils/builder */ \"./lib/cjs/utils/builder.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst dom_autoscroller_1 = __importDefault(__webpack_require__(/*! dom-autoscroller */ \"./node_modules/dom-autoscroller/dist/bundle.js\"));\nconst Templates_1 = __importDefault(__webpack_require__(/*! ./templates/Templates */ \"./lib/cjs/templates/Templates.js\"));\n__webpack_require__(/*! ./components/builder */ \"./lib/cjs/components/builder.js\");\n// We need this here because dragula pulls in CustomEvent class that requires global to exist.\nif (typeof window !== 'undefined' && typeof window.global === 'undefined') {\n window.global = window;\n}\nconst dragula_min_js_1 = __importDefault(__webpack_require__(/*! dragula/dist/dragula.min.js */ \"./node_modules/dragula/dist/dragula.min.js\"));\nclass WebformBuilder extends Component_1.default {\n // eslint-disable-next-line max-statements\n constructor() {\n let element, options;\n if (arguments[0] instanceof HTMLElement || arguments[1]) {\n element = arguments[0];\n options = arguments[1];\n }\n else {\n options = arguments[0];\n }\n // Reset skipInit in case PDFBuilder has set it.\n options.skipInit = false;\n options.display = options.display || 'form';\n super(null, options);\n this.moveHandler = (e) => {\n if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 13) {\n e.stopPropagation();\n e.preventDefault();\n }\n if (e.keyCode === 38) {\n this.updateComponentPlacement(true);\n }\n if (e.keyCode === 40) {\n this.updateComponentPlacement(false);\n }\n if (e.keyCode === 13) {\n this.stopMoving(this.selectedComponent);\n }\n };\n this.setElement(element);\n this.dragulaLib = dragula_min_js_1.default;\n this.builderHeight = 0;\n this.schemas = {};\n this.repeatablePaths = [];\n this.sideBarScroll = lodash_1.default.get(this.options, 'sideBarScroll', true);\n this.sideBarScrollOffset = lodash_1.default.get(this.options, 'sideBarScrollOffset', 0);\n this.dragDropEnabled = true;\n // Setup the builder options.\n this.builder = lodash_1.default.defaultsDeep({}, this.options.builder, this.defaultGroups);\n // Turn off if explicitely said to do so...\n lodash_1.default.each(this.defaultGroups, (config, key) => {\n if (config === false) {\n this.builder[key] = false;\n }\n });\n // Add the groups.////\n this.groups = {};\n this.groupOrder = [];\n for (const group in this.builder) {\n if (this.builder[group]) {\n this.builder[group].key = group;\n this.groups[group] = this.builder[group];\n this.groups[group].components = this.groups[group].components || {};\n this.groups[group].componentOrder = this.groups[group].componentOrder || [];\n this.groups[group].subgroups = Object.keys(this.groups[group].groups || {}).map((groupKey) => {\n this.groups[group].groups[groupKey].componentOrder = Object.keys(this.groups[group].groups[groupKey].components).map((key) => key);\n return this.groups[group].groups[groupKey];\n });\n this.groupOrder.push(this.groups[group]);\n }\n }\n this.groupOrder = this.groupOrder\n .filter(group => group && !group.ignore)\n .sort((a, b) => a.weight - b.weight)\n .map(group => group.key);\n for (const type in Components_1.default.components) {\n const component = Components_1.default.components[type];\n if (component.builderInfo && component.builderInfo.schema) {\n this.schemas[type] = component.builderInfo.schema;\n component.type = type;\n const builderInfo = component.builderInfo;\n builderInfo.key = component.type;\n this.addBuilderComponentInfo(builderInfo);\n }\n }\n // Filter out any extra components.\n // Add the components in each group.\n for (const group in this.groups) {\n const info = this.groups[group];\n for (const key in info.components) {\n const compKey = group === 'resource' ? `component-${key}` : key;\n let comp = info.components[compKey];\n if (comp === true &&\n Components_1.default.components[key] &&\n Components_1.default.components[key].builderInfo) {\n comp = Components_1.default.components[key].builderInfo;\n }\n if (comp && comp.schema) {\n this.schemas[key] = comp.schema;\n info.components[compKey] = comp;\n info.components[compKey].key = key;\n }\n else {\n // Do not include this component in the components array.\n delete info.components[compKey];\n }\n }\n // Order the components.\n this.orderComponents(info);\n }\n this.options.hooks = this.options.hooks || {};\n this.options.hooks.renderComponent = (html, { component, self }) => {\n var _a;\n if (self.type === 'form' && !self.key) {\n const template = this.hook('renderComponentFormTemplate', html.replace('formio-component-form', ''));\n // The main webform shouldn't have this class as it adds extra styles.\n return template;\n }\n if (this.options.disabled && this.options.disabled.includes(self.key) || self.parent.noDragDrop) {\n return html;\n }\n return this.renderTemplate('builderComponent', {\n html,\n disableBuilderActions: (_a = self === null || self === void 0 ? void 0 : self.component) === null || _a === void 0 ? void 0 : _a.disableBuilderActions,\n childComponent: component,\n });\n };\n this.options.hooks.renderComponents = (html, { components, self }) => {\n // if Datagrid and already has a component, don't make it droppable.\n if (self.type === 'datagrid' && components.length > 0 || self.noDragDrop) {\n return html;\n }\n if (!components ||\n (!components.length && !components.nodrop) ||\n (self.type === 'form' && components.length <= 1 && (components.length === 0 || components[0].type === 'button'))) {\n html = this.renderTemplate('builderPlaceholder', {\n position: 0\n }) + html;\n }\n return this.renderTemplate('builderComponents', {\n key: self.key,\n type: self.type,\n html,\n });\n };\n this.options.hooks.renderInput = (html, { self }) => {\n if (self.type === 'hidden') {\n return html + self.name;\n }\n return html;\n };\n this.options.hooks.renderLoading = (html, { self }) => {\n if (self.type === 'form' && self.key) {\n return self.name;\n }\n return html;\n };\n this.options.hooks.attachComponents = (element, components, container, component) => {\n // Don't attach if no element was found or component doesn't participate in drag'n'drop.\n if (!element) {\n return;\n }\n if (component.noDragDrop) {\n return element;\n }\n // Attach container and component to element for later reference.\n const containerElement = element.querySelector(`[ref=\"${component.component.key}-container\"]`) || element;\n containerElement.formioContainer = container;\n containerElement.formioComponent = component;\n // Add container to draggable list.\n if (this.dragula && this.allowDrop(element)) {\n this.dragula.containers.push(containerElement);\n }\n // If this is an existing datagrid element, don't make it draggable.\n if ((component.type === 'datagrid' || component.type === 'datamap') && components.length > 0) {\n return element;\n }\n // Since we added a wrapper, need to return the original element so that we can find the components inside it.\n return element.children[0];\n };\n this.options.hooks.attachDatagrid = (element, component) => {\n component.loadRefs(element, {\n [`${component.key}-container`]: 'single',\n });\n const dataGridContainer = component.refs[`${component.key}-container`];\n if (dataGridContainer) {\n component.attachComponents(dataGridContainer.parentNode, [], component.component.components);\n }\n // Need to set up horizontal rearrangement of fields.\n };\n this.options.hooks.attachComponent = this.attachComponent.bind(this);\n // Load resources tagged as 'builder'\n const query = {\n params: {\n type: 'resource',\n limit: 1000000,\n select: '_id,title,name,components'\n }\n };\n if (this.options && this.options.resourceTag) {\n query.params.tags = [this.options.resourceTag];\n }\n else if (!this.options || !this.options.hasOwnProperty('resourceTag')) {\n query.params.tags = ['builder'];\n }\n const formio = new Formio_1.Formio(Formio_1.Formio.projectUrl);\n const isResourcesDisabled = this.options.builder && this.options.builder.resource === false;\n formio.loadProject().then((project) => {\n if (project && (lodash_1.default.get(project, 'settings.addConfigToForms', false) || lodash_1.default.get(project, 'addConfigToForms', false))) {\n const config = project.config || {};\n this.options.formConfig = config;\n const pathToFormConfig = 'webform._form.config';\n const webformConfig = lodash_1.default.get(this, pathToFormConfig);\n if (this.webform && !webformConfig) {\n lodash_1.default.set(this, pathToFormConfig, config);\n }\n }\n }).catch((err) => {\n console.warn(`Could not load project settings: ${err.message || err}`);\n });\n if (!formio.noProject && !isResourcesDisabled && formio.formsUrl) {\n const resourceOptions = this.options.builder && this.options.builder.resource;\n formio.loadForms(query)\n .then((resources) => {\n if (resources.length) {\n this.builder.resource = {\n title: resourceOptions ? resourceOptions.title : 'Existing Resource Fields',\n key: 'resource',\n weight: resourceOptions ? resourceOptions.weight : 50,\n subgroups: [],\n components: [],\n componentOrder: []\n };\n this.groups.resource = {\n title: resourceOptions ? resourceOptions.title : 'Existing Resource Fields',\n key: 'resource',\n weight: resourceOptions ? resourceOptions.weight : 50,\n subgroups: [],\n components: [],\n componentOrder: []\n };\n if (!this.groupOrder.includes('resource')) {\n this.groupOrder.push('resource');\n }\n this.addExistingResourceFields(resources);\n }\n });\n }\n // Notify components if they need to modify their render.\n this.options.attachMode = 'builder';\n this.webform = this.webform || this.createForm(this.options);\n this.pathComponentsMapping = {};\n this.arrayDataComponentPaths = [];\n this.nestedDataComponents = [];\n this.arrayDataComponents = [];\n }\n allowDrop() {\n return true;\n }\n addExistingResourceFields(resources) {\n lodash_1.default.each(resources, (resource, index) => {\n const resourceKey = `resource-${resource.name}`;\n const subgroup = {\n key: resourceKey,\n title: resource.title,\n components: [],\n componentOrder: [],\n default: index === 0,\n };\n (0, formUtils_1.eachComponent)(resource.components, (component) => {\n if (component.type === 'button')\n return;\n if (this.options &&\n this.options.resourceFilter &&\n (!component.tags || component.tags.indexOf(this.options.resourceFilter) === -1))\n return;\n let componentName = component.label;\n if (!componentName && component.key) {\n componentName = lodash_1.default.upperFirst(component.key);\n }\n subgroup.componentOrder.push(`component-${component.key}`);\n subgroup.components[`component-${component.key}`] = lodash_1.default.merge((0, utils_1.fastCloneDeep)(Components_1.default.components[component.type]\n ? Components_1.default.components[component.type].builderInfo\n : Components_1.default.components['unknown'].builderInfo), {\n key: component.key,\n title: componentName,\n group: 'resource',\n subgroup: resourceKey,\n }, {\n schema: Object.assign(Object.assign({}, component), { label: component.label, key: component.key, lockKey: true, source: (!this.options.noSource ? resource._id : undefined), isNew: true })\n });\n }, true);\n this.groups.resource.subgroups.push(subgroup);\n });\n this.triggerRedraw();\n }\n attachTooltip(component, title) {\n return (0, tippy_js_1.default)(component, {\n allowHTML: true,\n trigger: 'mouseenter focus',\n placement: 'top',\n delay: [200, 0],\n zIndex: 10000,\n content: title\n });\n }\n attachComponent(element, component) {\n if (component instanceof WebformBuilder) {\n return;\n }\n // Add component to element for later reference.\n element.formioComponent = component;\n component.loadRefs(element, {\n removeComponent: 'single',\n editComponent: 'single',\n moveComponent: 'single',\n copyComponent: 'single',\n pasteComponent: 'single',\n editJson: 'single'\n });\n if (component.refs.copyComponent) {\n this.attachTooltip(component.refs.copyComponent, this.t('Copy'));\n component.addEventListener(component.refs.copyComponent, 'click', () => this.copyComponent(component));\n }\n if (component.refs.pasteComponent) {\n const pasteToolTip = this.attachTooltip(component.refs.pasteComponent, this.t('Paste below'));\n component.addEventListener(component.refs.pasteComponent, 'click', () => {\n pasteToolTip.hide();\n this.pasteComponent(component);\n });\n }\n if (component.refs.moveComponent) {\n this.attachTooltip(component.refs.moveComponent, this.t('Move'));\n if (this.keyboardActionsEnabled) {\n component.addEventListener(component.refs.moveComponent, 'click', () => {\n this.moveComponent(component);\n });\n }\n }\n const parent = this.getParentElement(element);\n if (component.refs.editComponent) {\n this.attachTooltip(component.refs.editComponent, this.t('Edit'));\n component.addEventListener(component.refs.editComponent, 'click', () => this.editComponent(component.schema, parent, false, false, component.component, { inDataGrid: component.isInDataGrid }));\n }\n if (component.refs.editJson) {\n this.attachTooltip(component.refs.editJson, this.t('Edit JSON'));\n component.addEventListener(component.refs.editJson, 'click', () => this.editComponent(component.schema, parent, false, true, component.component));\n }\n if (component.refs.removeComponent) {\n this.attachTooltip(component.refs.removeComponent, this.t('Remove'));\n component.addEventListener(component.refs.removeComponent, 'click', () => this.removeComponent(component.schema, parent, component.component));\n }\n return element;\n }\n createForm(options) {\n this.webform = new Webform_1.default(this.element, options);\n if (this.element) {\n this.loadRefs(this.element, {\n form: 'single'\n });\n if (this.refs.form) {\n this.webform.element = this.refs.form;\n }\n }\n return this.webform;\n }\n /**\n * Called when everything is ready.\n *\n * @returns {Promise} - Wait for webform to be ready.\n */\n get ready() {\n return this.webform.ready;\n }\n get defaultGroups() {\n return {\n basic: {\n title: 'Basic',\n weight: 0,\n default: true,\n },\n advanced: {\n title: 'Advanced',\n weight: 10\n },\n layout: {\n title: 'Layout',\n weight: 20\n },\n data: {\n title: 'Data',\n weight: 30\n },\n premium: {\n title: 'Premium',\n weight: 40\n }\n };\n }\n redraw() {\n return Webform_1.default.prototype.redraw.call(this);\n }\n get form() {\n return this.webform.form;\n }\n get schema() {\n return this.webform.schema;\n }\n set form(value) {\n this.setForm(value);\n }\n get container() {\n return this.webform.form.components;\n }\n /**\n * When a component sets its api key, we need to check if it is unique within its namespace. Find the namespace root\n * so we can calculate this correctly.\n * @param component\n */\n findNamespaceRoot(component) {\n const path = (0, utils_1.getArrayFromComponentPath)(component.path);\n // First get the component with nested parents.\n let comp = this.webform.getComponent(path);\n comp = Array.isArray(comp) ? comp[0] : comp;\n const namespaceKey = this.recurseNamespace(comp);\n // If there is no key, it is the root form.\n if (!namespaceKey || this.form.key === namespaceKey) {\n return this.form.components;\n }\n const componentSchema = component.component;\n // If the current component is the namespace, we don't need to find it again.\n if (namespaceKey === component.key) {\n return [...componentSchema.components, componentSchema];\n }\n // Get the namespace component so we have the original object.\n const namespaceComponent = (0, formUtils_1.getComponent)(this.form.components, namespaceKey, true);\n return namespaceComponent ? namespaceComponent.components : comp.components;\n }\n recurseNamespace(component) {\n // If there is no parent, we are at the root level.\n if (!component) {\n return null;\n }\n // Some components are their own namespace.\n if (['address', 'container', 'datagrid', 'editgrid', 'dynamicWizard', 'tree'].includes(component.type) || component.tree || component.arrayTree) {\n return component.key;\n }\n // Anything else, keep going up.\n return this.recurseNamespace(component.parent);\n }\n render() {\n return this.renderTemplate('builder', {\n sidebar: this.renderTemplate('builderSidebar', {\n scrollEnabled: this.sideBarScroll,\n groupOrder: this.groupOrder,\n groupId: `builder-sidebar-${this.id}`,\n groups: this.groupOrder.map((groupKey) => this.renderTemplate('builderSidebarGroup', {\n group: this.groups[groupKey],\n groupKey,\n groupId: `builder-sidebar-${this.id}`,\n subgroups: this.groups[groupKey].subgroups.map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n keyboardActionsEnabled: this.keyboardActionsEnabled,\n })),\n }),\n form: this.webform.render(),\n });\n }\n attach(element) {\n this.on('change', (form) => {\n this.populateRecaptchaSettings(form);\n });\n return super.attach(element).then(() => {\n this.loadRefs(element, {\n form: 'single',\n sidebar: 'single',\n 'sidebar-search': 'single',\n 'sidebar-groups': 'single',\n 'container': 'multiple',\n 'sidebar-anchor': 'multiple',\n 'sidebar-group': 'multiple',\n 'sidebar-container': 'multiple',\n 'sidebar-component': 'multiple',\n });\n if (this.sideBarScroll && Templates_1.default.current.handleBuilderSidebarScroll) {\n Templates_1.default.current.handleBuilderSidebarScroll.call(this, this);\n }\n // Add the paste status in form\n if (typeof window !== 'undefined' && window.sessionStorage) {\n const data = window.sessionStorage.getItem('formio.clipboard');\n if (data) {\n this.addClass(this.refs.form, 'builder-paste-mode');\n }\n }\n if (!(0, utils_1.bootstrapVersion)(this.options)) {\n const getAttribute = (anchor, attribute) => {\n let elem = anchor.getAttribute(`data-${attribute}`);\n if (!elem) {\n elem = anchor.getAttribute(`data-bs-${attribute}`);\n }\n return elem;\n };\n const hideShow = (group, show) => {\n if (show) {\n group.classList.add(['show']);\n group.style.display = 'inherit';\n }\n else {\n group.classList.remove(['show']);\n group.style.display = 'none';\n }\n };\n // Initialize\n this.refs['sidebar-group'].forEach((group) => {\n hideShow(group, getAttribute(group, 'default') === 'true');\n });\n // Click event\n this.refs['sidebar-anchor'].forEach((anchor, index) => {\n this.addEventListener(anchor, 'click', () => {\n const clickedParentId = getAttribute(anchor, 'parent').slice('#builder-sidebar-'.length);\n const clickedId = getAttribute(anchor, 'target').slice('#group-'.length);\n this.refs['sidebar-group'].forEach((group, groupIndex) => {\n const openByDefault = getAttribute(group, 'default') === 'true';\n const groupId = group.getAttribute('id').slice('group-'.length);\n const groupParent = getAttribute(group, 'parent').slice('#builder-sidebar-'.length);\n hideShow(group, ((openByDefault && groupParent === clickedId) || groupId === clickedParentId || groupIndex === index));\n });\n }, true);\n });\n }\n if (this.keyboardActionsEnabled) {\n this.refs['sidebar-component'].forEach((component) => {\n this.addEventListener(component, 'keydown', (event) => {\n if (event.keyCode === 13) {\n this.addNewComponent(component);\n }\n });\n });\n }\n this.addEventListener(this.refs['sidebar-search'], 'input', lodash_1.default.debounce((e) => {\n const searchString = e.target.value;\n this.searchFields(searchString);\n }, 300));\n if (this.dragDropEnabled) {\n this.initDragula();\n }\n const drake = this.dragula;\n if (this.refs.form) {\n (0, dom_autoscroller_1.default)([window], {\n margin: 20,\n maxSpeed: 6,\n scrollWhenOutside: true,\n autoScroll: function () {\n return this.down && (drake === null || drake === void 0 ? void 0 : drake.dragging);\n }\n });\n return this.webform.attach(this.refs.form);\n }\n });\n }\n searchFields(searchString = '') {\n const searchValue = searchString.toLowerCase();\n const sidebar = this.refs['sidebar'];\n const sidebarGroups = this.refs['sidebar-groups'];\n if (!sidebar || !sidebarGroups) {\n return;\n }\n const filterGroupBy = (group, searchValue = '') => {\n const result = lodash_1.default.toPlainObject(group);\n const { subgroups = [], components } = result;\n const filteredComponents = [];\n for (const key in components) {\n const isMatchedToTitle = this.t(components[key].title).toLowerCase().match(searchValue);\n const isMatchedToKey = components[key].key.toLowerCase().match(searchValue);\n if (isMatchedToTitle || isMatchedToKey) {\n filteredComponents.push(components[key]);\n }\n }\n this.orderComponents(result, filteredComponents);\n if (searchValue) {\n result.default = true;\n }\n if (result.componentOrder.length || subgroups.length) {\n return result;\n }\n return null;\n };\n const filterGroupOrder = (groupOrder, searchValue) => {\n const result = lodash_1.default.cloneDeep(groupOrder);\n return result.filter(key => filterGroupBy(this.groups[key], searchValue));\n };\n const filterSubgroups = (groups, searchValue) => {\n const result = lodash_1.default.clone(groups);\n return result\n .map(subgroup => filterGroupBy(subgroup, searchValue))\n .filter(subgroup => !lodash_1.default.isNull(subgroup));\n };\n const toTemplate = groupKey => {\n return {\n group: filterGroupBy(this.groups[groupKey], searchValue),\n groupKey,\n groupId: sidebar.id || sidebarGroups.id,\n subgroups: filterSubgroups(this.groups[groupKey].subgroups, searchValue)\n .map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n };\n };\n sidebarGroups.innerHTML = filterGroupOrder(this.groupOrder, searchValue)\n .map(groupKey => this.renderTemplate('builderSidebarGroup', toTemplate(groupKey)))\n .join('');\n this.loadRefs(this.element, {\n 'sidebar-groups': 'single',\n 'sidebar-anchor': 'multiple',\n 'sidebar-group': 'multiple',\n 'sidebar-container': 'multiple',\n });\n this.updateDragAndDrop();\n if (searchValue === '') {\n this.triggerRedraw();\n }\n }\n orderComponents(groupInfo, foundComponents) {\n const components = foundComponents || groupInfo.components;\n const isResource = groupInfo.key.indexOf('resource-') === 0;\n if (components) {\n groupInfo.componentOrder = Object.keys(components)\n .map(key => components[key])\n .filter(component => component && !component.ignore && !component.ignoreForForm)\n .sort((a, b) => a.weight - b.weight)\n .map(component => isResource ? `component-${component.key}` : component.key);\n }\n }\n updateDragAndDrop() {\n if (this.dragDropEnabled) {\n this.initDragula();\n }\n if (this.refs.form) {\n return this.webform.attach(this.refs.form);\n }\n }\n initDragula() {\n const options = this.options;\n if (this.dragula) {\n this.dragula.destroy();\n }\n const containersArray = Array.prototype.slice.call(this.refs['sidebar-container']).filter(item => {\n return item.id !== 'group-container-resource';\n });\n if (!dragula_min_js_1.default) {\n return;\n }\n this.dragula = (0, dragula_min_js_1.default)(containersArray, {\n moves(el) {\n let moves = true;\n const list = Array.from(el.classList).filter(item => item.indexOf('formio-component-') === 0);\n list.forEach(item => {\n const key = item.slice('formio-component-'.length);\n if (options.disabled && options.disabled.includes(key)) {\n moves = false;\n }\n });\n if (el.classList.contains('no-drag')) {\n moves = false;\n }\n return moves;\n },\n copy(el) {\n return el.classList.contains('drag-copy');\n },\n accepts(el, target) {\n return !el.contains(target) && !target.classList.contains('no-drop');\n }\n }).on('drop', (element, target, source, sibling) => this.onDrop(element, target, source, sibling));\n }\n detach() {\n if (this.dragula) {\n this.dragula.destroy();\n }\n this.dragula = null;\n if (this.sideBarScroll && Templates_1.default.current.clearBuilderSidebarScroll) {\n Templates_1.default.current.clearBuilderSidebarScroll.call(this, this);\n }\n super.detach();\n }\n getComponentInfo(key, group) {\n let info;\n // Need to check in first order as resource component key can be the same as from webform default components\n if (group && group.slice(0, group.indexOf('-')) === 'resource') {\n // This is an existing resource field.\n const resourceGroups = this.groups.resource.subgroups;\n const resourceGroup = lodash_1.default.find(resourceGroups, { key: group });\n if (resourceGroup && resourceGroup.components.hasOwnProperty(`component-${key}`)) {\n info = (0, utils_1.fastCloneDeep)(resourceGroup.components[`component-${key}`].schema);\n }\n }\n // This is a new component\n else if (this.schemas.hasOwnProperty(key)) {\n info = (0, utils_1.fastCloneDeep)(this.schemas[key]);\n }\n else if (this.groups.hasOwnProperty(group)) {\n const groupComponents = this.groups[group].components;\n if (groupComponents.hasOwnProperty(key)) {\n info = (0, utils_1.fastCloneDeep)(groupComponents[key].schema);\n }\n }\n else if (group === 'searchFields') { //Search components go into this group\n const resourceGroups = this.groups.resource.subgroups;\n for (let ix = 0; ix < resourceGroups.length; ix++) {\n const resourceGroup = resourceGroups[ix];\n if (resourceGroup.components.hasOwnProperty(`component-${key}`)) {\n info = (0, utils_1.fastCloneDeep)(resourceGroup.components[`component-${key}`].schema);\n break;\n }\n }\n }\n if (info) {\n info.key = this.generateKey(info);\n }\n return info;\n }\n getComponentsPath(component, parent) {\n // Get path to the component in the parent component.\n let path = 'components';\n let columnIndex = 0;\n let tableRowIndex = 0;\n let tableColumnIndex = 0;\n let tabIndex = 0;\n switch (parent.type) {\n case 'table':\n tableRowIndex = lodash_1.default.findIndex(parent.rows, row => row.some(column => column.components.some(comp => comp.key === component.key)));\n tableColumnIndex = lodash_1.default.findIndex(parent.rows[tableRowIndex], (column => column.components.some(comp => comp.key === component.key)));\n path = `rows[${tableRowIndex}][${tableColumnIndex}].components`;\n break;\n case 'columns':\n columnIndex = lodash_1.default.findIndex(parent.columns, column => column.components.some(comp => comp.key === component.key));\n path = `columns[${columnIndex}].components`;\n break;\n case 'tabs':\n tabIndex = lodash_1.default.findIndex(parent.components, tab => tab.components.some(comp => comp.key === component.key));\n path = `components[${tabIndex}].components`;\n break;\n }\n return path;\n }\n /* eslint-disable max-statements */\n onDrop(element, target, source, sibling) {\n var _a;\n if (!target) {\n return;\n }\n // If you try to drop within itself.\n if (element.contains(target)) {\n return;\n }\n const key = element.getAttribute('data-key');\n const type = element.getAttribute('data-type');\n const group = element.getAttribute('data-group');\n let info, isNew, path, index;\n if (key && group) {\n // This is a new component.\n info = this.getComponentInfo(key, group);\n if (!info && type) {\n info = this.getComponentInfo(type, group);\n }\n isNew = true;\n }\n else if (source.formioContainer) {\n index = lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key });\n if (index !== -1) {\n // Grab and remove the component from the source container.\n info = source.formioContainer.splice(lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key }), 1);\n // Since splice returns an array of one object, we need to destructure it.\n info = info[0];\n }\n }\n // If we haven't found the component, stop.\n if (!info) {\n return;\n }\n // Show an error if siblings are disabled for a component and such a component already exists.\n const compKey = (group === 'resource') ? `component-${key}` : key;\n const draggableComponent = ((_a = this.groups[group]) === null || _a === void 0 ? void 0 : _a.components[compKey]) || {};\n if (draggableComponent.disableSiblings) {\n let isCompAlreadyExists = false;\n (0, formUtils_1.eachComponent)(this.webform.components, (component) => {\n if (component.type === draggableComponent.schema.type) {\n isCompAlreadyExists = true;\n return;\n }\n }, true);\n if (isCompAlreadyExists) {\n this.webform.redraw();\n this.webform.setAlert('danger', `You cannot add more than one ${draggableComponent.key} component to one page.`);\n return;\n }\n }\n if (target !== source) {\n // Ensure the key remains unique in its new container.\n builder_1.default.uniquify(this.findNamespaceRoot(target.formioComponent), info);\n }\n const parent = target.formioComponent;\n // Insert in the new container.\n if (target.formioContainer) {\n if (sibling) {\n if (!sibling.getAttribute('data-noattach')) {\n index = lodash_1.default.findIndex(target.formioContainer, { key: lodash_1.default.get(sibling, 'formioComponent.component.key') });\n index = (index === -1) ? 0 : index;\n }\n else {\n index = sibling.getAttribute('data-position');\n }\n if (index !== -1) {\n target.formioContainer.splice(index, 0, info);\n }\n }\n else {\n target.formioContainer.push(info);\n }\n path = this.getComponentsPath(info, parent.component);\n index = lodash_1.default.findIndex(lodash_1.default.get(parent.schema, path), { key: info.key });\n if (index === -1) {\n index = 0;\n }\n }\n if (parent && parent.addChildComponent) {\n parent.addChildComponent(info, element, target, source, sibling);\n }\n const componentInDataGrid = parent.type === 'datagrid';\n if (isNew && !this.options.noNewEdit && !info.noNewEdit) {\n this.editComponent(info, target, isNew, null, null, { inDataGrid: componentInDataGrid });\n }\n // Only rebuild the parts needing to be rebuilt.\n let rebuild;\n if (target !== source) {\n if (source.formioContainer && source.contains(target)) {\n rebuild = source.formioComponent.rebuild();\n }\n else if (target.contains(source)) {\n rebuild = target.formioComponent.rebuild();\n }\n else {\n if (source.formioContainer) {\n rebuild = source.formioComponent.rebuild();\n }\n rebuild = target.formioComponent.rebuild();\n }\n }\n else {\n // If they are the same, only rebuild one.\n rebuild = target.formioComponent.rebuild();\n }\n if (!rebuild) {\n rebuild = Promise.resolve();\n }\n return rebuild.then(() => {\n this.emit('addComponent', info, parent, path, index, isNew && !this.options.noNewEdit && !info.noNewEdit);\n if (!isNew || this.options.noNewEdit || info.noNewEdit) {\n this.emit('change', this.form);\n }\n });\n }\n setForm(form) {\n var _a;\n if (!form.components) {\n form.components = [];\n }\n if (form && form.properties) {\n this.options.properties = form.properties;\n }\n this.keyboardActionsEnabled = lodash_1.default.get(this.options, 'keyboardBuilder', false) || ((_a = this.options.properties) === null || _a === void 0 ? void 0 : _a.keyboardBuilder);\n const isShowSubmitButton = !this.options.noDefaultSubmitButton\n && (!form.components.length || !form.components.find(comp => comp.key === 'submit'));\n // Ensure there is at least a submit button.\n if (isShowSubmitButton) {\n form.components.push({\n type: 'button',\n label: 'Submit',\n key: 'submit',\n size: 'md',\n block: false,\n action: 'submit',\n disableOnInvalid: true,\n theme: 'primary'\n });\n }\n if (this.webform) {\n const shouldRebuild = !this.webform.form.components ||\n (form.components.length !== this.webform.form.components.length);\n return this.webform.setForm(form, { keepAsReference: true }).then(() => {\n if (this.refs.form) {\n this.builderHeight = this.refs.form.offsetHeight;\n }\n if (!shouldRebuild) {\n return this.form;\n }\n return this.rebuild().then(() => this.form);\n });\n }\n return Promise.resolve(form);\n }\n populateRecaptchaSettings(form) {\n //populate isEnabled for recaptcha form settings\n let isRecaptchaEnabled = false;\n if (this.form.components) {\n (0, formUtils_1.eachComponent)(form.components, component => {\n if (isRecaptchaEnabled) {\n return;\n }\n if (component.type === 'recaptcha') {\n isRecaptchaEnabled = true;\n return false;\n }\n });\n if (isRecaptchaEnabled) {\n lodash_1.default.set(form, 'settings.recaptcha.isEnabled', true);\n }\n else if (lodash_1.default.get(form, 'settings.recaptcha.isEnabled')) {\n lodash_1.default.set(form, 'settings.recaptcha.isEnabled', false);\n }\n }\n }\n removeComponent(component, parent, original) {\n if (!parent) {\n return;\n }\n let remove = true;\n const removingComponentsGroup = !component.skipRemoveConfirm &&\n ((Array.isArray(component.components) && component.components.length) ||\n (Array.isArray(component.rows) && component.rows.length) ||\n (Array.isArray(component.columns) && component.columns.length));\n if (this.options.alwaysConfirmComponentRemoval || removingComponentsGroup) {\n const message = removingComponentsGroup ? 'Removing this component will also remove all of its children. Are you sure you want to do this?'\n : 'Are you sure you want to remove this component?';\n remove = window.confirm(this.t(message));\n }\n if (!original) {\n original = parent.formioContainer.find((comp) => comp.id === component.id);\n }\n const index = parent.formioContainer ? parent.formioContainer.indexOf(original) : 0;\n if (remove && index !== -1) {\n const path = this.getComponentsPath(component, parent.formioComponent.component);\n if (parent.formioContainer) {\n parent.formioContainer.splice(index, 1);\n }\n else if (parent.formioComponent && parent.formioComponent.removeChildComponent) {\n parent.formioComponent.removeChildComponent(component);\n }\n const rebuild = parent.formioComponent.rebuild() || Promise.resolve();\n rebuild.then(() => {\n this.emit('removeComponent', component, parent.formioComponent.schema, path, index);\n this.emit('change', this.form);\n });\n }\n return remove;\n }\n replaceDoubleQuotes(data, fieldsToRemoveDoubleQuotes = []) {\n if (data) {\n fieldsToRemoveDoubleQuotes.forEach((key) => {\n if (data[key]) {\n data[key] = data[key].replace(/\"/g, \"'\");\n }\n });\n return data;\n }\n }\n updateComponent(component, changed) {\n // Update the preview.\n if (this.preview) {\n this.preview.form = {\n components: [lodash_1.default.omit(Object.assign({}, component), [\n 'hidden',\n 'conditional',\n 'calculateValue',\n 'logic',\n 'autofocus',\n 'customConditional',\n ])],\n config: this.options.formConfig || {}\n };\n const fieldsToRemoveDoubleQuotes = ['label', 'tooltip'];\n this.preview.form.components.forEach(component => this.replaceDoubleQuotes(component, fieldsToRemoveDoubleQuotes));\n const previewElement = this.componentEdit.querySelector('[ref=\"preview\"]');\n if (previewElement) {\n this.setContent(previewElement, this.preview.render());\n this.preview.attach(previewElement);\n }\n }\n // Change the \"default value\" field to be reflective of this component.\n const defaultValueComponent = (0, formUtils_1.getComponent)(this.editForm.components, 'defaultValue', true);\n if (defaultValueComponent && component.type !== 'hidden') {\n const defaultChanged = changed && ((changed.component && changed.component.key === 'defaultValue')\n || (changed.instance && defaultValueComponent.hasComponent && defaultValueComponent.hasComponent(changed.instance)));\n if (!defaultChanged) {\n lodash_1.default.assign(defaultValueComponent.component, lodash_1.default.omit(Object.assign({}, component), [\n 'key',\n 'label',\n 'labelPosition',\n 'labelMargin',\n 'labelWidth',\n 'placeholder',\n 'tooltip',\n 'hidden',\n 'autofocus',\n 'validate',\n 'disabled',\n 'defaultValue',\n 'customDefaultValue',\n 'calculateValue',\n 'conditional',\n 'customConditional',\n 'id'\n ]));\n const parentComponent = defaultValueComponent.parent;\n let tabIndex = -1;\n let index = -1;\n parentComponent.tabs.some((tab, tIndex) => {\n tab.some((comp, compIndex) => {\n if (comp.id === defaultValueComponent.id) {\n tabIndex = tIndex;\n index = compIndex;\n return true;\n }\n return false;\n });\n });\n if (tabIndex !== -1 && index !== -1 && changed && changed.value) {\n const sibling = parentComponent.tabs[tabIndex][index + 1];\n parentComponent.removeComponent(defaultValueComponent);\n const newComp = parentComponent.addComponent(defaultValueComponent.component, defaultValueComponent.data, sibling);\n lodash_1.default.pull(newComp.validators, 'required');\n parentComponent.tabs[tabIndex].splice(index, 1, newComp);\n newComp.checkValidity = () => true;\n newComp.build(defaultValueComponent.element);\n }\n }\n else {\n let dataPath = changed.instance._data.key;\n const path = (0, utils_1.getArrayFromComponentPath)(changed.instance.path);\n path.shift();\n if (path.length) {\n path.unshift(component.key);\n dataPath = (0, utils_1.getStringFromComponentPath)(path);\n }\n lodash_1.default.set(this.preview._data, dataPath, changed.value);\n lodash_1.default.set(this.webform._data, dataPath, changed.value);\n }\n }\n // Called when we update a component.\n this.emit('updateComponent', component);\n }\n findRepeatablePaths() {\n const repeatablePaths = [];\n const keys = new Map();\n (0, formUtils_1.eachComponent)(this.form.components, (comp, path) => {\n if (!comp.key) {\n return;\n }\n if (keys.has(comp.key)) {\n if (keys.get(comp.key).includes(path)) {\n repeatablePaths.push(path);\n }\n else {\n keys.set(comp.key, [...keys.get(comp.key), path]);\n }\n }\n else {\n keys.set(comp.key, [path]);\n }\n }, true);\n return repeatablePaths;\n }\n highlightInvalidComponents() {\n const repeatablePaths = this.findRepeatablePaths();\n let hasInvalidComponents = false;\n this.webform.everyComponent((comp) => {\n var _a, _b;\n const path = comp.path;\n if (repeatablePaths.includes(path)) {\n comp.setCustomValidity(`API Key is not unique: ${comp.key}`);\n hasInvalidComponents = true;\n }\n else if ((_b = (_a = comp.error) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.startsWith('API Key is not unique')) {\n comp.setCustomValidity('');\n }\n });\n this.emit('builderFormValidityChange', hasInvalidComponents);\n }\n /**\n * Called when a new component is saved.\n *\n * @param parent\n * @param component\n * @return {boolean}\n */\n saveComponent(component, parent, isNew, original) {\n this.editForm.detach();\n const parentContainer = parent ? parent.formioContainer : this.container;\n const parentComponent = parent ? parent.formioComponent : this;\n this.dialog.close();\n const path = parentContainer ? this.getComponentsPath(component, parentComponent.component) : '';\n if (!original) {\n original = parent.formioContainer.find((comp) => comp.id === component.id);\n }\n const index = parentContainer ? parentContainer.indexOf(original) : 0;\n if (index !== -1) {\n let submissionData = this.editForm.submission.data;\n submissionData = submissionData.componentJson || submissionData;\n const fieldsToRemoveDoubleQuotes = ['label', 'tooltip'];\n this.replaceDoubleQuotes(submissionData, fieldsToRemoveDoubleQuotes);\n this.hook('beforeSaveComponentSettings', submissionData);\n let comp = null;\n parentComponent.getComponents().forEach((component) => {\n if (component.component.key === original.key) {\n comp = component;\n }\n });\n const originalComp = comp.component;\n const originalComponentSchema = comp.schema;\n const isParentSaveChildMethod = this.isParentSaveChildMethod(parent.formioComponent);\n if (parentContainer && !isParentSaveChildMethod) {\n parentContainer[index] = submissionData;\n if (comp) {\n comp.component = submissionData;\n }\n }\n else if (isParentSaveChildMethod) {\n parent.formioComponent.saveChildComponent(submissionData);\n }\n const rebuild = parentComponent.rebuild() || Promise.resolve();\n return rebuild.then(() => {\n const schema = parentContainer ? parentContainer[index] : (comp ? comp.schema : []);\n this.emitSaveComponentEvent(schema, originalComp, parentComponent.schema, path, index, isNew, originalComponentSchema);\n this.emit('change', this.form);\n this.highlightInvalidComponents();\n if (this.isComponentCreated) {\n const component = parent.formioComponent.components[0];\n this.moveComponent(component);\n this.isComponentCreated = false;\n }\n });\n }\n this.highlightInvalidComponents();\n return Promise.resolve();\n }\n emitSaveComponentEvent(schema, originalComp, parentComponentSchema, path, index, isNew, originalComponentSchema) {\n this.emit('saveComponent', schema, originalComp, parentComponentSchema, path, index, isNew, originalComponentSchema);\n }\n attachEditComponentControls(component, parent, isNew, original, ComponentClass) {\n const cancelButtons = this.componentEdit.querySelectorAll('[ref=\"cancelButton\"]');\n cancelButtons.forEach((cancelButton) => {\n this.editForm.addEventListener(cancelButton, 'click', (event) => {\n event.preventDefault();\n this.editForm.detach();\n this.emit('cancelComponent', component);\n this.dialog.close();\n this.highlightInvalidComponents();\n });\n });\n const removeButtons = this.componentEdit.querySelectorAll('[ref=\"removeButton\"]');\n removeButtons.forEach((removeButton) => {\n this.editForm.addEventListener(removeButton, 'click', (event) => {\n event.preventDefault();\n // Since we are already removing the component, don't trigger another remove.\n this.saved = true;\n this.editForm.detach();\n this.removeComponent(component, parent, original);\n this.dialog.close();\n this.highlightInvalidComponents();\n });\n });\n const saveButtons = this.componentEdit.querySelectorAll('[ref=\"saveButton\"]');\n saveButtons.forEach((saveButton) => {\n this.editForm.addEventListener(saveButton, 'click', (event) => {\n event.preventDefault();\n if (!this.editForm.checkValidity(this.editForm.data, true, this.editForm.data)) {\n this.editForm.setPristine(false);\n this.editForm.showErrors();\n return false;\n }\n this.saved = true;\n this.saveComponent(component, parent, isNew, original);\n });\n });\n const previewButtons = this.componentEdit.querySelectorAll('[ref=\"previewButton\"]');\n previewButtons.forEach((previewButton) => {\n this.editForm.addEventListener(previewButton, 'click', (event) => {\n event.preventDefault();\n this.showPreview = !this.showPreview;\n this.editForm.detach();\n this.setContent(this.componentEdit, this.renderTemplate('builderEditForm', {\n componentInfo: ComponentClass.builderInfo,\n editForm: this.editForm.render(),\n preview: this.preview ? this.preview.render() : false,\n showPreview: this.showPreview,\n helplinks: this.helplinks,\n }));\n this.editForm.attach(this.componentEdit.querySelector('[ref=\"editForm\"]'));\n this.attachEditComponentControls(component, parent, isNew, original, ComponentClass);\n });\n });\n }\n editComponent(component, parent, isNew, isJsonEdit, original, flags = {}) {\n var _a;\n if (!component.key) {\n return;\n }\n this.saved = false;\n const componentCopy = (0, utils_1.fastCloneDeep)(component);\n let ComponentClass = Components_1.default.components[componentCopy.type];\n const isCustom = ComponentClass === undefined;\n isJsonEdit = isJsonEdit || isCustom;\n ComponentClass = isCustom ? Components_1.default.components.unknown : ComponentClass;\n // Make sure we only have one dialog open at a time.\n if (this.dialog) {\n this.dialog.close();\n this.highlightInvalidComponents();\n }\n // This is the render step.\n const editFormOptions = lodash_1.default.clone(lodash_1.default.get(this, 'options.editForm', {}));\n if (this.editForm) {\n this.editForm.destroy();\n }\n // Allow editForm overrides per component.\n const overrides = lodash_1.default.get(this.options, `editForm.${componentCopy.type}`, {});\n // Pass along the form being edited.\n editFormOptions.editForm = this.form;\n editFormOptions.editComponent = component;\n editFormOptions.flags = flags;\n this.hook('editComponentParentInstance', editFormOptions, parent);\n this.editForm = new Webform_1.default(Object.assign(Object.assign(Object.assign({}, lodash_1.default.omit(this.options, ['hooks', 'builder', 'events', 'attachMode', 'skipInit'])), { language: this.options.language }), editFormOptions));\n this.hook('editFormProperties', parent);\n this.editForm.form = (isJsonEdit && !isCustom) ? {\n components: [\n {\n type: 'textarea',\n as: 'json',\n editor: 'ace',\n weight: 10,\n input: true,\n key: 'componentJson',\n label: 'Component JSON',\n tooltip: 'Edit the JSON for this component.'\n },\n {\n type: 'checkbox',\n key: 'showFullSchema',\n label: 'Full Schema'\n }\n ]\n } : ComponentClass.editForm(lodash_1.default.cloneDeep(overrides));\n const instanceOptions = {\n inFormBuilder: true,\n };\n this.hook('instanceOptionsPreview', instanceOptions);\n const instance = new ComponentClass(componentCopy, instanceOptions);\n const schema = this.hook('builderComponentSchema', component, instance);\n this.editForm.submission = isJsonEdit ? {\n data: {\n componentJson: schema,\n showFullSchema: this.options.showFullJsonSchema\n },\n } : {\n data: instance.component,\n };\n if (this.preview) {\n this.preview.destroy();\n }\n if (!ComponentClass.builderInfo.hasOwnProperty('preview') || ComponentClass.builderInfo.preview) {\n this.preview = new Webform_1.default(lodash_1.default.omit(Object.assign(Object.assign({}, this.options), { preview: true }), [\n 'hooks',\n 'builder',\n 'events',\n 'attachMode',\n 'calculateValue'\n ]));\n this.hook('previewFormSettitngs', schema, isJsonEdit);\n }\n this.showPreview = (_a = ComponentClass.builderInfo.showPreview) !== null && _a !== void 0 ? _a : true;\n this.componentEdit = this.ce('div', { 'class': 'component-edit-container' });\n this.setContent(this.componentEdit, this.renderTemplate('builderEditForm', {\n componentInfo: ComponentClass.builderInfo,\n editForm: this.editForm.render(),\n preview: this.preview ? this.preview.render() : false,\n showPreview: this.showPreview,\n helplinks: this.helplinks\n }));\n this.dialog = this.createModal(this.componentEdit, lodash_1.default.get(this.options, 'dialogAttr', {}));\n // This is the attach step.\n this.editForm.attach(this.componentEdit.querySelector('[ref=\"editForm\"]'));\n this.hook('editFormWrapper');\n this.updateComponent(componentCopy);\n this.editForm.on('change', (event) => {\n if (event.changed) {\n if (event.changed.component && event.changed.component.key === 'showFullSchema') {\n const { value } = event.changed;\n this.editForm.submission = {\n data: {\n componentJson: value ? instance.component : component,\n showFullSchema: value\n },\n };\n return;\n }\n // See if this is a manually modified key. Treat custom component keys as manually modified\n if ((event.changed.component && (event.changed.component.key === 'key')) || isJsonEdit) {\n componentCopy.keyModified = true;\n }\n let isComponentLabelChanged = false;\n if (event.changed.instance) {\n isComponentLabelChanged = ['label', 'title'].includes(event.changed.instance.path);\n }\n else if (event.changed.component) {\n isComponentLabelChanged = ['label', 'title'].includes(event.changed.component.key);\n }\n if (isComponentLabelChanged) {\n // Ensure this component has a key.\n if (isNew) {\n if (!event.data.keyModified) {\n this.editForm.everyComponent(component => {\n if (component.key === 'key' && component.parent.component.key === 'tabs') {\n component.setValue(this.updateComponentKey(event.data));\n return false;\n }\n });\n }\n if (this.form) {\n let formComponents = this.findNamespaceRoot(parent.formioComponent);\n // excluding component which key uniqueness is to be checked to prevent the comparing of the same keys\n formComponents = formComponents.filter(comp => editFormOptions.editComponent.id !== comp.id);\n // Set a unique key for this component.\n builder_1.default.uniquify(formComponents, event.data);\n }\n }\n }\n // Update the component.\n this.updateComponent(event.data.componentJson || event.data, event.changed);\n }\n });\n this.attachEditComponentControls(component, parent, isNew, original, ComponentClass);\n const dialogClose = () => {\n this.editForm.destroy(true);\n if (this.preview) {\n this.preview.destroy(true);\n this.preview = null;\n }\n if (isNew && !this.saved) {\n this.removeComponent(component, parent, original);\n this.highlightInvalidComponents();\n }\n // Clean up.\n this.removeEventListener(this.dialog, 'close', dialogClose);\n this.dialog = null;\n };\n this.addEventListener(this.dialog, 'close', dialogClose);\n // Called when we edit a component.\n this.emit('editComponent', component);\n }\n updateComponentKey(data) {\n return lodash_1.default.camelCase(data.title ||\n data.label ||\n data.placeholder ||\n data.type).replace(/^[0-9]*/, '');\n }\n moveComponent(component) {\n var _a;\n if (this.selectedComponent) {\n const prevSelected = this.selectedComponent;\n (_a = prevSelected.element) === null || _a === void 0 ? void 0 : _a.classList.remove('builder-component-selected');\n this.removeEventListener(document, 'keydown');\n }\n component.element.focus();\n component.element.classList.add('builder-component-selected');\n this.selectedComponent = component;\n this.addEventListener(document, 'keydown', this.moveHandler.bind(this));\n }\n updateComponentPlacement(direction) {\n const component = this.selectedComponent;\n let index, info;\n const step = direction ? -1 : 1;\n if (component) {\n const element = component.element;\n const sibling = direction ? element.previousElementSibling : element.nextElementSibling;\n const source = element.parentNode;\n const containerLength = source.formioContainer.length;\n if (containerLength && containerLength <= 1) {\n return;\n }\n if (source.formioContainer) {\n index = lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key });\n if (index !== -1) {\n info = source.formioContainer.splice(lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key }), 1);\n info = info[0];\n source.removeChild(element);\n }\n }\n const len = source.formioComponent.components.length;\n index = (index === -1) ? 0 : index + step;\n if (index === -1) {\n source.formioContainer.push(info);\n source.appendChild(element);\n }\n else if (index === len) {\n const key = source.formioContainer[0].key;\n index = lodash_1.default.findIndex(source.formioComponent.components, { key: key });\n const firstElement = source.formioComponent.components[index].element;\n source.formioContainer.splice(0, 0, info);\n source.insertBefore(element, firstElement);\n }\n else if (index !== -1) {\n source.formioContainer.splice(index, 0, info);\n direction\n ? source.insertBefore(element, sibling)\n : source.insertBefore(element, sibling.nextElementSibling);\n }\n element.focus();\n }\n }\n stopMoving(comp) {\n const parent = comp.element.parentNode;\n this.removeEventListener(document, 'keydown');\n parent.formioComponent.rebuild();\n this.selectedComponent = null;\n }\n addNewComponent(element) {\n var _a;\n const source = document.querySelector('.formio-builder-form');\n const key = element.getAttribute('data-key');\n const group = element.getAttribute('data-group');\n const isNew = true;\n let info;\n if (key && group) {\n info = this.getComponentInfo(key, group);\n }\n if (isNew && !this.options.noNewEdit && !info.noNewEdit) {\n builder_1.default.uniquify(this.findNamespaceRoot(source.formioComponent), info);\n this.editComponent(info, source, isNew, null, null);\n }\n const firstComponent = (_a = source.formioComponent.components[0]) === null || _a === void 0 ? void 0 : _a.element;\n if (firstComponent) {\n source.formioContainer.splice(0, 0, info);\n }\n else {\n source.formioContainer.push(info);\n }\n source.formioComponent.rebuild().then(() => {\n this.isComponentCreated = true;\n });\n }\n /**\n * Creates copy of component schema and stores it under sessionStorage.\n * @param {Component} component\n * @return {*}\n */\n copyComponent(component) {\n if (!window.sessionStorage) {\n return console.warn('Session storage is not supported in this browser.');\n }\n this.addClass(this.refs.form, 'builder-paste-mode');\n window.sessionStorage.setItem('formio.clipboard', JSON.stringify(component.schema));\n }\n /**\n * Paste copied component after the current component.\n * @param {Component} component\n * @return {*}\n */\n pasteComponent(component) {\n if (!window.sessionStorage) {\n return console.warn('Session storage is not supported in this browser.');\n }\n this.removeClass(this.refs.form, 'builder-paste-mode');\n if (window.sessionStorage) {\n const data = window.sessionStorage.getItem('formio.clipboard');\n if (data) {\n const schema = JSON.parse(data);\n const parent = this.getParentElement(component.element);\n if (parent) {\n builder_1.default.uniquify(this.findNamespaceRoot(parent.formioComponent), schema);\n let path = '';\n let index = 0;\n const isParentSaveChildMethod = this.isParentSaveChildMethod(parent.formioComponent);\n if (parent.formioContainer && !isParentSaveChildMethod) {\n index = parent.formioContainer.indexOf(component.component);\n path = this.getComponentsPath(schema, parent.formioComponent.component);\n parent.formioContainer.splice(index + 1, 0, schema);\n }\n else if (isParentSaveChildMethod) {\n parent.formioComponent.saveChildComponent(schema, false);\n }\n parent.formioComponent.rebuild();\n this.emitSaveComponentEvent(schema, schema, parent.formioComponent.component, path, (index + 1), true, schema);\n }\n this.emit('change', this.form);\n }\n }\n }\n isParentSaveChildMethod(parentComp) {\n return !!(parentComp && parentComp.saveChildComponent);\n }\n getParentElement(element) {\n let container = element;\n do {\n container = container.parentNode;\n } while (container && !container.formioComponent);\n return container;\n }\n addBuilderComponentInfo(component) {\n if (!component || !component.group || !this.groups[component.group]) {\n return;\n }\n component = lodash_1.default.clone(component);\n const groupInfo = this.groups[component.group];\n if (!groupInfo.components.hasOwnProperty(component.key)) {\n groupInfo.components[component.key] = component;\n }\n return component;\n }\n init() {\n if (this.webform) {\n this.webform.init();\n }\n return super.init();\n }\n clear() {\n if (this.webform.initialized) {\n this.webform.clear();\n }\n }\n destroy(all = false) {\n if (this.webform.initialized) {\n this.webform.destroy(all);\n }\n super.destroy(all);\n }\n addBuilderGroup(name, group) {\n if (!this.groups[name]) {\n this.groups[name] = group;\n this.groupOrder.push(name);\n this.triggerRedraw();\n }\n else {\n this.updateBuilderGroup(name, group);\n }\n }\n updateBuilderGroup(name, group) {\n if (this.groups[name]) {\n this.groups[name] = group;\n this.triggerRedraw();\n }\n }\n generateKey(info) {\n return info.key || lodash_1.default.camelCase(info.title ||\n info.label ||\n info.placeholder ||\n info.type);\n }\n}\nexports[\"default\"] = WebformBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/WebformBuilder.js?");
5338
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Webform_1 = __importDefault(__webpack_require__(/*! ./Webform */ \"./lib/cjs/Webform.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ./components/_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst tippy_js_1 = __importDefault(__webpack_require__(/*! tippy.js */ \"./node_modules/tippy.js/dist/tippy.esm.js\"));\nconst Components_1 = __importDefault(__webpack_require__(/*! ./components/Components */ \"./lib/cjs/components/Components.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst formUtils_1 = __webpack_require__(/*! ./utils/formUtils */ \"./lib/cjs/utils/formUtils.js\");\nconst builder_1 = __importDefault(__webpack_require__(/*! ./utils/builder */ \"./lib/cjs/utils/builder.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst dom_autoscroller_1 = __importDefault(__webpack_require__(/*! dom-autoscroller */ \"./node_modules/dom-autoscroller/dist/bundle.js\"));\nconst Templates_1 = __importDefault(__webpack_require__(/*! ./templates/Templates */ \"./lib/cjs/templates/Templates.js\"));\n__webpack_require__(/*! ./components/builder */ \"./lib/cjs/components/builder.js\");\n// We need this here because dragula pulls in CustomEvent class that requires global to exist.\nif (typeof window !== 'undefined' && typeof window.global === 'undefined') {\n window.global = window;\n}\nconst dragula_min_js_1 = __importDefault(__webpack_require__(/*! dragula/dist/dragula.min.js */ \"./node_modules/dragula/dist/dragula.min.js\"));\nclass WebformBuilder extends Component_1.default {\n // eslint-disable-next-line max-statements\n constructor() {\n let element, options;\n if (arguments[0] instanceof HTMLElement || arguments[1]) {\n element = arguments[0];\n options = arguments[1];\n }\n else {\n options = arguments[0];\n }\n // Reset skipInit in case PDFBuilder has set it.\n options.skipInit = false;\n options.display = options.display || 'form';\n super(null, options);\n this.moveHandler = (e) => {\n if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 13) {\n e.stopPropagation();\n e.preventDefault();\n }\n if (e.keyCode === 38) {\n this.updateComponentPlacement(true);\n }\n if (e.keyCode === 40) {\n this.updateComponentPlacement(false);\n }\n if (e.keyCode === 13) {\n this.stopMoving(this.selectedComponent);\n }\n };\n this.setElement(element);\n this.dragulaLib = dragula_min_js_1.default;\n this.builderHeight = 0;\n this.schemas = {};\n this.repeatablePaths = [];\n this.sideBarScroll = lodash_1.default.get(this.options, 'sideBarScroll', true);\n this.sideBarScrollOffset = lodash_1.default.get(this.options, 'sideBarScrollOffset', 0);\n this.dragDropEnabled = true;\n // Setup the builder options.\n this.builder = lodash_1.default.defaultsDeep({}, this.options.builder, this.defaultGroups);\n // Turn off if explicitely said to do so...\n lodash_1.default.each(this.defaultGroups, (config, key) => {\n if (config === false) {\n this.builder[key] = false;\n }\n });\n // Add the groups.////\n this.groups = {};\n this.groupOrder = [];\n for (const group in this.builder) {\n if (this.builder[group]) {\n this.builder[group].key = group;\n this.groups[group] = this.builder[group];\n this.groups[group].components = this.groups[group].components || {};\n this.groups[group].componentOrder = this.groups[group].componentOrder || [];\n this.groups[group].subgroups = Object.keys(this.groups[group].groups || {}).map((groupKey) => {\n this.groups[group].groups[groupKey].componentOrder = Object.keys(this.groups[group].groups[groupKey].components).map((key) => key);\n return this.groups[group].groups[groupKey];\n });\n this.groupOrder.push(this.groups[group]);\n }\n }\n this.groupOrder = this.groupOrder\n .filter(group => group && !group.ignore)\n .sort((a, b) => a.weight - b.weight)\n .map(group => group.key);\n for (const type in Components_1.default.components) {\n const component = Components_1.default.components[type];\n if (component.builderInfo && component.builderInfo.schema) {\n this.schemas[type] = component.builderInfo.schema;\n component.type = type;\n const builderInfo = component.builderInfo;\n builderInfo.key = component.type;\n this.addBuilderComponentInfo(builderInfo);\n }\n }\n // Filter out any extra components.\n // Add the components in each group.\n for (const group in this.groups) {\n const info = this.groups[group];\n for (const key in info.components) {\n const compKey = group === 'resource' ? `component-${key}` : key;\n let comp = info.components[compKey];\n if (comp === true &&\n Components_1.default.components[key] &&\n Components_1.default.components[key].builderInfo) {\n comp = Components_1.default.components[key].builderInfo;\n }\n if (comp && comp.schema) {\n this.schemas[key] = comp.schema;\n info.components[compKey] = comp;\n info.components[compKey].key = key;\n }\n else {\n // Do not include this component in the components array.\n delete info.components[compKey];\n }\n }\n // Order the components.\n this.orderComponents(info);\n }\n this.options.hooks = this.options.hooks || {};\n this.options.hooks.renderComponent = (html, { component, self }) => {\n var _a;\n if (self.type === 'form' && !self.key) {\n const template = this.hook('renderComponentFormTemplate', html.replace('formio-component-form', ''));\n // The main webform shouldn't have this class as it adds extra styles.\n return template;\n }\n if (this.options.disabled && this.options.disabled.includes(self.key) || self.parent.noDragDrop) {\n return html;\n }\n return this.renderTemplate('builderComponent', {\n html,\n disableBuilderActions: (_a = self === null || self === void 0 ? void 0 : self.component) === null || _a === void 0 ? void 0 : _a.disableBuilderActions,\n childComponent: component,\n });\n };\n this.options.hooks.renderComponents = (html, { components, self }) => {\n // if Datagrid and already has a component, don't make it droppable.\n if (self.type === 'datagrid' && components.length > 0 || self.noDragDrop) {\n return html;\n }\n if (!components ||\n (!components.length && !components.nodrop) ||\n (self.type === 'form' && components.length <= 1 && (components.length === 0 || components[0].type === 'button'))) {\n html = this.renderTemplate('builderPlaceholder', {\n position: 0\n }) + html;\n }\n return this.renderTemplate('builderComponents', {\n key: self.key,\n type: self.type,\n html,\n });\n };\n this.options.hooks.renderInput = (html, { self }) => {\n if (self.type === 'hidden') {\n return html + self.name;\n }\n return html;\n };\n this.options.hooks.renderLoading = (html, { self }) => {\n if (self.type === 'form' && self.key) {\n return self.name;\n }\n return html;\n };\n this.options.hooks.attachComponents = (element, components, container, component) => {\n // Don't attach if no element was found or component doesn't participate in drag'n'drop.\n if (!element) {\n return;\n }\n if (component.noDragDrop) {\n return element;\n }\n // Attach container and component to element for later reference.\n const containerElement = element.querySelector(`[ref=\"${component.component.key}-container\"]`) || element;\n containerElement.formioContainer = container;\n containerElement.formioComponent = component;\n // Add container to draggable list.\n if (this.dragula && this.allowDrop(element)) {\n this.dragula.containers.push(containerElement);\n }\n // If this is an existing datagrid element, don't make it draggable.\n if ((component.type === 'datagrid' || component.type === 'datamap') && components.length > 0) {\n return element;\n }\n // Since we added a wrapper, need to return the original element so that we can find the components inside it.\n return element.children[0];\n };\n this.options.hooks.attachDatagrid = (element, component) => {\n component.loadRefs(element, {\n [`${component.key}-container`]: 'single',\n });\n const dataGridContainer = component.refs[`${component.key}-container`];\n if (dataGridContainer) {\n component.attachComponents(dataGridContainer.parentNode, [], component.component.components);\n }\n // Need to set up horizontal rearrangement of fields.\n };\n this.options.hooks.attachComponent = this.attachComponent.bind(this);\n // Load resources tagged as 'builder'\n const query = {\n params: {\n type: 'resource',\n limit: 1000000,\n select: '_id,title,name,components'\n }\n };\n if (this.options && this.options.resourceTag) {\n query.params.tags = [this.options.resourceTag];\n }\n else if (!this.options || !this.options.hasOwnProperty('resourceTag')) {\n query.params.tags = ['builder'];\n }\n const formio = new Formio_1.Formio(Formio_1.Formio.projectUrl);\n const isResourcesDisabled = this.options.builder && this.options.builder.resource === false;\n formio.loadProject().then((project) => {\n if (project && (lodash_1.default.get(project, 'settings.addConfigToForms', false) || lodash_1.default.get(project, 'addConfigToForms', false))) {\n const config = project.config || {};\n this.options.formConfig = config;\n const pathToFormConfig = 'webform._form.config';\n const webformConfig = lodash_1.default.get(this, pathToFormConfig);\n if (this.webform && !webformConfig) {\n lodash_1.default.set(this, pathToFormConfig, config);\n }\n }\n }).catch((err) => {\n console.warn(`Could not load project settings: ${err.message || err}`);\n });\n if (!formio.noProject && !isResourcesDisabled && formio.formsUrl) {\n const resourceOptions = this.options.builder && this.options.builder.resource;\n formio.loadForms(query)\n .then((resources) => {\n if (resources.length) {\n this.builder.resource = {\n title: resourceOptions ? resourceOptions.title : 'Existing Resource Fields',\n key: 'resource',\n weight: resourceOptions ? resourceOptions.weight : 50,\n subgroups: [],\n components: [],\n componentOrder: []\n };\n this.groups.resource = {\n title: resourceOptions ? resourceOptions.title : 'Existing Resource Fields',\n key: 'resource',\n weight: resourceOptions ? resourceOptions.weight : 50,\n subgroups: [],\n components: [],\n componentOrder: []\n };\n if (!this.groupOrder.includes('resource')) {\n this.groupOrder.push('resource');\n }\n this.addExistingResourceFields(resources);\n }\n });\n }\n // Notify components if they need to modify their render.\n this.options.attachMode = 'builder';\n this.webform = this.webform || this.createForm(this.options);\n this.pathComponentsMapping = {};\n this.arrayDataComponentPaths = [];\n this.nestedDataComponents = [];\n this.arrayDataComponents = [];\n }\n allowDrop() {\n return true;\n }\n addExistingResourceFields(resources) {\n lodash_1.default.each(resources, (resource, index) => {\n const resourceKey = `resource-${resource.name}`;\n const subgroup = {\n key: resourceKey,\n title: resource.title,\n components: [],\n componentOrder: [],\n default: index === 0,\n };\n (0, formUtils_1.eachComponent)(resource.components, (component) => {\n if (component.type === 'button')\n return;\n if (this.options &&\n this.options.resourceFilter &&\n (!component.tags || component.tags.indexOf(this.options.resourceFilter) === -1))\n return;\n let componentName = component.label;\n if (!componentName && component.key) {\n componentName = lodash_1.default.upperFirst(component.key);\n }\n subgroup.componentOrder.push(`component-${component.key}`);\n subgroup.components[`component-${component.key}`] = lodash_1.default.merge((0, utils_1.fastCloneDeep)(Components_1.default.components[component.type]\n ? Components_1.default.components[component.type].builderInfo\n : Components_1.default.components['unknown'].builderInfo), {\n key: component.key,\n title: componentName,\n group: 'resource',\n subgroup: resourceKey,\n }, {\n schema: Object.assign(Object.assign({}, component), { label: component.label, key: component.key, lockKey: true, source: (!this.options.noSource ? resource._id : undefined), isNew: true })\n });\n }, true);\n this.groups.resource.subgroups.push(subgroup);\n });\n this.triggerRedraw();\n }\n attachTooltip(component, title) {\n return (0, tippy_js_1.default)(component, {\n allowHTML: true,\n trigger: 'mouseenter focus',\n placement: 'top',\n delay: [200, 0],\n zIndex: 10000,\n content: title\n });\n }\n attachComponent(element, component) {\n if (component instanceof WebformBuilder) {\n return;\n }\n // Add component to element for later reference.\n element.formioComponent = component;\n component.loadRefs(element, {\n removeComponent: 'single',\n editComponent: 'single',\n moveComponent: 'single',\n copyComponent: 'single',\n pasteComponent: 'single',\n editJson: 'single'\n });\n if (component.refs.copyComponent) {\n this.attachTooltip(component.refs.copyComponent, this.t('Copy'));\n component.addEventListener(component.refs.copyComponent, 'click', () => this.copyComponent(component));\n }\n if (component.refs.pasteComponent) {\n const pasteToolTip = this.attachTooltip(component.refs.pasteComponent, this.t('Paste below'));\n component.addEventListener(component.refs.pasteComponent, 'click', () => {\n pasteToolTip.hide();\n this.pasteComponent(component);\n });\n }\n if (component.refs.moveComponent) {\n this.attachTooltip(component.refs.moveComponent, this.t('Move'));\n if (this.keyboardActionsEnabled) {\n component.addEventListener(component.refs.moveComponent, 'click', () => {\n this.moveComponent(component);\n });\n }\n }\n const parent = this.getParentElement(element);\n if (component.refs.editComponent) {\n this.attachTooltip(component.refs.editComponent, this.t('Edit'));\n component.addEventListener(component.refs.editComponent, 'click', () => this.editComponent(component.schema, parent, false, false, component.component, { inDataGrid: component.isInDataGrid }));\n }\n if (component.refs.editJson) {\n this.attachTooltip(component.refs.editJson, this.t('Edit JSON'));\n component.addEventListener(component.refs.editJson, 'click', () => this.editComponent(component.schema, parent, false, true, component.component));\n }\n if (component.refs.removeComponent) {\n this.attachTooltip(component.refs.removeComponent, this.t('Remove'));\n component.addEventListener(component.refs.removeComponent, 'click', () => this.removeComponent(component.schema, parent, component.component));\n }\n return element;\n }\n createForm(options) {\n this.webform = new Webform_1.default(this.element, options);\n if (this.element) {\n this.loadRefs(this.element, {\n form: 'single'\n });\n if (this.refs.form) {\n this.webform.element = this.refs.form;\n }\n }\n return this.webform;\n }\n /**\n * Called when everything is ready.\n *\n * @returns {Promise} - Wait for webform to be ready.\n */\n get ready() {\n return this.webform.ready;\n }\n get defaultGroups() {\n return {\n basic: {\n title: 'Basic',\n weight: 0,\n default: true,\n },\n advanced: {\n title: 'Advanced',\n weight: 10\n },\n layout: {\n title: 'Layout',\n weight: 20\n },\n data: {\n title: 'Data',\n weight: 30\n },\n premium: {\n title: 'Premium',\n weight: 40\n }\n };\n }\n redraw() {\n return Webform_1.default.prototype.redraw.call(this);\n }\n get form() {\n return this.webform.form;\n }\n get schema() {\n return this.webform.schema;\n }\n set form(value) {\n this.setForm(value);\n }\n get container() {\n return this.webform.form.components;\n }\n /**\n * When a component sets its api key, we need to check if it is unique within its namespace. Find the namespace root\n * so we can calculate this correctly.\n * @param component\n */\n findNamespaceRoot(component) {\n const path = (0, utils_1.getArrayFromComponentPath)(component.path);\n // First get the component with nested parents.\n let comp = this.webform.getComponent(path);\n comp = Array.isArray(comp) ? comp[0] : comp;\n const namespaceKey = this.recurseNamespace(comp);\n // If there is no key, it is the root form.\n if (!namespaceKey || this.form.key === namespaceKey) {\n return this.form.components;\n }\n const componentSchema = component.component;\n // If the current component is the namespace, we don't need to find it again.\n if (namespaceKey === component.key) {\n return [...componentSchema.components, componentSchema];\n }\n // Get the namespace component so we have the original object.\n const namespaceComponent = (0, formUtils_1.getComponent)(this.form.components, namespaceKey, true);\n return namespaceComponent ? namespaceComponent.components : comp.components;\n }\n recurseNamespace(component) {\n // If there is no parent, we are at the root level.\n if (!component) {\n return null;\n }\n // Some components are their own namespace.\n if (['address', 'container', 'datagrid', 'editgrid', 'dynamicWizard', 'tree'].includes(component.type) || component.tree || component.arrayTree) {\n return component.key;\n }\n // Anything else, keep going up.\n return this.recurseNamespace(component.parent);\n }\n render() {\n return this.renderTemplate('builder', {\n sidebar: this.renderTemplate('builderSidebar', {\n scrollEnabled: this.sideBarScroll,\n groupOrder: this.groupOrder,\n groupId: `builder-sidebar-${this.id}`,\n groups: this.groupOrder.map((groupKey) => this.renderTemplate('builderSidebarGroup', {\n group: this.groups[groupKey],\n groupKey,\n groupId: `builder-sidebar-${this.id}`,\n subgroups: this.groups[groupKey].subgroups.map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n keyboardActionsEnabled: this.keyboardActionsEnabled,\n })),\n }),\n form: this.webform.render(),\n });\n }\n attach(element) {\n this.on('change', (form) => {\n this.populateRecaptchaSettings(form);\n });\n return super.attach(element).then(() => {\n this.loadRefs(element, {\n form: 'single',\n sidebar: 'single',\n 'sidebar-search': 'single',\n 'sidebar-groups': 'single',\n 'container': 'multiple',\n 'sidebar-anchor': 'multiple',\n 'sidebar-group': 'multiple',\n 'sidebar-container': 'multiple',\n 'sidebar-component': 'multiple',\n });\n if (this.sideBarScroll && Templates_1.default.current.handleBuilderSidebarScroll) {\n Templates_1.default.current.handleBuilderSidebarScroll.call(this, this);\n }\n // Add the paste status in form\n if (typeof window !== 'undefined' && window.sessionStorage) {\n const data = window.sessionStorage.getItem('formio.clipboard');\n if (data) {\n this.addClass(this.refs.form, 'builder-paste-mode');\n }\n }\n if (!(0, utils_1.bootstrapVersion)(this.options)) {\n const getAttribute = (anchor, attribute) => {\n let elem = anchor.getAttribute(`data-${attribute}`);\n if (!elem) {\n elem = anchor.getAttribute(`data-bs-${attribute}`);\n }\n return elem;\n };\n const hideShow = (group, show) => {\n if (show) {\n group.classList.add(['show']);\n group.style.display = 'inherit';\n }\n else {\n group.classList.remove(['show']);\n group.style.display = 'none';\n }\n };\n // Initialize\n this.refs['sidebar-group'].forEach((group) => {\n hideShow(group, getAttribute(group, 'default') === 'true');\n });\n // Click event\n this.refs['sidebar-anchor'].forEach((anchor, index) => {\n this.addEventListener(anchor, 'click', () => {\n const clickedParentId = getAttribute(anchor, 'parent').slice('#builder-sidebar-'.length);\n const clickedId = getAttribute(anchor, 'target').slice('#group-'.length);\n this.refs['sidebar-group'].forEach((group, groupIndex) => {\n const openByDefault = getAttribute(group, 'default') === 'true';\n const groupId = group.getAttribute('id').slice('group-'.length);\n const groupParent = getAttribute(group, 'parent').slice('#builder-sidebar-'.length);\n hideShow(group, ((openByDefault && groupParent === clickedId) || groupId === clickedParentId || groupIndex === index));\n });\n }, true);\n });\n }\n if (this.keyboardActionsEnabled) {\n this.refs['sidebar-component'].forEach((component) => {\n this.addEventListener(component, 'keydown', (event) => {\n if (event.keyCode === 13) {\n this.addNewComponent(component);\n }\n });\n });\n }\n this.addEventListener(this.refs['sidebar-search'], 'input', lodash_1.default.debounce((e) => {\n const searchString = e.target.value;\n this.searchFields(searchString);\n }, 300));\n if (this.dragDropEnabled) {\n this.initDragula();\n }\n const drake = this.dragula;\n if (this.refs.form) {\n (0, dom_autoscroller_1.default)([window], {\n margin: 20,\n maxSpeed: 6,\n scrollWhenOutside: true,\n autoScroll: function () {\n return this.down && (drake === null || drake === void 0 ? void 0 : drake.dragging);\n }\n });\n return this.webform.attach(this.refs.form);\n }\n });\n }\n searchFields(searchString = '') {\n const searchValue = searchString.toLowerCase();\n const sidebar = this.refs['sidebar'];\n const sidebarGroups = this.refs['sidebar-groups'];\n if (!sidebar || !sidebarGroups) {\n return;\n }\n const filterGroupBy = (group, searchValue = '') => {\n const result = lodash_1.default.toPlainObject(group);\n const { subgroups = [], components } = result;\n const filteredComponents = [];\n for (const key in components) {\n const isMatchedToTitle = this.t(components[key].title).toLowerCase().match(searchValue);\n const isMatchedToKey = components[key].key.toLowerCase().match(searchValue);\n if (isMatchedToTitle || isMatchedToKey) {\n filteredComponents.push(components[key]);\n }\n }\n this.orderComponents(result, filteredComponents);\n if (searchValue) {\n result.default = true;\n }\n if (result.componentOrder.length || subgroups.length) {\n return result;\n }\n return null;\n };\n const filterGroupOrder = (groupOrder, searchValue) => {\n const result = lodash_1.default.cloneDeep(groupOrder);\n return result.filter(key => filterGroupBy(this.groups[key], searchValue));\n };\n const filterSubgroups = (groups, searchValue) => {\n const result = lodash_1.default.clone(groups);\n return result\n .map(subgroup => filterGroupBy(subgroup, searchValue))\n .filter(subgroup => !lodash_1.default.isNull(subgroup));\n };\n const toTemplate = groupKey => {\n return {\n group: filterGroupBy(this.groups[groupKey], searchValue),\n groupKey,\n groupId: sidebar.id || sidebarGroups.id,\n subgroups: filterSubgroups(this.groups[groupKey].subgroups, searchValue)\n .map((group) => this.renderTemplate('builderSidebarGroup', {\n group,\n groupKey: group.key,\n groupId: `group-container-${groupKey}`,\n subgroups: []\n })),\n };\n };\n sidebarGroups.innerHTML = filterGroupOrder(this.groupOrder, searchValue)\n .map(groupKey => this.renderTemplate('builderSidebarGroup', toTemplate(groupKey)))\n .join('');\n this.loadRefs(this.element, {\n 'sidebar-groups': 'single',\n 'sidebar-anchor': 'multiple',\n 'sidebar-group': 'multiple',\n 'sidebar-container': 'multiple',\n });\n this.updateDragAndDrop();\n if (searchValue === '') {\n this.triggerRedraw();\n }\n }\n orderComponents(groupInfo, foundComponents) {\n const components = foundComponents || groupInfo.components;\n const isResource = groupInfo.key.indexOf('resource-') === 0;\n if (components) {\n groupInfo.componentOrder = Object.keys(components)\n .map(key => components[key])\n .filter(component => component && !component.ignore && !component.ignoreForForm)\n .sort((a, b) => a.weight - b.weight)\n .map(component => isResource ? `component-${component.key}` : component.key);\n }\n }\n updateDragAndDrop() {\n if (this.dragDropEnabled) {\n this.initDragula();\n }\n if (this.refs.form) {\n return this.webform.attach(this.refs.form);\n }\n }\n initDragula() {\n const options = this.options;\n if (this.dragula) {\n this.dragula.destroy();\n }\n const containersArray = Array.prototype.slice.call(this.refs['sidebar-container']).filter(item => {\n return item.id !== 'group-container-resource';\n });\n if (!dragula_min_js_1.default) {\n return;\n }\n this.dragula = (0, dragula_min_js_1.default)(containersArray, {\n moves(el) {\n let moves = true;\n const list = Array.from(el.classList).filter(item => item.indexOf('formio-component-') === 0);\n list.forEach(item => {\n const key = item.slice('formio-component-'.length);\n if (options.disabled && options.disabled.includes(key)) {\n moves = false;\n }\n });\n if (el.classList.contains('no-drag')) {\n moves = false;\n }\n return moves;\n },\n copy(el) {\n return el.classList.contains('drag-copy');\n },\n accepts(el, target) {\n return !el.contains(target) && !target.classList.contains('no-drop');\n }\n }).on('drop', (element, target, source, sibling) => this.onDrop(element, target, source, sibling));\n }\n detach() {\n if (this.dragula) {\n this.dragula.destroy();\n }\n this.dragula = null;\n if (this.sideBarScroll && Templates_1.default.current.clearBuilderSidebarScroll) {\n Templates_1.default.current.clearBuilderSidebarScroll.call(this, this);\n }\n super.detach();\n }\n getComponentInfo(key, group) {\n let info;\n // Need to check in first order as resource component key can be the same as from webform default components\n if (group && group.slice(0, group.indexOf('-')) === 'resource') {\n // This is an existing resource field.\n const resourceGroups = this.groups.resource.subgroups;\n const resourceGroup = lodash_1.default.find(resourceGroups, { key: group });\n if (resourceGroup && resourceGroup.components.hasOwnProperty(`component-${key}`)) {\n info = (0, utils_1.fastCloneDeep)(resourceGroup.components[`component-${key}`].schema);\n }\n }\n // This is a new component\n else if (this.schemas.hasOwnProperty(key)) {\n info = (0, utils_1.fastCloneDeep)(this.schemas[key]);\n }\n else if (this.groups.hasOwnProperty(group)) {\n const groupComponents = this.groups[group].components;\n if (groupComponents.hasOwnProperty(key)) {\n info = (0, utils_1.fastCloneDeep)(groupComponents[key].schema);\n }\n }\n else if (group === 'searchFields') { //Search components go into this group\n const resourceGroups = this.groups.resource.subgroups;\n for (let ix = 0; ix < resourceGroups.length; ix++) {\n const resourceGroup = resourceGroups[ix];\n if (resourceGroup.components.hasOwnProperty(`component-${key}`)) {\n info = (0, utils_1.fastCloneDeep)(resourceGroup.components[`component-${key}`].schema);\n break;\n }\n }\n }\n if (info) {\n info.key = this.generateKey(info);\n }\n return info;\n }\n getComponentsPath(component, parent) {\n // Get path to the component in the parent component.\n let path = 'components';\n let columnIndex = 0;\n let tableRowIndex = 0;\n let tableColumnIndex = 0;\n let tabIndex = 0;\n switch (parent.type) {\n case 'table':\n tableRowIndex = lodash_1.default.findIndex(parent.rows, row => row.some(column => column.components.some(comp => comp.key === component.key)));\n tableColumnIndex = lodash_1.default.findIndex(parent.rows[tableRowIndex], (column => column.components.some(comp => comp.key === component.key)));\n path = `rows[${tableRowIndex}][${tableColumnIndex}].components`;\n break;\n case 'columns':\n columnIndex = lodash_1.default.findIndex(parent.columns, column => column.components.some(comp => comp.key === component.key));\n path = `columns[${columnIndex}].components`;\n break;\n case 'tabs':\n tabIndex = lodash_1.default.findIndex(parent.components, tab => tab.components.some(comp => comp.key === component.key));\n path = `components[${tabIndex}].components`;\n break;\n }\n return path;\n }\n /* eslint-disable max-statements */\n onDrop(element, target, source, sibling) {\n var _a;\n if (!target) {\n return;\n }\n // If you try to drop within itself.\n if (element.contains(target)) {\n return;\n }\n const key = element.getAttribute('data-key');\n const type = element.getAttribute('data-type');\n const group = element.getAttribute('data-group');\n let info, isNew, path, index;\n if (key && group) {\n // This is a new component.\n info = this.getComponentInfo(key, group);\n if (!info && type) {\n info = this.getComponentInfo(type, group);\n }\n isNew = true;\n }\n else if (source.formioContainer) {\n index = lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key });\n if (index !== -1) {\n // Grab and remove the component from the source container.\n info = source.formioContainer.splice(lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key }), 1);\n // Since splice returns an array of one object, we need to destructure it.\n info = info[0];\n }\n }\n // If we haven't found the component, stop.\n if (!info) {\n return;\n }\n // Show an error if siblings are disabled for a component and such a component already exists.\n const compKey = (group === 'resource') ? `component-${key}` : key;\n const draggableComponent = ((_a = this.groups[group]) === null || _a === void 0 ? void 0 : _a.components[compKey]) || {};\n if (draggableComponent.disableSiblings) {\n let isCompAlreadyExists = false;\n (0, formUtils_1.eachComponent)(this.webform.components, (component) => {\n if (component.type === draggableComponent.schema.type) {\n isCompAlreadyExists = true;\n return;\n }\n }, true);\n if (isCompAlreadyExists) {\n this.webform.redraw();\n this.webform.setAlert('danger', `You cannot add more than one ${draggableComponent.key} component to one page.`);\n return;\n }\n }\n if (target !== source) {\n // Ensure the key remains unique in its new container.\n builder_1.default.uniquify(this.findNamespaceRoot(target.formioComponent), info);\n }\n const parent = target.formioComponent;\n // Insert in the new container.\n if (target.formioContainer) {\n if (sibling) {\n if (!sibling.getAttribute('data-noattach')) {\n index = lodash_1.default.findIndex(target.formioContainer, { key: lodash_1.default.get(sibling, 'formioComponent.component.key') });\n index = (index === -1) ? 0 : index;\n }\n else {\n index = sibling.getAttribute('data-position');\n }\n if (index !== -1) {\n target.formioContainer.splice(index, 0, info);\n }\n }\n else {\n target.formioContainer.push(info);\n }\n path = this.getComponentsPath(info, parent.component);\n index = lodash_1.default.findIndex(lodash_1.default.get(parent.schema, path), { key: info.key });\n if (index === -1) {\n index = 0;\n }\n }\n if (parent && parent.addChildComponent) {\n parent.addChildComponent(info, element, target, source, sibling);\n }\n const componentInDataGrid = parent.type === 'datagrid';\n if (isNew && !this.options.noNewEdit && !info.noNewEdit) {\n this.editComponent(info, target, isNew, null, null, { inDataGrid: componentInDataGrid });\n }\n // Only rebuild the parts needing to be rebuilt.\n let rebuild;\n if (target !== source) {\n if (source.formioContainer && source.contains(target)) {\n rebuild = source.formioComponent.rebuild();\n }\n else if (target.contains(source)) {\n rebuild = target.formioComponent.rebuild();\n }\n else {\n if (source.formioContainer) {\n rebuild = source.formioComponent.rebuild();\n }\n rebuild = target.formioComponent.rebuild();\n }\n }\n else {\n // If they are the same, only rebuild one.\n rebuild = target.formioComponent.rebuild();\n }\n if (!rebuild) {\n rebuild = Promise.resolve();\n }\n return rebuild.then(() => {\n this.emit('addComponent', info, parent, path, index, isNew && !this.options.noNewEdit && !info.noNewEdit);\n if (!isNew || this.options.noNewEdit || info.noNewEdit) {\n this.emit('change', this.form);\n }\n });\n }\n setForm(form) {\n var _a;\n if (!form.components) {\n form.components = [];\n }\n if (form && form.properties) {\n this.options.properties = form.properties;\n }\n this.keyboardActionsEnabled = lodash_1.default.get(this.options, 'keyboardBuilder', false) || ((_a = this.options.properties) === null || _a === void 0 ? void 0 : _a.keyboardBuilder);\n const isShowSubmitButton = !this.options.noDefaultSubmitButton\n && (!form.components.length || !form.components.find(comp => comp.key === 'submit'));\n // Ensure there is at least a submit button.\n if (isShowSubmitButton) {\n form.components.push({\n type: 'button',\n label: 'Submit',\n key: 'submit',\n size: 'md',\n block: false,\n action: 'submit',\n disableOnInvalid: true,\n theme: 'primary'\n });\n }\n if (this.webform) {\n const shouldRebuild = !this.webform.form.components ||\n (form.components.length !== this.webform.form.components.length);\n return this.webform.setForm(form, { keepAsReference: true }).then(() => {\n if (this.refs.form) {\n this.builderHeight = this.refs.form.offsetHeight;\n }\n if (!shouldRebuild) {\n return this.form;\n }\n return this.rebuild().then(() => this.form);\n });\n }\n return Promise.resolve(form);\n }\n populateRecaptchaSettings(form) {\n //populate isEnabled for recaptcha form settings\n let isRecaptchaEnabled = false;\n if (this.form.components) {\n (0, formUtils_1.eachComponent)(form.components, component => {\n if (isRecaptchaEnabled) {\n return;\n }\n if (component.type === 'recaptcha') {\n isRecaptchaEnabled = true;\n return false;\n }\n });\n if (isRecaptchaEnabled) {\n lodash_1.default.set(form, 'settings.recaptcha.isEnabled', true);\n }\n else if (lodash_1.default.get(form, 'settings.recaptcha.isEnabled')) {\n lodash_1.default.set(form, 'settings.recaptcha.isEnabled', false);\n }\n }\n }\n removeComponent(component, parent, original) {\n if (!parent) {\n return;\n }\n let remove = true;\n const removingComponentsGroup = !component.skipRemoveConfirm &&\n ((Array.isArray(component.components) && component.components.length) ||\n (Array.isArray(component.rows) && component.rows.length) ||\n (Array.isArray(component.columns) && component.columns.length));\n if (this.options.alwaysConfirmComponentRemoval || removingComponentsGroup) {\n const message = removingComponentsGroup ? 'Removing this component will also remove all of its children. Are you sure you want to do this?'\n : 'Are you sure you want to remove this component?';\n remove = window.confirm(this.t(message));\n }\n if (!original) {\n original = parent.formioContainer.find((comp) => comp.id === component.id);\n }\n const index = parent.formioContainer ? parent.formioContainer.indexOf(original) : 0;\n if (remove && index !== -1) {\n const path = this.getComponentsPath(component, parent.formioComponent.component);\n if (parent.formioContainer) {\n parent.formioContainer.splice(index, 1);\n }\n else if (parent.formioComponent && parent.formioComponent.removeChildComponent) {\n parent.formioComponent.removeChildComponent(component);\n }\n const rebuild = parent.formioComponent.rebuild() || Promise.resolve();\n rebuild.then(() => {\n this.emit('removeComponent', component, parent.formioComponent.schema, path, index);\n this.emit('change', this.form);\n });\n }\n return remove;\n }\n replaceDoubleQuotes(data, fieldsToRemoveDoubleQuotes = []) {\n if (data) {\n fieldsToRemoveDoubleQuotes.forEach((key) => {\n if (data[key]) {\n data[key] = data[key].replace(/\"/g, \"'\");\n }\n });\n return data;\n }\n }\n updateComponent(component, changed) {\n // Update the preview.\n if (this.preview) {\n this.preview.form = {\n components: [lodash_1.default.omit(Object.assign({}, component), [\n 'hidden',\n 'conditional',\n 'calculateValue',\n 'logic',\n 'autofocus',\n 'customConditional',\n ])],\n config: this.options.formConfig || {}\n };\n const fieldsToRemoveDoubleQuotes = ['label', 'tooltip'];\n this.preview.form.components.forEach(component => this.replaceDoubleQuotes(component, fieldsToRemoveDoubleQuotes));\n const previewElement = this.componentEdit.querySelector('[ref=\"preview\"]');\n if (previewElement) {\n this.setContent(previewElement, this.preview.render());\n this.preview.attach(previewElement);\n }\n }\n // Change the \"default value\" field to be reflective of this component.\n const defaultValueComponent = (0, formUtils_1.getComponent)(this.editForm.components, 'defaultValue', true);\n if (defaultValueComponent && component.type !== 'hidden') {\n const defaultChanged = changed && ((changed.component && changed.component.key === 'defaultValue')\n || (changed.instance && defaultValueComponent.hasComponent && defaultValueComponent.hasComponent(changed.instance)));\n if (!defaultChanged) {\n lodash_1.default.assign(defaultValueComponent.component, lodash_1.default.omit(Object.assign({}, component), [\n 'key',\n 'label',\n 'labelPosition',\n 'labelMargin',\n 'labelWidth',\n 'placeholder',\n 'tooltip',\n 'hidden',\n 'autofocus',\n 'validate',\n 'disabled',\n 'defaultValue',\n 'customDefaultValue',\n 'calculateValue',\n 'conditional',\n 'customConditional',\n 'id'\n ]));\n const parentComponent = defaultValueComponent.parent;\n let tabIndex = -1;\n let index = -1;\n parentComponent.tabs.some((tab, tIndex) => {\n tab.some((comp, compIndex) => {\n if (comp.id === defaultValueComponent.id) {\n tabIndex = tIndex;\n index = compIndex;\n return true;\n }\n return false;\n });\n });\n if (tabIndex !== -1 && index !== -1 && changed && !lodash_1.default.isNil(changed.value)) {\n const sibling = parentComponent.tabs[tabIndex][index + 1];\n parentComponent.removeComponent(defaultValueComponent);\n const newComp = parentComponent.addComponent(defaultValueComponent.component, defaultValueComponent.data, sibling);\n lodash_1.default.pull(newComp.validators, 'required');\n parentComponent.tabs[tabIndex].splice(index, 1, newComp);\n newComp.checkValidity = () => true;\n newComp.build(defaultValueComponent.element);\n }\n }\n else {\n let dataPath = changed.instance._data.key;\n const path = (0, utils_1.getArrayFromComponentPath)(changed.instance.path);\n path.shift();\n if (path.length) {\n path.unshift(component.key);\n dataPath = (0, utils_1.getStringFromComponentPath)(path);\n }\n lodash_1.default.set(this.preview._data, dataPath, changed.value);\n lodash_1.default.set(this.webform._data, dataPath, changed.value);\n }\n }\n // Called when we update a component.\n this.emit('updateComponent', component);\n }\n findRepeatablePaths() {\n const repeatablePaths = [];\n const keys = new Map();\n (0, formUtils_1.eachComponent)(this.form.components, (comp, path) => {\n if (!comp.key) {\n return;\n }\n if (keys.has(comp.key)) {\n if (keys.get(comp.key).includes(path)) {\n repeatablePaths.push(path);\n }\n else {\n keys.set(comp.key, [...keys.get(comp.key), path]);\n }\n }\n else {\n keys.set(comp.key, [path]);\n }\n }, true);\n return repeatablePaths;\n }\n highlightInvalidComponents() {\n const repeatablePaths = this.findRepeatablePaths();\n let hasInvalidComponents = false;\n this.webform.everyComponent((comp) => {\n var _a, _b;\n const path = comp.path;\n if (repeatablePaths.includes(path)) {\n comp.setCustomValidity(`API Key is not unique: ${comp.key}`);\n hasInvalidComponents = true;\n }\n else if ((_b = (_a = comp.error) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.startsWith('API Key is not unique')) {\n comp.setCustomValidity('');\n }\n });\n this.emit('builderFormValidityChange', hasInvalidComponents);\n }\n /**\n * Called when a new component is saved.\n *\n * @param parent\n * @param component\n * @return {boolean}\n */\n saveComponent(component, parent, isNew, original) {\n this.editForm.detach();\n const parentContainer = parent ? parent.formioContainer : this.container;\n const parentComponent = parent ? parent.formioComponent : this;\n this.dialog.close();\n const path = parentContainer ? this.getComponentsPath(component, parentComponent.component) : '';\n if (!original) {\n original = parent.formioContainer.find((comp) => comp.id === component.id);\n }\n const index = parentContainer ? parentContainer.indexOf(original) : 0;\n if (index !== -1) {\n let submissionData = this.editForm.submission.data;\n submissionData = submissionData.componentJson || submissionData;\n const fieldsToRemoveDoubleQuotes = ['label', 'tooltip'];\n this.replaceDoubleQuotes(submissionData, fieldsToRemoveDoubleQuotes);\n this.hook('beforeSaveComponentSettings', submissionData);\n let comp = null;\n parentComponent.getComponents().forEach((component) => {\n if (component.component.key === original.key) {\n comp = component;\n }\n });\n const originalComp = comp.component;\n const originalComponentSchema = comp.schema;\n const isParentSaveChildMethod = this.isParentSaveChildMethod(parent.formioComponent);\n if (parentContainer && !isParentSaveChildMethod) {\n parentContainer[index] = submissionData;\n if (comp) {\n comp.component = submissionData;\n }\n }\n else if (isParentSaveChildMethod) {\n parent.formioComponent.saveChildComponent(submissionData);\n }\n const rebuild = parentComponent.rebuild() || Promise.resolve();\n return rebuild.then(() => {\n const schema = parentContainer ? parentContainer[index] : (comp ? comp.schema : []);\n this.emitSaveComponentEvent(schema, originalComp, parentComponent.schema, path, index, isNew, originalComponentSchema);\n this.emit('change', this.form);\n this.highlightInvalidComponents();\n if (this.isComponentCreated) {\n const component = parent.formioComponent.components[0];\n this.moveComponent(component);\n this.isComponentCreated = false;\n }\n });\n }\n this.highlightInvalidComponents();\n return Promise.resolve();\n }\n emitSaveComponentEvent(schema, originalComp, parentComponentSchema, path, index, isNew, originalComponentSchema) {\n this.emit('saveComponent', schema, originalComp, parentComponentSchema, path, index, isNew, originalComponentSchema);\n }\n attachEditComponentControls(component, parent, isNew, original, ComponentClass) {\n const cancelButtons = this.componentEdit.querySelectorAll('[ref=\"cancelButton\"]');\n cancelButtons.forEach((cancelButton) => {\n this.editForm.addEventListener(cancelButton, 'click', (event) => {\n event.preventDefault();\n this.editForm.detach();\n this.emit('cancelComponent', component);\n this.dialog.close();\n this.highlightInvalidComponents();\n });\n });\n const removeButtons = this.componentEdit.querySelectorAll('[ref=\"removeButton\"]');\n removeButtons.forEach((removeButton) => {\n this.editForm.addEventListener(removeButton, 'click', (event) => {\n event.preventDefault();\n // Since we are already removing the component, don't trigger another remove.\n this.saved = true;\n this.editForm.detach();\n this.removeComponent(component, parent, original);\n this.dialog.close();\n this.highlightInvalidComponents();\n });\n });\n const saveButtons = this.componentEdit.querySelectorAll('[ref=\"saveButton\"]');\n saveButtons.forEach((saveButton) => {\n this.editForm.addEventListener(saveButton, 'click', (event) => {\n event.preventDefault();\n if (!this.editForm.checkValidity(this.editForm.data, true, this.editForm.data)) {\n this.editForm.setPristine(false);\n this.editForm.showErrors();\n return false;\n }\n this.saved = true;\n this.saveComponent(component, parent, isNew, original);\n });\n });\n const previewButtons = this.componentEdit.querySelectorAll('[ref=\"previewButton\"]');\n previewButtons.forEach((previewButton) => {\n this.editForm.addEventListener(previewButton, 'click', (event) => {\n event.preventDefault();\n this.showPreview = !this.showPreview;\n this.editForm.detach();\n this.setContent(this.componentEdit, this.renderTemplate('builderEditForm', {\n componentInfo: ComponentClass.builderInfo,\n editForm: this.editForm.render(),\n preview: this.preview ? this.preview.render() : false,\n showPreview: this.showPreview,\n helplinks: this.helplinks,\n }));\n this.editForm.attach(this.componentEdit.querySelector('[ref=\"editForm\"]'));\n this.attachEditComponentControls(component, parent, isNew, original, ComponentClass);\n });\n });\n }\n editComponent(component, parent, isNew, isJsonEdit, original, flags = {}) {\n var _a;\n if (!component.key) {\n return;\n }\n this.saved = false;\n const componentCopy = (0, utils_1.fastCloneDeep)(component);\n let ComponentClass = Components_1.default.components[componentCopy.type];\n const isCustom = ComponentClass === undefined;\n isJsonEdit = isJsonEdit || isCustom;\n ComponentClass = isCustom ? Components_1.default.components.unknown : ComponentClass;\n // Make sure we only have one dialog open at a time.\n if (this.dialog) {\n this.dialog.close();\n this.highlightInvalidComponents();\n }\n // This is the render step.\n const editFormOptions = lodash_1.default.clone(lodash_1.default.get(this, 'options.editForm', {}));\n if (this.editForm) {\n this.editForm.destroy();\n }\n // Allow editForm overrides per component.\n const overrides = lodash_1.default.get(this.options, `editForm.${componentCopy.type}`, {});\n // Pass along the form being edited.\n editFormOptions.editForm = this.form;\n editFormOptions.editComponent = component;\n editFormOptions.flags = flags;\n this.hook('editComponentParentInstance', editFormOptions, parent);\n this.editForm = new Webform_1.default(Object.assign(Object.assign(Object.assign({}, lodash_1.default.omit(this.options, ['hooks', 'builder', 'events', 'attachMode', 'skipInit'])), { language: this.options.language }), editFormOptions));\n this.hook('editFormProperties', parent);\n this.editForm.form = (isJsonEdit && !isCustom) ? {\n components: [\n {\n type: 'textarea',\n as: 'json',\n editor: 'ace',\n weight: 10,\n input: true,\n key: 'componentJson',\n label: 'Component JSON',\n tooltip: 'Edit the JSON for this component.'\n },\n {\n type: 'checkbox',\n key: 'showFullSchema',\n label: 'Full Schema'\n }\n ]\n } : ComponentClass.editForm(lodash_1.default.cloneDeep(overrides));\n const instanceOptions = {\n inFormBuilder: true,\n };\n this.hook('instanceOptionsPreview', instanceOptions);\n const instance = new ComponentClass(componentCopy, instanceOptions);\n const schema = this.hook('builderComponentSchema', component, instance);\n this.editForm.submission = isJsonEdit ? {\n data: {\n componentJson: schema,\n showFullSchema: this.options.showFullJsonSchema\n },\n } : {\n data: instance.component,\n };\n if (this.preview) {\n this.preview.destroy();\n }\n if (!ComponentClass.builderInfo.hasOwnProperty('preview') || ComponentClass.builderInfo.preview) {\n this.preview = new Webform_1.default(lodash_1.default.omit(Object.assign(Object.assign({}, this.options), { preview: true }), [\n 'hooks',\n 'builder',\n 'events',\n 'attachMode',\n 'calculateValue'\n ]));\n this.hook('previewFormSettitngs', schema, isJsonEdit);\n }\n this.showPreview = (_a = ComponentClass.builderInfo.showPreview) !== null && _a !== void 0 ? _a : true;\n this.componentEdit = this.ce('div', { 'class': 'component-edit-container' });\n this.setContent(this.componentEdit, this.renderTemplate('builderEditForm', {\n componentInfo: ComponentClass.builderInfo,\n editForm: this.editForm.render(),\n preview: this.preview ? this.preview.render() : false,\n showPreview: this.showPreview,\n helplinks: this.helplinks\n }));\n this.dialog = this.createModal(this.componentEdit, lodash_1.default.get(this.options, 'dialogAttr', {}));\n // This is the attach step.\n this.editForm.attach(this.componentEdit.querySelector('[ref=\"editForm\"]'));\n this.hook('editFormWrapper');\n this.updateComponent(componentCopy);\n this.editForm.on('change', (event) => {\n if (event.changed) {\n if (event.changed.component && event.changed.component.key === 'showFullSchema') {\n const { value } = event.changed;\n this.editForm.submission = {\n data: {\n componentJson: value ? instance.component : component,\n showFullSchema: value\n },\n };\n return;\n }\n // See if this is a manually modified key. Treat custom component keys as manually modified\n if ((event.changed.component && (event.changed.component.key === 'key')) || isJsonEdit) {\n componentCopy.keyModified = true;\n }\n let isComponentLabelChanged = false;\n if (event.changed.instance) {\n isComponentLabelChanged = ['label', 'title'].includes(event.changed.instance.path);\n }\n else if (event.changed.component) {\n isComponentLabelChanged = ['label', 'title'].includes(event.changed.component.key);\n }\n if (isComponentLabelChanged) {\n // Ensure this component has a key.\n if (isNew) {\n if (!event.data.keyModified) {\n this.editForm.everyComponent(component => {\n if (component.key === 'key' && component.parent.component.key === 'tabs') {\n component.setValue(this.updateComponentKey(event.data));\n return false;\n }\n });\n }\n if (this.form) {\n let formComponents = this.findNamespaceRoot(parent.formioComponent);\n // excluding component which key uniqueness is to be checked to prevent the comparing of the same keys\n formComponents = formComponents.filter(comp => editFormOptions.editComponent.id !== comp.id);\n // Set a unique key for this component.\n builder_1.default.uniquify(formComponents, event.data);\n }\n }\n }\n // Update the component.\n this.updateComponent(event.data.componentJson || event.data, event.changed);\n }\n });\n this.attachEditComponentControls(component, parent, isNew, original, ComponentClass);\n const dialogClose = () => {\n this.editForm.destroy(true);\n if (this.preview) {\n this.preview.destroy(true);\n this.preview = null;\n }\n if (isNew && !this.saved) {\n this.removeComponent(component, parent, original);\n this.highlightInvalidComponents();\n }\n // Clean up.\n this.removeEventListener(this.dialog, 'close', dialogClose);\n this.dialog = null;\n };\n this.addEventListener(this.dialog, 'close', dialogClose);\n // Called when we edit a component.\n this.emit('editComponent', component);\n }\n updateComponentKey(data) {\n return lodash_1.default.camelCase(data.title ||\n data.label ||\n data.placeholder ||\n data.type).replace(/^[0-9]*/, '');\n }\n moveComponent(component) {\n var _a;\n if (this.selectedComponent) {\n const prevSelected = this.selectedComponent;\n (_a = prevSelected.element) === null || _a === void 0 ? void 0 : _a.classList.remove('builder-component-selected');\n this.removeEventListener(document, 'keydown');\n }\n component.element.focus();\n component.element.classList.add('builder-component-selected');\n this.selectedComponent = component;\n this.addEventListener(document, 'keydown', this.moveHandler.bind(this));\n }\n updateComponentPlacement(direction) {\n const component = this.selectedComponent;\n let index, info;\n const step = direction ? -1 : 1;\n if (component) {\n const element = component.element;\n const sibling = direction ? element.previousElementSibling : element.nextElementSibling;\n const source = element.parentNode;\n const containerLength = source.formioContainer.length;\n if (containerLength && containerLength <= 1) {\n return;\n }\n if (source.formioContainer) {\n index = lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key });\n if (index !== -1) {\n info = source.formioContainer.splice(lodash_1.default.findIndex(source.formioContainer, { key: element.formioComponent.component.key }), 1);\n info = info[0];\n source.removeChild(element);\n }\n }\n const len = source.formioComponent.components.length;\n index = (index === -1) ? 0 : index + step;\n if (index === -1) {\n source.formioContainer.push(info);\n source.appendChild(element);\n }\n else if (index === len) {\n const key = source.formioContainer[0].key;\n index = lodash_1.default.findIndex(source.formioComponent.components, { key: key });\n const firstElement = source.formioComponent.components[index].element;\n source.formioContainer.splice(0, 0, info);\n source.insertBefore(element, firstElement);\n }\n else if (index !== -1) {\n source.formioContainer.splice(index, 0, info);\n direction\n ? source.insertBefore(element, sibling)\n : source.insertBefore(element, sibling.nextElementSibling);\n }\n element.focus();\n }\n }\n stopMoving(comp) {\n const parent = comp.element.parentNode;\n this.removeEventListener(document, 'keydown');\n parent.formioComponent.rebuild();\n this.selectedComponent = null;\n }\n addNewComponent(element) {\n var _a;\n const source = document.querySelector('.formio-builder-form');\n const key = element.getAttribute('data-key');\n const group = element.getAttribute('data-group');\n const isNew = true;\n let info;\n if (key && group) {\n info = this.getComponentInfo(key, group);\n }\n if (isNew && !this.options.noNewEdit && !info.noNewEdit) {\n builder_1.default.uniquify(this.findNamespaceRoot(source.formioComponent), info);\n this.editComponent(info, source, isNew, null, null);\n }\n const firstComponent = (_a = source.formioComponent.components[0]) === null || _a === void 0 ? void 0 : _a.element;\n if (firstComponent) {\n source.formioContainer.splice(0, 0, info);\n }\n else {\n source.formioContainer.push(info);\n }\n source.formioComponent.rebuild().then(() => {\n this.isComponentCreated = true;\n });\n }\n /**\n * Creates copy of component schema and stores it under sessionStorage.\n * @param {Component} component\n * @return {*}\n */\n copyComponent(component) {\n if (!window.sessionStorage) {\n return console.warn('Session storage is not supported in this browser.');\n }\n this.addClass(this.refs.form, 'builder-paste-mode');\n window.sessionStorage.setItem('formio.clipboard', JSON.stringify(component.schema));\n }\n /**\n * Paste copied component after the current component.\n * @param {Component} component\n * @return {*}\n */\n pasteComponent(component) {\n if (!window.sessionStorage) {\n return console.warn('Session storage is not supported in this browser.');\n }\n this.removeClass(this.refs.form, 'builder-paste-mode');\n if (window.sessionStorage) {\n const data = window.sessionStorage.getItem('formio.clipboard');\n if (data) {\n const schema = JSON.parse(data);\n const parent = this.getParentElement(component.element);\n if (parent) {\n builder_1.default.uniquify(this.findNamespaceRoot(parent.formioComponent), schema);\n let path = '';\n let index = 0;\n const isParentSaveChildMethod = this.isParentSaveChildMethod(parent.formioComponent);\n if (parent.formioContainer && !isParentSaveChildMethod) {\n index = parent.formioContainer.indexOf(component.component);\n path = this.getComponentsPath(schema, parent.formioComponent.component);\n parent.formioContainer.splice(index + 1, 0, schema);\n }\n else if (isParentSaveChildMethod) {\n parent.formioComponent.saveChildComponent(schema, false);\n }\n parent.formioComponent.rebuild();\n this.emitSaveComponentEvent(schema, schema, parent.formioComponent.component, path, (index + 1), true, schema);\n }\n this.emit('change', this.form);\n }\n }\n }\n isParentSaveChildMethod(parentComp) {\n return !!(parentComp && parentComp.saveChildComponent);\n }\n getParentElement(element) {\n let container = element;\n do {\n container = container.parentNode;\n } while (container && !container.formioComponent);\n return container;\n }\n addBuilderComponentInfo(component) {\n if (!component || !component.group || !this.groups[component.group]) {\n return;\n }\n component = lodash_1.default.clone(component);\n const groupInfo = this.groups[component.group];\n if (!groupInfo.components.hasOwnProperty(component.key)) {\n groupInfo.components[component.key] = component;\n }\n return component;\n }\n init() {\n if (this.webform) {\n this.webform.init();\n }\n return super.init();\n }\n clear() {\n if (this.webform.initialized) {\n this.webform.clear();\n }\n }\n destroy(all = false) {\n if (this.webform.initialized) {\n this.webform.destroy(all);\n }\n super.destroy(all);\n }\n addBuilderGroup(name, group) {\n if (!this.groups[name]) {\n this.groups[name] = group;\n this.groupOrder.push(name);\n this.triggerRedraw();\n }\n else {\n this.updateBuilderGroup(name, group);\n }\n }\n updateBuilderGroup(name, group) {\n if (this.groups[name]) {\n this.groups[name] = group;\n this.triggerRedraw();\n }\n }\n generateKey(info) {\n return info.key || lodash_1.default.camelCase(info.title ||\n info.label ||\n info.placeholder ||\n info.type);\n }\n}\nexports[\"default\"] = WebformBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/WebformBuilder.js?");
5350
5339
 
5351
5340
  /***/ }),
5352
5341
 
@@ -5610,7 +5599,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
5610
5599
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5611
5600
 
5612
5601
  "use strict";
5613
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Field_1 = __importDefault(__webpack_require__(/*! ../field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../../Formio */ \"./lib/cjs/Formio.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nclass ListComponent extends Field_1.default {\n static schema(...extend) {\n return Field_1.default.schema({\n dataSrc: 'values',\n authenticate: false,\n ignoreCache: false,\n template: '<span>{{ item.label }}</span>',\n validate: {\n onlyAvailableItems: false\n },\n }, ...extend);\n }\n get isSelectURL() {\n return this.component.dataSrc === 'url';\n }\n get selectData() {\n const selectData = lodash_1.default.get(this.root, 'submission.metadata.selectData', {});\n return lodash_1.default.get(selectData, this.path);\n }\n get shouldLoad() {\n if (this.loadingError) {\n return false;\n }\n // Live forms should always load.\n if (!this.options.readOnly) {\n return true;\n }\n // If there are template keys, then we need to see if we have the data.\n if (this.templateKeys && this.templateKeys.length) {\n // See if we already have the data we need.\n const dataValue = this.dataValue;\n const selectData = this.selectData;\n return this.templateKeys.reduce((shouldLoad, key) => {\n const hasValue = lodash_1.default.has(dataValue, key) ||\n (lodash_1.default.isArray(selectData) ? selectData.every((data) => lodash_1.default.has(data, key)) : lodash_1.default.has(selectData, key));\n return shouldLoad || !hasValue;\n }, false);\n }\n // Return that we should load.\n return true;\n }\n getTemplateKeys() {\n this.templateKeys = [];\n if (this.options.readOnly && this.component.template) {\n const keys = this.component.template.match(/({{\\s*(.*?)\\s*}})/g);\n if (keys) {\n keys.forEach((key) => {\n const propKey = key.match(/{{\\s*item\\.(.*?)\\s*}}/);\n if (propKey && propKey.length > 1) {\n this.templateKeys.push(propKey[1]);\n }\n });\n }\n }\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 // Must be implemented in child classes.\n setItems() { }\n updateCustomItems() { }\n loadItems() { }\n getOptionTemplate(data, value) {\n if (!this.component.template) {\n return data.label;\n }\n const options = {\n noeval: true,\n data: {}\n };\n const template = this.sanitize(this.component.template\n ? this.interpolate(this.component.template, { item: data }, options)\n : data.label, this.shouldSanitizeValue);\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (templateValue && !lodash_1.default.isObject(templateValue) && options.data.item) {\n // If the value is not an object, then we need to save the template data off for when it is selected.\n this.templateData[templateValue] = options.data.item;\n }\n return template;\n }\n itemTemplate(data, value) {\n if (lodash_1.default.isEmpty(data)) {\n return '';\n }\n const template = this.sanitize(this.getOptionTemplate(data, value), this.shouldSanitizeValue);\n if (template) {\n const label = template.replace(/<\\/?[^>]+(>|$)/g, '');\n if (!label)\n return;\n return template.replace(label, this.t(label, { _userInput: true }));\n }\n else {\n return this.sanitize(JSON.stringify(data), this.shouldSanitizeValue);\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 /* eslint-disable max-statements */\n updateItems(searchInput, forceUpdate) {\n if (!this.component.data) {\n console.warn(`Select component ${this.key} does not have data configuration.`);\n this.itemsLoadedResolve();\n return;\n }\n // Only load the data if it is visible.\n if (!this.visible) {\n this.itemsLoadedResolve();\n return;\n }\n switch (this.component.dataSrc) {\n case 'values':\n this.setItems(this.component.data.values);\n break;\n case 'json':\n this.setItems(this.component.data.json);\n break;\n case 'custom':\n this.updateCustomItems(forceUpdate);\n break;\n case 'resource': {\n // If there is no resource, or we are lazyLoading, wait until active.\n if (!this.component.data.resource || (!forceUpdate && !this.active)) {\n this.itemsLoadedResolve();\n return;\n }\n let resourceUrl = this.options.formio ? this.options.formio.formsUrl : `${Formio_1.Formio.getProjectUrl()}/form`;\n resourceUrl += (`/${this.component.data.resource}/submission`);\n if (forceUpdate || this.additionalResourcesAvailable || !this.serverCount) {\n try {\n this.loadItems(resourceUrl, searchInput, this.requestHeaders);\n }\n catch (err) {\n console.warn(`Unable to load resources for ${this.key}`);\n }\n }\n else {\n this.setItems(this.downloadedResources);\n }\n break;\n }\n case 'url': {\n if (!forceUpdate && !this.active && !this.calculatedValue && this.component.type === 'select') {\n // If we are lazyLoading, wait until activated.\n this.itemsLoadedResolve();\n return;\n }\n let { url } = this.component.data;\n let method;\n let body;\n if (url.startsWith('/')) {\n // if URL starts with '/project', we should use base URL to avoid issues with URL formed like <base_url>/<project_name>/project/<project_id>/...\n const baseUrl = url.startsWith('/project') ? Formio_1.Formio.getBaseUrl() : Formio_1.Formio.getProjectUrl() || Formio_1.Formio.getBaseUrl();\n url = baseUrl + url;\n }\n if (!this.component.data.method) {\n method = 'GET';\n }\n else {\n method = this.component.data.method;\n if (method.toUpperCase() === 'POST') {\n body = this.component.data.body;\n }\n else {\n body = null;\n }\n }\n const options = this.component.authenticate ? {} : { noToken: true };\n this.loadItems(url, searchInput, this.requestHeaders, options, method, body);\n break;\n }\n case 'indexeddb': {\n if (typeof window === 'undefined') {\n return;\n }\n if (!window.indexedDB) {\n window.alert(\"Your browser doesn't support current version of indexedDB\");\n }\n if (this.component.indexeddb && this.component.indexeddb.database && this.component.indexeddb.table) {\n const request = window.indexedDB.open(this.component.indexeddb.database);\n request.onupgradeneeded = (event) => {\n if (this.component.customOptions) {\n const db = event.target.result;\n const objectStore = db.createObjectStore(this.component.indexeddb.table, { keyPath: 'myKey', autoIncrement: true });\n objectStore.transaction.oncomplete = () => {\n const transaction = db.transaction(this.component.indexeddb.table, 'readwrite');\n this.component.customOptions.forEach((item) => {\n transaction.objectStore(this.component.indexeddb.table).put(item);\n });\n };\n }\n };\n request.onerror = () => {\n window.alert(request.errorCode);\n };\n request.onsuccess = (event) => {\n const db = event.target.result;\n const transaction = db.transaction(this.component.indexeddb.table, 'readwrite');\n const objectStore = transaction.objectStore(this.component.indexeddb.table);\n new Promise((resolve) => {\n const responseItems = [];\n objectStore.getAll().onsuccess = (event) => {\n event.target.result.forEach((item) => {\n responseItems.push(item);\n });\n resolve(responseItems);\n };\n }).then((items) => {\n if (!lodash_1.default.isEmpty(this.component.indexeddb.filter)) {\n items = lodash_1.default.filter(items, this.component.indexeddb.filter);\n }\n this.setItems(items);\n });\n };\n }\n }\n }\n }\n}\nexports[\"default\"] = ListComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/_classes/list/ListComponent.js?");
5602
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Field_1 = __importDefault(__webpack_require__(/*! ../field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../../Formio */ \"./lib/cjs/Formio.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nclass ListComponent extends Field_1.default {\n static schema(...extend) {\n return Field_1.default.schema({\n dataSrc: 'values',\n authenticate: false,\n ignoreCache: false,\n template: '<span>{{ item.label }}</span>',\n validate: {\n onlyAvailableItems: false\n },\n }, ...extend);\n }\n get isSelectURL() {\n return this.component.dataSrc === 'url';\n }\n get selectData() {\n const selectData = lodash_1.default.get(this.root, 'submission.metadata.selectData', {});\n return lodash_1.default.get(selectData, this.path);\n }\n get shouldLoad() {\n if (this.loadingError) {\n return false;\n }\n // Live forms should always load.\n if (!this.options.readOnly) {\n return true;\n }\n // If there are template keys, then we need to see if we have the data.\n if (this.templateKeys && this.templateKeys.length) {\n // See if we already have the data we need.\n const dataValue = this.dataValue;\n const selectData = this.selectData;\n return this.templateKeys.reduce((shouldLoad, key) => {\n const hasValue = lodash_1.default.has(dataValue, key) ||\n (lodash_1.default.isArray(selectData) ? selectData.every((data) => lodash_1.default.has(data, key)) : lodash_1.default.has(selectData, key));\n return shouldLoad || !hasValue;\n }, false);\n }\n // Return that we should load.\n return true;\n }\n getTemplateKeys() {\n this.templateKeys = [];\n if (this.options.readOnly && this.component.template) {\n const keys = this.component.template.match(/({{\\s*(.*?)\\s*}})/g);\n if (keys) {\n keys.forEach((key) => {\n const propKey = key.match(/{{\\s*item\\.(.*?)\\s*}}/);\n if (propKey && propKey.length > 1) {\n this.templateKeys.push(propKey[1]);\n }\n });\n }\n }\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 // Must be implemented in child classes.\n setItems() { }\n updateCustomItems() { }\n loadItems() { }\n getOptionTemplate(data, value, index) {\n if (!this.component.template) {\n return data.label;\n }\n const options = {\n noeval: true,\n data: {}\n };\n const template = this.sanitize(this.component.template\n ? this.interpolate(this.component.template, { item: data }, options)\n : data.label, this.shouldSanitizeValue);\n const templateValue = this.component.reference && (value === null || value === void 0 ? void 0 : value._id) ? value._id.toString() : value;\n if (templateValue && !lodash_1.default.isObject(templateValue) && options.data.item) {\n // If the value is not an object, then we need to save the template data off for when it is selected.\n this.templateData[templateValue] = options.data.item;\n }\n if (lodash_1.default.isNumber(index)) {\n this.templateData[index] = options.data.item;\n }\n return template;\n }\n itemTemplate(data, value, index) {\n if (lodash_1.default.isEmpty(data)) {\n return '';\n }\n const template = this.sanitize(this.getOptionTemplate(data, value, index), this.shouldSanitizeValue);\n if (template) {\n const label = template.replace(/<\\/?[^>]+(>|$)/g, '');\n if (!label)\n return;\n return template.replace(label, this.t(label, { _userInput: true }));\n }\n else {\n return this.sanitize(JSON.stringify(data), this.shouldSanitizeValue);\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 /* eslint-disable max-statements */\n updateItems(searchInput, forceUpdate) {\n if (!this.component.data) {\n console.warn(`Select component ${this.key} does not have data configuration.`);\n this.itemsLoadedResolve();\n return;\n }\n // Only load the data if it is visible.\n if (!this.visible) {\n this.itemsLoadedResolve();\n return;\n }\n switch (this.component.dataSrc) {\n case 'values':\n this.setItems(this.component.data.values);\n break;\n case 'json':\n this.setItems(this.component.data.json);\n break;\n case 'custom':\n this.updateCustomItems(forceUpdate);\n break;\n case 'resource': {\n // If there is no resource, or we are lazyLoading, wait until active.\n if (!this.component.data.resource || (!forceUpdate && !this.active)) {\n this.itemsLoadedResolve();\n return;\n }\n let resourceUrl = this.options.formio ? this.options.formio.formsUrl : `${Formio_1.Formio.getProjectUrl()}/form`;\n resourceUrl += (`/${this.component.data.resource}/submission`);\n if (forceUpdate || this.additionalResourcesAvailable || !this.serverCount) {\n try {\n this.loadItems(resourceUrl, searchInput, this.requestHeaders);\n }\n catch (err) {\n console.warn(`Unable to load resources for ${this.key}`);\n }\n }\n else {\n this.setItems(this.downloadedResources);\n }\n break;\n }\n case 'url': {\n if (!forceUpdate && !this.active && !this.calculatedValue && this.component.type === 'select') {\n // If we are lazyLoading, wait until activated.\n this.itemsLoadedResolve();\n return;\n }\n let { url } = this.component.data;\n let method;\n let body;\n if (url.startsWith('/')) {\n // if URL starts with '/project', we should use base URL to avoid issues with URL formed like <base_url>/<project_name>/project/<project_id>/...\n const baseUrl = url.startsWith('/project') ? Formio_1.Formio.getBaseUrl() : Formio_1.Formio.getProjectUrl() || Formio_1.Formio.getBaseUrl();\n url = baseUrl + url;\n }\n if (!this.component.data.method) {\n method = 'GET';\n }\n else {\n method = this.component.data.method;\n if (method.toUpperCase() === 'POST') {\n body = this.component.data.body;\n }\n else {\n body = null;\n }\n }\n const options = this.component.authenticate ? {} : { noToken: true };\n this.loadItems(url, searchInput, this.requestHeaders, options, method, body);\n break;\n }\n case 'indexeddb': {\n if (typeof window === 'undefined') {\n return;\n }\n if (!window.indexedDB) {\n window.alert(\"Your browser doesn't support current version of indexedDB\");\n }\n if (this.component.indexeddb && this.component.indexeddb.database && this.component.indexeddb.table) {\n const request = window.indexedDB.open(this.component.indexeddb.database);\n request.onupgradeneeded = (event) => {\n if (this.component.customOptions) {\n const db = event.target.result;\n const objectStore = db.createObjectStore(this.component.indexeddb.table, { keyPath: 'myKey', autoIncrement: true });\n objectStore.transaction.oncomplete = () => {\n const transaction = db.transaction(this.component.indexeddb.table, 'readwrite');\n this.component.customOptions.forEach((item) => {\n transaction.objectStore(this.component.indexeddb.table).put(item);\n });\n };\n }\n };\n request.onerror = () => {\n window.alert(request.errorCode);\n };\n request.onsuccess = (event) => {\n const db = event.target.result;\n const transaction = db.transaction(this.component.indexeddb.table, 'readwrite');\n const objectStore = transaction.objectStore(this.component.indexeddb.table);\n new Promise((resolve) => {\n const responseItems = [];\n objectStore.getAll().onsuccess = (event) => {\n event.target.result.forEach((item) => {\n responseItems.push(item);\n });\n resolve(responseItems);\n };\n }).then((items) => {\n if (!lodash_1.default.isEmpty(this.component.indexeddb.filter)) {\n items = lodash_1.default.filter(items, this.component.indexeddb.filter);\n }\n this.setItems(items);\n });\n };\n }\n }\n }\n }\n}\nexports[\"default\"] = ListComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/_classes/list/ListComponent.js?");
5614
5603
 
5615
5604
  /***/ }),
5616
5605
 
@@ -6842,7 +6831,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6842
6831
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6843
6832
 
6844
6833
  "use strict";
6845
- 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 ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass RadioComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'radio',\n inputType: 'radio',\n label: 'Radio',\n key: 'radio',\n values: [{ label: '', value: '' }],\n data: {\n url: '',\n },\n fieldSet: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Radio',\n group: 'basic',\n icon: 'dot-circle-o',\n weight: 80,\n documentation: '/userguide/form-building/form-components#radio',\n schema: RadioComponent.schema()\n };\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return {\n type: 'select',\n dataSrc: 'custom',\n valueProperty: 'value',\n dataType: classComp.dataType || '',\n data: {\n custom() {\n return classComp.values;\n }\n },\n };\n } });\n }\n static savedValueTypes(schema) {\n const { boolean, string, number, object, array } = utils_1.componentValueTypes;\n const { dataType } = schema;\n const types = (0, utils_1.getComponentSavedTypes)(schema);\n if (types) {\n return types;\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 constructor(component, options, data) {\n super(component, options, data);\n this.previousValue = this.dataValue || null;\n }\n get defaultSchema() {\n return RadioComponent.schema();\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && this.component.defaultValue === false) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n get inputInfo() {\n var _a;\n const info = super.elementInfo();\n info.type = 'input';\n info.changeEvent = 'click';\n info.attr.class = 'form-check-input';\n info.attr.name = info.attr.name += `[${(_a = this.root) === null || _a === void 0 ? void 0 : _a.id}-${this.id}]`;\n return info;\n }\n get emptyValue() {\n return '';\n }\n get isRadio() {\n return this.component.inputType === 'radio';\n }\n get optionSelectedClass() {\n return 'radio-selected';\n }\n get listData() {\n const listData = lodash_1.default.get(this.root, 'submission.metadata.listData', {});\n return lodash_1.default.get(listData, this.path);\n }\n init() {\n super.init();\n this.templateData = {};\n this.validators = this.validators.concat(['select', 'onlyAvailableItems', 'availableValueProperty']);\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 this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n this.optionsLoaded = false;\n this.loadedOptions = [];\n // Get the template keys for this radio component.\n this.getTemplateKeys();\n }\n render() {\n return super.render(this.renderTemplate('radio', {\n input: this.inputInfo,\n inline: this.component.inline,\n values: this.component.dataSrc === 'values' ? this.component.values : this.loadedOptions,\n value: this.dataValue,\n row: this.row,\n }));\n }\n attach(element) {\n this.loadRefs(element, { input: 'multiple', wrapper: 'multiple' });\n this.refs.input.forEach((input, index) => {\n this.addEventListener(input, this.inputInfo.changeEvent, () => {\n this.updateValue(null, {\n modified: true,\n });\n });\n if (this.component.values[index]) {\n this.addShortcut(input, this.component.values[index].shortcut);\n }\n if (this.isRadio) {\n let dataValue = this.dataValue;\n if (!lodash_1.default.isString(this.dataValue)) {\n dataValue = lodash_1.default.toString(this.dataValue);\n }\n input.checked = (dataValue === input.value && (input.value || this.component.dataSrc !== 'url'));\n this.addEventListener(input, 'keyup', (event) => {\n if (event.key === ' ' && dataValue === input.value) {\n event.preventDefault();\n this.updateValue(null, {\n modified: true,\n });\n }\n });\n }\n });\n this.triggerUpdate();\n this.setSelectedClasses();\n return super.attach(element);\n }\n detach(element) {\n if (element && this.refs.input) {\n this.refs.input.forEach((input, index) => {\n if (this.component.values[index]) {\n this.removeShortcut(input, this.component.values[index].shortcut);\n }\n });\n }\n super.detach();\n }\n getValue() {\n if (this.viewOnly || !this.refs.input || !this.refs.input.length) {\n return this.dataValue;\n }\n let value = this.dataValue;\n this.refs.input.forEach((input) => {\n if (input.checked) {\n value = input.value;\n }\n });\n return value;\n }\n validateValueProperty() {\n if (this.component.dataSrc === 'values') {\n return true;\n }\n return !lodash_1.default.some(this.refs.wrapper, (wrapper, index) => this.refs.input[index].checked && this.loadedOptions[index].invalid);\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => this.normalizeValue(optionValue) === value) !== -1;\n }\n return false;\n }\n getValueAsString(value) {\n if (!lodash_1.default.isString(value)) {\n value = lodash_1.default.toString(value);\n }\n if (this.component.dataSrc !== 'values') {\n return value;\n }\n const option = lodash_1.default.find(this.component.values, (v) => v.value === value);\n if (!value) {\n return lodash_1.default.get(option, 'label', '');\n }\n return lodash_1.default.get(option, 'label', '');\n }\n setValueAt(index, value) {\n if (this.refs.input && this.refs.input[index] && value !== null && value !== undefined) {\n const inputValue = this.refs.input[index].value;\n this.refs.input[index].checked = (inputValue === value.toString());\n }\n }\n loadItems(url, search, headers, options, method, body) {\n if (this.optionsLoaded) {\n return;\n }\n if (!this.shouldLoad) {\n this.loadItemsFromMetadata();\n return;\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 // 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.error = null;\n this.setItems(response);\n this.optionsLoaded = true;\n this.redraw();\n })\n .catch((err) => {\n this.handleLoadingError(err);\n });\n }\n loadItemsFromMetadata() {\n this.listData.forEach((item, i) => {\n this.loadedOptions[i] = {\n label: this.itemTemplate(item)\n };\n if (lodash_1.default.isEqual(item, this.selectData)) {\n this.loadedOptions[i].value = this.dataValue;\n }\n });\n this.optionsLoaded = true;\n this.redraw();\n }\n setItems(items) {\n const listData = [];\n items === null || items === void 0 ? void 0 : items.forEach((item, i) => {\n this.loadedOptions[i] = {\n value: item[this.component.valueProperty],\n label: this.itemTemplate(item, item[this.component.valueProperty])\n };\n listData.push(this.templateData[item[this.component.valueProperty]]);\n if (lodash_1.default.isUndefined(item[this.component.valueProperty]) ||\n lodash_1.default.isObject(item[this.component.valueProperty]) ||\n (!this.isRadio && lodash_1.default.isBoolean(item[this.component.valueProperty]))) {\n this.loadedOptions[i].invalid = true;\n }\n });\n if (this.isSelectURL) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.listData) {\n submission.metadata.listData = {};\n }\n lodash_1.default.set(submission.metadata.listData, this.path, listData);\n }\n }\n setSelectedClasses() {\n if (this.refs.wrapper) {\n //add/remove selected option class\n const value = this.dataValue;\n this.refs.wrapper.forEach((wrapper, index) => {\n const input = this.refs.input[index];\n const checked = (input.type === 'checkbox') ? value[input.value] : (input.value.toString() === value.toString());\n if (checked) {\n //add class to container when selected\n this.addClass(wrapper, this.optionSelectedClass);\n //change \"checked\" attribute\n input.setAttribute('checked', 'true');\n }\n else {\n this.removeClass(wrapper, this.optionSelectedClass);\n input.removeAttribute('checked');\n }\n });\n }\n }\n updateValue(value, flags) {\n const changed = super.updateValue(value, flags);\n if (changed) {\n this.setSelectedClasses();\n }\n if (!flags || !flags.modified || !this.isRadio) {\n if (changed) {\n this.previousValue = this.dataValue;\n }\n return changed;\n }\n // If they clicked on the radio that is currently selected, it needs to reset the value.\n this.currentValue = this.dataValue;\n const shouldResetValue = flags && flags.modified && !flags.noUpdateEvent && this.previousValue === this.currentValue;\n if (shouldResetValue) {\n this.resetValue();\n this.triggerChange(flags);\n this.setSelectedClasses();\n }\n this.previousValue = this.dataValue;\n return changed;\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (value === this.emptyValue) {\n return value;\n }\n if (!isNaN(parseFloat(value)) && isFinite(value)) {\n value = +value;\n }\n if (value === 'true') {\n value = true;\n }\n if (value === 'false') {\n value = false;\n }\n if (this.isSelectURL && this.templateData && this.templateData[value]) {\n const submission = this.root.submission;\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, this.templateData[value]);\n }\n return super.normalizeValue(value);\n }\n}\nexports[\"default\"] = RadioComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/radio/Radio.js?");
6834
+ 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 ListComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/list/ListComponent */ \"./lib/cjs/components/_classes/list/ListComponent.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass RadioComponent extends ListComponent_1.default {\n static schema(...extend) {\n return ListComponent_1.default.schema({\n type: 'radio',\n inputType: 'radio',\n label: 'Radio',\n key: 'radio',\n values: [{ label: '', value: '' }],\n data: {\n url: '',\n },\n fieldSet: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Radio',\n group: 'basic',\n icon: 'dot-circle-o',\n weight: 80,\n documentation: '/userguide/form-building/form-components#radio',\n schema: RadioComponent.schema()\n };\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return {\n type: 'select',\n dataSrc: 'custom',\n valueProperty: 'value',\n dataType: classComp.dataType || '',\n data: {\n custom() {\n return classComp.values;\n }\n },\n };\n } });\n }\n static savedValueTypes(schema) {\n const { boolean, string, number, object, array } = utils_1.componentValueTypes;\n const { dataType } = schema;\n const types = (0, utils_1.getComponentSavedTypes)(schema);\n if (types) {\n return types;\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 constructor(component, options, data) {\n super(component, options, data);\n this.previousValue = this.dataValue || null;\n }\n get defaultSchema() {\n return RadioComponent.schema();\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (!defaultValue && this.component.defaultValue === false) {\n defaultValue = this.component.defaultValue;\n }\n return defaultValue;\n }\n get inputInfo() {\n var _a;\n const info = super.elementInfo();\n info.type = 'input';\n info.changeEvent = 'click';\n info.attr.class = 'form-check-input';\n info.attr.name = info.attr.name += `[${(_a = this.root) === null || _a === void 0 ? void 0 : _a.id}-${this.id}]`;\n return info;\n }\n get emptyValue() {\n return '';\n }\n get isRadio() {\n return this.component.inputType === 'radio';\n }\n get optionSelectedClass() {\n return 'radio-selected';\n }\n get listData() {\n const listData = lodash_1.default.get(this.root, 'submission.metadata.listData', {});\n return lodash_1.default.get(listData, this.path);\n }\n init() {\n super.init();\n this.templateData = {};\n this.validators = this.validators.concat(['select', 'onlyAvailableItems', 'availableValueProperty']);\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 this.itemsLoaded = new Promise((resolve) => {\n this.itemsLoadedResolve = resolve;\n });\n this.optionsLoaded = false;\n this.loadedOptions = [];\n // Get the template keys for this radio component.\n this.getTemplateKeys();\n }\n render() {\n return super.render(this.renderTemplate('radio', {\n input: this.inputInfo,\n inline: this.component.inline,\n values: this.component.dataSrc === 'values' ? this.component.values : this.loadedOptions,\n value: this.dataValue,\n row: this.row,\n }));\n }\n attach(element) {\n this.loadRefs(element, { input: 'multiple', wrapper: 'multiple' });\n this.refs.input.forEach((input, index) => {\n this.addEventListener(input, this.inputInfo.changeEvent, () => {\n this.updateValue(null, {\n modified: true,\n });\n });\n if (this.component.values[index]) {\n this.addShortcut(input, this.component.values[index].shortcut);\n }\n if (this.isRadio) {\n let dataValue = this.dataValue;\n if (!lodash_1.default.isString(this.dataValue)) {\n dataValue = lodash_1.default.toString(this.dataValue);\n }\n if (this.isSelectURL && lodash_1.default.isObject(this.loadedOptions[index].value)) {\n input.checked = lodash_1.default.isEqual(this.loadedOptions[index].value, this.dataValue);\n }\n else {\n input.checked = (dataValue === input.value && (input.value || this.component.dataSrc !== 'url'));\n }\n this.addEventListener(input, 'keyup', (event) => {\n if (event.key === ' ' && dataValue === input.value) {\n event.preventDefault();\n this.updateValue(null, {\n modified: true,\n });\n }\n });\n }\n });\n this.triggerUpdate();\n this.setSelectedClasses();\n return super.attach(element);\n }\n detach(element) {\n if (element && this.refs.input) {\n this.refs.input.forEach((input, index) => {\n if (this.component.values[index]) {\n this.removeShortcut(input, this.component.values[index].shortcut);\n }\n });\n }\n super.detach();\n }\n getValue() {\n if (this.viewOnly || !this.refs.input || !this.refs.input.length) {\n return this.dataValue;\n }\n let value = this.dataValue;\n this.refs.input.forEach((input, index) => {\n if (input.checked) {\n value = (this.isSelectURL && lodash_1.default.isObject(this.loadedOptions[index].value)) ?\n this.loadedOptions[index].value :\n input.value;\n }\n });\n return value;\n }\n validateValueProperty() {\n if (this.component.dataSrc === 'values') {\n return true;\n }\n return !lodash_1.default.some(this.refs.wrapper, (wrapper, index) => this.refs.input[index].checked && this.loadedOptions[index].invalid);\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => this.normalizeValue(optionValue) === value) !== -1;\n }\n return false;\n }\n getValueAsString(value) {\n if (lodash_1.default.isObject(value)) {\n value = JSON.stringify(value);\n }\n else if (!lodash_1.default.isString(value)) {\n value = lodash_1.default.toString(value);\n }\n if (this.component.dataSrc !== 'values') {\n return value;\n }\n const option = lodash_1.default.find(this.component.values, (v) => v.value === value);\n if (!value) {\n return lodash_1.default.get(option, 'label', '');\n }\n return lodash_1.default.get(option, 'label', '');\n }\n setValueAt(index, value) {\n if (this.refs.input && this.refs.input[index] && value !== null && value !== undefined) {\n const inputValue = this.refs.input[index].value;\n this.refs.input[index].checked = (inputValue === value.toString());\n }\n }\n loadItems(url, search, headers, options, method, body) {\n if (this.optionsLoaded) {\n return;\n }\n if (!this.shouldLoad && this.listData) {\n this.loadItemsFromMetadata();\n return;\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 // 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.error = null;\n this.setItems(response);\n this.optionsLoaded = true;\n this.redraw();\n })\n .catch((err) => {\n this.handleLoadingError(err);\n });\n }\n loadItemsFromMetadata() {\n this.listData.forEach((item, i) => {\n this.loadedOptions[i] = {\n label: this.itemTemplate(item)\n };\n if (lodash_1.default.isEqual(item, this.selectData || lodash_1.default.pick(this.dataValue, lodash_1.default.keys(item)))) {\n this.loadedOptions[i].value = this.dataValue;\n }\n });\n this.optionsLoaded = true;\n this.redraw();\n }\n setItems(items) {\n const listData = [];\n items === null || items === void 0 ? void 0 : items.forEach((item, i) => {\n this.loadedOptions[i] = {\n value: this.component.valueProperty ? item[this.component.valueProperty] : item,\n label: this.component.valueProperty ? this.itemTemplate(item, item[this.component.valueProperty]) : this.itemTemplate(item, item, i)\n };\n listData.push(this.templateData[this.component.valueProperty ? item[this.component.valueProperty] : i]);\n if ((this.component.valueProperty || !this.isRadio) && (lodash_1.default.isUndefined(item[this.component.valueProperty]) ||\n (!this.isRadio && lodash_1.default.isObject(item[this.component.valueProperty])) ||\n (!this.isRadio && lodash_1.default.isBoolean(item[this.component.valueProperty])))) {\n this.loadedOptions[i].invalid = true;\n }\n });\n if (this.isSelectURL) {\n const submission = this.root.submission;\n if (!submission.metadata) {\n submission.metadata = {};\n }\n if (!submission.metadata.listData) {\n submission.metadata.listData = {};\n }\n lodash_1.default.set(submission.metadata.listData, this.path, listData);\n }\n }\n setSelectedClasses() {\n if (this.refs.wrapper) {\n //add/remove selected option class\n const value = this.dataValue;\n this.refs.wrapper.forEach((wrapper, index) => {\n const input = this.refs.input[index];\n const checked = (input.type === 'checkbox') ? value[input.value] : (input.value.toString() === value.toString());\n if (checked) {\n //add class to container when selected\n this.addClass(wrapper, this.optionSelectedClass);\n //change \"checked\" attribute\n input.setAttribute('checked', 'true');\n }\n else {\n this.removeClass(wrapper, this.optionSelectedClass);\n input.removeAttribute('checked');\n }\n });\n }\n }\n updateValue(value, flags) {\n const changed = super.updateValue(value, flags);\n if (changed) {\n this.setSelectedClasses();\n }\n if (!flags || !flags.modified || !this.isRadio) {\n if (changed) {\n this.previousValue = this.dataValue;\n }\n return changed;\n }\n // If they clicked on the radio that is currently selected, it needs to reset the value.\n this.currentValue = this.dataValue;\n const shouldResetValue = flags && flags.modified && !flags.noUpdateEvent && this.previousValue === this.currentValue;\n if (shouldResetValue) {\n this.resetValue();\n this.triggerChange(flags);\n this.setSelectedClasses();\n }\n this.previousValue = this.dataValue;\n return changed;\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (value === this.emptyValue) {\n return value;\n }\n if (!isNaN(parseFloat(value)) && isFinite(value)) {\n value = +value;\n }\n if (value === 'true') {\n value = true;\n }\n if (value === 'false') {\n value = false;\n }\n if (this.isSelectURL && this.templateData && this.templateData[value]) {\n const submission = this.root.submission;\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n lodash_1.default.set(submission.metadata.selectData, this.path, this.templateData[value]);\n }\n return super.normalizeValue(value);\n }\n}\nexports[\"default\"] = RadioComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/radio/Radio.js?");
6846
6835
 
6847
6836
  /***/ }),
6848
6837
 
@@ -6963,7 +6952,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
6963
6952
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6964
6953
 
6965
6954
  "use strict";
6966
- 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 return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return Object.assign(Object.assign({}, classComp), { type: 'select' });\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 this.validators = this.validators.concat(['select', 'onlyAvailableItems']);\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 if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get dataReady() {\n // If the root submission has been set, and we are still not attached, then assume\n // that our data is ready.\n if (this.root &&\n this.root.submissionSet &&\n !this.attached) {\n return Promise.resolve();\n }\n return this.itemsLoaded;\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 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 if (this.component.multiple && lodash_1.default.isArray(this.dataValue) ? this.dataValue.find((val) => value === val) : (this.dataValue === value)) {\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 *\n * @param value\n * @param label\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 // 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 && typeof this.component.onSetItems === 'function') {\n const newItems = this.component.onSetItems(this, 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()) {\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.error = null;\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 */\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.selectOptions || []);\n }\n this.focusableElement = input;\n this.addEventListener(input, 'focus', () => this.update());\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 }\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(updateComponent, 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', () => this.update());\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 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 /**\n * @param {*} value\n * @param {Array} items\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) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map(this.asString.bind(this)).join(', ')\n : this.asString(data);\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, retainObject) {\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 if (retainObject) {\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 (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 }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\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.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue, true));\n }\n return super.normalizeValue(this.normalizeSingleValue(value, true));\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\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 const changed = this.updateValue(value, flags);\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 if (this.component.multiple && Array.isArray(value)) {\n value = value.map(value => {\n if (typeof value === 'boolean' || typeof value === 'number') {\n return value.toString();\n }\n return value;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n value = value.toString();\n }\n }\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 get itemsLoaded() {\n return this._itemsLoaded || Promise.resolve();\n }\n set itemsLoaded(promise) {\n this._itemsLoaded = promise;\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, true);\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\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}\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 }\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 *\n * @return {boolean}\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 * @return {*}\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) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\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 {\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 => {\n if (this.isBooleanOrNumber(item)) {\n item = item.toString();\n }\n });\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\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 if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(this.itemTemplate(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 return !lodash_1.default.isNil(value)\n ? this.itemTemplate(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 if (this.focusableElement) {\n super.focus.call(this);\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?");
6955
+ 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 return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return Object.assign(Object.assign({}, classComp), { type: 'select' });\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 this.validators = this.validators.concat(['select', 'onlyAvailableItems']);\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 if (this.isHtmlRenderMode()) {\n this.activate();\n }\n // Get the template keys for this select component.\n this.getTemplateKeys();\n }\n get dataReady() {\n // If the root submission has been set, and we are still not attached, then assume\n // that our data is ready.\n if (this.root &&\n this.root.submissionSet &&\n !this.attached) {\n return Promise.resolve();\n }\n return this.itemsLoaded;\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 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 if (this.component.multiple && lodash_1.default.isArray(this.dataValue) ? this.dataValue.find((val) => value === val) : (this.dataValue === value)) {\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 *\n * @param value\n * @param label\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 // 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 && typeof this.component.onSetItems === 'function') {\n const newItems = this.component.onSetItems(this, 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.error = null;\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 */\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.selectOptions || []);\n }\n this.focusableElement = input;\n this.addEventListener(input, 'focus', () => this.update());\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 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(updateComponent, 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', () => this.update());\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 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 /**\n * @param {*} value\n * @param {Array} items\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) {\n return (this.component.multiple && Array.isArray(data))\n ? data.map(this.asString.bind(this)).join(', ')\n : this.asString(data);\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, retainObject) {\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 if (retainObject) {\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 (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 }\n lodash_1.default.set(submission.metadata.selectData, this.path, templateData);\n }\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.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n if (this.component.multiple && Array.isArray(value)) {\n return value.map((singleValue) => this.normalizeSingleValue(singleValue, true));\n }\n return super.normalizeValue(this.normalizeSingleValue(value, true));\n }\n setValue(value, flags = {}) {\n const previousValue = this.dataValue;\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 const changed = this.updateValue(value, flags);\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 if (this.component.multiple && Array.isArray(value)) {\n value = value.map(value => {\n if (typeof value === 'boolean' || typeof value === 'number') {\n return value.toString();\n }\n return value;\n });\n }\n else {\n if (typeof value === 'boolean' || typeof value === 'number') {\n value = value.toString();\n }\n }\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 get itemsLoaded() {\n return this._itemsLoaded || Promise.resolve();\n }\n set itemsLoaded(promise) {\n this._itemsLoaded = promise;\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, true);\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\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}\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 }\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 *\n * @return {boolean}\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 * @return {*}\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) {\n var _a;\n value = value !== null && value !== void 0 ? value : this.getValue();\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 {\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 => {\n if (this.isBooleanOrNumber(item)) {\n item = item.toString();\n }\n });\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\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 if (Array.isArray(value)) {\n const items = [];\n value.forEach(item => items.push(this.itemTemplate(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 return !lodash_1.default.isNil(value)\n ? this.itemTemplate(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 if (this.focusableElement) {\n super.focus.call(this);\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?");
6967
6956
 
6968
6957
  /***/ }),
6969
6958
 
@@ -7018,7 +7007,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
7018
7007
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
7019
7008
 
7020
7009
  "use strict";
7021
- 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 utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Radio_1 = __importDefault(__webpack_require__(/*! ../radio/Radio */ \"./lib/cjs/components/radio/Radio.js\"));\nclass SelectBoxesComponent extends Radio_1.default {\n static schema(...extend) {\n return Radio_1.default.schema({\n type: 'selectboxes',\n label: 'Select Boxes',\n key: 'selectBoxes',\n inline: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select Boxes',\n group: 'basic',\n icon: 'plus-square',\n weight: 60,\n documentation: '/userguide/form-building/form-components#select-box',\n schema: SelectBoxesComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SelectBoxesComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return {\n type: 'select',\n dataSrc: 'custom',\n valueProperty: 'value',\n valueType: 'string',\n data: {\n custom: `values = ${classComp && classComp.values ? JSON.stringify(classComp.values) : []}`\n },\n };\n } });\n }\n static savedValueTypes(schema) {\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n constructor(...args) {\n super(...args);\n this.validators = this.validators.concat('minSelectedCount', 'maxSelectedCount', 'availableValueProperty');\n }\n init() {\n super.init();\n this.component.inputType = 'checkbox';\n }\n get defaultSchema() {\n return SelectBoxesComponent.schema();\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.attr.name += '[]';\n info.attr.type = 'checkbox';\n info.attr.class = 'form-check-input';\n return info;\n }\n get emptyValue() {\n return this.component.values.reduce((prev, value) => {\n if (value.value) {\n prev[value.value] = false;\n }\n return prev;\n }, {});\n }\n get defaultValue() {\n let defaultValue = this.emptyValue;\n if (!lodash_1.default.isEmpty(this.component.defaultValue)) {\n defaultValue = this.component.defaultValue;\n }\n if (this.component.customDefaultValue && !this.options.preview) {\n defaultValue = this.evaluate(this.component.customDefaultValue, { value: '' }, 'value');\n }\n return defaultValue;\n }\n /**\n * Only empty if the values are all false.\n *\n * @param value\n * @return {boolean}\n */\n isEmpty(value = this.dataValue) {\n let empty = true;\n for (const key in value) {\n if (value.hasOwnProperty(key) && value[key]) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n getValue() {\n if (this.viewOnly || !this.refs.input || !this.refs.input.length) {\n return this.dataValue;\n }\n const value = {};\n lodash_1.default.each(this.refs.input, (input) => {\n value[input.value] = !!input.checked;\n });\n return value;\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n value = value || {};\n if (typeof value !== 'object') {\n if (typeof value === 'string') {\n value = {\n [value]: true\n };\n }\n else {\n value = {};\n }\n }\n if (Array.isArray(value)) {\n lodash_1.default.each(value, (val) => {\n value[val] = true;\n });\n }\n const checkedValues = lodash_1.default.keys(lodash_1.default.pickBy(value, (val) => val));\n if (this.isSelectURL && this.templateData && lodash_1.default.every(checkedValues, (val) => this.templateData[val])) {\n const submission = this.root.submission;\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n const selectData = [];\n checkedValues.forEach((value) => selectData.push(this.templateData[value]));\n lodash_1.default.set(submission.metadata.selectData, this.path, selectData);\n }\n return value;\n }\n /**\n * Set the value of this component.\n *\n * @param value\n * @param flags\n */\n setValue(value, flags = {}) {\n const changed = this.updateValue(value, flags);\n value = this.dataValue;\n if (this.isHtmlRenderMode()) {\n if (changed) {\n this.redraw();\n }\n }\n else {\n lodash_1.default.each(this.refs.input, (input) => {\n if (lodash_1.default.isUndefined(value[input.value])) {\n value[input.value] = false;\n }\n input.checked = !!value[input.value];\n });\n }\n return changed;\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (this.isSelectURL) {\n return (0, lodash_1.default)(value).pickBy((val) => val).keys().join(', ');\n }\n return (0, lodash_1.default)(this.component.values || [])\n .filter((v) => value[v.value])\n .map('label')\n .join(', ');\n }\n setSelectedClasses() {\n if (this.refs.wrapper) {\n //add/remove selected option class\n const value = this.dataValue;\n const valuesKeys = Object.keys(value);\n this.refs.wrapper.forEach((wrapper, index) => {\n let key = valuesKeys[index];\n const input = this.refs.input[index];\n if ((input === null || input === void 0 ? void 0 : input.value.toString()) !== key) {\n key = valuesKeys.find((k) => (input === null || input === void 0 ? void 0 : input.value.toString()) === k);\n }\n const isChecked = value[key];\n if ((isChecked && key) || (this.isSelectURL && !this.shouldLoad && this.listData && lodash_1.default.findIndex(this.selectData, this.listData[index]) !== -1)) {\n //add class to container when selected\n this.addClass(wrapper, this.optionSelectedClass);\n //change \"checked\" attribute\n input.setAttribute('checked', 'true');\n }\n else if (!isChecked && key) {\n this.removeClass(wrapper, this.optionSelectedClass);\n input.removeAttribute('checked');\n }\n });\n }\n }\n setInputsDisabled(value, onlyUnchecked) {\n if (this.refs.input) {\n this.refs.input.forEach(item => {\n if (onlyUnchecked && !item.checked || !onlyUnchecked) {\n item.disabled = value;\n }\n });\n }\n }\n checkComponentValidity(data, dirty, rowData, options) {\n const minCount = this.component.validate.minSelectedCount;\n const maxCount = this.component.validate.maxSelectedCount;\n if (!this.shouldSkipValidation(data, dirty, rowData)) {\n const isValid = this.isValid(data, dirty);\n if ((maxCount || minCount)) {\n const count = Object.keys(this.validationValue).reduce((total, key) => {\n if (this.validationValue[key]) {\n total++;\n }\n return total;\n }, 0);\n // Disable the rest of inputs if the max amount is already checked\n if (maxCount && count >= maxCount) {\n this.setInputsDisabled(true, true);\n }\n else if (maxCount && !this.shouldDisabled) {\n this.setInputsDisabled(false);\n }\n if (!isValid && maxCount && count > maxCount) {\n const message = this.t(this.component.maxSelectedCountMessage || 'You can only select up to {{maxCount}} items.', { maxCount });\n this.setCustomValidity(message, dirty);\n return false;\n }\n else if (!isValid && minCount && count < minCount) {\n this.setInputsDisabled(false);\n const message = this.t(this.component.minSelectedCountMessage || 'You must select at least {{minCount}} items.', { minCount });\n this.setCustomValidity(message, dirty);\n return false;\n }\n }\n }\n return super.checkComponentValidity(data, dirty, rowData, options);\n }\n}\nexports[\"default\"] = SelectBoxesComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/selectboxes/SelectBoxes.js?");
7010
+ 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 utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Radio_1 = __importDefault(__webpack_require__(/*! ../radio/Radio */ \"./lib/cjs/components/radio/Radio.js\"));\nclass SelectBoxesComponent extends Radio_1.default {\n static schema(...extend) {\n return Radio_1.default.schema({\n type: 'selectboxes',\n label: 'Select Boxes',\n key: 'selectBoxes',\n inline: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Select Boxes',\n group: 'basic',\n icon: 'plus-square',\n weight: 60,\n documentation: '/userguide/form-building/form-components#select-box',\n schema: SelectBoxesComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SelectBoxesComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { valueComponent(classComp) {\n return {\n type: 'select',\n dataSrc: 'custom',\n valueProperty: 'value',\n valueType: 'string',\n data: {\n custom: `values = ${classComp && classComp.values ? JSON.stringify(classComp.values) : []}`\n },\n };\n } });\n }\n static savedValueTypes(schema) {\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n constructor(...args) {\n super(...args);\n this.validators = this.validators.concat('minSelectedCount', 'maxSelectedCount', 'availableValueProperty');\n }\n init() {\n super.init();\n this.component.inputType = 'checkbox';\n }\n get defaultSchema() {\n return SelectBoxesComponent.schema();\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.attr.name += '[]';\n info.attr.type = 'checkbox';\n info.attr.class = 'form-check-input';\n return info;\n }\n get emptyValue() {\n return this.component.values.reduce((prev, value) => {\n if (value.value) {\n prev[value.value] = false;\n }\n return prev;\n }, {});\n }\n get defaultValue() {\n let defaultValue = this.emptyValue;\n if (!lodash_1.default.isEmpty(this.component.defaultValue)) {\n defaultValue = this.component.defaultValue;\n }\n if (this.component.customDefaultValue && !this.options.preview) {\n defaultValue = this.evaluate(this.component.customDefaultValue, { value: '' }, 'value');\n }\n return defaultValue;\n }\n /**\n * Only empty if the values are all false.\n *\n * @param value\n * @return {boolean}\n */\n isEmpty(value = this.dataValue) {\n let empty = true;\n for (const key in value) {\n if (value.hasOwnProperty(key) && value[key]) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n getValue() {\n if (this.viewOnly || !this.refs.input || !this.refs.input.length) {\n return this.dataValue;\n }\n const value = {};\n lodash_1.default.each(this.refs.input, (input) => {\n value[input.value] = !!input.checked;\n });\n return value;\n }\n /**\n * Normalize values coming into updateValue.\n *\n * @param value\n * @return {*}\n */\n normalizeValue(value) {\n value = value || {};\n if (typeof value !== 'object') {\n if (typeof value === 'string') {\n value = {\n [value]: true\n };\n }\n else {\n value = {};\n }\n }\n if (Array.isArray(value)) {\n lodash_1.default.each(value, (val) => {\n value[val] = true;\n });\n }\n const checkedValues = lodash_1.default.keys(lodash_1.default.pickBy(value, (val) => val));\n if (this.isSelectURL && this.templateData && lodash_1.default.every(checkedValues, (val) => this.templateData[val])) {\n const submission = this.root.submission;\n if (!submission.metadata.selectData) {\n submission.metadata.selectData = {};\n }\n const selectData = [];\n checkedValues.forEach((value) => selectData.push(this.templateData[value]));\n lodash_1.default.set(submission.metadata.selectData, this.path, selectData);\n }\n return value;\n }\n /**\n * Set the value of this component.\n *\n * @param value\n * @param flags\n */\n setValue(value, flags = {}) {\n const changed = this.updateValue(value, flags);\n value = this.dataValue;\n if (this.isHtmlRenderMode()) {\n if (changed) {\n this.redraw();\n }\n }\n else {\n lodash_1.default.each(this.refs.input, (input) => {\n if (lodash_1.default.isUndefined(value[input.value])) {\n value[input.value] = false;\n }\n input.checked = !!value[input.value];\n });\n }\n return changed;\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (this.isSelectURL) {\n return (0, lodash_1.default)(value).pickBy((val) => val).keys().join(', ');\n }\n return (0, lodash_1.default)(this.component.values || [])\n .filter((v) => value[v.value])\n .map('label')\n .join(', ');\n }\n setSelectedClasses() {\n if (this.refs.wrapper) {\n //add/remove selected option class\n const value = this.dataValue;\n const valuesKeys = Object.keys(value);\n this.refs.wrapper.forEach((wrapper, index) => {\n let key = valuesKeys[index];\n const input = this.refs.input[index];\n if ((input === null || input === void 0 ? void 0 : input.value.toString()) !== key) {\n key = valuesKeys.find((k) => (input === null || input === void 0 ? void 0 : input.value.toString()) === k);\n }\n const isChecked = value[key];\n if ((isChecked && key) || (this.isSelectURL && !this.shouldLoad && this.listData && lodash_1.default.findIndex(this.selectData, this.listData[index]) !== -1)) {\n //add class to container when selected\n this.addClass(wrapper, this.optionSelectedClass);\n //change \"checked\" attribute\n input.setAttribute('checked', 'true');\n }\n else if (!isChecked && key) {\n this.removeClass(wrapper, this.optionSelectedClass);\n input.removeAttribute('checked');\n }\n });\n }\n }\n setInputsDisabled(value, onlyUnchecked) {\n if (this.refs.input) {\n this.refs.input.forEach(item => {\n if (onlyUnchecked && !item.checked || !onlyUnchecked) {\n item.disabled = value;\n }\n });\n }\n }\n checkComponentValidity(data, dirty, rowData, options) {\n const minCount = this.component.validate.minSelectedCount;\n const maxCount = this.component.validate.maxSelectedCount;\n if (!this.shouldSkipValidation(data, dirty, rowData)) {\n const isValid = this.isValid(data, dirty);\n if ((maxCount || minCount)) {\n const count = Object.keys(this.validationValue).reduce((total, key) => {\n if (this.validationValue[key]) {\n total++;\n }\n return total;\n }, 0);\n // Disable the rest of inputs if the max amount is already checked\n if (maxCount && count >= maxCount) {\n this.setInputsDisabled(true, true);\n }\n else if (maxCount && !this.shouldDisabled) {\n this.setInputsDisabled(false);\n }\n if (!isValid && maxCount && count > maxCount) {\n const message = this.t(this.component.maxSelectedCountMessage || 'You can only select up to {{maxCount}} items.', { maxCount });\n this.setCustomValidity(message, dirty);\n return false;\n }\n else if (!isValid && minCount && count < minCount) {\n this.setInputsDisabled(false);\n const message = this.t(this.component.minSelectedCountMessage || 'You must select at least {{minCount}} items.', { minCount });\n this.setCustomValidity(message, dirty);\n return false;\n }\n }\n }\n return super.checkComponentValidity(data, dirty, rowData, options);\n }\n validateValueAvailability(setting, value) {\n if (!(0, utils_1.boolValue)(setting) || !value) {\n return true;\n }\n const values = this.component.values;\n const availableValueKeys = (values || []).map(({ value: optionValue }) => optionValue);\n const valueKeys = Object.keys(value);\n return valueKeys.every((key) => availableValueKeys.includes(key));\n }\n}\nexports[\"default\"] = SelectBoxesComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/selectboxes/SelectBoxes.js?");
7022
7011
 
7023
7012
  /***/ }),
7024
7013
 
@@ -7051,7 +7040,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
7051
7040
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
7052
7041
 
7053
7042
  "use strict";
7054
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst signature_pad_1 = __importDefault(__webpack_require__(/*! signature_pad */ \"./node_modules/signature_pad/dist/signature_pad.js\"));\nconst resize_observer_polyfill_1 = __importDefault(__webpack_require__(/*! resize-observer-polyfill */ \"./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass SignatureComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'signature',\n label: 'Signature',\n key: 'signature',\n footer: 'Sign above',\n width: '100%',\n height: '150px',\n penColor: 'black',\n backgroundColor: 'rgb(245,245,235)',\n minWidth: '0.5',\n maxWidth: '2.5',\n keepOverlayRatio: true,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Signature',\n group: 'advanced',\n icon: 'pencil',\n weight: 120,\n documentation: '/developers/integrations/esign/esign-integrations#signature-component',\n schema: SignatureComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SignatureComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: ['isEmpty', 'isNotEmpty'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.string];\n }\n init() {\n var _a, _b, _c, _d, _e;\n super.init();\n this.currentWidth = 0;\n this.scale = 1;\n if (!this.component.width) {\n this.component.width = '100%';\n }\n if (!this.component.height) {\n this.component.height = '200px';\n }\n if (this.component.keepOverlayRatio\n && ((_a = this.options) === null || _a === void 0 ? void 0 : _a.display) === 'pdf'\n && ((_b = this.component.overlay) === null || _b === void 0 ? void 0 : _b.width)\n && ((_c = this.component.overlay) === null || _c === void 0 ? void 0 : _c.height)) {\n this.ratio = ((_d = this.component.overlay) === null || _d === void 0 ? void 0 : _d.width) / ((_e = this.component.overlay) === null || _e === void 0 ? void 0 : _e.height);\n this.component.width = '100%';\n this.component.height = 'auto';\n }\n }\n get emptyValue() {\n return '';\n }\n get defaultSchema() {\n return SignatureComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'hidden';\n return info;\n }\n get className() {\n return `${super.className} signature-pad`;\n }\n labelIsHidden() {\n return this.component.hideLabel;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.refs.signatureImage && (this.options.readOnly || this.disabled)) {\n this.refs.signatureImage.setAttribute('src', value);\n this.showCanvas(false);\n }\n if (this.signaturePad) {\n if (!value) {\n this.signaturePad.clear();\n }\n else if (changed) {\n this.triggerChange();\n }\n }\n if (this.signaturePad && this.dataValue && this.signaturePad.isEmpty()) {\n this.setDataToSigaturePad();\n }\n return changed;\n }\n showCanvas(show) {\n if (show) {\n if (this.refs.canvas) {\n this.refs.canvas.style.display = 'inherit';\n }\n if (this.refs.signatureImage) {\n this.refs.signatureImage.style.display = 'none';\n }\n }\n else {\n if (this.refs.canvas) {\n this.refs.canvas.style.display = 'none';\n }\n if (this.refs.signatureImage) {\n this.refs.signatureImage.style.display = 'inherit';\n this.refs.signatureImage.style.maxHeight = '100%';\n }\n }\n }\n onDisabled() {\n this.showCanvas(!super.disabled);\n if (this.signaturePad) {\n if (super.disabled) {\n this.signaturePad.off();\n if (this.refs.refresh) {\n this.refs.refresh.classList.add('disabled');\n }\n if (this.refs.signatureImage && this.dataValue) {\n this.refs.signatureImage.setAttribute('src', this.dataValue);\n }\n }\n else {\n this.signaturePad.on();\n if (this.refs.refresh) {\n this.refs.refresh.classList.remove('disabled');\n }\n }\n }\n }\n checkSize(force, scale) {\n if (this.refs.padBody && (force || this.refs.padBody && this.refs.padBody.offsetWidth !== this.currentWidth)) {\n this.scale = force ? scale : this.scale;\n this.currentWidth = this.refs.padBody.offsetWidth;\n const width = this.currentWidth * this.scale;\n const height = this.ratio ? width / this.ratio : this.refs.padBody.offsetHeight * this.scale;\n const maxHeight = this.ratio ? height : this.refs.padBody.offsetHeight * this.scale;\n this.refs.canvas.width = width;\n this.refs.canvas.height = height > maxHeight ? maxHeight : height;\n this.refs.canvas.style.maxWidth = `${this.currentWidth * this.scale}px`;\n this.refs.canvas.style.maxHeight = `${maxHeight}px`;\n const ctx = this.refs.canvas.getContext('2d');\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.scale((1 / this.scale), (1 / this.scale));\n ctx.fillStyle = this.signaturePad.backgroundColor;\n ctx.fillRect(0, 0, this.refs.canvas.width, this.refs.canvas.height);\n this.signaturePad.clear();\n if (this.dataValue) {\n this.setDataToSigaturePad();\n }\n this.showCanvas(true);\n }\n }\n renderElement(value, index) {\n return this.renderTemplate('signature', {\n element: super.renderElement(value, index),\n required: lodash_1.default.get(this.component, 'validate.required', false),\n });\n }\n get hasModalSaveButton() {\n return false;\n }\n getModalPreviewTemplate() {\n return this.renderTemplate('modalPreview', {\n previewText: this.dataValue ?\n `<img src=${this.dataValue} ref='openModal' style=\"width: 100%;height: 100%;\" />` :\n this.t('Click to Sign')\n });\n }\n attach(element) {\n this.loadRefs(element, { canvas: 'single', refresh: 'single', padBody: 'single', signatureImage: 'single' });\n const superAttach = super.attach(element);\n if (this.refs.refresh && this.options.readOnly) {\n this.refs.refresh.classList.add('disabled');\n }\n // Create the signature pad.\n if (this.refs.canvas) {\n this.signaturePad = new signature_pad_1.default(this.refs.canvas, {\n minWidth: this.component.minWidth,\n maxWidth: this.component.maxWidth,\n penColor: this.component.penColor,\n backgroundColor: this.component.backgroundColor\n });\n this.signaturePad.addEventListener('endStroke', () => this.setValue(this.signaturePad.toDataURL()));\n this.refs.signatureImage.setAttribute('src', this.signaturePad.toDataURL());\n this.onDisabled();\n // Ensure the signature is always the size of its container.\n if (this.refs.padBody) {\n if (!this.refs.padBody.style.maxWidth) {\n this.refs.padBody.style.maxWidth = '100%';\n }\n if (!this.builderMode && !this.options.preview) {\n this.observer = new resize_observer_polyfill_1.default(() => {\n this.checkSize();\n });\n this.observer.observe(this.refs.padBody);\n }\n this.addEventListener(window, 'resize', lodash_1.default.debounce(() => this.checkSize(), 10));\n setTimeout(function checkWidth() {\n if (this.refs.padBody && this.refs.padBody.offsetWidth) {\n this.checkSize();\n }\n else {\n setTimeout(checkWidth.bind(this), 20);\n }\n }.bind(this), 20);\n }\n }\n this.addEventListener(this.refs.refresh, 'click', (event) => {\n event.preventDefault();\n this.showCanvas(true);\n this.signaturePad.clear();\n this.setValue(this.defaultValue);\n });\n this.setValue(this.dataValue);\n return superAttach;\n }\n /* eslint-enable max-statements */\n detach() {\n if (this.observer) {\n this.observer.disconnect();\n this.observer = null;\n }\n if (this.signaturePad) {\n this.signaturePad.off();\n }\n this.signaturePad = null;\n this.currentWidth = 0;\n super.detach();\n }\n getValueAsString(value) {\n if (lodash_1.default.isUndefined(value) && this.inDataTable) {\n return '';\n }\n return value ? 'Yes' : 'No';\n }\n focus() {\n this.refs.padBody.focus();\n }\n setDataToSigaturePad() {\n this.signaturePad.fromDataURL(this.dataValue, {\n ratio: 1,\n width: this.refs.canvas.width,\n height: this.refs.canvas.height,\n });\n }\n}\nexports[\"default\"] = SignatureComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/signature/Signature.js?");
7043
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst signature_pad_1 = __importDefault(__webpack_require__(/*! signature_pad */ \"./node_modules/signature_pad/dist/signature_pad.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass SignatureComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'signature',\n label: 'Signature',\n key: 'signature',\n footer: 'Sign above',\n width: '100%',\n height: '150px',\n penColor: 'black',\n backgroundColor: 'rgb(245,245,235)',\n minWidth: '0.5',\n maxWidth: '2.5',\n keepOverlayRatio: true,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Signature',\n group: 'advanced',\n icon: 'pencil',\n weight: 120,\n documentation: '/developers/integrations/esign/esign-integrations#signature-component',\n schema: SignatureComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return SignatureComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: ['isEmpty', 'isNotEmpty'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.string];\n }\n init() {\n var _a, _b, _c, _d, _e;\n super.init();\n this.currentWidth = 0;\n this.scale = 1;\n if (!this.component.width) {\n this.component.width = '100%';\n }\n if (!this.component.height) {\n this.component.height = '200px';\n }\n if (this.component.keepOverlayRatio\n && ((_a = this.options) === null || _a === void 0 ? void 0 : _a.display) === 'pdf'\n && ((_b = this.component.overlay) === null || _b === void 0 ? void 0 : _b.width)\n && ((_c = this.component.overlay) === null || _c === void 0 ? void 0 : _c.height)) {\n this.ratio = ((_d = this.component.overlay) === null || _d === void 0 ? void 0 : _d.width) / ((_e = this.component.overlay) === null || _e === void 0 ? void 0 : _e.height);\n this.component.width = '100%';\n this.component.height = 'auto';\n }\n }\n get emptyValue() {\n return '';\n }\n get defaultSchema() {\n return SignatureComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'hidden';\n return info;\n }\n get className() {\n return `${super.className} signature-pad`;\n }\n labelIsHidden() {\n return this.component.hideLabel;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.refs.signatureImage && (this.options.readOnly || this.disabled)) {\n this.refs.signatureImage.setAttribute('src', value);\n this.showCanvas(false);\n }\n if (this.signaturePad) {\n if (!value) {\n this.signaturePad.clear();\n }\n else if (changed) {\n this.triggerChange();\n }\n }\n if (this.signaturePad && this.dataValue && this.signaturePad.isEmpty()) {\n this.setDataToSigaturePad();\n }\n return changed;\n }\n showCanvas(show) {\n if (show) {\n if (this.refs.canvas) {\n this.refs.canvas.style.display = 'inherit';\n }\n if (this.refs.signatureImage) {\n this.refs.signatureImage.style.display = 'none';\n }\n }\n else {\n if (this.refs.canvas) {\n this.refs.canvas.style.display = 'none';\n }\n if (this.refs.signatureImage) {\n this.refs.signatureImage.style.display = 'inherit';\n this.refs.signatureImage.style.maxHeight = '100%';\n }\n }\n }\n onDisabled() {\n this.showCanvas(!super.disabled);\n if (this.signaturePad) {\n if (super.disabled) {\n this.signaturePad.off();\n if (this.refs.refresh) {\n this.refs.refresh.classList.add('disabled');\n }\n if (this.refs.signatureImage && this.dataValue) {\n this.refs.signatureImage.setAttribute('src', this.dataValue);\n }\n }\n else {\n this.signaturePad.on();\n if (this.refs.refresh) {\n this.refs.refresh.classList.remove('disabled');\n }\n }\n }\n }\n checkSize(force, scale) {\n if (this.refs.padBody && (force || this.refs.padBody && this.refs.padBody.offsetWidth !== this.currentWidth)) {\n this.scale = force ? scale : this.scale;\n this.currentWidth = this.refs.padBody.offsetWidth;\n const width = this.currentWidth * this.scale;\n const height = this.ratio ? width / this.ratio : this.refs.padBody.offsetHeight * this.scale;\n const maxHeight = this.ratio ? height : this.refs.padBody.offsetHeight * this.scale;\n this.refs.canvas.width = width;\n this.refs.canvas.height = height > maxHeight ? maxHeight : height;\n this.refs.canvas.style.maxWidth = `${this.currentWidth * this.scale}px`;\n this.refs.canvas.style.maxHeight = `${maxHeight}px`;\n const ctx = this.refs.canvas.getContext('2d');\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.scale((1 / this.scale), (1 / this.scale));\n ctx.fillStyle = this.signaturePad.backgroundColor;\n ctx.fillRect(0, 0, this.refs.canvas.width, this.refs.canvas.height);\n this.signaturePad.clear();\n if (this.dataValue) {\n this.setDataToSigaturePad();\n }\n this.showCanvas(true);\n }\n }\n renderElement(value, index) {\n return this.renderTemplate('signature', {\n element: super.renderElement(value, index),\n required: lodash_1.default.get(this.component, 'validate.required', false),\n });\n }\n get hasModalSaveButton() {\n return false;\n }\n getModalPreviewTemplate() {\n return this.renderTemplate('modalPreview', {\n previewText: this.dataValue ?\n `<img src=${this.dataValue} ref='openModal' style=\"width: 100%;height: 100%;\" />` :\n this.t('Click to Sign')\n });\n }\n attach(element) {\n this.loadRefs(element, { canvas: 'single', refresh: 'single', padBody: 'single', signatureImage: 'single' });\n const superAttach = super.attach(element);\n if (this.refs.refresh && this.options.readOnly) {\n this.refs.refresh.classList.add('disabled');\n }\n // Create the signature pad.\n if (this.refs.canvas) {\n this.signaturePad = new signature_pad_1.default(this.refs.canvas, {\n minWidth: this.component.minWidth,\n maxWidth: this.component.maxWidth,\n penColor: this.component.penColor,\n backgroundColor: this.component.backgroundColor\n });\n this.signaturePad.addEventListener('endStroke', () => this.setValue(this.signaturePad.toDataURL()));\n this.refs.signatureImage.setAttribute('src', this.signaturePad.toDataURL());\n this.onDisabled();\n // Ensure the signature is always the size of its container.\n if (this.refs.padBody) {\n if (!this.refs.padBody.style.maxWidth) {\n this.refs.padBody.style.maxWidth = '100%';\n }\n if (!this.builderMode && !this.options.preview) {\n this.observer = new ResizeObserver(() => {\n this.checkSize();\n });\n this.observer.observe(this.refs.padBody);\n }\n this.addEventListener(window, 'resize', lodash_1.default.debounce(() => this.checkSize(), 10));\n setTimeout(function checkWidth() {\n if (this.refs.padBody && this.refs.padBody.offsetWidth) {\n this.checkSize();\n }\n else {\n setTimeout(checkWidth.bind(this), 20);\n }\n }.bind(this), 20);\n }\n }\n this.addEventListener(this.refs.refresh, 'click', (event) => {\n event.preventDefault();\n this.showCanvas(true);\n this.signaturePad.clear();\n this.setValue(this.defaultValue);\n });\n this.setValue(this.dataValue);\n return superAttach;\n }\n /* eslint-enable max-statements */\n detach() {\n if (this.observer) {\n this.observer.disconnect();\n this.observer = null;\n }\n if (this.signaturePad) {\n this.signaturePad.off();\n }\n this.signaturePad = null;\n this.currentWidth = 0;\n super.detach();\n }\n getValueAsString(value) {\n if (lodash_1.default.isUndefined(value) && this.inDataTable) {\n return '';\n }\n return value ? 'Yes' : 'No';\n }\n focus() {\n this.refs.padBody.focus();\n }\n setDataToSigaturePad() {\n this.signaturePad.fromDataURL(this.dataValue, {\n ratio: 1,\n width: this.refs.canvas.width,\n height: this.refs.canvas.height,\n });\n }\n}\nexports[\"default\"] = SignatureComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/signature/Signature.js?");
7055
7044
 
7056
7045
  /***/ }),
7057
7046
 
@@ -7887,7 +7876,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
7887
7876
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
7888
7877
 
7889
7878
  "use strict";
7890
- eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.KEY_CODES = void 0;\nconst choices_js_1 = __importDefault(__webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\"));\n/**\n * TODO: REMOVE THIS ONCE THE PULL REQUEST HAS BEEN RESOLVED.\n *\n * https://github.com/jshjohnson/Choices/pull/788\n *\n * This is intentionally not part of the extended class, since other components use Choices and need this fix as well.\n * @type {Choices._generatePlaceholderValue}\n * @private\n */\nchoices_js_1.default.prototype._generatePlaceholderValue = function () {\n if (this._isSelectElement && this.passedElement.placeholderOption) {\n const { placeholderOption } = this.passedElement;\n return placeholderOption ? placeholderOption.text : false;\n }\n const { placeholder, placeholderValue } = this.config;\n const { element: { dataset }, } = this.passedElement;\n if (placeholder) {\n if (placeholderValue) {\n return placeholderValue;\n }\n if (dataset.placeholder) {\n return dataset.placeholder;\n }\n }\n return false;\n};\nexports.KEY_CODES = {\n BACK_KEY: 46,\n DELETE_KEY: 8,\n TAB_KEY: 9,\n ENTER_KEY: 13,\n A_KEY: 65,\n ESC_KEY: 27,\n UP_KEY: 38,\n DOWN_KEY: 40,\n PAGE_UP_KEY: 33,\n PAGE_DOWN_KEY: 34,\n};\nclass ChoicesWrapper extends choices_js_1.default {\n constructor(...args) {\n super(...args);\n this._onTabKey = this._onTabKey.bind(this);\n this.isDirectionUsing = false;\n this.shouldOpenDropDown = true;\n }\n _handleButtonAction(activeItems, element) {\n if (!this._isSelectOneElement) {\n return super._handleButtonAction(activeItems, element);\n }\n if (!activeItems ||\n !element ||\n !this.config.removeItems ||\n !this.config.removeItemButton) {\n return;\n }\n super._handleButtonAction(activeItems, element);\n }\n _onEnterKey(args) {\n // Prevent dropdown form opening when removeItemButton was pressed using 'Enter' on keyboard\n if (args.event.target.className === 'choices__button') {\n this.shouldOpenDropDown = false;\n }\n super._onEnterKey(args);\n }\n _onDirectionKey(...args) {\n if (!this._isSelectOneElement) {\n return super._onDirectionKey(...args);\n }\n this.isDirectionUsing = true;\n super._onDirectionKey(...args);\n this.onSelectValue(...args);\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => {\n this.isDirectionUsing = false;\n }, 250);\n }\n _onTabKey({ activeItems, hasActiveDropdown }) {\n if (hasActiveDropdown) {\n this._selectHighlightedChoice(activeItems);\n }\n }\n _selectHighlightedChoice(activeItems) {\n const highlightedChoice = this.dropdown.getChild(`.${this.config.classNames.highlightedState}`);\n if (highlightedChoice) {\n this._handleChoiceAction(activeItems, highlightedChoice);\n }\n event.preventDefault();\n }\n _onKeyDown(event) {\n if (!this._isSelectOneElement) {\n return super._onKeyDown(event);\n }\n const { target, keyCode, ctrlKey, metaKey } = event;\n if (target !== this.input.element &&\n !this.containerOuter.element.contains(target)) {\n return;\n }\n const activeItems = this._store.activeItems;\n const hasFocusedInput = this.input.isFocussed;\n const hasActiveDropdown = this.dropdown.isActive;\n const hasItems = this.itemList.hasChildren;\n const keyString = String.fromCharCode(keyCode);\n const { BACK_KEY, DELETE_KEY, TAB_KEY, ENTER_KEY, A_KEY, ESC_KEY, UP_KEY, DOWN_KEY, PAGE_UP_KEY, PAGE_DOWN_KEY, } = exports.KEY_CODES;\n const hasCtrlDownKeyPressed = ctrlKey || metaKey;\n // If a user is typing and the dropdown is not active\n if (!hasActiveDropdown && !this._isTextElement && /[a-zA-Z0-9-_ ]/.test(keyString)) {\n const currentValue = this.input.element.value;\n this.input.element.value = currentValue ? `${currentValue}${keyString}` : keyString;\n this.showDropdown();\n }\n // Map keys to key actions\n const keyDownActions = {\n [A_KEY]: this._onAKey,\n [TAB_KEY]: this._onTabKey,\n [ENTER_KEY]: this._onEnterKey,\n [ESC_KEY]: this._onEscapeKey,\n [UP_KEY]: this._onDirectionKey,\n [PAGE_UP_KEY]: this._onDirectionKey,\n [DOWN_KEY]: this._onDirectionKey,\n [PAGE_DOWN_KEY]: this._onDirectionKey,\n [DELETE_KEY]: this._onDeleteKey,\n [BACK_KEY]: this._onDeleteKey,\n };\n // If keycode has a function, run it\n if (keyDownActions[keyCode]) {\n keyDownActions[keyCode]({\n event,\n target,\n keyCode,\n metaKey,\n activeItems,\n hasFocusedInput,\n hasActiveDropdown,\n hasItems,\n hasCtrlDownKeyPressed,\n });\n }\n }\n onSelectValue({ event, activeItems, hasActiveDropdown }) {\n if (hasActiveDropdown) {\n this._selectHighlightedChoice(activeItems);\n }\n else if (this._isSelectOneElement) {\n this.showDropdown();\n event.preventDefault();\n }\n }\n showDropdown(...args) {\n if (!this.shouldOpenDropDown) {\n this.shouldOpenDropDown = true;\n return;\n }\n super.showDropdown(...args);\n }\n hideDropdown(...args) {\n if (this.isDirectionUsing) {\n return;\n }\n super.hideDropdown(...args);\n }\n _onBlur(...args) {\n if (this._isScrollingOnIe) {\n return;\n }\n super._onBlur(...args);\n }\n}\nexports[\"default\"] = ChoicesWrapper;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/utils/ChoicesWrapper.js?");
7879
+ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.KEY_CODES = void 0;\nconst choices_js_1 = __importDefault(__webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\"));\n/**\n * TODO: REMOVE THIS ONCE THE PULL REQUEST HAS BEEN RESOLVED.\n *\n * https://github.com/jshjohnson/Choices/pull/788\n *\n * This is intentionally not part of the extended class, since other components use Choices and need this fix as well.\n * @type {Choices._generatePlaceholderValue}\n * @private\n */\nchoices_js_1.default.prototype._generatePlaceholderValue = function () {\n if (this._isSelectElement && this.passedElement.placeholderOption) {\n const { placeholderOption } = this.passedElement;\n return placeholderOption ? placeholderOption.text : false;\n }\n const { placeholder, placeholderValue } = this.config;\n const { element: { dataset }, } = this.passedElement;\n if (placeholder) {\n if (placeholderValue) {\n return placeholderValue;\n }\n if (dataset.placeholder) {\n return dataset.placeholder;\n }\n }\n return false;\n};\nexports.KEY_CODES = {\n BACK_KEY: 46,\n DELETE_KEY: 8,\n TAB_KEY: 9,\n ENTER_KEY: 13,\n A_KEY: 65,\n ESC_KEY: 27,\n UP_KEY: 38,\n DOWN_KEY: 40,\n PAGE_UP_KEY: 33,\n PAGE_DOWN_KEY: 34,\n};\nclass ChoicesWrapper extends choices_js_1.default {\n constructor(...args) {\n super(...args);\n this._onTabKey = this._onTabKey.bind(this);\n this.isDirectionUsing = false;\n this.shouldOpenDropDown = true;\n }\n _onTouchEnd(event) {\n var target = (event || event.touches[0]).target;\n var touchWasWithinContainer = this._wasTap && this.containerOuter.element.contains(target);\n if (touchWasWithinContainer) {\n var containerWasExactTarget = target === this.containerOuter.element || target === this.containerInner.element;\n if (containerWasExactTarget) {\n if (this._isTextElement) {\n this.input.focus();\n }\n else if (this._isSelectMultipleElement) {\n this.input.focus();\n this.showDropdown();\n }\n }\n // Prevents focus event firing\n event.stopPropagation();\n }\n this._wasTap = true;\n }\n _handleButtonAction(activeItems, element) {\n if (!this._isSelectOneElement) {\n return super._handleButtonAction(activeItems, element);\n }\n if (!activeItems ||\n !element ||\n !this.config.removeItems ||\n !this.config.removeItemButton) {\n return;\n }\n super._handleButtonAction(activeItems, element);\n }\n _onEnterKey(args) {\n // Prevent dropdown form opening when removeItemButton was pressed using 'Enter' on keyboard\n if (args.event.target.className === 'choices__button') {\n this.shouldOpenDropDown = false;\n }\n super._onEnterKey(args);\n }\n _onDirectionKey(...args) {\n if (!this._isSelectOneElement) {\n return super._onDirectionKey(...args);\n }\n this.isDirectionUsing = true;\n super._onDirectionKey(...args);\n this.onSelectValue(...args);\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => {\n this.isDirectionUsing = false;\n }, 250);\n }\n _onTabKey({ activeItems, hasActiveDropdown }) {\n if (hasActiveDropdown) {\n this._selectHighlightedChoice(activeItems);\n }\n }\n _selectHighlightedChoice(activeItems) {\n const highlightedChoice = this.dropdown.getChild(`.${this.config.classNames.highlightedState}`);\n if (highlightedChoice) {\n this._handleChoiceAction(activeItems, highlightedChoice);\n }\n event.preventDefault();\n }\n _onKeyDown(event) {\n if (!this._isSelectOneElement) {\n return super._onKeyDown(event);\n }\n const { target, keyCode, ctrlKey, metaKey } = event;\n if (target !== this.input.element &&\n !this.containerOuter.element.contains(target)) {\n return;\n }\n const activeItems = this._store.activeItems;\n const hasFocusedInput = this.input.isFocussed;\n const hasActiveDropdown = this.dropdown.isActive;\n const hasItems = this.itemList.hasChildren;\n const keyString = String.fromCharCode(keyCode);\n const { BACK_KEY, DELETE_KEY, TAB_KEY, ENTER_KEY, A_KEY, ESC_KEY, UP_KEY, DOWN_KEY, PAGE_UP_KEY, PAGE_DOWN_KEY, } = exports.KEY_CODES;\n const hasCtrlDownKeyPressed = ctrlKey || metaKey;\n // If a user is typing and the dropdown is not active\n if (!hasActiveDropdown && !this._isTextElement && /[a-zA-Z0-9-_ ]/.test(keyString)) {\n const currentValue = this.input.element.value;\n this.input.element.value = currentValue ? `${currentValue}${keyString}` : keyString;\n this.showDropdown();\n }\n // Map keys to key actions\n const keyDownActions = {\n [A_KEY]: this._onAKey,\n [TAB_KEY]: this._onTabKey,\n [ENTER_KEY]: this._onEnterKey,\n [ESC_KEY]: this._onEscapeKey,\n [UP_KEY]: this._onDirectionKey,\n [PAGE_UP_KEY]: this._onDirectionKey,\n [DOWN_KEY]: this._onDirectionKey,\n [PAGE_DOWN_KEY]: this._onDirectionKey,\n [DELETE_KEY]: this._onDeleteKey,\n [BACK_KEY]: this._onDeleteKey,\n };\n // If keycode has a function, run it\n if (keyDownActions[keyCode]) {\n keyDownActions[keyCode]({\n event,\n target,\n keyCode,\n metaKey,\n activeItems,\n hasFocusedInput,\n hasActiveDropdown,\n hasItems,\n hasCtrlDownKeyPressed,\n });\n }\n }\n onSelectValue({ event, activeItems, hasActiveDropdown }) {\n if (hasActiveDropdown) {\n this._selectHighlightedChoice(activeItems);\n }\n else if (this._isSelectOneElement) {\n this.showDropdown();\n event.preventDefault();\n }\n }\n showDropdown(...args) {\n if (!this.shouldOpenDropDown) {\n this.shouldOpenDropDown = true;\n return;\n }\n super.showDropdown(...args);\n }\n hideDropdown(...args) {\n if (this.isDirectionUsing) {\n return;\n }\n super.hideDropdown(...args);\n }\n _onBlur(...args) {\n if (this._isScrollingOnIe) {\n return;\n }\n super._onBlur(...args);\n }\n}\nexports[\"default\"] = ChoicesWrapper;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/utils/ChoicesWrapper.js?");
7891
7880
 
7892
7881
  /***/ }),
7893
7882
 
@@ -10138,7 +10127,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
10138
10127
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
10139
10128
 
10140
10129
  "use strict";
10141
- 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 core_1 = __webpack_require__(/*! @formio/core */ \"./node_modules/@formio/core/lib/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return core_1.Formio; } }));\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\ncore_1.Formio.cdn = new CDN_1.default();\ncore_1.Formio.Providers = providers_1.default;\ncore_1.Formio.version = '5.0.0-rc.23';\nconst isNil = (val) => val === null || val === undefined;\ncore_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback) {\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 = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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 core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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 core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// For reverse compatability.\ncore_1.Formio.Promise = Promise;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10130
+ 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 core_1 = __webpack_require__(/*! @formio/core */ \"./node_modules/@formio/core/lib/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return core_1.Formio; } }));\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\ncore_1.Formio.cdn = new CDN_1.default();\ncore_1.Formio.Providers = providers_1.default;\ncore_1.Formio.version = '5.0.0-rc.24';\nconst isNil = (val) => val === null || val === undefined;\ncore_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback) {\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 = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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 core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\ncore_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = core_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return core_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 core_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// For reverse compatability.\ncore_1.Formio.Promise = Promise;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
10142
10131
 
10143
10132
  /***/ }),
10144
10133