@formio/js 5.0.0-rc.66 → 5.0.0-rc.68
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/formio.builder.css +0 -1
- package/dist/formio.builder.min.css +1 -1
- package/dist/formio.embed.js +1 -1
- package/dist/formio.embed.min.js +1 -1
- package/dist/formio.embed.min.js.LICENSE.txt +1 -1
- package/dist/formio.form.css +0 -1
- package/dist/formio.form.js +11 -11
- package/dist/formio.form.min.css +1 -1
- package/dist/formio.form.min.js +1 -1
- package/dist/formio.form.min.js.LICENSE.txt +1 -1
- package/dist/formio.full.css +0 -1
- package/dist/formio.full.js +12 -12
- package/dist/formio.full.min.css +1 -1
- package/dist/formio.full.min.js +1 -1
- package/dist/formio.full.min.js.LICENSE.txt +1 -1
- package/dist/formio.js +2 -2
- package/dist/formio.min.js +1 -1
- package/dist/formio.min.js.LICENSE.txt +1 -1
- package/dist/formio.utils.js +3 -3
- package/dist/formio.utils.min.js +1 -1
- package/dist/formio.utils.min.js.LICENSE.txt +1 -1
- package/lib/cjs/Webform.js +4 -0
- package/lib/cjs/components/address/Address.js +4 -0
- package/lib/cjs/components/address/editForm/Address.edit.provider.js +1 -1
- package/lib/cjs/components/datagrid/DataGrid.d.ts +9 -0
- package/lib/cjs/components/datagrid/DataGrid.js +49 -34
- package/lib/cjs/components/datagrid/fixtures/comp-with-reorder.d.ts +100 -0
- package/lib/cjs/components/datagrid/fixtures/comp-with-reorder.js +139 -0
- package/lib/cjs/components/datagrid/fixtures/index.d.ts +2 -1
- package/lib/cjs/components/datagrid/fixtures/index.js +3 -1
- package/lib/cjs/components/datamap/DataMap.js +2 -2
- package/lib/cjs/components/day/fixtures/comp8.d.ts +41 -0
- package/lib/cjs/components/day/fixtures/comp8.js +40 -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/editgrid/EditGrid.js +4 -3
- package/lib/cjs/components/editgrid/fixtures/comp16.d.ts +52 -0
- package/lib/cjs/components/editgrid/fixtures/comp16.js +71 -0
- package/lib/cjs/components/editgrid/fixtures/index.d.ts +2 -1
- package/lib/cjs/components/editgrid/fixtures/index.js +3 -1
- package/lib/cjs/translations/en.d.ts +3 -0
- package/lib/cjs/translations/en.js +4 -1
- package/lib/mjs/Webform.js +4 -0
- package/lib/mjs/components/address/Address.js +4 -0
- package/lib/mjs/components/address/editForm/Address.edit.provider.js +1 -1
- package/lib/mjs/components/datagrid/DataGrid.d.ts +9 -0
- package/lib/mjs/components/datagrid/DataGrid.js +48 -33
- package/lib/mjs/components/datagrid/fixtures/comp-with-reorder.d.ts +100 -0
- package/lib/mjs/components/datagrid/fixtures/comp-with-reorder.js +137 -0
- package/lib/mjs/components/datagrid/fixtures/index.d.ts +2 -1
- package/lib/mjs/components/datagrid/fixtures/index.js +2 -1
- package/lib/mjs/components/datamap/DataMap.js +1 -1
- package/lib/mjs/components/day/fixtures/comp8.d.ts +41 -0
- package/lib/mjs/components/day/fixtures/comp8.js +38 -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/editgrid/EditGrid.js +4 -3
- package/lib/mjs/components/editgrid/fixtures/comp16.d.ts +52 -0
- package/lib/mjs/components/editgrid/fixtures/comp16.js +69 -0
- package/lib/mjs/components/editgrid/fixtures/index.d.ts +2 -1
- package/lib/mjs/components/editgrid/fixtures/index.js +2 -1
- package/lib/mjs/translations/en.d.ts +3 -0
- package/lib/mjs/translations/en.js +4 -1
- package/package.json +2 -2
package/dist/formio.form.js
CHANGED
@@ -552,7 +552,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument
|
|
552
552
|
/***/ (function(__unused_webpack_module, exports) {
|
553
553
|
|
554
554
|
"use strict";
|
555
|
-
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.EN_ERRORS = void 0;\nexports.EN_ERRORS = {\n unsavedRowsError: 'Please save all rows before proceeding.',\n invalidRowsError: 'Please correct invalid rows before proceeding.',\n invalidRowError: 'Invalid row. Please correct it or delete.',\n invalidOption: '{{field}} is an invalid value.',\n invalidDay: '{{field}} is not a valid day.',\n required: '{{field}} is required',\n unique: '{{field}} must be unique',\n array: '{{field}} must be an array',\n array_nonempty: '{{field}} must be a non-empty array', // eslint-disable-line camelcase\n nonarray: '{{field}} must not be an array',\n select: '{{field}} contains an invalid selection',\n pattern: '{{field}} does not match the pattern {{pattern}}',\n minLength: '{{field}} must have at least {{length}} characters.',\n maxLength: '{{field}} must have no more than {{length}} characters.',\n minWords: '{{field}} must have at least {{length}} words.',\n maxWords: '{{field}} must have no more than {{length}} words.',\n min: '{{field}} cannot be less than {{min}}.',\n max: '{{field}} cannot be greater than {{max}}.',\n maxDate: '{{field}} should not contain date after {{- maxDate}}',\n minDate: '{{field}} should not contain date before {{- minDate}}',\n maxYear: '{{field}} should not contain year greater than {{maxYear}}',\n minSelectedCount: 'You must select at least {{minCount}} items',\n maxSelectedCount: 'You may only select up to {{maxCount}} items',\n minYear: '{{field}} should not contain year less than {{minYear}}',\n invalid_email: '{{field}} must be a valid email.', // eslint-disable-line camelcase\n invalid_url: '{{field}} must be a valid url.', // eslint-disable-line camelcase\n invalid_regex: '{{field}} does not match the pattern {{regex}}.', // eslint-disable-line camelcase\n invalid_date: '{{field}} is not a valid date.', // eslint-disable-line camelcase\n invalid_day: '{{field}} is not a valid day.', // eslint-disable-line camelcase\n invalidValueProperty: 'Invalid Value Property',\n mask: '{{field}} does not match the mask.',\n valueIsNotAvailable: '{{ field }} is an invalid value.',\n time: '{{field}} is not a valid time.',\n invalidDate: '{{field}} is not a valid date',\n number: '{{field}} is not a valid number.'\n};\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/process/validation/i18n/en.js?");
|
555
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.EN_ERRORS = void 0;\nexports.EN_ERRORS = {\n unsavedRowsError: 'Please save all rows before proceeding.',\n invalidRowsError: 'Please correct invalid rows before proceeding.',\n invalidRowError: 'Invalid row. Please correct it or delete.',\n invalidOption: '{{field}} is an invalid value.',\n invalidDay: '{{field}} is not a valid day.',\n required: '{{field}} is required',\n unique: '{{field}} must be unique',\n array: '{{field}} must be an array',\n array_nonempty: '{{field}} must be a non-empty array', // eslint-disable-line camelcase\n nonarray: '{{field}} must not be an array',\n select: '{{field}} contains an invalid selection',\n pattern: '{{field}} does not match the pattern {{pattern}}',\n minLength: '{{field}} must have at least {{length}} characters.',\n maxLength: '{{field}} must have no more than {{length}} characters.',\n minWords: '{{field}} must have at least {{length}} words.',\n maxWords: '{{field}} must have no more than {{length}} words.',\n min: '{{field}} cannot be less than {{min}}.',\n max: '{{field}} cannot be greater than {{max}}.',\n maxDate: '{{field}} should not contain date after {{- maxDate}}',\n minDate: '{{field}} should not contain date before {{- minDate}}',\n maxYear: '{{field}} should not contain year greater than {{maxYear}}',\n minSelectedCount: 'You must select at least {{minCount}} items',\n maxSelectedCount: 'You may only select up to {{maxCount}} items',\n minYear: '{{field}} should not contain year less than {{minYear}}',\n invalid_email: '{{field}} must be a valid email.', // eslint-disable-line camelcase\n invalid_url: '{{field}} must be a valid url.', // eslint-disable-line camelcase\n invalid_regex: '{{field}} does not match the pattern {{regex}}.', // eslint-disable-line camelcase\n invalid_date: '{{field}} is not a valid date.', // eslint-disable-line camelcase\n invalid_day: '{{field}} is not a valid day.', // eslint-disable-line camelcase\n invalidValueProperty: 'Invalid Value Property',\n mask: '{{field}} does not match the mask.',\n valueIsNotAvailable: '{{ field }} is an invalid value.',\n time: '{{field}} is not a valid time.',\n invalidDate: '{{field}} is not a valid date',\n number: '{{field}} is not a valid number.',\n requiredDayField: '{{ field }} is required',\n requiredMonthField: '{{ field }} is required',\n requiredYearField: '{{ field }} is required'\n};\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/process/validation/i18n/en.js?");
|
556
556
|
|
557
557
|
/***/ }),
|
558
558
|
|
@@ -640,7 +640,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo
|
|
640
640
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
641
641
|
|
642
642
|
"use strict";
|
643
|
-
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.validateAvailableItemsInfo = exports.validateAvailableItemsSync = exports.shouldValidate = exports.validateAvailableItems = void 0;\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\nconst error_1 = __webpack_require__(/*! ../../../error */ \"./node_modules/@formio/core/lib/error/index.js\");\nconst utils_1 = __webpack_require__(/*! ../../../utils */ \"./node_modules/@formio/core/lib/utils/index.js\");\nconst util_1 = __webpack_require__(/*! ../util */ \"./node_modules/@formio/core/lib/process/validation/util.js\");\nfunction isValidatableRadioComponent(component) {\n var _a;\n return (component &&\n component.type === 'radio' &&\n !!((_a = component.validate) === null || _a === void 0 ? void 0 : _a.onlyAvailableItems) &&\n component.dataSrc === 'values');\n}\nfunction isValidateableSelectComponent(component) {\n var _a;\n return (component &&\n !!((_a = component.validate) === null || _a === void 0 ? void 0 : _a.hasOwnProperty('onlyAvailableItems')) &&\n component.type === 'select' &&\n component.dataSrc !== 'resource');\n}\nfunction mapDynamicValues(component, values) {\n return values.map((value) => {\n if (component.valueProperty) {\n return value[component.valueProperty];\n }\n return value;\n });\n}\nfunction mapStaticValues(values) {\n return values.map((obj) => obj.value);\n}\nfunction getAvailableSelectValues(component, context) {\n return __awaiter(this, void 0, void 0, function* () {\n if ((0, lodash_1.isUndefined)(component.dataSrc) && component.data.hasOwnProperty('values')) {\n component.dataSrc = 'values';\n }\n ;\n switch (component.dataSrc) {\n case 'values':\n if (Array.isArray(component.data.values)) {\n return mapStaticValues(component.data.values);\n }\n throw new error_1.ProcessorError(`Failed to validate available values in static values select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n case 'json': {\n if (typeof component.data.json === 'string') {\n try {\n return mapDynamicValues(component, JSON.parse(component.data.json));\n }\n catch (err) {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': ${err}`, context, 'validate:validateAvailableItems');\n }\n }\n else if (Array.isArray(component.data.json)) {\n // TODO: need to retype this\n return mapDynamicValues(component, component.data.json);\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n }\n case 'custom':\n const customItems = utils_1.Evaluator.evaluate(component.data.custom, {\n values: [],\n }, 'values');\n if ((0, util_1.isPromise)(customItems)) {\n const resolvedCustomItems = yield customItems;\n if (Array.isArray(resolvedCustomItems)) {\n return resolvedCustomItems;\n }\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n if (Array.isArray(customItems)) {\n return customItems;\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n default:\n throw new error_1.ProcessorError(`Failed to validate available values in select component '${component.key}': data source ${component.dataSrc} is not valid}`, context, 'validate:validateAvailableItems');\n }\n });\n}\nfunction getAvailableSelectValuesSync(component, context) {\n var _a;\n if ((0, lodash_1.isUndefined)(component.dataSrc) && component.data.hasOwnProperty('values')) {\n component.dataSrc = 'values';\n }\n ;\n switch (component.dataSrc) {\n case 'values':\n if (Array.isArray((_a = component.data) === null || _a === void 0 ? void 0 : _a.values)) {\n return mapStaticValues(component.data.values);\n }\n throw new error_1.ProcessorError(`Failed to validate available values in static values select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n case 'json': {\n if (typeof component.data.json === 'string') {\n try {\n return mapDynamicValues(component, JSON.parse(component.data.json));\n }\n catch (err) {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': ${err}`, context, 'validate:validateAvailableItems');\n }\n }\n else if (Array.isArray(component.data.json)) {\n // TODO: need to retype this\n return mapDynamicValues(component, component.data.json);\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n }\n case 'custom':\n const customItems = utils_1.Evaluator.evaluate(component.data.custom, {\n values: [],\n }, 'values');\n if (Array.isArray(customItems)) {\n return customItems;\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n case 'url':\n return null;\n default:\n throw new error_1.ProcessorError(`Failed to validate available values in select component '${component.key}': data source ${component.dataSrc} is not valid}`, context, 'validate:validateAvailableItems');\n }\n}\nfunction compareComplexValues(valueA, valueB, context) {\n if (!(0, util_1.isObject)(valueA) || !(0, util_1.isObject)(valueB)) {\n return false;\n }\n try {\n // TODO: we need to have normalized values here at this moment, otherwise\n // this won't work\n return JSON.stringify(valueA) === JSON.stringify(valueB);\n }\n catch (err) {\n throw new error_1.ProcessorError(`Error while comparing available values: ${err}`, context, 'validate:validateAvailableItems');\n }\n}\nconst validateAvailableItems = (context) => __awaiter(void 0, void 0, void 0, function* () {\n const { component, value } = context;\n const error = new error_1.FieldError('invalidOption', context, 'onlyAvailableItems');\n try {\n if (isValidatableRadioComponent(component)) {\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return null;\n }\n const values = component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => optionValue === value) !== -1\n ? null\n : error;\n }\n return null;\n }\n else if (isValidateableSelectComponent(component)) {\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return null;\n }\n const values = yield getAvailableSelectValues(component, context);\n if (values) {\n if ((0, util_1.isObject)(value)) {\n return values.find((optionValue) => compareComplexValues(optionValue, value, context)) !==\n undefined\n ? null\n : error;\n }\n return values.find((optionValue) => optionValue === value) !== undefined ? null : error;\n }\n }\n }\n catch (err) {\n throw new error_1.ProcessorError(err.message || err, context, 'validate:validateAvailableItems');\n }\n return null;\n});\nexports.validateAvailableItems = validateAvailableItems;\nconst shouldValidate = (context) => {\n const { component, value } = context;\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return false;\n }\n if (isValidatableRadioComponent(component)) {\n return true;\n }\n if (isValidateableSelectComponent(component)) {\n return true;\n }\n return false;\n};\nexports.shouldValidate = shouldValidate;\nconst validateAvailableItemsSync = (context) => {\n const { component, value } = context;\n const error = new error_1.FieldError('invalidOption', context, 'onlyAvailableItems');\n try {\n if (!(0, exports.shouldValidate)(context)) {\n return null;\n }\n if (isValidatableRadioComponent(component)) {\n const values = component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => optionValue === value) !== -1\n ? null\n : error;\n }\n return null;\n }\n else if (isValidateableSelectComponent(component)) {\n const values = getAvailableSelectValuesSync(component, context);\n if (values) {\n if ((0, util_1.isObject)(value)) {\n return values.find((optionValue) => compareComplexValues(optionValue, value, context)) !==\n undefined\n ? null\n : error;\n }\n return values.find((optionValue) => optionValue === value) !== undefined ? null : error;\n }\n }\n }\n catch (err) {\n throw new error_1.ProcessorError(err.message || err, context, 'validate:validateAvailableItems');\n }\n return null;\n};\nexports.validateAvailableItemsSync = validateAvailableItemsSync;\nexports.validateAvailableItemsInfo = {\n name: 'validateAvailableItems',\n process: exports.validateAvailableItems,\n processSync: exports.validateAvailableItemsSync,\n shouldProcess: exports.shouldValidate\n};\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/process/validation/rules/validateAvailableItems.js?");
|
643
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.validateAvailableItemsInfo = exports.validateAvailableItemsSync = exports.shouldValidate = exports.validateAvailableItems = void 0;\nconst lodash_1 = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\nconst error_1 = __webpack_require__(/*! ../../../error */ \"./node_modules/@formio/core/lib/error/index.js\");\nconst utils_1 = __webpack_require__(/*! ../../../utils */ \"./node_modules/@formio/core/lib/utils/index.js\");\nconst util_1 = __webpack_require__(/*! ../util */ \"./node_modules/@formio/core/lib/process/validation/util.js\");\nfunction isValidatableRadioComponent(component) {\n var _a;\n return (component &&\n component.type === 'radio' &&\n !!((_a = component.validate) === null || _a === void 0 ? void 0 : _a.onlyAvailableItems) &&\n component.dataSrc === 'values');\n}\nfunction isValidateableSelectComponent(component) {\n var _a;\n return (component &&\n !!((_a = component.validate) === null || _a === void 0 ? void 0 : _a.onlyAvailableItems) &&\n component.type === 'select' &&\n component.dataSrc !== 'resource');\n}\nfunction mapDynamicValues(component, values) {\n return values.map((value) => {\n if (component.valueProperty) {\n return value[component.valueProperty];\n }\n return value;\n });\n}\nfunction mapStaticValues(values) {\n return values.map((obj) => obj.value);\n}\nfunction getAvailableSelectValues(component, context) {\n return __awaiter(this, void 0, void 0, function* () {\n if ((0, lodash_1.isUndefined)(component.dataSrc) && component.data.hasOwnProperty('values')) {\n component.dataSrc = 'values';\n }\n ;\n switch (component.dataSrc) {\n case 'values':\n if (Array.isArray(component.data.values)) {\n return mapStaticValues(component.data.values);\n }\n throw new error_1.ProcessorError(`Failed to validate available values in static values select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n case 'json': {\n if (typeof component.data.json === 'string') {\n try {\n return mapDynamicValues(component, JSON.parse(component.data.json));\n }\n catch (err) {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': ${err}`, context, 'validate:validateAvailableItems');\n }\n }\n else if (Array.isArray(component.data.json)) {\n // TODO: need to retype this\n return mapDynamicValues(component, component.data.json);\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n }\n case 'custom':\n const customItems = utils_1.Evaluator.evaluate(component.data.custom, {\n values: [],\n }, 'values');\n if ((0, util_1.isPromise)(customItems)) {\n const resolvedCustomItems = yield customItems;\n if (Array.isArray(resolvedCustomItems)) {\n return resolvedCustomItems;\n }\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n if (Array.isArray(customItems)) {\n return customItems;\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n default:\n throw new error_1.ProcessorError(`Failed to validate available values in select component '${component.key}': data source ${component.dataSrc} is not valid}`, context, 'validate:validateAvailableItems');\n }\n });\n}\nfunction getAvailableSelectValuesSync(component, context) {\n var _a;\n if ((0, lodash_1.isUndefined)(component.dataSrc) && component.data.hasOwnProperty('values')) {\n component.dataSrc = 'values';\n }\n ;\n switch (component.dataSrc) {\n case 'values':\n if (Array.isArray((_a = component.data) === null || _a === void 0 ? void 0 : _a.values)) {\n return mapStaticValues(component.data.values);\n }\n throw new error_1.ProcessorError(`Failed to validate available values in static values select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n case 'json': {\n if (typeof component.data.json === 'string') {\n try {\n return mapDynamicValues(component, JSON.parse(component.data.json));\n }\n catch (err) {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': ${err}`, context, 'validate:validateAvailableItems');\n }\n }\n else if (Array.isArray(component.data.json)) {\n // TODO: need to retype this\n return mapDynamicValues(component, component.data.json);\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n }\n case 'custom':\n const customItems = utils_1.Evaluator.evaluate(component.data.custom, {\n values: [],\n }, 'values');\n if (Array.isArray(customItems)) {\n return customItems;\n }\n else {\n throw new error_1.ProcessorError(`Failed to validate available values in JSON select component '${component.key}': the values are not an array`, context, 'validate:validateAvailableItems');\n }\n case 'url':\n return null;\n default:\n throw new error_1.ProcessorError(`Failed to validate available values in select component '${component.key}': data source ${component.dataSrc} is not valid}`, context, 'validate:validateAvailableItems');\n }\n}\nfunction compareComplexValues(valueA, valueB, context) {\n if (!(0, util_1.isObject)(valueA) || !(0, util_1.isObject)(valueB)) {\n return false;\n }\n try {\n // TODO: we need to have normalized values here at this moment, otherwise\n // this won't work\n return JSON.stringify(valueA) === JSON.stringify(valueB);\n }\n catch (err) {\n throw new error_1.ProcessorError(`Error while comparing available values: ${err}`, context, 'validate:validateAvailableItems');\n }\n}\nconst validateAvailableItems = (context) => __awaiter(void 0, void 0, void 0, function* () {\n const { component, value } = context;\n const error = new error_1.FieldError('invalidOption', context, 'onlyAvailableItems');\n try {\n if (isValidatableRadioComponent(component)) {\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return null;\n }\n const values = component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => optionValue === value) !== -1\n ? null\n : error;\n }\n return null;\n }\n else if (isValidateableSelectComponent(component)) {\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return null;\n }\n const values = yield getAvailableSelectValues(component, context);\n if (values) {\n if ((0, util_1.isObject)(value)) {\n return values.find((optionValue) => compareComplexValues(optionValue, value, context)) !==\n undefined\n ? null\n : error;\n }\n return values.find((optionValue) => optionValue === value) !== undefined ? null : error;\n }\n }\n }\n catch (err) {\n throw new error_1.ProcessorError(err.message || err, context, 'validate:validateAvailableItems');\n }\n return null;\n});\nexports.validateAvailableItems = validateAvailableItems;\nconst shouldValidate = (context) => {\n const { component, value } = context;\n if (value == null || (0, lodash_1.isEmpty)(value)) {\n return false;\n }\n if (isValidatableRadioComponent(component)) {\n return true;\n }\n if (isValidateableSelectComponent(component)) {\n return true;\n }\n return false;\n};\nexports.shouldValidate = shouldValidate;\nconst validateAvailableItemsSync = (context) => {\n const { component, value } = context;\n const error = new error_1.FieldError('invalidOption', context, 'onlyAvailableItems');\n try {\n if (!(0, exports.shouldValidate)(context)) {\n return null;\n }\n if (isValidatableRadioComponent(component)) {\n const values = component.values;\n if (values) {\n return values.findIndex(({ value: optionValue }) => optionValue === value) !== -1\n ? null\n : error;\n }\n return null;\n }\n else if (isValidateableSelectComponent(component)) {\n const values = getAvailableSelectValuesSync(component, context);\n if (values) {\n if ((0, util_1.isObject)(value)) {\n return values.find((optionValue) => compareComplexValues(optionValue, value, context)) !==\n undefined\n ? null\n : error;\n }\n return values.find((optionValue) => optionValue === value) !== undefined ? null : error;\n }\n }\n }\n catch (err) {\n throw new error_1.ProcessorError(err.message || err, context, 'validate:validateAvailableItems');\n }\n return null;\n};\nexports.validateAvailableItemsSync = validateAvailableItemsSync;\nexports.validateAvailableItemsInfo = {\n name: 'validateAvailableItems',\n process: exports.validateAvailableItems,\n processSync: exports.validateAvailableItemsSync,\n shouldProcess: exports.shouldValidate\n};\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/process/validation/rules/validateAvailableItems.js?");
|
644
644
|
|
645
645
|
/***/ }),
|
646
646
|
|
@@ -893,7 +893,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument
|
|
893
893
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
894
894
|
|
895
895
|
"use strict";
|
896
|
-
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.validateRequiredDayInfo = exports.validateRequiredDaySync = exports.validateRequiredDay = exports.shouldValidate = void 0;\nconst error_1 = __webpack_require__(/*! ../../../error */ \"./node_modules/@formio/core/lib/error/index.js\");\nconst isValidatableDayComponent = (component) => {\n return (component &&\n component.type === 'day' &&\n component.fields.day
|
896
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.validateRequiredDayInfo = exports.validateRequiredDaySync = exports.validateRequiredDay = exports.shouldValidate = void 0;\nconst error_1 = __webpack_require__(/*! ../../../error */ \"./node_modules/@formio/core/lib/error/index.js\");\nconst isValidatableDayComponent = (component) => {\n var _a, _b, _c, _d, _e, _f;\n return (component &&\n component.type === 'day' &&\n (((_b = (_a = component.fields) === null || _a === void 0 ? void 0 : _a.day) === null || _b === void 0 ? void 0 : _b.required) || ((_d = (_c = component.fields) === null || _c === void 0 ? void 0 : _c.month) === null || _d === void 0 ? void 0 : _d.required) || ((_f = (_e = component.fields) === null || _e === void 0 ? void 0 : _e.year) === null || _f === void 0 ? void 0 : _f.required)));\n};\nconst shouldValidate = (context) => {\n const { component } = context;\n return isValidatableDayComponent(component);\n};\nexports.shouldValidate = shouldValidate;\nconst validateRequiredDay = (context) => __awaiter(void 0, void 0, void 0, function* () {\n return (0, exports.validateRequiredDaySync)(context);\n});\nexports.validateRequiredDay = validateRequiredDay;\nconst validateRequiredDaySync = (context) => {\n var _a, _b, _c, _d, _e, _f;\n const { component, value } = context;\n if (!(0, exports.shouldValidate)(context)) {\n return null;\n }\n if (!isValidatableDayComponent(component)) {\n return null;\n }\n if (!value) {\n return new error_1.FieldError('requiredDayEmpty', context, 'day');\n }\n if (typeof value !== 'string') {\n throw new error_1.ProcessorError(`Cannot validate required day field of ${value} because it is not a string`, context, 'validate:validateRequiredDay');\n }\n const [DAY, MONTH, YEAR] = (component).dayFirst ? [0, 1, 2] : [1, 0, 2];\n const values = value.split('/').map((x) => parseInt(x, 10)), day = values[DAY], month = values[MONTH], year = values[YEAR];\n if (!day && ((_b = (_a = component.fields) === null || _a === void 0 ? void 0 : _a.day) === null || _b === void 0 ? void 0 : _b.required)) {\n return new error_1.FieldError('requiredDayField', context, 'day');\n }\n if (!month && ((_d = (_c = component.fields) === null || _c === void 0 ? void 0 : _c.month) === null || _d === void 0 ? void 0 : _d.required)) {\n return new error_1.FieldError('requiredMonthField', context, 'day');\n }\n if (!year && ((_f = (_e = component.fields) === null || _e === void 0 ? void 0 : _e.year) === null || _f === void 0 ? void 0 : _f.required)) {\n return new error_1.FieldError('requiredYearField', context, 'day');\n }\n return null;\n};\nexports.validateRequiredDaySync = validateRequiredDaySync;\nexports.validateRequiredDayInfo = {\n name: 'validateRequiredDay',\n process: exports.validateRequiredDay,\n processSync: exports.validateRequiredDaySync,\n shouldProcess: exports.shouldValidate,\n};\n\n\n//# sourceURL=webpack://Formio/./node_modules/@formio/core/lib/process/validation/rules/validateRequiredDay.js?");
|
897
897
|
|
898
898
|
/***/ }),
|
899
899
|
|
@@ -5524,7 +5524,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5524
5524
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5525
5525
|
|
5526
5526
|
"use strict";
|
5527
|
-
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 compare_versions_1 = __webpack_require__(/*! compare-versions */ \"./node_modules/compare-versions/lib/esm/index.js\");\nconst EventEmitter_1 = __importDefault(__webpack_require__(/*! ./EventEmitter */ \"./lib/cjs/EventEmitter.js\"));\nconst i18n_1 = __importDefault(__webpack_require__(/*! ./i18n */ \"./lib/cjs/i18n.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst Components_1 = __importDefault(__webpack_require__(/*! ./components/Components */ \"./lib/cjs/components/Components.js\"));\nconst NestedDataComponent_1 = __importDefault(__webpack_require__(/*! ./components/_classes/nesteddata/NestedDataComponent */ \"./lib/cjs/components/_classes/nesteddata/NestedDataComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst formUtils_1 = __webpack_require__(/*! ./utils/formUtils */ \"./lib/cjs/utils/formUtils.js\");\nconst dragula_1 = __importDefault(__webpack_require__(/*! dragula */ \"./node_modules/dragula/dragula.js\"));\n// Initialize the available forms.\nFormio_1.Formio.forms = {};\n// Allow people to register components.\nFormio_1.Formio.registerComponent = Components_1.default.setComponent;\n/**\n *\n * @param {any} icons - The icons to use.\n * @returns {any} - The icon set.\n */\nfunction getIconSet(icons) {\n if (icons === \"fontawesome\") {\n return \"fa\";\n }\n return icons || \"\";\n}\n/**\n *\n * @param {any} options - The options to get.\n * @returns {any} - The options.\n */\nfunction getOptions(options) {\n options = lodash_1.default.defaults(options, {\n submitOnEnter: false,\n iconset: getIconSet(options && options.icons ? options.icons : Formio_1.Formio.icons),\n i18next: null,\n saveDraft: false,\n alwaysDirty: false,\n saveDraftThrottle: 5000,\n display: \"form\",\n cdnUrl: Formio_1.Formio.cdn.baseUrl,\n });\n if (!options.events) {\n options.events = new EventEmitter_1.default();\n }\n return options;\n}\n/**\n * Represents a JSON value.\n * @typedef {(string | number | boolean | null | JSONArray | JSONObject)} JSON\n */\n/**\n * Represents a JSON array.\n * @typedef {Array<JSON>} JSONArray\n */\n/**\n * Represents a JSON object.\n * @typedef {{[key: string]: JSON}} JSONObject\n */\n/**\n * @typedef {object} FormioHooks\n * @property {Function} [beforeSubmit] - A function that is called before the form is submitted.\n * @property {Function} [beforeCancel] - A function that is called before the form is canceled.\n * @property {Function} [beforeNext] - A function that is called before moving to the next page in a multi-page form.\n * @property {Function} [beforePrev] - A function that is called before moving to the previous page in a multi-page form.\n * @property {Function} [attachComponent] - A function that is called when a component is attached to the form.\n * @property {Function} [setDataValue] - A function that is called when setting the value of a data component.\n * @property {Function} [addComponents] - A function that is called when adding multiple components to the form.\n * @property {Function} [addComponent] - A function that is called when adding a single component to the form.\n * @property {Function} [customValidation] - A function that is called for custom validation of the form.\n * @property {Function} [attachWebform] - A function that is called when attaching a webform to the form.\n */\n/**\n * @typedef {object} SanitizeConfig\n * @property {string[]} [addAttr] - The attributes to add.\n * @property {string[]} [addTags] - The tags to add.\n * @property {string[]} [allowedAttrs] - The allowed attributes.\n * @property {string[]} [allowedTags] - The allowed tags.\n * @property {string[]} [allowedUriRegex] - The allowed URI regex.\n * @property {string[]} [addUriSafeAttr] - The URI safe attributes.\n */\n/**\n * @typedef {object} ButtonSettings\n * @property {boolean} [showPrevious] - Show the \"Previous\" button.\n * @property {boolean} [showNext] - Show the \"Next\" button.\n * @property {boolean} [showCancel] - Show the \"Cancel\" button.\n * @property {boolean} [showSubmit] - Show the \"Submit\" button.\n */\n/**\n * @typedef {object} FormOptions\n * @property {boolean} [saveDraft] - Enable the save draft feature.\n * @property {number} [saveDraftThrottle] - The throttle for the save draft feature.\n * @property {boolean} [readOnly] - Set this form to readOnly.\n * @property {boolean} [noAlerts] - Disable the alerts dialog.\n * @property {{[key: string]: string}} [i18n] - The translation file for this rendering.\n * @property {string} [template] - Custom logic for creation of elements.\n * @property {boolean} [noDefaults] - Exclude default values from the settings.\n * @property {any} [fileService] - The file service for this form.\n * @property {EventEmitter} [events] - The EventEmitter for this form.\n * @property {string} [language] - The language to render this form in.\n * @property {{[key: string]: string}} [i18next] - The i18next configuration for this form.\n * @property {boolean} [viewAsHtml] - View the form as raw HTML.\n * @property {'form' | 'html' | 'flat' | 'builder' | 'pdf'} [renderMode] - The render mode for this form.\n * @property {boolean} [highlightErrors] - Highlight any errors on the form.\n * @property {string} [componentErrorClass] - The error class for components.\n * @property {any} [templates] - The templates for this form.\n * @property {string} [iconset] - The iconset for this form.\n * @property {import('@formio/core').Component[]} [components] - The components for this form.\n * @property {{[key: string]: boolean}} [disabled] - Disabled components for this form.\n * @property {boolean} [showHiddenFields] - Show hidden fields.\n * @property {{[key: string]: boolean}} [hide] - Hidden components for this form.\n * @property {{[key: string]: boolean}} [show] - Components to show for this form.\n * @property {Formio} [formio] - The Formio instance for this form.\n * @property {string} [decimalSeparator] - The decimal separator for this form.\n * @property {string} [thousandsSeparator] - The thousands separator for this form.\n * @property {FormioHooks} [hooks] - The hooks for this form.\n * @property {boolean} [alwaysDirty] - Always be dirty.\n * @property {boolean} [skipDraftRestore] - Skip restoring a draft.\n * @property {'form' | 'wizard' | 'pdf'} [display] - The display for this form.\n * @property {string} [cdnUrl] - The CDN url for this form.\n * @property {boolean} [flatten] - Flatten the form.\n * @property {boolean} [sanitize] - Sanitize the form.\n * @property {SanitizeConfig} [sanitizeConfig] - The sanitize configuration for this form.\n * @property {ButtonSettings} [buttonSettings] - The button settings for this form.\n * @property {object} [breadcrumbSettings] - The breadcrumb settings for this form.\n * @property {boolean} [allowPrevious] - Allow the previous button (for Wizard forms).\n * @property {string[]} [wizardButtonOrder] - The order of the buttons (for Wizard forms).\n * @property {boolean} [showCheckboxBackground] - Show the checkbox background.\n * @property {boolean} [inputsOnly] - Only show inputs in the form and no labels.\n * @property {boolean} [building] - If we are in the process of building the form.\n * @property {number} [zoom] - The zoom for PDF forms.\n */\nclass Webform extends NestedDataComponent_1.default {\n /**\n * Creates a new Form instance.\n * @param {HTMLElement | object | import('Form').FormOptions} [elementOrOptions] - The DOM element to render this form within or the options to create this form instance.\n * @param {import('Form').FormOptions} [options] - The options to create a new form instance.\n */\n constructor(elementOrOptions, options = undefined) {\n let element, formOptions;\n if (elementOrOptions instanceof HTMLElement || options) {\n element = elementOrOptions;\n formOptions = options || {};\n }\n else {\n formOptions = elementOrOptions || {};\n }\n super(null, getOptions(formOptions));\n this.executeShortcuts = (event) => {\n const { target } = event;\n if (!this.keyboardCatchableElement(target)) {\n return;\n }\n const ctrl = event.ctrlKey || event.metaKey;\n const keyCode = event.keyCode;\n let char = \"\";\n if (65 <= keyCode && keyCode <= 90) {\n char = String.fromCharCode(keyCode);\n }\n else if (keyCode === 13) {\n char = \"Enter\";\n }\n else if (keyCode === 27) {\n char = \"Esc\";\n }\n lodash_1.default.each(this.shortcuts, (shortcut) => {\n if (shortcut.ctrl && !ctrl) {\n return;\n }\n if (shortcut.shortcut === char) {\n shortcut.element.click();\n event.preventDefault();\n }\n });\n };\n this.setElement(element);\n // Keep track of all available forms globally.\n Formio_1.Formio.forms[this.id] = this;\n // Set the base url.\n if (this.options.baseUrl) {\n Formio_1.Formio.setBaseUrl(this.options.baseUrl);\n }\n /**\n * The type of this element.\n * @type {string}\n */\n this.type = \"form\";\n this._src = \"\";\n this._loading = false;\n this._form = {};\n this.draftEnabled = false;\n this.savingDraft = false;\n if (this.options.saveDraftThrottle) {\n this.triggerSaveDraft = lodash_1.default.throttle(this.saveDraft.bind(this), this.options.saveDraftThrottle);\n }\n else {\n this.triggerSaveDraft = this.saveDraft.bind(this);\n }\n /**\n * Determines if this form should submit the API on submit.\n * @type {boolean}\n */\n this.nosubmit = false;\n /**\n * Determines if the form has tried to be submitted, error or not.\n * @type {boolean}\n */\n this.submitted = false;\n /**\n * Determines if the form is being submitted at the moment.\n * @type {boolean}\n */\n this.submitting = false;\n /**\n * The Formio instance for this form.\n * @type {Formio}\n */\n this.formio = null;\n /**\n * The loader HTML element.\n * @type {HTMLElement}\n */\n this.loader = null;\n /**\n * The alert HTML element\n * @type {HTMLElement}\n */\n this.alert = null;\n /**\n * Promise that is triggered when the submission is done loading.\n * @type {Promise}\n */\n this.onSubmission = null;\n /**\n * Determines if this submission is explicitly set.\n * @type {boolean}\n */\n this.submissionSet = false;\n /**\n * Promise that executes when the form is ready and rendered.\n * @type {Promise}\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.formReady.then(() => {\n * console.log('The form is ready!');\n * });\n * form.src = 'https://examples.form.io/example';\n */\n this.formReady = new Promise((resolve, reject) => {\n /**\n * Called when the formReady state of this form has been resolved.\n * @type {Function}\n */\n this.formReadyResolve = resolve;\n /**\n * Called when this form could not load and is rejected.\n * @type {Function}\n */\n this.formReadyReject = reject;\n });\n /**\n * Promise that executes when the submission is ready and rendered.\n * @type {Promise}\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.submissionReady.then(() => {\n * console.log('The submission is ready!');\n * });\n * form.src = 'https://examples.form.io/example/submission/234234234234234243';\n */\n this.submissionReady = new Promise((resolve, reject) => {\n /**\n * Called when the formReady state of this form has been resolved.\n * @type {Function}\n */\n this.submissionReadyResolve = resolve;\n /**\n * Called when this form could not load and is rejected.\n * @type {Function}\n */\n this.submissionReadyReject = reject;\n });\n this.shortcuts = [];\n // Set language after everything is established.\n this.language = this.i18next.language;\n // See if we need to restore the draft from a user.\n if (this.options.saveDraft) {\n if (this.options.skipDraftRestore) {\n this.draftEnabled = true;\n this.savingDraft = false;\n }\n else {\n this.formReady.then(() => {\n const user = Formio_1.Formio.getUser();\n // Only restore a draft if the submission isn't explicitly set.\n if (user && !this.submissionSet) {\n this.restoreDraft(user._id);\n }\n });\n }\n }\n this.component.clearOnHide = false;\n // Ensure the root is set to this component.\n this.root = this;\n this.localRoot = this;\n this.root.dragulaLib = dragula_1.default;\n }\n /* eslint-enable max-statements */\n get language() {\n return this.options.language;\n }\n get emptyValue() {\n return null;\n }\n componentContext() {\n return this._data;\n }\n /**\n * Sets the language for this form.\n * @param {string} lang - The language to use (e.g. 'en', 'sp', etc.)\n */\n set language(lang) {\n if (!this.i18next) {\n return;\n }\n this.options.language = lang;\n if (this.i18next.language === lang) {\n return;\n }\n this.i18next.changeLanguage(lang, (err) => {\n if (err) {\n return;\n }\n this.rebuild();\n this.emit(\"languageChanged\");\n });\n }\n get componentComponents() {\n return this.form.components;\n }\n get shadowRoot() {\n return this.options.shadowRoot;\n }\n /**\n * Add a language for translations\n * @param {string} code - The language code for the language being added.\n * @param {object} lang - The language translations.\n * @param {boolean} [active] - If this language should be set as the active language.\n */\n addLanguage(code, lang, active = false) {\n if (this.i18next) {\n var translations = lodash_1.default.assign((0, utils_1.fastCloneDeep)(i18n_1.default.resources.en.translation), lang);\n this.i18next.addResourceBundle(code, \"translation\", translations, true, true);\n if (active) {\n this.language = code;\n }\n }\n }\n keyboardCatchableElement(element) {\n if (element.nodeName === \"TEXTAREA\") {\n return false;\n }\n if (element.nodeName === \"INPUT\") {\n return [\"text\", \"email\", \"password\"].indexOf(element.type) === -1;\n }\n return true;\n }\n addShortcut(element, shortcut) {\n if (!shortcut || !/^([A-Z]|Enter|Esc)$/i.test(shortcut)) {\n return;\n }\n shortcut = lodash_1.default.capitalize(shortcut);\n if (shortcut === \"Enter\" || shortcut === \"Esc\") {\n // Restrict Enter and Esc only for buttons\n if (element.tagName !== \"BUTTON\") {\n return;\n }\n this.shortcuts.push({\n shortcut,\n element,\n });\n }\n else {\n this.shortcuts.push({\n ctrl: true,\n shortcut,\n element,\n });\n }\n }\n removeShortcut(element, shortcut) {\n if (!shortcut || !/^([A-Z]|Enter|Esc)$/i.test(shortcut)) {\n return;\n }\n lodash_1.default.remove(this.shortcuts, {\n shortcut,\n element,\n });\n }\n /**\n * Get the embed source of the form.\n * @returns {string} - The source of the form.\n */\n get src() {\n return this._src;\n }\n /**\n * Loads the submission if applicable.\n * @returns {Promise} - The promise that is triggered when the submission is loaded.\n */\n loadSubmission() {\n this.loadingSubmission = true;\n if (this.formio.submissionId) {\n this.onSubmission = this.formio\n .loadSubmission()\n .then((submission) => this.setSubmission(submission), (err) => this.submissionReadyReject(err))\n .catch((err) => this.submissionReadyReject(err));\n }\n else {\n this.submissionReadyResolve();\n }\n return this.submissionReady;\n }\n /**\n * Set the src of the form renderer.\n * @param {string} value - The source value to set.\n * @param {any} options - The options to set.\n * @returns {Promise} - The promise that is triggered when the form is set.\n */\n setSrc(value, options) {\n if (this.setUrl(value, options)) {\n this.nosubmit = false;\n return this.formio\n .loadForm({ params: { live: 1 } })\n .then((form) => {\n const setForm = this.setForm(form);\n this.loadSubmission();\n return setForm;\n })\n .catch((err) => {\n console.warn(err);\n this.formReadyReject(err);\n });\n }\n return Promise.resolve();\n }\n /**\n * Set the Form source, which is typically the Form.io embed URL.\n * @param {string} value - The value of the form embed url.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.formReady.then(() => {\n * console.log('The form is formReady!');\n * });\n * form.src = 'https://examples.form.io/example';\n */\n set src(value) {\n this.setSrc(value);\n }\n /**\n * Get the embed source of the form.\n * @returns {string} - returns the source of the form.\n */\n get url() {\n return this._src;\n }\n /**\n * Sets the url of the form renderer.\n * @param {string} value - The value to set the url to.\n * @param {any} options - The options to set.\n * @returns {boolean} - TRUE means the url was set, FALSE otherwise.\n */\n setUrl(value, options) {\n if (!value || typeof value !== \"string\" || value === this._src) {\n return false;\n }\n this._src = value;\n this.nosubmit = true;\n this.formio = this.options.formio = new Formio_1.Formio(value, options);\n if (this.type === \"form\") {\n // Set the options source so this can be passed to other components.\n this.options.src = value;\n }\n return true;\n }\n /**\n * Set the form source but don't initialize the form and submission from the url.\n * @param {string} value - The value of the form embed url.\n */\n set url(value) {\n this.setUrl(value);\n }\n /**\n * Called when both the form and submission have been loaded.\n * @returns {Promise} - The promise to trigger when both form and submission have loaded.\n */\n get ready() {\n return this.formReady.then(() => {\n return super.ready.then(() => {\n return this.loadingSubmission ? this.submissionReady : true;\n });\n });\n }\n /**\n * Returns if this form is loading.\n * @returns {boolean} - TRUE means the form is loading, FALSE otherwise.\n */\n get loading() {\n return this._loading;\n }\n /**\n * Set the loading state for this form, and also show the loader spinner.\n * @param {boolean} loading - If this form should be \"loading\" or not.\n */\n set loading(loading) {\n if (this._loading !== loading) {\n this._loading = loading;\n if (!this.loader && loading) {\n this.loader = this.ce(\"div\", {\n class: \"loader-wrapper\",\n });\n const spinner = this.ce(\"div\", {\n class: \"loader text-center\",\n });\n this.loader.appendChild(spinner);\n }\n /* eslint-disable max-depth */\n if (this.loader) {\n try {\n if (loading) {\n this.prependTo(this.loader, this.wrapper);\n }\n else {\n this.removeChildFrom(this.loader, this.wrapper);\n }\n }\n catch (err) {\n // ingore\n }\n }\n /* eslint-enable max-depth */\n }\n }\n /**\n * Sets the JSON schema for the form to be rendered.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.setForm({\n * components: [\n * {\n * type: 'textfield',\n * key: 'firstName',\n * label: 'First Name',\n * placeholder: 'Enter your first name.',\n * input: true\n * },\n * {\n * type: 'textfield',\n * key: 'lastName',\n * label: 'Last Name',\n * placeholder: 'Enter your last name',\n * input: true\n * },\n * {\n * type: 'button',\n * action: 'submit',\n * label: 'Submit',\n * theme: 'primary'\n * }\n * ]\n * });\n * @param {object} form - The JSON schema of the form @see https://examples.form.io/example for an example JSON schema.\n * @param {any} flags - Any flags to apply when setting the form.\n * @returns {Promise} - The promise that is triggered when the form is set.\n */\n setForm(form, flags = {}) {\n var _a, _b, _c;\n const isFormAlreadySet = this._form && ((_a = this._form.components) === null || _a === void 0 ? void 0 : _a.length);\n try {\n // Do not set the form again if it has been already set\n if (isFormAlreadySet && JSON.stringify(this._form) === JSON.stringify(form)) {\n return Promise.resolve();\n }\n // Create the form.\n this._form = (flags === null || flags === void 0 ? void 0 : flags.keepAsReference) ? form : lodash_1.default.cloneDeep(form);\n if (this.onSetForm) {\n this.onSetForm(lodash_1.default.cloneDeep(this._form), form);\n }\n if ((_c = (_b = this.parent) === null || _b === void 0 ? void 0 : _b.component) === null || _c === void 0 ? void 0 : _c.modalEdit) {\n return Promise.resolve();\n }\n }\n catch (err) {\n console.warn(err);\n // If provided form is not a valid JSON object, do not set it too\n return Promise.resolve();\n }\n // Allow the form to provide component overrides.\n if (form && form.settings && form.settings.components) {\n this.options.components = form.settings.components;\n }\n if (form && form.properties) {\n this.options.properties = form.properties;\n }\n // Use the sanitize config from the form settings or the global sanitize config if it is not provided in the options\n if (!this.options.sanitizeConfig && !this.builderMode) {\n this.options.sanitizeConfig =\n lodash_1.default.get(form, \"settings.sanitizeConfig\") ||\n lodash_1.default.get(form, \"globalSettings.sanitizeConfig\");\n }\n if (\"schema\" in form && (0, compare_versions_1.compareVersions)(form.schema, \"1.x\") > 0) {\n this.ready.then(() => {\n this.setAlert(\"alert alert-danger\", \"Form schema is for a newer version, please upgrade your renderer. Some functionality may not work.\");\n });\n }\n // See if they pass a module, and evaluate it if so.\n if (form && form.module) {\n let formModule = null;\n if (typeof form.module === \"string\") {\n try {\n formModule = this.evaluate(`return ${form.module}`);\n }\n catch (err) {\n console.warn(err);\n }\n }\n else {\n formModule = form.module;\n }\n if (formModule) {\n Formio_1.Formio.use(formModule);\n // Since we got here after instantiation, we need to manually apply form options.\n if (formModule.options && formModule.options.form) {\n this.options = Object.assign(this.options, formModule.options.form);\n }\n }\n }\n this.initialized = false;\n const rebuild = this.rebuild() || Promise.resolve();\n return rebuild.then(() => {\n this.emit(\"formLoad\", form);\n this.triggerCaptcha();\n // Make sure to trigger onChange after a render event occurs to speed up form rendering.\n setTimeout(() => {\n this.onChange(flags);\n this.formReadyResolve();\n }, 0);\n return this.formReady;\n });\n }\n /**\n * Gets the form object.\n * @returns {object} - The form JSON schema.\n */\n get form() {\n if (!this._form) {\n this._form = {\n components: [],\n };\n }\n return this._form;\n }\n /**\n * Sets the form value.\n * @alias setForm\n * @param {object} form - The form schema object.\n */\n set form(form) {\n this.setForm(form);\n }\n /**\n * Returns the submission object that was set within this form.\n * @returns {object} - The submission object.\n */\n get submission() {\n return this.getValue();\n }\n /**\n * Sets the submission of a form.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.src = 'https://examples.form.io/example';\n * form.submission = {data: {\n * firstName: 'Joe',\n * lastName: 'Smith',\n * email: 'joe@example.com'\n * }};\n * @param {object} submission - The Form.io submission object.\n */\n set submission(submission) {\n this.setSubmission(submission);\n }\n /**\n * Sets a submission and returns the promise when it is ready.\n * @param {any} submission - The submission to set.\n * @param {any} flags - Any flags to apply when setting the submission.\n * @returns {Promise} - The promise that is triggered when the submission is set.\n */\n setSubmission(submission, flags = {}) {\n flags = Object.assign(Object.assign({}, flags), { fromSubmission: lodash_1.default.has(flags, \"fromSubmission\") ? flags.fromSubmission : true });\n return (this.onSubmission = this.formReady\n .then((resolveFlags) => {\n if (resolveFlags) {\n flags = Object.assign(Object.assign({}, flags), resolveFlags);\n }\n this.submissionSet = true;\n this.triggerChange(flags);\n this.emit(\"beforeSetSubmission\", submission);\n this.setValue(submission, flags);\n return this.submissionReadyResolve(submission);\n }, (err) => this.submissionReadyReject(err))\n .catch((err) => this.submissionReadyReject(err)));\n }\n handleDraftError(errName, errDetails, restoreDraft) {\n const errorMessage = lodash_1.default.trim(`${this.t(errName)} ${errDetails || \"\"}`);\n console.warn(errorMessage);\n this.emit(restoreDraft ? \"restoreDraftError\" : \"saveDraftError\", errDetails || errorMessage);\n }\n saveDraft() {\n if (!this.draftEnabled) {\n return;\n }\n if (!this.formio) {\n this.handleDraftError(\"saveDraftInstanceError\");\n return;\n }\n if (!Formio_1.Formio.getUser()) {\n this.handleDraftError(\"saveDraftAuthError\");\n return;\n }\n const draft = (0, utils_1.fastCloneDeep)(this.submission);\n draft.state = \"draft\";\n if (!this.savingDraft && !this.submitting) {\n this.emit(\"saveDraftBegin\");\n this.savingDraft = true;\n this.formio\n .saveSubmission(draft)\n .then((sub) => {\n // Set id to submission to avoid creating new draft submission\n this.submission._id = sub._id;\n this.savingDraft = false;\n this.emit(\"saveDraft\", sub);\n })\n .catch((err) => {\n this.savingDraft = false;\n this.handleDraftError(\"saveDraftError\", err);\n });\n }\n }\n /**\n * Restores a draft submission based on the user who is authenticated.\n * @param {string} userId - The user id where we need to restore the draft from.\n */\n restoreDraft(userId) {\n const formio = this.formio || this.options.formio;\n if (!formio) {\n this.handleDraftError(\"restoreDraftInstanceError\", null, true);\n return;\n }\n this.savingDraft = true;\n formio\n .loadSubmissions({\n params: {\n state: 'draft',\n owner: userId,\n sort: '-created'\n },\n })\n .then((submissions) => {\n if (submissions.length > 0 && !this.options.skipDraftRestore) {\n const draft = (0, utils_1.fastCloneDeep)(submissions[0]);\n return this.setSubmission(draft).then(() => {\n this.draftEnabled = true;\n this.savingDraft = false;\n this.emit(\"restoreDraft\", draft);\n });\n }\n // Enable drafts so that we can keep track of changes.\n this.draftEnabled = true;\n this.savingDraft = false;\n this.emit(\"restoreDraft\", null);\n })\n .catch((err) => {\n this.draftEnabled = true;\n this.savingDraft = false;\n this.handleDraftError(\"restoreDraftError\", err, true);\n });\n }\n get schema() {\n const schema = (0, utils_1.fastCloneDeep)(lodash_1.default.omit(this._form, [\"components\"]));\n schema.components = [];\n this.eachComponent((component) => schema.components.push(component.schema));\n return schema;\n }\n mergeData(_this, _that) {\n lodash_1.default.mergeWith(_this, _that, (thisValue, thatValue) => {\n if (Array.isArray(thisValue) &&\n Array.isArray(thatValue) &&\n thisValue.length !== thatValue.length) {\n return thatValue;\n }\n });\n }\n setValue(submission, flags = {}) {\n if (!submission || !submission.data) {\n submission = {\n data: {},\n metadata: submission.metadata,\n };\n }\n // Metadata needs to be available before setValue\n this._submission.metadata = submission.metadata ? lodash_1.default.cloneDeep(submission.metadata) : {};\n this.editing = !!submission._id;\n // Set the timezone in the options if available.\n if (!this.options.submissionTimezone &&\n submission.metadata &&\n submission.metadata.timezone) {\n this.options.submissionTimezone = submission.metadata.timezone;\n }\n const changed = super.setValue(submission.data, flags);\n if (!flags.sanitize) {\n this.mergeData(this.data, submission.data);\n }\n submission.data = this.data;\n this._submission = submission;\n return changed;\n }\n getValue() {\n if (!this._submission.data) {\n this._submission.data = {};\n }\n if (this.viewOnly) {\n return this._submission;\n }\n const submission = this._submission;\n submission.data = this.data;\n return this._submission;\n }\n /**\n * Build the form.\n * @returns {Promise} - The promise that is triggered when the form is built.\n */\n init() {\n if (this.options.submission) {\n const submission = lodash_1.default.extend({}, this.options.submission);\n this._submission = submission;\n this._data = submission.data;\n }\n else {\n this._submission = this._submission || { data: {} };\n }\n // Remove any existing components.\n if (this.components && this.components.length) {\n this.destroyComponents();\n this.components = [];\n }\n if (this.component) {\n this.component.components = this.form ? this.form.components : [];\n }\n else {\n this.component = this.form;\n }\n this.component.type = \"form\";\n this.component.input = false;\n this.addComponents();\n this.on(\"submitButton\", (options) => {\n this.submit(false, options).catch((e) => {\n options.instance.loading = false;\n return e !== false && e !== undefined && console.log(e);\n });\n }, true);\n this.on(\"checkValidity\", (data) => this.validate(data, { dirty: true, process: \"change\" }), true);\n this.on(\"requestUrl\", (args) => this.submitUrl(args.url, args.headers), true);\n this.on(\"resetForm\", () => this.resetValue(), true);\n this.on(\"deleteSubmission\", () => this.deleteSubmission(), true);\n this.on(\"refreshData\", () => this.updateValue(), true);\n this.executeFormController();\n return this.formReady;\n }\n executeFormController() {\n // If no controller value or\n // hidden and set to clearOnHide (Don't calculate a value for a hidden field set to clear when hidden)\n if (!this.form ||\n !this.form.controller ||\n ((!this.visible || this.component.hidden) &&\n this.component.clearOnHide &&\n !this.rootPristine)) {\n return false;\n }\n this.formReady.then(() => {\n this.evaluate(this.form.controller, {\n components: this.components,\n instance: this,\n });\n });\n }\n /**\n *\n */\n teardown() {\n this.emit(\"formDelete\", this.id);\n delete Formio_1.Formio.forms[this.id];\n delete this.executeShortcuts;\n delete this.triggerSaveDraft;\n super.teardown();\n }\n destroy(all = false) {\n this.off(\"submitButton\");\n this.off(\"checkValidity\");\n this.off(\"requestUrl\");\n this.off(\"resetForm\");\n this.off(\"deleteSubmission\");\n this.off(\"refreshData\");\n return super.destroy(all);\n }\n build(element) {\n if (element || this.element) {\n return this.ready.then(() => {\n element = element || this.element;\n super.build(element);\n });\n }\n return this.ready;\n }\n getClassName() {\n let classes = \"formio-form\";\n if (this.options.readOnly) {\n classes += \" formio-read-only\";\n }\n return classes;\n }\n render() {\n return super.render(this.renderTemplate(\"webform\", {\n classes: this.getClassName(),\n children: this.renderComponents(),\n }), this.builderMode ? \"builder\" : \"form\", true);\n }\n redraw() {\n // Don't bother if we have not built yet.\n if (!this.element) {\n return Promise.resolve();\n }\n this.clear();\n this.setContent(this.element, this.render());\n return this.attach(this.element);\n }\n attach(element) {\n this.setElement(element);\n this.loadRefs(element, { webform: \"single\" });\n const childPromise = this.attachComponents(this.refs.webform);\n this.addEventListener(document, \"keydown\", this.executeShortcuts);\n this.currentForm = this;\n this.hook(\"attachWebform\", element, this);\n return childPromise.then(() => {\n this.emit(\"render\", this.element);\n return this.setValue(this._submission, {\n noUpdateEvent: true,\n });\n });\n }\n hasRequiredFields() {\n let result = false;\n (0, formUtils_1.eachComponent)(this.form.components, (component) => {\n if (component.validate.required) {\n result = true;\n return true;\n }\n }, true);\n return result;\n }\n resetValue() {\n lodash_1.default.each(this.getComponents(), (comp) => comp.resetValue());\n this.setPristine(true);\n this.onChange({ resetValue: true });\n }\n /**\n * Sets a new alert to display in the error dialog of the form.\n * @param {string} type - The type of alert to display. \"danger\", \"success\", \"warning\", etc.\n * @param {string} message - The message to show in the alert.\n * @param {object} options - The options for the alert.\n */\n setAlert(type, message, options) {\n if (!type && this.submitted) {\n if (this.alert) {\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.removeEventListener(el, \"click\");\n this.removeEventListener(el, \"keypress\");\n });\n }\n this.removeChild(this.alert);\n this.alert = null;\n }\n return;\n }\n if (this.options.noAlerts) {\n if (!message) {\n this.emit(\"error\", false);\n }\n return;\n }\n if (this.alert) {\n try {\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.removeEventListener(el, \"click\");\n this.removeEventListener(el, \"keypress\");\n });\n }\n this.removeChild(this.alert);\n this.alert = null;\n }\n catch (err) {\n // ignore\n }\n }\n if (message) {\n const attrs = {\n class: (options && options.classes) || `alert alert-${type}`,\n id: `error-list-${this.id}`,\n };\n const templateOptions = {\n message: message instanceof HTMLElement ? message.outerHTML : message,\n attrs: attrs,\n type,\n };\n this.alert = (0, utils_1.convertStringToHTMLElement)(this.renderTemplate(\"alert\", templateOptions), `#${attrs.id}`);\n }\n if (!this.alert) {\n return;\n }\n this.loadRefs(this.alert, { errorRef: \"multiple\" });\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.addEventListener(el, \"click\", (e) => {\n const key = e.currentTarget.dataset.componentKey;\n this.focusOnComponent(key);\n });\n this.addEventListener(el, \"keydown\", (e) => {\n if (e.keyCode === 13) {\n e.preventDefault();\n const key = e.currentTarget.dataset.componentKey;\n this.focusOnComponent(key);\n }\n });\n });\n }\n this.prepend(this.alert);\n }\n /**\n * Focus on selected component.\n * @param {string} key - The key of selected component.\n */\n focusOnComponent(key) {\n if (key) {\n const component = this.getComponent(key);\n if (component) {\n component.focus();\n }\n }\n }\n /**\n * Show the errors of this form within the alert dialog.\n * @param {object} error - An optional additional error to display along with the component errors.\n * @returns {*}\n */\n /* eslint-disable no-unused-vars */\n /**\n *\n * @param {Array} errors - An array of errors to display.\n * @param {boolean} triggerEvent - Whether or not to trigger the error event.\n * @returns {void|Array} - The errors that were set.\n */\n showErrors(errors, triggerEvent) {\n this.loading = false;\n if (!Array.isArray(errors)) {\n errors = [errors];\n }\n errors = errors.concat(this.customErrors).filter((err) => !!err);\n if (!errors.length) {\n this.setAlert(false);\n return;\n }\n // Mark any components as invalid if in a custom message.\n errors.forEach((err) => {\n const { components = [] } = err;\n if (err.component) {\n components.push(err.component);\n }\n if (err.path) {\n components.push(err.path);\n }\n components.forEach((path) => {\n const originalPath = (0, utils_1.getStringFromComponentPath)(path);\n const component = this.getComponent(path, lodash_1.default.identity, originalPath);\n if (err.fromServer) {\n if (component.serverErrors) {\n component.serverErrors.push(err);\n }\n else {\n component.serverErrors = [err];\n }\n }\n const components = lodash_1.default.compact(Array.isArray(component) ? component : [component]);\n components.forEach((component) => component.setCustomValidity(err.message, true));\n });\n });\n const displayedErrors = [];\n if (errors.length) {\n errors = lodash_1.default.uniqBy(errors, (error) => error.message);\n const createListItem = (message, index) => {\n var _a, _b, _c;\n const err = errors[index];\n const messageFromIndex = !lodash_1.default.isUndefined(index) && errors && errors[index];\n const keyOrPath = (messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.formattedKeyOrPath) ||\n (messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.path) ||\n ((_a = messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.context) === null || _a === void 0 ? void 0 : _a.path) ||\n (((_b = err.context) === null || _b === void 0 ? void 0 : _b.component) && ((_c = err.context) === null || _c === void 0 ? void 0 : _c.component.key)) ||\n (err.component && err.component.key) ||\n (err.fromServer && err.path);\n const formattedKeyOrPath = keyOrPath ? (0, utils_1.getStringFromComponentPath)(keyOrPath) : \"\";\n if (typeof err !== \"string\" && !err.formattedKeyOrPath) {\n err.formattedKeyOrPath = formattedKeyOrPath;\n }\n return {\n message: (0, utils_1.unescapeHTML)(message),\n keyOrPath: formattedKeyOrPath,\n };\n };\n errors.forEach(({ message, context, fromServer, component }, index) => {\n const text = !(component === null || component === void 0 ? void 0 : component.label) || (context === null || context === void 0 ? void 0 : context.hasLabel) || fromServer\n ? this.t(\"alertMessage\", { message: this.t(message) })\n : this.t(\"alertMessageWithLabel\", {\n label: this.t(component === null || component === void 0 ? void 0 : component.label),\n message: this.t(message),\n });\n displayedErrors.push(createListItem(text, index));\n });\n }\n const errorsList = this.renderTemplate(\"errorsList\", { errors: displayedErrors });\n this.root.setAlert(\"danger\", errorsList);\n if (triggerEvent) {\n this.emit(\"error\", errors);\n }\n return errors;\n }\n /* eslint-enable no-unused-vars */\n /**\n * Called when the submission has completed, or if the submission needs to be sent to an external library.\n * @param {object} submission - The submission object.\n * @param {boolean} saved - Whether or not this submission was saved to the server.\n * @returns {object} - The submission object.\n */\n onSubmit(submission, saved) {\n var _a;\n this.loading = false;\n this.submitting = false;\n this.setPristine(true);\n // We want to return the submitted submission and setValue will mutate the submission so cloneDeep it here.\n this.setValue((0, utils_1.fastCloneDeep)(submission), {\n noValidate: true,\n noCheck: true,\n });\n this.setAlert(\"success\", `<p>${this.t(\"complete\")}</p>`);\n // Cancel triggered saveDraft to prevent overriding the submitted state\n if (this.draftEnabled && ((_a = this.triggerSaveDraft) === null || _a === void 0 ? void 0 : _a.cancel)) {\n this.triggerSaveDraft.cancel();\n }\n this.emit(\"submit\", submission, saved);\n if (saved) {\n this.emit(\"submitDone\", submission);\n }\n return submission;\n }\n normalizeError(error) {\n if (error) {\n if (typeof error === \"object\" && \"details\" in error) {\n error = error.details;\n }\n if (typeof error === \"string\") {\n error = { message: error };\n }\n }\n return error;\n }\n /**\n * Called when an error occurs during the submission.\n * @param {object} error - The error that occured.\n * @returns {Array} errors - All errors.\n */\n onSubmissionError(error) {\n error = this.normalizeError(error);\n this.submitting = false;\n this.setPristine(false);\n this.emit(\"submitError\", error || this.errors);\n // Allow for silent cancellations (no error message, no submit button error state)\n if (error && error.silent) {\n this.emit(\"change\", { isValid: true }, { silent: true });\n return false;\n }\n const errors = this.showErrors(error, true);\n if (this.root && this.root.alert) {\n this.scrollIntoView(this.root.alert);\n }\n return errors;\n }\n /**\n * Trigger the change event for this form.\n * @param {any} flags - The flags to set on this change event.\n * @param {any} changed - The changed object which reflects the changes in the form.\n * @param {boolean} modified - Whether or not the form has been modified.\n * @param {any} changes - The changes that have occured in the form.\n */\n onChange(flags, changed, modified, changes) {\n flags = flags || {};\n let isChangeEventEmitted = false;\n super.onChange(flags, true);\n const value = lodash_1.default.clone(this.submission);\n flags.changed = value.changed = changed;\n flags.changes = changes;\n if (modified && this.pristine) {\n this.pristine = false;\n }\n this.checkData(value.data, flags);\n const shouldValidate = !flags.noValidate ||\n flags.fromIFrame ||\n (flags.fromSubmission && this.rootPristine && this.pristine && flags.changed);\n const errors = shouldValidate\n ? this.validate(value.data, Object.assign(Object.assign({}, flags), { process: \"change\" }))\n : [];\n value.isValid = errors.length === 0;\n this.loading = false;\n if (this.submitted) {\n // show server errors while they are not cleaned/fixed\n const nonComponentServerErrors = lodash_1.default.filter(this.serverErrors || [], (err) => !err.component && !err.path);\n this.showErrors(nonComponentServerErrors.length ? nonComponentServerErrors : errors);\n }\n // See if we need to save the draft of the form.\n if (modified && this.options.saveDraft) {\n this.triggerSaveDraft();\n }\n if (!flags || !flags.noEmit) {\n this.emit(\"change\", value, flags, modified);\n isChangeEventEmitted = true;\n }\n // The form is initialized after the first change event occurs.\n if (isChangeEventEmitted && !this.initialized) {\n this.emit(\"initialized\");\n this.initialized = true;\n }\n }\n /**\n * Send a delete request to the server.\n * @returns {Promise} - The promise that is triggered when the delete is complete.\n */\n deleteSubmission() {\n return this.formio.deleteSubmission().then(() => {\n this.emit(\"submissionDeleted\", this.submission);\n this.resetValue();\n });\n }\n /**\n * Cancels the submission.\n * @param {boolean} noconfirm - Whether or not to confirm the cancellation.\n * @alias reset\n * @returns {boolean} - TRUE means the submission was cancelled, FALSE otherwise.\n */\n cancel(noconfirm) {\n const shouldReset = this.hook(\"beforeCancel\", true);\n if (shouldReset && (noconfirm || confirm(this.t(\"confirmCancel\")))) {\n this.resetValue();\n return true;\n }\n else {\n this.emit(\"cancelSubmit\");\n return false;\n }\n }\n setMetadata(submission) {\n // Add in metadata about client submitting the form\n submission.metadata = submission.metadata || {};\n lodash_1.default.defaults(submission.metadata, {\n timezone: lodash_1.default.get(this, \"_submission.metadata.timezone\", (0, utils_1.currentTimezone)()),\n offset: parseInt(lodash_1.default.get(this, \"_submission.metadata.offset\", (0, moment_1.default)().utcOffset()), 10),\n origin: document.location.origin,\n referrer: document.referrer,\n browserName: navigator.appName,\n userAgent: navigator.userAgent,\n pathName: window.location.pathname,\n onLine: navigator.onLine,\n });\n }\n submitForm(options = {}) {\n this.clearServerErrors();\n return new Promise((resolve, reject) => {\n // Read-only forms should never submit.\n if (this.options.readOnly) {\n return resolve({\n submission: this.submission,\n saved: false,\n });\n }\n const submission = (0, utils_1.fastCloneDeep)(this.submission || {});\n this.setMetadata(submission);\n submission.state = options.state || submission.state || \"submitted\";\n const isDraft = submission.state === \"draft\";\n this.hook(\"beforeSubmit\", Object.assign(Object.assign({}, submission), { component: options.component }), (err, data) => {\n var _a;\n if (err) {\n return reject(err);\n }\n submission._vnote = data && data._vnote ? data._vnote : \"\";\n try {\n if (!isDraft && !options.noValidate) {\n if (!submission.data) {\n return reject(\"Invalid Submission\");\n }\n const errors = this.validate(submission.data, {\n dirty: true,\n silentCheck: false,\n process: \"submit\",\n });\n if (errors.length ||\n ((_a = options.beforeSubmitResults) === null || _a === void 0 ? void 0 : _a.some((result) => result.status === \"rejected\"))) {\n return reject(errors);\n }\n }\n }\n catch (err) {\n console.error(err);\n }\n this.everyComponent((comp) => {\n if (submission._vnote && comp.type === \"form\" && comp.component.reference) {\n lodash_1.default.get(submission.data, comp.path, {})._vnote = submission._vnote;\n }\n const { persistent } = comp.component;\n if (persistent === \"client-only\") {\n lodash_1.default.unset(submission.data, comp.path);\n }\n });\n this.hook(\"customValidation\", Object.assign(Object.assign({}, submission), { component: options.component }), (err) => {\n if (err) {\n // If string is returned, cast to object.\n if (typeof err === \"string\") {\n err = {\n message: err,\n };\n }\n // Ensure err is an array.\n err = Array.isArray(err) ? err : [err];\n return reject(err);\n }\n this.loading = true;\n // Use the form action to submit the form if available.\n if (this._form && this._form.action) {\n const method = submission.data._id &&\n this._form.action.includes(submission.data._id)\n ? \"PUT\"\n : \"POST\";\n return Formio_1.Formio.makeStaticRequest(this._form.action, method, submission, this.formio ? this.formio.options : {})\n .then((result) => resolve({\n submission: result,\n saved: true,\n }))\n .catch((error) => {\n this.setServerErrors(error);\n return reject(error);\n });\n }\n const submitFormio = this.formio;\n if (this.nosubmit || !submitFormio) {\n return resolve({\n submission,\n saved: false,\n });\n }\n // If this is an actionUrl, then make sure to save the action and not the submission.\n const submitMethod = submitFormio.actionUrl\n ? \"saveAction\"\n : \"saveSubmission\";\n submitFormio[submitMethod](submission)\n .then((result) => resolve({\n submission: result,\n saved: true,\n }))\n .catch((error) => {\n this.setServerErrors(error);\n return reject(error);\n });\n });\n });\n });\n }\n setServerErrors(error) {\n if (error.details) {\n this.serverErrors = error.details\n .filter((err) => (err.level ? err.level === \"error\" : err))\n .map((err) => {\n err.fromServer = true;\n return err;\n });\n }\n else if (typeof error === \"string\") {\n this.serverErrors = [{ fromServer: true, level: \"error\", message: error }];\n }\n }\n executeSubmit(options) {\n this.submitted = true;\n this.submitting = true;\n return this.submitForm(options)\n .then(({ submission, saved }) => this.onSubmit(submission, saved))\n .then((results) => {\n this.submissionInProcess = false;\n return results;\n })\n .catch((err) => {\n this.submissionInProcess = false;\n return Promise.reject(this.onSubmissionError(err));\n });\n }\n clearServerErrors() {\n var _a;\n (_a = this.serverErrors) === null || _a === void 0 ? void 0 : _a.forEach((error) => {\n if (error.path) {\n const pathArray = (0, utils_1.getArrayFromComponentPath)(error.path);\n const component = this.getComponent(pathArray, lodash_1.default.identity, error.formattedKeyOrPath);\n if (component) {\n component.serverErrors = [];\n }\n }\n });\n this.serverErrors = [];\n }\n /**\n * Submits the form.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.src = 'https://examples.form.io/example';\n * form.submission = {data: {\n * firstName: 'Joe',\n * lastName: 'Smith',\n * email: 'joe@example.com'\n * }};\n * form.submit().then((submission) => {\n * console.log(submission);\n * });\n * @param {boolean} before - If this submission occured from the before handlers.\n * @param {any} options - The options to use when submitting this form.\n * @returns {Promise} - A promise when the form is done submitting.\n */\n submit(before = false, options = {}) {\n this.submissionInProcess = true;\n if (!before) {\n return this.beforeSubmit(options).then(() => this.executeSubmit(options));\n }\n else {\n return this.executeSubmit(options);\n }\n }\n submitUrl(URL, headers) {\n if (!URL) {\n return console.warn(\"Missing URL argument\");\n }\n const submission = this.submission || {};\n const API_URL = URL;\n const settings = {\n method: \"POST\",\n headers: {},\n };\n if (headers && headers.length > 0) {\n headers.map((e) => {\n if (e.header !== \"\" && e.value !== \"\") {\n settings.headers[e.header] = this.interpolate(e.value, submission);\n }\n });\n }\n if (API_URL && settings) {\n Formio_1.Formio.makeStaticRequest(API_URL, settings.method, submission, {\n headers: settings.headers,\n })\n .then(() => {\n this.emit(\"requestDone\");\n this.setAlert(\"success\", \"<p> Success </p>\");\n })\n .catch((e) => {\n const message = `${e.statusText ? e.statusText : \"\"} ${e.status ? e.status : e}`;\n this.emit(\"error\", message);\n console.error(message);\n this.setAlert(\"danger\", `<p> ${message} </p>`);\n return Promise.reject(this.onSubmissionError(e));\n });\n }\n else {\n this.emit(\"error\", \"You should add a URL to this button.\");\n this.setAlert(\"warning\", \"You should add a URL to this button.\");\n return console.warn(\"You should add a URL to this button.\");\n }\n }\n triggerCaptcha() {\n if (!this || !this.components) {\n return;\n }\n const captchaComponent = [];\n (0, formUtils_1.eachComponent)(this.components, (component) => {\n if (/^(re)?captcha$/.test(component.type) && component.component.eventType === 'formLoad') {\n captchaComponent.push(component);\n }\n });\n if (captchaComponent.length > 0) {\n captchaComponent[0].verify(`${this.form.name ? this.form.name : 'form'}Load`);\n }\n }\n set nosubmit(value) {\n this._nosubmit = !!value;\n this.emit(\"nosubmit\", this._nosubmit);\n }\n get nosubmit() {\n return this._nosubmit || false;\n }\n get conditions() {\n var _a, _b;\n return (_b = (_a = this.schema.settings) === null || _a === void 0 ? void 0 : _a.conditions) !== null && _b !== void 0 ? _b : [];\n }\n get variables() {\n var _a, _b;\n return (_b = (_a = this.schema.settings) === null || _a === void 0 ? void 0 : _a.variables) !== null && _b !== void 0 ? _b : [];\n }\n}\nexports[\"default\"] = Webform;\nWebform.setBaseUrl = Formio_1.Formio.setBaseUrl;\nWebform.setApiUrl = Formio_1.Formio.setApiUrl;\nWebform.setAppUrl = Formio_1.Formio.setAppUrl;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Webform.js?");
|
5527
|
+
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 compare_versions_1 = __webpack_require__(/*! compare-versions */ \"./node_modules/compare-versions/lib/esm/index.js\");\nconst EventEmitter_1 = __importDefault(__webpack_require__(/*! ./EventEmitter */ \"./lib/cjs/EventEmitter.js\"));\nconst i18n_1 = __importDefault(__webpack_require__(/*! ./i18n */ \"./lib/cjs/i18n.js\"));\nconst Formio_1 = __webpack_require__(/*! ./Formio */ \"./lib/cjs/Formio.js\");\nconst Components_1 = __importDefault(__webpack_require__(/*! ./components/Components */ \"./lib/cjs/components/Components.js\"));\nconst NestedDataComponent_1 = __importDefault(__webpack_require__(/*! ./components/_classes/nesteddata/NestedDataComponent */ \"./lib/cjs/components/_classes/nesteddata/NestedDataComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ./utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst formUtils_1 = __webpack_require__(/*! ./utils/formUtils */ \"./lib/cjs/utils/formUtils.js\");\n// We need this here because dragula pulls in CustomEvent class that requires global to exist.\nif (typeof window !== 'undefined' && typeof window.global === 'undefined') {\n window.global = window;\n}\nconst dragula_1 = __importDefault(__webpack_require__(/*! dragula */ \"./node_modules/dragula/dragula.js\"));\n// Initialize the available forms.\nFormio_1.Formio.forms = {};\n// Allow people to register components.\nFormio_1.Formio.registerComponent = Components_1.default.setComponent;\n/**\n *\n * @param {any} icons - The icons to use.\n * @returns {any} - The icon set.\n */\nfunction getIconSet(icons) {\n if (icons === \"fontawesome\") {\n return \"fa\";\n }\n return icons || \"\";\n}\n/**\n *\n * @param {any} options - The options to get.\n * @returns {any} - The options.\n */\nfunction getOptions(options) {\n options = lodash_1.default.defaults(options, {\n submitOnEnter: false,\n iconset: getIconSet(options && options.icons ? options.icons : Formio_1.Formio.icons),\n i18next: null,\n saveDraft: false,\n alwaysDirty: false,\n saveDraftThrottle: 5000,\n display: \"form\",\n cdnUrl: Formio_1.Formio.cdn.baseUrl,\n });\n if (!options.events) {\n options.events = new EventEmitter_1.default();\n }\n return options;\n}\n/**\n * Represents a JSON value.\n * @typedef {(string | number | boolean | null | JSONArray | JSONObject)} JSON\n */\n/**\n * Represents a JSON array.\n * @typedef {Array<JSON>} JSONArray\n */\n/**\n * Represents a JSON object.\n * @typedef {{[key: string]: JSON}} JSONObject\n */\n/**\n * @typedef {object} FormioHooks\n * @property {Function} [beforeSubmit] - A function that is called before the form is submitted.\n * @property {Function} [beforeCancel] - A function that is called before the form is canceled.\n * @property {Function} [beforeNext] - A function that is called before moving to the next page in a multi-page form.\n * @property {Function} [beforePrev] - A function that is called before moving to the previous page in a multi-page form.\n * @property {Function} [attachComponent] - A function that is called when a component is attached to the form.\n * @property {Function} [setDataValue] - A function that is called when setting the value of a data component.\n * @property {Function} [addComponents] - A function that is called when adding multiple components to the form.\n * @property {Function} [addComponent] - A function that is called when adding a single component to the form.\n * @property {Function} [customValidation] - A function that is called for custom validation of the form.\n * @property {Function} [attachWebform] - A function that is called when attaching a webform to the form.\n */\n/**\n * @typedef {object} SanitizeConfig\n * @property {string[]} [addAttr] - The attributes to add.\n * @property {string[]} [addTags] - The tags to add.\n * @property {string[]} [allowedAttrs] - The allowed attributes.\n * @property {string[]} [allowedTags] - The allowed tags.\n * @property {string[]} [allowedUriRegex] - The allowed URI regex.\n * @property {string[]} [addUriSafeAttr] - The URI safe attributes.\n */\n/**\n * @typedef {object} ButtonSettings\n * @property {boolean} [showPrevious] - Show the \"Previous\" button.\n * @property {boolean} [showNext] - Show the \"Next\" button.\n * @property {boolean} [showCancel] - Show the \"Cancel\" button.\n * @property {boolean} [showSubmit] - Show the \"Submit\" button.\n */\n/**\n * @typedef {object} FormOptions\n * @property {boolean} [saveDraft] - Enable the save draft feature.\n * @property {number} [saveDraftThrottle] - The throttle for the save draft feature.\n * @property {boolean} [readOnly] - Set this form to readOnly.\n * @property {boolean} [noAlerts] - Disable the alerts dialog.\n * @property {{[key: string]: string}} [i18n] - The translation file for this rendering.\n * @property {string} [template] - Custom logic for creation of elements.\n * @property {boolean} [noDefaults] - Exclude default values from the settings.\n * @property {any} [fileService] - The file service for this form.\n * @property {EventEmitter} [events] - The EventEmitter for this form.\n * @property {string} [language] - The language to render this form in.\n * @property {{[key: string]: string}} [i18next] - The i18next configuration for this form.\n * @property {boolean} [viewAsHtml] - View the form as raw HTML.\n * @property {'form' | 'html' | 'flat' | 'builder' | 'pdf'} [renderMode] - The render mode for this form.\n * @property {boolean} [highlightErrors] - Highlight any errors on the form.\n * @property {string} [componentErrorClass] - The error class for components.\n * @property {any} [templates] - The templates for this form.\n * @property {string} [iconset] - The iconset for this form.\n * @property {import('@formio/core').Component[]} [components] - The components for this form.\n * @property {{[key: string]: boolean}} [disabled] - Disabled components for this form.\n * @property {boolean} [showHiddenFields] - Show hidden fields.\n * @property {{[key: string]: boolean}} [hide] - Hidden components for this form.\n * @property {{[key: string]: boolean}} [show] - Components to show for this form.\n * @property {Formio} [formio] - The Formio instance for this form.\n * @property {string} [decimalSeparator] - The decimal separator for this form.\n * @property {string} [thousandsSeparator] - The thousands separator for this form.\n * @property {FormioHooks} [hooks] - The hooks for this form.\n * @property {boolean} [alwaysDirty] - Always be dirty.\n * @property {boolean} [skipDraftRestore] - Skip restoring a draft.\n * @property {'form' | 'wizard' | 'pdf'} [display] - The display for this form.\n * @property {string} [cdnUrl] - The CDN url for this form.\n * @property {boolean} [flatten] - Flatten the form.\n * @property {boolean} [sanitize] - Sanitize the form.\n * @property {SanitizeConfig} [sanitizeConfig] - The sanitize configuration for this form.\n * @property {ButtonSettings} [buttonSettings] - The button settings for this form.\n * @property {object} [breadcrumbSettings] - The breadcrumb settings for this form.\n * @property {boolean} [allowPrevious] - Allow the previous button (for Wizard forms).\n * @property {string[]} [wizardButtonOrder] - The order of the buttons (for Wizard forms).\n * @property {boolean} [showCheckboxBackground] - Show the checkbox background.\n * @property {boolean} [inputsOnly] - Only show inputs in the form and no labels.\n * @property {boolean} [building] - If we are in the process of building the form.\n * @property {number} [zoom] - The zoom for PDF forms.\n */\nclass Webform extends NestedDataComponent_1.default {\n /**\n * Creates a new Form instance.\n * @param {HTMLElement | object | import('Form').FormOptions} [elementOrOptions] - The DOM element to render this form within or the options to create this form instance.\n * @param {import('Form').FormOptions} [options] - The options to create a new form instance.\n */\n constructor(elementOrOptions, options = undefined) {\n let element, formOptions;\n if (elementOrOptions instanceof HTMLElement || options) {\n element = elementOrOptions;\n formOptions = options || {};\n }\n else {\n formOptions = elementOrOptions || {};\n }\n super(null, getOptions(formOptions));\n this.executeShortcuts = (event) => {\n const { target } = event;\n if (!this.keyboardCatchableElement(target)) {\n return;\n }\n const ctrl = event.ctrlKey || event.metaKey;\n const keyCode = event.keyCode;\n let char = \"\";\n if (65 <= keyCode && keyCode <= 90) {\n char = String.fromCharCode(keyCode);\n }\n else if (keyCode === 13) {\n char = \"Enter\";\n }\n else if (keyCode === 27) {\n char = \"Esc\";\n }\n lodash_1.default.each(this.shortcuts, (shortcut) => {\n if (shortcut.ctrl && !ctrl) {\n return;\n }\n if (shortcut.shortcut === char) {\n shortcut.element.click();\n event.preventDefault();\n }\n });\n };\n this.setElement(element);\n // Keep track of all available forms globally.\n Formio_1.Formio.forms[this.id] = this;\n // Set the base url.\n if (this.options.baseUrl) {\n Formio_1.Formio.setBaseUrl(this.options.baseUrl);\n }\n /**\n * The type of this element.\n * @type {string}\n */\n this.type = \"form\";\n this._src = \"\";\n this._loading = false;\n this._form = {};\n this.draftEnabled = false;\n this.savingDraft = false;\n if (this.options.saveDraftThrottle) {\n this.triggerSaveDraft = lodash_1.default.throttle(this.saveDraft.bind(this), this.options.saveDraftThrottle);\n }\n else {\n this.triggerSaveDraft = this.saveDraft.bind(this);\n }\n /**\n * Determines if this form should submit the API on submit.\n * @type {boolean}\n */\n this.nosubmit = false;\n /**\n * Determines if the form has tried to be submitted, error or not.\n * @type {boolean}\n */\n this.submitted = false;\n /**\n * Determines if the form is being submitted at the moment.\n * @type {boolean}\n */\n this.submitting = false;\n /**\n * The Formio instance for this form.\n * @type {Formio}\n */\n this.formio = null;\n /**\n * The loader HTML element.\n * @type {HTMLElement}\n */\n this.loader = null;\n /**\n * The alert HTML element\n * @type {HTMLElement}\n */\n this.alert = null;\n /**\n * Promise that is triggered when the submission is done loading.\n * @type {Promise}\n */\n this.onSubmission = null;\n /**\n * Determines if this submission is explicitly set.\n * @type {boolean}\n */\n this.submissionSet = false;\n /**\n * Promise that executes when the form is ready and rendered.\n * @type {Promise}\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.formReady.then(() => {\n * console.log('The form is ready!');\n * });\n * form.src = 'https://examples.form.io/example';\n */\n this.formReady = new Promise((resolve, reject) => {\n /**\n * Called when the formReady state of this form has been resolved.\n * @type {Function}\n */\n this.formReadyResolve = resolve;\n /**\n * Called when this form could not load and is rejected.\n * @type {Function}\n */\n this.formReadyReject = reject;\n });\n /**\n * Promise that executes when the submission is ready and rendered.\n * @type {Promise}\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.submissionReady.then(() => {\n * console.log('The submission is ready!');\n * });\n * form.src = 'https://examples.form.io/example/submission/234234234234234243';\n */\n this.submissionReady = new Promise((resolve, reject) => {\n /**\n * Called when the formReady state of this form has been resolved.\n * @type {Function}\n */\n this.submissionReadyResolve = resolve;\n /**\n * Called when this form could not load and is rejected.\n * @type {Function}\n */\n this.submissionReadyReject = reject;\n });\n this.shortcuts = [];\n // Set language after everything is established.\n this.language = this.i18next.language;\n // See if we need to restore the draft from a user.\n if (this.options.saveDraft) {\n if (this.options.skipDraftRestore) {\n this.draftEnabled = true;\n this.savingDraft = false;\n }\n else {\n this.formReady.then(() => {\n const user = Formio_1.Formio.getUser();\n // Only restore a draft if the submission isn't explicitly set.\n if (user && !this.submissionSet) {\n this.restoreDraft(user._id);\n }\n });\n }\n }\n this.component.clearOnHide = false;\n // Ensure the root is set to this component.\n this.root = this;\n this.localRoot = this;\n this.root.dragulaLib = dragula_1.default;\n }\n /* eslint-enable max-statements */\n get language() {\n return this.options.language;\n }\n get emptyValue() {\n return null;\n }\n componentContext() {\n return this._data;\n }\n /**\n * Sets the language for this form.\n * @param {string} lang - The language to use (e.g. 'en', 'sp', etc.)\n */\n set language(lang) {\n if (!this.i18next) {\n return;\n }\n this.options.language = lang;\n if (this.i18next.language === lang) {\n return;\n }\n this.i18next.changeLanguage(lang, (err) => {\n if (err) {\n return;\n }\n this.rebuild();\n this.emit(\"languageChanged\");\n });\n }\n get componentComponents() {\n return this.form.components;\n }\n get shadowRoot() {\n return this.options.shadowRoot;\n }\n /**\n * Add a language for translations\n * @param {string} code - The language code for the language being added.\n * @param {object} lang - The language translations.\n * @param {boolean} [active] - If this language should be set as the active language.\n */\n addLanguage(code, lang, active = false) {\n if (this.i18next) {\n var translations = lodash_1.default.assign((0, utils_1.fastCloneDeep)(i18n_1.default.resources.en.translation), lang);\n this.i18next.addResourceBundle(code, \"translation\", translations, true, true);\n if (active) {\n this.language = code;\n }\n }\n }\n keyboardCatchableElement(element) {\n if (element.nodeName === \"TEXTAREA\") {\n return false;\n }\n if (element.nodeName === \"INPUT\") {\n return [\"text\", \"email\", \"password\"].indexOf(element.type) === -1;\n }\n return true;\n }\n addShortcut(element, shortcut) {\n if (!shortcut || !/^([A-Z]|Enter|Esc)$/i.test(shortcut)) {\n return;\n }\n shortcut = lodash_1.default.capitalize(shortcut);\n if (shortcut === \"Enter\" || shortcut === \"Esc\") {\n // Restrict Enter and Esc only for buttons\n if (element.tagName !== \"BUTTON\") {\n return;\n }\n this.shortcuts.push({\n shortcut,\n element,\n });\n }\n else {\n this.shortcuts.push({\n ctrl: true,\n shortcut,\n element,\n });\n }\n }\n removeShortcut(element, shortcut) {\n if (!shortcut || !/^([A-Z]|Enter|Esc)$/i.test(shortcut)) {\n return;\n }\n lodash_1.default.remove(this.shortcuts, {\n shortcut,\n element,\n });\n }\n /**\n * Get the embed source of the form.\n * @returns {string} - The source of the form.\n */\n get src() {\n return this._src;\n }\n /**\n * Loads the submission if applicable.\n * @returns {Promise} - The promise that is triggered when the submission is loaded.\n */\n loadSubmission() {\n this.loadingSubmission = true;\n if (this.formio.submissionId) {\n this.onSubmission = this.formio\n .loadSubmission()\n .then((submission) => this.setSubmission(submission), (err) => this.submissionReadyReject(err))\n .catch((err) => this.submissionReadyReject(err));\n }\n else {\n this.submissionReadyResolve();\n }\n return this.submissionReady;\n }\n /**\n * Set the src of the form renderer.\n * @param {string} value - The source value to set.\n * @param {any} options - The options to set.\n * @returns {Promise} - The promise that is triggered when the form is set.\n */\n setSrc(value, options) {\n if (this.setUrl(value, options)) {\n this.nosubmit = false;\n return this.formio\n .loadForm({ params: { live: 1 } })\n .then((form) => {\n const setForm = this.setForm(form);\n this.loadSubmission();\n return setForm;\n })\n .catch((err) => {\n console.warn(err);\n this.formReadyReject(err);\n });\n }\n return Promise.resolve();\n }\n /**\n * Set the Form source, which is typically the Form.io embed URL.\n * @param {string} value - The value of the form embed url.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.formReady.then(() => {\n * console.log('The form is formReady!');\n * });\n * form.src = 'https://examples.form.io/example';\n */\n set src(value) {\n this.setSrc(value);\n }\n /**\n * Get the embed source of the form.\n * @returns {string} - returns the source of the form.\n */\n get url() {\n return this._src;\n }\n /**\n * Sets the url of the form renderer.\n * @param {string} value - The value to set the url to.\n * @param {any} options - The options to set.\n * @returns {boolean} - TRUE means the url was set, FALSE otherwise.\n */\n setUrl(value, options) {\n if (!value || typeof value !== \"string\" || value === this._src) {\n return false;\n }\n this._src = value;\n this.nosubmit = true;\n this.formio = this.options.formio = new Formio_1.Formio(value, options);\n if (this.type === \"form\") {\n // Set the options source so this can be passed to other components.\n this.options.src = value;\n }\n return true;\n }\n /**\n * Set the form source but don't initialize the form and submission from the url.\n * @param {string} value - The value of the form embed url.\n */\n set url(value) {\n this.setUrl(value);\n }\n /**\n * Called when both the form and submission have been loaded.\n * @returns {Promise} - The promise to trigger when both form and submission have loaded.\n */\n get ready() {\n return this.formReady.then(() => {\n return super.ready.then(() => {\n return this.loadingSubmission ? this.submissionReady : true;\n });\n });\n }\n /**\n * Returns if this form is loading.\n * @returns {boolean} - TRUE means the form is loading, FALSE otherwise.\n */\n get loading() {\n return this._loading;\n }\n /**\n * Set the loading state for this form, and also show the loader spinner.\n * @param {boolean} loading - If this form should be \"loading\" or not.\n */\n set loading(loading) {\n if (this._loading !== loading) {\n this._loading = loading;\n if (!this.loader && loading) {\n this.loader = this.ce(\"div\", {\n class: \"loader-wrapper\",\n });\n const spinner = this.ce(\"div\", {\n class: \"loader text-center\",\n });\n this.loader.appendChild(spinner);\n }\n /* eslint-disable max-depth */\n if (this.loader) {\n try {\n if (loading) {\n this.prependTo(this.loader, this.wrapper);\n }\n else {\n this.removeChildFrom(this.loader, this.wrapper);\n }\n }\n catch (err) {\n // ingore\n }\n }\n /* eslint-enable max-depth */\n }\n }\n /**\n * Sets the JSON schema for the form to be rendered.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.setForm({\n * components: [\n * {\n * type: 'textfield',\n * key: 'firstName',\n * label: 'First Name',\n * placeholder: 'Enter your first name.',\n * input: true\n * },\n * {\n * type: 'textfield',\n * key: 'lastName',\n * label: 'Last Name',\n * placeholder: 'Enter your last name',\n * input: true\n * },\n * {\n * type: 'button',\n * action: 'submit',\n * label: 'Submit',\n * theme: 'primary'\n * }\n * ]\n * });\n * @param {object} form - The JSON schema of the form @see https://examples.form.io/example for an example JSON schema.\n * @param {any} flags - Any flags to apply when setting the form.\n * @returns {Promise} - The promise that is triggered when the form is set.\n */\n setForm(form, flags = {}) {\n var _a, _b, _c;\n const isFormAlreadySet = this._form && ((_a = this._form.components) === null || _a === void 0 ? void 0 : _a.length);\n try {\n // Do not set the form again if it has been already set\n if (isFormAlreadySet && JSON.stringify(this._form) === JSON.stringify(form)) {\n return Promise.resolve();\n }\n // Create the form.\n this._form = (flags === null || flags === void 0 ? void 0 : flags.keepAsReference) ? form : lodash_1.default.cloneDeep(form);\n if (this.onSetForm) {\n this.onSetForm(lodash_1.default.cloneDeep(this._form), form);\n }\n if ((_c = (_b = this.parent) === null || _b === void 0 ? void 0 : _b.component) === null || _c === void 0 ? void 0 : _c.modalEdit) {\n return Promise.resolve();\n }\n }\n catch (err) {\n console.warn(err);\n // If provided form is not a valid JSON object, do not set it too\n return Promise.resolve();\n }\n // Allow the form to provide component overrides.\n if (form && form.settings && form.settings.components) {\n this.options.components = form.settings.components;\n }\n if (form && form.properties) {\n this.options.properties = form.properties;\n }\n // Use the sanitize config from the form settings or the global sanitize config if it is not provided in the options\n if (!this.options.sanitizeConfig && !this.builderMode) {\n this.options.sanitizeConfig =\n lodash_1.default.get(form, \"settings.sanitizeConfig\") ||\n lodash_1.default.get(form, \"globalSettings.sanitizeConfig\");\n }\n if (\"schema\" in form && (0, compare_versions_1.compareVersions)(form.schema, \"1.x\") > 0) {\n this.ready.then(() => {\n this.setAlert(\"alert alert-danger\", \"Form schema is for a newer version, please upgrade your renderer. Some functionality may not work.\");\n });\n }\n // See if they pass a module, and evaluate it if so.\n if (form && form.module) {\n let formModule = null;\n if (typeof form.module === \"string\") {\n try {\n formModule = this.evaluate(`return ${form.module}`);\n }\n catch (err) {\n console.warn(err);\n }\n }\n else {\n formModule = form.module;\n }\n if (formModule) {\n Formio_1.Formio.use(formModule);\n // Since we got here after instantiation, we need to manually apply form options.\n if (formModule.options && formModule.options.form) {\n this.options = Object.assign(this.options, formModule.options.form);\n }\n }\n }\n this.initialized = false;\n const rebuild = this.rebuild() || Promise.resolve();\n return rebuild.then(() => {\n this.emit(\"formLoad\", form);\n this.triggerCaptcha();\n // Make sure to trigger onChange after a render event occurs to speed up form rendering.\n setTimeout(() => {\n this.onChange(flags);\n this.formReadyResolve();\n }, 0);\n return this.formReady;\n });\n }\n /**\n * Gets the form object.\n * @returns {object} - The form JSON schema.\n */\n get form() {\n if (!this._form) {\n this._form = {\n components: [],\n };\n }\n return this._form;\n }\n /**\n * Sets the form value.\n * @alias setForm\n * @param {object} form - The form schema object.\n */\n set form(form) {\n this.setForm(form);\n }\n /**\n * Returns the submission object that was set within this form.\n * @returns {object} - The submission object.\n */\n get submission() {\n return this.getValue();\n }\n /**\n * Sets the submission of a form.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.src = 'https://examples.form.io/example';\n * form.submission = {data: {\n * firstName: 'Joe',\n * lastName: 'Smith',\n * email: 'joe@example.com'\n * }};\n * @param {object} submission - The Form.io submission object.\n */\n set submission(submission) {\n this.setSubmission(submission);\n }\n /**\n * Sets a submission and returns the promise when it is ready.\n * @param {any} submission - The submission to set.\n * @param {any} flags - Any flags to apply when setting the submission.\n * @returns {Promise} - The promise that is triggered when the submission is set.\n */\n setSubmission(submission, flags = {}) {\n flags = Object.assign(Object.assign({}, flags), { fromSubmission: lodash_1.default.has(flags, \"fromSubmission\") ? flags.fromSubmission : true });\n return (this.onSubmission = this.formReady\n .then((resolveFlags) => {\n if (resolveFlags) {\n flags = Object.assign(Object.assign({}, flags), resolveFlags);\n }\n this.submissionSet = true;\n this.triggerChange(flags);\n this.emit(\"beforeSetSubmission\", submission);\n this.setValue(submission, flags);\n return this.submissionReadyResolve(submission);\n }, (err) => this.submissionReadyReject(err))\n .catch((err) => this.submissionReadyReject(err)));\n }\n handleDraftError(errName, errDetails, restoreDraft) {\n const errorMessage = lodash_1.default.trim(`${this.t(errName)} ${errDetails || \"\"}`);\n console.warn(errorMessage);\n this.emit(restoreDraft ? \"restoreDraftError\" : \"saveDraftError\", errDetails || errorMessage);\n }\n saveDraft() {\n if (!this.draftEnabled) {\n return;\n }\n if (!this.formio) {\n this.handleDraftError(\"saveDraftInstanceError\");\n return;\n }\n if (!Formio_1.Formio.getUser()) {\n this.handleDraftError(\"saveDraftAuthError\");\n return;\n }\n const draft = (0, utils_1.fastCloneDeep)(this.submission);\n draft.state = \"draft\";\n if (!this.savingDraft && !this.submitting) {\n this.emit(\"saveDraftBegin\");\n this.savingDraft = true;\n this.formio\n .saveSubmission(draft)\n .then((sub) => {\n // Set id to submission to avoid creating new draft submission\n this.submission._id = sub._id;\n this.savingDraft = false;\n this.emit(\"saveDraft\", sub);\n })\n .catch((err) => {\n this.savingDraft = false;\n this.handleDraftError(\"saveDraftError\", err);\n });\n }\n }\n /**\n * Restores a draft submission based on the user who is authenticated.\n * @param {string} userId - The user id where we need to restore the draft from.\n */\n restoreDraft(userId) {\n const formio = this.formio || this.options.formio;\n if (!formio) {\n this.handleDraftError(\"restoreDraftInstanceError\", null, true);\n return;\n }\n this.savingDraft = true;\n formio\n .loadSubmissions({\n params: {\n state: 'draft',\n owner: userId,\n sort: '-created'\n },\n })\n .then((submissions) => {\n if (submissions.length > 0 && !this.options.skipDraftRestore) {\n const draft = (0, utils_1.fastCloneDeep)(submissions[0]);\n return this.setSubmission(draft).then(() => {\n this.draftEnabled = true;\n this.savingDraft = false;\n this.emit(\"restoreDraft\", draft);\n });\n }\n // Enable drafts so that we can keep track of changes.\n this.draftEnabled = true;\n this.savingDraft = false;\n this.emit(\"restoreDraft\", null);\n })\n .catch((err) => {\n this.draftEnabled = true;\n this.savingDraft = false;\n this.handleDraftError(\"restoreDraftError\", err, true);\n });\n }\n get schema() {\n const schema = (0, utils_1.fastCloneDeep)(lodash_1.default.omit(this._form, [\"components\"]));\n schema.components = [];\n this.eachComponent((component) => schema.components.push(component.schema));\n return schema;\n }\n mergeData(_this, _that) {\n lodash_1.default.mergeWith(_this, _that, (thisValue, thatValue) => {\n if (Array.isArray(thisValue) &&\n Array.isArray(thatValue) &&\n thisValue.length !== thatValue.length) {\n return thatValue;\n }\n });\n }\n setValue(submission, flags = {}) {\n if (!submission || !submission.data) {\n submission = {\n data: {},\n metadata: submission.metadata,\n };\n }\n // Metadata needs to be available before setValue\n this._submission.metadata = submission.metadata ? lodash_1.default.cloneDeep(submission.metadata) : {};\n this.editing = !!submission._id;\n // Set the timezone in the options if available.\n if (!this.options.submissionTimezone &&\n submission.metadata &&\n submission.metadata.timezone) {\n this.options.submissionTimezone = submission.metadata.timezone;\n }\n const changed = super.setValue(submission.data, flags);\n if (!flags.sanitize) {\n this.mergeData(this.data, submission.data);\n }\n submission.data = this.data;\n this._submission = submission;\n return changed;\n }\n getValue() {\n if (!this._submission.data) {\n this._submission.data = {};\n }\n if (this.viewOnly) {\n return this._submission;\n }\n const submission = this._submission;\n submission.data = this.data;\n return this._submission;\n }\n /**\n * Build the form.\n * @returns {Promise} - The promise that is triggered when the form is built.\n */\n init() {\n if (this.options.submission) {\n const submission = lodash_1.default.extend({}, this.options.submission);\n this._submission = submission;\n this._data = submission.data;\n }\n else {\n this._submission = this._submission || { data: {} };\n }\n // Remove any existing components.\n if (this.components && this.components.length) {\n this.destroyComponents();\n this.components = [];\n }\n if (this.component) {\n this.component.components = this.form ? this.form.components : [];\n }\n else {\n this.component = this.form;\n }\n this.component.type = \"form\";\n this.component.input = false;\n this.addComponents();\n this.on(\"submitButton\", (options) => {\n this.submit(false, options).catch((e) => {\n options.instance.loading = false;\n return e !== false && e !== undefined && console.log(e);\n });\n }, true);\n this.on(\"checkValidity\", (data) => this.validate(data, { dirty: true, process: \"change\" }), true);\n this.on(\"requestUrl\", (args) => this.submitUrl(args.url, args.headers), true);\n this.on(\"resetForm\", () => this.resetValue(), true);\n this.on(\"deleteSubmission\", () => this.deleteSubmission(), true);\n this.on(\"refreshData\", () => this.updateValue(), true);\n this.executeFormController();\n return this.formReady;\n }\n executeFormController() {\n // If no controller value or\n // hidden and set to clearOnHide (Don't calculate a value for a hidden field set to clear when hidden)\n if (!this.form ||\n !this.form.controller ||\n ((!this.visible || this.component.hidden) &&\n this.component.clearOnHide &&\n !this.rootPristine)) {\n return false;\n }\n this.formReady.then(() => {\n this.evaluate(this.form.controller, {\n components: this.components,\n instance: this,\n });\n });\n }\n /**\n *\n */\n teardown() {\n this.emit(\"formDelete\", this.id);\n delete Formio_1.Formio.forms[this.id];\n delete this.executeShortcuts;\n delete this.triggerSaveDraft;\n super.teardown();\n }\n destroy(all = false) {\n this.off(\"submitButton\");\n this.off(\"checkValidity\");\n this.off(\"requestUrl\");\n this.off(\"resetForm\");\n this.off(\"deleteSubmission\");\n this.off(\"refreshData\");\n return super.destroy(all);\n }\n build(element) {\n if (element || this.element) {\n return this.ready.then(() => {\n element = element || this.element;\n super.build(element);\n });\n }\n return this.ready;\n }\n getClassName() {\n let classes = \"formio-form\";\n if (this.options.readOnly) {\n classes += \" formio-read-only\";\n }\n return classes;\n }\n render() {\n return super.render(this.renderTemplate(\"webform\", {\n classes: this.getClassName(),\n children: this.renderComponents(),\n }), this.builderMode ? \"builder\" : \"form\", true);\n }\n redraw() {\n // Don't bother if we have not built yet.\n if (!this.element) {\n return Promise.resolve();\n }\n this.clear();\n this.setContent(this.element, this.render());\n return this.attach(this.element);\n }\n attach(element) {\n this.setElement(element);\n this.loadRefs(element, { webform: \"single\" });\n const childPromise = this.attachComponents(this.refs.webform);\n this.addEventListener(document, \"keydown\", this.executeShortcuts);\n this.currentForm = this;\n this.hook(\"attachWebform\", element, this);\n return childPromise.then(() => {\n this.emit(\"render\", this.element);\n return this.setValue(this._submission, {\n noUpdateEvent: true,\n });\n });\n }\n hasRequiredFields() {\n let result = false;\n (0, formUtils_1.eachComponent)(this.form.components, (component) => {\n if (component.validate.required) {\n result = true;\n return true;\n }\n }, true);\n return result;\n }\n resetValue() {\n lodash_1.default.each(this.getComponents(), (comp) => comp.resetValue());\n this.setPristine(true);\n this.onChange({ resetValue: true });\n }\n /**\n * Sets a new alert to display in the error dialog of the form.\n * @param {string} type - The type of alert to display. \"danger\", \"success\", \"warning\", etc.\n * @param {string} message - The message to show in the alert.\n * @param {object} options - The options for the alert.\n */\n setAlert(type, message, options) {\n if (!type && this.submitted) {\n if (this.alert) {\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.removeEventListener(el, \"click\");\n this.removeEventListener(el, \"keypress\");\n });\n }\n this.removeChild(this.alert);\n this.alert = null;\n }\n return;\n }\n if (this.options.noAlerts) {\n if (!message) {\n this.emit(\"error\", false);\n }\n return;\n }\n if (this.alert) {\n try {\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.removeEventListener(el, \"click\");\n this.removeEventListener(el, \"keypress\");\n });\n }\n this.removeChild(this.alert);\n this.alert = null;\n }\n catch (err) {\n // ignore\n }\n }\n if (message) {\n const attrs = {\n class: (options && options.classes) || `alert alert-${type}`,\n id: `error-list-${this.id}`,\n };\n const templateOptions = {\n message: message instanceof HTMLElement ? message.outerHTML : message,\n attrs: attrs,\n type,\n };\n this.alert = (0, utils_1.convertStringToHTMLElement)(this.renderTemplate(\"alert\", templateOptions), `#${attrs.id}`);\n }\n if (!this.alert) {\n return;\n }\n this.loadRefs(this.alert, { errorRef: \"multiple\" });\n if (this.refs.errorRef && this.refs.errorRef.length) {\n this.refs.errorRef.forEach((el) => {\n this.addEventListener(el, \"click\", (e) => {\n const key = e.currentTarget.dataset.componentKey;\n this.focusOnComponent(key);\n });\n this.addEventListener(el, \"keydown\", (e) => {\n if (e.keyCode === 13) {\n e.preventDefault();\n const key = e.currentTarget.dataset.componentKey;\n this.focusOnComponent(key);\n }\n });\n });\n }\n this.prepend(this.alert);\n }\n /**\n * Focus on selected component.\n * @param {string} key - The key of selected component.\n */\n focusOnComponent(key) {\n if (key) {\n const component = this.getComponent(key);\n if (component) {\n component.focus();\n }\n }\n }\n /**\n * Show the errors of this form within the alert dialog.\n * @param {object} error - An optional additional error to display along with the component errors.\n * @returns {*}\n */\n /* eslint-disable no-unused-vars */\n /**\n *\n * @param {Array} errors - An array of errors to display.\n * @param {boolean} triggerEvent - Whether or not to trigger the error event.\n * @returns {void|Array} - The errors that were set.\n */\n showErrors(errors, triggerEvent) {\n this.loading = false;\n if (!Array.isArray(errors)) {\n errors = [errors];\n }\n errors = errors.concat(this.customErrors).filter((err) => !!err);\n if (!errors.length) {\n this.setAlert(false);\n return;\n }\n // Mark any components as invalid if in a custom message.\n errors.forEach((err) => {\n const { components = [] } = err;\n if (err.component) {\n components.push(err.component);\n }\n if (err.path) {\n components.push(err.path);\n }\n components.forEach((path) => {\n const originalPath = (0, utils_1.getStringFromComponentPath)(path);\n const component = this.getComponent(path, lodash_1.default.identity, originalPath);\n if (err.fromServer) {\n if (component.serverErrors) {\n component.serverErrors.push(err);\n }\n else {\n component.serverErrors = [err];\n }\n }\n const components = lodash_1.default.compact(Array.isArray(component) ? component : [component]);\n components.forEach((component) => component.setCustomValidity(err.message, true));\n });\n });\n const displayedErrors = [];\n if (errors.length) {\n errors = lodash_1.default.uniqBy(errors, (error) => error.message);\n const createListItem = (message, index) => {\n var _a, _b, _c;\n const err = errors[index];\n const messageFromIndex = !lodash_1.default.isUndefined(index) && errors && errors[index];\n const keyOrPath = (messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.formattedKeyOrPath) ||\n (messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.path) ||\n ((_a = messageFromIndex === null || messageFromIndex === void 0 ? void 0 : messageFromIndex.context) === null || _a === void 0 ? void 0 : _a.path) ||\n (((_b = err.context) === null || _b === void 0 ? void 0 : _b.component) && ((_c = err.context) === null || _c === void 0 ? void 0 : _c.component.key)) ||\n (err.component && err.component.key) ||\n (err.fromServer && err.path);\n const formattedKeyOrPath = keyOrPath ? (0, utils_1.getStringFromComponentPath)(keyOrPath) : \"\";\n if (typeof err !== \"string\" && !err.formattedKeyOrPath) {\n err.formattedKeyOrPath = formattedKeyOrPath;\n }\n return {\n message: (0, utils_1.unescapeHTML)(message),\n keyOrPath: formattedKeyOrPath,\n };\n };\n errors.forEach(({ message, context, fromServer, component }, index) => {\n const text = !(component === null || component === void 0 ? void 0 : component.label) || (context === null || context === void 0 ? void 0 : context.hasLabel) || fromServer\n ? this.t(\"alertMessage\", { message: this.t(message) })\n : this.t(\"alertMessageWithLabel\", {\n label: this.t(component === null || component === void 0 ? void 0 : component.label),\n message: this.t(message),\n });\n displayedErrors.push(createListItem(text, index));\n });\n }\n const errorsList = this.renderTemplate(\"errorsList\", { errors: displayedErrors });\n this.root.setAlert(\"danger\", errorsList);\n if (triggerEvent) {\n this.emit(\"error\", errors);\n }\n return errors;\n }\n /* eslint-enable no-unused-vars */\n /**\n * Called when the submission has completed, or if the submission needs to be sent to an external library.\n * @param {object} submission - The submission object.\n * @param {boolean} saved - Whether or not this submission was saved to the server.\n * @returns {object} - The submission object.\n */\n onSubmit(submission, saved) {\n var _a;\n this.loading = false;\n this.submitting = false;\n this.setPristine(true);\n // We want to return the submitted submission and setValue will mutate the submission so cloneDeep it here.\n this.setValue((0, utils_1.fastCloneDeep)(submission), {\n noValidate: true,\n noCheck: true,\n });\n this.setAlert(\"success\", `<p>${this.t(\"complete\")}</p>`);\n // Cancel triggered saveDraft to prevent overriding the submitted state\n if (this.draftEnabled && ((_a = this.triggerSaveDraft) === null || _a === void 0 ? void 0 : _a.cancel)) {\n this.triggerSaveDraft.cancel();\n }\n this.emit(\"submit\", submission, saved);\n if (saved) {\n this.emit(\"submitDone\", submission);\n }\n return submission;\n }\n normalizeError(error) {\n if (error) {\n if (typeof error === \"object\" && \"details\" in error) {\n error = error.details;\n }\n if (typeof error === \"string\") {\n error = { message: error };\n }\n }\n return error;\n }\n /**\n * Called when an error occurs during the submission.\n * @param {object} error - The error that occured.\n * @returns {Array} errors - All errors.\n */\n onSubmissionError(error) {\n error = this.normalizeError(error);\n this.submitting = false;\n this.setPristine(false);\n this.emit(\"submitError\", error || this.errors);\n // Allow for silent cancellations (no error message, no submit button error state)\n if (error && error.silent) {\n this.emit(\"change\", { isValid: true }, { silent: true });\n return false;\n }\n const errors = this.showErrors(error, true);\n if (this.root && this.root.alert) {\n this.scrollIntoView(this.root.alert);\n }\n return errors;\n }\n /**\n * Trigger the change event for this form.\n * @param {any} flags - The flags to set on this change event.\n * @param {any} changed - The changed object which reflects the changes in the form.\n * @param {boolean} modified - Whether or not the form has been modified.\n * @param {any} changes - The changes that have occured in the form.\n */\n onChange(flags, changed, modified, changes) {\n flags = flags || {};\n let isChangeEventEmitted = false;\n super.onChange(flags, true);\n const value = lodash_1.default.clone(this.submission);\n flags.changed = value.changed = changed;\n flags.changes = changes;\n if (modified && this.pristine) {\n this.pristine = false;\n }\n this.checkData(value.data, flags);\n const shouldValidate = !flags.noValidate ||\n flags.fromIFrame ||\n (flags.fromSubmission && this.rootPristine && this.pristine && flags.changed);\n const errors = shouldValidate\n ? this.validate(value.data, Object.assign(Object.assign({}, flags), { process: \"change\" }))\n : [];\n value.isValid = errors.length === 0;\n this.loading = false;\n if (this.submitted) {\n // show server errors while they are not cleaned/fixed\n const nonComponentServerErrors = lodash_1.default.filter(this.serverErrors || [], (err) => !err.component && !err.path);\n this.showErrors(nonComponentServerErrors.length ? nonComponentServerErrors : errors);\n }\n // See if we need to save the draft of the form.\n if (modified && this.options.saveDraft) {\n this.triggerSaveDraft();\n }\n if (!flags || !flags.noEmit) {\n this.emit(\"change\", value, flags, modified);\n isChangeEventEmitted = true;\n }\n // The form is initialized after the first change event occurs.\n if (isChangeEventEmitted && !this.initialized) {\n this.emit(\"initialized\");\n this.initialized = true;\n }\n }\n /**\n * Send a delete request to the server.\n * @returns {Promise} - The promise that is triggered when the delete is complete.\n */\n deleteSubmission() {\n return this.formio.deleteSubmission().then(() => {\n this.emit(\"submissionDeleted\", this.submission);\n this.resetValue();\n });\n }\n /**\n * Cancels the submission.\n * @param {boolean} noconfirm - Whether or not to confirm the cancellation.\n * @alias reset\n * @returns {boolean} - TRUE means the submission was cancelled, FALSE otherwise.\n */\n cancel(noconfirm) {\n const shouldReset = this.hook(\"beforeCancel\", true);\n if (shouldReset && (noconfirm || confirm(this.t(\"confirmCancel\")))) {\n this.resetValue();\n return true;\n }\n else {\n this.emit(\"cancelSubmit\");\n return false;\n }\n }\n setMetadata(submission) {\n // Add in metadata about client submitting the form\n submission.metadata = submission.metadata || {};\n lodash_1.default.defaults(submission.metadata, {\n timezone: lodash_1.default.get(this, \"_submission.metadata.timezone\", (0, utils_1.currentTimezone)()),\n offset: parseInt(lodash_1.default.get(this, \"_submission.metadata.offset\", (0, moment_1.default)().utcOffset()), 10),\n origin: document.location.origin,\n referrer: document.referrer,\n browserName: navigator.appName,\n userAgent: navigator.userAgent,\n pathName: window.location.pathname,\n onLine: navigator.onLine,\n });\n }\n submitForm(options = {}) {\n this.clearServerErrors();\n return new Promise((resolve, reject) => {\n // Read-only forms should never submit.\n if (this.options.readOnly) {\n return resolve({\n submission: this.submission,\n saved: false,\n });\n }\n const submission = (0, utils_1.fastCloneDeep)(this.submission || {});\n this.setMetadata(submission);\n submission.state = options.state || submission.state || \"submitted\";\n const isDraft = submission.state === \"draft\";\n this.hook(\"beforeSubmit\", Object.assign(Object.assign({}, submission), { component: options.component }), (err, data) => {\n var _a;\n if (err) {\n return reject(err);\n }\n submission._vnote = data && data._vnote ? data._vnote : \"\";\n try {\n if (!isDraft && !options.noValidate) {\n if (!submission.data) {\n return reject(\"Invalid Submission\");\n }\n const errors = this.validate(submission.data, {\n dirty: true,\n silentCheck: false,\n process: \"submit\",\n });\n if (errors.length ||\n ((_a = options.beforeSubmitResults) === null || _a === void 0 ? void 0 : _a.some((result) => result.status === \"rejected\"))) {\n return reject(errors);\n }\n }\n }\n catch (err) {\n console.error(err);\n }\n this.everyComponent((comp) => {\n if (submission._vnote && comp.type === \"form\" && comp.component.reference) {\n lodash_1.default.get(submission.data, comp.path, {})._vnote = submission._vnote;\n }\n const { persistent } = comp.component;\n if (persistent === \"client-only\") {\n lodash_1.default.unset(submission.data, comp.path);\n }\n });\n this.hook(\"customValidation\", Object.assign(Object.assign({}, submission), { component: options.component }), (err) => {\n if (err) {\n // If string is returned, cast to object.\n if (typeof err === \"string\") {\n err = {\n message: err,\n };\n }\n // Ensure err is an array.\n err = Array.isArray(err) ? err : [err];\n return reject(err);\n }\n this.loading = true;\n // Use the form action to submit the form if available.\n if (this._form && this._form.action) {\n const method = submission.data._id &&\n this._form.action.includes(submission.data._id)\n ? \"PUT\"\n : \"POST\";\n return Formio_1.Formio.makeStaticRequest(this._form.action, method, submission, this.formio ? this.formio.options : {})\n .then((result) => resolve({\n submission: result,\n saved: true,\n }))\n .catch((error) => {\n this.setServerErrors(error);\n return reject(error);\n });\n }\n const submitFormio = this.formio;\n if (this.nosubmit || !submitFormio) {\n return resolve({\n submission,\n saved: false,\n });\n }\n // If this is an actionUrl, then make sure to save the action and not the submission.\n const submitMethod = submitFormio.actionUrl\n ? \"saveAction\"\n : \"saveSubmission\";\n submitFormio[submitMethod](submission)\n .then((result) => resolve({\n submission: result,\n saved: true,\n }))\n .catch((error) => {\n this.setServerErrors(error);\n return reject(error);\n });\n });\n });\n });\n }\n setServerErrors(error) {\n if (error.details) {\n this.serverErrors = error.details\n .filter((err) => (err.level ? err.level === \"error\" : err))\n .map((err) => {\n err.fromServer = true;\n return err;\n });\n }\n else if (typeof error === \"string\") {\n this.serverErrors = [{ fromServer: true, level: \"error\", message: error }];\n }\n }\n executeSubmit(options) {\n this.submitted = true;\n this.submitting = true;\n return this.submitForm(options)\n .then(({ submission, saved }) => this.onSubmit(submission, saved))\n .then((results) => {\n this.submissionInProcess = false;\n return results;\n })\n .catch((err) => {\n this.submissionInProcess = false;\n return Promise.reject(this.onSubmissionError(err));\n });\n }\n clearServerErrors() {\n var _a;\n (_a = this.serverErrors) === null || _a === void 0 ? void 0 : _a.forEach((error) => {\n if (error.path) {\n const pathArray = (0, utils_1.getArrayFromComponentPath)(error.path);\n const component = this.getComponent(pathArray, lodash_1.default.identity, error.formattedKeyOrPath);\n if (component) {\n component.serverErrors = [];\n }\n }\n });\n this.serverErrors = [];\n }\n /**\n * Submits the form.\n * @example\n * import Webform from '@formio/js/Webform';\n * let form = new Webform(document.getElementById('formio'));\n * form.src = 'https://examples.form.io/example';\n * form.submission = {data: {\n * firstName: 'Joe',\n * lastName: 'Smith',\n * email: 'joe@example.com'\n * }};\n * form.submit().then((submission) => {\n * console.log(submission);\n * });\n * @param {boolean} before - If this submission occured from the before handlers.\n * @param {any} options - The options to use when submitting this form.\n * @returns {Promise} - A promise when the form is done submitting.\n */\n submit(before = false, options = {}) {\n this.submissionInProcess = true;\n if (!before) {\n return this.beforeSubmit(options).then(() => this.executeSubmit(options));\n }\n else {\n return this.executeSubmit(options);\n }\n }\n submitUrl(URL, headers) {\n if (!URL) {\n return console.warn(\"Missing URL argument\");\n }\n const submission = this.submission || {};\n const API_URL = URL;\n const settings = {\n method: \"POST\",\n headers: {},\n };\n if (headers && headers.length > 0) {\n headers.map((e) => {\n if (e.header !== \"\" && e.value !== \"\") {\n settings.headers[e.header] = this.interpolate(e.value, submission);\n }\n });\n }\n if (API_URL && settings) {\n Formio_1.Formio.makeStaticRequest(API_URL, settings.method, submission, {\n headers: settings.headers,\n })\n .then(() => {\n this.emit(\"requestDone\");\n this.setAlert(\"success\", \"<p> Success </p>\");\n })\n .catch((e) => {\n const message = `${e.statusText ? e.statusText : \"\"} ${e.status ? e.status : e}`;\n this.emit(\"error\", message);\n console.error(message);\n this.setAlert(\"danger\", `<p> ${message} </p>`);\n return Promise.reject(this.onSubmissionError(e));\n });\n }\n else {\n this.emit(\"error\", \"You should add a URL to this button.\");\n this.setAlert(\"warning\", \"You should add a URL to this button.\");\n return console.warn(\"You should add a URL to this button.\");\n }\n }\n triggerCaptcha() {\n if (!this || !this.components) {\n return;\n }\n const captchaComponent = [];\n (0, formUtils_1.eachComponent)(this.components, (component) => {\n if (/^(re)?captcha$/.test(component.type) && component.component.eventType === 'formLoad') {\n captchaComponent.push(component);\n }\n });\n if (captchaComponent.length > 0) {\n captchaComponent[0].verify(`${this.form.name ? this.form.name : 'form'}Load`);\n }\n }\n set nosubmit(value) {\n this._nosubmit = !!value;\n this.emit(\"nosubmit\", this._nosubmit);\n }\n get nosubmit() {\n return this._nosubmit || false;\n }\n get conditions() {\n var _a, _b;\n return (_b = (_a = this.schema.settings) === null || _a === void 0 ? void 0 : _a.conditions) !== null && _b !== void 0 ? _b : [];\n }\n get variables() {\n var _a, _b;\n return (_b = (_a = this.schema.settings) === null || _a === void 0 ? void 0 : _a.variables) !== null && _b !== void 0 ? _b : [];\n }\n}\nexports[\"default\"] = Webform;\nWebform.setBaseUrl = Formio_1.Formio.setBaseUrl;\nWebform.setApiUrl = Formio_1.Formio.setApiUrl;\nWebform.setAppUrl = Formio_1.Formio.setAppUrl;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Webform.js?");
|
5528
5528
|
|
5529
5529
|
/***/ }),
|
5530
5530
|
|
@@ -5799,7 +5799,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5799
5799
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5800
5800
|
|
5801
5801
|
"use strict";
|
5802
|
-
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.AddressComponentMode = void 0;\nconst autocompleter_1 = __importDefault(__webpack_require__(/*! autocompleter */ \"./node_modules/autocompleter/autocomplete.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst GoogleAddressProvider_1 = __webpack_require__(/*! ../../providers/address/GoogleAddressProvider */ \"./lib/cjs/providers/address/GoogleAddressProvider.js\");\nconst Field_1 = __importDefault(__webpack_require__(/*! ../_classes/field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst NestedComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nested/NestedComponent */ \"./lib/cjs/components/_classes/nested/NestedComponent.js\"));\nconst Container_1 = __importDefault(__webpack_require__(/*! ../container/Container */ \"./lib/cjs/components/container/Container.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nexports.AddressComponentMode = {\n Autocomplete: 'autocomplete',\n Manual: 'manual',\n};\nconst RemoveValueIconHiddenClass = 'address-autocomplete-remove-value-icon--hidden';\nconst ChildConditional = 'show = _.get(instance, \\'parent.manualMode\\', false);';\nclass AddressComponent extends Container_1.default {\n static schema(...extend) {\n return Container_1.default.schema({\n type: 'address',\n label: 'Address',\n key: 'address',\n switchToManualModeLabel: 'Can\\'t find address? Switch to manual mode.',\n provider: '',\n providerOptions: {},\n manualModeViewString: '',\n hideLabel: false,\n disableClearIcon: false,\n enableManualMode: false,\n components: [\n {\n label: 'Address 1',\n tableView: false,\n key: 'address1',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Address 2',\n tableView: false,\n key: 'address2',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'City',\n tableView: false,\n key: 'city',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'State',\n tableView: false,\n key: 'state',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Country',\n tableView: false,\n key: 'country',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Zip Code',\n tableView: false,\n key: 'zip',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n ],\n }, ...extend);\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n static get builderInfo() {\n return {\n title: 'Address',\n group: 'advanced',\n icon: 'home',\n documentation: '/userguide/form-building/advanced-components#address',\n weight: 35,\n schema: AddressComponent.schema(),\n };\n }\n mergeSchema(component = {}) {\n let { defaultSchema } = this;\n if (component.components) {\n defaultSchema = lodash_1.default.omit(defaultSchema, 'components');\n }\n return lodash_1.default.defaultsDeep(component, defaultSchema);\n }\n init() {\n this.components = this.components || [];\n if (this.builderMode || this.manualModeEnabled) {\n NestedComponent_1.default.prototype.addComponents.call(this, this.manualMode ? this.address : {});\n }\n Field_1.default.prototype.init.call(this);\n if (!this.builderMode) {\n if (this.component.provider) {\n const { provider, providerOptions, } = this.component;\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n else if (this.component.map) {\n // Fallback to legacy version where Google Maps was the only provider.\n this.component.provider = GoogleAddressProvider_1.GoogleAddressProvider.name;\n this.component.providerOptions = this.component.providerOptions || {};\n const { map, provider, providerOptions, } = this.component;\n const { key, region, } = map;\n if (key) {\n lodash_1.default.set(providerOptions, 'params.key', key);\n }\n if (region) {\n lodash_1.default.set(providerOptions, 'params.region', region);\n }\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n }\n }\n initializeProvider(provider, options = {}) {\n const url = this.interpolate(options.url);\n const Provider = Formio_1.Formio.Providers.getProvider('address', provider);\n return new Provider(Object.assign(Object.assign({}, options), { url }));\n }\n get emptyValue() {\n return this.manualModeEnabled\n ? {\n mode: exports.AddressComponentMode.Autocomplete,\n address: {},\n }\n : {};\n }\n get mode() {\n var _a, _b;\n if (!this.manualModeEnabled) {\n return exports.AddressComponentMode.Autocomplete;\n }\n return (_b = (_a = this.dataValue) === null || _a === void 0 ? void 0 : _a.mode) !== null && _b !== void 0 ? _b : exports.AddressComponentMode.Autocomplete;\n }\n set mode(value) {\n if (this.manualModeEnabled) {\n this.dataValue.mode = value;\n }\n }\n get autocompleteMode() {\n return this.mode === exports.AddressComponentMode.Autocomplete;\n }\n get manualMode() {\n return this.mode === exports.AddressComponentMode.Manual;\n }\n get manualModeEnabled() {\n return !this.isMultiple && Boolean(this.component.enableManualMode);\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n component.data = this.address;\n component.setValue(component.dataValue, {\n noUpdateEvent: true,\n });\n });\n }\n get isMultiple() {\n return Boolean(this.component.multiple);\n }\n get address() {\n if (this.isMultiple) {\n return lodash_1.default.isArray(this.dataValue) ? this.dataValue : [this.dataValue];\n }\n // Manual mode is not implementing for multiple value\n return (this.manualModeEnabled && this.dataValue) ? this.dataValue.address : this.dataValue;\n }\n set address(value) {\n if (this.manualModeEnabled && !this.isMultiple) {\n this.dataValue.address = value;\n }\n else {\n this.dataValue = value;\n }\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (this.isMultiple) {\n defaultValue = lodash_1.default.isArray(defaultValue) ? defaultValue : [defaultValue];\n }\n return defaultValue;\n }\n get defaultSchema() {\n return AddressComponent.schema();\n }\n isValueInLegacyFormat(value) {\n return value && !value.mode;\n }\n normalizeValue(value) {\n return (this.manualModeEnabled && this.isValueInLegacyFormat(value))\n ? {\n mode: exports.AddressComponentMode.Autocomplete,\n address: value,\n }\n : value;\n }\n setValue(value, flags = {}) {\n const changed = Field_1.default.prototype.setValue.call(this, value, flags);\n if (this.manualMode) {\n this.restoreComponentsContext();\n }\n if (changed || !lodash_1.default.isEmpty(value) && flags.fromSubmission) {\n this.redraw();\n }\n return changed;\n }\n static get modeSwitcherRef() {\n return 'modeSwitcher';\n }\n static get removeValueIconRef() {\n return 'removeValueIcon';\n }\n static get searchInputRef() {\n return 'searchInput';\n }\n static get addRowButtonRef() {\n return 'addButton';\n }\n static get removeRowButtonRef() {\n return 'removeRow';\n }\n get modeSwitcher() {\n return this.refs\n ? (this.refs[AddressComponent.modeSwitcherRef] || null)\n : null;\n }\n get removeValueIcon() {\n return this.refs\n ? (this.refs[AddressComponent.removeValueIconRef] || null)\n : null;\n }\n get searchInput() {\n return this.refs\n ? (this.refs[AddressComponent.searchInputRef] || null)\n : null;\n }\n get addRowButton() {\n return this.refs\n ? (this.refs[AddressComponent.addRowButtonRef] || null)\n : null;\n }\n get removeRowButton() {\n return this.refs\n ? (this.refs[AddressComponent.removeRowButtonRef] || null)\n : null;\n }\n get searchInputAttributes() {\n const attr = {\n name: this.options.name,\n type: 'text',\n class: 'form-control',\n lang: this.options.language,\n tabindex: this.component.tabindex || 0,\n };\n if (this.component.placeholder) {\n attr.placeholder = this.t(this.component.placeholder), { _userInput: true };\n }\n if (this.disabled) {\n attr.disabled = 'disabled';\n }\n lodash_1.default.defaults(attr, this.component.attributes);\n return attr;\n }\n get templateName() {\n return 'address';\n }\n get gridTemplateName() {\n return 'multiValueTable';\n }\n get rowTemplateName() {\n return 'multiValueRow';\n }\n get hasChildren() {\n return !this.isMultiple && (this.builderMode || this.manualModeEnabled);\n }\n get addAnother() {\n return this.t(this.component.addAnother || 'Add Another');\n }\n renderElement(value) {\n return this.renderTemplate(this.templateName, {\n children: this.hasChildren ? this.renderComponents() : '',\n nestedKey: this.nestedKey,\n inputAttributes: this.searchInputAttributes,\n ref: {\n modeSwitcher: AddressComponent.modeSwitcherRef,\n removeValueIcon: AddressComponent.removeValueIconRef,\n searchInput: AddressComponent.searchInputRef,\n },\n displayValue: this.getDisplayValue(value),\n mode: {\n autocomplete: this.autocompleteMode,\n manual: this.manualMode,\n },\n });\n }\n renderRow(value, index) {\n return this.renderTemplate(this.rowTemplateName, {\n index,\n disabled: this.disabled,\n element: `${this.renderElement(value, index)}`,\n });\n }\n renderGrid() {\n return this.renderTemplate(this.gridTemplateName, {\n rows: this.address.map(this.renderRow.bind(this)).join(''),\n disabled: this.disabled,\n addAnother: this.addAnother,\n });\n }\n render() {\n if (this.isMultiple) {\n return super.render(this.renderGrid());\n }\n return super.render(this.renderElement());\n }\n onSelectAddress(address, element, index) {\n if (this.isMultiple) {\n this.address[index] = address;\n this.address = [...this.address];\n }\n else {\n this.address = address;\n }\n this.triggerChange({\n modified: true,\n });\n if (element) {\n element.value = this.getDisplayValue(this.isMultiple ? this.address[index] : this.address);\n }\n this.updateRemoveIcon(index);\n }\n addRow() {\n this.address = this.address.concat(this.emptyValue);\n super.redraw();\n }\n attach(element) {\n const result = ((this.builderMode || this.manualMode) ? super.attach : Field_1.default.prototype.attach).call(this, element);\n if (!this.builderMode) {\n if (!this.provider && this.component.provider) {\n const { provider, providerOptions, } = this.component;\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n }\n this.loadRefs(element, {\n [AddressComponent.addRowButtonRef]: 'single',\n [AddressComponent.modeSwitcherRef]: 'single',\n [AddressComponent.removeRowButtonRef]: 'multiple',\n [AddressComponent.removeValueIconRef]: 'multiple',\n [AddressComponent.searchInputRef]: 'multiple',\n });\n this.searchInput.forEach((element, index) => {\n if (!this.builderMode && element && this.provider) {\n if (this.component.provider === 'google') {\n this.provider.attachAutocomplete(element, index, this.onSelectAddress.bind(this));\n }\n else {\n (0, autocompleter_1.default)({\n input: element,\n debounceWaitMs: 300,\n fetch: (text, update) => {\n const query = text;\n this.provider.search(query).then(update);\n },\n render: (address) => {\n const div = this.ce('div');\n div.textContent = this.getDisplayValue(address);\n return div;\n },\n onSelect: (address) => {\n this.onSelectAddress(address, element, index);\n },\n });\n }\n this.addEventListener(element, 'blur', () => {\n if (!element) {\n return;\n }\n if (element.value) {\n element.value = this.getDisplayValue(this.isMultiple ? this.address[index] : this.address);\n }\n });\n this.addEventListener(element, 'keyup', () => {\n if (!element) {\n return;\n }\n if (!element.value) {\n this.clearAddress(element, index);\n }\n });\n }\n });\n if (this.addRowButton) {\n this.addEventListener(this.addRowButton, 'click', event => {\n event.preventDefault();\n this.addRow();\n });\n }\n this.removeRowButton.forEach((removeRowButton, index) => {\n this.addEventListener(removeRowButton, 'click', event => {\n event.preventDefault();\n this.removeValue(index);\n });\n });\n if (this.modeSwitcher) {\n this.addEventListener(this.modeSwitcher, 'change', () => {\n if (!this.modeSwitcher) {\n return;\n }\n this.dataValue = this.emptyValue;\n this.mode = this.modeSwitcher.checked\n ? exports.AddressComponentMode.Manual\n : exports.AddressComponentMode.Autocomplete;\n if (!this.builderMode) {\n if (this.manualMode) {\n this.restoreComponentsContext();\n }\n this.triggerChange({\n modified: true,\n });\n }\n this.redraw();\n });\n }\n if (!this.builderMode) {\n this.removeValueIcon.forEach((removeValueIcon, index) => {\n this.updateRemoveIcon(index);\n const removeValueHandler = () => {\n var _a;\n const searchInput = (_a = this.searchInput) === null || _a === void 0 ? void 0 : _a[index];\n this.clearAddress(searchInput, index);\n if (searchInput) {\n searchInput.focus();\n }\n };\n this.addEventListener(removeValueIcon, 'click', removeValueHandler);\n this.addEventListener(removeValueIcon, 'keydown', ({ key }) => {\n if (key === 'Enter') {\n removeValueHandler();\n }\n });\n });\n lodash_1.default.each(this.refs.searchInput || [], el => this.addFocusBlurEvents(el));\n }\n return result;\n }\n addChildComponent(component) {\n component.customConditional = ChildConditional;\n }\n redraw() {\n const modeSwitcherInFocus = (this.modeSwitcher && (document.activeElement === this.modeSwitcher));\n return super.redraw()\n .then((result) => {\n if (modeSwitcherInFocus && this.modeSwitcher) {\n this.modeSwitcher.focus();\n }\n return result;\n });\n }\n clearAddress(element, index) {\n var _a;\n if (!this.isEmpty()) {\n this.triggerChange();\n }\n if ((_a = this.address) === null || _a === void 0 ? void 0 : _a[index]) {\n this.address[index] = this.emptyValue;\n }\n else {\n this.address = this.emptyValue;\n }\n if (element) {\n element.value = '';\n }\n this.updateRemoveIcon(index);\n }\n getDisplayValue(value = this.address) {\n return (this.provider && !this.manualMode)\n ? this.provider.getDisplayValue(value)\n : '';\n }\n validateMultiple() {\n return this.isMultiple;\n }\n updateRemoveIcon(index) {\n var _a;\n const removeValueIcon = (_a = this.removeValueIcon) === null || _a === void 0 ? void 0 : _a[index];\n if (removeValueIcon) {\n const value = this.isMultiple ? this.address[index] : this.address;\n if (this.isEmpty(value) || this.disabled) {\n this.addClass(removeValueIcon, RemoveValueIconHiddenClass);\n }\n else {\n this.removeClass(removeValueIcon, RemoveValueIconHiddenClass);\n }\n }\n }\n getValueAsString(value, options) {\n if (!value) {\n return '';\n }\n const normalizedValue = this.normalizeValue(value);\n const { address, mode, } = (this.manualModeEnabled\n ? normalizedValue\n : {\n address: normalizedValue,\n mode: exports.AddressComponentMode.Autocomplete,\n });\n const valueInManualMode = (mode === exports.AddressComponentMode.Manual);\n if (this.provider && !valueInManualMode) {\n return this.getDisplayValue(address);\n }\n if (valueInManualMode) {\n if (this.component.manualModeViewString) {\n return this.interpolate(this.component.manualModeViewString, {\n address,\n data: this.data,\n component: this.component,\n });\n }\n return this.getComponents()\n .filter((component) => component.hasValue(address))\n .map((component) => [component, lodash_1.default.get(address, component.key)])\n .filter(([component, componentValue]) => !component.isEmpty(componentValue))\n .map(([component, componentValue]) => component.getValueAsString(componentValue, options))\n .join(', ');\n }\n return super.getValueAsString(address, options);\n }\n focus() {\n if (this.searchInput && this.searchInput[0]) {\n this.searchInput[0].focus();\n }\n }\n}\nexports[\"default\"] = AddressComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/address/Address.js?");
|
5802
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.AddressComponentMode = void 0;\nconst autocompleter_1 = __importDefault(__webpack_require__(/*! autocompleter */ \"./node_modules/autocompleter/autocomplete.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst Formio_1 = __webpack_require__(/*! ../../Formio */ \"./lib/cjs/Formio.js\");\nconst GoogleAddressProvider_1 = __webpack_require__(/*! ../../providers/address/GoogleAddressProvider */ \"./lib/cjs/providers/address/GoogleAddressProvider.js\");\nconst Field_1 = __importDefault(__webpack_require__(/*! ../_classes/field/Field */ \"./lib/cjs/components/_classes/field/Field.js\"));\nconst NestedComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nested/NestedComponent */ \"./lib/cjs/components/_classes/nested/NestedComponent.js\"));\nconst Container_1 = __importDefault(__webpack_require__(/*! ../container/Container */ \"./lib/cjs/components/container/Container.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nexports.AddressComponentMode = {\n Autocomplete: 'autocomplete',\n Manual: 'manual',\n};\nconst RemoveValueIconHiddenClass = 'address-autocomplete-remove-value-icon--hidden';\nconst ChildConditional = 'show = _.get(instance, \\'parent.manualMode\\', false);';\nclass AddressComponent extends Container_1.default {\n static schema(...extend) {\n return Container_1.default.schema({\n type: 'address',\n label: 'Address',\n key: 'address',\n switchToManualModeLabel: 'Can\\'t find address? Switch to manual mode.',\n provider: '',\n providerOptions: {},\n manualModeViewString: '',\n hideLabel: false,\n disableClearIcon: false,\n enableManualMode: false,\n components: [\n {\n label: 'Address 1',\n tableView: false,\n key: 'address1',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Address 2',\n tableView: false,\n key: 'address2',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'City',\n tableView: false,\n key: 'city',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'State',\n tableView: false,\n key: 'state',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Country',\n tableView: false,\n key: 'country',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n {\n label: 'Zip Code',\n tableView: false,\n key: 'zip',\n type: 'textfield',\n input: true,\n customConditional: ChildConditional,\n },\n ],\n }, ...extend);\n }\n static savedValueTypes(schema) {\n schema = schema || {};\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n static get builderInfo() {\n return {\n title: 'Address',\n group: 'advanced',\n icon: 'home',\n documentation: '/userguide/form-building/advanced-components#address',\n weight: 35,\n schema: AddressComponent.schema(),\n };\n }\n mergeSchema(component = {}) {\n let { defaultSchema } = this;\n if (component.components) {\n defaultSchema = lodash_1.default.omit(defaultSchema, 'components');\n }\n return lodash_1.default.defaultsDeep(component, defaultSchema);\n }\n init() {\n this.components = this.components || [];\n if (this.builderMode || this.manualModeEnabled) {\n NestedComponent_1.default.prototype.addComponents.call(this, this.manualMode ? this.address : {});\n }\n Field_1.default.prototype.init.call(this);\n if (!this.builderMode) {\n if (this.component.provider) {\n const { provider, providerOptions, } = this.component;\n if (lodash_1.default.get(providerOptions, 'params.subscriptionKey')) {\n lodash_1.default.set(providerOptions, \"params['subscription-key']\", lodash_1.default.get(providerOptions, 'params.subscriptionKey'));\n lodash_1.default.unset(providerOptions, 'params.subscriptionKey');\n }\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n else if (this.component.map) {\n // Fallback to legacy version where Google Maps was the only provider.\n this.component.provider = GoogleAddressProvider_1.GoogleAddressProvider.name;\n this.component.providerOptions = this.component.providerOptions || {};\n const { map, provider, providerOptions, } = this.component;\n const { key, region, } = map;\n if (key) {\n lodash_1.default.set(providerOptions, 'params.key', key);\n }\n if (region) {\n lodash_1.default.set(providerOptions, 'params.region', region);\n }\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n }\n }\n initializeProvider(provider, options = {}) {\n const url = this.interpolate(options.url);\n const Provider = Formio_1.Formio.Providers.getProvider('address', provider);\n return new Provider(Object.assign(Object.assign({}, options), { url }));\n }\n get emptyValue() {\n return this.manualModeEnabled\n ? {\n mode: exports.AddressComponentMode.Autocomplete,\n address: {},\n }\n : {};\n }\n get mode() {\n var _a, _b;\n if (!this.manualModeEnabled) {\n return exports.AddressComponentMode.Autocomplete;\n }\n return (_b = (_a = this.dataValue) === null || _a === void 0 ? void 0 : _a.mode) !== null && _b !== void 0 ? _b : exports.AddressComponentMode.Autocomplete;\n }\n set mode(value) {\n if (this.manualModeEnabled) {\n this.dataValue.mode = value;\n }\n }\n get autocompleteMode() {\n return this.mode === exports.AddressComponentMode.Autocomplete;\n }\n get manualMode() {\n return this.mode === exports.AddressComponentMode.Manual;\n }\n get manualModeEnabled() {\n return !this.isMultiple && Boolean(this.component.enableManualMode);\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n component.data = this.address;\n component.setValue(component.dataValue, {\n noUpdateEvent: true,\n });\n });\n }\n get isMultiple() {\n return Boolean(this.component.multiple);\n }\n get address() {\n if (this.isMultiple) {\n return lodash_1.default.isArray(this.dataValue) ? this.dataValue : [this.dataValue];\n }\n // Manual mode is not implementing for multiple value\n return (this.manualModeEnabled && this.dataValue) ? this.dataValue.address : this.dataValue;\n }\n set address(value) {\n if (this.manualModeEnabled && !this.isMultiple) {\n this.dataValue.address = value;\n }\n else {\n this.dataValue = value;\n }\n }\n get defaultValue() {\n let defaultValue = super.defaultValue;\n if (this.isMultiple) {\n defaultValue = lodash_1.default.isArray(defaultValue) ? defaultValue : [defaultValue];\n }\n return defaultValue;\n }\n get defaultSchema() {\n return AddressComponent.schema();\n }\n isValueInLegacyFormat(value) {\n return value && !value.mode;\n }\n normalizeValue(value) {\n return (this.manualModeEnabled && this.isValueInLegacyFormat(value))\n ? {\n mode: exports.AddressComponentMode.Autocomplete,\n address: value,\n }\n : value;\n }\n setValue(value, flags = {}) {\n const changed = Field_1.default.prototype.setValue.call(this, value, flags);\n if (this.manualMode) {\n this.restoreComponentsContext();\n }\n if (changed || !lodash_1.default.isEmpty(value) && flags.fromSubmission) {\n this.redraw();\n }\n return changed;\n }\n static get modeSwitcherRef() {\n return 'modeSwitcher';\n }\n static get removeValueIconRef() {\n return 'removeValueIcon';\n }\n static get searchInputRef() {\n return 'searchInput';\n }\n static get addRowButtonRef() {\n return 'addButton';\n }\n static get removeRowButtonRef() {\n return 'removeRow';\n }\n get modeSwitcher() {\n return this.refs\n ? (this.refs[AddressComponent.modeSwitcherRef] || null)\n : null;\n }\n get removeValueIcon() {\n return this.refs\n ? (this.refs[AddressComponent.removeValueIconRef] || null)\n : null;\n }\n get searchInput() {\n return this.refs\n ? (this.refs[AddressComponent.searchInputRef] || null)\n : null;\n }\n get addRowButton() {\n return this.refs\n ? (this.refs[AddressComponent.addRowButtonRef] || null)\n : null;\n }\n get removeRowButton() {\n return this.refs\n ? (this.refs[AddressComponent.removeRowButtonRef] || null)\n : null;\n }\n get searchInputAttributes() {\n const attr = {\n name: this.options.name,\n type: 'text',\n class: 'form-control',\n lang: this.options.language,\n tabindex: this.component.tabindex || 0,\n };\n if (this.component.placeholder) {\n attr.placeholder = this.t(this.component.placeholder), { _userInput: true };\n }\n if (this.disabled) {\n attr.disabled = 'disabled';\n }\n lodash_1.default.defaults(attr, this.component.attributes);\n return attr;\n }\n get templateName() {\n return 'address';\n }\n get gridTemplateName() {\n return 'multiValueTable';\n }\n get rowTemplateName() {\n return 'multiValueRow';\n }\n get hasChildren() {\n return !this.isMultiple && (this.builderMode || this.manualModeEnabled);\n }\n get addAnother() {\n return this.t(this.component.addAnother || 'Add Another');\n }\n renderElement(value) {\n return this.renderTemplate(this.templateName, {\n children: this.hasChildren ? this.renderComponents() : '',\n nestedKey: this.nestedKey,\n inputAttributes: this.searchInputAttributes,\n ref: {\n modeSwitcher: AddressComponent.modeSwitcherRef,\n removeValueIcon: AddressComponent.removeValueIconRef,\n searchInput: AddressComponent.searchInputRef,\n },\n displayValue: this.getDisplayValue(value),\n mode: {\n autocomplete: this.autocompleteMode,\n manual: this.manualMode,\n },\n });\n }\n renderRow(value, index) {\n return this.renderTemplate(this.rowTemplateName, {\n index,\n disabled: this.disabled,\n element: `${this.renderElement(value, index)}`,\n });\n }\n renderGrid() {\n return this.renderTemplate(this.gridTemplateName, {\n rows: this.address.map(this.renderRow.bind(this)).join(''),\n disabled: this.disabled,\n addAnother: this.addAnother,\n });\n }\n render() {\n if (this.isMultiple) {\n return super.render(this.renderGrid());\n }\n return super.render(this.renderElement());\n }\n onSelectAddress(address, element, index) {\n if (this.isMultiple) {\n this.address[index] = address;\n this.address = [...this.address];\n }\n else {\n this.address = address;\n }\n this.triggerChange({\n modified: true,\n });\n if (element) {\n element.value = this.getDisplayValue(this.isMultiple ? this.address[index] : this.address);\n }\n this.updateRemoveIcon(index);\n }\n addRow() {\n this.address = this.address.concat(this.emptyValue);\n super.redraw();\n }\n attach(element) {\n const result = ((this.builderMode || this.manualMode) ? super.attach : Field_1.default.prototype.attach).call(this, element);\n if (!this.builderMode) {\n if (!this.provider && this.component.provider) {\n const { provider, providerOptions, } = this.component;\n this.provider = this.initializeProvider(provider, providerOptions);\n }\n }\n this.loadRefs(element, {\n [AddressComponent.addRowButtonRef]: 'single',\n [AddressComponent.modeSwitcherRef]: 'single',\n [AddressComponent.removeRowButtonRef]: 'multiple',\n [AddressComponent.removeValueIconRef]: 'multiple',\n [AddressComponent.searchInputRef]: 'multiple',\n });\n this.searchInput.forEach((element, index) => {\n if (!this.builderMode && element && this.provider) {\n if (this.component.provider === 'google') {\n this.provider.attachAutocomplete(element, index, this.onSelectAddress.bind(this));\n }\n else {\n (0, autocompleter_1.default)({\n input: element,\n debounceWaitMs: 300,\n fetch: (text, update) => {\n const query = text;\n this.provider.search(query).then(update);\n },\n render: (address) => {\n const div = this.ce('div');\n div.textContent = this.getDisplayValue(address);\n return div;\n },\n onSelect: (address) => {\n this.onSelectAddress(address, element, index);\n },\n });\n }\n this.addEventListener(element, 'blur', () => {\n if (!element) {\n return;\n }\n if (element.value) {\n element.value = this.getDisplayValue(this.isMultiple ? this.address[index] : this.address);\n }\n });\n this.addEventListener(element, 'keyup', () => {\n if (!element) {\n return;\n }\n if (!element.value) {\n this.clearAddress(element, index);\n }\n });\n }\n });\n if (this.addRowButton) {\n this.addEventListener(this.addRowButton, 'click', event => {\n event.preventDefault();\n this.addRow();\n });\n }\n this.removeRowButton.forEach((removeRowButton, index) => {\n this.addEventListener(removeRowButton, 'click', event => {\n event.preventDefault();\n this.removeValue(index);\n });\n });\n if (this.modeSwitcher) {\n this.addEventListener(this.modeSwitcher, 'change', () => {\n if (!this.modeSwitcher) {\n return;\n }\n this.dataValue = this.emptyValue;\n this.mode = this.modeSwitcher.checked\n ? exports.AddressComponentMode.Manual\n : exports.AddressComponentMode.Autocomplete;\n if (!this.builderMode) {\n if (this.manualMode) {\n this.restoreComponentsContext();\n }\n this.triggerChange({\n modified: true,\n });\n }\n this.redraw();\n });\n }\n if (!this.builderMode) {\n this.removeValueIcon.forEach((removeValueIcon, index) => {\n this.updateRemoveIcon(index);\n const removeValueHandler = () => {\n var _a;\n const searchInput = (_a = this.searchInput) === null || _a === void 0 ? void 0 : _a[index];\n this.clearAddress(searchInput, index);\n if (searchInput) {\n searchInput.focus();\n }\n };\n this.addEventListener(removeValueIcon, 'click', removeValueHandler);\n this.addEventListener(removeValueIcon, 'keydown', ({ key }) => {\n if (key === 'Enter') {\n removeValueHandler();\n }\n });\n });\n lodash_1.default.each(this.refs.searchInput || [], el => this.addFocusBlurEvents(el));\n }\n return result;\n }\n addChildComponent(component) {\n component.customConditional = ChildConditional;\n }\n redraw() {\n const modeSwitcherInFocus = (this.modeSwitcher && (document.activeElement === this.modeSwitcher));\n return super.redraw()\n .then((result) => {\n if (modeSwitcherInFocus && this.modeSwitcher) {\n this.modeSwitcher.focus();\n }\n return result;\n });\n }\n clearAddress(element, index) {\n var _a;\n if (!this.isEmpty()) {\n this.triggerChange();\n }\n if ((_a = this.address) === null || _a === void 0 ? void 0 : _a[index]) {\n this.address[index] = this.emptyValue;\n }\n else {\n this.address = this.emptyValue;\n }\n if (element) {\n element.value = '';\n }\n this.updateRemoveIcon(index);\n }\n getDisplayValue(value = this.address) {\n return (this.provider && !this.manualMode)\n ? this.provider.getDisplayValue(value)\n : '';\n }\n validateMultiple() {\n return this.isMultiple;\n }\n updateRemoveIcon(index) {\n var _a;\n const removeValueIcon = (_a = this.removeValueIcon) === null || _a === void 0 ? void 0 : _a[index];\n if (removeValueIcon) {\n const value = this.isMultiple ? this.address[index] : this.address;\n if (this.isEmpty(value) || this.disabled) {\n this.addClass(removeValueIcon, RemoveValueIconHiddenClass);\n }\n else {\n this.removeClass(removeValueIcon, RemoveValueIconHiddenClass);\n }\n }\n }\n getValueAsString(value, options) {\n if (!value) {\n return '';\n }\n const normalizedValue = this.normalizeValue(value);\n const { address, mode, } = (this.manualModeEnabled\n ? normalizedValue\n : {\n address: normalizedValue,\n mode: exports.AddressComponentMode.Autocomplete,\n });\n const valueInManualMode = (mode === exports.AddressComponentMode.Manual);\n if (this.provider && !valueInManualMode) {\n return this.getDisplayValue(address);\n }\n if (valueInManualMode) {\n if (this.component.manualModeViewString) {\n return this.interpolate(this.component.manualModeViewString, {\n address,\n data: this.data,\n component: this.component,\n });\n }\n return this.getComponents()\n .filter((component) => component.hasValue(address))\n .map((component) => [component, lodash_1.default.get(address, component.key)])\n .filter(([component, componentValue]) => !component.isEmpty(componentValue))\n .map(([component, componentValue]) => component.getValueAsString(componentValue, options))\n .join(', ');\n }\n return super.getValueAsString(address, options);\n }\n focus() {\n if (this.searchInput && this.searchInput[0]) {\n this.searchInput[0].focus();\n }\n }\n}\nexports[\"default\"] = AddressComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/address/Address.js?");
|
5803
5803
|
|
5804
5804
|
/***/ }),
|
5805
5805
|
|
@@ -5887,7 +5887,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5887
5887
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5888
5888
|
|
5889
5889
|
"use strict";
|
5890
|
-
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 NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Components_1 = __webpack_require__(/*! ../Components */ \"./lib/cjs/components/Components.js\");\nclass DataGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n label: 'Data Grid',\n key: 'dataGrid',\n type: 'datagrid',\n clearOnHide: true,\n input: true,\n tree: true,\n components: []\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Grid',\n icon: 'th',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-grid',\n showPreview: false,\n weight: 30,\n schema: DataGridComponent.schema()\n };\n }\n constructor(...args) {\n super(...args);\n this.type = 'datagrid';\n this.tabIndex = 0;\n }\n init() {\n this.components = this.components || [];\n // Add new values based on minLength.\n this.rows = [];\n this.columns = [...this.component.components];\n if (this.initRows || !lodash_1.default.isEqual(this.dataValue, this.emptyValue)) {\n this.createRows(true);\n }\n this.visibleColumns = {};\n this.prevHasAddButton = this.hasAddButton();\n this.checkColumns();\n }\n get dataValue() {\n const dataValue = super.dataValue;\n if (!dataValue || !Array.isArray(dataValue)) {\n return this.emptyValue;\n }\n return dataValue;\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultSchema() {\n return DataGridComponent.schema();\n }\n get initEmpty() {\n return this.component.initEmpty || this.component.noFirstRow;\n }\n get initRows() {\n return this.builderMode || this.path === 'defaultValue' || !this.initEmpty;\n }\n get emptyValue() {\n return this.initEmpty ? [] : [{}];\n }\n get addAnotherPosition() {\n return lodash_1.default.get(this.component, 'addAnotherPosition', 'bottom');\n }\n get minLength() {\n if (this.hasRowGroups()) {\n return lodash_1.default.sum(this.getGroupSizes());\n }\n else {\n return lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n }\n get defaultValue() {\n const isBuilderMode = this.builderMode;\n const isEmptyInit = this.initEmpty;\n // Ensure we have one and only one row in builder mode.\n if (isBuilderMode || (isEmptyInit && !this.dataValue.length)) {\n return isEmptyInit && !isBuilderMode ? [] : [{}];\n }\n const value = super.defaultValue;\n let defaultValue;\n if (Array.isArray(value)) {\n defaultValue = value;\n }\n else if (value && (typeof value === 'object')) {\n defaultValue = [value];\n }\n else {\n defaultValue = this.emptyValue;\n }\n for (let dIndex = defaultValue.length; dIndex < this.minLength; dIndex++) {\n defaultValue.push({});\n }\n return defaultValue;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n lodash_1.default.each(this.refs[`${this.datagridKey}-addRow`], (button) => {\n button.disabled = disabled;\n });\n lodash_1.default.each(this.refs[`${this.datagridKey}-removeRow`], (button) => {\n button.disabled = disabled;\n });\n }\n get disabled() {\n return super.disabled;\n }\n get datagridKey() {\n return `datagrid-${this.key}`;\n }\n get allowReorder() {\n return !this.options.readOnly && lodash_1.default.get(this.component, 'reorder', false);\n }\n get iteratableRows() {\n return this.rows.map((row, index) => ({\n components: row,\n data: this.dataValue[index],\n }));\n }\n isEmpty(value = this.dataValue) {\n var _a;\n const isEmpty = super.isEmpty(value);\n if ((_a = this.components) === null || _a === void 0 ? void 0 : _a.length) {\n return this.components.reduce((isEmpty, component) => {\n return isEmpty && component.isEmpty();\n }, true);\n }\n return isEmpty;\n }\n /**\n * Split rows into chunks.\n * @param {number[]} groups - array of numbers where each item is size of group\n * @param {Array<T>} rows - rows collection\n * @returns {Array<T[]>} - The chunked rows\n */\n getRowChunks(groups, rows) {\n const [, chunks] = groups.reduce(([startIndex, acc], size) => {\n const endIndex = startIndex + size;\n return [endIndex, [...acc, [startIndex, endIndex]]];\n }, [0, []]);\n return chunks.map(range => lodash_1.default.slice(rows, ...range));\n }\n /**\n * Create groups object.\n * Each key in object represents index of first row in group.\n * @returns {object} - The groups object.\n */\n getGroups() {\n const groups = lodash_1.default.get(this.component, 'rowGroups', []);\n const sizes = lodash_1.default.map(groups, 'numberOfRows').slice(0, -1);\n const indexes = sizes.reduce((groupIndexes, size) => {\n const last = groupIndexes[groupIndexes.length - 1];\n return groupIndexes.concat(last + size);\n }, [0]);\n return groups.reduce((gidxs, group, idx) => {\n return Object.assign(Object.assign({}, gidxs), { [indexes[idx]]: group });\n }, {});\n }\n /**\n * Get group sizes.\n * @returns {number[]} - The array of group sizes.\n */\n getGroupSizes() {\n return lodash_1.default.map(lodash_1.default.get(this.component, 'rowGroups', []), 'numberOfRows');\n }\n hasRowGroups() {\n return lodash_1.default.get(this, 'component.enableRowGroups', false) && !this.builderMode;\n }\n totalRowsNumber(groups) {\n return lodash_1.default.sum(lodash_1.default.map(groups, 'numberOfRows'));\n }\n setStaticValue(n) {\n this.dataValue = lodash_1.default.range(n).map(() => ({}));\n }\n hasExtraColumn() {\n return (this.hasRemoveButtons() || this.canAddColumn);\n }\n hasRemoveButtons() {\n return !this.builderMode && !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n hasTopSubmit() {\n return this.hasAddButton() && ['top', 'both'].includes(this.addAnotherPosition);\n }\n hasBottomSubmit() {\n return this.hasAddButton() && ['bottom', 'both'].includes(this.addAnotherPosition);\n }\n get canAddColumn() {\n return this.builderMode && !this.options.design;\n }\n render() {\n const columns = this.getColumns();\n let columnExtra = 0;\n const hasRemoveButtons = this.hasRemoveButtons();\n if (this.component.reorder) {\n columnExtra++;\n }\n if (hasRemoveButtons) {\n columnExtra++;\n }\n if (this.canAddColumn) {\n columnExtra++;\n }\n const colWidth = Math.floor(12 / (columns.length + columnExtra));\n return super.render(this.renderTemplate('datagrid', {\n rows: this.getRows(),\n columns: columns,\n groups: this.hasRowGroups() ? this.getGroups() : [],\n visibleColumns: this.visibleColumns,\n hasToggle: lodash_1.default.get(this, 'component.groupToggle', false),\n hasHeader: this.hasHeader(),\n hasExtraColumn: this.hasExtraColumn(),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons,\n hasTopSubmit: this.hasTopSubmit(),\n hasBottomSubmit: this.hasBottomSubmit(),\n hasGroups: this.hasRowGroups(),\n numColumns: columns.length + (this.hasExtraColumn() ? 1 : 0),\n datagridKey: this.datagridKey,\n allowReorder: this.allowReorder,\n builder: this.builderMode,\n canAddColumn: this.canAddColumn,\n tabIndex: this.tabIndex,\n placeholder: this.renderTemplate('builderPlaceholder', {\n position: this.componentComponents.length,\n }),\n colWidth: colWidth.toString()\n }));\n }\n getRows() {\n return this.rows.map(row => {\n const components = {};\n lodash_1.default.each(row, (col, key) => {\n components[key] = col.render();\n });\n return components;\n });\n }\n getColumns() {\n return this.columns.filter((comp) => {\n return (!this.visibleColumns.hasOwnProperty(comp.key) || this.visibleColumns[comp.key]);\n });\n }\n hasHeader() {\n return this.component.components.reduce((hasHeader, col) => {\n // If any of the components has a title and it isn't hidden, display the header.\n return hasHeader || ((col.label || col.title) && !col.hideLabel);\n }, false);\n }\n loadRefs(element, refs) {\n super.loadRefs(element, refs);\n if (refs['messageContainer'] === 'single') {\n const container = lodash_1.default.last(element.querySelectorAll(`[${this._referenceAttributeName}=messageContainer]`));\n this.refs['messageContainer'] = container || this.refs['messageContainer'];\n }\n }\n attach(element) {\n this.loadRefs(element, {\n [`${this.datagridKey}-row`]: 'multiple',\n [`${this.datagridKey}-tbody`]: 'single',\n [`${this.datagridKey}-addRow`]: 'multiple',\n [`${this.datagridKey}-removeRow`]: 'multiple',\n [`${this.datagridKey}-group-header`]: 'multiple',\n [this.datagridKey]: 'multiple',\n 'messageContainer': 'single'\n });\n if (this.allowReorder) {\n this.refs[`${this.datagridKey}-row`].forEach((row, index) => {\n row.dragInfo = { index };\n });\n if (this.root.dragulaLib) {\n this.dragula = this.root.dragulaLib([this.refs[`${this.datagridKey}-tbody`]], {\n moves: (_draggedElement, _oldParent, clickedElement) => {\n const clickedElementKey = clickedElement.getAttribute('data-key');\n const oldParentKey = _oldParent.getAttribute('data-key');\n //Check if the clicked button belongs to that container, if false, it belongs to the nested container\n if (oldParentKey === clickedElementKey) {\n return clickedElement.classList.contains('formio-drag-button');\n }\n }\n }).on('drop', this.onReorder.bind(this));\n this.dragula.on('cloned', (el, original) => {\n if (el && el.children && original && original.children) {\n lodash_1.default.each(original.children, (child, index) => {\n const styles = getComputedStyle(child, null);\n if (styles.cssText !== '') {\n el.children[index].style.cssText = styles.cssText;\n }\n else {\n const cssText = Object.values(styles).reduce((css, propertyName) => {\n return `${css}${propertyName}:${styles.getPropertyValue(propertyName)};`;\n }, '');\n el.children[index].style.cssText = cssText;\n }\n });\n }\n });\n }\n }\n this.refs[`${this.datagridKey}-addRow`].forEach((addButton) => {\n this.addEventListener(addButton, 'click', this.addRow.bind(this));\n });\n this.refs[`${this.datagridKey}-removeRow`].forEach((removeButton, index) => {\n this.addEventListener(removeButton, 'click', this.removeRow.bind(this, index));\n });\n if (this.hasRowGroups()) {\n this.refs.chunks = this.getRowChunks(this.getGroupSizes(), this.refs[`${this.datagridKey}-row`]);\n this.refs[`${this.datagridKey}-group-header`].forEach((header, index) => {\n this.addEventListener(header, 'click', () => this.toggleGroup(header, index));\n });\n }\n const columns = this.getColumns();\n const rowLength = columns.length;\n this.rows.forEach((row, rowIndex) => {\n let columnIndex = 0;\n columns.forEach((col) => {\n this.attachComponents(this.refs[this.datagridKey][(rowIndex * rowLength) + columnIndex], [this.rows[rowIndex][col.key]], this.getComponentsContainer());\n columnIndex++;\n });\n });\n return super.attach(element);\n }\n getComponentsContainer() {\n return this.component.components;\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = sibling ? sibling.dragInfo.index : this.dataValue.length;\n const movedBelow = newPosition > oldPosition;\n const dataValue = (0, utils_1.fastCloneDeep)(this.dataValue);\n const draggedRowData = dataValue[oldPosition];\n //insert element at new position\n dataValue.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n dataValue.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n //need to re-build rows to re-calculate indexes and other indexed fields for component instance (like rows for ex.)\n this.setValue(dataValue, { isReordered: true });\n this.rebuild();\n }\n focusOnNewRowElement(row) {\n Object.keys(row).find((key) => {\n const element = row[key].element;\n if (element) {\n const focusableElements = (0, utils_1.getFocusableElements)(element);\n if (focusableElements && focusableElements[0]) {\n focusableElements[0].focus();\n return true;\n }\n }\n return false;\n });\n }\n addRow() {\n const index = this.rows.length;\n // Handle length mismatch between rows and dataValue\n if (this.dataValue.length === index) {\n this.dataValue.push({});\n }\n let row;\n const dataValue = this.dataValue;\n const defaultValue = this.defaultValue;\n if (this.initEmpty && defaultValue[index]) {\n row = defaultValue[index];\n dataValue[index] = row;\n }\n else {\n row = dataValue[index];\n }\n this.rows[index] = this.createRowComponents(row, index);\n this.emit('dataGridAddRow', {\n component: this.component,\n row\n });\n this.checkConditions();\n this.triggerChange();\n this.redraw().then(() => {\n this.focusOnNewRowElement(this.rows[index]);\n });\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n var _a;\n if ((_a = component.options) === null || _a === void 0 ? void 0 : _a.name) {\n const newName = `[${this.key}][${rowIndex}]`;\n component.options.name = component.options.name.replace(`[${this.key}][${component.rowIndex}]`, newName);\n }\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n component.path = Components_1.Components.getComponentPath(component);\n });\n }\n updateRowsComponents(rowIndex) {\n this.rows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(Object.values(row), rowIndex + index);\n });\n }\n removeRow(index) {\n const makeEmpty = index === 0 && this.rows.length === 1;\n const flags = { isReordered: !makeEmpty, resetValue: makeEmpty };\n this.splice(index, flags);\n this.emit('dataGridDeleteRow', { index });\n const [row] = this.rows.splice(index, 1);\n this.removeRowComponents(row);\n this.updateRowsComponents(index);\n this.setValue(this.dataValue, flags);\n this.redraw();\n }\n removeRowComponents(row) {\n lodash_1.default.each(row, (component) => this.removeComponent(component));\n }\n getRowValues() {\n return this.dataValue;\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n component.data = rowData;\n });\n }\n createRows(init, rebuild) {\n let added = false;\n const rowValues = this.getRowValues();\n // Create any missing rows.\n rowValues.forEach((row, index) => {\n if (!rebuild && this.rows[index]) {\n this.setRowComponentsData(index, row);\n }\n else {\n if (this.rows[index]) {\n this.removeRowComponents(this.rows[index]);\n }\n this.rows[index] = this.createRowComponents(row, index);\n added = true;\n }\n });\n // Delete any extra rows.\n const removedRows = this.rows.splice(rowValues.length);\n const removed = !!removedRows.length;\n // Delete components of extra rows (to make sure that this.components contain only components of exisiting rows)\n if (removed) {\n removedRows.forEach(row => this.removeRowComponents(row));\n }\n if (!init && (added || removed)) {\n this.redraw();\n }\n return added;\n }\n createRowComponents(row, rowIndex) {\n const components = {};\n this.tabIndex = 0;\n this.component.components.map((col, colIndex) => {\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n let columnComponent;\n if (this.builderMode) {\n col.id = col.id + rowIndex;\n columnComponent = col;\n }\n else {\n columnComponent = Object.assign(Object.assign({}, col), { id: (col.id + rowIndex) });\n }\n const component = this.createComponent(columnComponent, options, row);\n component.parentDisabled = !!this.disabled;\n component.rowIndex = rowIndex;\n component.inDataGrid = true;\n if (columnComponent.tabindex &&\n parseInt(columnComponent.tabindex) > this.tabIndex) {\n this.tabIndex = parseInt(columnComponent.tabindex);\n }\n components[col.key] = component;\n });\n return components;\n }\n checkColumns(data, flags = {}) {\n data = data || this.rootValue;\n let show = false;\n if (!this.rows || !this.rows.length) {\n return { rebuild: false, show: false };\n }\n if (this.builderMode) {\n return { rebuild: false, show: true };\n }\n const visibility = {};\n let logicRebuild = false;\n const dataValue = this.dataValue;\n this.rows.forEach((row, rowIndex) => {\n lodash_1.default.each(row, (col, key) => {\n if (col && (typeof col.checkConditions === 'function')) {\n const firstRowCheck = visibility[key] === undefined;\n visibility[key] = !!visibility[key] ||\n (col.checkConditions(data, flags, dataValue[rowIndex]) && col.type !== 'hidden');\n if (col.component.logic && firstRowCheck) {\n const compIndex = lodash_1.default.findIndex(this.columns, ['key', key]);\n const equalColumns = lodash_1.default.isEqualWith(this.columns[compIndex], col.component, (col1, col2, key) => {\n // Don't compare columns by their auto-generated ids.\n if (key === 'id') {\n return true;\n }\n });\n if (!equalColumns) {\n logicRebuild = true;\n this.columns[compIndex] = col.component;\n }\n }\n }\n });\n });\n const rebuild = !lodash_1.default.isEqual(visibility, this.visibleColumns) || logicRebuild;\n lodash_1.default.each(visibility, (col) => {\n show |= col;\n });\n this.visibleColumns = visibility;\n return { rebuild, show };\n }\n checkComponentConditions(data, flags, row) {\n const isVisible = this.visible;\n // If table isn't visible, don't bother calculating columns.\n if (!super.checkComponentConditions(data, flags, row)) {\n return false;\n }\n const { rebuild, show } = this.checkColumns(data, flags);\n // Check if a rebuild is needed or the visibility changes.\n if (rebuild || !isVisible) {\n this.createRows(false, rebuild);\n }\n // Return if this table should show.\n return show;\n }\n setValue(value, flags = {}) {\n if (!value) {\n this.dataValue = this.defaultValue;\n this.createRows();\n return false;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n this.createRows();\n value = [{}];\n }\n }\n // Make sure we always have at least one row.\n // NOTE: Removing this will break \"Public Configurations\" in portal. ;)\n if (value && !value.length && !this.initEmpty) {\n value.push({});\n }\n const isSettingSubmission = flags.fromSubmission && !lodash_1.default.isEqual(value, this.emptyValue);\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n if (this.initRows || isSettingSubmission ||\n (Array.isArray(this.dataValue) && this.dataValue.length !== this.rows.length)) {\n if (!this.createRows() && changed) {\n this.redraw();\n }\n }\n if (this.componentModal && isSettingSubmission) {\n this.componentModal.setValue(value);\n }\n this.rows.forEach((row, rowIndex) => {\n if (value.length <= rowIndex) {\n return;\n }\n lodash_1.default.each(row, (col) => {\n col.rowIndex = rowIndex;\n this.setNestedValue(col, value[rowIndex], flags);\n });\n });\n this.updateOnChange(flags, changed);\n return changed;\n }\n restoreComponentsContext() {\n this.rows.forEach((row, index) => lodash_1.default.forIn(row, (component) => component.data = this.dataValue[index]));\n }\n getComponent(path, fn) {\n path = Array.isArray(path) ? path : [path];\n const [key, ...remainingPath] = path;\n let result = [];\n if (lodash_1.default.isNumber(key) && remainingPath.length) {\n const compKey = remainingPath.pop();\n result = this.rows[key][compKey];\n // If the component is inside a Layout Component, try to find it among all the row's components\n if (!result) {\n Object.entries(this.rows[key]).forEach(([, comp]) => {\n if ('getComponent' in comp) {\n const possibleResult = comp.getComponent([compKey], fn);\n if (possibleResult) {\n result = possibleResult;\n }\n }\n });\n }\n if (result && lodash_1.default.isFunction(fn)) {\n fn(result, this.getComponents());\n }\n if (remainingPath.length && 'getComponent' in result) {\n return result.getComponent(remainingPath, fn);\n }\n return result;\n }\n if (!lodash_1.default.isString(key)) {\n return result;\n }\n this.everyComponent((component, components) => {\n if (component.component.key === key) {\n let comp = component;\n if (remainingPath.length > 0 && 'getComponent' in component) {\n comp = component.getComponent(remainingPath, fn);\n }\n else if (fn) {\n fn(component, components);\n }\n result = result.concat(comp);\n }\n });\n return result.length > 0 ? result : null;\n }\n toggleGroup(element, index) {\n element.classList.toggle('collapsed');\n lodash_1.default.each(this.refs.chunks[index], row => {\n row.classList.toggle('hidden');\n });\n }\n}\nexports[\"default\"] = DataGridComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datagrid/DataGrid.js?");
|
5890
|
+
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 NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst Components_1 = __importDefault(__webpack_require__(/*! ../Components */ \"./lib/cjs/components/Components.js\"));\nconst dragula_1 = __importDefault(__webpack_require__(/*! dragula */ \"./node_modules/dragula/dragula.js\"));\nclass DataGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n label: 'Data Grid',\n key: 'dataGrid',\n type: 'datagrid',\n clearOnHide: true,\n input: true,\n tree: true,\n components: []\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Grid',\n icon: 'th',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-grid',\n showPreview: false,\n weight: 30,\n schema: DataGridComponent.schema()\n };\n }\n constructor(...args) {\n super(...args);\n this.type = 'datagrid';\n this.tabIndex = 0;\n }\n init() {\n this.components = this.components || [];\n // Add new values based on minLength.\n this.rows = [];\n this.columns = [...this.component.components];\n if (this.initRows || !lodash_1.default.isEqual(this.dataValue, this.emptyValue)) {\n this.createRows(true);\n }\n this.visibleColumns = {};\n this.prevHasAddButton = this.hasAddButton();\n this.checkColumns();\n }\n get dataValue() {\n const dataValue = super.dataValue;\n if (!dataValue || !Array.isArray(dataValue)) {\n return this.emptyValue;\n }\n return dataValue;\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultSchema() {\n return DataGridComponent.schema();\n }\n get initEmpty() {\n return this.component.initEmpty || this.component.noFirstRow;\n }\n get initRows() {\n return this.builderMode || this.path === 'defaultValue' || !this.initEmpty;\n }\n get emptyValue() {\n return this.initEmpty ? [] : [{}];\n }\n get addAnotherPosition() {\n return lodash_1.default.get(this.component, 'addAnotherPosition', 'bottom');\n }\n get minLength() {\n if (this.hasRowGroups()) {\n return lodash_1.default.sum(this.getGroupSizes());\n }\n else {\n return lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n }\n get defaultValue() {\n const isBuilderMode = this.builderMode;\n const isEmptyInit = this.initEmpty;\n // Ensure we have one and only one row in builder mode.\n if (isBuilderMode || (isEmptyInit && !this.dataValue.length)) {\n return isEmptyInit && !isBuilderMode ? [] : [{}];\n }\n const value = super.defaultValue;\n let defaultValue;\n if (Array.isArray(value)) {\n defaultValue = value;\n }\n else if (value && (typeof value === 'object')) {\n defaultValue = [value];\n }\n else {\n defaultValue = this.emptyValue;\n }\n for (let dIndex = defaultValue.length; dIndex < this.minLength; dIndex++) {\n defaultValue.push({});\n }\n return defaultValue;\n }\n set disabled(disabled) {\n super.disabled = disabled;\n lodash_1.default.each(this.refs[`${this.datagridKey}-addRow`], (button) => {\n button.disabled = disabled;\n });\n lodash_1.default.each(this.refs[`${this.datagridKey}-removeRow`], (button) => {\n button.disabled = disabled;\n });\n }\n get disabled() {\n return super.disabled;\n }\n get datagridKey() {\n return `datagrid-${this.key}`;\n }\n get allowReorder() {\n return !this.options.readOnly && lodash_1.default.get(this.component, 'reorder', false);\n }\n get iteratableRows() {\n return this.rows.map((row, index) => ({\n components: row,\n data: this.dataValue[index],\n }));\n }\n isEmpty(value = this.dataValue) {\n var _a;\n const isEmpty = super.isEmpty(value);\n if ((_a = this.components) === null || _a === void 0 ? void 0 : _a.length) {\n return this.components.reduce((isEmpty, component) => {\n return isEmpty && component.isEmpty();\n }, true);\n }\n return isEmpty;\n }\n /**\n * Split rows into chunks.\n * @param {number[]} groups - array of numbers where each item is size of group\n * @param {Array<T>} rows - rows collection\n * @returns {Array<T[]>} - The chunked rows\n */\n getRowChunks(groups, rows) {\n const [, chunks] = groups.reduce(([startIndex, acc], size) => {\n const endIndex = startIndex + size;\n return [endIndex, [...acc, [startIndex, endIndex]]];\n }, [0, []]);\n return chunks.map(range => lodash_1.default.slice(rows, ...range));\n }\n /**\n * Create groups object.\n * Each key in object represents index of first row in group.\n * @returns {object} - The groups object.\n */\n getGroups() {\n const groups = lodash_1.default.get(this.component, 'rowGroups', []);\n const sizes = lodash_1.default.map(groups, 'numberOfRows').slice(0, -1);\n const indexes = sizes.reduce((groupIndexes, size) => {\n const last = groupIndexes[groupIndexes.length - 1];\n return groupIndexes.concat(last + size);\n }, [0]);\n return groups.reduce((gidxs, group, idx) => {\n return Object.assign(Object.assign({}, gidxs), { [indexes[idx]]: group });\n }, {});\n }\n /**\n * Get group sizes.\n * @returns {number[]} - The array of group sizes.\n */\n getGroupSizes() {\n return lodash_1.default.map(lodash_1.default.get(this.component, 'rowGroups', []), 'numberOfRows');\n }\n hasRowGroups() {\n return lodash_1.default.get(this, 'component.enableRowGroups', false) && !this.builderMode;\n }\n totalRowsNumber(groups) {\n return lodash_1.default.sum(lodash_1.default.map(groups, 'numberOfRows'));\n }\n setStaticValue(n) {\n this.dataValue = lodash_1.default.range(n).map(() => ({}));\n }\n hasExtraColumn() {\n return (this.hasRemoveButtons() || this.canAddColumn);\n }\n hasRemoveButtons() {\n return !this.builderMode && !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n hasTopSubmit() {\n return this.hasAddButton() && ['top', 'both'].includes(this.addAnotherPosition);\n }\n hasBottomSubmit() {\n return this.hasAddButton() && ['bottom', 'both'].includes(this.addAnotherPosition);\n }\n get canAddColumn() {\n return this.builderMode && !this.options.design;\n }\n render() {\n const columns = this.getColumns();\n let columnExtra = 0;\n const hasRemoveButtons = this.hasRemoveButtons();\n if (this.component.reorder) {\n columnExtra++;\n }\n if (hasRemoveButtons) {\n columnExtra++;\n }\n if (this.canAddColumn) {\n columnExtra++;\n }\n const colWidth = Math.floor(12 / (columns.length + columnExtra));\n return super.render(this.renderTemplate('datagrid', {\n rows: this.getRows(),\n columns: columns,\n groups: this.hasRowGroups() ? this.getGroups() : [],\n visibleColumns: this.visibleColumns,\n hasToggle: lodash_1.default.get(this, 'component.groupToggle', false),\n hasHeader: this.hasHeader(),\n hasExtraColumn: this.hasExtraColumn(),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons,\n hasTopSubmit: this.hasTopSubmit(),\n hasBottomSubmit: this.hasBottomSubmit(),\n hasGroups: this.hasRowGroups(),\n numColumns: columns.length + (this.hasExtraColumn() ? 1 : 0),\n datagridKey: this.datagridKey,\n allowReorder: this.allowReorder,\n builder: this.builderMode,\n canAddColumn: this.canAddColumn,\n tabIndex: this.tabIndex,\n placeholder: this.renderTemplate('builderPlaceholder', {\n position: this.componentComponents.length,\n }),\n colWidth: colWidth.toString()\n }));\n }\n getRows() {\n return this.rows.map(row => {\n const components = {};\n lodash_1.default.each(row, (col, key) => {\n components[key] = col.render();\n });\n return components;\n });\n }\n getColumns() {\n return this.columns.filter((comp) => {\n return (!this.visibleColumns.hasOwnProperty(comp.key) || this.visibleColumns[comp.key]);\n });\n }\n hasHeader() {\n return this.component.components.reduce((hasHeader, col) => {\n // If any of the components has a title and it isn't hidden, display the header.\n return hasHeader || ((col.label || col.title) && !col.hideLabel);\n }, false);\n }\n loadRefs(element, refs) {\n super.loadRefs(element, refs);\n if (refs['messageContainer'] === 'single') {\n const container = lodash_1.default.last(element.querySelectorAll(`[${this._referenceAttributeName}=messageContainer]`));\n this.refs['messageContainer'] = container || this.refs['messageContainer'];\n }\n }\n attach(element) {\n this.loadRefs(element, {\n [`${this.datagridKey}-row`]: 'multiple',\n [`${this.datagridKey}-tbody`]: 'single',\n [`${this.datagridKey}-addRow`]: 'multiple',\n [`${this.datagridKey}-removeRow`]: 'multiple',\n [`${this.datagridKey}-group-header`]: 'multiple',\n [this.datagridKey]: 'multiple',\n 'messageContainer': 'single'\n });\n if (this.allowReorder) {\n this.refs[`${this.datagridKey}-row`].forEach((row, index) => {\n row.dragInfo = { index };\n });\n this.dragula = (0, dragula_1.default)([this.refs[`${this.datagridKey}-tbody`]], {\n moves: (_draggedElement, _oldParent, clickedElement) => {\n const clickedElementKey = clickedElement.getAttribute('data-key');\n const oldParentKey = _oldParent.getAttribute('data-key');\n //Check if the clicked button belongs to that container, if false, it belongs to the nested container\n if (oldParentKey === clickedElementKey) {\n return clickedElement.classList.contains('formio-drag-button');\n }\n }\n }).on('drop', this.onReorder.bind(this));\n this.dragula.on('cloned', (el, original) => {\n if (el && el.children && original && original.children) {\n lodash_1.default.each(original.children, (child, index) => {\n const styles = getComputedStyle(child, null);\n if (styles.cssText !== '') {\n el.children[index].style.cssText = styles.cssText;\n }\n else {\n const cssText = Object.values(styles).reduce((css, propertyName) => {\n return `${css}${propertyName}:${styles.getPropertyValue(propertyName)};`;\n }, '');\n el.children[index].style.cssText = cssText;\n }\n });\n }\n });\n }\n this.refs[`${this.datagridKey}-addRow`].forEach((addButton) => {\n this.addEventListener(addButton, 'click', this.addRow.bind(this));\n });\n this.refs[`${this.datagridKey}-removeRow`].forEach((removeButton, index) => {\n this.addEventListener(removeButton, 'click', this.removeRow.bind(this, index));\n });\n if (this.hasRowGroups()) {\n this.refs.chunks = this.getRowChunks(this.getGroupSizes(), this.refs[`${this.datagridKey}-row`]);\n this.refs[`${this.datagridKey}-group-header`].forEach((header, index) => {\n this.addEventListener(header, 'click', () => this.toggleGroup(header, index));\n });\n }\n const columns = this.getColumns();\n const rowLength = columns.length;\n this.rows.forEach((row, rowIndex) => {\n let columnIndex = 0;\n columns.forEach((col) => {\n this.attachComponents(this.refs[this.datagridKey][(rowIndex * rowLength) + columnIndex], [this.rows[rowIndex][col.key]], this.getComponentsContainer());\n columnIndex++;\n });\n });\n return super.attach(element);\n }\n getComponentsContainer() {\n return this.component.components;\n }\n /**\n * Reorder values in array based on the old and new position\n * @param {any} valuesArr - An array of values.\n * @param {number} oldPosition - The index of the value in array before reordering.\n * @param {number} newPosition - The index of the value in array after reordering.\n * @param {boolean|any} movedBelow - Whether or not the value is moved below.\n * @returns {void}\n */\n reorderValues(valuesArr, oldPosition, newPosition, movedBelow) {\n if (!lodash_1.default.isArray(valuesArr) || lodash_1.default.isEmpty(valuesArr)) {\n return;\n }\n const draggedRowData = valuesArr[oldPosition];\n //insert element at new position\n valuesArr.splice(newPosition, 0, draggedRowData);\n //remove element from old position (if was moved above, after insertion it's at +1 index)\n valuesArr.splice(movedBelow ? oldPosition : oldPosition + 1, 1);\n }\n onReorder(element, _target, _source, sibling) {\n if (!element.dragInfo || (sibling && !sibling.dragInfo)) {\n console.warn('There is no Drag Info available for either dragged or sibling element');\n return;\n }\n const oldPosition = element.dragInfo.index;\n //should drop at next sibling position; no next sibling means drop to last position\n const newPosition = sibling ? sibling.dragInfo.index : this.dataValue.length;\n const movedBelow = newPosition > oldPosition;\n const dataValue = (0, utils_1.fastCloneDeep)(this.dataValue);\n this.reorderValues(dataValue, oldPosition, newPosition, movedBelow);\n //reorder select data\n this.reorderValues(lodash_1.default.get(this.root, `submission.metadata.selectData.${this.path}`, []), oldPosition, newPosition, movedBelow);\n //need to re-build rows to re-calculate indexes and other indexed fields for component instance (like rows for ex.)\n this.setValue(dataValue, { isReordered: true });\n this.rebuild();\n }\n focusOnNewRowElement(row) {\n Object.keys(row).find((key) => {\n const element = row[key].element;\n if (element) {\n const focusableElements = (0, utils_1.getFocusableElements)(element);\n if (focusableElements && focusableElements[0]) {\n focusableElements[0].focus();\n return true;\n }\n }\n return false;\n });\n }\n addRow() {\n const index = this.rows.length;\n // Handle length mismatch between rows and dataValue\n if (this.dataValue.length === index) {\n this.dataValue.push({});\n }\n let row;\n const dataValue = this.dataValue;\n const defaultValue = this.defaultValue;\n if (this.initEmpty && defaultValue[index]) {\n row = defaultValue[index];\n dataValue[index] = row;\n }\n else {\n row = dataValue[index];\n }\n this.rows[index] = this.createRowComponents(row, index);\n this.emit('dataGridAddRow', {\n component: this.component,\n row\n });\n this.checkConditions();\n this.triggerChange();\n this.redraw().then(() => {\n this.focusOnNewRowElement(this.rows[index]);\n });\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n var _a;\n if ((_a = component.options) === null || _a === void 0 ? void 0 : _a.name) {\n const newName = `[${this.key}][${rowIndex}]`;\n component.options.name = component.options.name.replace(`[${this.key}][${component.rowIndex}]`, newName);\n }\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n component.path = Components_1.default.getComponentPath(component);\n });\n }\n updateRowsComponents(rowIndex) {\n this.rows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(Object.values(row), rowIndex + index);\n });\n }\n removeRow(index) {\n const makeEmpty = index === 0 && this.rows.length === 1;\n const flags = { isReordered: !makeEmpty, resetValue: makeEmpty };\n this.splice(index, flags);\n this.emit('dataGridDeleteRow', { index });\n const [row] = this.rows.splice(index, 1);\n this.removeRowComponents(row);\n this.updateRowsComponents(index);\n this.setValue(this.dataValue, flags);\n this.redraw();\n }\n removeRowComponents(row) {\n lodash_1.default.each(row, (component) => this.removeComponent(component));\n }\n getRowValues() {\n return this.dataValue;\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n component.data = rowData;\n });\n }\n createRows(init, rebuild) {\n let added = false;\n const rowValues = this.getRowValues();\n // Create any missing rows.\n rowValues.forEach((row, index) => {\n if (!rebuild && this.rows[index]) {\n this.setRowComponentsData(index, row);\n }\n else {\n if (this.rows[index]) {\n this.removeRowComponents(this.rows[index]);\n }\n this.rows[index] = this.createRowComponents(row, index);\n added = true;\n }\n });\n // Delete any extra rows.\n const removedRows = this.rows.splice(rowValues.length);\n const removed = !!removedRows.length;\n // Delete components of extra rows (to make sure that this.components contain only components of exisiting rows)\n if (removed) {\n removedRows.forEach(row => this.removeRowComponents(row));\n }\n if (!init && (added || removed)) {\n this.redraw();\n }\n return added;\n }\n createRowComponents(row, rowIndex) {\n const components = {};\n this.tabIndex = 0;\n this.component.components.map((col, colIndex) => {\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n let columnComponent;\n if (this.builderMode) {\n col.id = col.id + rowIndex;\n columnComponent = col;\n }\n else {\n columnComponent = Object.assign(Object.assign({}, col), { id: (col.id + rowIndex) });\n }\n const component = this.createComponent(columnComponent, options, row);\n component.parentDisabled = !!this.disabled;\n component.rowIndex = rowIndex;\n component.inDataGrid = true;\n if (columnComponent.tabindex &&\n parseInt(columnComponent.tabindex) > this.tabIndex) {\n this.tabIndex = parseInt(columnComponent.tabindex);\n }\n components[col.key] = component;\n });\n return components;\n }\n checkColumns(data, flags = {}) {\n data = data || this.rootValue;\n let show = false;\n if (!this.rows || !this.rows.length) {\n return { rebuild: false, show: false };\n }\n if (this.builderMode) {\n return { rebuild: false, show: true };\n }\n const visibility = {};\n let logicRebuild = false;\n const dataValue = this.dataValue;\n this.rows.forEach((row, rowIndex) => {\n lodash_1.default.each(row, (col, key) => {\n if (col && (typeof col.checkConditions === 'function')) {\n const firstRowCheck = visibility[key] === undefined;\n visibility[key] = !!visibility[key] ||\n (col.checkConditions(data, flags, dataValue[rowIndex]) && col.type !== 'hidden');\n if (col.component.logic && firstRowCheck) {\n const compIndex = lodash_1.default.findIndex(this.columns, ['key', key]);\n const equalColumns = lodash_1.default.isEqualWith(this.columns[compIndex], col.component, (col1, col2, key) => {\n // Don't compare columns by their auto-generated ids.\n if (key === 'id') {\n return true;\n }\n });\n if (!equalColumns) {\n logicRebuild = true;\n this.columns[compIndex] = col.component;\n }\n }\n }\n });\n });\n const rebuild = !lodash_1.default.isEqual(visibility, this.visibleColumns) || logicRebuild;\n lodash_1.default.each(visibility, (col) => {\n show |= col;\n });\n this.visibleColumns = visibility;\n return { rebuild, show };\n }\n checkComponentConditions(data, flags, row) {\n const isVisible = this.visible;\n // If table isn't visible, don't bother calculating columns.\n if (!super.checkComponentConditions(data, flags, row)) {\n return false;\n }\n const { rebuild, show } = this.checkColumns(data, flags);\n // Check if a rebuild is needed or the visibility changes.\n if (rebuild || !isVisible) {\n this.createRows(false, rebuild);\n }\n // Return if this table should show.\n return show;\n }\n setValue(value, flags = {}) {\n if (!value) {\n this.dataValue = this.defaultValue;\n this.createRows();\n return false;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n this.createRows();\n value = [{}];\n }\n }\n // Make sure we always have at least one row.\n // NOTE: Removing this will break \"Public Configurations\" in portal. ;)\n if (value && !value.length && !this.initEmpty) {\n value.push({});\n }\n const isSettingSubmission = flags.fromSubmission && !lodash_1.default.isEqual(value, this.emptyValue);\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n if (this.initRows || isSettingSubmission ||\n (Array.isArray(this.dataValue) && this.dataValue.length !== this.rows.length)) {\n if (!this.createRows() && changed) {\n this.redraw();\n }\n }\n if (this.componentModal && isSettingSubmission) {\n this.componentModal.setValue(value);\n }\n this.rows.forEach((row, rowIndex) => {\n if (value.length <= rowIndex) {\n return;\n }\n lodash_1.default.each(row, (col) => {\n col.rowIndex = rowIndex;\n this.setNestedValue(col, value[rowIndex], flags);\n });\n });\n this.updateOnChange(flags, changed);\n return changed;\n }\n restoreComponentsContext() {\n this.rows.forEach((row, index) => lodash_1.default.forIn(row, (component) => component.data = this.dataValue[index]));\n }\n getComponent(path, fn) {\n path = Array.isArray(path) ? path : [path];\n const [key, ...remainingPath] = path;\n let result = [];\n if (lodash_1.default.isNumber(key) && remainingPath.length) {\n const compKey = remainingPath.pop();\n result = this.rows[key][compKey];\n // If the component is inside a Layout Component, try to find it among all the row's components\n if (!result) {\n Object.entries(this.rows[key]).forEach(([, comp]) => {\n if ('getComponent' in comp) {\n const possibleResult = comp.getComponent([compKey], fn);\n if (possibleResult) {\n result = possibleResult;\n }\n }\n });\n }\n if (result && lodash_1.default.isFunction(fn)) {\n fn(result, this.getComponents());\n }\n if (remainingPath.length && 'getComponent' in result) {\n return result.getComponent(remainingPath, fn);\n }\n return result;\n }\n if (!lodash_1.default.isString(key)) {\n return result;\n }\n this.everyComponent((component, components) => {\n if (component.component.key === key) {\n let comp = component;\n if (remainingPath.length > 0 && 'getComponent' in component) {\n comp = component.getComponent(remainingPath, fn);\n }\n else if (fn) {\n fn(component, components);\n }\n result = result.concat(comp);\n }\n });\n return result.length > 0 ? result : null;\n }\n toggleGroup(element, index) {\n element.classList.toggle('collapsed');\n lodash_1.default.each(this.refs.chunks[index], row => {\n row.classList.toggle('hidden');\n });\n }\n}\nexports[\"default\"] = DataGridComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datagrid/DataGrid.js?");
|
5891
5891
|
|
5892
5892
|
/***/ }),
|
5893
5893
|
|
@@ -5898,7 +5898,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5898
5898
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5899
5899
|
|
5900
5900
|
"use strict";
|
5901
|
-
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst DataGrid_1 = __importDefault(__webpack_require__(/*! ../datagrid/DataGrid */ \"./lib/cjs/components/datagrid/DataGrid.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.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 Components_1 = __webpack_require__(/*! ../Components */ \"./lib/cjs/components/Components.js\");\nclass DataMapComponent extends DataGrid_1.default {\n static schema(...extend) {\n return Component_1.default.schema({\n label: 'Data Map',\n key: 'dataMap',\n type: 'datamap',\n clearOnHide: true,\n addAnother: 'Add Another',\n disableAddingRemovingRows: false,\n keyBeforeValue: true,\n valueComponent: {\n type: 'textfield',\n key: 'value',\n label: 'Value',\n input: true\n },\n input: true,\n validate: {\n maxLength: 0,\n minLength: 0\n }\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Map',\n icon: 'th-list',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-map',\n showPreview: false,\n weight: 20,\n schema: DataMapComponent.schema()\n };\n }\n get schema() {\n const schema = super.schema;\n if (this.components && (this.components.length > 0)) {\n schema.valueComponent = this.components[this.components.length - 1].schema;\n }\n return lodash_1.default.omit(schema, 'components');\n }\n static savedValueTypes(schema) {\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n constructor(component, options, data) {\n super(component, options, data);\n this.type = 'datamap';\n }\n init() {\n this.components = [];\n this.rows = [];\n this.createRows();\n this.visibleColumns = {\n key: true,\n [this.valueKey]: true\n };\n this.component.valueComponent.hideLabel = true;\n }\n get defaultSchema() {\n return DataMapComponent.schema();\n }\n get emptyValue() {\n return {};\n }\n get dataValue() {\n if (!this.key ||\n (!this.visible && this.component.clearOnHide)) {\n return this.emptyValue;\n }\n if (!this.hasValue() && this.shouldAddDefaultValue) {\n this.dataValue = this.emptyValue;\n }\n return lodash_1.default.get(this.data, this.key);\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultValue() {\n const value = super.defaultValue;\n if (Array.isArray(value)) {\n return value[0];\n }\n return this.emptyValue;\n }\n get keySchema() {\n return {\n type: 'textfield',\n input: true,\n hideLabel: true,\n label: this.component.keyLabel || 'Key',\n key: '__key',\n disableBuilderActions: true,\n };\n }\n get valueKey() {\n return this.component.valueComponent.key;\n }\n getRowValues() {\n const dataValue = this.dataValue;\n if (this.builderMode) {\n return [dataValue];\n }\n if (lodash_1.default.isEmpty(dataValue)) {\n return [];\n }\n return Object.keys(dataValue).map(() => dataValue);\n }\n getComponentsContainer() {\n if (this.builderMode) {\n return this.getComponents().map(comp => comp.component);\n }\n return super.getComponentsContainer();\n }\n get iteratableRows() {\n return this.rows.map((row) => {\n return Object.keys(row).map(key => ({\n components: row[key],\n data: row[key].dataValue,\n }));\n });\n }\n componentContext(component) {\n return this.iteratableRows[component.row].find(comp => comp.components.key === component.key).data;\n }\n hasHeader() {\n return true;\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode;\n }\n getColumns() {\n const keySchema = Object.assign({}, this.keySchema);\n const valueSchema = Object.assign({}, this.component.valueComponent);\n keySchema.hideLabel = false;\n valueSchema.hideLabel = false;\n return this.component.keyBeforeValue ?\n [keySchema, valueSchema] :\n [valueSchema, keySchema];\n }\n getRowKey(rowIndex) {\n const keys = Object.keys(this.dataValue);\n if (!keys[rowIndex]) {\n keys[rowIndex] = (0, utils_1.uniqueKey)(this.dataValue, this.defaultRowKey);\n }\n return keys[rowIndex];\n }\n get defaultRowKey() {\n return 'key';\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n if (component.key === '__key') {\n component.data = {\n '__key': Object.keys(rowData)[rowIndex],\n };\n }\n else {\n component.data = rowData;\n }\n });\n }\n getValueAsString(value, options) {\n if ((options === null || options === void 0 ? void 0 : options.email) && this.visible && !this.skipInEmail && lodash_1.default.isObject(value)) {\n let result = (`\n <table border=\"1\" style=\"width:100%\">\n <tbody>\n `);\n result = Object.keys(value).reduce((result, key) => {\n result += (`\n <tr>\n <th style=\"padding: 5px 10px;\">${key}</th>\n <td style=\"width:100%;padding:5px 10px;\">${this.getView(value[key], options)}</td>\n </tr>\n `);\n return result;\n }, result);\n result += (`\n </tbody>\n </table>\n `);\n return result;\n }\n if (lodash_1.default.isEmpty(value)) {\n return '';\n }\n if (options === null || options === void 0 ? void 0 : options.modalPreview) {\n delete options.modalPreview;\n return this.getDataValueAsTable(value, options);\n }\n return typeof value === 'object' ? '[Complex Data]' : value;\n }\n getDataValueAsTable(value, options) {\n let result = (`\n <table border=\"1\" style=\"width:100%\">\n <tbody>\n `);\n if (this.visible && lodash_1.default.isObject(value)) {\n Object.keys(value).forEach((key) => {\n result += (`\n <tr>\n <th style=\"padding: 5px 10px;\">${key}</th>\n <td style=\"width:100%;padding:5px 10px;\">${this.getView(value[key], options)}</td>\n </tr>\n `);\n });\n }\n result += (`\n </tbody>\n </table>\n `);\n return result;\n }\n createRowComponents(row, rowIndex) {\n // Use original value component API key in builder mode to be able to edit value component\n let key = this.builderMode ? this.valueKey : this.getRowKey(rowIndex);\n // Create a new event emitter since fields are isolated.\n const options = lodash_1.default.clone(this.options);\n options.events = new eventemitter3_1.default();\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}`;\n const components = {};\n components['__key'] = this.createComponent(this.keySchema, options, { __key: this.builderMode ? this.defaultRowKey : key });\n components['__key'].on('componentChange', (event) => {\n const dataValue = this.dataValue;\n const newKey = (0, utils_1.uniqueKey)(dataValue, event.value);\n dataValue[newKey] = dataValue[key];\n delete dataValue[key];\n const comp = components[this.valueKey];\n comp.component.key = newKey;\n comp.path = Components_1.Components.calculateComponentPath(comp);\n key = newKey;\n });\n const valueComponent = lodash_1.default.clone(this.component.valueComponent);\n valueComponent.key = key;\n const componentOptions = this.options;\n componentOptions.row = options.row;\n components[this.valueKey] = this.createComponent(valueComponent, componentOptions, this.dataValue);\n return components;\n }\n get canAddColumn() {\n return false;\n }\n addChildComponent(component) {\n this.component.valueComponent = component;\n }\n saveChildComponent(component) {\n // Update the Value Component, the Key Component is not allowed to edit\n if (component.key !== this.keySchema.key) {\n this.component.valueComponent = component;\n }\n }\n removeChildComponent() {\n const defaultSchema = DataMapComponent.schema();\n this.component.valueComponent = defaultSchema.valueComponent;\n }\n addRow() {\n const index = this.rows.length;\n this.rows[index] = this.createRowComponents(this.dataValue, index);\n this.redraw();\n this.triggerChange();\n }\n removeRow(index) {\n const keys = Object.keys(this.dataValue);\n if (keys[index]) {\n delete this.dataValue[keys[index]];\n }\n this.rows.splice(index, 1);\n this.redraw();\n this.triggerChange();\n }\n setValue(value, flags = {}) {\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n this.createRows();\n this.updateOnChange(flags, changed);\n return changed;\n }\n checkColumns() {\n if (this.builderMode || (!this.dataValue || !Object.keys(this.dataValue).length)) {\n return { rebuild: false, show: true };\n }\n if (Object.keys(this.dataValue).length > (this.rows || []).length) {\n return { rebuild: true, show: true };\n }\n return { rebuild: false, show: true };\n }\n}\nexports[\"default\"] = DataMapComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datamap/DataMap.js?");
|
5901
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst DataGrid_1 = __importDefault(__webpack_require__(/*! ../datagrid/DataGrid */ \"./lib/cjs/components/datagrid/DataGrid.js\"));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.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 Components_1 = __importDefault(__webpack_require__(/*! ../Components */ \"./lib/cjs/components/Components.js\"));\nclass DataMapComponent extends DataGrid_1.default {\n static schema(...extend) {\n return Component_1.default.schema({\n label: 'Data Map',\n key: 'dataMap',\n type: 'datamap',\n clearOnHide: true,\n addAnother: 'Add Another',\n disableAddingRemovingRows: false,\n keyBeforeValue: true,\n valueComponent: {\n type: 'textfield',\n key: 'value',\n label: 'Value',\n input: true\n },\n input: true,\n validate: {\n maxLength: 0,\n minLength: 0\n }\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Data Map',\n icon: 'th-list',\n group: 'data',\n documentation: '/userguide/form-building/data-components#data-map',\n showPreview: false,\n weight: 20,\n schema: DataMapComponent.schema()\n };\n }\n get schema() {\n const schema = super.schema;\n if (this.components && (this.components.length > 0)) {\n schema.valueComponent = this.components[this.components.length - 1].schema;\n }\n return lodash_1.default.omit(schema, 'components');\n }\n static savedValueTypes(schema) {\n return (0, utils_1.getComponentSavedTypes)(schema) || [utils_1.componentValueTypes.object];\n }\n constructor(component, options, data) {\n super(component, options, data);\n this.type = 'datamap';\n }\n init() {\n this.components = [];\n this.rows = [];\n this.createRows();\n this.visibleColumns = {\n key: true,\n [this.valueKey]: true\n };\n this.component.valueComponent.hideLabel = true;\n }\n get defaultSchema() {\n return DataMapComponent.schema();\n }\n get emptyValue() {\n return {};\n }\n get dataValue() {\n if (!this.key ||\n (!this.visible && this.component.clearOnHide)) {\n return this.emptyValue;\n }\n if (!this.hasValue() && this.shouldAddDefaultValue) {\n this.dataValue = this.emptyValue;\n }\n return lodash_1.default.get(this.data, this.key);\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get defaultValue() {\n const value = super.defaultValue;\n if (Array.isArray(value)) {\n return value[0];\n }\n return this.emptyValue;\n }\n get keySchema() {\n return {\n type: 'textfield',\n input: true,\n hideLabel: true,\n label: this.component.keyLabel || 'Key',\n key: '__key',\n disableBuilderActions: true,\n };\n }\n get valueKey() {\n return this.component.valueComponent.key;\n }\n getRowValues() {\n const dataValue = this.dataValue;\n if (this.builderMode) {\n return [dataValue];\n }\n if (lodash_1.default.isEmpty(dataValue)) {\n return [];\n }\n return Object.keys(dataValue).map(() => dataValue);\n }\n getComponentsContainer() {\n if (this.builderMode) {\n return this.getComponents().map(comp => comp.component);\n }\n return super.getComponentsContainer();\n }\n get iteratableRows() {\n return this.rows.map((row) => {\n return Object.keys(row).map(key => ({\n components: row[key],\n data: row[key].dataValue,\n }));\n });\n }\n componentContext(component) {\n return this.iteratableRows[component.row].find(comp => comp.components.key === component.key).data;\n }\n hasHeader() {\n return true;\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode;\n }\n getColumns() {\n const keySchema = Object.assign({}, this.keySchema);\n const valueSchema = Object.assign({}, this.component.valueComponent);\n keySchema.hideLabel = false;\n valueSchema.hideLabel = false;\n return this.component.keyBeforeValue ?\n [keySchema, valueSchema] :\n [valueSchema, keySchema];\n }\n getRowKey(rowIndex) {\n const keys = Object.keys(this.dataValue);\n if (!keys[rowIndex]) {\n keys[rowIndex] = (0, utils_1.uniqueKey)(this.dataValue, this.defaultRowKey);\n }\n return keys[rowIndex];\n }\n get defaultRowKey() {\n return 'key';\n }\n setRowComponentsData(rowIndex, rowData) {\n lodash_1.default.each(this.rows[rowIndex], (component) => {\n if (component.key === '__key') {\n component.data = {\n '__key': Object.keys(rowData)[rowIndex],\n };\n }\n else {\n component.data = rowData;\n }\n });\n }\n getValueAsString(value, options) {\n if ((options === null || options === void 0 ? void 0 : options.email) && this.visible && !this.skipInEmail && lodash_1.default.isObject(value)) {\n let result = (`\n <table border=\"1\" style=\"width:100%\">\n <tbody>\n `);\n result = Object.keys(value).reduce((result, key) => {\n result += (`\n <tr>\n <th style=\"padding: 5px 10px;\">${key}</th>\n <td style=\"width:100%;padding:5px 10px;\">${this.getView(value[key], options)}</td>\n </tr>\n `);\n return result;\n }, result);\n result += (`\n </tbody>\n </table>\n `);\n return result;\n }\n if (lodash_1.default.isEmpty(value)) {\n return '';\n }\n if (options === null || options === void 0 ? void 0 : options.modalPreview) {\n delete options.modalPreview;\n return this.getDataValueAsTable(value, options);\n }\n return typeof value === 'object' ? '[Complex Data]' : value;\n }\n getDataValueAsTable(value, options) {\n let result = (`\n <table border=\"1\" style=\"width:100%\">\n <tbody>\n `);\n if (this.visible && lodash_1.default.isObject(value)) {\n Object.keys(value).forEach((key) => {\n result += (`\n <tr>\n <th style=\"padding: 5px 10px;\">${key}</th>\n <td style=\"width:100%;padding:5px 10px;\">${this.getView(value[key], options)}</td>\n </tr>\n `);\n });\n }\n result += (`\n </tbody>\n </table>\n `);\n return result;\n }\n createRowComponents(row, rowIndex) {\n // Use original value component API key in builder mode to be able to edit value component\n let key = this.builderMode ? this.valueKey : this.getRowKey(rowIndex);\n // Create a new event emitter since fields are isolated.\n const options = lodash_1.default.clone(this.options);\n options.events = new eventemitter3_1.default();\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}`;\n const components = {};\n components['__key'] = this.createComponent(this.keySchema, options, { __key: this.builderMode ? this.defaultRowKey : key });\n components['__key'].on('componentChange', (event) => {\n const dataValue = this.dataValue;\n const newKey = (0, utils_1.uniqueKey)(dataValue, event.value);\n dataValue[newKey] = dataValue[key];\n delete dataValue[key];\n const comp = components[this.valueKey];\n comp.component.key = newKey;\n comp.path = Components_1.default.calculateComponentPath(comp);\n key = newKey;\n });\n const valueComponent = lodash_1.default.clone(this.component.valueComponent);\n valueComponent.key = key;\n const componentOptions = this.options;\n componentOptions.row = options.row;\n components[this.valueKey] = this.createComponent(valueComponent, componentOptions, this.dataValue);\n return components;\n }\n get canAddColumn() {\n return false;\n }\n addChildComponent(component) {\n this.component.valueComponent = component;\n }\n saveChildComponent(component) {\n // Update the Value Component, the Key Component is not allowed to edit\n if (component.key !== this.keySchema.key) {\n this.component.valueComponent = component;\n }\n }\n removeChildComponent() {\n const defaultSchema = DataMapComponent.schema();\n this.component.valueComponent = defaultSchema.valueComponent;\n }\n addRow() {\n const index = this.rows.length;\n this.rows[index] = this.createRowComponents(this.dataValue, index);\n this.redraw();\n this.triggerChange();\n }\n removeRow(index) {\n const keys = Object.keys(this.dataValue);\n if (keys[index]) {\n delete this.dataValue[keys[index]];\n }\n this.rows.splice(index, 1);\n this.redraw();\n this.triggerChange();\n }\n setValue(value, flags = {}) {\n const changed = this.hasChanged(value, this.dataValue);\n this.dataValue = value;\n this.createRows();\n this.updateOnChange(flags, changed);\n return changed;\n }\n checkColumns() {\n if (this.builderMode || (!this.dataValue || !Object.keys(this.dataValue).length)) {\n return { rebuild: false, show: true };\n }\n if (Object.keys(this.dataValue).length > (this.rows || []).length) {\n return { rebuild: true, show: true };\n }\n return { rebuild: false, show: true };\n }\n}\nexports[\"default\"] = DataMapComponent;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/datamap/DataMap.js?");
|
5902
5902
|
|
5903
5903
|
/***/ }),
|
5904
5904
|
|
@@ -5931,7 +5931,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
5931
5931
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
5932
5932
|
|
5933
5933
|
"use strict";
|
5934
|
-
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst process_1 = __webpack_require__(/*! @formio/core/process */ \"./node_modules/@formio/core/lib/process/index.js\");\nconst components_1 = __webpack_require__(/*! @formio/bootstrap/components */ \"./node_modules/@formio/bootstrap/lib/cjs/templates/components/index.js\");\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst Alert_1 = __importDefault(__webpack_require__(/*! ../alert/Alert */ \"./lib/cjs/components/alert/Alert.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst EditRowState = {\n New: 'new',\n Editing: 'editing',\n Saved: 'saved',\n Viewing: 'viewing',\n Removed: 'removed',\n Draft: 'draft',\n};\nclass EditGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n type: 'editgrid',\n label: 'Edit Grid',\n key: 'editGrid',\n clearOnHide: true,\n input: true,\n tree: true,\n removeRow: 'Cancel',\n defaultOpen: false,\n openWhenEmpty: false,\n modal: false,\n components: [],\n inlineEdit: false,\n templates: {\n header: EditGridComponent.defaultHeaderTemplate,\n row: EditGridComponent.defaultRowTemplate,\n tableHeader: EditGridComponent.defaultTableHeaderTemplate,\n tableRow: EditGridComponent.defaultTableRowTemplate,\n footer: '',\n },\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Edit Grid',\n icon: 'tasks',\n group: 'data',\n documentation: '/userguide/form-building/data-components#edit-grid',\n showPreview: false,\n weight: 30,\n schema: EditGridComponent.schema(),\n };\n }\n static get defaultHeaderTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">{{ t(component.label) }}</div>\n {% } %}\n {% }) %}\n </div>`;\n }\n static get defaultTableHeaderTemplate() {\n return `\n <tr>\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">{{ component.label }}</td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">Actions</td>\n {% } %}\n </tr>\n `;\n }\n static get defaultRowTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">\n {{ isVisibleInRow(component) ? getView(component, row[component.key]) : ''}}\n </div>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <div class=\"col-sm-2\">\n <div class=\"btn-group pull-right\">\n <button class=\"btn btn-default btn-light btn-sm editRow\"><i class=\"{{ iconClass('pen-fill') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </div>\n {% } %}\n </div>`;\n }\n static get defaultTableRowTemplate() {\n return `\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">\n {{ getView(component, row[component.key]) }}\n </td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">\n <div class=\"btn-group\">\n <button class=\"btn btn-default btn-light btn-sm editRow\" aria-label=\"{{ t('Edit row') }}\"><i class=\"{{ iconClass('pen-fill') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\" aria-label=\"{{ t('Remove row') }}\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </td>\n {% } %}\n `;\n }\n get defaultDialogTemplate() {\n return `\n <h3 ${this._referenceAttributeName}=\"dialogHeader\">${this.t('Do you want to clear data?')}</h3>\n <div style=\"display:flex; justify-content: flex-end;\">\n <button ${this._referenceAttributeName}=\"dialogCancelButton\" class=\"btn btn-secondary\" aria-label=\"${this.t('Cancel')}\">${this.t('Cancel')}</button>\n <button ${this._referenceAttributeName}=\"dialogYesButton\" class=\"btn btn-danger\" aria-label=\"${this.t('Yes, delete it')}\">${this.t('Yes, delete it')}</button>\n </div>\n `;\n }\n get defaultRowTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableRowTemplate\n : EditGridComponent.defaultRowTemplate;\n }\n get defaultHeaderTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableHeaderTemplate\n : EditGridComponent.defaultHeaderTemplate;\n }\n get rowTemplate() {\n let rowTemplate;\n if (utils_1.Evaluator.noeval) {\n rowTemplate = this.displayAsTable ?\n components_1.editgrid.tableRow\n : components_1.editgrid.row;\n }\n else {\n rowTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableRow', this.defaultRowTemplate)\n : lodash_1.default.get(this.component, 'templates.row', this.defaultRowTemplate);\n }\n return rowTemplate;\n }\n get headerTemplate() {\n let headerTemplate;\n if (utils_1.Evaluator.noeval) {\n headerTemplate = this.displayAsTable ?\n components_1.editgrid.tableHeader\n : components_1.editgrid.header;\n }\n else {\n headerTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableHeader', this.defaultHeaderTemplate)\n : lodash_1.default.get(this.component, 'templates.header', this.defaultHeaderTemplate);\n }\n return headerTemplate;\n }\n /**\n * @returns {boolean} - Returns true if the component has nested components which don't trigger changes on the root level\n */\n get hasScopedChildren() {\n return !this.inlineEditMode;\n }\n get defaultSchema() {\n return EditGridComponent.schema();\n }\n get emptyValue() {\n return [];\n }\n get editgridKey() {\n return `editgrid-${this.key}`;\n }\n get rowRef() {\n return `${this.editgridKey}-row`;\n }\n get rowElements() {\n return this.refs[this.rowRef];\n }\n get rowRefs() {\n return this.refs[`editgrid-${this.component.key}-row`];\n }\n get addRowRef() {\n return `${this.editgridKey}-addRow`;\n }\n get addRowElements() {\n return this.refs[this.addRowRef];\n }\n get saveRowRef() {\n return `${this.editgridKey}-saveRow`;\n }\n get saveRowElements() {\n return this.refs[this.saveRowRef];\n }\n get cancelRowRef() {\n return `${this.editgridKey}-cancelRow`;\n }\n get cancelRowElements() {\n return this.refs[this.cancelRowRef];\n }\n get inlineEditMode() {\n return this.component.inlineEdit;\n }\n get saveEditMode() {\n return !this.inlineEditMode;\n }\n get minLength() {\n return this.builderMode ? 0 : lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n get data() {\n return this._data;\n }\n get dataValue() {\n return super.dataValue || [];\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get displayAsTable() {\n return this.component.displayAsTable;\n }\n set data(value) {\n this._data = value;\n const data = this.dataValue;\n (this.editRows || []).forEach((row, index) => {\n if (!data[index] && row.state !== EditRowState.New) {\n data[index] = {};\n }\n const rowData = data[index] || {};\n row.data = rowData;\n row.components.forEach((component) => {\n component.data = rowData;\n });\n });\n }\n get iteratableRows() {\n return this.editRows;\n }\n get defaultValue() {\n const value = super.defaultValue;\n const defaultValue = Array.isArray(value) ? value : [];\n lodash_1.default.times(this.minLength - defaultValue.length, () => defaultValue.push({}));\n return defaultValue;\n }\n constructor(...args) {\n super(...args);\n this.type = 'editgrid';\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n init() {\n if (this.builderMode) {\n this.editRows = [];\n return super.init();\n }\n this.components = this.components || [];\n const dataValue = this.dataValue;\n const openWhenEmpty = !dataValue.length && this.component.openWhenEmpty;\n if (openWhenEmpty) {\n const dataObj = {};\n this.editRows = [];\n this.createRow(dataObj, 0);\n }\n else {\n this.editRows = dataValue.map((row, rowIndex) => ({\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n error: null,\n rowIndex,\n }));\n }\n this.prevHasAddButton = this.hasAddButton();\n this.checkData();\n this.setVariableTypeComponents();\n if (this.variableTypeComponentsIndexes.length) {\n lodash_1.default.each(this.editRows || [], (editRow, rowIndex) => this.checkRowVariableTypeComponents(editRow, rowIndex));\n }\n }\n checkRowVariableTypeComponents(editRow, rowIndex) {\n const rowComponents = editRow.components;\n if (lodash_1.default.some(this.variableTypeComponentsIndexes, (compIndex) => {\n const variableTypeComp = rowComponents[compIndex];\n return variableTypeComp.type !== variableTypeComp.component.type;\n })) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex, true);\n }\n }\n setVariableTypeComponents() {\n //set components which type is changing within a row (e.g.,by mergeComponentSchema action)\n this.variableTypeComponentsIndexes = [];\n lodash_1.default.each(this.component.components, (comp, index) => {\n if (comp.typeChangeEnabled) {\n this.variableTypeComponentsIndexes.push(index);\n }\n });\n }\n isOpen(editRow) {\n return [EditRowState.New, EditRowState.Editing, EditRowState.Viewing].includes(editRow.state);\n }\n isComponentVisibleInSomeRow(component) {\n const rows = this.editRows;\n const savedStates = [EditRowState.Saved, EditRowState.Editing, EditRowState.Draft];\n const savedRows = rows.filter(row => lodash_1.default.includes(savedStates, row.state));\n this.visibleInHeader = this.visibleInHeader || [];\n const changeVisibleInHeader = (component, isVisible) => {\n if (!isVisible) {\n lodash_1.default.remove(this.visibleInHeader, (key) => key === component.key);\n }\n if (isVisible && !lodash_1.default.includes(this.visibleInHeader, component.key)) {\n this.visibleInHeader.push(component.key);\n }\n };\n if (lodash_1.default.isEmpty(rows)) {\n const rowComponents = this.createRowComponents({}, 0);\n let checkComponent;\n (0, utils_1.eachComponent)(rowComponents, (comp) => {\n if (comp.component.key === component.key) {\n checkComponent = comp;\n }\n comp.checkConditions();\n });\n const isVisible = checkComponent ? checkComponent.visible : true;\n [...this.components].forEach((comp) => this.removeComponent(comp, this.components));\n changeVisibleInHeader(component, isVisible);\n return isVisible;\n }\n const isOpenRowWhenEmpty = lodash_1.default.get(this.component, 'openWhenEmpty') && rows.length === 1 && rows[0].state === EditRowState.New;\n if (!lodash_1.default.isEmpty(rows) && lodash_1.default.isEmpty(savedRows) && !isOpenRowWhenEmpty) {\n return lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return lodash_1.default.some(isOpenRowWhenEmpty ? rows : savedRows, (row, index) => {\n const editingRow = row.state === EditRowState.Editing;\n let isVisible;\n if (!editingRow) {\n const flattenedComponents = this.flattenComponents(index);\n const instance = flattenedComponents[component.key];\n isVisible = instance ? instance.visible : true;\n changeVisibleInHeader(component, isVisible);\n }\n else {\n isVisible = lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return isVisible;\n });\n }\n render(children) {\n if (this.builderMode) {\n return super.render();\n }\n const dataValue = this.dataValue;\n const headerTemplate = this.headerTemplate;\n const t = this.t.bind(this);\n const templateName = this.displayAsTable ? 'editgridTable' : 'editgrid';\n return super.render(children || this.renderTemplate(templateName, {\n ref: {\n row: this.rowRef,\n addRow: this.addRowRef,\n saveRow: this.saveRowRef,\n cancelRow: this.cancelRowRef,\n },\n header: this.renderString(headerTemplate, {\n displayValue: (component) => this.displayComponentValue(component, true),\n components: this.component.components,\n value: dataValue,\n t\n }),\n footer: this.renderString(lodash_1.default.get(this.component, 'templates.footer'), {\n components: this.component.components,\n value: dataValue,\n t\n }),\n rows: this.editRows.map(this.renderRow.bind(this)),\n openRows: this.editRows.map((row) => this.isOpen(row)),\n errors: this.editRows.map((row) => row.error),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons: this.hasRemoveButtons(),\n }));\n }\n renderComponents(components) {\n components = components || this.getComponents();\n const children = components.map(component => component.render());\n const templateName = this.displayAsTable && this.prevHasAddButton ? 'tableComponents' : 'components';\n return this.renderTemplate(templateName, {\n children,\n components,\n });\n }\n attach(element) {\n if (this.builderMode) {\n return super.attach(element);\n }\n this.loadRefs(element, {\n [this.addRowRef]: 'multiple',\n [this.saveRowRef]: 'multiple',\n [this.cancelRowRef]: 'multiple',\n [this.rowRef]: 'multiple',\n });\n this.addRowElements.forEach((addButton) => {\n this.addEventListener(addButton, 'click', () => this.addRow());\n });\n let openRowCount = 0;\n this.rowElements.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow === null || editRow === void 0 ? void 0 : editRow.isRowSelected) {\n row.classList.add('selected');\n }\n if (this.isOpen(editRow)) {\n this.attachComponents(row, editRow.components);\n this.addEventListener(this.saveRowElements[openRowCount], 'click', () => this.saveRow(rowIndex, true));\n this.addEventListener(this.cancelRowElements[openRowCount], 'click', () => this.cancelRow(rowIndex));\n openRowCount++;\n }\n else {\n // Attach edit and remove button events.\n [\n {\n className: 'removeRow',\n event: 'click',\n action: () => this.removeRow(rowIndex, true),\n },\n {\n className: 'editRow',\n event: 'click',\n action: () => {\n this.editRow(rowIndex).then(() => {\n var _a;\n if (this.component.rowDrafts) {\n const errors = this.validateRow(editRow, false);\n const shouldShowRowErrorsAlert = this.component.modal && errors.length && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted);\n if (shouldShowRowErrorsAlert) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n }\n });\n },\n },\n {\n className: 'row',\n event: 'click',\n action: () => {\n row.classList.toggle('selected');\n let eventName = 'editGridSelectRow';\n if (Array.from(row.classList).includes('selected')) {\n editRow.isRowSelected = true;\n }\n else {\n delete editRow.isRowSelected;\n eventName = 'editGridUnSelectRow';\n }\n this.emit(eventName, {\n component: this.component,\n data: this.dataValue[rowIndex]\n });\n },\n }\n ].forEach(({ className, event, action, }) => {\n const elements = row.getElementsByClassName(className);\n Array.prototype.forEach.call(elements, (element) => {\n if (this.options.pdf && lodash_1.default.intersection(element.classList, ['editRow', 'removeRow']).length) {\n element.style.display = 'none';\n }\n else {\n this.addEventListener(element, event, action);\n }\n });\n });\n }\n });\n // Add open class to the element if any edit grid row is open\n if (openRowCount) {\n this.addClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n else {\n this.removeClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n messageContainer: 'single-scope',\n });\n return superAttach;\n }\n flattenRowDataValue(dataValue) {\n const flattened = {};\n Object.keys(dataValue).forEach((key) => {\n if (lodash_1.default.isObject(dataValue[key]) && !lodash_1.default.isNil(dataValue[key])) {\n Object.assign(flattened, this.flattenRowDataValue(dataValue[key]));\n }\n else {\n flattened[key] = dataValue[key];\n }\n });\n return flattened;\n }\n isComponentVisibleInRow(component, flattenedComponents) {\n const instance = flattenedComponents[component.key];\n return instance ? instance.visible : true;\n }\n displayComponentValue(component, header) {\n return !!((!component.hasOwnProperty('tableView') || component.tableView)\n && header ? this.isComponentVisibleInSomeRow(component) : lodash_1.default.includes(this.visibleInHeader, component.key));\n }\n renderRow(row, rowIndex) {\n const dataValue = this.dataValue;\n if (this.isOpen(row)) {\n return this.renderComponents(row.components);\n }\n else {\n const flattenedComponents = this.flattenComponents(rowIndex);\n const rowTemplate = this.rowTemplate;\n return this.renderString(rowTemplate, {\n row: dataValue[rowIndex] || {},\n data: this.data,\n rowIndex,\n components: this.component.components,\n flattenedComponents,\n displayValue: (component) => this.displayComponentValue(component),\n isVisibleInRow: (component) => this.isComponentVisibleInRow(component, flattenedComponents),\n getView: (component, data) => {\n var _a, _b;\n const instance = flattenedComponents[component.key];\n const view = instance ? instance.getView(data || instance.dataValue) : '';\n // If there is an html tag in view, don't allow it to be injected in template\n const htmlTagRegExp = new RegExp('<(.*?)>');\n return typeof view === 'string' && view.length && !((_a = instance.component) === null || _a === void 0 ? void 0 : _a.template) && htmlTagRegExp.test(view) && ((_b = instance.component) === null || _b === void 0 ? void 0 : _b.inputFormat) !== 'html'\n ? `<input type=\"text\" value=\"${view.replace(/\"/g, '"')}\" readonly/>`\n : view;\n },\n state: this.editRows[rowIndex].state,\n t: this.t.bind(this)\n });\n }\n }\n eachComponent(fn, rowIndex) {\n lodash_1.default.each(this.getComponents(rowIndex), (component, index) => {\n if (fn(component, index) === false) {\n return false;\n }\n });\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n var _a;\n const rowData = this.dataValue[component.rowIndex];\n const editRowData = (_a = this.editRows[component.rowIndex]) === null || _a === void 0 ? void 0 : _a.data;\n component.data = rowData || editRowData;\n });\n }\n flattenComponents(rowIndex) {\n const result = {};\n this.everyComponent((component) => {\n result[component.component.flattenAs || component.key] = component;\n }, rowIndex);\n return result;\n }\n getComponents(rowIndex) {\n var _a;\n // Ensure editrows is set.\n this.editRows = this.editRows || [];\n return this.builderMode\n ? super.getComponents()\n : lodash_1.default.isNumber(rowIndex)\n ? (((_a = this.editRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.components) || [])\n : this.editRows.reduce((result, row) => result.concat(row.components || []), []);\n }\n destroy(all = false) {\n this.calculatedValue = undefined;\n super.destroy(all);\n }\n destroyComponents(all = false, rowIndex = 0) {\n if (this.builderMode) {\n return super.destroyComponents(all);\n }\n const components = this.getComponents(rowIndex).slice();\n components.forEach((comp) => this.removeComponent(comp, this.components, all));\n }\n createRow(dataObj, rowIndex) {\n const editRow = {\n components: this.createRowComponents(dataObj, rowIndex),\n data: dataObj,\n state: EditRowState.New,\n backup: null,\n error: null,\n rowIndex,\n };\n this.editRows.push(editRow);\n if (this.inlineEditMode) {\n this.dataValue.push(dataObj);\n }\n return editRow;\n }\n addRow() {\n if (this.options.readOnly) {\n return;\n }\n const dataObj = {};\n const rowIndex = this.editRows.length;\n const editRow = this.createRow(dataObj, rowIndex);\n if (editRow.state === EditRowState.New) {\n this.emptyRow = (0, utils_1.fastCloneDeep)(editRow.data);\n }\n if (this.inlineEditMode) {\n this.triggerChange();\n }\n this.emit('editGridAddRow', {\n component: this.component,\n row: editRow,\n });\n this.processRow('checkData', null, {}, editRow.data, editRow.components);\n if (this.component.modal) {\n this.addRowModal(rowIndex);\n }\n else {\n this.redraw();\n }\n return editRow;\n }\n addRowModal(rowIndex) {\n const modalContent = this.ce('div');\n const editRow = this.editRows[rowIndex];\n editRow.willBeSaved = false;\n const { components } = editRow;\n modalContent.innerHTML = this.renderComponents(components);\n const dialog = this.component.modal ? this.createModal(modalContent, {}, () => this.showDialog(rowIndex)) : undefined;\n dialog.classList.add(`editgrid-row-modal-${this.id}`);\n editRow.dialog = dialog;\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n this.alert = new Alert_1.default(dialog.refs.dialogContents, this);\n this.addEventListener(dialog, 'close', () => {\n if (!editRow.willBeSaved) {\n if (this.editRows[rowIndex] && this.editRows[rowIndex].state !== EditRowState.New) {\n this.editRows[rowIndex].components.forEach((comp) => {\n comp.setPristine(true);\n });\n }\n this.cancelRow(rowIndex);\n }\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n // Remove references to dialog elements to prevent possible in some cases memory leaks\n delete editRow.confirmationDialog;\n delete editRow.dialog;\n });\n dialog.refs.dialogContents.appendChild(this.ce('button', {\n class: 'btn btn-primary',\n onClick: () => {\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!errors.length || this.component.rowDrafts) {\n editRow.willBeSaved = true;\n dialog.close();\n this.saveRow(rowIndex, true);\n }\n else {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n },\n }, this.component.saveRow || 'Save'));\n return this.attachComponents(modalContent, components);\n }\n showDialog(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow.state === EditRowState.New ? lodash_1.default.isEqual(this.emptyRow, editRow.data) : lodash_1.default.isEqual(editRow.backup, editRow.data)) {\n return Promise.resolve();\n }\n const wrapper = this.ce('div', { ref: 'confirmationDialog' });\n const dialogContent = this.component.dialogTemplate || this.defaultDialogTemplate;\n wrapper.innerHTML = dialogContent;\n wrapper.refs = {};\n this.loadRefs.call(wrapper, wrapper, {\n dialogHeader: 'single',\n dialogCancelButton: 'single',\n dialogYesButton: 'single',\n });\n const dialog = this.createModal(wrapper);\n dialog.classList.add(`editgrid-row-modal-confirmation-${this.id}`);\n const close = (event) => {\n event.preventDefault();\n dialog.close();\n };\n let dialogResult;\n const promise = new Promise((resolve, reject) => {\n dialogResult = { resolve, reject };\n });\n this.addEventListener(wrapper.refs.dialogYesButton, 'click', (event) => {\n close(event);\n dialogResult.resolve();\n });\n this.addEventListener(wrapper.refs.dialogCancelButton, 'click', (event) => {\n close(event);\n dialogResult.reject();\n });\n editRow.confirmationDialog = dialog;\n return promise;\n }\n editRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n const isAlreadyEditing = editRow.state === EditRowState.Editing || editRow.state === EditRowState.New;\n if (!editRow || isAlreadyEditing) {\n return Promise.resolve();\n }\n editRow.prevState = editRow.state;\n editRow.state = this.options.readOnly ? EditRowState.Viewing : EditRowState.Editing;\n if (this.lazyLoad && (editRow.components.length === 0)) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex);\n }\n const dataSnapshot = (0, utils_1.fastCloneDeep)(editRow.data);\n if (this.inlineEditMode) {\n editRow.backup = dataSnapshot;\n }\n else {\n editRow.backup = (0, utils_1.fastCloneDeep)(editRow.data);\n editRow.data = dataSnapshot;\n this.restoreRowContext(editRow);\n }\n if (this.component.modal) {\n return this.addRowModal(rowIndex);\n }\n return this.redraw();\n }\n clearErrors(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow && Array.isArray(editRow.components)) {\n editRow.components.forEach((comp) => {\n comp.setPristine(true);\n comp.setCustomValidity('');\n });\n }\n }\n cancelRow(rowIndex) {\n if (this.options.readOnly) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n switch (editRow.state) {\n case EditRowState.New: {\n editRow.state = EditRowState.Removed;\n this.clearErrors(rowIndex);\n this.destroyComponents(false, rowIndex);\n if (this.inlineEditMode) {\n this.splice(rowIndex);\n }\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n break;\n }\n case EditRowState.Editing: {\n editRow.state = editRow.prevState;\n if (this.inlineEditMode) {\n this.dataValue[rowIndex] = editRow.backup;\n }\n editRow.data = editRow.backup;\n editRow.backup = null;\n this.restoreRowContext(editRow);\n this.clearErrors(rowIndex);\n break;\n }\n }\n this.emit('editGridCancelRow', {\n instance: this,\n component: this.component,\n editRow,\n });\n this.checkValidity(null, true);\n this.redraw();\n if (this.component.rowDrafts) {\n this.checkValidity(this.data, false);\n }\n }\n saveRow(rowIndex, modified) {\n var _a, _b;\n const editRow = this.editRows[rowIndex];\n if (this.options.readOnly) {\n return;\n }\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!this.component.rowDrafts) {\n if (errors.length) {\n return false;\n }\n }\n if (this.saveEditMode) {\n const dataValue = this.dataValue;\n if ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a.focusedComponent) === null || _b === void 0 ? void 0 : _b.component.typeChangeEnabled) {\n this.root.focusedComponent = null;\n }\n switch (editRow.state) {\n case EditRowState.New: {\n const newIndex = dataValue.length;\n dataValue.push(editRow.data);\n editRow.components.forEach(component => component.rowIndex = newIndex);\n if (rowIndex !== newIndex) {\n this.editRows.splice(rowIndex, 1);\n this.editRows.splice(newIndex, 0, editRow);\n }\n break;\n }\n case EditRowState.Editing: {\n dataValue[rowIndex] = editRow.data;\n break;\n }\n }\n }\n editRow.state = this.component.rowDrafts && errors.length ? EditRowState.Draft : EditRowState.Saved;\n editRow.backup = null;\n this.updateValue();\n this.emit('editGridSaveRow', {\n component: this.component,\n row: editRow.data,\n instance: this\n });\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n if (this.component.rowDrafts) {\n editRow.components.forEach(comp => comp.setPristine(this.pristine));\n }\n this.checkValidity(null, true);\n this.redraw();\n if (editRow.alerts) {\n editRow.alerts = false;\n }\n return true;\n }\n beforeFocus(component) {\n if ('beforeFocus' in this.parent) {\n this.parent.beforeFocus(this);\n }\n const relativePath = this.getRelativePath(component.path);\n const arrayPath = (0, utils_1.getArrayFromComponentPath)(relativePath);\n const rowIndex = arrayPath[0];\n let rowToEditIndex = arrayPath[0];\n this.editRows.forEach((row, indexInArray) => {\n if (row.rowIndex === rowIndex) {\n rowToEditIndex = indexInArray;\n }\n });\n if (lodash_1.default.isNumber(rowToEditIndex)) {\n this.editRow(rowToEditIndex);\n }\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n });\n }\n updateRowsComponents(rowIndex) {\n this.editRows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(row.components, rowIndex + index);\n });\n }\n baseRemoveRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n editRow.state = EditRowState.Removed;\n this.destroyComponents(false, rowIndex);\n return editRow;\n }\n removeRow(rowIndex, modified) {\n if (this.options.readOnly) {\n return;\n }\n this.clearErrors(rowIndex);\n this.baseRemoveRow(rowIndex);\n this.splice(rowIndex);\n this.emit('editGridDeleteRow', {\n index: rowIndex\n });\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n this.updateRowsComponents(rowIndex);\n this.updateValue();\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n this.checkValidity(null, true);\n this.checkData();\n this.redraw();\n }\n createRowComponents(row, rowIndex, recreatePartially) {\n // Iterate through existing components and destroy the ones with the same rowIndex.\n if (this.components) {\n for (let i = 0; i < this.components.length; i++) {\n if (this.components[i].rowIndex === rowIndex) {\n this.components[i].destroy();\n this.components.splice(i, 1);\n }\n }\n }\n const currentRowComponents = lodash_1.default.get(this.editRows, `[${rowIndex}].components`, null);\n return this.component.components.map((col, colIndex) => {\n var _a;\n if (recreatePartially && currentRowComponents && this.variableTypeComponentsIndexes.length) {\n const currentComp = currentRowComponents[colIndex];\n const shouldRecreate = lodash_1.default.includes(this.variableTypeComponentsIndexes, colIndex) && (currentComp === null || currentComp === void 0 ? void 0 : currentComp.type) !== ((_a = currentComp === null || currentComp === void 0 ? void 0 : currentComp.component) === null || _a === void 0 ? void 0 : _a.type);\n if (!shouldRecreate) {\n return currentComp;\n }\n col = currentComp.component;\n }\n const column = lodash_1.default.clone(col);\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n options.onChange = (flags = {}, changed, modified) => {\n var _a, _b;\n if (((_a = changed.instance.root) === null || _a === void 0 ? void 0 : _a.id) && (((_b = this.root) === null || _b === void 0 ? void 0 : _b.id) !== changed.instance.root.id)) {\n changed.instance.root.triggerChange(flags, changed, modified);\n }\n else if (!this.component.modal) {\n this.triggerRootChange(flags, changed, modified);\n }\n if (this.inlineEditMode) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n this.processRow('checkData', null, Object.assign(Object.assign({}, flags), { changed }), editRow.data, editRow.components);\n this.validateRow(editRow, false);\n }\n if (this.variableTypeComponentsIndexes.length) {\n this.checkRowVariableTypeComponents(editRow, rowIndex);\n this.redraw();\n }\n };\n const comp = this.createComponent(lodash_1.default.assign({}, column, { row: options.row }), options, row, null, recreatePartially && currentRowComponents ? currentRowComponents[colIndex] : null);\n comp.rowIndex = rowIndex;\n comp.inEditGrid = true;\n return comp;\n });\n }\n hasOpenRows() {\n return this.editRows.some(row => this.isOpen(row));\n }\n getAttachedData(data = null) {\n const ourData = (0, utils_1.fastCloneDeep)(data || this._data || this.rootValue);\n lodash_1.default.set(ourData, this.key, this.editRows.map((row) => row.data));\n return ourData;\n }\n shouldValidateDraft(editRow) {\n var _a, _b;\n // Draft rows should be validated only when there was an attempt to submit a form\n return (editRow.state === EditRowState.Draft &&\n !this.pristine &&\n !((_a = this.root) === null || _a === void 0 ? void 0 : _a.pristine) &&\n !this.hasOpenRows()) ||\n ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted);\n }\n shouldValidateRow(editRow, dirty) {\n return this.shouldValidateDraft(editRow) ||\n editRow.state === EditRowState.New ||\n editRow.state === EditRowState.Editing ||\n editRow.alerts ||\n dirty;\n }\n validateRow(editRow, dirty, forceSilentCheck) {\n var _a;\n editRow.errors = [];\n if (this.shouldValidateRow(editRow, dirty)) {\n const silentCheck = (this.component.rowDrafts && !this.shouldValidateDraft(editRow)) || forceSilentCheck;\n const rootValue = (0, utils_1.fastCloneDeep)(this.rootValue);\n const editGridValue = lodash_1.default.get(rootValue, this.path, []);\n editGridValue[editRow.rowIndex] = editRow.data;\n lodash_1.default.set(rootValue, this.path, editGridValue);\n const validationProcessorProcess = (context) => this.validationProcessor(context, { dirty, silentCheck });\n editRow.errors = (0, process_1.processSync)({\n components: (0, utils_1.fastCloneDeep)(this.component.components).map((component) => {\n component.parentPath = `${this.path}[${editRow.rowIndex}]`;\n return component;\n }),\n data: rootValue,\n row: editRow.data,\n process: 'validateRow',\n instances: this.componentsMap,\n scope: { errors: [] },\n processors: [\n {\n process: validationProcessorProcess,\n processSync: validationProcessorProcess\n }\n ]\n }).errors;\n }\n // TODO: this is essentially running its own custom validation and should be moved into a validation rule\n if (this.component.validate && this.component.validate.row) {\n const valid = this.evaluate(this.component.validate.row, {\n valid: (editRow.length === 0),\n row: editRow.data\n }, 'valid', true);\n if (valid.toString() !== 'true') {\n editRow.errors.push({\n type: 'error',\n rowError: true,\n message: valid.toString()\n });\n }\n if (valid === null) {\n editRow.errors.push({\n type: 'error',\n message: `Invalid row validation for ${this.key}`\n });\n }\n }\n if (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted)) {\n this.showRowErrorAlerts(editRow, editRow.errors);\n }\n return editRow.errors;\n }\n showRowErrorAlerts(editRow, errors) {\n if (editRow.alerts) {\n if (this.alert) {\n if (errors.length) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n else {\n this.alert.clear();\n this.alert = null;\n }\n }\n }\n }\n /**\n * @returns {boolean} - Return that this component processes its own validation.\n */\n get processOwnValidation() {\n return true;\n }\n checkComponentValidity(data, dirty, row, options = {}, errors = []) {\n var _a, _b;\n const { silentCheck } = options;\n const superValid = super.checkComponentValidity(data, dirty, row, options, errors);\n // If super tells us that component invalid and there is no need to update alerts, just return false\n if (!superValid && (!this.alert && !this.hasOpenRows())) {\n return false;\n }\n let rowsEditing = false;\n const allRowErrors = [];\n this.editRows.forEach((editRow, index) => {\n // Trigger all errors on the row.\n const rowErrors = this.validateRow(editRow, dirty, silentCheck);\n errors.push(...rowErrors);\n allRowErrors.push(...rowErrors);\n if (this.rowRefs) {\n const rowContainer = this.rowRefs[index];\n if (rowContainer) {\n const errorContainer = rowContainer.querySelector('.editgrid-row-error');\n if (rowErrors.length && errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n const rowError = rowErrors.find(error => error.rowError);\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(rowError ? rowError.message : this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n }\n // If this is a dirty check, and any rows are still editing, we need to throw validation error.\n rowsEditing |= (dirty && this.isOpen(editRow));\n });\n if (allRowErrors.length) {\n if (!silentCheck && (dirty || this.dirty) && (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted))) {\n this.setCustomValidity(this.t(this.errorMessage('invalidRowsError')), dirty);\n this.removeClass(this.element, 'has-error');\n }\n return false;\n }\n else if (rowsEditing && this.saveEditMode && !this.component.openWhenEmpty) {\n this.setCustomValidity(this.t(this.errorMessage('unsavedRowsError')), dirty);\n return false;\n }\n const message = this.invalid || this.invalidMessage(data, dirty, false, row);\n if (allRowErrors.length && ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted) && !message) {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n this.root.showErrors([message]);\n }\n else {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n }\n return superValid;\n }\n setRowInvalid(ref, index) {\n const editRow = this.editRows[index];\n const errorContainer = ref.querySelector('.editgrid-row-error');\n if (errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n changeState(changed, flags) {\n if (this.visible && (changed || (flags.resetValue && this.component.modalEdit))) {\n this.rebuild();\n }\n else {\n this.redraw();\n }\n }\n setValue(value, flags = {}) {\n if (!value) {\n value = this.defaultValue;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n return false;\n }\n }\n const changed = this.hasChanged(value, this.dataValue);\n if (this.parent && !this.options.server) {\n this.parent.checkComponentConditions();\n }\n this.dataValue = value;\n // Refresh editRow data when data changes.\n this.dataValue.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n editRow.data = row;\n this.restoreRowContext(editRow, flags);\n editRow.state = EditRowState.Saved;\n editRow.backup = null;\n editRow.errors = [];\n }\n else {\n this.editRows[rowIndex] = {\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n errors: [],\n };\n }\n });\n let { length: dataLength } = this.dataValue;\n // If the last row is a new row, then do not remove it.\n if (this.editRows[dataLength] && (this.editRows[dataLength].state === EditRowState.New)) {\n dataLength = (dataLength + 1);\n }\n this.editRows.slice(dataLength).forEach((editRow, index) => this.baseRemoveRow(dataLength + index));\n this.editRows = this.editRows.slice(0, dataLength);\n this.openWhenEmpty();\n this.updateOnChange(flags, changed);\n // do not call checkData with server option, it is called when change is triggered in updateOnChange\n if (!this.options.server) {\n this.checkData();\n }\n this.changeState(changed, flags);\n return changed;\n }\n openWhenEmpty() {\n const shouldBeOpened = !this.dataValue.length && this.component.openWhenEmpty;\n const hasNoRows = !this.editRows.length;\n if (hasNoRows && shouldBeOpened && !this.builderMode) {\n const dataObj = {};\n this.createRow(dataObj, 0);\n }\n }\n restoreRowContext(editRow, flags = {}) {\n editRow.components.forEach((component) => {\n component.data = editRow.data;\n this.setNestedValue(component, editRow.data, flags);\n });\n }\n emptyRows() {\n this.editRows.forEach((editRow, index) => this.destroyComponents(false, index));\n this.editRows = [];\n }\n resetValue() {\n super.resetValue();\n this.emptyRows();\n }\n}\nexports[\"default\"] = EditGridComponent;\nEditGridComponent.prototype.hasChanged = Component_1.default.prototype.hasChanged;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/editgrid/EditGrid.js?");
|
5934
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst lodash_1 = __importDefault(__webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\"));\nconst process_1 = __webpack_require__(/*! @formio/core/process */ \"./node_modules/@formio/core/lib/process/index.js\");\nconst components_1 = __webpack_require__(/*! @formio/bootstrap/components */ \"./node_modules/@formio/bootstrap/lib/cjs/templates/components/index.js\");\nconst NestedArrayComponent_1 = __importDefault(__webpack_require__(/*! ../_classes/nestedarray/NestedArrayComponent */ \"./lib/cjs/components/_classes/nestedarray/NestedArrayComponent.js\"));\nconst Component_1 = __importDefault(__webpack_require__(/*! ../_classes/component/Component */ \"./lib/cjs/components/_classes/component/Component.js\"));\nconst Alert_1 = __importDefault(__webpack_require__(/*! ../alert/Alert */ \"./lib/cjs/components/alert/Alert.js\"));\nconst utils_1 = __webpack_require__(/*! ../../utils/utils */ \"./lib/cjs/utils/utils.js\");\nconst EditRowState = {\n New: 'new',\n Editing: 'editing',\n Saved: 'saved',\n Viewing: 'viewing',\n Removed: 'removed',\n Draft: 'draft',\n};\nclass EditGridComponent extends NestedArrayComponent_1.default {\n static schema(...extend) {\n return NestedArrayComponent_1.default.schema({\n type: 'editgrid',\n label: 'Edit Grid',\n key: 'editGrid',\n clearOnHide: true,\n input: true,\n tree: true,\n removeRow: 'Cancel',\n defaultOpen: false,\n openWhenEmpty: false,\n modal: false,\n components: [],\n inlineEdit: false,\n templates: {\n header: EditGridComponent.defaultHeaderTemplate,\n row: EditGridComponent.defaultRowTemplate,\n tableHeader: EditGridComponent.defaultTableHeaderTemplate,\n tableRow: EditGridComponent.defaultTableRowTemplate,\n footer: '',\n },\n }, ...extend);\n }\n static get builderInfo() {\n return {\n title: 'Edit Grid',\n icon: 'tasks',\n group: 'data',\n documentation: '/userguide/form-building/data-components#edit-grid',\n showPreview: false,\n weight: 30,\n schema: EditGridComponent.schema(),\n };\n }\n static get defaultHeaderTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">{{ t(component.label) }}</div>\n {% } %}\n {% }) %}\n </div>`;\n }\n static get defaultTableHeaderTemplate() {\n return `\n <tr>\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">{{ component.label }}</td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">Actions</td>\n {% } %}\n </tr>\n `;\n }\n static get defaultRowTemplate() {\n return `<div class=\"row\">\n {% util.eachComponent(components, function(component) { %}\n {% if (displayValue(component)) { %}\n <div class=\"col-sm-2\">\n {{ isVisibleInRow(component) ? getView(component, row[component.key]) : ''}}\n </div>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <div class=\"col-sm-2\">\n <div class=\"btn-group pull-right\">\n <button class=\"btn btn-default btn-light btn-sm editRow\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </div>\n {% } %}\n </div>`;\n }\n static get defaultTableRowTemplate() {\n return `\n {% util.eachComponent(components, function(component) { %}\n {% if (!component.hasOwnProperty('tableView') || component.tableView) { %}\n <td class=\"editgrid-table-column\">\n {{ getView(component, row[component.key]) }}\n </td>\n {% } %}\n {% }) %}\n {% if (!instance.options.readOnly && !instance.disabled) { %}\n <td class=\"editgrid-table-column\">\n <div class=\"btn-group\">\n <button class=\"btn btn-default btn-light btn-sm editRow\" aria-label=\"{{ t('Edit row') }}\"><i class=\"{{ iconClass('edit') }}\"></i></button>\n {% if (!instance.hasRemoveButtons || instance.hasRemoveButtons()) { %}\n <button class=\"btn btn-danger btn-sm removeRow\" aria-label=\"{{ t('Remove row') }}\"><i class=\"{{ iconClass('trash') }}\"></i></button>\n {% } %}\n </div>\n </td>\n {% } %}\n `;\n }\n get defaultDialogTemplate() {\n return `\n <h3 ${this._referenceAttributeName}=\"dialogHeader\">${this.t('Do you want to clear data?')}</h3>\n <div style=\"display:flex; justify-content: flex-end;\">\n <button ${this._referenceAttributeName}=\"dialogCancelButton\" class=\"btn btn-secondary\" aria-label=\"${this.t('Cancel')}\">${this.t('Cancel')}</button>\n <button ${this._referenceAttributeName}=\"dialogYesButton\" class=\"btn btn-danger\" aria-label=\"${this.t('Yes, delete it')}\">${this.t('Yes, delete it')}</button>\n </div>\n `;\n }\n get defaultRowTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableRowTemplate\n : EditGridComponent.defaultRowTemplate;\n }\n get defaultHeaderTemplate() {\n return this.displayAsTable\n ? EditGridComponent.defaultTableHeaderTemplate\n : EditGridComponent.defaultHeaderTemplate;\n }\n get rowTemplate() {\n let rowTemplate;\n if (utils_1.Evaluator.noeval) {\n rowTemplate = this.displayAsTable ?\n components_1.editgrid.tableRow\n : components_1.editgrid.row;\n }\n else {\n rowTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableRow', this.defaultRowTemplate)\n : lodash_1.default.get(this.component, 'templates.row', this.defaultRowTemplate);\n }\n return rowTemplate;\n }\n get headerTemplate() {\n let headerTemplate;\n if (utils_1.Evaluator.noeval) {\n headerTemplate = this.displayAsTable ?\n components_1.editgrid.tableHeader\n : components_1.editgrid.header;\n }\n else {\n headerTemplate = this.displayAsTable ?\n lodash_1.default.get(this.component, 'templates.tableHeader', this.defaultHeaderTemplate)\n : lodash_1.default.get(this.component, 'templates.header', this.defaultHeaderTemplate);\n }\n return headerTemplate;\n }\n /**\n * @returns {boolean} - Returns true if the component has nested components which don't trigger changes on the root level\n */\n get hasScopedChildren() {\n return !this.inlineEditMode;\n }\n get defaultSchema() {\n return EditGridComponent.schema();\n }\n get emptyValue() {\n return [];\n }\n get editgridKey() {\n return `editgrid-${this.key}`;\n }\n get rowRef() {\n return `${this.editgridKey}-row`;\n }\n get rowElements() {\n return this.refs[this.rowRef];\n }\n get rowRefs() {\n return this.refs[`editgrid-${this.component.key}-row`];\n }\n get addRowRef() {\n return `${this.editgridKey}-addRow`;\n }\n get addRowElements() {\n return this.refs[this.addRowRef];\n }\n get saveRowRef() {\n return `${this.editgridKey}-saveRow`;\n }\n get saveRowElements() {\n return this.refs[this.saveRowRef];\n }\n get cancelRowRef() {\n return `${this.editgridKey}-cancelRow`;\n }\n get cancelRowElements() {\n return this.refs[this.cancelRowRef];\n }\n get inlineEditMode() {\n return this.component.inlineEdit;\n }\n get saveEditMode() {\n return !this.inlineEditMode;\n }\n get minLength() {\n return this.builderMode ? 0 : lodash_1.default.get(this.component, 'validate.minLength', 0);\n }\n get data() {\n return this._data;\n }\n get dataValue() {\n return super.dataValue || [];\n }\n set dataValue(value) {\n super.dataValue = value;\n }\n get displayAsTable() {\n return this.component.displayAsTable;\n }\n set data(value) {\n this._data = value;\n const data = this.dataValue;\n (this.editRows || []).forEach((row, index) => {\n if (!data[index] && row.state !== EditRowState.New) {\n data[index] = {};\n }\n const rowData = data[index] || {};\n row.data = rowData;\n row.components.forEach((component) => {\n component.data = rowData;\n });\n });\n }\n get iteratableRows() {\n return this.editRows;\n }\n get defaultValue() {\n const value = super.defaultValue;\n const defaultValue = Array.isArray(value) ? value : [];\n lodash_1.default.times(this.minLength - defaultValue.length, () => defaultValue.push({}));\n return defaultValue;\n }\n constructor(...args) {\n super(...args);\n this.type = 'editgrid';\n }\n hasRemoveButtons() {\n return !this.component.disableAddingRemovingRows &&\n !this.options.readOnly &&\n !this.disabled &&\n this.fullMode &&\n (this.dataValue.length > lodash_1.default.get(this.component, 'validate.minLength', 0));\n }\n init() {\n if (this.builderMode) {\n this.editRows = [];\n return super.init();\n }\n this.components = this.components || [];\n const dataValue = this.dataValue;\n const openWhenEmpty = !dataValue.length && this.component.openWhenEmpty;\n if (openWhenEmpty) {\n const dataObj = {};\n this.editRows = [];\n this.createRow(dataObj, 0);\n }\n else {\n this.editRows = dataValue.map((row, rowIndex) => ({\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n error: null,\n rowIndex,\n }));\n }\n this.prevHasAddButton = this.hasAddButton();\n this.checkData();\n this.setVariableTypeComponents();\n if (this.variableTypeComponentsIndexes.length) {\n lodash_1.default.each(this.editRows || [], (editRow, rowIndex) => this.checkRowVariableTypeComponents(editRow, rowIndex));\n }\n }\n checkRowVariableTypeComponents(editRow, rowIndex) {\n const rowComponents = editRow.components;\n if (lodash_1.default.some(this.variableTypeComponentsIndexes, (compIndex) => {\n const variableTypeComp = rowComponents[compIndex];\n return variableTypeComp.type !== variableTypeComp.component.type;\n })) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex, true);\n }\n }\n setVariableTypeComponents() {\n //set components which type is changing within a row (e.g.,by mergeComponentSchema action)\n this.variableTypeComponentsIndexes = [];\n lodash_1.default.each(this.component.components, (comp, index) => {\n if (comp.typeChangeEnabled) {\n this.variableTypeComponentsIndexes.push(index);\n }\n });\n }\n isOpen(editRow) {\n return [EditRowState.New, EditRowState.Editing, EditRowState.Viewing].includes(editRow.state);\n }\n isComponentVisibleInSomeRow(component) {\n const rows = this.editRows;\n const savedStates = [EditRowState.Saved, EditRowState.Editing, EditRowState.Draft];\n const savedRows = rows.filter(row => lodash_1.default.includes(savedStates, row.state));\n this.visibleInHeader = this.visibleInHeader || [];\n const changeVisibleInHeader = (component, isVisible) => {\n if (!isVisible) {\n lodash_1.default.remove(this.visibleInHeader, (key) => key === component.key);\n }\n if (isVisible && !lodash_1.default.includes(this.visibleInHeader, component.key)) {\n this.visibleInHeader.push(component.key);\n }\n };\n if (lodash_1.default.isEmpty(rows)) {\n const rowComponents = this.createRowComponents({}, 0);\n let checkComponent;\n (0, utils_1.eachComponent)(rowComponents, (comp) => {\n if (comp.component.key === component.key) {\n checkComponent = comp;\n }\n comp.checkConditions();\n });\n const isVisible = checkComponent ? checkComponent.visible : true;\n [...this.components].forEach((comp) => this.removeComponent(comp, this.components));\n changeVisibleInHeader(component, isVisible);\n return isVisible;\n }\n const isOpenRowWhenEmpty = lodash_1.default.get(this.component, 'openWhenEmpty') && rows.length === 1 && rows[0].state === EditRowState.New;\n if (!lodash_1.default.isEmpty(rows) && lodash_1.default.isEmpty(savedRows) && !isOpenRowWhenEmpty) {\n return lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return lodash_1.default.some(isOpenRowWhenEmpty ? rows : savedRows, (row, index) => {\n const editingRow = row.state === EditRowState.Editing;\n let isVisible;\n if (!editingRow) {\n const flattenedComponents = this.flattenComponents(index);\n const instance = flattenedComponents[component.key];\n isVisible = instance ? instance.visible : true;\n changeVisibleInHeader(component, isVisible);\n }\n else {\n isVisible = lodash_1.default.includes(this.visibleInHeader, component.key);\n }\n return isVisible;\n });\n }\n render(children) {\n if (this.builderMode) {\n return super.render();\n }\n const dataValue = this.dataValue;\n const headerTemplate = this.headerTemplate;\n const t = this.t.bind(this);\n const templateName = this.displayAsTable ? 'editgridTable' : 'editgrid';\n return super.render(children || this.renderTemplate(templateName, {\n ref: {\n row: this.rowRef,\n addRow: this.addRowRef,\n saveRow: this.saveRowRef,\n cancelRow: this.cancelRowRef,\n },\n header: this.renderString(headerTemplate, {\n displayValue: (component) => this.displayComponentValue(component, true),\n components: this.component.components,\n value: dataValue,\n t\n }),\n footer: this.renderString(lodash_1.default.get(this.component, 'templates.footer'), {\n components: this.component.components,\n value: dataValue,\n t\n }),\n rows: this.editRows.map(this.renderRow.bind(this)),\n openRows: this.editRows.map((row) => this.isOpen(row)),\n errors: this.editRows.map((row) => row.error),\n hasAddButton: this.hasAddButton(),\n hasRemoveButtons: this.hasRemoveButtons(),\n }));\n }\n renderComponents(components) {\n components = components || this.getComponents();\n const children = components.map(component => component.render());\n const templateName = this.displayAsTable && this.prevHasAddButton ? 'tableComponents' : 'components';\n return this.renderTemplate(templateName, {\n children,\n components,\n });\n }\n attach(element) {\n if (this.builderMode) {\n return super.attach(element);\n }\n this.loadRefs(element, {\n [this.addRowRef]: 'multiple',\n [this.saveRowRef]: 'multiple',\n [this.cancelRowRef]: 'multiple',\n [this.rowRef]: 'multiple',\n });\n this.addRowElements.forEach((addButton) => {\n this.addEventListener(addButton, 'click', () => this.addRow());\n });\n let openRowCount = 0;\n this.rowElements.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow === null || editRow === void 0 ? void 0 : editRow.isRowSelected) {\n row.classList.add('selected');\n }\n if (this.isOpen(editRow)) {\n this.attachComponents(row, editRow.components);\n this.addEventListener(this.saveRowElements[openRowCount], 'click', () => this.saveRow(rowIndex, true));\n this.addEventListener(this.cancelRowElements[openRowCount], 'click', () => this.cancelRow(rowIndex));\n openRowCount++;\n }\n else {\n // Attach edit and remove button events.\n [\n {\n className: 'removeRow',\n event: 'click',\n action: () => this.removeRow(rowIndex, true),\n },\n {\n className: 'editRow',\n event: 'click',\n action: () => {\n this.editRow(rowIndex).then(() => {\n var _a;\n if (this.component.rowDrafts) {\n const errors = this.validateRow(editRow, false);\n const shouldShowRowErrorsAlert = this.component.modal && errors.length && ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted);\n if (shouldShowRowErrorsAlert) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n }\n });\n },\n },\n {\n className: 'row',\n event: 'click',\n action: () => {\n row.classList.toggle('selected');\n let eventName = 'editGridSelectRow';\n if (Array.from(row.classList).includes('selected')) {\n editRow.isRowSelected = true;\n }\n else {\n delete editRow.isRowSelected;\n eventName = 'editGridUnSelectRow';\n }\n this.emit(eventName, {\n component: this.component,\n data: this.dataValue[rowIndex]\n });\n },\n }\n ].forEach(({ className, event, action, }) => {\n const elements = row.getElementsByClassName(className);\n Array.prototype.forEach.call(elements, (element) => {\n if (this.options.pdf && lodash_1.default.intersection(element.classList, ['editRow', 'removeRow']).length) {\n element.style.display = 'none';\n }\n else {\n this.addEventListener(element, event, action);\n }\n });\n });\n }\n });\n // Add open class to the element if any edit grid row is open\n if (openRowCount) {\n this.addClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n else {\n this.removeClass(this.refs.component, `formio-component-${this.component.type}-row-open`);\n }\n const superAttach = super.attach(element);\n this.loadRefs(element, {\n messageContainer: 'single-scope',\n });\n return superAttach;\n }\n flattenRowDataValue(dataValue) {\n const flattened = {};\n Object.keys(dataValue).forEach((key) => {\n if (lodash_1.default.isObject(dataValue[key]) && !lodash_1.default.isNil(dataValue[key])) {\n Object.assign(flattened, this.flattenRowDataValue(dataValue[key]));\n }\n else {\n flattened[key] = dataValue[key];\n }\n });\n return flattened;\n }\n isComponentVisibleInRow(component, flattenedComponents) {\n const instance = flattenedComponents[component.key];\n return instance ? instance.visible : true;\n }\n displayComponentValue(component, header) {\n return !!((!component.hasOwnProperty('tableView') || component.tableView)\n && header ? this.isComponentVisibleInSomeRow(component) : lodash_1.default.includes(this.visibleInHeader, component.key));\n }\n renderRow(row, rowIndex) {\n const dataValue = this.dataValue;\n if (this.isOpen(row)) {\n return this.renderComponents(row.components);\n }\n else {\n const flattenedComponents = this.flattenComponents(rowIndex);\n const rowTemplate = this.rowTemplate;\n return this.renderString(rowTemplate, {\n row: dataValue[rowIndex] || {},\n data: this.data,\n rowIndex,\n components: this.component.components,\n flattenedComponents,\n displayValue: (component) => this.displayComponentValue(component),\n isVisibleInRow: (component) => this.isComponentVisibleInRow(component, flattenedComponents),\n getView: (component, data) => {\n var _a, _b;\n const instance = flattenedComponents[component.key];\n const view = instance ? instance.getView(data || instance.dataValue) : '';\n // If there is an html tag in view, don't allow it to be injected in template\n const htmlTagRegExp = new RegExp('<(.*?)>');\n return typeof view === 'string' && view.length && !((_a = instance.component) === null || _a === void 0 ? void 0 : _a.template) && htmlTagRegExp.test(view) && ((_b = instance.component) === null || _b === void 0 ? void 0 : _b.inputFormat) !== 'html'\n ? `<input type=\"text\" value=\"${view.replace(/\"/g, '"')}\" readonly/>`\n : view;\n },\n state: this.editRows[rowIndex].state,\n t: this.t.bind(this)\n });\n }\n }\n eachComponent(fn, rowIndex) {\n lodash_1.default.each(this.getComponents(rowIndex), (component, index) => {\n if (fn(component, index) === false) {\n return false;\n }\n });\n }\n restoreComponentsContext() {\n this.getComponents().forEach((component) => {\n var _a;\n const rowData = this.dataValue[component.rowIndex];\n const editRowData = (_a = this.editRows[component.rowIndex]) === null || _a === void 0 ? void 0 : _a.data;\n component.data = rowData || editRowData;\n });\n }\n flattenComponents(rowIndex) {\n const result = {};\n this.everyComponent((component) => {\n result[component.component.flattenAs || component.key] = component;\n }, rowIndex);\n return result;\n }\n getComponents(rowIndex) {\n var _a;\n // Ensure editrows is set.\n this.editRows = this.editRows || [];\n return this.builderMode\n ? super.getComponents()\n : lodash_1.default.isNumber(rowIndex)\n ? (((_a = this.editRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.components) || [])\n : this.editRows.reduce((result, row) => result.concat(row.components || []), []);\n }\n destroy(all = false) {\n this.calculatedValue = undefined;\n super.destroy(all);\n }\n destroyComponents(all = false, rowIndex = 0) {\n if (this.builderMode) {\n return super.destroyComponents(all);\n }\n const components = this.getComponents(rowIndex).slice();\n components.forEach((comp) => this.removeComponent(comp, this.components, all));\n }\n createRow(dataObj, rowIndex) {\n const editRow = {\n components: this.createRowComponents(dataObj, rowIndex),\n data: dataObj,\n state: EditRowState.New,\n backup: null,\n error: null,\n rowIndex,\n };\n this.editRows.push(editRow);\n if (this.inlineEditMode) {\n this.dataValue.push(dataObj);\n }\n return editRow;\n }\n addRow() {\n if (this.options.readOnly) {\n return;\n }\n const dataObj = {};\n const rowIndex = this.editRows.length;\n const editRow = this.createRow(dataObj, rowIndex);\n if (editRow.state === EditRowState.New) {\n this.emptyRow = (0, utils_1.fastCloneDeep)(editRow.data);\n }\n if (this.inlineEditMode) {\n this.triggerChange();\n }\n this.emit('editGridAddRow', {\n component: this.component,\n row: editRow,\n });\n this.processRow('checkData', null, {}, editRow.data, editRow.components);\n if (this.component.modal) {\n this.addRowModal(rowIndex);\n }\n else {\n this.redraw();\n }\n return editRow;\n }\n addRowModal(rowIndex) {\n const modalContent = this.ce('div');\n const editRow = this.editRows[rowIndex];\n editRow.willBeSaved = false;\n const { components } = editRow;\n modalContent.innerHTML = this.renderComponents(components);\n const dialog = this.component.modal ? this.createModal(modalContent, {}, () => this.showDialog(rowIndex)) : undefined;\n dialog.classList.add(`editgrid-row-modal-${this.id}`);\n editRow.dialog = dialog;\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n this.alert = new Alert_1.default(dialog.refs.dialogContents, this);\n this.addEventListener(dialog, 'close', () => {\n if (!editRow.willBeSaved) {\n if (this.editRows[rowIndex] && this.editRows[rowIndex].state !== EditRowState.New) {\n this.editRows[rowIndex].components.forEach((comp) => {\n comp.setPristine(true);\n });\n }\n this.cancelRow(rowIndex);\n }\n if (this.alert) {\n this.alert.clear();\n this.alert = null;\n }\n // Remove references to dialog elements to prevent possible in some cases memory leaks\n delete editRow.confirmationDialog;\n delete editRow.dialog;\n });\n dialog.refs.dialogContents.appendChild(this.ce('button', {\n class: 'btn btn-primary',\n onClick: () => {\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!errors.length || this.component.rowDrafts) {\n editRow.willBeSaved = true;\n dialog.close();\n this.saveRow(rowIndex, true);\n }\n else {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n },\n }, this.component.saveRow || 'Save'));\n return this.attachComponents(modalContent, components);\n }\n showDialog(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow.state === EditRowState.New ? lodash_1.default.isEqual(this.emptyRow, editRow.data) : lodash_1.default.isEqual(editRow.backup, editRow.data)) {\n return Promise.resolve();\n }\n const wrapper = this.ce('div', { ref: 'confirmationDialog' });\n const dialogContent = this.component.dialogTemplate || this.defaultDialogTemplate;\n wrapper.innerHTML = dialogContent;\n wrapper.refs = {};\n this.loadRefs.call(wrapper, wrapper, {\n dialogHeader: 'single',\n dialogCancelButton: 'single',\n dialogYesButton: 'single',\n });\n const dialog = this.createModal(wrapper);\n dialog.classList.add(`editgrid-row-modal-confirmation-${this.id}`);\n const close = (event) => {\n event.preventDefault();\n dialog.close();\n };\n let dialogResult;\n const promise = new Promise((resolve, reject) => {\n dialogResult = { resolve, reject };\n });\n this.addEventListener(wrapper.refs.dialogYesButton, 'click', (event) => {\n close(event);\n dialogResult.resolve();\n });\n this.addEventListener(wrapper.refs.dialogCancelButton, 'click', (event) => {\n close(event);\n dialogResult.reject();\n });\n editRow.confirmationDialog = dialog;\n return promise;\n }\n editRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n const isAlreadyEditing = editRow.state === EditRowState.Editing || editRow.state === EditRowState.New;\n if (!editRow || isAlreadyEditing) {\n return Promise.resolve();\n }\n editRow.prevState = editRow.state;\n editRow.state = this.options.readOnly ? EditRowState.Viewing : EditRowState.Editing;\n if (this.lazyLoad && (editRow.components.length === 0)) {\n editRow.components = this.createRowComponents(editRow.data, rowIndex);\n }\n const dataSnapshot = (0, utils_1.fastCloneDeep)(editRow.data);\n if (this.inlineEditMode) {\n editRow.backup = dataSnapshot;\n }\n else {\n editRow.backup = (0, utils_1.fastCloneDeep)(editRow.data);\n editRow.data = dataSnapshot;\n this.restoreRowContext(editRow);\n }\n if (this.component.modal) {\n return this.addRowModal(rowIndex);\n }\n return this.redraw();\n }\n clearErrors(rowIndex) {\n const editRow = this.editRows[rowIndex];\n if (editRow && Array.isArray(editRow.components)) {\n editRow.components.forEach((comp) => {\n comp.setPristine(true);\n comp.setCustomValidity('');\n });\n }\n }\n cancelRow(rowIndex) {\n if (this.options.readOnly) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n switch (editRow.state) {\n case EditRowState.New: {\n editRow.state = EditRowState.Removed;\n this.clearErrors(rowIndex);\n this.destroyComponents(false, rowIndex);\n if (this.inlineEditMode) {\n this.splice(rowIndex);\n }\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n break;\n }\n case EditRowState.Editing: {\n editRow.state = editRow.prevState;\n if (this.inlineEditMode) {\n this.dataValue[rowIndex] = editRow.backup;\n }\n editRow.data = editRow.backup;\n editRow.backup = null;\n this.restoreRowContext(editRow);\n this.clearErrors(rowIndex);\n break;\n }\n }\n this.emit('editGridCancelRow', {\n instance: this,\n component: this.component,\n editRow,\n });\n this.checkValidity(null, true);\n this.redraw();\n if (this.component.rowDrafts) {\n this.checkValidity(this.data, false);\n }\n }\n saveRow(rowIndex, modified) {\n var _a, _b;\n const editRow = this.editRows[rowIndex];\n if (this.options.readOnly) {\n return;\n }\n // After an attempt to save, all the components inside the row should become not pristine\n if (!this.component.rowDrafts) {\n editRow.components.forEach((comp) => comp.setPristine(false));\n }\n const errors = this.validateRow(editRow, true);\n if (!this.component.rowDrafts) {\n if (errors.length) {\n return false;\n }\n }\n if (this.saveEditMode) {\n const dataValue = this.dataValue;\n if ((_b = (_a = this.root) === null || _a === void 0 ? void 0 : _a.focusedComponent) === null || _b === void 0 ? void 0 : _b.component.typeChangeEnabled) {\n this.root.focusedComponent = null;\n }\n switch (editRow.state) {\n case EditRowState.New: {\n const newIndex = dataValue.length;\n dataValue.push(editRow.data);\n editRow.components.forEach(component => component.rowIndex = newIndex);\n if (rowIndex !== newIndex) {\n this.editRows.splice(rowIndex, 1);\n this.editRows.splice(newIndex, 0, editRow);\n }\n break;\n }\n case EditRowState.Editing: {\n dataValue[rowIndex] = editRow.data;\n break;\n }\n }\n }\n editRow.state = this.component.rowDrafts && errors.length ? EditRowState.Draft : EditRowState.Saved;\n editRow.backup = null;\n this.updateValue();\n this.emit('editGridSaveRow', {\n component: this.component,\n row: editRow.data,\n instance: this\n });\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n if (this.component.rowDrafts) {\n editRow.components.forEach(comp => comp.setPristine(this.pristine));\n }\n this.checkValidity(null, true);\n this.redraw();\n if (editRow.alerts) {\n editRow.alerts = false;\n }\n return true;\n }\n beforeFocus(component) {\n if ('beforeFocus' in this.parent) {\n this.parent.beforeFocus(this);\n }\n const relativePath = this.getRelativePath(component.path);\n const arrayPath = (0, utils_1.getArrayFromComponentPath)(relativePath);\n const rowIndex = arrayPath[0];\n let rowToEditIndex = arrayPath[0];\n this.editRows.forEach((row, indexInArray) => {\n if (row.rowIndex === rowIndex) {\n rowToEditIndex = indexInArray;\n }\n });\n if (lodash_1.default.isNumber(rowToEditIndex)) {\n this.editRow(rowToEditIndex);\n }\n }\n updateComponentsRowIndex(components, rowIndex) {\n components.forEach((component, colIndex) => {\n component.rowIndex = rowIndex;\n component.row = `${rowIndex}-${colIndex}`;\n });\n }\n updateRowsComponents(rowIndex) {\n this.editRows.slice(rowIndex).forEach((row, index) => {\n this.updateComponentsRowIndex(row.components, rowIndex + index);\n });\n }\n baseRemoveRow(rowIndex) {\n const editRow = this.editRows[rowIndex];\n editRow.state = EditRowState.Removed;\n this.destroyComponents(false, rowIndex);\n return editRow;\n }\n removeRow(rowIndex, modified) {\n if (this.options.readOnly) {\n return;\n }\n this.clearErrors(rowIndex);\n this.baseRemoveRow(rowIndex);\n this.splice(rowIndex);\n this.emit('editGridDeleteRow', {\n index: rowIndex\n });\n this.editRows.splice(rowIndex, 1);\n this.openWhenEmpty();\n this.updateRowsComponents(rowIndex);\n this.updateValue();\n this.triggerChange({ modified, noPristineChangeOnModified: modified && this.component.rowDrafts, isolateRow: true });\n this.checkValidity(null, true);\n this.checkData();\n this.redraw();\n }\n createRowComponents(row, rowIndex, recreatePartially) {\n // Iterate through existing components and destroy the ones with the same rowIndex.\n if (this.components) {\n for (let i = 0; i < this.components.length; i++) {\n if (this.components[i].rowIndex === rowIndex) {\n this.components[i].destroy();\n this.components.splice(i, 1);\n }\n }\n }\n const currentRowComponents = lodash_1.default.get(this.editRows, `[${rowIndex}].components`, null);\n return this.component.components.map((col, colIndex) => {\n var _a;\n if (recreatePartially && currentRowComponents && this.variableTypeComponentsIndexes.length) {\n const currentComp = currentRowComponents[colIndex];\n const shouldRecreate = lodash_1.default.includes(this.variableTypeComponentsIndexes, colIndex) && (currentComp === null || currentComp === void 0 ? void 0 : currentComp.type) !== ((_a = currentComp === null || currentComp === void 0 ? void 0 : currentComp.component) === null || _a === void 0 ? void 0 : _a.type);\n if (!shouldRecreate) {\n return currentComp;\n }\n col = currentComp.component;\n }\n const column = lodash_1.default.clone(col);\n const options = lodash_1.default.clone(this.options);\n options.name += `[${rowIndex}]`;\n options.row = `${rowIndex}-${colIndex}`;\n options.onChange = (flags = {}, changed, modified) => {\n var _a, _b;\n if (((_a = changed.instance.root) === null || _a === void 0 ? void 0 : _a.id) && (((_b = this.root) === null || _b === void 0 ? void 0 : _b.id) !== changed.instance.root.id)) {\n changed.instance.root.triggerChange(flags, changed, modified);\n }\n else if (!this.component.modal) {\n this.triggerRootChange(flags, changed, modified);\n }\n if (this.inlineEditMode) {\n return;\n }\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n this.processRow('checkData', null, Object.assign(Object.assign({}, flags), { changed }), editRow.data, editRow.components);\n this.validateRow(editRow, false);\n }\n if (this.variableTypeComponentsIndexes.length) {\n this.checkRowVariableTypeComponents(editRow, rowIndex);\n this.redraw();\n }\n };\n const comp = this.createComponent(lodash_1.default.assign({}, column, { row: options.row }), options, row, null, recreatePartially && currentRowComponents ? currentRowComponents[colIndex] : null);\n comp.rowIndex = rowIndex;\n comp.inEditGrid = true;\n return comp;\n });\n }\n hasOpenRows() {\n return this.editRows.some(row => this.isOpen(row));\n }\n getAttachedData(data = null) {\n const ourData = (0, utils_1.fastCloneDeep)(data || this._data || this.rootValue);\n lodash_1.default.set(ourData, this.key, this.editRows.map((row) => row.data));\n return ourData;\n }\n shouldValidateDraft(editRow) {\n var _a, _b;\n // Draft rows should be validated only when there was an attempt to submit a form\n return (editRow.state === EditRowState.Draft &&\n !this.pristine &&\n !((_a = this.root) === null || _a === void 0 ? void 0 : _a.pristine) &&\n !this.hasOpenRows()) ||\n ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted);\n }\n shouldValidateRow(editRow, dirty) {\n return this.shouldValidateDraft(editRow) ||\n editRow.state === EditRowState.New ||\n editRow.state === EditRowState.Editing ||\n editRow.alerts ||\n dirty;\n }\n validateRow(editRow, dirty, forceSilentCheck) {\n var _a;\n editRow.errors = [];\n if (this.shouldValidateRow(editRow, dirty)) {\n const silentCheck = (this.component.rowDrafts && !this.shouldValidateDraft(editRow)) || forceSilentCheck;\n const rootValue = (0, utils_1.fastCloneDeep)(this.rootValue);\n const editGridValue = lodash_1.default.get(rootValue, this.path, []);\n editGridValue[editRow.rowIndex] = editRow.data;\n lodash_1.default.set(rootValue, this.path, editGridValue);\n const validationProcessorProcess = (context) => this.validationProcessor(context, { dirty, silentCheck });\n editRow.errors = (0, process_1.processSync)({\n components: (0, utils_1.fastCloneDeep)(this.component.components).map((component) => {\n component.parentPath = `${this.path}[${editRow.rowIndex}]`;\n return component;\n }),\n data: rootValue,\n row: editRow.data,\n process: 'validateRow',\n instances: this.componentsMap,\n scope: { errors: [] },\n processors: [\n {\n process: validationProcessorProcess,\n processSync: validationProcessorProcess\n }\n ]\n }).errors;\n }\n // TODO: this is essentially running its own custom validation and should be moved into a validation rule\n if (this.component.validate && this.component.validate.row) {\n const valid = this.evaluate(this.component.validate.row, {\n valid: (editRow.length === 0),\n row: editRow.data\n }, 'valid', true);\n if (valid.toString() !== 'true') {\n editRow.errors.push({\n type: 'error',\n rowError: true,\n message: valid.toString()\n });\n }\n if (valid === null) {\n editRow.errors.push({\n type: 'error',\n message: `Invalid row validation for ${this.key}`\n });\n }\n }\n if (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted)) {\n this.showRowErrorAlerts(editRow, editRow.errors);\n }\n return editRow.errors;\n }\n showRowErrorAlerts(editRow, errors) {\n if (editRow.alerts) {\n if (this.alert) {\n if (errors.length) {\n this.alert.showErrors(errors, false);\n editRow.alerts = true;\n }\n else {\n this.alert.clear();\n this.alert = null;\n }\n }\n }\n }\n /**\n * @returns {boolean} - Return that this component processes its own validation.\n */\n get processOwnValidation() {\n return true;\n }\n checkComponentValidity(data, dirty, row, options = {}, errors = []) {\n var _a, _b;\n const { silentCheck } = options;\n const superValid = super.checkComponentValidity(data, dirty, row, options, errors);\n // If super tells us that component invalid and there is no need to update alerts, just return false\n if (!superValid && (!this.alert && !this.hasOpenRows())) {\n return false;\n }\n let rowsEditing = false;\n const allRowErrors = [];\n this.editRows.forEach((editRow, index) => {\n // Trigger all errors on the row.\n const rowErrors = this.validateRow(editRow, dirty, silentCheck);\n errors.push(...rowErrors);\n allRowErrors.push(...rowErrors);\n if (this.rowRefs) {\n const rowContainer = this.rowRefs[index];\n if (rowContainer) {\n const errorContainer = rowContainer.querySelector('.editgrid-row-error');\n if (rowErrors.length && errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n const rowError = rowErrors.find(error => error.rowError);\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(rowError ? rowError.message : this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n }\n // If this is a dirty check, and any rows are still editing, we need to throw validation error.\n rowsEditing |= (dirty && this.isOpen(editRow));\n });\n if (allRowErrors.length) {\n if (!silentCheck && (dirty || this.dirty) && (!this.component.rowDrafts || ((_a = this.root) === null || _a === void 0 ? void 0 : _a.submitted))) {\n this.setCustomValidity(this.t(this.errorMessage('invalidRowsError')), dirty);\n this.removeClass(this.element, 'has-error');\n }\n return false;\n }\n else if (rowsEditing && this.saveEditMode && !this.component.openWhenEmpty) {\n this._errors = this.setCustomValidity(this.t(this.errorMessage('unsavedRowsError')), dirty);\n errors.push(...this._errors);\n return false;\n }\n const message = this.invalid || this.invalidMessage(data, dirty, false, row);\n if (allRowErrors.length && ((_b = this.root) === null || _b === void 0 ? void 0 : _b.submitted) && !message) {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n this.root.showErrors([message]);\n }\n else {\n this._errors = this.setCustomValidity(message, dirty);\n errors.push(...this._errors);\n }\n return superValid;\n }\n setRowInvalid(ref, index) {\n const editRow = this.editRows[index];\n const errorContainer = ref.querySelector('.editgrid-row-error');\n if (errorContainer && (!this.component.rowDrafts || this.shouldValidateDraft(editRow))) {\n this.addClass(errorContainer, 'help-block');\n errorContainer.textContent = this.t(this.errorMessage('invalidRowError'));\n }\n else if (errorContainer) {\n errorContainer.textContent = '';\n }\n }\n changeState(changed, flags) {\n if (this.visible && (changed || (flags.resetValue && this.component.modalEdit))) {\n this.rebuild();\n }\n else {\n this.redraw();\n }\n }\n setValue(value, flags = {}) {\n if (!value) {\n value = this.defaultValue;\n }\n if (!Array.isArray(value)) {\n if (typeof value === 'object') {\n value = [value];\n }\n else {\n return false;\n }\n }\n const changed = this.hasChanged(value, this.dataValue);\n if (this.parent && !this.options.server) {\n this.parent.checkComponentConditions();\n }\n this.dataValue = value;\n // Refresh editRow data when data changes.\n this.dataValue.forEach((row, rowIndex) => {\n const editRow = this.editRows[rowIndex];\n if (editRow) {\n editRow.data = row;\n this.restoreRowContext(editRow, flags);\n editRow.state = EditRowState.Saved;\n editRow.backup = null;\n editRow.errors = [];\n }\n else {\n this.editRows[rowIndex] = {\n components: this.lazyLoad ? [] : this.createRowComponents(row, rowIndex),\n data: row,\n state: EditRowState.Saved,\n backup: null,\n errors: [],\n };\n }\n });\n let { length: dataLength } = this.dataValue;\n // If the last row is a new row, then do not remove it.\n if (this.editRows[dataLength] && (this.editRows[dataLength].state === EditRowState.New)) {\n dataLength = (dataLength + 1);\n }\n this.editRows.slice(dataLength).forEach((editRow, index) => this.baseRemoveRow(dataLength + index));\n this.editRows = this.editRows.slice(0, dataLength);\n this.openWhenEmpty();\n this.updateOnChange(flags, changed);\n // do not call checkData with server option, it is called when change is triggered in updateOnChange\n if (!this.options.server) {\n this.checkData();\n }\n this.changeState(changed, flags);\n return changed;\n }\n openWhenEmpty() {\n const shouldBeOpened = !this.dataValue.length && this.component.openWhenEmpty;\n const hasNoRows = !this.editRows.length;\n if (hasNoRows && shouldBeOpened && !this.builderMode) {\n const dataObj = {};\n this.createRow(dataObj, 0);\n }\n }\n restoreRowContext(editRow, flags = {}) {\n editRow.components.forEach((component) => {\n component.data = editRow.data;\n this.setNestedValue(component, editRow.data, flags);\n });\n }\n emptyRows() {\n this.editRows.forEach((editRow, index) => this.destroyComponents(false, index));\n this.editRows = [];\n }\n resetValue() {\n super.resetValue();\n this.emptyRows();\n }\n}\nexports[\"default\"] = EditGridComponent;\nEditGridComponent.prototype.hasChanged = Component_1.default.prototype.hasChanged;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/components/editgrid/EditGrid.js?");
|
5935
5935
|
|
5936
5936
|
/***/ }),
|
5937
5937
|
|
@@ -6536,7 +6536,7 @@ eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {
|
|
6536
6536
|
/***/ (function(__unused_webpack_module, exports) {
|
6537
6537
|
|
6538
6538
|
"use strict";
|
6539
|
-
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports[\"default\"] = {\n unsavedRowsError: 'Please save all rows before proceeding.',\n invalidRowsError: 'Please correct invalid rows before proceeding.',\n invalidRowError: 'Invalid row. Please correct it or delete.',\n invalidOption: '{{field}} is an invalid value.',\n invalidDay: '{{field}} is not a valid day.',\n alertMessageWithLabel: '{{label}}: {{message}}',\n alertMessage: '{{message}}',\n complete: 'Submission Complete',\n error: 'Please fix the following errors before submitting.',\n errorListHotkey: 'Press Ctrl + Alt + X to go back to the error list.',\n errorsListNavigationMessage: 'Click to navigate to the field with following error.',\n submitError: 'Please check the form and correct all errors before submitting.',\n required: '{{field}} is required',\n unique: '{{field}} must be unique',\n array: '{{field}} must be an array',\n array_nonempty: '{{field}} must be a non-empty array', // eslint-disable-line camelcase\n nonarray: '{{field}} must not be an array',\n select: '{{field}} contains an invalid selection',\n pattern: '{{field}} does not match the pattern {{pattern}}',\n minLength: '{{field}} must have at least {{length}} characters.',\n maxLength: '{{field}} must have no more than {{length}} characters.',\n minWords: '{{field}} must have at least {{length}} words.',\n maxWords: '{{field}} must have no more than {{length}} words.',\n min: '{{field}} cannot be less than {{min}}.',\n max: '{{field}} cannot be greater than {{max}}.',\n maxDate: '{{field}} should not contain date after {{- maxDate}}',\n minDate: '{{field}} should not contain date before {{- minDate}}',\n maxYear: '{{field}} should not contain year greater than {{maxYear}}',\n minYear: '{{field}} should not contain year less than {{minYear}}',\n minSelectedCount: 'You must select at least {{minCount}} items',\n maxSelectedCount: 'You may only select up to {{maxCount}} items',\n invalid_email: '{{field}} must be a valid email.', // eslint-disable-line camelcase\n invalid_url: '{{field}} must be a valid url.', // eslint-disable-line camelcase\n invalid_regex: '{{field}} does not match the pattern {{regex}}.', // eslint-disable-line camelcase\n invalid_date: '{{field}} is not a valid date.', // eslint-disable-line camelcase\n invalid_day: '{{field}} is not a valid day.', // eslint-disable-line camelcase\n invalidValueProperty: 'Invalid Value Property',\n mask: '{{field}} does not match the mask.',\n valueIsNotAvailable: '{{ field }} is an invalid value.',\n stripe: '{{stripe}}',\n month: 'Month',\n day: 'Day',\n year: 'Year',\n january: 'January',\n february: 'February',\n march: 'March',\n april: 'April',\n may: 'May',\n june: 'June',\n july: 'July',\n august: 'August',\n september: 'September',\n october: 'October',\n november: 'November',\n december: 'December',\n next: 'Next',\n previous: 'Previous',\n cancel: 'Cancel',\n submit: 'Submit Form',\n confirmCancel: 'Are you sure you want to cancel?',\n saveDraftInstanceError: 'Cannot save draft because there is no formio instance.',\n saveDraftAuthError: 'Cannot save draft unless a user is authenticated.',\n restoreDraftInstanceError: 'Cannot restore draft because there is no formio instance.',\n saveDraftError: 'Unable to save draft.',\n restoreDraftError: 'Unable to restore draft.',\n time: 'Invalid time',\n cancelButtonAriaLabel: 'Cancel button. Click to reset the form',\n previousButtonAriaLabel: 'Previous button. Click to go back to the previous tab',\n nextButtonAriaLabel: 'Next button. Click to go to the next tab',\n submitButtonAriaLabel: 'Submit Form button. Click to submit the form',\n reCaptchaTokenValidationError: 'ReCAPTCHA: Token validation error',\n reCaptchaTokenNotSpecifiedError: 'ReCAPTCHA: Token is not specified in submission',\n apiKey: 'API Key is not unique: {{key}}',\n typeRemaining: '{{ remaining }} {{ type }} remaining.',\n typeCount: '{{ count }} {{ type }}'\n};\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/translations/en.js?");
|
6539
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports[\"default\"] = {\n unsavedRowsError: 'Please save all rows before proceeding.',\n invalidRowsError: 'Please correct invalid rows before proceeding.',\n invalidRowError: 'Invalid row. Please correct it or delete.',\n invalidOption: '{{field}} is an invalid value.',\n invalidDay: '{{field}} is not a valid day.',\n alertMessageWithLabel: '{{label}}: {{message}}',\n alertMessage: '{{message}}',\n complete: 'Submission Complete',\n error: 'Please fix the following errors before submitting.',\n errorListHotkey: 'Press Ctrl + Alt + X to go back to the error list.',\n errorsListNavigationMessage: 'Click to navigate to the field with following error.',\n submitError: 'Please check the form and correct all errors before submitting.',\n required: '{{field}} is required',\n unique: '{{field}} must be unique',\n array: '{{field}} must be an array',\n array_nonempty: '{{field}} must be a non-empty array', // eslint-disable-line camelcase\n nonarray: '{{field}} must not be an array',\n select: '{{field}} contains an invalid selection',\n pattern: '{{field}} does not match the pattern {{pattern}}',\n minLength: '{{field}} must have at least {{length}} characters.',\n maxLength: '{{field}} must have no more than {{length}} characters.',\n minWords: '{{field}} must have at least {{length}} words.',\n maxWords: '{{field}} must have no more than {{length}} words.',\n min: '{{field}} cannot be less than {{min}}.',\n max: '{{field}} cannot be greater than {{max}}.',\n maxDate: '{{field}} should not contain date after {{- maxDate}}',\n minDate: '{{field}} should not contain date before {{- minDate}}',\n maxYear: '{{field}} should not contain year greater than {{maxYear}}',\n minYear: '{{field}} should not contain year less than {{minYear}}',\n minSelectedCount: 'You must select at least {{minCount}} items',\n maxSelectedCount: 'You may only select up to {{maxCount}} items',\n invalid_email: '{{field}} must be a valid email.', // eslint-disable-line camelcase\n invalid_url: '{{field}} must be a valid url.', // eslint-disable-line camelcase\n invalid_regex: '{{field}} does not match the pattern {{regex}}.', // eslint-disable-line camelcase\n invalid_date: '{{field}} is not a valid date.', // eslint-disable-line camelcase\n invalid_day: '{{field}} is not a valid day.', // eslint-disable-line camelcase\n invalidValueProperty: 'Invalid Value Property',\n mask: '{{field}} does not match the mask.',\n valueIsNotAvailable: '{{ field }} is an invalid value.',\n stripe: '{{stripe}}',\n month: 'Month',\n day: 'Day',\n year: 'Year',\n january: 'January',\n february: 'February',\n march: 'March',\n april: 'April',\n may: 'May',\n june: 'June',\n july: 'July',\n august: 'August',\n september: 'September',\n october: 'October',\n november: 'November',\n december: 'December',\n next: 'Next',\n previous: 'Previous',\n cancel: 'Cancel',\n submit: 'Submit Form',\n confirmCancel: 'Are you sure you want to cancel?',\n saveDraftInstanceError: 'Cannot save draft because there is no formio instance.',\n saveDraftAuthError: 'Cannot save draft unless a user is authenticated.',\n restoreDraftInstanceError: 'Cannot restore draft because there is no formio instance.',\n saveDraftError: 'Unable to save draft.',\n restoreDraftError: 'Unable to restore draft.',\n time: 'Invalid time',\n cancelButtonAriaLabel: 'Cancel button. Click to reset the form',\n previousButtonAriaLabel: 'Previous button. Click to go back to the previous tab',\n nextButtonAriaLabel: 'Next button. Click to go to the next tab',\n submitButtonAriaLabel: 'Submit Form button. Click to submit the form',\n reCaptchaTokenValidationError: 'ReCAPTCHA: Token validation error',\n reCaptchaTokenNotSpecifiedError: 'ReCAPTCHA: Token is not specified in submission',\n apiKey: 'API Key is not unique: {{key}}',\n typeRemaining: '{{ remaining }} {{ type }} remaining.',\n typeCount: '{{ count }} {{ type }}',\n requiredDayField: '{{ field }} is required',\n requiredMonthField: '{{ field }} is required',\n requiredYearField: '{{ field }} is required'\n};\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/translations/en.js?");
|
6540
6540
|
|
6541
6541
|
/***/ }),
|
6542
6542
|
|
@@ -9579,7 +9579,7 @@ eval("\nvar parent = __webpack_require__(/*! ../../es/object/from-entries */ \".
|
|
9579
9579
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
9580
9580
|
|
9581
9581
|
"use strict";
|
9582
|
-
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.FormBuilder = exports.Form = exports.Formio = void 0;\nconst CDN_js_1 = __importDefault(__webpack_require__(/*! ./CDN.js */ \"./lib/cjs/CDN.js\"));\nclass Formio {\n static setLicense(license, norecurse = false) {\n _a.license = license;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setLicense(license);\n }\n }\n static setBaseUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setBaseUrl(url);\n }\n }\n static setApiUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setApiUrl(url);\n }\n }\n static setProjectUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setProjectUrl(url);\n }\n }\n static setAppUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setAppUrl(url);\n }\n }\n static setPathType(type, norecurse = false) {\n _a.pathType = type;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setPathType(type);\n }\n }\n static debug(...args) {\n if (_a.config.debug) {\n console.log(...args);\n }\n }\n static clearCache() {\n if (_a.FormioClass) {\n _a.FormioClass.clearCache();\n }\n }\n static global(prop, flag = '') {\n const globalValue = window[prop];\n if (flag && globalValue && !globalValue[flag]) {\n return null;\n }\n _a.debug(`Getting global ${prop}`, globalValue);\n return globalValue;\n }\n static use(module) {\n if (_a.FormioClass && _a.FormioClass.isRenderer) {\n _a.FormioClass.use(module);\n }\n else {\n _a.modules.push(module);\n }\n }\n static createElement(type, attrs, children) {\n const element = document.createElement(type);\n if (!attrs) {\n return element;\n }\n Object.keys(attrs).forEach(key => {\n element.setAttribute(key, attrs[key]);\n });\n (children || []).forEach(child => {\n element.appendChild(_a.createElement(child.tag, child.attrs, child.children));\n });\n return element;\n }\n static addScript(wrapper, src, name, flag = '') {\n return __awaiter(this, void 0, void 0, function* () {\n if (!src) {\n return Promise.resolve();\n }\n if (typeof src !== 'string' && src.length) {\n return Promise.all(src.map(ref => _a.addScript(wrapper, ref)));\n }\n if (name && _a.global(name, flag)) {\n _a.debug(`${name} already loaded.`);\n return Promise.resolve(_a.global(name));\n }\n _a.debug('Adding Script', src);\n try {\n wrapper.appendChild(_a.createElement('script', {\n src\n }));\n }\n catch (err) {\n _a.debug(err);\n return Promise.resolve();\n }\n if (!name) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n _a.debug(`Waiting to load ${name}`);\n const wait = setInterval(() => {\n if (_a.global(name, flag)) {\n clearInterval(wait);\n _a.debug(`${name} loaded.`);\n resolve(_a.global(name));\n }\n }, 100);\n });\n });\n }\n static addStyles(wrapper, href) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!href) {\n return;\n }\n if (typeof href !== 'string' && href.length) {\n href.forEach(ref => _a.addStyles(wrapper, ref));\n return;\n }\n _a.debug('Adding Styles', href);\n wrapper.appendChild(_a.createElement('link', {\n rel: 'stylesheet',\n href\n }));\n });\n }\n static submitDone(instance, submission) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.debug('Submision Complete', submission);\n if (_a.config.submitDone) {\n _a.config.submitDone(submission, instance);\n }\n const successMessage = (_a.config.success || '').toString();\n if (successMessage && successMessage.toLowerCase() !== 'false' && instance.element) {\n instance.element.innerHTML = `<div class=\"alert-success\" role=\"alert\">${successMessage}</div>`;\n }\n let returnUrl = _a.config.redirect;\n // Allow form based configuration for return url.\n if (!returnUrl &&\n (instance._form &&\n instance._form.settings &&\n (instance._form.settings.returnUrl ||\n instance._form.settings.redirect))) {\n _a.debug('Return url found in form configuration');\n returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;\n }\n if (returnUrl) {\n const formSrc = instance.formio ? instance.formio.formUrl : '';\n const hasQuery = !!returnUrl.match(/\\?/);\n const isOrigin = returnUrl.indexOf(location.origin) === 0;\n returnUrl += hasQuery ? '&' : '?';\n returnUrl += `sub=${submission._id}`;\n if (!isOrigin && formSrc) {\n returnUrl += `&form=${encodeURIComponent(formSrc)}`;\n }\n _a.debug('Return URL', returnUrl);\n window.location.href = returnUrl;\n if (isOrigin) {\n window.location.reload();\n }\n }\n });\n }\n // Return the full script if the builder is being used.\n static formioScript(script, builder) {\n builder = builder || _a.config.includeBuilder;\n if (_a.fullAdded || builder) {\n _a.fullAdded = true;\n return script.replace('formio.form', 'formio.full');\n }\n return script;\n }\n static addLibrary(libWrapper, lib, name) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!lib) {\n return;\n }\n if (lib.dependencies) {\n for (let i = 0; i < lib.dependencies.length; i++) {\n const libName = lib.dependencies[i];\n yield _a.addLibrary(libWrapper, _a.config.libs[libName], libName);\n }\n }\n if (lib.css) {\n yield _a.addStyles((lib.global ? document.body : libWrapper), lib.css);\n }\n if (lib.js) {\n const module = yield _a.addScript((lib.global ? document.body : libWrapper), lib.js, lib.use ? name : false);\n if (lib.use) {\n _a.debug(`Using ${name}`);\n const options = lib.options || {};\n if (!options.license && _a.license) {\n options.license = _a.license;\n }\n _a.use((typeof lib.use === 'function' ? lib.use(module) : module), options);\n }\n }\n if (lib.globalStyle) {\n const style = _a.createElement('style');\n style.type = 'text/css';\n style.innerHTML = lib.globalStyle;\n document.body.appendChild(style);\n }\n });\n }\n static addLoader(wrapper) {\n return __awaiter(this, void 0, void 0, function* () {\n wrapper.appendChild(_a.createElement('div', {\n 'class': 'formio-loader'\n }, [{\n tag: 'div',\n attrs: {\n class: 'loader-wrapper'\n },\n children: [{\n tag: 'div',\n attrs: {\n class: 'loader text-center'\n }\n }]\n }]));\n });\n }\n // eslint-disable-next-line max-statements\n static init(element, options = {}, builder = false) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.cdn = new CDN_js_1.default(_a.config.cdn, _a.config.cdnUrls || {});\n _a.config.libs = _a.config.libs || {\n uswds: {\n dependencies: ['fontawesome'],\n js: `${_a.cdn.uswds}/uswds.min.js`,\n css: `${_a.cdn.uswds}/uswds.min.css`,\n use: true\n },\n fontawesome: {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: `https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css`,\n globalStyle: `@font-face {\n font-family: 'FontAwesome';\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0');\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');\n font-weight: normal;\n font-style: normal;\n }`\n },\n bootstrap4: {\n dependencies: ['fontawesome'],\n css: `${_a.cdn.bootstrap4}/css/bootstrap.min.css`\n },\n bootstrap: {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootstrap}/css/bootstrap.min.css`\n },\n 'bootstrap-icons': {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: 'https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.min.css',\n globalStyle: `@font-face {\n font-display: block;\n font-family: \"bootstrap-icons\";\n src: url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6\") format(\"woff2\"),\n url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6\") format(\"woff\");\n }`\n }\n };\n // Add all bootswatch templates.\n ['cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', 'litera', 'lumen', 'lux', 'materia', 'minty', 'pulse', 'sandstone', 'simplex', 'sketchy', 'slate', 'solar', 'spacelab', 'superhero', 'united', 'yeti'].forEach((template) => {\n _a.config.libs[template] = {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootswatch}/dist/${template}/bootstrap.min.css`\n };\n });\n const id = _a.config.id || `formio-${Math.random().toString(36).substring(7)}`;\n // Create a new wrapper and add the element inside of a new wrapper.\n let wrapper = _a.createElement('div', {\n 'id': `${id}-wrapper`\n });\n element.parentNode.insertBefore(wrapper, element);\n // If we include the libraries, then we will attempt to run this in shadow dom.\n const useShadowDom = _a.config.includeLibs && !_a.config.noshadow && (typeof wrapper.attachShadow === 'function');\n if (useShadowDom) {\n wrapper = wrapper.attachShadow({\n mode: 'open'\n });\n options.shadowRoot = wrapper;\n }\n element.parentNode.removeChild(element);\n wrapper.appendChild(element);\n // If this is inside of shadow dom, then we need to add the styles and scripts to the shadow dom.\n const libWrapper = useShadowDom ? wrapper : document.body;\n // Load the renderer styles.\n yield _a.addStyles(libWrapper, _a.config.embedCSS || `${_a.cdn.js}/formio.embed.css`);\n // Add a loader.\n _a.addLoader(wrapper);\n const formioSrc = _a.config.full ? 'formio.full' : 'formio.form';\n const renderer = _a.config.debug ? formioSrc : `${formioSrc}.min`;\n _a.FormioClass = yield _a.addScript(libWrapper, _a.formioScript(_a.config.script || `${_a.cdn.js}/${renderer}.js`, builder), 'Formio', builder ? 'isBuilder' : 'isRenderer');\n _a.FormioClass.cdn = _a.cdn;\n _a.FormioClass.setBaseUrl(options.baseUrl || _a.baseUrl || _a.config.base);\n _a.FormioClass.setProjectUrl(options.projectUrl || _a.projectUrl || _a.config.project);\n _a.FormioClass.language = _a.language;\n _a.setLicense(_a.license || _a.config.license || false);\n _a.modules.forEach((module) => {\n _a.FormioClass.use(module);\n });\n if (_a.icons) {\n _a.FormioClass.icons = _a.icons;\n }\n if (_a.pathType) {\n _a.FormioClass.setPathType(_a.pathType);\n }\n // Add libraries if they wish to include the libs.\n if (_a.config.template && _a.config.includeLibs) {\n yield _a.addLibrary(libWrapper, _a.config.libs[_a.config.template], _a.config.template);\n }\n if (!_a.config.libraries) {\n _a.config.libraries = _a.config.modules || {};\n }\n // Adding premium if it is provided via the config.\n if (_a.config.premium) {\n _a.config.libraries.premium = _a.config.premium;\n }\n // Allow adding dynamic modules.\n if (_a.config.libraries) {\n for (const name in _a.config.libraries) {\n const lib = _a.config.libraries[name];\n lib.use = lib.use || true;\n yield _a.addLibrary(libWrapper, lib, name);\n }\n }\n yield _a.addStyles(libWrapper, _a.formioScript(_a.config.style || `${_a.cdn.js}/${renderer}.css`, builder));\n if (_a.config.before) {\n yield _a.config.before(_a.FormioClass, element, _a.config);\n }\n _a.FormioClass.license = true;\n _a._formioReady(_a.FormioClass);\n return wrapper;\n });\n }\n // Called after an instance has been created.\n static afterCreate(instance, wrapper, readyEvent) {\n return __awaiter(this, void 0, void 0, function* () {\n const loader = wrapper.querySelector('.formio-loader');\n if (loader) {\n wrapper.removeChild(loader);\n }\n _a.FormioClass.events.emit(readyEvent, instance);\n if (_a.config.after) {\n _a.debug('Calling ready callback');\n _a.config.after(instance, _a.config);\n }\n return instance;\n });\n }\n // Create a new form.\n static createForm(element, form, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (_a.FormioClass) {\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true }));\n }\n const wrapper = yield _a.init(element, options);\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true })).then((instance) => {\n // Set the default submission data.\n if (_a.config.submission) {\n _a.debug('Setting submission', _a.config.submission);\n instance.submission = _a.config.submission;\n }\n // Call the after create method.\n _a.afterCreate(instance, wrapper, 'formEmbedded');\n return instance;\n });\n });\n }\n // Create a form builder.\n static builder(element, form, options = {}) {\n var _b;\n return __awaiter(this, void 0, void 0, function* () {\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.builder) {\n return _a.FormioClass.builder(element, form, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.builder(element, form, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'builderEmbedded');\n return instance;\n });\n });\n }\n}\nexports.Formio = Formio;\n_a = Formio;\nFormio.FormioClass = null;\nFormio.config = {};\nFormio.modules = [];\nFormio.icons = '';\nFormio.license = '';\nFormio.formioReady = new Promise((ready, reject) => {\n _a._formioReady = ready;\n _a._formioReadyReject = reject;\n});\nFormio.version = '5.0.0-rc.66';\n// Create a report.\nFormio.Report = {\n create: (element, submission, options = {}) => __awaiter(void 0, void 0, void 0, function* () {\n var _b;\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.Report) {\n return _a.FormioClass.Report.create(element, submission, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.Report.create(element, submission, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'reportEmbedded');\n return instance;\n });\n })\n};\nCDN_js_1.default.defaultCDN = Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nclass Form {\n constructor(element, form, options) {\n this.form = form;\n this.element = element;\n this.options = options || {};\n this.init();\n this.instance = {\n proxy: true,\n ready: this.ready,\n destroy: () => { }\n };\n }\n init() {\n if (this.instance && !this.instance.proxy) {\n this.instance.destroy();\n }\n this.element.innerHTML = '';\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.form = instance.form;\n return instance;\n });\n }\n create() {\n return Formio.createForm(this.element, this.form, this.options);\n }\n setForm(form) {\n this.form = form;\n if (this.instance) {\n this.instance.setForm(form);\n }\n }\n setDisplay(display) {\n if (this.instance.proxy) {\n return this.ready;\n }\n this.form.display = display;\n this.instance.destroy();\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.setForm(this.form);\n });\n return this.ready;\n }\n}\nexports.Form = Form;\nclass FormBuilder extends Form {\n create() {\n return Formio.builder(this.element, this.form, this.options);\n }\n}\nexports.FormBuilder = FormBuilder;\nFormio.Form = Form;\nFormio.FormBuilder = FormBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Embed.js?");
|
9582
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.FormBuilder = exports.Form = exports.Formio = void 0;\nconst CDN_js_1 = __importDefault(__webpack_require__(/*! ./CDN.js */ \"./lib/cjs/CDN.js\"));\nclass Formio {\n static setLicense(license, norecurse = false) {\n _a.license = license;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setLicense(license);\n }\n }\n static setBaseUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setBaseUrl(url);\n }\n }\n static setApiUrl(url, norecurse = false) {\n _a.baseUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setApiUrl(url);\n }\n }\n static setProjectUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setProjectUrl(url);\n }\n }\n static setAppUrl(url, norecurse = false) {\n _a.projectUrl = url;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setAppUrl(url);\n }\n }\n static setPathType(type, norecurse = false) {\n _a.pathType = type;\n if (!norecurse && _a.FormioClass) {\n _a.FormioClass.setPathType(type);\n }\n }\n static debug(...args) {\n if (_a.config.debug) {\n console.log(...args);\n }\n }\n static clearCache() {\n if (_a.FormioClass) {\n _a.FormioClass.clearCache();\n }\n }\n static global(prop, flag = '') {\n const globalValue = window[prop];\n if (flag && globalValue && !globalValue[flag]) {\n return null;\n }\n _a.debug(`Getting global ${prop}`, globalValue);\n return globalValue;\n }\n static use(module) {\n if (_a.FormioClass && _a.FormioClass.isRenderer) {\n _a.FormioClass.use(module);\n }\n else {\n _a.modules.push(module);\n }\n }\n static createElement(type, attrs, children) {\n const element = document.createElement(type);\n if (!attrs) {\n return element;\n }\n Object.keys(attrs).forEach(key => {\n element.setAttribute(key, attrs[key]);\n });\n (children || []).forEach(child => {\n element.appendChild(_a.createElement(child.tag, child.attrs, child.children));\n });\n return element;\n }\n static addScript(wrapper, src, name, flag = '') {\n return __awaiter(this, void 0, void 0, function* () {\n if (!src) {\n return Promise.resolve();\n }\n if (typeof src !== 'string' && src.length) {\n return Promise.all(src.map(ref => _a.addScript(wrapper, ref)));\n }\n if (name && _a.global(name, flag)) {\n _a.debug(`${name} already loaded.`);\n return Promise.resolve(_a.global(name));\n }\n _a.debug('Adding Script', src);\n try {\n wrapper.appendChild(_a.createElement('script', {\n src\n }));\n }\n catch (err) {\n _a.debug(err);\n return Promise.resolve();\n }\n if (!name) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n _a.debug(`Waiting to load ${name}`);\n const wait = setInterval(() => {\n if (_a.global(name, flag)) {\n clearInterval(wait);\n _a.debug(`${name} loaded.`);\n resolve(_a.global(name));\n }\n }, 100);\n });\n });\n }\n static addStyles(wrapper, href) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!href) {\n return;\n }\n if (typeof href !== 'string' && href.length) {\n href.forEach(ref => _a.addStyles(wrapper, ref));\n return;\n }\n _a.debug('Adding Styles', href);\n wrapper.appendChild(_a.createElement('link', {\n rel: 'stylesheet',\n href\n }));\n });\n }\n static submitDone(instance, submission) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.debug('Submision Complete', submission);\n if (_a.config.submitDone) {\n _a.config.submitDone(submission, instance);\n }\n const successMessage = (_a.config.success || '').toString();\n if (successMessage && successMessage.toLowerCase() !== 'false' && instance.element) {\n instance.element.innerHTML = `<div class=\"alert-success\" role=\"alert\">${successMessage}</div>`;\n }\n let returnUrl = _a.config.redirect;\n // Allow form based configuration for return url.\n if (!returnUrl &&\n (instance._form &&\n instance._form.settings &&\n (instance._form.settings.returnUrl ||\n instance._form.settings.redirect))) {\n _a.debug('Return url found in form configuration');\n returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;\n }\n if (returnUrl) {\n const formSrc = instance.formio ? instance.formio.formUrl : '';\n const hasQuery = !!returnUrl.match(/\\?/);\n const isOrigin = returnUrl.indexOf(location.origin) === 0;\n returnUrl += hasQuery ? '&' : '?';\n returnUrl += `sub=${submission._id}`;\n if (!isOrigin && formSrc) {\n returnUrl += `&form=${encodeURIComponent(formSrc)}`;\n }\n _a.debug('Return URL', returnUrl);\n window.location.href = returnUrl;\n if (isOrigin) {\n window.location.reload();\n }\n }\n });\n }\n // Return the full script if the builder is being used.\n static formioScript(script, builder) {\n builder = builder || _a.config.includeBuilder;\n if (_a.fullAdded || builder) {\n _a.fullAdded = true;\n return script.replace('formio.form', 'formio.full');\n }\n return script;\n }\n static addLibrary(libWrapper, lib, name) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!lib) {\n return;\n }\n if (lib.dependencies) {\n for (let i = 0; i < lib.dependencies.length; i++) {\n const libName = lib.dependencies[i];\n yield _a.addLibrary(libWrapper, _a.config.libs[libName], libName);\n }\n }\n if (lib.css) {\n yield _a.addStyles((lib.global ? document.body : libWrapper), lib.css);\n }\n if (lib.js) {\n const module = yield _a.addScript((lib.global ? document.body : libWrapper), lib.js, lib.use ? name : false);\n if (lib.use) {\n _a.debug(`Using ${name}`);\n const options = lib.options || {};\n if (!options.license && _a.license) {\n options.license = _a.license;\n }\n _a.use((typeof lib.use === 'function' ? lib.use(module) : module), options);\n }\n }\n if (lib.globalStyle) {\n const style = _a.createElement('style');\n style.type = 'text/css';\n style.innerHTML = lib.globalStyle;\n document.body.appendChild(style);\n }\n });\n }\n static addLoader(wrapper) {\n return __awaiter(this, void 0, void 0, function* () {\n wrapper.appendChild(_a.createElement('div', {\n 'class': 'formio-loader'\n }, [{\n tag: 'div',\n attrs: {\n class: 'loader-wrapper'\n },\n children: [{\n tag: 'div',\n attrs: {\n class: 'loader text-center'\n }\n }]\n }]));\n });\n }\n // eslint-disable-next-line max-statements\n static init(element, options = {}, builder = false) {\n return __awaiter(this, void 0, void 0, function* () {\n _a.cdn = new CDN_js_1.default(_a.config.cdn, _a.config.cdnUrls || {});\n _a.config.libs = _a.config.libs || {\n uswds: {\n dependencies: ['fontawesome'],\n js: `${_a.cdn.uswds}/uswds.min.js`,\n css: `${_a.cdn.uswds}/uswds.min.css`,\n use: true\n },\n fontawesome: {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: `https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css`,\n globalStyle: `@font-face {\n font-family: 'FontAwesome';\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0');\n src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');\n font-weight: normal;\n font-style: normal;\n }`\n },\n bootstrap4: {\n dependencies: ['fontawesome'],\n css: `${_a.cdn.bootstrap4}/css/bootstrap.min.css`\n },\n bootstrap: {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootstrap}/css/bootstrap.min.css`\n },\n 'bootstrap-icons': {\n // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need\n // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page.\n css: 'https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.min.css',\n globalStyle: `@font-face {\n font-display: block;\n font-family: \"bootstrap-icons\";\n src: url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6\") format(\"woff2\"),\n url(\"https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6\") format(\"woff\");\n }`\n }\n };\n // Add all bootswatch templates.\n ['cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', 'litera', 'lumen', 'lux', 'materia', 'minty', 'pulse', 'sandstone', 'simplex', 'sketchy', 'slate', 'solar', 'spacelab', 'superhero', 'united', 'yeti'].forEach((template) => {\n _a.config.libs[template] = {\n dependencies: ['bootstrap-icons'],\n css: `${_a.cdn.bootswatch}/dist/${template}/bootstrap.min.css`\n };\n });\n const id = _a.config.id || `formio-${Math.random().toString(36).substring(7)}`;\n // Create a new wrapper and add the element inside of a new wrapper.\n let wrapper = _a.createElement('div', {\n 'id': `${id}-wrapper`\n });\n element.parentNode.insertBefore(wrapper, element);\n // If we include the libraries, then we will attempt to run this in shadow dom.\n const useShadowDom = _a.config.includeLibs && !_a.config.noshadow && (typeof wrapper.attachShadow === 'function');\n if (useShadowDom) {\n wrapper = wrapper.attachShadow({\n mode: 'open'\n });\n options.shadowRoot = wrapper;\n }\n element.parentNode.removeChild(element);\n wrapper.appendChild(element);\n // If this is inside of shadow dom, then we need to add the styles and scripts to the shadow dom.\n const libWrapper = useShadowDom ? wrapper : document.body;\n // Load the renderer styles.\n yield _a.addStyles(libWrapper, _a.config.embedCSS || `${_a.cdn.js}/formio.embed.css`);\n // Add a loader.\n _a.addLoader(wrapper);\n const formioSrc = _a.config.full ? 'formio.full' : 'formio.form';\n const renderer = _a.config.debug ? formioSrc : `${formioSrc}.min`;\n _a.FormioClass = yield _a.addScript(libWrapper, _a.formioScript(_a.config.script || `${_a.cdn.js}/${renderer}.js`, builder), 'Formio', builder ? 'isBuilder' : 'isRenderer');\n _a.FormioClass.cdn = _a.cdn;\n _a.FormioClass.setBaseUrl(options.baseUrl || _a.baseUrl || _a.config.base);\n _a.FormioClass.setProjectUrl(options.projectUrl || _a.projectUrl || _a.config.project);\n _a.FormioClass.language = _a.language;\n _a.setLicense(_a.license || _a.config.license || false);\n _a.modules.forEach((module) => {\n _a.FormioClass.use(module);\n });\n if (_a.icons) {\n _a.FormioClass.icons = _a.icons;\n }\n if (_a.pathType) {\n _a.FormioClass.setPathType(_a.pathType);\n }\n // Add libraries if they wish to include the libs.\n if (_a.config.template && _a.config.includeLibs) {\n yield _a.addLibrary(libWrapper, _a.config.libs[_a.config.template], _a.config.template);\n }\n if (!_a.config.libraries) {\n _a.config.libraries = _a.config.modules || {};\n }\n // Adding premium if it is provided via the config.\n if (_a.config.premium) {\n _a.config.libraries.premium = _a.config.premium;\n }\n // Allow adding dynamic modules.\n if (_a.config.libraries) {\n for (const name in _a.config.libraries) {\n const lib = _a.config.libraries[name];\n lib.use = lib.use || true;\n yield _a.addLibrary(libWrapper, lib, name);\n }\n }\n yield _a.addStyles(libWrapper, _a.formioScript(_a.config.style || `${_a.cdn.js}/${renderer}.css`, builder));\n if (_a.config.before) {\n yield _a.config.before(_a.FormioClass, element, _a.config);\n }\n _a.FormioClass.license = true;\n _a._formioReady(_a.FormioClass);\n return wrapper;\n });\n }\n // Called after an instance has been created.\n static afterCreate(instance, wrapper, readyEvent) {\n return __awaiter(this, void 0, void 0, function* () {\n const loader = wrapper.querySelector('.formio-loader');\n if (loader) {\n wrapper.removeChild(loader);\n }\n _a.FormioClass.events.emit(readyEvent, instance);\n if (_a.config.after) {\n _a.debug('Calling ready callback');\n _a.config.after(instance, _a.config);\n }\n return instance;\n });\n }\n // Create a new form.\n static createForm(element, form, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (_a.FormioClass) {\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true }));\n }\n const wrapper = yield _a.init(element, options);\n return _a.FormioClass.createForm(element, form, Object.assign(Object.assign({}, options), { noLoader: true })).then((instance) => {\n // Set the default submission data.\n if (_a.config.submission) {\n _a.debug('Setting submission', _a.config.submission);\n instance.submission = _a.config.submission;\n }\n // Call the after create method.\n _a.afterCreate(instance, wrapper, 'formEmbedded');\n return instance;\n });\n });\n }\n // Create a form builder.\n static builder(element, form, options = {}) {\n var _b;\n return __awaiter(this, void 0, void 0, function* () {\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.builder) {\n return _a.FormioClass.builder(element, form, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.builder(element, form, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'builderEmbedded');\n return instance;\n });\n });\n }\n}\nexports.Formio = Formio;\n_a = Formio;\nFormio.FormioClass = null;\nFormio.config = {};\nFormio.modules = [];\nFormio.icons = '';\nFormio.license = '';\nFormio.formioReady = new Promise((ready, reject) => {\n _a._formioReady = ready;\n _a._formioReadyReject = reject;\n});\nFormio.version = '5.0.0-rc.68';\n// Create a report.\nFormio.Report = {\n create: (element, submission, options = {}) => __awaiter(void 0, void 0, void 0, function* () {\n var _b;\n if ((_b = _a.FormioClass) === null || _b === void 0 ? void 0 : _b.Report) {\n return _a.FormioClass.Report.create(element, submission, options);\n }\n const wrapper = yield _a.init(element, options, true);\n return _a.FormioClass.Report.create(element, submission, options).then((instance) => {\n _a.afterCreate(instance, wrapper, 'reportEmbedded');\n return instance;\n });\n })\n};\nCDN_js_1.default.defaultCDN = Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nclass Form {\n constructor(element, form, options) {\n this.form = form;\n this.element = element;\n this.options = options || {};\n this.init();\n this.instance = {\n proxy: true,\n ready: this.ready,\n destroy: () => { }\n };\n }\n init() {\n if (this.instance && !this.instance.proxy) {\n this.instance.destroy();\n }\n this.element.innerHTML = '';\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.form = instance.form;\n return instance;\n });\n }\n create() {\n return Formio.createForm(this.element, this.form, this.options);\n }\n setForm(form) {\n this.form = form;\n if (this.instance) {\n this.instance.setForm(form);\n }\n }\n setDisplay(display) {\n if (this.instance.proxy) {\n return this.ready;\n }\n this.form.display = display;\n this.instance.destroy();\n this.ready = this.create().then((instance) => {\n this.instance = instance;\n this.setForm(this.form);\n });\n return this.ready;\n }\n}\nexports.Form = Form;\nclass FormBuilder extends Form {\n create() {\n return Formio.builder(this.element, this.form, this.options);\n }\n}\nexports.FormBuilder = FormBuilder;\nFormio.Form = Form;\nFormio.FormBuilder = FormBuilder;\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Embed.js?");
|
9583
9583
|
|
9584
9584
|
/***/ }),
|
9585
9585
|
|
@@ -9590,7 +9590,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument
|
|
9590
9590
|
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
9591
9591
|
|
9592
9592
|
"use strict";
|
9593
|
-
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst sdk_1 = __webpack_require__(/*! @formio/core/sdk */ \"./node_modules/@formio/core/lib/sdk/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return sdk_1.Formio; } }));\nconst Embed_1 = __webpack_require__(/*! ./Embed */ \"./lib/cjs/Embed.js\");\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\nsdk_1.Formio.cdn = new CDN_1.default();\nsdk_1.Formio.Providers = providers_1.default;\nsdk_1.Formio.version = '5.0.0-rc.
|
9593
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Formio = void 0;\nconst sdk_1 = __webpack_require__(/*! @formio/core/sdk */ \"./node_modules/@formio/core/lib/sdk/index.js\");\nObject.defineProperty(exports, \"Formio\", ({ enumerable: true, get: function () { return sdk_1.Formio; } }));\nconst Embed_1 = __webpack_require__(/*! ./Embed */ \"./lib/cjs/Embed.js\");\nconst CDN_1 = __importDefault(__webpack_require__(/*! ./CDN */ \"./lib/cjs/CDN.js\"));\nconst providers_1 = __importDefault(__webpack_require__(/*! ./providers */ \"./lib/cjs/providers/index.js\"));\nsdk_1.Formio.cdn = new CDN_1.default();\nsdk_1.Formio.Providers = providers_1.default;\nsdk_1.Formio.version = '5.0.0-rc.68';\nCDN_1.default.defaultCDN = sdk_1.Formio.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io';\nconst isNil = (val) => val === null || val === undefined;\nsdk_1.Formio.prototype.uploadFile = function (storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback, multipartOptions) {\n const requestArgs = {\n provider: storage,\n method: 'upload',\n file: file,\n fileName: fileName,\n dir: dir\n };\n fileKey = fileKey || 'file';\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', storage);\n if (Provider) {\n const provider = new Provider(this);\n if (uploadStartCallback) {\n uploadStartCallback();\n }\n return provider.uploadFile(file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, abortCallback, multipartOptions);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.downloadFile = function (file, options) {\n const requestArgs = {\n method: 'download',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.downloadFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\nsdk_1.Formio.prototype.deleteFile = function (file, options) {\n const requestArgs = {\n method: 'delete',\n file: file\n };\n const request = sdk_1.Formio.pluginWait('preRequest', requestArgs)\n .then(() => {\n return sdk_1.Formio.pluginGet('fileRequest', requestArgs)\n .then((result) => {\n if (file.storage && isNil(result)) {\n const Provider = providers_1.default.getProvider('storage', file.storage);\n if (Provider) {\n const provider = new Provider(this);\n return provider.deleteFile(file, options);\n }\n else {\n throw ('Storage provider not found');\n }\n }\n return result || { url: '' };\n });\n });\n return sdk_1.Formio.pluginAlter('wrapFileRequestPromise', request, requestArgs);\n};\n// Esnure we proxy the following methods to the FormioEmbed class.\n['setBaseUrl', 'setApiUrl', 'setAppUrl', 'setProjectUrl', 'setPathType', 'setLicense'].forEach((fn) => {\n const baseFn = sdk_1.Formio[fn];\n sdk_1.Formio[fn] = function (arg) {\n const retVal = Embed_1.Formio[fn](arg, true);\n return baseFn ? baseFn.call(this, arg) : retVal;\n };\n});\n// For reverse compatability.\nsdk_1.Formio.Promise = Promise;\nsdk_1.Formio.formioReady = Embed_1.Formio.formioReady;\nsdk_1.Formio.config = Embed_1.Formio.config;\nsdk_1.Formio.builder = Embed_1.Formio.builder;\nsdk_1.Formio.Report = Embed_1.Formio.Report;\nsdk_1.Formio.Form = Embed_1.Formio.Form;\nsdk_1.Formio.FormBuilder = Embed_1.Formio.FormBuilder;\nsdk_1.Formio.use = Embed_1.Formio.use;\nsdk_1.Formio.createForm = Embed_1.Formio.createForm;\nsdk_1.Formio.submitDone = Embed_1.Formio.submitDone;\nsdk_1.Formio.addLibrary = Embed_1.Formio.addLibrary;\nsdk_1.Formio.addLoader = Embed_1.Formio.addLoader;\nsdk_1.Formio.addToGlobal = (global) => {\n if (typeof global === 'object' && !global.Formio) {\n global.Formio = sdk_1.Formio;\n }\n};\nif (typeof __webpack_require__.g !== 'undefined') {\n sdk_1.Formio.addToGlobal(__webpack_require__.g);\n}\nif (typeof window !== 'undefined') {\n sdk_1.Formio.addToGlobal(window);\n}\nEmbed_1.Formio._formioReady(sdk_1.Formio);\n\n\n//# sourceURL=webpack://Formio/./lib/cjs/Formio.js?");
|
9594
9594
|
|
9595
9595
|
/***/ }),
|
9596
9596
|
|