@skireal/form-builder
Version:
Form builder for Angular apps
1,089 lines (1,079 loc) • 169 kB
JavaScript
import { __decorate, __spread, __values, __assign, __read } from 'tslib';
import { EventEmitter, Input, Output, Component, ViewEncapsulation, ɵɵdefineInjectable, ɵɵinject, Injectable, ApplicationRef, ComponentFactoryResolver, Injector, INJECTOR, Pipe, NgModule } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { moveItemInArray, DragDropModule } from '@angular/cdk/drag-drop';
import { BehaviorSubject } from 'rxjs';
import { CommonModule } from '@angular/common';
var FormBuilderComponent = /** @class */ (function () {
function FormBuilderComponent() {
this.enableGeneralFields = true;
this.enableConditionalLogicBlocks = false;
this.isSurvey = true;
this.incomingFormData = '';
this.enableSetValidationOptions = false;
this.locale = {};
this.jsonCreated = new EventEmitter();
this.formData = {
formData: {
steps: [],
generalFields: []
},
options: {
name: '',
type: '',
country: ''
},
uniqueFormData: []
};
}
FormBuilderComponent.prototype.ngOnInit = function () {
this.formData = JSON.parse(this.incomingFormData);
};
FormBuilderComponent.prototype.onSaveClicked = function ($event) {
var jsonData = JSON.stringify($event);
this.jsonCreated.emit(jsonData);
};
__decorate([
Input()
], FormBuilderComponent.prototype, "enableGeneralFields", void 0);
__decorate([
Input()
], FormBuilderComponent.prototype, "enableConditionalLogicBlocks", void 0);
__decorate([
Input()
], FormBuilderComponent.prototype, "isSurvey", void 0);
__decorate([
Input()
], FormBuilderComponent.prototype, "incomingFormData", void 0);
__decorate([
Input()
], FormBuilderComponent.prototype, "enableSetValidationOptions", void 0);
__decorate([
Input()
], FormBuilderComponent.prototype, "locale", void 0);
__decorate([
Output()
], FormBuilderComponent.prototype, "jsonCreated", void 0);
FormBuilderComponent = __decorate([
Component({
selector: 'form-builder',
template: "<div>\n <app-ui\n (saveClicked)=\"onSaveClicked($event)\"\n [enableGeneralFields]=\"enableGeneralFields\"\n [enableConditionalLogicBlocks]=\"enableConditionalLogicBlocks\"\n [isSurvey]=\"isSurvey\"\n [incomingFormData]=\"formData\"\n [enableSetValidationOptions]=\"enableSetValidationOptions\"\n [locale]=\"locale\">\n </app-ui>\n</div>\n",
encapsulation: ViewEncapsulation.None,
styles: ["@font-face{font-display:block;font-family:bootstrap-icons;src:url(https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6) format(\"woff2\"),url(https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6) format(\"woff\")}:root{--fb-body-bg:#fff;--fb-body-color:#212529;--fb-border-radius:0.375rem;--fb-border-radius-lg:0.5rem;--fb-border-width:1px;--fb-border-color:#dee2e6;--fb-body-font-family:var(--fb-font-sans-serif);--fb-body-font-weight:400;--fb-body-line-height:1.5;--fb-font-sans-serif:system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",\"Noto Sans\",\"Liberation Sans\",Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\",\"Segoe UI Symbol\",\"Noto Color Emoji\";--fb-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,\"Liberation Mono\",\"Courier New\",monospace}input.ng-invalid.ng-touched{border:1px solid red;box-shadow:0 0 0 .1rem rgba(255,76,76,.966)}.cdk-drag-preview{z-index:10000005!important}.form-builder__form-control{display:block;width:100%;height:auto;box-sizing:border-box;padding:6px 12px;font-size:16px;font-weight:400;line-height:1.5;text-align:start;color:#212529;background-color:#fff;border:.8px solid #dee2e6;border-radius:6px;box-shadow:none;cursor:text;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;-moz-appearance:none;appearance:none}.form-builder__form-control-sm{padding:4px 8px;font-size:13px;border-radius:3px}.form-builder__form-select{display:block;align-items:center;box-sizing:border-box;width:100%;padding:6px 12px;overflow:visible;font-size:16px;font-weight:400;line-height:1.5;text-align:start;color:#212529;background-color:#fff;background-image:url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e\");background-position:calc(100% - 12px) 50%;background-repeat:no-repeat;background-size:16px 12px;border:.8px solid #dee2e6;border-radius:6px;box-shadow:none;cursor:default;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;-moz-appearance:none;appearance:none;pointer-events:auto}.form-builder__form-select:focus{border-color:#86b7fe;outline:0;box-shadow:0 0 0 .05rem rgba(13,110,253,.25)}.text-right{text-align:right!important}.text-left{text-align:left!important}.text-center{text-align:center!important}.form-builder__row .form-builder__col{flex-shrink:0;width:100%;max-width:100%;padding-right:12px;padding-left:12px}.form-builder__row{display:flex;flex-wrap:wrap;margin-left:-12px;margin-right:-12px}.form-builder__col{flex:1 0 0%}.p-0{padding:0!important}@media (min-width:1200px){.form-builder__col-xl-2{flex:0 0 auto;width:16.66666667%}}"]
})
], FormBuilderComponent);
return FormBuilderComponent;
}());
var _a, _b;
var FormFieldType;
(function (FormFieldType) {
FormFieldType["Text"] = "text";
FormFieldType["Textarea"] = "textarea";
FormFieldType["Date"] = "date";
FormFieldType["Select"] = "select";
FormFieldType["Number"] = "number";
FormFieldType["Checkbox"] = "checkbox";
FormFieldType["CheckboxGroup"] = "checkbox-group";
FormFieldType["Radio"] = "radio";
FormFieldType["NeedContact"] = "need-contact";
FormFieldType["File"] = "file";
FormFieldType["Password"] = "password";
FormFieldType["Email"] = "email";
FormFieldType["Phone"] = "phone";
FormFieldType["Likert"] = "likert";
FormFieldType["Csat"] = "csat";
FormFieldType["CES"] = "ces";
FormFieldType["NPS"] = "nps";
FormFieldType["QE"] = "qe";
FormFieldType["ContactName"] = "contact-name";
FormFieldType["ContactSurname"] = "contact-surname";
FormFieldType["ContactEmail"] = "contact-email";
FormFieldType["ContactPhone"] = "contact-phone";
FormFieldType["CountryDropdown"] = "country-dropdown";
})(FormFieldType || (FormFieldType = {}));
var ValidatorType;
(function (ValidatorType) {
ValidatorType["Required"] = "required";
ValidatorType["MinLength"] = "minlength";
ValidatorType["MaxLength"] = "maxlength";
ValidatorType["Pattern"] = "pattern";
ValidatorType["Email"] = "email";
ValidatorType["Min"] = "min";
ValidatorType["Max"] = "max";
ValidatorType["RequiredTrue"] = "requiredTrue";
})(ValidatorType || (ValidatorType = {}));
var formFieldTypes = [
FormFieldType.Text,
FormFieldType.Textarea,
FormFieldType.Date,
FormFieldType.Select,
FormFieldType.Number,
FormFieldType.Checkbox,
FormFieldType.CheckboxGroup,
FormFieldType.Radio,
FormFieldType.NeedContact,
FormFieldType.File,
FormFieldType.Password,
FormFieldType.Email,
FormFieldType.Phone,
FormFieldType.Likert,
FormFieldType.Csat,
FormFieldType.CES,
FormFieldType.NPS,
FormFieldType.QE
];
var surveyFieldTypes = [
FormFieldType.CountryDropdown,
FormFieldType.Text,
FormFieldType.Textarea,
FormFieldType.Date,
FormFieldType.Select,
FormFieldType.Checkbox,
FormFieldType.CheckboxGroup,
FormFieldType.Radio,
FormFieldType.Likert,
FormFieldType.Csat,
FormFieldType.CES,
FormFieldType.NPS,
FormFieldType.QE,
FormFieldType.NeedContact,
FormFieldType.ContactName,
FormFieldType.ContactSurname,
FormFieldType.ContactEmail,
FormFieldType.ContactPhone
];
var fieldTypesNames = (_a = {},
_a[FormFieldType.CountryDropdown] = 'Country',
_a[FormFieldType.Text] = 'Text Input',
_a[FormFieldType.Textarea] = 'Text Area',
_a[FormFieldType.Date] = 'Date',
_a[FormFieldType.Select] = 'Select',
_a[FormFieldType.Number] = 'Number',
_a[FormFieldType.Checkbox] = 'Checkbox',
_a[FormFieldType.CheckboxGroup] = 'Checkboxes',
_a[FormFieldType.Radio] = 'Radio',
_a[FormFieldType.File] = 'File Attachment',
_a[FormFieldType.Password] = 'Password',
_a[FormFieldType.Email] = 'Email',
_a[FormFieldType.Phone] = 'Phone Number',
_a[FormFieldType.Likert] = 'Likert Scale',
_a[FormFieldType.Csat] = 'CSAT Scale',
_a[FormFieldType.CES] = 'CES Scale',
_a[FormFieldType.NPS] = 'NPS Scale',
_a[FormFieldType.QE] = 'QE Group',
_a[FormFieldType.NeedContact] = 'Need Contact',
_a[FormFieldType.ContactName] = 'Contact Name',
_a[FormFieldType.ContactSurname] = 'Contact Surname',
_a[FormFieldType.ContactEmail] = 'Contact Email',
_a[FormFieldType.ContactPhone] = 'Contact Phone',
_a);
var uniqueFieldTypes = [
FormFieldType.NeedContact,
FormFieldType.ContactName,
FormFieldType.ContactSurname,
FormFieldType.ContactEmail,
FormFieldType.ContactPhone
];
var validatorTypes = [
ValidatorType.Required,
ValidatorType.MinLength,
ValidatorType.MaxLength,
ValidatorType.Pattern,
ValidatorType.Email,
ValidatorType.Min,
ValidatorType.Max,
ValidatorType.RequiredTrue
];
var commonFields = [
{ id: 'active', name: 'Active', isArray: false },
{ id: 'classes', name: 'Classes', isArray: false, placeholder: 'e.g., class1 class2' },
{ id: 'placeholder', name: 'Placeholder', isArray: false },
{ id: 'title', name: 'Title', isArray: false },
{ id: 'description', name: 'Description', isArray: false },
{ id: 'validators', name: 'Validators', isArray: true },
{ id: 'required', name: 'Required', isArray: false },
{ id: 'warningMessage', name: 'Warning message', isArray: false },
{ id: 'analyticsTitle', name: 'Analytics title', isArray: false },
{ id: 'step', name: 'Move to step', isArray: false }
];
var fieldsByType = (_b = {},
_b[FormFieldType.Text] = __spread(commonFields, [
{ id: 'feedBackText', name: 'Use this field when creating feedback text', isArray: false }
]),
_b[FormFieldType.Textarea] = __spread(commonFields, [
{ id: 'feedBackText', name: 'Use this field when creating feedback text', isArray: false }
]),
_b[FormFieldType.Date] = __spread(commonFields),
_b[FormFieldType.Select] = __spread(commonFields, [
{ id: 'options', name: 'Options', isArray: true },
{ id: 'hasOther', name: 'Has other', isArray: false }
]),
_b[FormFieldType.Number] = __spread(commonFields),
_b[FormFieldType.Checkbox] = __spread(commonFields),
_b[FormFieldType.CheckboxGroup] = __spread(commonFields, [
{ id: 'options', name: 'Options', isArray: true },
{ id: 'hasOther', name: 'Has other', isArray: false }
]),
_b[FormFieldType.Radio] = __spread(commonFields, [
{ id: 'options', name: 'Options', isArray: true },
{ id: 'hasOther', name: 'Has other', isArray: false }
]),
_b[FormFieldType.NeedContact] = __spread(commonFields, [
{ id: 'options', name: 'Options', isArray: true },
{ id: 'defaultValue', name: 'Default value', isArray: false }
]),
_b[FormFieldType.File] = __spread(commonFields),
_b[FormFieldType.Password] = __spread(commonFields),
_b[FormFieldType.Email] = __spread(commonFields),
_b[FormFieldType.Phone] = __spread(commonFields),
_b[FormFieldType.Likert] = __spread(commonFields, [
{ id: 'optionsTitle', name: 'Options title', isArray: false },
{ id: 'options', name: 'Options', isArray: true },
{ id: 'rows', name: 'Rows', isArray: true }
]),
_b[FormFieldType.Csat] = __spread(commonFields, [
{ id: 'firstAnswer', name: 'First answer', isArray: false },
{ id: 'lastAnswer', name: 'Last answer', isArray: false },
{ id: 'hasNA', name: 'Has N/A', isArray: false }
]),
_b[FormFieldType.CES] = __spread(commonFields, [{ id: 'hasNA', name: 'Has N/A', isArray: false }]),
_b[FormFieldType.NPS] = __spread(commonFields, [
{
id: 'comment',
name: 'Comment',
isArray: false,
isObject: true,
objectFields: [
{ id: 'commentTitle', name: 'Comment Title', isArray: false },
{ id: 'commentSubtitle', name: 'Comment Subtitle', isArray: false },
{ id: 'commentWarningMessage', name: 'Comment Warning Message', isArray: false }
]
},
{ id: 'firstAnswer', name: 'First answer', isArray: false },
{ id: 'lastAnswer', name: 'Last answer', isArray: false }
]),
_b[FormFieldType.QE] = __spread(commonFields, [
{ id: 'firstAnswer', name: 'First answer', isArray: false },
{ id: 'lastAnswer', name: 'Last answer', isArray: false },
{
id: 'qeScales',
name: 'QE scales',
isArray: true,
children: [
{
id: 'qeScaleChildren',
name: 'QE Scale Children',
isArray: true,
parentArray: 'qeScales'
}
]
}
]),
_b[FormFieldType.ContactName] = __spread(commonFields),
_b[FormFieldType.ContactSurname] = __spread(commonFields),
_b[FormFieldType.ContactEmail] = __spread(commonFields),
_b[FormFieldType.ContactPhone] = __spread(commonFields),
_b[FormFieldType.CountryDropdown] = __spread(commonFields),
_b);
var defaultOptionValues = [];
var controlsMap = {
validators: ['type', 'value', 'errormsg'],
options: ['name', 'value', 'country'],
rows: ['title'],
qeScales: ['title', 'subtitle', 'qeScaleChildren'],
qeScaleChildren: ['title']
};
var defaultConditionalLogicBlock = {
selectedField: {
type: '',
id: '',
name: ''
},
selectedCondition: '',
conditionValue: '',
selectedAction: '',
selectedTargetField: '',
type: 'conditionalLogicBlock'
};
var conditionOptions = {
text: ['equals', 'contains', 'is empty', 'is not empty'],
checkbox: ['is empty', 'is not empty'],
number: [
'equals',
'not equals',
'greater',
'less',
'greater or equals',
'less or equals',
'is empty',
'is not empty'
]
};
var haveOptionsFieldTypes = [
'select',
'checkbox-group',
'radio',
'likert',
'need-contact'
];
var withoutValueValidatorTypes = ['required', 'requiredTrue', 'email'];
var booleanFields = ['active', 'required', 'hasOther', 'hasNA'];
var arrayProperties = ['validators', 'options', 'rows', 'qeScales'];
var defaultValuesMap = {
options: {
country: 'ZZ'
}
};
var maxLengthMap = {
placeholder: 250,
title: 1000,
warningMessage: 1000,
analyticsTitle: 250
};
var requiredSubfieldsMap = {
options: ['name', 'value'],
rows: ['title'],
qeScales: ['title']
};
var UiFormService = /** @class */ (function () {
function UiFormService(fb) {
this.fb = fb;
this.fieldsToCreate = [];
this.fieldsToCreateSubject = new BehaviorSubject(this.fieldsToCreate);
}
UiFormService.prototype.createFormGroup = function (addedFields) {
var formGroupConfig = this.generateFormGroupConfig(addedFields);
return this.fb.group(formGroupConfig);
};
UiFormService.prototype.generateFormGroupConfig = function (addedFields) {
var e_1, _a;
var formGroupConfig = {};
try {
for (var addedFields_1 = __values(addedFields), addedFields_1_1 = addedFields_1.next(); !addedFields_1_1.done; addedFields_1_1 = addedFields_1.next()) {
var field = addedFields_1_1.value;
formGroupConfig[field.id] = this.createControlForField(field);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (addedFields_1_1 && !addedFields_1_1.done && (_a = addedFields_1.return)) _a.call(addedFields_1);
}
finally { if (e_1) throw e_1.error; }
}
return formGroupConfig;
};
UiFormService.prototype.createControlForField = function (field) {
if (field.isArray) {
return this.createFormArray();
}
else if (field.isObject && field.objectFields) {
return this.createFormGroupForObject(field.objectFields);
}
else {
return this.createControl(field.defaultValue);
}
};
UiFormService.prototype.createFormGroupForObject = function (objectFields) {
var e_2, _a;
var formGroupConfig = {};
try {
for (var objectFields_1 = __values(objectFields), objectFields_1_1 = objectFields_1.next(); !objectFields_1_1.done; objectFields_1_1 = objectFields_1.next()) {
var field = objectFields_1_1.value;
formGroupConfig[field.id] = this.createControlForField(field);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (objectFields_1_1 && !objectFields_1_1.done && (_a = objectFields_1.return)) _a.call(objectFields_1);
}
finally { if (e_2) throw e_2.error; }
}
return this.fb.group(formGroupConfig);
};
UiFormService.prototype.createControl = function (defaultValue) {
if (defaultValue === void 0) { defaultValue = ''; }
return this.fb.control(defaultValue);
};
UiFormService.prototype.createFormArray = function () {
return this.fb.array([]);
};
UiFormService.prototype.addControlToFormArray = function (formArray, arrayName, nestedArrayConfig) {
var newGroup = this.createGroupForArray(arrayName, nestedArrayConfig);
formArray.push(newGroup);
};
UiFormService.prototype.removeControlFromFormArray = function (formArray, index) {
formArray.removeAt(index);
};
UiFormService.prototype.createGroupForArray = function (arrayName, nestedArrayConfig) {
var _this = this;
var group = this.fb.group({});
var controlFields = controlsMap[arrayName] || [];
if (controlFields) {
controlFields.forEach(function (fieldName) {
var _a;
if (nestedArrayConfig && fieldName in nestedArrayConfig) {
group.addControl(fieldName, nestedArrayConfig[fieldName]);
}
else {
var defaultValue = ((_a = defaultValuesMap[arrayName]) === null || _a === void 0 ? void 0 : _a[fieldName]) || '';
group.addControl(fieldName, _this.createControl(defaultValue));
}
});
}
else {
console.log("Invalid controlName: " + arrayName);
}
return group;
};
UiFormService.prototype.saveFieldProperties = function (form, fieldType) {
var _this = this;
var _a, _b;
var fieldOptions = __assign(__assign({}, form.value), { validators: (_a = form.value.validators) === null || _a === void 0 ? void 0 : _a.filter(function (validator) {
return Object.values(validator).some(function (property) { return property !== ''; });
}), type: fieldType, id: this.generateUniqueId().toString(), options: (_b = form.value.options) === null || _b === void 0 ? void 0 : _b.map(function (option) { return (__assign(__assign({}, option), { id: _this.generateUniqueId().toString() })); }) });
booleanFields.forEach(function (field) {
if (typeof fieldOptions[field] !== 'boolean') {
fieldOptions[field] = false;
}
});
if (fieldType === 'nps' && form.value.comment) {
var isCommentEmpty = Object.values(fieldOptions.comment || {}).every(function (value) { return value === '' || value === null || value === undefined; });
if (!isCommentEmpty) {
fieldOptions.comment = __assign(__assign({}, fieldOptions.comment), { commentId: this.generateUniqueId().toString() });
}
}
if (fieldType === 'qe' && form.value.qeScales) {
fieldOptions.qeScales = form.value.qeScales.map(function (scale) {
var _a;
return (__assign(__assign({}, scale), { id: _this.generateUniqueId().toString(), qeScaleChildren: (_a = scale.qeScaleChildren) === null || _a === void 0 ? void 0 : _a.map(function (child) { return (__assign(__assign({}, child), { id: _this.generateUniqueId().toString() })); }) }));
});
}
if (fieldType === 'likert' && form.value.rows) {
fieldOptions.rows = form.value.rows.map(function (row) { return (__assign(__assign({}, row), { id: _this.generateUniqueId().toString() })); });
}
return fieldOptions;
};
UiFormService.prototype.generateUniqueId = function () {
return Math.floor(Math.random() * 100000000).toString();
};
UiFormService.prototype.setFieldsToCreate = function (fieldType) {
this.fieldsToCreate = fieldsByType[fieldType];
this.fieldsToCreateSubject.next(this.fieldsToCreate);
};
UiFormService.prototype.getFieldsToCreate = function () {
return this.fieldsToCreateSubject.asObservable();
};
UiFormService.prototype.getRequiredFields = function (fieldType) {
var baseFields = ['title', 'analyticsTitle'];
var typeSpecificFields = {
select: ['options'],
'checkbox-group': ['options'],
radio: ['options'],
likert: ['options', 'rows'],
qe: ['qeScales']
};
return __spread(baseFields, (typeSpecificFields[fieldType] || []));
};
UiFormService.ctorParameters = function () { return [
{ type: FormBuilder }
]; };
UiFormService.ɵprov = ɵɵdefineInjectable({ factory: function UiFormService_Factory() { return new UiFormService(ɵɵinject(FormBuilder)); }, token: UiFormService, providedIn: "root" });
UiFormService = __decorate([
Injectable({
providedIn: 'root'
})
], UiFormService);
return UiFormService;
}());
var defaultFormOptionsObject = {
formData: {
steps: [
{
addedFields: [
{
id: 'id',
name: 'name',
title: 'title'
}
],
conditionalLogicBlocks: []
}
],
generalFields: []
},
options: {
name: 'formName',
type: 'formType',
country: 'NG'
},
uniqueFormData: []
};
var FormDataService = /** @class */ (function () {
function FormDataService() {
this.formOptionsFull = new BehaviorSubject(defaultFormOptionsObject);
}
FormDataService.prototype.setFormData = function (data) {
this.formOptionsFull.next(data);
};
FormDataService.prototype.getFormData = function () {
return this.formOptionsFull.asObservable();
};
FormDataService.prototype.prepareFormData = function (formData) {
var formOptionsFullObject = formData;
var formDataSteps = formData.formData.steps;
formDataSteps.forEach(function (stepFormData, index) {
var stepData = [];
stepFormData.addedFields.forEach(function (field) {
var _a, _b, _c;
var fieldData = __assign({}, field);
if ('step' in fieldData) {
delete fieldData.step;
}
if (fieldData.type === 'need-contact') {
delete fieldData.options;
}
var hasNonRequiredValidator = (_a = field.validators) === null || _a === void 0 ? void 0 : _a.some(function (validator) { return validator.type !== 'required'; });
var hasRequiredValidator = (_b = field.validators) === null || _b === void 0 ? void 0 : _b.some(function (validator) { return validator.type === 'required'; });
if (hasNonRequiredValidator && !hasRequiredValidator) {
(_c = fieldData.validators) === null || _c === void 0 ? void 0 : _c.push({
type: 'required',
errormsg: 'This field is required'
});
}
stepData.push(fieldData);
});
formOptionsFullObject.formData.steps[index] = {
title: "Step " + (index + 1),
addedFields: stepData,
conditionalLogicBlocks: stepFormData.conditionalLogicBlocks
};
});
return formOptionsFullObject;
};
FormDataService.ɵprov = ɵɵdefineInjectable({ factory: function FormDataService_Factory() { return new FormDataService(); }, token: FormDataService, providedIn: "root" });
FormDataService = __decorate([
Injectable({
providedIn: 'root'
})
], FormDataService);
return FormDataService;
}());
var ConfirmationDialogComponent = /** @class */ (function () {
function ConfirmationDialogComponent() {
this.message = 'Are you sure?';
this.confirm = new EventEmitter();
}
ConfirmationDialogComponent.prototype.ngOnInit = function () { };
ConfirmationDialogComponent.prototype.confirmAction = function () {
this.confirm.emit(true);
};
ConfirmationDialogComponent.prototype.cancelAction = function () {
this.confirm.emit(false);
};
__decorate([
Input()
], ConfirmationDialogComponent.prototype, "message", void 0);
__decorate([
Output()
], ConfirmationDialogComponent.prototype, "confirm", void 0);
ConfirmationDialogComponent = __decorate([
Component({
selector: 'app-confirmation-dialog',
template: "<div class=\"form-builder__confirmation-dialog\">\n <div class=\"form-builder__confirmation-dialog__content\">\n <p>{{ message }}</p>\n <div class=\"form-builder__confirmation-dialog__actions\">\n <button (click)=\"confirmAction()\" class=\"form-builder__btn form-builder__btn-primary\">\n Yes\n </button>\n <button (click)=\"cancelAction()\" class=\"form-builder__btn form-builder__btn-secondary\">\n No\n </button>\n </div>\n </div>\n</div>\n",
styles: [".form-builder__btn{display:inline-block;box-sizing:border-box;align-items:flex-start;padding:6px 12px;font-weight:400;text-align:center;-webkit-text-decoration:none #fff solid auto;text-decoration:none #fff solid auto;text-indent:0;text-shadow:none;text-transform:none;vertical-align:middle;word-spacing:normal;letter-spacing:normal;line-height:24px;color:#fff;background-color:rgba(169,157,184,.8);border:.8px solid rgba(169,157,184,.8);border-radius:6px;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;pointer-events:auto;text-rendering:auto;-webkit-appearance:auto;-moz-appearance:auto;appearance:auto}.form-builder__btn-sm{padding:3px 10px;font-size:.75rem}.form-builder__btn-primary{background-color:rgba(169,157,184,.8);border-color:rgba(169,157,184,.8)}.form-builder__btn-primary:active,.form-builder__btn-primary:hover{background-color:#a99db8;border-color:#a99db8}.form-builder__btn-secondary{background-color:rgba(148,169,160,.8);border-color:rgba(148,169,160,.8)}.form-builder__btn-secondary:active,.form-builder__btn-secondary:hover{background-color:#94a9a0;border-color:#94a9a0}.form-builder__btn-danger{background-color:rgba(230,88,88,.8);border-color:rgba(230,88,88,.8)}.form-builder__btn-danger:active,.form-builder__btn-danger:hover{background-color:#e65858;border-color:#e65858}.form-builder__btn-success{background-color:rgba(81,167,76,.8);border-color:rgba(81,167,76,.8)}.form-builder__btn-success:active,.form-builder__btn-success:hover{background-color:#51a74c;border-color:#51a74c}.form-builder__confirmation-dialog{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);display:flex;justify-content:center;align-items:center;z-index:505}.form-builder__confirmation-dialog__actions{margin-bottom:5px;margin-top:5px;text-align:center}.form-builder__confirmation-dialog__actions .form-builder__btn{margin-right:10px}.form-builder__confirmation-dialog__actions .form-builder__btn:last-child{margin-right:0}.form-builder__confirmation-dialog__content{background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.2);text-align:center}"]
})
], ConfirmationDialogComponent);
return ConfirmationDialogComponent;
}());
var ConfirmationService = /** @class */ (function () {
function ConfirmationService(appRef, componentFactoryResolver, injector) {
this.appRef = appRef;
this.componentFactoryResolver = componentFactoryResolver;
this.injector = injector;
this.dialogComponentRef = null;
}
ConfirmationService.prototype.open = function (message) {
var _this = this;
return new Promise(function (resolve) {
var factory = _this.componentFactoryResolver.resolveComponentFactory(ConfirmationDialogComponent);
_this.dialogComponentRef = factory.create(_this.injector);
_this.dialogComponentRef.instance.message = message;
_this.dialogComponentRef.instance.confirm.subscribe(function (result) {
resolve(result);
_this.close();
});
_this.appRef.attachView(_this.dialogComponentRef.hostView);
var domElem = _this.dialogComponentRef.hostView.rootNodes[0];
document.body.appendChild(domElem);
});
};
ConfirmationService.prototype.close = function () {
if (this.dialogComponentRef) {
this.appRef.detachView(this.dialogComponentRef.hostView);
this.dialogComponentRef.destroy();
this.dialogComponentRef = null;
}
};
ConfirmationService.ctorParameters = function () { return [
{ type: ApplicationRef },
{ type: ComponentFactoryResolver },
{ type: Injector }
]; };
ConfirmationService.ɵprov = ɵɵdefineInjectable({ factory: function ConfirmationService_Factory() { return new ConfirmationService(ɵɵinject(ApplicationRef), ɵɵinject(ComponentFactoryResolver), ɵɵinject(INJECTOR)); }, token: ConfirmationService, providedIn: "root" });
ConfirmationService = __decorate([
Injectable({
providedIn: 'root'
})
], ConfirmationService);
return ConfirmationService;
}());
var LocaleService = /** @class */ (function () {
function LocaleService() {
this.localeSubject = new BehaviorSubject({});
this.locale$ = this.localeSubject.asObservable();
}
LocaleService.prototype.setLocale = function (locale) {
this.localeSubject.next(locale);
};
LocaleService.prototype.getCurrentLocale = function () {
return this.localeSubject.value;
};
LocaleService.ɵprov = ɵɵdefineInjectable({ factory: function LocaleService_Factory() { return new LocaleService(); }, token: LocaleService, providedIn: "root" });
LocaleService = __decorate([
Injectable({
providedIn: 'root'
})
], LocaleService);
return LocaleService;
}());
var UIComponent = /** @class */ (function () {
function UIComponent(uiFormService, formDataService, confirmationService, localeService) {
this.uiFormService = uiFormService;
this.formDataService = formDataService;
this.confirmationService = confirmationService;
this.localeService = localeService;
this.enableGeneralFields = true;
this.enableConditionalLogicBlocks = false;
this.isSurvey = true;
this.incomingFormData = {
formData: {
steps: [],
generalFields: []
},
options: {
name: '',
type: '',
country: ''
},
uniqueFormData: []
};
this.enableSetValidationOptions = false;
this.locale = {};
this.saveClicked = new EventEmitter();
this.formFieldType = FormFieldType;
this.formData = {
formData: {
steps: [],
generalFields: []
},
options: {
name: '',
type: '',
country: ''
},
uniqueFormData: []
};
this.addedFields = [];
this.generalFields = [];
this.conditionalLogicBlocks = [];
this.fieldLabels = fieldTypesNames;
this.currentStep = 0;
this.usedFieldTypes = [];
this.isSidebarOpen = false;
this.isFieldsInsertingOpen = false;
this.isFieldPropertiesOpen = false;
this.isGeneral = false;
this.fieldToEdit = { id: '', name: '' };
this.hasFeedBackText = false;
this.editedFieldId = null;
}
UIComponent.prototype.ngOnInit = function () {
this.insertFormData();
this.createForm();
this.initializeUsedFieldTypes(this.addedFields);
this.updateSpecialFieldStates();
if (this.locale) {
this.localeService.setLocale(this.locale);
}
};
UIComponent.prototype.ngOnChanges = function (changes) {
if (changes['locale'] && this.locale) {
this.localeService.setLocale(this.locale);
}
};
UIComponent.prototype.createForm = function () {
this.dynamicForm = this.uiFormService.createFormGroup(this.addedFields);
if (this.enableGeneralFields) {
this.generalForm = this.uiFormService.createFormGroup(this.generalFields);
}
};
UIComponent.prototype.removeField = function (field, isGeneral) {
var fieldsArray;
var formGroup;
if (isGeneral) {
fieldsArray = this.generalFields;
formGroup = this.generalForm;
}
else {
fieldsArray = this.addedFields;
formGroup = this.dynamicForm;
}
var index = fieldsArray.indexOf(field);
if (index !== -1) {
fieldsArray.splice(index, 1);
formGroup.removeControl(field.id);
}
if (this.isFieldUnique(field.type)) {
var typeIndex = this.usedFieldTypes.indexOf(field.type);
if (typeIndex !== -1) {
this.usedFieldTypes.splice(typeIndex, 1);
}
}
this.saveCurrentStepData();
};
UIComponent.prototype.copyField = function (field, isGeneral) {
var fieldsArray;
var formGroup;
if (isGeneral) {
fieldsArray = this.generalFields;
formGroup = this.generalForm;
}
else {
fieldsArray = this.addedFields;
formGroup = this.dynamicForm;
}
var copiedField = __assign({}, field);
copiedField.id = this.uiFormService.generateUniqueId();
if (copiedField.feedBackText) {
copiedField.feedBackText = false;
}
var originalFieldIndex = fieldsArray.indexOf(field);
fieldsArray.splice(originalFieldIndex + 1, 0, copiedField);
var newFormControl = this.uiFormService.createControl();
formGroup.addControl(copiedField.id, newFormControl);
this.saveCurrentStepData();
};
UIComponent.prototype.insertConditionalLogicBlock = function () {
var newBlock = defaultConditionalLogicBlock;
this.conditionalLogicBlocks.push(newBlock);
this.saveCurrentStepData();
};
UIComponent.prototype.removeConditionalLogicBlock = function (index) {
this.conditionalLogicBlocks.splice(index, 1);
this.saveCurrentStepData();
};
UIComponent.prototype.goToStep = function (step) {
this.currentStep = step;
if (!this.formData.formData.steps[this.currentStep]) {
this.formData.formData.steps[this.currentStep] = {
addedFields: [],
conditionalLogicBlocks: []
};
}
this.updateStep();
};
UIComponent.prototype.goToNextStep = function () {
if (this.addedFields.length === 0) {
return;
}
this.saveCurrentStepData();
this.currentStep++;
this.goToStep(this.currentStep);
};
UIComponent.prototype.goToPreviousStep = function () {
if (this.currentStep > 0) {
this.saveCurrentStepData();
this.currentStep--;
this.goToStep(this.currentStep);
}
};
UIComponent.prototype.saveCurrentStepData = function () {
this.formData.formData.generalFields = __spread(this.generalFields);
this.formData.formData.steps[this.currentStep] = {
addedFields: __spread(this.addedFields),
conditionalLogicBlocks: __spread(this.conditionalLogicBlocks)
};
this.updateSpecialFieldStates();
};
UIComponent.prototype.updateSpecialFieldStates = function () {
var _a;
var needContactField = this.findFieldInSteps(FormFieldType.NeedContact);
this.needContactDefaultValue = (_a = needContactField) === null || _a === void 0 ? void 0 : _a.defaultValue;
if (needContactField &&
needContactField.defaultValue !== undefined &&
!this.enableSetValidationOptions) {
this.updateRequiredFields(needContactField.defaultValue);
}
this.updateFeedBackTextFields();
};
UIComponent.prototype.updateFeedBackTextFields = function () {
var e_1, _a, e_2, _b;
this.hasFeedBackText = false;
try {
for (var _c = __values(this.formData.formData.steps), _d = _c.next(); !_d.done; _d = _c.next()) {
var step = _d.value;
try {
for (var _e = (e_2 = void 0, __values(step.addedFields)), _f = _e.next(); !_f.done; _f = _e.next()) {
var field = _f.value;
if (field.type &&
[FormFieldType.Text, FormFieldType.Textarea].includes(field.type) &&
field.feedBackText) {
this.hasFeedBackText = true;
break;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
if (this.hasFeedBackText)
break;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
};
UIComponent.prototype.findFieldInSteps = function (fieldType) {
var e_3, _a;
try {
for (var _b = __values(this.formData.formData.steps), _c = _b.next(); !_c.done; _c = _b.next()) {
var step = _c.value;
var field = step.addedFields.find(function (f) { return f.type === fieldType; });
if (field) {
return field;
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_3) throw e_3.error; }
}
return undefined;
};
UIComponent.prototype.updateRequiredFields = function (value) {
var e_4, _a;
var isRequired = value === '1';
try {
for (var _b = __values(this.formData.formData.steps), _c = _b.next(); !_c.done; _c = _b.next()) {
var step = _c.value;
step.addedFields.forEach(function (field) {
if (field.type &&
[
FormFieldType.ContactName,
FormFieldType.ContactSurname,
FormFieldType.ContactEmail
].includes(field.type)) {
field.required = isRequired;
}
});
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_4) throw e_4.error; }
}
};
UIComponent.prototype.insertFormData = function () {
var _a, _b, _c, _d, _e;
var incomingFormData = this.incomingFormData;
if (incomingFormData) {
this.formData = incomingFormData;
}
else {
this.formData = {
formData: {
steps: [],
generalFields: []
},
options: {
name: '',
type: '',
country: ''
},
uniqueFormData: []
};
}
this.addedFields = (_b = (_a = this.formData.formData.steps[this.currentStep]) === null || _a === void 0 ? void 0 : _a.addedFields, (_b !== null && _b !== void 0 ? _b : []));
this.generalFields = (_c = this.formData.formData.generalFields, (_c !== null && _c !== void 0 ? _c : []));
this.conditionalLogicBlocks = (_e = (_d = this.formData.formData.steps[this.currentStep]) === null || _d === void 0 ? void 0 : _d.conditionalLogicBlocks, (_e !== null && _e !== void 0 ? _e : []));
};
UIComponent.prototype.saveForm = function () {
this.saveCurrentStepData();
var payload = this.formDataService.prepareFormData(this.formData);
this.formDataService.setFormData(payload);
this.saveClicked.emit(payload);
};
UIComponent.prototype.preventDefault = function (event) {
event.preventDefault();
};
UIComponent.prototype.onDrop = function (event) {
var formArray = event.container.data;
moveItemInArray(formArray, event.previousIndex, event.currentIndex);
this.saveCurrentStepData();
};
UIComponent.prototype.copyStep = function (index) {
var _this = this;
if (this.addedFields.length === 0) {
return;
}
var copiedStep = __assign({}, this.formData.formData.steps[index]);
copiedStep.addedFields = copiedStep.addedFields.map(function (field) { return (__assign(__assign({}, field), { id: _this.uiFormService.generateUniqueId() })); });
this.formData.formData.steps.splice(index + 1, 0, copiedStep);
this.goToStep(index + 1);
this.saveCurrentStepData();
};
UIComponent.prototype.moveStep = function (index, direction) {
var _a, _b;
if (direction === 'next') {
_a = __read([
this.formData.formData.steps[index + 1],
this.formData.formData.steps[index]
], 2), this.formData.formData.steps[index] = _a[0], this.formData.formData.steps[index + 1] = _a[1];
}
else if (direction === 'prev') {
_b = __read([
this.formData.formData.steps[index - 1],
this.formData.formData.steps[index]
], 2), this.formData.formData.steps[index] = _b[0], this.formData.formData.steps[index - 1] = _b[1];
}
this.goToStep(index);
this.saveCurrentStepData();
};
UIComponent.prototype.deleteStepConfirmation = function (index) {
var _this = this;
var localizedMessage = this.localeService.getCurrentLocale()['Are you sure you want to delete this step?'] ||
'Are you sure you want to delete this step?';
this.confirmationService.open(localizedMessage).then(function (result) {
if (result) {
_this.deleteStep(index);
}
});
};
UIComponent.prototype.deleteStep = function (index) {
this.formData.formData.steps.splice(index, 1);
if (this.currentStep >= index) {
this.currentStep = this.currentStep > 0 ? this.currentStep - 1 : 0;
}
if (this.formData.formData.steps.length > 0) {
this.updateStep();
}
else {
this.addedFields = [];
this.conditionalLogicBlocks = [];
this.createForm();
}
this.saveCurrentStepData();
};
UIComponent.prototype.updateStep = function () {
this.addedFields = this.formData.formData.steps[this.currentStep].addedFields;
this.conditionalLogicBlocks =
this.formData.formData.steps[this.currentStep].conditionalLogicBlocks;
this.createForm();
};
UIComponent.prototype.isFieldUnique = function (fieldType) {
return uniqueFieldTypes.includes(fieldType);
};
UIComponent.prototype.toggleSidebar = function () {
this.isSidebarOpen = this.isFieldsInsertingOpen || this.isFieldPropertiesOpen;
};
UIComponent.prototype.toggleFieldsInsertingSidebar = function (isGeneral) {
if (isGeneral === void 0) { isGeneral = false; }
this.isFieldsInsertingOpen = !this.isFieldsInsertingOpen;
this.isFieldPropertiesOpen = false;
this.isGeneral = isGeneral;
this.toggleSidebar();
};
UIComponent.prototype.toggleFieldPropertiesSidebar = function (field, isGeneral) {
this.isFieldPropertiesOpen = !this.isFieldPropertiesOpen;
this.isFieldsInsertingOpen = false;
this.toggleSidebar();
this.fieldToEdit = field;
this.isGeneral = isGeneral;
this.editedFieldId = this.isFieldPropertiesOpen ? field.id : null;
if (!this.isSidebarOpen) {
this.editedFieldId = null;
}
};
UIComponent.prototype.onPropertiesSave = function (selectedField) {
if (selectedField) {
var newFormControl = this.uiFormService.createControl(selectedField.defaultValue);
if (this.isGeneral) {
this.generalFields.push(selectedField);
this.generalForm.addControl(selectedField.id, newFormControl);
}
else {
this.addedFields.push(selectedField);
this.dynamicForm.addControl(selectedField.id, newFormControl);
}
this.addUsedFieldType(selectedField.type);
this.saveCurrentStepData();
}
};
UIComponent.prototype.onPropertiesSaveAfterEdit = function (updatedField) {
if (updatedField) {
var fieldsArray = void 0;
if (this.isGeneral) {
fieldsArray = this.generalFields;
}
else {
fieldsArray = this.addedFields;
}
var index = fieldsArray.indexOf(this.fieldToEdit);
if (index !== -1) {
if (updatedField.step !== this.currentStep) {
fieldsArray.splice(index, 1);
var newStepIndex = updatedField.step;
var targetStep = this.formData.formData.steps[newStepIndex];
targetStep.addedFields.push(updatedField);
}
else {
fieldsArray[index] = updatedField;
}
}
if (updatedField.defaultValue !== undefined) {
var formControl = this.dynamicForm.get(updatedField.id);
if (formControl) {
formControl.setValue(updatedField.defaultValue);
}
}
this.saveCurrentStepData();
}
};
UIComponent.prototype.addUsedFieldType = function (type) {
if (this.isFieldUnique(type) && !this.usedFieldTypes.includes(type)) {
this.usedFieldTypes.push(type);
}
};
UIComponent.prototype.initializeUsedFieldTypes = function (fields) {
var _this = this;
fields.forEach(function (field) {
_this.addUsedFieldType(field.type);
});
};