@formio/js 5.0.0-rc.21 → 5.0.0-rc.22
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/formio.embed.min.js.LICENSE.txt +1 -1
- package/dist/formio.form.js +6 -6
- package/dist/formio.form.min.js +1 -1
- package/dist/formio.form.min.js.LICENSE.txt +1 -1
- package/dist/formio.full.js +6 -6
- package/dist/formio.full.min.js +1 -1
- package/dist/formio.full.min.js.LICENSE.txt +1 -1
- package/dist/formio.js +1 -1
- package/dist/formio.min.js +1 -1
- package/dist/formio.min.js.LICENSE.txt +1 -1
- package/dist/formio.utils.min.js.LICENSE.txt +1 -1
- package/lib/cjs/Element.js +5 -0
- package/lib/cjs/components/day/Day.js +4 -0
- package/lib/cjs/components/day/fixtures/comp5.d.ts +29 -0
- package/lib/cjs/components/day/fixtures/comp5.js +32 -0
- package/lib/cjs/components/day/fixtures/index.d.ts +2 -1
- package/lib/cjs/components/day/fixtures/index.js +3 -1
- package/lib/cjs/components/form/Form.js +2 -1
- package/lib/cjs/components/select/Select.js +2 -1
- package/lib/cjs/components/select/fixtures/comp19.d.ts +23 -0
- package/lib/cjs/components/select/fixtures/comp19.js +36 -0
- package/lib/cjs/components/select/fixtures/index.d.ts +2 -1
- package/lib/cjs/components/select/fixtures/index.js +3 -1
- package/lib/cjs/components/tags/Tags.js +2 -0
- package/lib/cjs/components/tags/fixtures/comp6.d.ts +17 -0
- package/lib/cjs/components/tags/fixtures/comp6.js +20 -0
- package/lib/cjs/components/tags/fixtures/index.d.ts +2 -1
- package/lib/cjs/components/tags/fixtures/index.js +3 -1
- package/lib/mjs/Element.js +5 -0
- package/lib/mjs/components/day/Day.js +4 -0
- package/lib/mjs/components/day/fixtures/comp5.d.ts +29 -0
- package/lib/mjs/components/day/fixtures/comp5.js +30 -0
- package/lib/mjs/components/day/fixtures/index.d.ts +2 -1
- package/lib/mjs/components/day/fixtures/index.js +2 -1
- package/lib/mjs/components/form/Form.js +2 -1
- package/lib/mjs/components/select/Select.js +2 -1
- package/lib/mjs/components/select/fixtures/comp19.d.ts +23 -0
- package/lib/mjs/components/select/fixtures/comp19.js +34 -0
- package/lib/mjs/components/select/fixtures/index.d.ts +2 -1
- package/lib/mjs/components/select/fixtures/index.js +2 -1
- package/lib/mjs/components/tags/Tags.js +2 -0
- package/lib/mjs/components/tags/fixtures/comp6.d.ts +17 -0
- package/lib/mjs/components/tags/fixtures/comp6.js +18 -0
- package/lib/mjs/components/tags/fixtures/index.d.ts +2 -1
- package/lib/mjs/components/tags/fixtures/index.js +2 -1
- package/package.json +1 -1
package/dist/formio.form.js
CHANGED
@@ -4791,7 +4791,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\n// A
|
|
4791
4791
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
4792
4792
|
|
4793
4793
|
"use strict";
|
4794
|
-
eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst EventEmitter_1 = __importDefault(__webpack_require__(/*! ./EventEmitter */ \"./lib/cjs/EventEmitter.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst FormioUtils = __importStar(__webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\"));\nconst i18n_1 = __webpack_require__(/*! ./utils/i18n */ \"./lib/cjs/utils/i18n.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst moment_1 = __importDefault(__webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\"));\nconst vanilla_text_mask_1 = __importDefault(__webpack_require__(/*! @formio/vanilla-text-mask */ \"./node_modules/@formio/vanilla-text-mask/dist/vanillaTextMask.js\"));\n/**\n * The root component for all elements within the Form.io renderer.\n */\nclass Element {\n constructor(options) {\n var _a;\n /**\n * The options for this component.\n * @type {{}}\n */\n this.options = Object.assign({\n language: 'en',\n highlightErrors: true,\n componentErrorClass: 'formio-error-wrapper',\n componentWarningClass: 'formio-warning-wrapper',\n row: '',\n namespace: 'formio'\n }, options || {});\n /**\n * The ID of this component. This value is auto-generated when the component is created, but\n * can also be provided from the component.id value passed into the constructor.\n * @type {string}\n */\n this.id = FormioUtils.getRandomComponentId();\n /**\n * An array of event handlers so that the destry command can deregister them.\n * @type {Array}\n */\n this.eventHandlers = [];\n // Use the i18next that is passed in, otherwise use the global version.\n this.options.i18n = this.options.i18n || {};\n if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.language) {\n this.options.i18n.language = this.options.language;\n }\n this.options.i18next = this.i18next = this.options.i18next || i18n_1.I18n.init(this.options.i18n);\n /**\n * An instance of the EventEmitter class to handle the emitting and registration of events.\n *\n * @type {EventEmitter}\n */\n this.events = (options && options.events) ? options.events : new EventEmitter_1.default();\n this.defaultMask = null;\n /**\n * Conditional to show or hide helplinks in editForm\n *\n * @type {*|boolean}\n */\n this.helplinks = (this.options.helplinks === 'false') ? false : (this.options.helplinks || 'https://help.form.io');\n }\n /**\n * Register for a new event within this component.\n *\n * @example\n * let component = new BaseComponent({\n * type: 'textfield',\n * label: 'First Name',\n * key: 'firstName'\n * });\n * component.on('componentChange', (changed) => {\n * console.log('this element is changed.');\n * });\n *\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function} cb - The callback handler to handle this event.\n */\n on(event, cb, internal, once = false) {\n if (!this.events) {\n return;\n }\n const type = `${this.options.namespace}.${event}`;\n // Store the component id in the handler so that we can determine which events are for this component.\n cb.id = this.id;\n cb.key = this.key;\n cb.internal = internal;\n // Register for this event.\n return this.events[once ? 'once' : 'on'](type, cb);\n }\n /**\n * Register for a new single-fire event within this component.\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function} cb - The callback handler to handle this event.\n */\n once(event, cb, internal) {\n return this.on(event, cb, internal, true);\n }\n /**\n * Allow catching any event.\n *\n * @param cb\n * @returns {this}\n */\n onAny(cb) {\n if (!this.events) {\n return;\n }\n return this.events.onAny(cb);\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param cb\n * @returns {this}\n */\n offAny(cb) {\n if (!this.events) {\n return;\n }\n return this.events.offAny(cb);\n }\n /**\n * Removes a listener for a certain event. Not passing the 2nd arg will remove all listeners for that event.\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function|undefined} cb - The callback handler to handle this event.\n */\n off(event, cb) {\n if (!this.events) {\n return;\n }\n const type = `${this.options.namespace}.${event}`;\n this.events.listeners(type).forEach((listener) => {\n // Ensure the listener is for this element\n if (!listener || listener.id !== this.id) {\n return;\n }\n // If there is a given callback, only deal with the match\n if (cb && cb !== listener) {\n return;\n }\n this.events.off(type, listener);\n });\n }\n /**\n * Emit a new event.\n *\n * @param {string} event - The event to emit.\n * @param {Object} data - The data to emit with the handler.\n */\n emit(event, ...data) {\n if (this.events) {\n this.events.emit(`${this.options.namespace}.${event}`, ...data);\n }\n }\n /**\n * Check if the component has an event handler set up for the event.\n *\n * @param {string} event - The event name.\n * @returns {boolean}\n */\n hasEventHandler(event) {\n if (!this.events) {\n return false;\n }\n const type = `${this.options.namespace}.${event}`;\n return this.events.listeners(type).some((listener) => {\n if (!listener) {\n return false;\n }\n return listener.id === this.id || listener.key === this.key;\n });\n }\n /**\n * Wrapper method to add an event listener to an HTML element.\n *\n * @param obj\n * The DOM element to add the event to.\n * @param type\n * The event name to add.\n * @param func\n * The callback function to be executed when the listener is triggered.\n * @param persistent\n * If this listener should persist beyond \"destroy\" commands.\n */\n addEventListener(obj, type, func, persistent) {\n if (!obj) {\n return;\n }\n if (!persistent) {\n this.eventHandlers.push({ id: this.id, obj, type, func });\n }\n if ('addEventListener' in obj) {\n obj.addEventListener(type, func, false);\n }\n else if ('attachEvent' in obj) {\n obj.attachEvent(`on${type}`, func);\n }\n return this;\n }\n /**\n * Remove an event listener from the object.\n *\n * @param obj\n * @param type\n */\n removeEventListener(obj, type, func = null) {\n const indexes = [];\n if (!obj) {\n return;\n }\n this.eventHandlers.forEach((handler, index) => {\n if ((handler.id === this.id)\n && obj.removeEventListener\n && (handler.type === type)\n && (!func || handler.func === func)) {\n obj.removeEventListener(type, handler.func);\n indexes.push(index);\n }\n });\n if (indexes.length) {\n lodash_1.default.pullAt(this.eventHandlers, indexes);\n }\n return this;\n }\n removeEventListeners() {\n this.eventHandlers.forEach(handler => {\n if ((this.id === handler.id) && handler.type && handler.obj && handler.obj.removeEventListener) {\n handler.obj.removeEventListener(handler.type, handler.func);\n }\n });\n this.eventHandlers = [];\n }\n removeAllEvents(includeExternal) {\n if (this.events) {\n lodash_1.default.each(this.events._events, (events, type) => {\n lodash_1.default.each(events, (listener) => {\n if (listener && (this.id === listener.id) && (includeExternal || listener.internal)) {\n this.events.off(type, listener);\n }\n });\n });\n }\n }\n teardown() {\n delete this.i18next;\n delete this.events;\n }\n /**\n * Removes all event listeners attached to this component.\n */\n destroy(all = false) {\n this.removeEventListeners();\n this.removeAllEvents();\n if (all) {\n this.teardown();\n }\n }\n /**\n * Append an HTML DOM element to a container.\n *\n * @param element\n * @param container\n */\n appendTo(element, container) {\n container === null || container === void 0 ? void 0 : container.appendChild(element);\n return this;\n }\n /**\n * Prepend an HTML DOM element to a container.\n *\n * @param {HTMLElement} element - The DOM element to prepend.\n * @param {HTMLElement} container - The DOM element that is the container of the element getting prepended.\n */\n prependTo(element, container) {\n if (container) {\n if (container.firstChild) {\n try {\n container.insertBefore(element, container.firstChild);\n }\n catch (err) {\n console.warn(err);\n container.appendChild(element);\n }\n }\n else {\n container.appendChild(element);\n }\n }\n return this;\n }\n /**\n * Removes an HTML DOM element from its bounding container.\n *\n * @param {HTMLElement} element - The element to remove.\n * @param {HTMLElement} container - The DOM element that is the container of the element to remove.\n */\n removeChildFrom(element, container) {\n if (container && container.contains(element)) {\n try {\n container.removeChild(element);\n }\n catch (err) {\n console.warn(err);\n }\n }\n return this;\n }\n /**\n * Alias for document.createElement.\n *\n * @param {string} type - The type of element to create\n * @param {Object} attr - The element attributes to add to the created element.\n * @param {Various} children - Child elements. Can be a DOM Element, string or array of both.\n *\n * @return {HTMLElement} - The created element.\n */\n ce(type, attr, children = null) {\n // console.warn('Call to deprecated this.ce(). Dom elements should be created with templates, not manually with ce.');\n // Create the element.\n const element = document.createElement(type);\n // Add attributes.\n if (attr) {\n this.attr(element, attr);\n }\n // Append the children.\n this.appendChild(element, children);\n return element;\n }\n /**\n * Append different types of children.\n *\n * @param child\n */\n appendChild(element, child) {\n if (Array.isArray(child)) {\n child.forEach((oneChild) => this.appendChild(element, oneChild));\n }\n else if (child instanceof HTMLElement || child instanceof Text) {\n element.appendChild(child);\n }\n else if (child) {\n element.appendChild(this.text(child.toString()));\n }\n return this;\n }\n /**\n * Creates a new input mask placeholder.\n * @param {HTMLElement} mask - The input mask.\n * @returns {string} - The placeholder that will exist within the input as they type.\n */\n maskPlaceholder(mask) {\n return mask.map((char) => (char instanceof RegExp) ? this.placeholderChar : char).join('');\n }\n get placeholderChar() {\n var _a;\n return ((_a = this.component) === null || _a === void 0 ? void 0 : _a.inputMaskPlaceholderChar) || '_';\n }\n /**\n * Sets the input mask for an input.\n *\n * @param {HTMLElement} input - The html input to apply the mask to.\n * @param {String} inputMask - The input mask to add to this input.\n * @param {Boolean} usePlaceholder - Set the mask placeholder on the input.\n */\n setInputMask(input, inputMask, usePlaceholder) {\n if (input && inputMask) {\n const mask = FormioUtils.getInputMask(inputMask, this.placeholderChar);\n this.defaultMask = mask;\n try {\n //destroy previous mask\n if (input.mask) {\n input.mask.destroy();\n }\n input.mask = (0, vanilla_text_mask_1.default)({\n inputElement: input,\n mask,\n placeholderChar: this.placeholderChar,\n shadowRoot: this.root ? this.root.shadowRoot : null\n });\n }\n catch (e) {\n // Don't pass error up, to prevent form rejection.\n // Internal bug of vanilla-text-mask on iOS (`selectionEnd`);\n console.warn(e);\n }\n if (mask.numeric) {\n input.setAttribute('pattern', '\\\\d*');\n }\n if (usePlaceholder) {\n input.setAttribute('placeholder', this.maskPlaceholder(mask));\n }\n }\n }\n /**\n * Translate a text using the i18n system.\n *\n * @param {string|Array<string>} text - The i18n identifier.\n * @param {Object} params - The i18n parameters to use for translation.\n */\n t(text, ...args) {\n return this.i18next ? this.i18next.t(text, ...args) : text;\n }\n /**\n * Alias to create a text node.\n * @param text\n * @returns {Text}\n */\n text(text) {\n return document.createTextNode(this.t(text));\n }\n /**\n * Adds an object of attributes onto an element.\n * @param {HtmlElement} element - The element to add the attributes to.\n * @param {Object} attr - The attributes to add to the input element.\n */\n attr(element, attr) {\n if (!element) {\n return;\n }\n lodash_1.default.each(attr, (value, key) => {\n if (typeof value !== 'undefined') {\n if (key.indexOf('on') === 0) {\n // If this is an event, add a listener.\n this.addEventListener(element, key.substr(2).toLowerCase(), value);\n }\n else {\n // Otherwise it is just an attribute.\n element.setAttribute(key, value);\n }\n }\n });\n }\n /**\n * Determines if an element has a class.\n *\n * Taken from jQuery https://j11y.io/jquery/#v=1.5.0&fn=jQuery.fn.hasClass\n */\n hasClass(element, className) {\n if (!element) {\n return false;\n }\n // Allow templates to intercept.\n className = ` ${className} `;\n return ((` ${element.className} `).replace(/[\\n\\t\\r]/g, ' ').indexOf(className) > -1);\n }\n /**\n * Adds a class to a DOM element.\n *\n * @param element\n * The element to add a class to.\n * @param className\n * The name of the class to add.\n */\n addClass(element, className) {\n if (!element || !(element instanceof HTMLElement)) {\n return this;\n }\n // Allow templates to intercept.\n const classes = element.getAttribute('class');\n if (!(classes === null || classes === void 0 ? void 0 : classes.includes(className))) {\n element.setAttribute('class', `${classes} ${className}`);\n }\n return this;\n }\n /**\n * Remove a class from a DOM element.\n *\n * @param element\n * The DOM element to remove the class from.\n * @param className\n * The name of the class that is to be removed.\n */\n removeClass(element, className) {\n if (!element || !className || !(element instanceof HTMLElement)) {\n return this;\n }\n // Allow templates to intercept.\n let cls = element.getAttribute('class');\n if (cls) {\n cls = cls.replace(new RegExp(` ${className}`, 'g'), '');\n element.setAttribute('class', cls);\n }\n return this;\n }\n /**\n * Empty's an HTML DOM element.\n *\n * @param {HTMLElement} element - The element you wish to empty.\n */\n empty(element) {\n if (element) {\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n }\n }\n /**\n * Create an evaluation context for all script executions and interpolations.\n *\n * @param additional\n * @return {*}\n */\n evalContext(additional) {\n var _a;\n return Object.assign({\n _: lodash_1.default,\n utils: FormioUtils,\n util: FormioUtils,\n user: Formio_1.Formio.getUser(),\n moment: moment_1.default,\n instance: this,\n self: this,\n token: Formio_1.Formio.getToken({\n decode: true\n }),\n config: this.root && this.root.form && this.root.form.config\n ? this.root.form.config\n : ((_a = this.options) === null || _a === void 0 ? void 0 : _a.formConfig)\n ? this.options.formConfig\n : {},\n }, additional, lodash_1.default.get(this.root, 'options.evalContext', {}));\n }\n /**\n * Performs an interpolation using the evaluation context of this component.\n *\n * @param string\n * @param data\n * @return {XML|string|*|void}\n */\n interpolate(string, data, options = {}) {\n if (typeof string !== 'function' && (this.component.content || this.component.html)\n && !FormioUtils.Evaluator.templateSettings.interpolate.test(string)) {\n string = FormioUtils.translateHTMLTemplate(String(string), (value) => this.t(value));\n }\n return FormioUtils.interpolate(string, this.evalContext(data), options);\n }\n /**\n * Performs an evaluation using the evaluation context of this component.\n *\n * @param func\n * @param args\n * @param ret\n * @param tokenize\n * @return {*}\n */\n evaluate(func, args, ret, tokenize) {\n return FormioUtils.evaluate(func, this.evalContext(args), ret, tokenize);\n }\n /**\n * Allow for options to hook into the functionality of this renderer.\n * @return {*}\n */\n hook() {\n const name = arguments[0];\n if (this.options &&\n this.options.hooks &&\n this.options.hooks[name]) {\n return this.options.hooks[name].apply(this, Array.prototype.slice.call(arguments, 1));\n }\n else {\n // If this is an async hook instead of a sync.\n const fn = (typeof arguments[arguments.length - 1] === 'function') ? arguments[arguments.length - 1] : null;\n if (fn) {\n return fn(null, arguments[1]);\n }\n else {\n return arguments[1];\n }\n }\n }\n}\nexports[\"default\"] = Element;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Element.js?");
|
4794
|
+
eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst EventEmitter_1 = __importDefault(__webpack_require__(/*! ./EventEmitter */ \"./lib/cjs/EventEmitter.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst FormioUtils = __importStar(__webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\"));\nconst i18n_1 = __webpack_require__(/*! ./utils/i18n */ \"./lib/cjs/utils/i18n.js\");\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst moment_1 = __importDefault(__webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\"));\nconst vanilla_text_mask_1 = __importDefault(__webpack_require__(/*! @formio/vanilla-text-mask */ \"./node_modules/@formio/vanilla-text-mask/dist/vanillaTextMask.js\"));\n/**\n * The root component for all elements within the Form.io renderer.\n */\nclass Element {\n constructor(options) {\n var _a;\n /**\n * The options for this component.\n * @type {{}}\n */\n this.options = Object.assign({\n language: 'en',\n highlightErrors: true,\n componentErrorClass: 'formio-error-wrapper',\n componentWarningClass: 'formio-warning-wrapper',\n row: '',\n namespace: 'formio'\n }, options || {});\n /**\n * The ID of this component. This value is auto-generated when the component is created, but\n * can also be provided from the component.id value passed into the constructor.\n * @type {string}\n */\n this.id = FormioUtils.getRandomComponentId();\n /**\n * An array of event handlers so that the destry command can deregister them.\n * @type {Array}\n */\n this.eventHandlers = [];\n // Use the i18next that is passed in, otherwise use the global version.\n this.options.i18n = this.options.i18n || {};\n if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.language) {\n this.options.i18n.language = this.options.language;\n }\n this.options.i18next = this.i18next = this.options.i18next || i18n_1.I18n.init(this.options.i18n);\n /**\n * An instance of the EventEmitter class to handle the emitting and registration of events.\n *\n * @type {EventEmitter}\n */\n this.events = (options && options.events) ? options.events : new EventEmitter_1.default();\n this.defaultMask = null;\n /**\n * Conditional to show or hide helplinks in editForm\n *\n * @type {*|boolean}\n */\n this.helplinks = (this.options.helplinks === 'false') ? false : (this.options.helplinks || 'https://help.form.io');\n }\n /**\n * Register for a new event within this component.\n *\n * @example\n * let component = new BaseComponent({\n * type: 'textfield',\n * label: 'First Name',\n * key: 'firstName'\n * });\n * component.on('componentChange', (changed) => {\n * console.log('this element is changed.');\n * });\n *\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function} cb - The callback handler to handle this event.\n */\n on(event, cb, internal, once = false) {\n if (!this.events) {\n return;\n }\n const type = `${this.options.namespace}.${event}`;\n // Store the component id in the handler so that we can determine which events are for this component.\n cb.id = this.id;\n cb.key = this.key;\n cb.internal = internal;\n // Register for this event.\n return this.events[once ? 'once' : 'on'](type, cb);\n }\n /**\n * Register for a new single-fire event within this component.\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function} cb - The callback handler to handle this event.\n */\n once(event, cb, internal) {\n return this.on(event, cb, internal, true);\n }\n /**\n * Allow catching any event.\n *\n * @param cb\n * @returns {this}\n */\n onAny(cb) {\n if (!this.events) {\n return;\n }\n return this.events.onAny(cb);\n }\n /**\n * Removes the listener that will be fired when any event is emitted.\n *\n * @param cb\n * @returns {this}\n */\n offAny(cb) {\n if (!this.events) {\n return;\n }\n return this.events.offAny(cb);\n }\n /**\n * Removes a listener for a certain event. Not passing the 2nd arg will remove all listeners for that event.\n *\n * @param {string} event - The event you wish to register the handler for.\n * @param {function|undefined} cb - The callback handler to handle this event.\n */\n off(event, cb) {\n if (!this.events) {\n return;\n }\n const type = `${this.options.namespace}.${event}`;\n this.events.listeners(type).forEach((listener) => {\n // Ensure the listener is for this element\n if (!listener || listener.id !== this.id) {\n return;\n }\n // If there is a given callback, only deal with the match\n if (cb && cb !== listener) {\n return;\n }\n this.events.off(type, listener);\n });\n }\n /**\n * Emit a new event.\n *\n * @param {string} event - The event to emit.\n * @param {Object} data - The data to emit with the handler.\n */\n emit(event, ...data) {\n if (this.events) {\n this.events.emit(`${this.options.namespace}.${event}`, ...data);\n }\n }\n /**\n * Check if the component has an event handler set up for the event.\n *\n * @param {string} event - The event name.\n * @returns {boolean}\n */\n hasEventHandler(event) {\n if (!this.events) {\n return false;\n }\n const type = `${this.options.namespace}.${event}`;\n return this.events.listeners(type).some((listener) => {\n if (!listener) {\n return false;\n }\n return listener.id === this.id || listener.key === this.key;\n });\n }\n /**\n * Wrapper method to add an event listener to an HTML element.\n *\n * @param obj\n * The DOM element to add the event to.\n * @param type\n * The event name to add.\n * @param func\n * The callback function to be executed when the listener is triggered.\n * @param persistent\n * If this listener should persist beyond \"destroy\" commands.\n */\n addEventListener(obj, type, func, persistent) {\n if (!obj) {\n return;\n }\n if (!persistent) {\n this.eventHandlers.push({ id: this.id, obj, type, func });\n }\n if ('addEventListener' in obj) {\n obj.addEventListener(type, func, false);\n }\n else if ('attachEvent' in obj) {\n obj.attachEvent(`on${type}`, func);\n }\n return this;\n }\n /**\n * Remove an event listener from the object.\n *\n * @param obj\n * @param type\n */\n removeEventListener(obj, type, func = null) {\n const indexes = [];\n if (!obj) {\n return;\n }\n this.eventHandlers.forEach((handler, index) => {\n if ((handler.id === this.id)\n && obj.removeEventListener\n && (handler.type === type)\n && (!func || handler.func === func)) {\n obj.removeEventListener(type, handler.func);\n indexes.push(index);\n }\n });\n if (indexes.length) {\n lodash_1.default.pullAt(this.eventHandlers, indexes);\n }\n return this;\n }\n removeEventListeners() {\n this.eventHandlers.forEach(handler => {\n if ((this.id === handler.id) && handler.type && handler.obj && handler.obj.removeEventListener) {\n handler.obj.removeEventListener(handler.type, handler.func);\n }\n });\n this.eventHandlers = [];\n }\n removeAllEvents(includeExternal) {\n if (this.events) {\n lodash_1.default.each(this.events._events, (events, type) => {\n lodash_1.default.each(events, (listener) => {\n if (listener && (this.id === listener.id) && (includeExternal || listener.internal)) {\n this.events.off(type, listener);\n }\n });\n });\n }\n }\n teardown() {\n delete this.i18next;\n delete this.events;\n }\n /**\n * Removes all event listeners attached to this component.\n */\n destroy(all = false) {\n this.removeEventListeners();\n this.removeAllEvents();\n if (all) {\n this.teardown();\n }\n }\n /**\n * Append an HTML DOM element to a container.\n *\n * @param element\n * @param container\n */\n appendTo(element, container) {\n container === null || container === void 0 ? void 0 : container.appendChild(element);\n return this;\n }\n /**\n * Prepend an HTML DOM element to a container.\n *\n * @param {HTMLElement} element - The DOM element to prepend.\n * @param {HTMLElement} container - The DOM element that is the container of the element getting prepended.\n */\n prependTo(element, container) {\n if (container) {\n if (container.firstChild) {\n try {\n container.insertBefore(element, container.firstChild);\n }\n catch (err) {\n console.warn(err);\n container.appendChild(element);\n }\n }\n else {\n container.appendChild(element);\n }\n }\n return this;\n }\n /**\n * Removes an HTML DOM element from its bounding container.\n *\n * @param {HTMLElement} element - The element to remove.\n * @param {HTMLElement} container - The DOM element that is the container of the element to remove.\n */\n removeChildFrom(element, container) {\n if (container && container.contains(element)) {\n try {\n container.removeChild(element);\n }\n catch (err) {\n console.warn(err);\n }\n }\n return this;\n }\n /**\n * Alias for document.createElement.\n *\n * @param {string} type - The type of element to create\n * @param {Object} attr - The element attributes to add to the created element.\n * @param {Various} children - Child elements. Can be a DOM Element, string or array of both.\n *\n * @return {HTMLElement} - The created element.\n */\n ce(type, attr, children = null) {\n // console.warn('Call to deprecated this.ce(). Dom elements should be created with templates, not manually with ce.');\n // Create the element.\n const element = document.createElement(type);\n // Add attributes.\n if (attr) {\n this.attr(element, attr);\n }\n // Append the children.\n this.appendChild(element, children);\n return element;\n }\n /**\n * Append different types of children.\n *\n * @param child\n */\n appendChild(element, child) {\n if (Array.isArray(child)) {\n child.forEach((oneChild) => this.appendChild(element, oneChild));\n }\n else if (child instanceof HTMLElement || child instanceof Text) {\n element.appendChild(child);\n }\n else if (child) {\n element.appendChild(this.text(child.toString()));\n }\n return this;\n }\n /**\n * Creates a new input mask placeholder.\n * @param {HTMLElement} mask - The input mask.\n * @returns {string} - The placeholder that will exist within the input as they type.\n */\n maskPlaceholder(mask) {\n return mask.map((char) => (char instanceof RegExp) ? this.placeholderChar : char).join('');\n }\n get placeholderChar() {\n var _a;\n return ((_a = this.component) === null || _a === void 0 ? void 0 : _a.inputMaskPlaceholderChar) || '_';\n }\n /**\n * Sets the input mask for an input.\n *\n * @param {HTMLElement} input - The html input to apply the mask to.\n * @param {String} inputMask - The input mask to add to this input.\n * @param {Boolean} usePlaceholder - Set the mask placeholder on the input.\n */\n setInputMask(input, inputMask, usePlaceholder) {\n if (input && inputMask) {\n const mask = FormioUtils.getInputMask(inputMask, this.placeholderChar);\n this.defaultMask = mask;\n try {\n //destroy previous mask\n if (input.mask) {\n input.mask.destroy();\n }\n input.mask = (0, vanilla_text_mask_1.default)({\n inputElement: input,\n mask,\n placeholderChar: this.placeholderChar,\n shadowRoot: this.root ? this.root.shadowRoot : null\n });\n }\n catch (e) {\n // Don't pass error up, to prevent form rejection.\n // Internal bug of vanilla-text-mask on iOS (`selectionEnd`);\n console.warn(e);\n }\n if (mask.numeric) {\n input.setAttribute('pattern', '\\\\d*');\n }\n if (usePlaceholder) {\n input.setAttribute('placeholder', this.maskPlaceholder(mask));\n }\n }\n }\n /**\n * Translate a text using the i18n system.\n *\n * @param {string|Array<string>} text - The i18n identifier.\n * @param {Object} params - The i18n parameters to use for translation.\n */\n t(text, ...args) {\n return this.i18next ? this.i18next.t(text, ...args) : text;\n }\n /**\n * Alias to create a text node.\n * @param text\n * @returns {Text}\n */\n text(text) {\n return document.createTextNode(this.t(text));\n }\n /**\n * Adds an object of attributes onto an element.\n * @param {HtmlElement} element - The element to add the attributes to.\n * @param {Object} attr - The attributes to add to the input element.\n */\n attr(element, attr) {\n if (!element) {\n return;\n }\n lodash_1.default.each(attr, (value, key) => {\n if (typeof value !== 'undefined') {\n if (key.indexOf('on') === 0) {\n // If this is an event, add a listener.\n this.addEventListener(element, key.substr(2).toLowerCase(), value);\n }\n else {\n // Otherwise it is just an attribute.\n element.setAttribute(key, value);\n }\n }\n });\n }\n /**\n * Determines if an element has a class.\n *\n * Taken from jQuery https://j11y.io/jquery/#v=1.5.0&fn=jQuery.fn.hasClass\n */\n hasClass(element, className) {\n if (!element) {\n return false;\n }\n // Allow templates to intercept.\n className = ` ${className} `;\n return ((` ${element.className} `).replace(/[\\n\\t\\r]/g, ' ').indexOf(className) > -1);\n }\n /**\n * Adds a class to a DOM element.\n *\n * @param element\n * The element to add a class to.\n * @param className\n * The name of the class to add.\n */\n addClass(element, className) {\n if (!element || !(element instanceof HTMLElement)) {\n return this;\n }\n // Allow templates to intercept.\n const classes = element.getAttribute('class');\n if (!(classes === null || classes === void 0 ? void 0 : classes.includes(className))) {\n element.setAttribute('class', `${classes} ${className}`);\n }\n return this;\n }\n /**\n * Remove a class from a DOM element.\n *\n * @param element\n * The DOM element to remove the class from.\n * @param className\n * The name of the class that is to be removed.\n */\n removeClass(element, className) {\n if (!element || !className || !(element instanceof HTMLElement)) {\n return this;\n }\n // Allow templates to intercept.\n let cls = element.getAttribute('class');\n if (cls) {\n cls = cls.replace(new RegExp(` ${className}`, 'g'), '');\n element.setAttribute('class', cls);\n }\n return this;\n }\n /**\n * Empty's an HTML DOM element.\n *\n * @param {HTMLElement} element - The element you wish to empty.\n */\n empty(element) {\n if (element) {\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n }\n }\n /**\n * Create an evaluation context for all script executions and interpolations.\n *\n * @param additional\n * @return {*}\n */\n evalContext(additional) {\n var _a;\n return Object.assign({\n _: lodash_1.default,\n utils: FormioUtils,\n util: FormioUtils,\n user: Formio_1.Formio.getUser(),\n moment: moment_1.default,\n instance: this,\n self: this,\n token: Formio_1.Formio.getToken({\n decode: true\n }),\n config: this.root && this.root.form && this.root.form.config\n ? this.root.form.config\n : ((_a = this.options) === null || _a === void 0 ? void 0 : _a.formConfig)\n ? this.options.formConfig\n : {},\n }, additional, lodash_1.default.get(this.root, 'options.evalContext', {}));\n }\n /**\n * Performs an interpolation using the evaluation context of this component.\n *\n * @param string\n * @param data\n * @return {XML|string|*|void}\n */\n interpolate(string, data, options = {}) {\n if (typeof string !== 'function' && (this.component.content || this.component.html)\n && !FormioUtils.Evaluator.templateSettings.interpolate.test(string)) {\n string = FormioUtils.translateHTMLTemplate(String(string), (value) => this.t(value));\n }\n if (this.component.filter === string && !this.options.building) {\n const evalContext = this.evalContext(data);\n evalContext.data = lodash_1.default.mapValues(evalContext.data, (val) => lodash_1.default.isString(val) ? encodeURIComponent(val) : val);\n return FormioUtils.interpolate(string, evalContext, options);\n }\n return FormioUtils.interpolate(string, this.evalContext(data), options);\n }\n /**\n * Performs an evaluation using the evaluation context of this component.\n *\n * @param func\n * @param args\n * @param ret\n * @param tokenize\n * @return {*}\n */\n evaluate(func, args, ret, tokenize) {\n return FormioUtils.evaluate(func, this.evalContext(args), ret, tokenize);\n }\n /**\n * Allow for options to hook into the functionality of this renderer.\n * @return {*}\n */\n hook() {\n const name = arguments[0];\n if (this.options &&\n this.options.hooks &&\n this.options.hooks[name]) {\n return this.options.hooks[name].apply(this, Array.prototype.slice.call(arguments, 1));\n }\n else {\n // If this is an async hook instead of a sync.\n const fn = (typeof arguments[arguments.length - 1] === 'function') ? arguments[arguments.length - 1] : null;\n if (fn) {\n return fn(null, arguments[1]);\n }\n else {\n return arguments[1];\n }\n }\n }\n}\nexports[\"default\"] = Element;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Element.js?");
|
4795
4795
|
|
4796
4796
|
/***/ }),
|
4797
4797
|
|
@@ -5231,7 +5231,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5231
5231
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5232
5232
|
|
5233
5233
|
"use strict";
|
5234
|
-
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 moment_1 = __importDefault(__webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\"));\nconst Field_1 = __importDefault(__webpack_require__(/*! ../_classes/field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass DayComponent extends Field_1.default {\n static schema(...extend) {\n return Field_1.default.schema({\n type: 'day',\n label: 'Day',\n key: 'day',\n fields: {\n day: {\n type: 'number',\n placeholder: '',\n required: false\n },\n month: {\n type: 'select',\n placeholder: '',\n required: false\n },\n year: {\n type: 'number',\n placeholder: '',\n required: false\n }\n },\n dayFirst: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Day',\n group: 'advanced',\n icon: 'calendar',\n documentation: '/userguide/form-building/advanced-components#day',\n weight: 50,\n schema: DayComponent.schema()\n };\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: ['isDateEqual', 'isNotDateEqual', 'isEmpty', 'isNotEmpty', 'dateLessThan', 'dateGreaterThan', 'dateLessThanOrEqual', 'dateGreaterThanOrEqual'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.string];\n }\n constructor(component, options, data) {\n if (component.maxDate) {\n component.maxDate = (0, moment_1.default)(component.maxDate, 'YYYY-MM-DD').toISOString();\n }\n if (component.minDate) {\n component.minDate = (0, moment_1.default)(component.minDate, 'YYYY-MM-DD').toISOString();\n }\n super(component, options, data);\n }\n static get serverConditionSettings() {\n return DayComponent.conditionOperatorsSettings;\n }\n /**\n * The empty value for day component.\n *\n * @return {'00/00/0000'}\n */\n get emptyValue() {\n return '00/00/0000';\n }\n get valueMask() {\n return /^\\d{2}\\/\\d{2}\\/\\d{4}$/;\n }\n get dayRequired() {\n return this.showDay && lodash_1.default.get(this.component, 'fields.day.required', false);\n }\n get showDay() {\n return !lodash_1.default.get(this.component, 'fields.day.hide', false);\n }\n get monthRequired() {\n return this.showMonth && lodash_1.default.get(this.component, 'fields.month.required', false);\n }\n get showMonth() {\n return !lodash_1.default.get(this.component, 'fields.month.hide', false);\n }\n get yearRequired() {\n return this.showYear && lodash_1.default.get(this.component, 'fields.year.required', false);\n }\n get showYear() {\n return !lodash_1.default.get(this.component, 'fields.year.hide', false);\n }\n get defaultSchema() {\n return DayComponent.schema();\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'input';\n info.attr.type = 'hidden';\n info.changeEvent = 'input';\n return info;\n }\n inputDefinition(name) {\n let min, max;\n if (name === 'day') {\n min = 1;\n max = 31;\n }\n if (name === 'month') {\n min = 1;\n max = 12;\n }\n if (name === 'year') {\n min = lodash_1.default.get(this.component, 'fields.year.minYear', 1900) || 1900;\n max = lodash_1.default.get(this.component, 'fields.year.maxYear', 2030) || 1900;\n }\n return {\n type: 'input',\n ref: name,\n attr: {\n id: `${this.component.key}-${name}`,\n class: `form-control ${this.transform('class', `formio-day-component-${name}`)}`,\n type: this.component.fields[name].type === 'select' ? 'select' : 'number',\n placeholder: this.component.fields[name].placeholder,\n step: 1,\n min,\n max,\n }\n };\n }\n selectDefinition(name) {\n return {\n multiple: false,\n ref: name,\n widget: 'html5',\n attr: {\n id: `${this.component.key}-${name}`,\n class: 'form-control',\n name,\n lang: this.options.language\n }\n };\n }\n get days() {\n if (this._days) {\n return this._days;\n }\n this._days = [\n { value: '', label: lodash_1.default.get(this.component, 'fields.day.placeholder', '') }\n ];\n for (let x = 1; x <= 31; x++) {\n this._days.push({\n value: x,\n label: x.toString()\n });\n }\n return this._days;\n }\n get months() {\n if (this._months) {\n return this._months;\n }\n this._months = [\n {\n value: '',\n label: lodash_1.default.get(this.component, 'fields.month.placeholder') || (this.hideInputLabels ? this.t('Month') : '')\n },\n { value: 1, label: 'January' },\n { value: 2, label: 'February' },\n { value: 3, label: 'March' },\n { value: 4, label: 'April' },\n { value: 5, label: 'May' },\n { value: 6, label: 'June' },\n { value: 7, label: 'July' },\n { value: 8, label: 'August' },\n { value: 9, label: 'September' },\n { value: 10, label: 'October' },\n { value: 11, label: 'November' },\n { value: 12, label: 'December' }\n ];\n return this._months;\n }\n get years() {\n if (this._years) {\n return this._years;\n }\n this._years = [\n { value: '', label: lodash_1.default.get(this.component, 'fields.year.placeholder', '') }\n ];\n const minYears = lodash_1.default.get(this.component, 'fields.year.minYear', 1900) || 1900;\n const maxYears = lodash_1.default.get(this.component, 'fields.year.maxYear', 2030) || 2030;\n for (let x = minYears; x <= maxYears; x++) {\n this._years.push({\n value: x,\n label: x.toString()\n });\n }\n return this._years;\n }\n setErrorClasses(elements, dirty, hasError) {\n super.setErrorClasses(elements, dirty, hasError);\n super.setErrorClasses([this.refs.day, this.refs.month, this.refs.year], dirty, hasError);\n }\n removeInputError(elements) {\n super.removeInputError([this.refs.day, this.refs.month, this.refs.year]);\n super.removeInputError(elements);\n }\n init() {\n super.init();\n this.validators = this.validators.concat(['day', 'maxDate', 'minDate', 'minYear', 'maxYear']);\n const minYear = this.component.fields.year.minYear;\n const maxYear = this.component.fields.year.maxYear;\n this.component.maxYear = maxYear;\n this.component.minYear = minYear;\n const dateFormatInfo = (0, utils_1.getLocaleDateFormatInfo)(this.options.language);\n this.dayFirst = this.component.useLocaleSettings\n ? dateFormatInfo.dayFirst\n : this.component.dayFirst;\n }\n render() {\n if (this.isHtmlRenderMode()) {\n return super.render(this.renderTemplate('input'));\n }\n return super.render(this.renderTemplate('day', {\n dayFirst: this.dayFirst,\n showDay: this.showDay,\n showMonth: this.showMonth,\n showYear: this.showYear,\n day: this.renderField('day'),\n month: this.renderField('month'),\n year: this.renderField('year'),\n }));\n }\n renderField(name) {\n if (this.component.fields[name].type === 'select') {\n return this.renderTemplate('select', {\n input: this.selectDefinition(name),\n selectOptions: this[`${name}s`].reduce((html, option) => html + this.renderTemplate('selectOption', {\n option,\n selected: false,\n attrs: {}\n }), ''),\n });\n }\n else {\n return this.renderTemplate('input', {\n prefix: this.prefix,\n suffix: this.suffix,\n input: this.inputDefinition(name)\n });\n }\n }\n attach(element) {\n this.loadRefs(element, { day: 'single', month: 'single', year: 'single', input: 'multiple' });\n const superAttach = super.attach(element);\n if (this.shouldDisabled) {\n this.setDisabled(this.refs.day, true);\n this.setDisabled(this.refs.month, true);\n this.setDisabled(this.refs.year, true);\n if (this.refs.input) {\n this.refs.input.forEach((input) => this.setDisabled(input, true));\n }\n }\n else {\n this.addEventListener(this.refs.day, 'input', () => this.updateValue(null, {\n modified: true\n }));\n // TODO: Need to rework this to work with day select as well.\n // Change day max input when month changes.\n this.addEventListener(this.refs.month, 'input', () => {\n const maxDay = this.refs.year ? parseInt(new Date(this.refs.year.value, this.refs.month.value, 0).getDate(), 10)\n : '';\n const day = this.getFieldValue('day');\n if (!this.component.fields.day.hide && maxDay) {\n this.refs.day.max = maxDay;\n }\n if (maxDay && day > maxDay) {\n this.refs.day.value = this.refs.day.max;\n }\n this.updateValue(null, {\n modified: true\n });\n });\n this.addEventListener(this.refs.year, 'input', () => this.updateValue(null, {\n modified: true\n }));\n this.addEventListener(this.refs.input, this.info.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n }\n this.setValue(this.dataValue);\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n return superAttach;\n }\n validateRequired(setting, value) {\n const { day, month, year } = this.parts;\n if (this.dayRequired && !day) {\n return false;\n }\n if (this.monthRequired && !month) {\n return false;\n }\n if (this.yearRequired && !year) {\n return false;\n }\n if (!(0, utils_1.boolValue)(setting)) {\n return true;\n }\n return !this.isEmpty(value);\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.refs.year || !this.refs.month || !this.refs.day) {\n return;\n }\n if (disabled) {\n this.refs.year.setAttribute('disabled', 'disabled');\n this.refs.month.setAttribute('disabled', 'disabled');\n this.refs.day.setAttribute('disabled', 'disabled');\n }\n else {\n this.refs.year.removeAttribute('disabled');\n this.refs.month.removeAttribute('disabled');\n this.refs.day.removeAttribute('disabled');\n }\n }\n normalizeValue(value) {\n if (!value || this.valueMask.test(value)) {\n return value;\n }\n const dateParts = [];\n const valueParts = value.split('/');\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const defaultValue = this.component.defaultValue ? this.component.defaultValue.split('/') : '';\n const getNextPart = (shouldTake, defaultValue) => dateParts.push(shouldTake ? valueParts.shift() : defaultValue);\n if (this.dayFirst) {\n getNextPart(this.showDay, defaultValue ? defaultValue[DAY] : '00');\n }\n getNextPart(this.showMonth, defaultValue ? defaultValue[MONTH] : '00');\n if (!this.dayFirst) {\n getNextPart(this.showDay, defaultValue ? defaultValue[DAY] : '00');\n }\n getNextPart(this.showYear, defaultValue ? defaultValue[YEAR] : '0000');\n return dateParts.join('/');\n }\n /**\n * Set the value at a specific index.\n *\n * @param index\n * @param value\n */\n setValueAt(index, value) {\n // temporary solution to avoid input reset\n // on invalid date.\n if (!value || value === 'Invalid date') {\n return null;\n }\n const parts = value.split('/');\n let day;\n if (this.component.dayFirst) {\n day = parts.shift();\n }\n const month = parts.shift();\n if (!this.component.dayFirst) {\n day = parts.shift();\n }\n const year = parts.shift();\n if (this.refs.day && this.showDay) {\n this.refs.day.value = day === '00' ? '' : parseInt(day, 10);\n }\n if (this.refs.month && this.showMonth) {\n this.refs.month.value = month === '00' ? '' : parseInt(month, 10);\n }\n if (this.refs.year && this.showYear) {\n this.refs.year.value = year === '0000' ? '' : parseInt(year, 10);\n }\n }\n getFieldValue(name) {\n const parts = this.dataValue ? this.dataValue.split('/') : [];\n let val = 0;\n switch (name) {\n case 'month':\n val = parts[this.dayFirst ? 1 : 0];\n break;\n case 'day':\n val = parts[this.dayFirst ? 0 : 1];\n break;\n case 'year':\n val = parts[2];\n break;\n }\n val = parseInt(val, 10);\n return (!lodash_1.default.isNaN(val) && lodash_1.default.isNumber(val)) ? val : 0;\n }\n get parts() {\n return {\n day: this.getFieldValue('day'),\n month: this.getFieldValue('month'),\n year: this.getFieldValue('year'),\n };\n }\n /**\n * Get the format for the value string.\n * @returns {string}\n */\n get format() {\n let format = '';\n if (this.component.dayFirst && this.showDay) {\n format += 'D/';\n }\n if (this.showMonth) {\n format += 'M/';\n }\n if (!this.component.dayFirst && this.showDay) {\n format += 'D/';\n }\n if (this.showYear) {\n format += 'YYYY';\n return format;\n }\n else {\n // Trim off the \"/\" from the end of the format string.\n return format.length ? format.substring(0, format.length - 1) : format;\n }\n }\n /**\n * Return the date for this component.\n *\n * @param value\n * @return {*}\n */\n getDate(value) {\n let defaults = [], day, month, year;\n // Map positions to identifiers to get default values for each part of day\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const defaultValue = value || this.component.defaultValue;\n if (defaultValue) {\n defaults = defaultValue.split('/').map(x => parseInt(x, 10));\n }\n if (this.showDay && this.refs.day) {\n day = parseInt(this.refs.day.value, 10);\n }\n if (day === undefined || lodash_1.default.isNaN(day)) {\n day = defaults[DAY] && !lodash_1.default.isNaN(defaults[DAY]) ? defaults[DAY] : 0;\n }\n if (this.showMonth && this.refs.month) {\n // Months are 0 indexed.\n month = parseInt(this.refs.month.value, 10);\n }\n if (month === undefined || lodash_1.default.isNaN(month)) {\n month = defaults[MONTH] && !lodash_1.default.isNaN(defaults[MONTH]) ? defaults[MONTH] : 0;\n }\n if (this.showYear && this.refs.year) {\n year = parseInt(this.refs.year.value);\n }\n if (year === undefined || lodash_1.default.isNaN(year)) {\n year = defaults[YEAR] && !lodash_1.default.isNaN(defaults[YEAR]) ? defaults[YEAR] : 0;\n }\n let result;\n if (!day && !month && !year) {\n return null;\n }\n // add trailing zeros if the data is showed\n day = this.showDay ? day.toString().padStart(2, 0) : '';\n month = this.showMonth ? month.toString().padStart(2, 0) : '';\n year = this.showYear ? year.toString().padStart(4, 0) : '';\n if (this.component.dayFirst) {\n result = `${day}${this.showDay && this.showMonth || this.showDay && this.showYear ? '/' : ''}${month}${this.showMonth && this.showYear ? '/' : ''}${year}`;\n }\n else {\n result = `${month}${this.showDay && this.showMonth || this.showMonth && this.showYear ? '/' : ''}${day}${this.showDay && this.showYear ? '/' : ''}${year}`;\n }\n return result;\n }\n /**\n * Return the date object for this component.\n * @returns {Date}\n */\n get date() {\n return this.getDate();\n }\n /**\n * Return the raw value.\n *\n * @returns {Date}\n */\n get validationValue() {\n return this.dataValue;\n }\n getValue() {\n const result = super.getValue();\n return (!result) ? this.dataValue : result;\n }\n /**\n * Get the value at a specific index.\n *\n * @param index\n * @returns {*}\n */\n getValueAt(index) {\n const date = this.date || this.emptyValue;\n if (date) {\n this.refs.input[index].value = date;\n return this.refs.input[index].value;\n }\n else {\n this.refs.input[index].value = '';\n return null;\n }\n }\n /**\n * Get the input value of the date.\n *\n * @param value\n * @return {null}\n */\n getValueAsString(value) {\n return this.getDate(value) || '';\n }\n focus() {\n var _a, _b, _c;\n if (this.dayFirst && this.showDay || !this.dayFirst && !this.showMonth && this.showDay) {\n (_a = this.refs.day) === null || _a === void 0 ? void 0 : _a.focus();\n }\n else if (this.dayFirst && !this.showDay && this.showMonth || !this.dayFirst && this.showMonth) {\n (_b = this.refs.month) === null || _b === void 0 ? void 0 : _b.focus();\n }\n else if (!this.showDay && !this.showDay && this.showYear) {\n (_c = this.refs.year) === null || _c === void 0 ? void 0 : _c.focus();\n }\n }\n isPartialDay(value) {\n if (!value) {\n return false;\n }\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const values = value.split('/');\n return (values[DAY] === '00' || values[MONTH] === '00' || values[YEAR] === '0000');\n }\n getValidationFormat() {\n return this.dayFirst ? 'DD-MM-YYYY' : 'MM-DD-YYYY';\n }\n}\nexports[\"default\"] = DayComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/day/Day.js?");
|
5234
|
+
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 moment_1 = __importDefault(__webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\"));\nconst Field_1 = __importDefault(__webpack_require__(/*! ../_classes/field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nclass DayComponent extends Field_1.default {\n static schema(...extend) {\n return Field_1.default.schema({\n type: 'day',\n label: 'Day',\n key: 'day',\n fields: {\n day: {\n type: 'number',\n placeholder: '',\n required: false\n },\n month: {\n type: 'select',\n placeholder: '',\n required: false\n },\n year: {\n type: 'number',\n placeholder: '',\n required: false\n }\n },\n dayFirst: false\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Day',\n group: 'advanced',\n icon: 'calendar',\n documentation: '/userguide/form-building/advanced-components#day',\n weight: 50,\n schema: DayComponent.schema()\n };\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: ['isDateEqual', 'isNotDateEqual', 'isEmpty', 'isNotEmpty', 'dateLessThan', 'dateGreaterThan', 'dateLessThanOrEqual', 'dateGreaterThanOrEqual'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.string];\n }\n constructor(component, options, data) {\n if (component.maxDate) {\n component.maxDate = (0, moment_1.default)(component.maxDate, 'YYYY-MM-DD').toISOString();\n }\n if (component.minDate) {\n component.minDate = (0, moment_1.default)(component.minDate, 'YYYY-MM-DD').toISOString();\n }\n super(component, options, data);\n }\n static get serverConditionSettings() {\n return DayComponent.conditionOperatorsSettings;\n }\n /**\n * The empty value for day component.\n *\n * @return {'00/00/0000'}\n */\n get emptyValue() {\n return '00/00/0000';\n }\n get valueMask() {\n return /^\\d{2}\\/\\d{2}\\/\\d{4}$/;\n }\n get dayRequired() {\n return this.showDay && lodash_1.default.get(this.component, 'fields.day.required', false);\n }\n get showDay() {\n return !lodash_1.default.get(this.component, 'fields.day.hide', false);\n }\n get monthRequired() {\n return this.showMonth && lodash_1.default.get(this.component, 'fields.month.required', false);\n }\n get showMonth() {\n return !lodash_1.default.get(this.component, 'fields.month.hide', false);\n }\n get yearRequired() {\n return this.showYear && lodash_1.default.get(this.component, 'fields.year.required', false);\n }\n get showYear() {\n return !lodash_1.default.get(this.component, 'fields.year.hide', false);\n }\n get defaultSchema() {\n return DayComponent.schema();\n }\n get shouldDisabled() {\n return super.shouldDisabled || this.parentDisabled;\n }\n get inputInfo() {\n const info = super.elementInfo();\n info.type = 'input';\n info.attr.type = 'hidden';\n info.changeEvent = 'input';\n return info;\n }\n inputDefinition(name) {\n let min, max;\n if (name === 'day') {\n min = 1;\n max = 31;\n }\n if (name === 'month') {\n min = 1;\n max = 12;\n }\n if (name === 'year') {\n min = lodash_1.default.get(this.component, 'fields.year.minYear', 1900) || 1900;\n max = lodash_1.default.get(this.component, 'fields.year.maxYear', 2030) || 1900;\n }\n return {\n type: 'input',\n ref: name,\n attr: {\n id: `${this.component.key}-${name}`,\n class: `form-control ${this.transform('class', `formio-day-component-${name}`)}`,\n type: this.component.fields[name].type === 'select' ? 'select' : 'number',\n placeholder: this.component.fields[name].placeholder,\n step: 1,\n min,\n max,\n }\n };\n }\n selectDefinition(name) {\n return {\n multiple: false,\n ref: name,\n widget: 'html5',\n attr: {\n id: `${this.component.key}-${name}`,\n class: 'form-control',\n name,\n lang: this.options.language\n }\n };\n }\n get days() {\n if (this._days) {\n return this._days;\n }\n this._days = [\n { value: '', label: lodash_1.default.get(this.component, 'fields.day.placeholder', '') }\n ];\n for (let x = 1; x <= 31; x++) {\n this._days.push({\n value: x,\n label: x.toString()\n });\n }\n return this._days;\n }\n get months() {\n if (this._months) {\n return this._months;\n }\n this._months = [\n {\n value: '',\n label: lodash_1.default.get(this.component, 'fields.month.placeholder') || (this.hideInputLabels ? this.t('Month') : '')\n },\n { value: 1, label: 'January' },\n { value: 2, label: 'February' },\n { value: 3, label: 'March' },\n { value: 4, label: 'April' },\n { value: 5, label: 'May' },\n { value: 6, label: 'June' },\n { value: 7, label: 'July' },\n { value: 8, label: 'August' },\n { value: 9, label: 'September' },\n { value: 10, label: 'October' },\n { value: 11, label: 'November' },\n { value: 12, label: 'December' }\n ];\n return this._months;\n }\n get years() {\n if (this._years) {\n return this._years;\n }\n this._years = [\n { value: '', label: lodash_1.default.get(this.component, 'fields.year.placeholder', '') }\n ];\n const minYears = lodash_1.default.get(this.component, 'fields.year.minYear', 1900) || 1900;\n const maxYears = lodash_1.default.get(this.component, 'fields.year.maxYear', 2030) || 2030;\n for (let x = minYears; x <= maxYears; x++) {\n this._years.push({\n value: x,\n label: x.toString()\n });\n }\n return this._years;\n }\n setErrorClasses(elements, dirty, hasError) {\n super.setErrorClasses(elements, dirty, hasError);\n super.setErrorClasses([this.refs.day, this.refs.month, this.refs.year], dirty, hasError);\n }\n removeInputError(elements) {\n super.removeInputError([this.refs.day, this.refs.month, this.refs.year]);\n super.removeInputError(elements);\n }\n init() {\n super.init();\n this.validators = this.validators.concat(['day', 'maxDate', 'minDate', 'minYear', 'maxYear']);\n const minYear = this.component.fields.year.minYear;\n const maxYear = this.component.fields.year.maxYear;\n this.component.maxYear = maxYear;\n this.component.minYear = minYear;\n const dateFormatInfo = (0, utils_1.getLocaleDateFormatInfo)(this.options.language);\n this.dayFirst = this.component.useLocaleSettings\n ? dateFormatInfo.dayFirst\n : this.component.dayFirst;\n }\n render() {\n if (this.isHtmlRenderMode()) {\n return super.render(this.renderTemplate('input'));\n }\n return super.render(this.renderTemplate('day', {\n dayFirst: this.dayFirst,\n showDay: this.showDay,\n showMonth: this.showMonth,\n showYear: this.showYear,\n day: this.renderField('day'),\n month: this.renderField('month'),\n year: this.renderField('year'),\n }));\n }\n renderField(name) {\n if (this.component.fields[name].type === 'select') {\n return this.renderTemplate('select', {\n input: this.selectDefinition(name),\n selectOptions: this[`${name}s`].reduce((html, option) => html + this.renderTemplate('selectOption', {\n option,\n selected: false,\n attrs: {}\n }), ''),\n });\n }\n else {\n return this.renderTemplate('input', {\n prefix: this.prefix,\n suffix: this.suffix,\n input: this.inputDefinition(name)\n });\n }\n }\n attach(element) {\n this.loadRefs(element, { day: 'single', month: 'single', year: 'single', input: 'multiple' });\n const superAttach = super.attach(element);\n if (this.shouldDisabled) {\n this.setDisabled(this.refs.day, true);\n this.setDisabled(this.refs.month, true);\n this.setDisabled(this.refs.year, true);\n if (this.refs.input) {\n this.refs.input.forEach((input) => this.setDisabled(input, true));\n }\n }\n else {\n this.addEventListener(this.refs.day, 'input', () => this.updateValue(null, {\n modified: true\n }));\n // TODO: Need to rework this to work with day select as well.\n // Change day max input when month changes.\n this.addEventListener(this.refs.month, 'input', () => {\n const maxDay = this.refs.year ? parseInt(new Date(this.refs.year.value, this.refs.month.value, 0).getDate(), 10)\n : '';\n const day = this.getFieldValue('day');\n if (!this.component.fields.day.hide && maxDay) {\n this.refs.day.max = maxDay;\n }\n if (maxDay && day > maxDay) {\n this.refs.day.value = this.refs.day.max;\n }\n this.updateValue(null, {\n modified: true\n });\n });\n this.addEventListener(this.refs.year, 'input', () => this.updateValue(null, {\n modified: true\n }));\n this.addEventListener(this.refs.input, this.info.changeEvent, () => this.updateValue(null, {\n modified: true\n }));\n [this.refs.day, this.refs.month, this.refs.year].forEach((element) => {\n Input_1.default.prototype.addFocusBlurEvents.call(this, element);\n });\n }\n this.setValue(this.dataValue);\n // Force the disabled state with getters and setters.\n this.disabled = this.shouldDisabled;\n return superAttach;\n }\n validateRequired(setting, value) {\n const { day, month, year } = this.parts;\n if (this.dayRequired && !day) {\n return false;\n }\n if (this.monthRequired && !month) {\n return false;\n }\n if (this.yearRequired && !year) {\n return false;\n }\n if (!(0, utils_1.boolValue)(setting)) {\n return true;\n }\n return !this.isEmpty(value);\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.refs.year || !this.refs.month || !this.refs.day) {\n return;\n }\n if (disabled) {\n this.refs.year.setAttribute('disabled', 'disabled');\n this.refs.month.setAttribute('disabled', 'disabled');\n this.refs.day.setAttribute('disabled', 'disabled');\n }\n else {\n this.refs.year.removeAttribute('disabled');\n this.refs.month.removeAttribute('disabled');\n this.refs.day.removeAttribute('disabled');\n }\n }\n normalizeValue(value) {\n if (!value || this.valueMask.test(value)) {\n return value;\n }\n const dateParts = [];\n const valueParts = value.split('/');\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const defaultValue = this.component.defaultValue ? this.component.defaultValue.split('/') : '';\n const getNextPart = (shouldTake, defaultValue) => dateParts.push(shouldTake ? valueParts.shift() : defaultValue);\n if (this.dayFirst) {\n getNextPart(this.showDay, defaultValue ? defaultValue[DAY] : '00');\n }\n getNextPart(this.showMonth, defaultValue ? defaultValue[MONTH] : '00');\n if (!this.dayFirst) {\n getNextPart(this.showDay, defaultValue ? defaultValue[DAY] : '00');\n }\n getNextPart(this.showYear, defaultValue ? defaultValue[YEAR] : '0000');\n return dateParts.join('/');\n }\n /**\n * Set the value at a specific index.\n *\n * @param index\n * @param value\n */\n setValueAt(index, value) {\n // temporary solution to avoid input reset\n // on invalid date.\n if (!value || value === 'Invalid date') {\n return null;\n }\n const parts = value.split('/');\n let day;\n if (this.component.dayFirst) {\n day = parts.shift();\n }\n const month = parts.shift();\n if (!this.component.dayFirst) {\n day = parts.shift();\n }\n const year = parts.shift();\n if (this.refs.day && this.showDay) {\n this.refs.day.value = day === '00' ? '' : parseInt(day, 10);\n }\n if (this.refs.month && this.showMonth) {\n this.refs.month.value = month === '00' ? '' : parseInt(month, 10);\n }\n if (this.refs.year && this.showYear) {\n this.refs.year.value = year === '0000' ? '' : parseInt(year, 10);\n }\n }\n getFieldValue(name) {\n const parts = this.dataValue ? this.dataValue.split('/') : [];\n let val = 0;\n switch (name) {\n case 'month':\n val = parts[this.dayFirst ? 1 : 0];\n break;\n case 'day':\n val = parts[this.dayFirst ? 0 : 1];\n break;\n case 'year':\n val = parts[2];\n break;\n }\n val = parseInt(val, 10);\n return (!lodash_1.default.isNaN(val) && lodash_1.default.isNumber(val)) ? val : 0;\n }\n get parts() {\n return {\n day: this.getFieldValue('day'),\n month: this.getFieldValue('month'),\n year: this.getFieldValue('year'),\n };\n }\n /**\n * Get the format for the value string.\n * @returns {string}\n */\n get format() {\n let format = '';\n if (this.component.dayFirst && this.showDay) {\n format += 'D/';\n }\n if (this.showMonth) {\n format += 'M/';\n }\n if (!this.component.dayFirst && this.showDay) {\n format += 'D/';\n }\n if (this.showYear) {\n format += 'YYYY';\n return format;\n }\n else {\n // Trim off the \"/\" from the end of the format string.\n return format.length ? format.substring(0, format.length - 1) : format;\n }\n }\n /**\n * Return the date for this component.\n *\n * @param value\n * @return {*}\n */\n getDate(value) {\n let defaults = [], day, month, year;\n // Map positions to identifiers to get default values for each part of day\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const defaultValue = value || this.component.defaultValue;\n if (defaultValue) {\n defaults = defaultValue.split('/').map(x => parseInt(x, 10));\n }\n if (this.showDay && this.refs.day) {\n day = parseInt(this.refs.day.value, 10);\n }\n if (day === undefined || lodash_1.default.isNaN(day)) {\n day = defaults[DAY] && !lodash_1.default.isNaN(defaults[DAY]) ? defaults[DAY] : 0;\n }\n if (this.showMonth && this.refs.month) {\n // Months are 0 indexed.\n month = parseInt(this.refs.month.value, 10);\n }\n if (month === undefined || lodash_1.default.isNaN(month)) {\n month = defaults[MONTH] && !lodash_1.default.isNaN(defaults[MONTH]) ? defaults[MONTH] : 0;\n }\n if (this.showYear && this.refs.year) {\n year = parseInt(this.refs.year.value);\n }\n if (year === undefined || lodash_1.default.isNaN(year)) {\n year = defaults[YEAR] && !lodash_1.default.isNaN(defaults[YEAR]) ? defaults[YEAR] : 0;\n }\n let result;\n if (!day && !month && !year) {\n return null;\n }\n // add trailing zeros if the data is showed\n day = this.showDay ? day.toString().padStart(2, 0) : '';\n month = this.showMonth ? month.toString().padStart(2, 0) : '';\n year = this.showYear ? year.toString().padStart(4, 0) : '';\n if (this.component.dayFirst) {\n result = `${day}${this.showDay && this.showMonth || this.showDay && this.showYear ? '/' : ''}${month}${this.showMonth && this.showYear ? '/' : ''}${year}`;\n }\n else {\n result = `${month}${this.showDay && this.showMonth || this.showMonth && this.showYear ? '/' : ''}${day}${this.showDay && this.showYear ? '/' : ''}${year}`;\n }\n return result;\n }\n /**\n * Return the date object for this component.\n * @returns {Date}\n */\n get date() {\n return this.getDate();\n }\n /**\n * Return the raw value.\n *\n * @returns {Date}\n */\n get validationValue() {\n return this.dataValue;\n }\n getValue() {\n const result = super.getValue();\n return (!result) ? this.dataValue : result;\n }\n /**\n * Get the value at a specific index.\n *\n * @param index\n * @returns {*}\n */\n getValueAt(index) {\n const date = this.date || this.emptyValue;\n if (date) {\n this.refs.input[index].value = date;\n return this.refs.input[index].value;\n }\n else {\n this.refs.input[index].value = '';\n return null;\n }\n }\n /**\n * Get the input value of the date.\n *\n * @param value\n * @return {null}\n */\n getValueAsString(value) {\n return this.getDate(value) || '';\n }\n focus() {\n var _a, _b, _c;\n if (this.dayFirst && this.showDay || !this.dayFirst && !this.showMonth && this.showDay) {\n (_a = this.refs.day) === null || _a === void 0 ? void 0 : _a.focus();\n }\n else if (this.dayFirst && !this.showDay && this.showMonth || !this.dayFirst && this.showMonth) {\n (_b = this.refs.month) === null || _b === void 0 ? void 0 : _b.focus();\n }\n else if (!this.showDay && !this.showDay && this.showYear) {\n (_c = this.refs.year) === null || _c === void 0 ? void 0 : _c.focus();\n }\n }\n isPartialDay(value) {\n if (!value) {\n return false;\n }\n const [DAY, MONTH, YEAR] = this.component.dayFirst ? [0, 1, 2] : [1, 0, 2];\n const values = value.split('/');\n return (values[DAY] === '00' || values[MONTH] === '00' || values[YEAR] === '0000');\n }\n getValidationFormat() {\n return this.dayFirst ? 'DD-MM-YYYY' : 'MM-DD-YYYY';\n }\n}\nexports[\"default\"] = DayComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/day/Day.js?");
|
5235
5235
|
|
5236
5236
|
/***/ }),
|
5237
5237
|
|
@@ -5286,7 +5286,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument
|
|
5286
5286
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5287
5287
|
|
5288
5288
|
"use strict";
|
5289
|
-
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 Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst ComponentModal_1 = __importDefault(__webpack_require__(/*! ../_classes/componentModal/ComponentModal */ \"./lib/cjs/components/_classes/componentModal/ComponentModal.js\"));\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nclass FormComponent extends Component_1.default {\n static schema(...extend) {\n return Component_1.default.schema({\n label: 'Form',\n type: 'form',\n key: 'form',\n src: '',\n reference: true,\n form: '',\n path: '',\n tableView: true,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Nested Form',\n icon: 'wpforms',\n group: 'premium',\n documentation: '/userguide/form-building/premium-components#nested-form',\n weight: 110,\n schema: FormComponent.schema()\n };\n }\n static savedValueTypes() {\n return [utils_1.componentValueTypes.object];\n }\n init() {\n super.init();\n this.formObj = {\n display: this.component.display,\n settings: this.component.settings,\n components: this.component.components\n };\n this.valueChanged = false;\n this.subForm = null;\n this.formSrc = '';\n if (this.component.src) {\n this.formSrc = this.component.src;\n }\n if (!this.component.src &&\n !this.options.formio &&\n (this.component.form || this.component.path)) {\n if (this.component.project) {\n this.formSrc = Formio_1.Formio.getBaseUrl();\n // Check to see if it is a MongoID.\n if ((0, utils_1.isMongoId)(this.component.project)) {\n this.formSrc += '/project';\n }\n this.formSrc += `/${this.component.project}`;\n this.options.project = this.formSrc;\n }\n else {\n this.formSrc = Formio_1.Formio.getProjectUrl();\n this.options.project = this.formSrc;\n }\n if (this.component.form) {\n if ((0, utils_1.isMongoId)(this.component.form)) {\n this.formSrc += `/form/${this.component.form}`;\n }\n else {\n this.formSrc += `/${this.component.form}`;\n }\n }\n else if (this.component.path) {\n this.formSrc += `/${this.component.path}`;\n }\n }\n // Build the source based on the root src path.\n if (!this.formSrc && this.options.formio) {\n const rootSrc = this.options.formio.formsUrl;\n if (this.component.form && (0, utils_1.isMongoId)(this.component.form)) {\n this.formSrc = `${rootSrc}/${this.component.form}`;\n }\n else {\n const formPath = this.component.path || this.component.form;\n this.formSrc = `${rootSrc.replace(/\\/form$/, '')}/${formPath}`;\n }\n }\n if (this.builderMode && this.component.hasOwnProperty('formRevision')) {\n this.component.revision = this.component.formRevision;\n delete this.component.formRevision;\n }\n // Add revision version if set.\n if (this.component.revision || this.component.revision === 0 ||\n this.component.formRevision || this.component.formRevision === 0\n || this.component.revisionId) {\n this.setFormRevision(this.component.revisionId || this.component.revision || this.component.formRevision);\n }\n return this.createSubForm();\n }\n get dataReady() {\n return this.subFormReady || Promise.resolve();\n }\n get defaultValue() {\n // Not not provide a default value unless the subform is ready so that it will initialize correctly.\n return this.subForm ? super.defaultValue : null;\n }\n get defaultSchema() {\n return FormComponent.schema();\n }\n get emptyValue() {\n return { data: {} };\n }\n get ready() {\n return this.subFormReady || Promise.resolve();\n }\n get useOriginalRevision() {\n var _a, _b;\n return ((_a = this.component) === null || _a === void 0 ? void 0 : _a.useOriginalRevision) && !!((_b = this.formObj) === null || _b === void 0 ? void 0 : _b.revisions);\n }\n setFormRevision(rev) {\n // Remove current revisions from src if it is\n this.formSrc = this.formSrc.replace(/\\/v\\/[0-9a-z]+/, '');\n const revNumber = Number.parseInt(rev);\n if (!isNaN(revNumber)) {\n this.subFormRevision = rev;\n this.formSrc += `/v/${rev}`;\n }\n else {\n this.subFormRevision = undefined;\n }\n }\n getComponent(path, fn) {\n path = (0, utils_1.getArrayFromComponentPath)(path);\n if (path[0] === 'data') {\n path.shift();\n }\n const originalPathStr = `${this.path}.data.${(0, utils_1.getStringFromComponentPath)(path)}`;\n if (this.subForm) {\n return this.subForm.getComponent(path, fn, originalPathStr);\n }\n }\n getSubOptions(options = {}) {\n options.parentPath = `${this.path}.data.`;\n options.events = this.createEmitter();\n // Make sure to not show the submit button in wizards in the nested forms.\n lodash_1.default.set(options, 'buttonSettings.showSubmit', false);\n if (!this.options) {\n return options;\n }\n if (this.options.base) {\n options.base = this.options.base;\n }\n if (this.options.project) {\n options.project = this.options.project;\n }\n if (this.options.readOnly || this.component.disabled) {\n options.readOnly = this.options.readOnly || this.component.disabled;\n }\n if (this.options.breadcrumbSettings) {\n options.breadcrumbSettings = this.options.breadcrumbSettings;\n }\n if (this.options.buttonSettings) {\n options.buttonSettings = lodash_1.default.clone(this.options.buttonSettings);\n }\n if (this.options.viewAsHtml) {\n options.viewAsHtml = this.options.viewAsHtml;\n }\n if (this.options.language) {\n options.language = this.options.language;\n }\n if (this.options.template) {\n options.template = this.options.template;\n }\n if (this.options.templates) {\n options.templates = this.options.templates;\n }\n if (this.options.renderMode) {\n options.renderMode = this.options.renderMode;\n }\n if (this.options.attachMode) {\n options.attachMode = this.options.attachMode;\n }\n if (this.options.iconset) {\n options.iconset = this.options.iconset;\n }\n if (this.options.fileService) {\n options.fileService = this.options.fileService;\n }\n if (this.options.onChange) {\n options.onChange = this.options.onChange;\n }\n return options;\n }\n render() {\n if (this.builderMode) {\n return super.render(this.component.label || 'Nested form');\n }\n const subform = this.subForm ? this.subForm.render() : this.renderTemplate('loading');\n return super.render(subform);\n }\n asString(value) {\n return this.getValueAsString(value);\n }\n /**\n * Prints out the value of form components as a datagrid value.\n */\n getValueAsString(value) {\n if (!value) {\n return 'No data provided';\n }\n if (!value.data && value._id) {\n return value._id;\n }\n if (!value.data || !Object.keys(value.data).length) {\n return 'No data provided';\n }\n return '[Complex Data]';\n }\n attach(element) {\n // Don't attach in builder.\n if (this.builderMode) {\n return super.attach(element);\n }\n return super.attach(element)\n .then(() => {\n if (this.isSubFormLazyLoad() && !this.hasLoadedForm && !this.subFormLoading) {\n this.createSubForm(true);\n }\n return this.subFormReady.then(() => {\n this.empty(element);\n if (this.options.builder) {\n this.setContent(element, this.ce('div', {\n class: 'text-muted text-center p-2'\n }, this.text(this.formObj.title)));\n return;\n }\n this.setContent(element, this.render());\n if (this.subForm) {\n if (this.isNestedWizard) {\n element = this.root.element;\n }\n this.subForm.attach(element);\n this.valueChanged = this.hasSetValue;\n if (!this.valueChanged && this.dataValue.state !== 'submitted') {\n this.setDefaultValue();\n }\n else {\n this.restoreValue();\n }\n }\n if (!this.builderMode && this.component.modalEdit) {\n const modalShouldBeOpened = this.componentModal ? this.componentModal.isOpened : false;\n const currentValue = modalShouldBeOpened ? this.componentModal.currentValue : this.dataValue;\n this.componentModal = new ComponentModal_1.default(this, element, modalShouldBeOpened, currentValue);\n this.setOpenModalElement();\n }\n this.calculateValue();\n });\n });\n }\n detach() {\n if (this.subForm) {\n this.subForm.detach();\n }\n super.detach();\n }\n get currentForm() {\n return this._currentForm;\n }\n get hasLoadedForm() {\n return this.formObj\n && this.formObj.components\n && Array.isArray(this.formObj.components)\n && this.formObj.components.length;\n }\n set currentForm(instance) {\n this._currentForm = instance;\n if (!this.subForm) {\n return;\n }\n this.subForm.getComponents().forEach(component => {\n component.currentForm = this;\n });\n }\n get isRevisionChanged() {\n return lodash_1.default.isNumber(this.subFormRevision)\n && lodash_1.default.isNumber(this.formObj._vid)\n && this.formObj._vid !== this.subFormRevision;\n }\n destroy(all = false) {\n if (this.subForm) {\n this.subForm.destroy(all);\n this.subForm = null;\n this.subFormReady = null;\n }\n super.destroy(all);\n }\n redraw() {\n if (this.subForm) {\n this.subForm.form = this.formObj;\n this.setSubFormDisabled(this.subForm);\n }\n return super.redraw();\n }\n /**\n * Pass everyComponent to subform.\n * @param args\n * @returns {*|void}\n */\n everyComponent(...args) {\n if (this.subForm) {\n this.subForm.everyComponent(...args);\n }\n }\n setSubFormDisabled(subForm) {\n subForm.disabled = this.disabled; // When the Nested Form is disabled make the subForm disabled\n }\n updateSubWizards(subForm) {\n var _a, _b;\n if (this.isNestedWizard && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.subWizards) && ((_b = subForm === null || subForm === void 0 ? void 0 : subForm._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard') {\n const existedForm = this.root.subWizards.findIndex(form => form.component.form === this.component.form);\n if (existedForm !== -1) {\n this.root.subWizards[existedForm] = this;\n }\n else {\n this.root.subWizards.push(this);\n }\n this.emit('subWizardsUpdated', subForm);\n }\n }\n /**\n * Create a subform instance.\n *\n * @return {*}\n */\n createSubForm(fromAttach) {\n this.subFormReady = this.loadSubForm(fromAttach).then((form) => {\n if (!form) {\n return;\n }\n // Iterate through every component and hide the submit button.\n (0, utils_1.eachComponent)(form.components, (component) => {\n this.hideSubmitButton(component);\n });\n // If the subform is already created then destroy the old one.\n if (this.subForm) {\n this.subForm.destroy();\n }\n // Render the form.\n return (new Form_1.default(form, this.getSubOptions())).ready.then((instance) => {\n this.subForm = instance;\n this.subForm.currentForm = this;\n this.subForm.parent = this;\n this.subForm.parentVisible = this.visible;\n this.subForm.on('change', () => {\n if (this.subForm) {\n this.dataValue = this.subForm.getValue();\n this.triggerChange({\n noEmit: true\n });\n }\n });\n this.subForm.url = this.formSrc;\n this.subForm.nosubmit = true;\n this.subForm.root = this.root;\n this.subForm.localRoot = this.isNestedWizard ? this.localRoot : this.subForm;\n this.restoreValue();\n this.valueChanged = this.hasSetValue;\n this.onChange();\n return this.subForm;\n });\n }).then((subForm) => {\n this.updateSubWizards(subForm);\n return subForm;\n });\n return this.subFormReady;\n }\n hideSubmitButton(component) {\n const isSubmitButton = (component.type === 'button') &&\n ((component.action === 'submit') || !component.action);\n if (isSubmitButton) {\n component.hidden = true;\n }\n }\n /**\n * Load the subform.\n */\n loadSubForm(fromAttach) {\n if (this.builderMode || this.isHidden() || (this.isSubFormLazyLoad() && !fromAttach)) {\n return Promise.resolve();\n }\n if (this.hasLoadedForm && !this.isRevisionChanged) {\n // Pass config down to sub forms.\n if (this.root && this.root.form && this.root.form.config && !this.formObj.config) {\n this.formObj.config = this.root.form.config;\n }\n return Promise.resolve(this.formObj);\n }\n else if (this.formSrc) {\n this.subFormLoading = true;\n return (new Formio_1.Formio(this.formSrc)).loadForm({ params: { live: 1 } })\n .then((formObj) => {\n this.formObj = formObj;\n this.subFormLoading = false;\n return formObj;\n })\n .catch((err) => {\n console.log(err);\n return null;\n });\n }\n return Promise.resolve();\n }\n get subFormData() {\n var _a;\n return ((_a = this.dataValue) === null || _a === void 0 ? void 0 : _a.data) || {};\n }\n checkComponentValidity(data, dirty, row, options) {\n options = options || {};\n const silentCheck = options.silentCheck || false;\n if (this.subForm) {\n return this.subForm.checkValidity(this.subFormData, dirty, null, silentCheck);\n }\n return super.checkComponentValidity(data, dirty, row, options);\n }\n checkComponentConditions(data, flags, row) {\n const visible = super.checkComponentConditions(data, flags, row);\n // Return if already hidden\n if (!visible) {\n return visible;\n }\n if (this.subForm) {\n return this.subForm.checkConditions(this.subFormData);\n }\n // There are few cases when subForm is not loaded when a change is triggered,\n // so we need to perform checkConditions after it is ready, or some conditional fields might be hidden in View mode\n else if (this.subFormReady) {\n this.subFormReady.then(() => {\n if (this.subForm) {\n return this.subForm.checkConditions(this.subFormData);\n }\n });\n }\n return visible;\n }\n calculateValue(data, flags, row) {\n if (this.subForm) {\n return this.subForm.calculateValue(this.subFormData, flags);\n }\n return super.calculateValue(data, flags, row);\n }\n setPristine(pristine) {\n super.setPristine(pristine);\n if (this.subForm) {\n this.subForm.setPristine(pristine);\n }\n }\n /**\n * Determine if the subform should be submitted.\n * @return {*|boolean}\n */\n get shouldSubmit() {\n return this.subFormReady && (!this.component.hasOwnProperty('reference') || this.component.reference) && !this.isHidden();\n }\n /**\n * Returns the data for the subform.\n *\n * @return {*}\n */\n getSubFormData() {\n if (lodash_1.default.get(this.subForm, 'form.display') === 'pdf') {\n return this.subForm.getSubmission();\n }\n else {\n return Promise.resolve(this.dataValue);\n }\n }\n /**\n * Submit the subform if configured to do so.\n *\n * @return {*}\n */\n submitSubForm(rejectOnError) {\n // If we wish to submit the form on next page, then do that here.\n if (this.shouldSubmit) {\n return this.subFormReady.then(() => {\n if (!this.subForm) {\n return this.dataValue;\n }\n this.subForm.nosubmit = false;\n return this.subForm.submitForm().then(result => {\n this.subForm.loading = false;\n this.subForm.showAllErrors = false;\n this.dataValue = result.submission;\n return this.dataValue;\n }).catch(err => {\n this.subForm.showAllErrors = true;\n if (rejectOnError) {\n this.subForm.onSubmissionError(err);\n return Promise.reject(err);\n }\n else {\n return {};\n }\n });\n });\n }\n return this.getSubFormData();\n }\n /**\n * Submit the form before the next page is triggered.\n */\n beforePage(next) {\n // Should not submit child forms if we are going to the previous page\n if (!next) {\n return super.beforePage(next);\n }\n return this.submitSubForm(true).then(() => super.beforePage(next));\n }\n /**\n * Submit the form before the whole form is triggered.\n */\n beforeSubmit() {\n var _a;\n const submission = this.dataValue;\n const isAlreadySubmitted = submission && submission._id && submission.form;\n // This submission has already been submitted, so just return the reference data.\n if (isAlreadySubmitted && !((_a = this.subForm) === null || _a === void 0 ? void 0 : _a.wizard)) {\n this.dataValue = submission;\n return Promise.resolve(this.dataValue);\n }\n return this.submitSubForm(false)\n .then(() => {\n return this.dataValue;\n })\n .then(() => super.beforeSubmit());\n }\n isSubFormLazyLoad() {\n var _a, _b;\n return ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard' && this.component.lazyLoad;\n }\n isHidden() {\n if (!this.visible) {\n return true;\n }\n return !super.checkConditions(this.rootValue);\n }\n setValue(submission, flags = {}) {\n var _a;\n const changed = super.setValue(submission, flags);\n this.valueChanged = true;\n if (this.subForm) {\n const revisionPath = submission._frid ? '_frid' : '_vid';\n const shouldLoadOriginalRevision = this.useOriginalRevision\n && (lodash_1.default.isNumber(submission[revisionPath]) || lodash_1.default.isNumber(submission._fvid))\n && lodash_1.default.isNumber((_a = this.subForm.form) === null || _a === void 0 ? void 0 : _a[revisionPath])\n && submission._fvid !== this.subForm.form[revisionPath];\n if (shouldLoadOriginalRevision) {\n this.setFormRevision(submission._frid || submission._fvid);\n this.createSubForm().then(() => {\n this.attach(this.element);\n });\n }\n else {\n this.setSubFormValue(submission, flags);\n }\n }\n return changed;\n }\n setSubFormValue(submission, flags) {\n const shouldLoadSubmissionById = submission\n && submission._id\n && this.subForm.formio\n && lodash_1.default.isEmpty(submission.data);\n if (shouldLoadSubmissionById) {\n const formId = submission.form || this.formObj.form || this.component.form;\n const submissionUrl = `${this.subForm.formio.formsUrl}/${formId}/submission/${submission._id}`;\n this.subForm.setUrl(submissionUrl, this.options);\n this.subForm.loadSubmission();\n }\n else {\n this.subForm.setValue(submission, flags);\n }\n }\n isEmpty(value = this.dataValue) {\n return value === null || lodash_1.default.isEqual(value, this.emptyValue) || (this.areAllComponentsEmpty(value.data) && !value._id);\n }\n areAllComponentsEmpty(data) {\n let res = true;\n if (this.subForm) {\n this.subForm.everyComponent((comp) => {\n const componentValue = lodash_1.default.get(data, comp.key);\n res &= comp.isEmpty(componentValue);\n });\n }\n else {\n res = false;\n }\n return res;\n }\n getValue() {\n if (this.subForm) {\n return this.subForm.getValue();\n }\n return this.dataValue;\n }\n get errors() {\n let errors = super.errors;\n if (this.subForm) {\n errors = errors.concat(this.subForm.errors);\n }\n return errors;\n }\n updateSubFormVisibility() {\n if (this.subForm) {\n this.subForm.parentVisible = this.visible;\n }\n }\n /**\n * Determines if this form is a Nested Wizard\n * which means it should be a Wizard itself and should be a direct child of a Wizard's page\n * @returns {boolean}\n */\n get isNestedWizard() {\n var _a, _b, _c, _d, _e;\n return ((_b = (_a = this.subForm) === null || _a === void 0 ? void 0 : _a._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard' && ((_e = (_d = (_c = this.parent) === null || _c === void 0 ? void 0 : _c.parent) === null || _d === void 0 ? void 0 : _d._form) === null || _e === void 0 ? void 0 : _e.display) === 'wizard';\n }\n get visible() {\n return super.visible;\n }\n set visible(value) {\n const isNestedWizard = this.isNestedWizard;\n if (this._visible !== value) {\n this._visible = value;\n // Form doesn't load if hidden. If it becomes visible, create the form.\n if (!this.subForm && value) {\n this.createSubForm();\n this.subFormReady.then(() => {\n this.updateSubFormVisibility();\n this.clearOnHide();\n });\n this.redraw();\n return;\n }\n this.updateSubFormVisibility();\n this.clearOnHide();\n isNestedWizard ? this.rebuild() : this.redraw();\n }\n if (!value && isNestedWizard) {\n this.root.redraw();\n }\n }\n get parentVisible() {\n return super.parentVisible;\n }\n set parentVisible(value) {\n if (this._parentVisible !== value) {\n this._parentVisible = value;\n this.clearOnHide();\n // Form doesn't load if hidden. If it becomes visible, create the form.\n if (!this.subForm && value) {\n this.createSubForm();\n this.subFormReady.then(() => {\n this.updateSubFormVisibility();\n });\n this.redraw();\n return;\n }\n this.updateSubFormVisibility();\n this.redraw();\n }\n }\n isInternalEvent(event) {\n switch (event) {\n case 'focus':\n case 'blur':\n case 'componentChange':\n case 'componentError':\n case 'error':\n case 'formLoad':\n case 'languageChanged':\n case 'render':\n case 'checkValidity':\n case 'initialized':\n case 'submit':\n case 'submitButton':\n case 'nosubmit':\n case 'updateComponent':\n case 'submitDone':\n case 'submissionDeleted':\n case 'requestDone':\n case 'nextPage':\n case 'prevPage':\n case 'wizardNavigationClicked':\n case 'updateWizardNav':\n case 'restoreDraft':\n case 'saveDraft':\n case 'saveComponent':\n case 'pdfUploaded':\n return true;\n default:\n return false;\n }\n }\n createEmitter() {\n const emitter = new eventemitter3_1.default();\n const nativeEmit = emitter.emit;\n const that = this;\n emitter.emit = function (event, ...args) {\n const eventType = event.replace(`${that.options.namespace}.`, '');\n nativeEmit.call(this, event, ...args);\n if (!that.isInternalEvent(eventType)) {\n that.emit(eventType, ...args);\n }\n };\n return emitter;\n }\n deleteValue() {\n super.setValue(null, {\n noUpdateEvent: true,\n noDefault: true\n });\n this.unset();\n }\n}\nexports[\"default\"] = FormComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/form/Form.js?");
|
5289
|
+
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 Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst ComponentModal_1 = __importDefault(__webpack_require__(/*! ../_classes/componentModal/ComponentModal */ \"./lib/cjs/components/_classes/componentModal/ComponentModal.js\"));\nconst eventemitter3_1 = __importDefault(__webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst Form_1 = __importDefault(__webpack_require__(/*! ../../Form */ \"./lib/cjs/Form.js\"));\nclass FormComponent extends Component_1.default {\n static schema(...extend) {\n return Component_1.default.schema({\n label: 'Form',\n type: 'form',\n key: 'form',\n src: '',\n reference: true,\n form: '',\n path: '',\n tableView: true,\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Nested Form',\n icon: 'wpforms',\n group: 'premium',\n documentation: '/userguide/form-building/premium-components#nested-form',\n weight: 110,\n schema: FormComponent.schema()\n };\n }\n static savedValueTypes() {\n return [utils_1.componentValueTypes.object];\n }\n init() {\n super.init();\n this.formObj = {\n display: this.component.display,\n settings: this.component.settings,\n components: this.component.components\n };\n this.valueChanged = false;\n this.subForm = null;\n this.formSrc = '';\n if (this.component.src) {\n this.formSrc = this.component.src;\n }\n if (!this.component.src &&\n !this.options.formio &&\n (this.component.form || this.component.path)) {\n if (this.component.project) {\n this.formSrc = Formio_1.Formio.getBaseUrl();\n // Check to see if it is a MongoID.\n if ((0, utils_1.isMongoId)(this.component.project)) {\n this.formSrc += '/project';\n }\n this.formSrc += `/${this.component.project}`;\n this.options.project = this.formSrc;\n }\n else {\n this.formSrc = Formio_1.Formio.getProjectUrl();\n this.options.project = this.formSrc;\n }\n if (this.component.form) {\n if ((0, utils_1.isMongoId)(this.component.form)) {\n this.formSrc += `/form/${this.component.form}`;\n }\n else {\n this.formSrc += `/${this.component.form}`;\n }\n }\n else if (this.component.path) {\n this.formSrc += `/${this.component.path}`;\n }\n }\n // Build the source based on the root src path.\n if (!this.formSrc && this.options.formio) {\n const rootSrc = this.options.formio.formsUrl;\n if (this.component.form && (0, utils_1.isMongoId)(this.component.form)) {\n this.formSrc = `${rootSrc}/${this.component.form}`;\n }\n else {\n const formPath = this.component.path || this.component.form;\n this.formSrc = `${rootSrc.replace(/\\/form$/, '')}/${formPath}`;\n }\n }\n if (this.builderMode && this.component.hasOwnProperty('formRevision')) {\n this.component.revision = this.component.formRevision;\n delete this.component.formRevision;\n }\n // Add revision version if set.\n if (this.component.revision || this.component.revision === 0 ||\n this.component.formRevision || this.component.formRevision === 0\n || this.component.revisionId) {\n this.setFormRevision(this.component.revisionId || this.component.revision || this.component.formRevision);\n }\n return this.createSubForm();\n }\n get dataReady() {\n return this.subFormReady || Promise.resolve();\n }\n get defaultValue() {\n // Not not provide a default value unless the subform is ready so that it will initialize correctly.\n return this.subForm ? super.defaultValue : null;\n }\n get defaultSchema() {\n return FormComponent.schema();\n }\n get emptyValue() {\n return { data: {} };\n }\n get ready() {\n return this.subFormReady || Promise.resolve();\n }\n get useOriginalRevision() {\n var _a, _b;\n return ((_a = this.component) === null || _a === void 0 ? void 0 : _a.useOriginalRevision) && !!((_b = this.formObj) === null || _b === void 0 ? void 0 : _b.revisions);\n }\n setFormRevision(rev) {\n // Remove current revisions from src if it is\n this.formSrc = this.formSrc.replace(/\\/v\\/[0-9a-z]+/, '');\n const revNumber = Number.parseInt(rev);\n if (!isNaN(revNumber)) {\n this.subFormRevision = rev;\n this.formSrc += `/v/${rev}`;\n }\n else {\n this.subFormRevision = undefined;\n }\n }\n getComponent(path, fn) {\n path = (0, utils_1.getArrayFromComponentPath)(path);\n if (path[0] === 'data') {\n path.shift();\n }\n const originalPathStr = `${this.path}.data.${(0, utils_1.getStringFromComponentPath)(path)}`;\n if (this.subForm) {\n return this.subForm.getComponent(path, fn, originalPathStr);\n }\n }\n getSubOptions(options = {}) {\n options.parentPath = `${this.path}.data.`;\n options.events = this.createEmitter();\n // Make sure to not show the submit button in wizards in the nested forms.\n lodash_1.default.set(options, 'buttonSettings.showSubmit', false);\n if (!this.options) {\n return options;\n }\n if (this.options.base) {\n options.base = this.options.base;\n }\n if (this.options.project) {\n options.project = this.options.project;\n }\n if (this.options.readOnly || this.component.disabled) {\n options.readOnly = this.options.readOnly || this.component.disabled;\n }\n if (this.options.breadcrumbSettings) {\n options.breadcrumbSettings = this.options.breadcrumbSettings;\n }\n if (this.options.buttonSettings) {\n options.buttonSettings = lodash_1.default.clone(this.options.buttonSettings);\n }\n if (this.options.viewAsHtml) {\n options.viewAsHtml = this.options.viewAsHtml;\n }\n if (this.options.language) {\n options.language = this.options.language;\n }\n if (this.options.template) {\n options.template = this.options.template;\n }\n if (this.options.templates) {\n options.templates = this.options.templates;\n }\n if (this.options.renderMode) {\n options.renderMode = this.options.renderMode;\n }\n if (this.options.attachMode) {\n options.attachMode = this.options.attachMode;\n }\n if (this.options.iconset) {\n options.iconset = this.options.iconset;\n }\n if (this.options.fileService) {\n options.fileService = this.options.fileService;\n }\n if (this.options.onChange) {\n options.onChange = this.options.onChange;\n }\n return options;\n }\n render() {\n if (this.builderMode) {\n return super.render(this.component.label || 'Nested form');\n }\n const subform = this.subForm ? this.subForm.render() : this.renderTemplate('loading');\n return super.render(subform);\n }\n asString(value) {\n return this.getValueAsString(value);\n }\n /**\n * Prints out the value of form components as a datagrid value.\n */\n getValueAsString(value) {\n if (!value) {\n return 'No data provided';\n }\n if (!value.data && value._id) {\n return value._id;\n }\n if (!value.data || !Object.keys(value.data).length) {\n return 'No data provided';\n }\n return '[Complex Data]';\n }\n attach(element) {\n // Don't attach in builder.\n if (this.builderMode) {\n return super.attach(element);\n }\n return super.attach(element)\n .then(() => {\n if (this.isSubFormLazyLoad() && !this.hasLoadedForm && !this.subFormLoading) {\n this.createSubForm(true);\n }\n return this.subFormReady.then(() => {\n this.empty(element);\n if (this.options.builder) {\n this.setContent(element, this.ce('div', {\n class: 'text-muted text-center p-2'\n }, this.text(this.formObj.title)));\n return;\n }\n this.setContent(element, this.render());\n if (this.subForm) {\n if (this.isNestedWizard) {\n element = this.root.element;\n }\n this.subForm.attach(element);\n this.valueChanged = this.hasSetValue;\n if (!this.valueChanged && this.dataValue.state !== 'submitted') {\n this.setDefaultValue();\n }\n else {\n this.restoreValue();\n }\n }\n if (!this.builderMode && this.component.modalEdit) {\n const modalShouldBeOpened = this.componentModal ? this.componentModal.isOpened : false;\n const currentValue = modalShouldBeOpened ? this.componentModal.currentValue : this.dataValue;\n this.componentModal = new ComponentModal_1.default(this, element, modalShouldBeOpened, currentValue);\n this.setOpenModalElement();\n }\n this.calculateValue();\n });\n });\n }\n detach() {\n if (this.subForm) {\n this.subForm.detach();\n }\n super.detach();\n }\n get currentForm() {\n return this._currentForm;\n }\n get hasLoadedForm() {\n return this.formObj\n && this.formObj.components\n && Array.isArray(this.formObj.components)\n && this.formObj.components.length;\n }\n set currentForm(instance) {\n this._currentForm = instance;\n if (!this.subForm) {\n return;\n }\n this.subForm.getComponents().forEach(component => {\n component.currentForm = this;\n });\n }\n get isRevisionChanged() {\n return lodash_1.default.isNumber(this.subFormRevision)\n && lodash_1.default.isNumber(this.formObj._vid)\n && this.formObj._vid !== this.subFormRevision;\n }\n destroy(all = false) {\n if (this.subForm) {\n this.subForm.destroy(all);\n this.subForm = null;\n this.subFormReady = null;\n }\n super.destroy(all);\n }\n redraw() {\n if (this.subForm) {\n this.subForm.form = this.formObj;\n this.setSubFormDisabled(this.subForm);\n }\n return super.redraw();\n }\n /**\n * Pass everyComponent to subform.\n * @param args\n * @returns {*|void}\n */\n everyComponent(...args) {\n if (this.subForm) {\n this.subForm.everyComponent(...args);\n }\n }\n setSubFormDisabled(subForm) {\n subForm.disabled = this.disabled; // When the Nested Form is disabled make the subForm disabled\n }\n updateSubWizards(subForm) {\n var _a, _b;\n if (this.isNestedWizard && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.subWizards) && ((_b = subForm === null || subForm === void 0 ? void 0 : subForm._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard') {\n const existedForm = this.root.subWizards.findIndex(form => form.component.form === this.component.form);\n if (existedForm !== -1) {\n this.root.subWizards[existedForm] = this;\n }\n else {\n this.root.subWizards.push(this);\n }\n this.emit('subWizardsUpdated', subForm);\n }\n }\n /**\n * Create a subform instance.\n *\n * @return {*}\n */\n createSubForm(fromAttach) {\n this.subFormReady = this.loadSubForm(fromAttach).then((form) => {\n if (!form) {\n return;\n }\n // Iterate through every component and hide the submit button.\n (0, utils_1.eachComponent)(form.components, (component) => {\n this.hideSubmitButton(component);\n });\n // If the subform is already created then destroy the old one.\n if (this.subForm) {\n this.subForm.destroy();\n }\n // Render the form.\n return (new Form_1.default(form, this.getSubOptions())).ready.then((instance) => {\n this.subForm = instance;\n this.subForm.currentForm = this;\n this.subForm.parent = this;\n this.subForm.parentVisible = this.visible;\n this.subForm.on('change', () => {\n if (this.subForm) {\n this.dataValue = this.subForm.getValue();\n this.triggerChange({\n noEmit: true\n });\n }\n });\n this.subForm.url = this.formSrc;\n this.subForm.nosubmit = true;\n this.subForm.root = this.root;\n this.subForm.localRoot = this.isNestedWizard ? this.localRoot : this.subForm;\n this.restoreValue();\n this.valueChanged = this.hasSetValue;\n this.onChange();\n return this.subForm;\n });\n }).then((subForm) => {\n this.updateSubWizards(subForm);\n return subForm;\n });\n return this.subFormReady;\n }\n hideSubmitButton(component) {\n const isSubmitButton = (component.type === 'button') &&\n ((component.action === 'submit') || !component.action);\n if (isSubmitButton) {\n component.hidden = true;\n }\n }\n /**\n * Load the subform.\n */\n loadSubForm(fromAttach) {\n if (this.builderMode || this.isHidden() || (this.isSubFormLazyLoad() && !fromAttach)) {\n return Promise.resolve();\n }\n if (this.hasLoadedForm && !this.isRevisionChanged &&\n !(this.options.pdf && this.useOriginalRevision && lodash_1.default.isNull(this.subForm) && !this.subFormLoading)) {\n // Pass config down to sub forms.\n if (this.root && this.root.form && this.root.form.config && !this.formObj.config) {\n this.formObj.config = this.root.form.config;\n }\n return Promise.resolve(this.formObj);\n }\n else if (this.formSrc) {\n this.subFormLoading = true;\n return (new Formio_1.Formio(this.formSrc)).loadForm({ params: { live: 1 } })\n .then((formObj) => {\n this.formObj = formObj;\n this.subFormLoading = false;\n return formObj;\n })\n .catch((err) => {\n console.log(err);\n return null;\n });\n }\n return Promise.resolve();\n }\n get subFormData() {\n var _a;\n return ((_a = this.dataValue) === null || _a === void 0 ? void 0 : _a.data) || {};\n }\n checkComponentValidity(data, dirty, row, options) {\n options = options || {};\n const silentCheck = options.silentCheck || false;\n if (this.subForm) {\n return this.subForm.checkValidity(this.subFormData, dirty, null, silentCheck);\n }\n return super.checkComponentValidity(data, dirty, row, options);\n }\n checkComponentConditions(data, flags, row) {\n const visible = super.checkComponentConditions(data, flags, row);\n // Return if already hidden\n if (!visible) {\n return visible;\n }\n if (this.subForm) {\n return this.subForm.checkConditions(this.subFormData);\n }\n // There are few cases when subForm is not loaded when a change is triggered,\n // so we need to perform checkConditions after it is ready, or some conditional fields might be hidden in View mode\n else if (this.subFormReady) {\n this.subFormReady.then(() => {\n if (this.subForm) {\n return this.subForm.checkConditions(this.subFormData);\n }\n });\n }\n return visible;\n }\n calculateValue(data, flags, row) {\n if (this.subForm) {\n return this.subForm.calculateValue(this.subFormData, flags);\n }\n return super.calculateValue(data, flags, row);\n }\n setPristine(pristine) {\n super.setPristine(pristine);\n if (this.subForm) {\n this.subForm.setPristine(pristine);\n }\n }\n /**\n * Determine if the subform should be submitted.\n * @return {*|boolean}\n */\n get shouldSubmit() {\n return this.subFormReady && (!this.component.hasOwnProperty('reference') || this.component.reference) && !this.isHidden();\n }\n /**\n * Returns the data for the subform.\n *\n * @return {*}\n */\n getSubFormData() {\n if (lodash_1.default.get(this.subForm, 'form.display') === 'pdf') {\n return this.subForm.getSubmission();\n }\n else {\n return Promise.resolve(this.dataValue);\n }\n }\n /**\n * Submit the subform if configured to do so.\n *\n * @return {*}\n */\n submitSubForm(rejectOnError) {\n // If we wish to submit the form on next page, then do that here.\n if (this.shouldSubmit) {\n return this.subFormReady.then(() => {\n if (!this.subForm) {\n return this.dataValue;\n }\n this.subForm.nosubmit = false;\n return this.subForm.submitForm().then(result => {\n this.subForm.loading = false;\n this.subForm.showAllErrors = false;\n this.dataValue = result.submission;\n return this.dataValue;\n }).catch(err => {\n this.subForm.showAllErrors = true;\n if (rejectOnError) {\n this.subForm.onSubmissionError(err);\n return Promise.reject(err);\n }\n else {\n return {};\n }\n });\n });\n }\n return this.getSubFormData();\n }\n /**\n * Submit the form before the next page is triggered.\n */\n beforePage(next) {\n // Should not submit child forms if we are going to the previous page\n if (!next) {\n return super.beforePage(next);\n }\n return this.submitSubForm(true).then(() => super.beforePage(next));\n }\n /**\n * Submit the form before the whole form is triggered.\n */\n beforeSubmit() {\n var _a;\n const submission = this.dataValue;\n const isAlreadySubmitted = submission && submission._id && submission.form;\n // This submission has already been submitted, so just return the reference data.\n if (isAlreadySubmitted && !((_a = this.subForm) === null || _a === void 0 ? void 0 : _a.wizard)) {\n this.dataValue = submission;\n return Promise.resolve(this.dataValue);\n }\n return this.submitSubForm(false)\n .then(() => {\n return this.dataValue;\n })\n .then(() => super.beforeSubmit());\n }\n isSubFormLazyLoad() {\n var _a, _b;\n return ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard' && this.component.lazyLoad;\n }\n isHidden() {\n if (!this.visible) {\n return true;\n }\n return !super.checkConditions(this.rootValue);\n }\n setValue(submission, flags = {}) {\n var _a;\n const changed = super.setValue(submission, flags);\n this.valueChanged = true;\n if (this.subForm) {\n const revisionPath = submission._frid ? '_frid' : '_vid';\n const shouldLoadOriginalRevision = this.useOriginalRevision\n && (lodash_1.default.isNumber(submission[revisionPath]) || lodash_1.default.isNumber(submission._fvid))\n && lodash_1.default.isNumber((_a = this.subForm.form) === null || _a === void 0 ? void 0 : _a[revisionPath])\n && submission._fvid !== this.subForm.form[revisionPath];\n if (shouldLoadOriginalRevision) {\n this.setFormRevision(submission._frid || submission._fvid);\n this.createSubForm().then(() => {\n this.attach(this.element);\n });\n }\n else {\n this.setSubFormValue(submission, flags);\n }\n }\n return changed;\n }\n setSubFormValue(submission, flags) {\n const shouldLoadSubmissionById = submission\n && submission._id\n && this.subForm.formio\n && lodash_1.default.isEmpty(submission.data);\n if (shouldLoadSubmissionById) {\n const formId = submission.form || this.formObj.form || this.component.form;\n const submissionUrl = `${this.subForm.formio.formsUrl}/${formId}/submission/${submission._id}`;\n this.subForm.setUrl(submissionUrl, this.options);\n this.subForm.loadSubmission();\n }\n else {\n this.subForm.setValue(submission, flags);\n }\n }\n isEmpty(value = this.dataValue) {\n return value === null || lodash_1.default.isEqual(value, this.emptyValue) || (this.areAllComponentsEmpty(value.data) && !value._id);\n }\n areAllComponentsEmpty(data) {\n let res = true;\n if (this.subForm) {\n this.subForm.everyComponent((comp) => {\n const componentValue = lodash_1.default.get(data, comp.key);\n res &= comp.isEmpty(componentValue);\n });\n }\n else {\n res = false;\n }\n return res;\n }\n getValue() {\n if (this.subForm) {\n return this.subForm.getValue();\n }\n return this.dataValue;\n }\n get errors() {\n let errors = super.errors;\n if (this.subForm) {\n errors = errors.concat(this.subForm.errors);\n }\n return errors;\n }\n updateSubFormVisibility() {\n if (this.subForm) {\n this.subForm.parentVisible = this.visible;\n }\n }\n /**\n * Determines if this form is a Nested Wizard\n * which means it should be a Wizard itself and should be a direct child of a Wizard's page\n * @returns {boolean}\n */\n get isNestedWizard() {\n var _a, _b, _c, _d, _e;\n return ((_b = (_a = this.subForm) === null || _a === void 0 ? void 0 : _a._form) === null || _b === void 0 ? void 0 : _b.display) === 'wizard' && ((_e = (_d = (_c = this.parent) === null || _c === void 0 ? void 0 : _c.parent) === null || _d === void 0 ? void 0 : _d._form) === null || _e === void 0 ? void 0 : _e.display) === 'wizard';\n }\n get visible() {\n return super.visible;\n }\n set visible(value) {\n const isNestedWizard = this.isNestedWizard;\n if (this._visible !== value) {\n this._visible = value;\n // Form doesn't load if hidden. If it becomes visible, create the form.\n if (!this.subForm && value) {\n this.createSubForm();\n this.subFormReady.then(() => {\n this.updateSubFormVisibility();\n this.clearOnHide();\n });\n this.redraw();\n return;\n }\n this.updateSubFormVisibility();\n this.clearOnHide();\n isNestedWizard ? this.rebuild() : this.redraw();\n }\n if (!value && isNestedWizard) {\n this.root.redraw();\n }\n }\n get parentVisible() {\n return super.parentVisible;\n }\n set parentVisible(value) {\n if (this._parentVisible !== value) {\n this._parentVisible = value;\n this.clearOnHide();\n // Form doesn't load if hidden. If it becomes visible, create the form.\n if (!this.subForm && value) {\n this.createSubForm();\n this.subFormReady.then(() => {\n this.updateSubFormVisibility();\n });\n this.redraw();\n return;\n }\n this.updateSubFormVisibility();\n this.redraw();\n }\n }\n isInternalEvent(event) {\n switch (event) {\n case 'focus':\n case 'blur':\n case 'componentChange':\n case 'componentError':\n case 'error':\n case 'formLoad':\n case 'languageChanged':\n case 'render':\n case 'checkValidity':\n case 'initialized':\n case 'submit':\n case 'submitButton':\n case 'nosubmit':\n case 'updateComponent':\n case 'submitDone':\n case 'submissionDeleted':\n case 'requestDone':\n case 'nextPage':\n case 'prevPage':\n case 'wizardNavigationClicked':\n case 'updateWizardNav':\n case 'restoreDraft':\n case 'saveDraft':\n case 'saveComponent':\n case 'pdfUploaded':\n return true;\n default:\n return false;\n }\n }\n createEmitter() {\n const emitter = new eventemitter3_1.default();\n const nativeEmit = emitter.emit;\n const that = this;\n emitter.emit = function (event, ...args) {\n const eventType = event.replace(`${that.options.namespace}.`, '');\n nativeEmit.call(this, event, ...args);\n if (!that.isInternalEvent(eventType)) {\n that.emit(eventType, ...args);\n }\n };\n return emitter;\n }\n deleteValue() {\n super.setValue(null, {\n noUpdateEvent: true,\n noDefault: true\n });\n this.unset();\n }\n}\nexports[\"default\"] = FormComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/form/Form.js?");
|
5290
5290
|
|
5291
5291
|
/***/ }),
|
5292
5292
|
|
@@ -5407,7 +5407,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5407
5407
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5408
5408
|
|
5409
5409
|
"use strict";
|
5410
|
-
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 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 this.addFocusBlurEvents(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?");
|
5410
|
+
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?");
|
5411
5411
|
|
5412
5412
|
/***/ }),
|
5413
5413
|
|
@@ -5473,7 +5473,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5473
5473
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5474
5474
|
|
5475
5475
|
"use strict";
|
5476
|
-
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst choices_js_1 = __importDefault(__webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\"));\nclass TagsComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'tags',\n label: 'Tags',\n key: 'tags',\n delimeter: ',',\n storeas: 'string',\n maxTags: 0\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Tags',\n icon: 'tags',\n group: 'advanced',\n documentation: '/userguide/form-building/advanced-components#tags',\n weight: 30,\n schema: TagsComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return TagsComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: [...super.conditionOperatorsSettings.operators, 'includes', 'notIncludes'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes[schema.storeas] || utils_1.componentValueTypes.string];\n }\n init() {\n super.init();\n }\n get emptyValue() {\n return (this.component.storeas === 'string') ? '' : [];\n }\n get defaultSchema() {\n return TagsComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'text';\n info.changeEvent = 'change';\n return info;\n }\n get delimiter() {\n return this.component.delimeter || ',';\n }\n attachElement(element, index) {\n super.attachElement(element, index);\n if (!element) {\n return;\n }\n if (this.i18next) {\n element.setAttribute('dir', this.i18next.dir());\n }\n if (this.choices) {\n this.choices.destroy();\n }\n if (!choices_js_1.default) {\n return;\n }\n const hasPlaceholder = !!this.component.placeholder;\n this.choices = new choices_js_1.default(element, {\n delimiter: this.delimiter,\n editItems: true,\n allowHTML: true,\n maxItemCount: this.component.maxTags,\n removeItemButton: true,\n duplicateItemsAllowed: false,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n placeholder: hasPlaceholder,\n placeholderValue: hasPlaceholder ? this.t(this.component.placeholder, { _userInput: true }) : null,\n });\n this.choices.itemList.element.tabIndex = element.tabIndex;\n this.addEventListener(this.choices.input.element, 'blur', () => {\n const value = this.choices.input.value;\n const maxTagsNumber = this.component.maxTags;\n const valuesCount = this.choices.getValue(true).length;\n const isRepeatedValue = this.choices.getValue(true).some(existingValue => existingValue.trim() === value.trim());\n if (value) {\n if (maxTagsNumber && valuesCount === maxTagsNumber) {\n this.choices.addItems = false;\n this.choices.clearInput();\n }\n else if (isRepeatedValue) {\n this.choices.clearInput();\n }\n else {\n this.choices.setValue([value]);\n this.choices.clearInput();\n this.choices.hideDropdown(true);\n this.updateValue(null, {\n modified: true\n });\n }\n }\n });\n }\n detach() {\n if (this.choices) {\n this.choices.destroy();\n this.choices = null;\n }\n super.detach();\n }\n normalizeValue(value) {\n if (this.component.storeas === 'string' && Array.isArray(value)) {\n return value.join(this.delimiter);\n }\n else if (this.component.storeas === 'array' && typeof value === 'string') {\n return value.split(this.delimiter).filter(result => result);\n }\n return value;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.choices) {\n let dataValue = this.dataValue;\n this.choices.removeActiveItems();\n if (dataValue) {\n if (typeof dataValue === 'string') {\n dataValue = dataValue.split(this.delimiter).filter(result => result);\n }\n const value = Array.isArray(dataValue) ? dataValue : [dataValue];\n this.choices.setValue(value.map((val) => this.sanitize(val, this.shouldSanitizeValue)));\n }\n }\n return changed;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.choices.disable();\n }\n else {\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n focus() {\n if (this.refs.input && this.refs.input.length) {\n this.refs.input[0].parentNode.lastChild.focus();\n }\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (Array.isArray(value)) {\n return value.join(`${this.delimiter || ','} `);\n }\n const stringValue = value.toString();\n return this.sanitize(stringValue, this.shouldSanitizeValue);\n }\n}\nexports[\"default\"] = TagsComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/tags/Tags.js?");
|
5476
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Input_1 = __importDefault(__webpack_require__(/*! ../_classes/input/Input */ \"./lib/cjs/components/_classes/input/Input.js\"));\nconst choices_js_1 = __importDefault(__webpack_require__(/*! @formio/choices.js */ \"./node_modules/@formio/choices.js/public/assets/scripts/choices.js\"));\nclass TagsComponent extends Input_1.default {\n static schema(...extend) {\n return Input_1.default.schema({\n type: 'tags',\n label: 'Tags',\n key: 'tags',\n delimeter: ',',\n storeas: 'string',\n maxTags: 0\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Tags',\n icon: 'tags',\n group: 'advanced',\n documentation: '/userguide/form-building/advanced-components#tags',\n weight: 30,\n schema: TagsComponent.schema()\n };\n }\n static get serverConditionSettings() {\n return TagsComponent.conditionOperatorsSettings;\n }\n static get conditionOperatorsSettings() {\n return Object.assign(Object.assign({}, super.conditionOperatorsSettings), { operators: [...super.conditionOperatorsSettings.operators, 'includes', 'notIncludes'] });\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes[schema.storeas] || utils_1.componentValueTypes.string];\n }\n init() {\n super.init();\n }\n get emptyValue() {\n return (this.component.storeas === 'string') ? '' : [];\n }\n get defaultSchema() {\n return TagsComponent.schema();\n }\n get inputInfo() {\n const info = super.inputInfo;\n info.type = 'input';\n info.attr.type = 'text';\n info.changeEvent = 'change';\n return info;\n }\n get delimiter() {\n return this.component.delimeter || ',';\n }\n attachElement(element, index) {\n super.attachElement(element, index);\n if (!element) {\n return;\n }\n if (this.i18next) {\n element.setAttribute('dir', this.i18next.dir());\n }\n if (this.choices) {\n this.choices.destroy();\n }\n if (!choices_js_1.default) {\n return;\n }\n const hasPlaceholder = !!this.component.placeholder;\n this.choices = new choices_js_1.default(element, {\n delimiter: this.delimiter,\n editItems: true,\n allowHTML: true,\n maxItemCount: this.component.maxTags,\n removeItemButton: true,\n duplicateItemsAllowed: false,\n shadowRoot: this.root ? this.root.shadowRoot : null,\n placeholder: hasPlaceholder,\n placeholderValue: hasPlaceholder ? this.t(this.component.placeholder, { _userInput: true }) : null,\n });\n this.choices.itemList.element.tabIndex = element.tabIndex;\n this.addEventListener(this.choices.input.element, 'blur', () => {\n // Emit event to the native Formio input, so the listener attached in the Input.js will be invoked\n element.dispatchEvent(new Event('blur'));\n const value = this.choices.input.value;\n const maxTagsNumber = this.component.maxTags;\n const valuesCount = this.choices.getValue(true).length;\n const isRepeatedValue = this.choices.getValue(true).some(existingValue => existingValue.trim() === value.trim());\n if (value) {\n if (maxTagsNumber && valuesCount === maxTagsNumber) {\n this.choices.addItems = false;\n this.choices.clearInput();\n }\n else if (isRepeatedValue) {\n this.choices.clearInput();\n }\n else {\n this.choices.setValue([value]);\n this.choices.clearInput();\n this.choices.hideDropdown(true);\n this.updateValue(null, {\n modified: true\n });\n }\n }\n });\n }\n detach() {\n if (this.choices) {\n this.choices.destroy();\n this.choices = null;\n }\n super.detach();\n }\n normalizeValue(value) {\n if (this.component.storeas === 'string' && Array.isArray(value)) {\n return value.join(this.delimiter);\n }\n else if (this.component.storeas === 'array' && typeof value === 'string') {\n return value.split(this.delimiter).filter(result => result);\n }\n return value;\n }\n setValue(value, flags = {}) {\n const changed = super.setValue(value, flags);\n if (this.choices) {\n let dataValue = this.dataValue;\n this.choices.removeActiveItems();\n if (dataValue) {\n if (typeof dataValue === 'string') {\n dataValue = dataValue.split(this.delimiter).filter(result => result);\n }\n const value = Array.isArray(dataValue) ? dataValue : [dataValue];\n this.choices.setValue(value.map((val) => this.sanitize(val, this.shouldSanitizeValue)));\n }\n }\n return changed;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n if (!this.choices) {\n return;\n }\n if (disabled) {\n this.choices.disable();\n }\n else {\n this.choices.enable();\n }\n }\n get disabled() {\n return super.disabled;\n }\n focus() {\n if (this.refs.input && this.refs.input.length) {\n this.refs.input[0].parentNode.lastChild.focus();\n }\n }\n getValueAsString(value) {\n if (!value) {\n return '';\n }\n if (Array.isArray(value)) {\n return value.join(`${this.delimiter || ','} `);\n }\n const stringValue = value.toString();\n return this.sanitize(stringValue, this.shouldSanitizeValue);\n }\n}\nexports[\"default\"] = TagsComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/tags/Tags.js?");
|
5477
5477
|
|
5478
5478
|
/***/ }),
|
5479
5479
|
|
@@ -8131,7 +8131,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
|
|
8131
8131
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
8132
8132
|
|
8133
8133
|
"use strict";
|
8134
|
-
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.
|
8134
|
+
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.22';\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?");
|
8135
8135
|
|
8136
8136
|
/***/ }),
|
8137
8137
|
|