-
Notifications
You must be signed in to change notification settings - Fork 0
/
at-form-complex.html
1067 lines (903 loc) · 38.6 KB
/
at-form-complex.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<link rel="import" href="../tangere/tangere.html">
<link rel="import" href="../at-core-style-classes/at-core-style-classes.html">
<link rel="import" href="../at-i18n/at-i18n-behavior.html">
<link rel="import" href="../at-core-schema/at-core-schema.html">
<link rel="import" href="../at-rule-engine/at-rule-engine.html">
<link rel="import" href="../at-form-behaviors/at-form-behaviors.html">
<link rel="import" href="../at-form-behaviors/at-form-behaviors-rules-evaluation.html">
<link rel="import" href="../iron-label/iron-label.html">
<link rel="import" href="../at-core-view/at-core-view.html">
<link rel="import" href="../at-core-resize-sensor/at-core-resize-sensor.html">
<link rel="import" href="../at-core-activity/at-core-activity.html">
<link rel="import" href="../at-core-schema/jsyaml-import.html">
<dom-module id="at-form-complex">
<template>
<style include="at-form-common"></style>
<style include="iron-flex"></style>
<style include="iron-flex-factors"></style>
<style include="at-core-style-classes">
:host * {
box-sizing: border-box;
}
:host {
@apply --at-form-host;
}
.wrapper {
position: relative;
}
.clear-float {
clear: both;
}
#insertPoint.layout.horizontal :first-child {
padding: 0 4px 0 0;
}
#insertPoint.layout.horizontal :last-child {
padding: 0 0 0 4px;
}
.layout.horizontal .form-element {
padding: 0 4px 0 4px;
}
/*
*ij* default value of min-height changed to 34px from 0
this is a workaround a flex bug in IE11 where min height was not applied correctly in flexbox mode
https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items
*/
.form-element {
min-height: var(--at-form-complex-form-element-min-height, 76px);
}
/*
*ij* default value of min-height changed to 34px from 0
this is a workaround a flex bug in IE11 where min height was not applied correctly in flexbox mode
https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items
*/
.horizontal .form-element {
min-height: var(--at-form-complex-layout-horizontal-form-element-min-height, 76px);
}
.form-element.at-form-checkbox,
.horizontal .form-element.at-form-checkbox {
min-height: 32px;
}
</style>
<at-core-activity id="schemaActivity" handle-as="text" headers='{ "X-Client": "Now" }' on-response="_handleSchemaActivityResponse" on-error="_handleSchemaActivityError"></at-core-activity>
<div id="messages" class="font-body1"></div>
<div class="wrapper">
<at-core-resize-sensor id="resizeSensor" on-resize-sensed="_handleResizeSensed"></at-core-resize-sensor>
<div class="clear-float"></div>
<div>
<div id="atContainer" class="at-container">
<iron-label id="label">{{label}}</iron-label>
<template is="dom-if" if="{{label}}" on-dom-change="_handleLabelHrDomChange">
<hr id="labelHr">
</template>
<div id="contentContainer" class="at-content-container">
<div id="insertPoint"></div>
<at-core-view id="placeholder" view="[[placeholder]]" hidden></at-core-view>
</div>
<div id="hint"></div>
</div>
</div>
</div>
</template>
</dom-module>
<script>
"use strict";
Polymer({
is: 'at-form-complex',
behaviors: [Tangere.behaviors.i18n, Tangere.behaviors.RulesEvaluation, Tangere.behaviors.formUIGeneric],
properties: {
schemaUrl: {
type: String,
value: '',
observer: "_schemaUrlChanged"
},
schemaUrlPrefix: {
type: String,
value: '',
observer: "_schemaUrlChanged"
},
/**
* Textual label for the element
* @property label
* @type String
* @default ''
*/
label: {
type: String,
value: '',
title: 'Label'
},
/**
* When true hides the label for the element
* @property hideLabel
* @type Boolean
* @default false
*/
hideLabel: {
type: Boolean,
value: false,
observer: '_hideLabelChanged',
title: 'Do not show the label'
},
/**
* becomes true when all elements are rendered
* @property rendered
* @type Boolean
* @default false
*/
rendered: {
type: Boolean,
value: false
},
/**
* Specification of elements that should appear on the element.<br/>
* Provide either an object or string.<br/>
* List property definitions inside properties object.<br/>
*
* @property schema
* @type Object | Stirng
* @default { properties: {} }
*/
schema: {
type: Object,
value: function() {
return {
properties: {}
};
},
observer: '_schemaChanged',
title: 'Schema'
},
/**
* Holds values of the elements on the element
*
* @property value
* @type Object | String
* @default {}
*/
value: {
type: Object,
value: function() {
return {};
},
observer: '_valueChanged',
title: 'Value'
},
/**
* When true disables all elements on the form
* @property disabled
* @type Boolean
* @default false
*/
disabled: {
type: Boolean,
value: false,
observer: '_disabledChanged',
title: 'Field value can not be changed'
},
/**
* Hides the element. When hidden nothing is displayed for the element
* @property hide
* @type Boolean
* @default false
*/
hide: {
type: Boolean,
value: false,
observer: '_hideChanged',
title: 'Field is invisible'
},
placeholder: {
type: String,
value: "<div class='m'> <div class='placeholder-text'></div><div class='placeholder-text mtsm'></div></div>",
xtype: 'code',
xgridcols: "12",
mode: "html"
},
/**
* Controls the layout of the rendered elements
*
* @property layout
* @type String
* @default vertical
*/
layout: {
type: String,
value: 'vertical',
observer: '_layoutChanged',
xtype: 'enum',
xvaluelist: 'horizontal,vertical'
}
},
$meta: [{
title: "Object",
type: "object"
}],
_hideLabelChanged: function(newValue, oldValue) {
this.toggleClass("hidden", newValue, this.$.label);
this._toggleLabelHorizontalLine(newValue);
},
_handleLabelHrDomChange: function(event) {
this._toggleLabelHorizontalLine(this.hideLabel);
},
_toggleLabelHorizontalLine: function(hideLabel) {
var labelHr = this.$$('#labelHr');
if (labelHr) {
this.toggleClass("hidden", hideLabel, labelHr);
}
},
_handleResizeSensed: function(event) {
var newWidth = event.detail.value.width;
this._updateLayoutForWidth(newWidth);
},
_updateLayoutForWidth: function(newWidth) {
if (isNaN(newWidth)) return;
if (this._isFormArrayRow) return;
if (!this.rendered) return;
if (newWidth < 600) {
this.layout = "vertical";
} else {
this.layout = "horizontal";
}
},
ready: function() {
this._isReady = true;
},
_schemaUrlChanged: function(newValue, oldValue) {
if (!this.schemaUrl) return;
Polymer.dom(this.$.insertPoint).placeholder = this.placeholder;
var url = this.schemaUrlPrefix ? this.schemaUrlPrefix : "";
url = url + this.schemaUrl;
if (url.indexOf("/") == -1) return; // url needs to be absolute or relative, but not in samefolder; schemaUrlPrefix not yet set
this.$.schemaActivity.url = url;
this.$.schemaActivity.generateRequest();
},
_handleSchemaActivityResponse: function(event) {
var newSchemaStr = event.detail;
try {
var newSchema = JSON.parse(newSchemaStr);
} catch (e) {
// try yaml
try {
newSchema = window.jsyaml.load(newSchemaStr);
} catch (e) {
Polymer.dom(this.$.insertPoint).innerHTML = "";
this._setError('Data returned by remote service is not a json string nor yaml string.');
// close modal and clear placeholder, because next time _initialize is called placeholder should be set
// this._clearPlaceholder();
return;
}
}
// this will trigger _schemaChanged but since schemaUrl is set _schemaChanged will return immediatelly
this.schema = newSchema;
},
_handleSchemaActivityError: function(event) {
},
// map legacy xtypes
// this list is also in at-form-complex and at-core-dashboard
// DO NOT EXTEND THIS LIST; for new elements xtype should be the element name, so there is no need to new elements to be in this list
_displayTypeToFormElementMapping: {
array: "at-form-array",
boolean: "at-form-checkbox",
toggle: "at-form-checkbox",
code: "at-form-codemirror",
json: "at-form-codemirror",
object: "at-form-complex",
date: "at-form-date",
time: "at-form-date",
datetime: "at-form-date",
daterange: "at-form-daterange",
file: "at-form-file",
html: "at-form-html",
image: "at-form-image",
'enum': "at-form-lookup",
lookup: "at-form-lookup",
marked: "at-form-markdown",
password: "at-form-password",
number: "at-form-number",
radio: "at-form-radio",
section: "at-form-section",
state: "at-form-state",
string: "at-form-text",
textarea: "at-form-textarea",
cron: "at-form-cron",
random: "at-form-random"
},
_getElementName: function(displayType) {
var elementName = this._displayTypeToFormElementMapping[displayType];
return elementName;
},
_schemaChanged: function(newValue, oldValue) {
this._setError("");
var _sh = window.schemaHelpers;
if (_sh.isString(newValue)) {
/*
if newValue for schema is given as json string, parse it and assign it to this.schema
if newValue is a valid json string this.schema will trigger _schemaChanged again so we return to prevent schema changes being applied twice
if newValue is an invalid json string just return. Whatever the previous schema was that remains visible to the user
*/
try {
if (newValue == "") newValue = '{"properties": {}}';
newValue = JSON.parse(newValue);
this.schema = newValue;
} catch (e) {
console.log(e);
}
return;
}
if (!_sh.isObject(newValue) || !_sh.isObject(newValue.properties)) return;
// if value is set before schema, this._internalData is already updated
// if schema is set first this._internalData is undefined so its initialized to empty object
if (!this._internalData) {
this._internalData = {};
}
var self = this;
// calculating valid state for the form is faster if we cache references to each element on the form
// its even faster if we exclude elements that do not have valid property
self._elementsToValidate = [];
if (!_sh.isArray(self._unsupported_types)) {
// ------------------------------------------------------------
// unsupported types
// list type or xtype of the element that should not be supported by at-form-complex
// ------------------------------------------------------------
self._unsupported_types = ["object"];
}
// This flag tells when form complex has completed rendering all the elements
this.rendered = false;
// clear the previous html content in the container
Polymer.dom(this.$.insertPoint).innerHTML = "";
var properties = newValue.properties;
var propNames = Object.getOwnPropertyNames(properties);
// do not render empty schema
if (propNames.length === 0) return;
// figure out what needs to be imported
var notImportedElements = [];
propNames.forEach(function(propName) {
var propDef = properties[propName];
var displayType = _sh.getDisplayType(propDef, self._unsupported_types);
// propDef.default !== window is added to hanlde cases from polymer behaviors
// where initial value for properities is window
if (propDef.default !== window) {
// element is not loaded; scheadule it for importHref
var scheduledPropDef = JSON.parse(JSON.stringify(propDef));
scheduledPropDef.displayType = displayType;
notImportedElements.push(scheduledPropDef);
}
});
if (!notImportedElements.length) {
this._renderSchema(propNames, properties);
return;
}
Polymer.dom(this.$.placeholder).removeAttribute('hidden');
var pendingImportsCount = notImportedElements.length;
notImportedElements.forEach(function(propDef, index) {
// To construct elemHref we need static information about what (type, xtype) maps to which at-form element
// Right now, only $meta in each element contains this information and central array of components is populated with $meta information
// So, to dynamically importHref needed elements we need to introduce static information (which will just be a copy paste from $meta of each element)
var displayType = propDef.displayType;
var elementName = self._getElementName(displayType);
if (elementName == undefined) { elementName = displayType; }
if (!elementName) {
console.debug("Please add a mapping for (type, xtype) = (" + propDef.type + ", " + propDef.xtype + ") to displayTypeToFormElementMapping object in at-form-complex");
pendingImportsCount -= 1;
} else {
// construct elemHref
var compUrl = this.resolveUrl("../");
if (document.URL.indexOf("/elements/designer-element/") >= 0) {
compUrl = "/components/";
}
if (window.ComponentsBase != undefined) {
compUrl = window.ComponentsBase;
}
var elemHref = compUrl + elementName + "/" + elementName + ".html";
self.importHref(elemHref, function(e) {
// import was successful
pendingImportsCount -= 1;
if (!pendingImportsCount) {
self._renderSchema(propNames, properties);
}
}, function(e) {
// import failed
console.log("import failed: " + e.target.href);
}, true);
}
}, this);
},
_renderSchema: function(propertyNames, propDefs) {
var self = this;
var _sh = window.schemaHelpers;
var fieldsFragment = document.createDocumentFragment();
var divPrototype = document.createElement('div');
var propertyDefinition; // definition of a single property
var defaultValue; // holds the default value for the element
var containsProperty; // temporary holds the value from the at-form-complex.value property
var displayType; // type of the property; translates to a coresponding element
var fieldContainer; // at-form-complex class="field" wrapper for formElement
var fieldElement; // holds a reference to a newly created element
var insertPoint = this.$.insertPoint;
if (this._isFormArrayRow) {
Polymer.dom(insertPoint).classList.add('layout');
Polymer.dom(insertPoint).classList.add(this.layout);
}
propertyNames.forEach(function(propertyName) {
propertyDefinition = propDefs[propertyName];
// handle the default value
defaultValue = propertyDefinition.default;
containsProperty = self._internalData.hasOwnProperty(propertyName);
// if default value is defined and _internalData[propertyName] value is undefiend put default value into self._internalData
if (defaultValue !== undefined && !containsProperty) {
self._internalData[propertyName] = defaultValue;
}
displayType = schemaHelpers.getDisplayType(propertyDefinition, self._unsupported_types);
fieldContainer = divPrototype.cloneNode(true);
Polymer.dom(fieldContainer).classList.add('form-element');
var gridColsCssName = "flex";
if (!self._isFormArrayRow) {
// handle xgridcols
var xgridcols = displayType === "section" ? 12 : 6;
if (_sh.isString(propertyDefinition.xgridcols) || _sh.isNumber(propertyDefinition.xgridcols)) {
xgridcols = parseInt(propertyDefinition.xgridcols);
}
gridColsCssName = "col-" + xgridcols;
}
Polymer.dom(fieldContainer).classList.add(gridColsCssName);
var elementName = self._getElementName(displayType);
if (elementName === undefined) elementName = displayType;
fieldElement = schemaHelpers.createElement(propertyName, displayType, propertyDefinition, elementName);
if (fieldElement.is === "at-form-checkbox") {
fieldContainer.classList.add('at-form-checkbox');
}
// special handling for at-form-section; at-form-section should have .mt class from at-core-style-classes and min-height value of unset
if (fieldElement.tagName.toLowerCase() == "at-form-section") {
Polymer.dom(fieldElement).classList.add("mtlg");
}
if (displayType !== "section") {
if (!self._internalData.hasOwnProperty(propertyName)) {
// at-form-complex._internalData doesn't contain an entry for the current property
// add initial value of the formElement to the at-form-complex.data
if (typeof fieldElement.value !== "object") {
self._internalData[propertyName] = fieldElement.value;
} else {
self._internalData[propertyName] = JSON.parse(JSON.stringify(fieldElement.value));
}
} else {
// else set initial value from at-form-complex.data to fromElement
if (typeof self._internalData[propertyName] !== 'object') {
fieldElement.value = self._internalData[propertyName];
} else {
fieldElement.value = JSON.parse(JSON.stringify(self._internalData[propertyName]));
}
}
}
if (_sh.isFunction(fieldElement.clearUIValidState)) {
// at-form-section doesn't have clearUIValidState function nor does it need one
fieldElement.clearUIValidState();
} else if (_sh.isFunction(fieldElement._clearUIValidState)) {
fieldElement._clearUIValidState();
}
fieldElement.addEventListener('value-changed', function(event) {
event.stopPropagation();
var id = event.target.id;
var newValue = event.detail.value;
var currentValue = self._internalData[id];
if (!_sh.areEqual(currentValue, newValue)) {
self._updateValueObject(id, newValue);
}
});
Polymer.dom(fieldElement).setAttribute('id', propertyName);
self._elementsToValidate.push(fieldElement);
fieldElement.hideLabel = (!!self._isFormArrayRow && self.layout == "horizontal") || propertyDefinition.hideLabel;
// if at-form-complex is initially hidden, element should be hidden as well
fieldElement.hide = self.hide || _sh.parseBool(propertyDefinition.hide);
// added for AT-214; when element is hidden, fieldContainer for that element should be hidden as well
self.toggleClass('hidden', fieldElement.hide, fieldContainer);
// if at-form-complex is initially disabled, element should be disabled as well
fieldElement.disabled = self.disabled || _sh.parseBool(propertyDefinition.disabled);
// form-complex passes its value of autovalidate to its contained elements
// this enables at-core-form to control autovalidate value for elements contained inside form-complex
fieldElement.autoValidate = self.autoValidate;
// append paper element to its container
Polymer.dom(fieldContainer).appendChild(fieldElement);
// add container to as child to insertPoint
Polymer.dom(fieldsFragment).appendChild(fieldContainer);
});
// if data was set first there is a chance that some properties form this._internalData are missing in this.data
// this.data must be updated with missing properties
if (_sh.isObject(self.value)) {
var internalDataKeys = Object.keys(this._internalData);
internalDataKeys.forEach(function(key, index) {
// self.value[key] === undefined means that the key is missing from self.value
if (!self.value.hasOwnProperty(key)) {
self.value[key] = self._internalData[key];
}
});
}
Polymer.dom(self.$.insertPoint).appendChild(fieldsFragment);
Polymer.dom(self.$.placeholder).setAttribute('hidden', '');
// evaluate rules against new schema
if (propertyNames.length) {
self._executeRuleEvaluation(this.schema);
}
// if any element is required in schema its valid state is updated after creation
// at-form-complex needs to reflect that state
this.validate();
Polymer.dom.flush();
this.$.resizeSensor.reset();
var currentWidth = this.$.resizeSensor.queryWidth();
// This flag tells when form complex has completed rendering all the elements
this.rendered = true;
if (!isNaN(currentWidth)) {
this._updateLayoutForWidth(currentWidth);
}
// todo: analyze problem that it seems that it doesn't bubble to at-carbon-form-modal
this.fire('rendered', this, { bubbles: true, composed: true });
},
attached: function() {
Polymer.dom.flush();
this.$.resizeSensor.reset();
var currentWidth = this.$.resizeSensor.queryWidth();
if (isNaN(currentWidth)) return;
this._updateLayoutForWidth(currentWidth);
},
_executeRuleEvaluation: function(schema, isRendered) {
var _sh = window.schemaHelpers;
if (this._isBusinessRulesEvaluationInProgress) {
return;
}
this._isBusinessRulesEvaluationInProgress = true;
if (_sh.isArray(schema.rules) && schema.rules.length) {
// what is happening here? Please note that steps are explained in reverse order because of dependencies
// 3. Why do we reset _rulesEvaluator every time
// Because _rulesEvaluator remembers last data it evaluated rules against
// if data is the same rules are not evaluated
// this means that if user doesn't change default values for elements between rule Editing and preview,
// updated rules will not be initially executed, but its expected that rules be executed
this._rulesEvaluator = RulesEvaluator();
// 2. Why do we reset active schema every time?
// Because, activeSchema is cached as a private variable in at-form-behaviors-rules-evaluation so its saved between schema changes,
var activeSchema = {
properties: {}
};
activeSchema.properties = JSON.parse(JSON.stringify(schema.properties));
this._activeSchema = activeSchema;
// 1. Its expected to display the results of rules evaluation when new schema is set
// at-core-form invokes rule evaluation when any element on the form changes value;
// its not really desirable to invoke rule evaluation that way, since we have access to at-form-behaviors-rules-evaluation._evaluateRules function
// but to invoke evaluate rules we need a property and its value; so we provide first property on the form and its value
var propNames = Object.keys(schema.properties);
var propName = propNames[0];
var propValue = this.getElement(propName).value;
this._evaluateRules(propName, propValue);
// 1a. Why do we clear ui valid state of the elements
// Because its expected that initially UI errors are not displayed. Errors should be displayed only when user interacts with the element(s)
var self = this;
propNames.forEach(function(propName, index) {
var element = self.getElement(propName);
element._clearUIValidState();
});
}
this._isBusinessRulesEvaluationInProgress = false;
},
/* *ij*
OK. Imperative data binding doesn't work in polymer anymore.
It may happen in the future but not in near future.
Using at-form-complex.data[field] = 'newValue' doesn't work. Its not possible to bind to at-form-complex.data[field] to update field value automatically
Explained in https://github.com/Polymer/polymer/issues/1778 and https://github.com/Polymer/polymer/issues/1796
So, to solve this shortcoming a updateFormElementValue function is introduced
The purpose of this function is, obviously, to update a value of the specific field.
This function will update the .data object and .value of the field with provided elementId.
If the field with provided elementId doesn't exist a debug message will be loged in the console
Alternative to this approach is to create a completely new object each time you want to update the .data property
IMO, this approach is a waste of time. An updateFormElementValue function is much more efficient
Another alternative to this approach is to have a function that will return the element itself. Than the client can do whatever he likes with the element
not just update value. This approach seems reasonable for setFieldState action in at-form-rule-edit
*/
updateFormElementValue: function(elementId, value) {
var fieldElement = this.getElement(elementId);
if (!fieldElement) {
return;
}
this._internalData[elementId] = value;
this.value[elementId] = value;
fieldElement.value = value;
// *ij* polymer js doesn't call valueChanged if value is of type array or object
// we check for this situation and call valueChanged by hand
if (schemaHelpers.isObject(fieldElement.value) || schemaHelpers.isArray(fieldElement.value)) {
if (fieldElement.valueChanged) {
fieldElement.valueChanged(value, undefined);
} else if (fieldElement._valueChanged) {
fieldElement._valueChanged(value, undefined);
}
}
},
setElementState: function(elementId, state, value) {
var element = this.getElement(elementId);
if (!element) {
return;
}
element[state] = value;
// added for AT-214; when element is hidden its container should also be hidden
if (state === "hide") {
this.toggleClass('hidden', value, element.parentElement);
}
},
getElement: function(elementId) {
if (!this.$) return null;
var fieldsContainer = this.$.insertPoint;
var selector = '#' + elementId;
var fieldElement = Polymer.dom(fieldsContainer).querySelector(selector);
return fieldElement;
},
_valueChanged: function(newValue, oldValue) {
var self = this;
var _sh = window.schemaHelpers;
if (_sh.isString(newValue)) {
/*
if newValue for data is given as json string, parse it and assign it to this.data
if newValue is a valid json string this.data will trigger _dataChanged again so we return to prevent data changes being applied twice
if newValue is an invalid json string just return. Whatever the previous data was that remains visible to the user
*/
try {
newValue = JSON.parse(newValue);
this.value = newValue;
} catch (e) {
console.log(e);
}
return;
}
// if new value is not an object, ignore the value and return
if (!_sh.isObject(newValue)) {
console.log('at-form-complex expects objects as new value, but got ' + _sh.formatJson(newValue) + ' instead');
return;
}
// initalize _internalData object; this objects holds last valid data set to at-core-form
if (!this._internalData) {
this._internalData = {};
}
var _internalData = this._internalData;
// update _internalData with keys from newValue
var newValueKeys = Object.keys(newValue);
newValueKeys.forEach(function(key, index) {
_internalData[key] = JSON.parse(JSON.stringify(newValue[key]));
});
if (!_sh.isObject(this.schema) || !_sh.isObject(this.schema.properties) || Object.keys(this.schema.properties).length === 0) {
// when schema is not set data-changed event should still be fired so that behavior is the same as when schema is set
this._fireValueChangedEvent(this.value);
// this means that schema is not set and at-form-complex is not initialized; return
return;
}
// at this point this._internalData contains updated values for each element on the form because
// 1) if schema was set first, this._internalData was already populated with initial values for each element,
// and entries from newValue are merged into this._internalData
// 2) if value was set first, properties from this._internalData may be missing in this.value so they need to be copied over
// but this is done in _schemaChanged
var fieldsContainer = Polymer.dom(this.$.insertPoint);
var fieldElement;
// fallback to default value in schema when new value objects doesn't contain property
if (this.schema && this.schema.properties) {
var schemaPropertyKeys = Object.getOwnPropertyNames(self.schema.properties);
schemaPropertyKeys.forEach(function (schemaPropertyKey, schemaPropertyIndex) {
if (newValue.hasOwnProperty(schemaPropertyKey) == false) {
// only update form element value if .default value is available
if (self.schema.properties[schemaPropertyKey].default != undefined) {
self.updateFormElementValue(schemaPropertyKey, self.schema.properties[schemaPropertyKey].default);
}
}
});
}
// use newValueKeys here because only keys from newValue are the ones changing
newValueKeys.forEach(function(propertyName) {
fieldElement = self.getElement(propertyName);
if (fieldElement) {
fieldElement.value = JSON.parse(JSON.stringify(newValue[propertyName]));
}
});
// newValue can contain only a subset of properties on the form
// value in value-changed should contain all properties so we need to copy over missing properties from _internalData
var internalDataKeys = Object.keys(this._internalData);
internalDataKeys.forEach(function(key, index) {
if (!self.value.hasOwnProperty(key)) {
self.value[key] = JSON.parse(JSON.stringify(self._internalData[key]));
}
});
if (!this._isSchemaEmpty(this.schema) && this.__rendered__) {
self._executeRuleEvaluation(this.schema);
}
this.validate();
this._fireValueChangedEvent(this.value);
},
/*
* This function is called on value-changed event for each element on the form
* property is property name
* value is the new value to be set
*/
_updateValueObject: function(property, value) {
var _sh = window.schemaHelpers;
// this if is a guard against infinite loop that can be caused by
// DataValidator.prototype.complexActionsAdapter.copyFieldValue
// at-rule-engine/script/rule-engine.js line 308
var rules = this.schema.rules;
this._internalData[property] = value;
if (_sh.isArray(rules) && rules.length > 0) {
if (this._isBusinessRulesEvaluationInProgress) {
return;
}
this._isBusinessRulesEvaluationInProgress = true;
this._evaluateRules(property, value);
this._isBusinessRulesEvaluationInProgress = false;
} else {
if (!_sh.isObject(this.value)) {
this.value = {};
}
this.value[property] = value;
if (_sh.isObject(value) || _sh.isArray(value)) {
var clonedValue = JSON.parse(JSON.stringify(value));
this._internalData[property] = clonedValue;
this.value[property] = clonedValue;
}
// we call validate here for this branch only, because _evaluateRules already calls at-form-complex validate or the other branch
this.validate();
}
this.fire('value-changed', { value: this.value, property: property }, { bubbles: false });
},
_disabledChanged: function(newValue, oldValue) {
this.toggleClass('disabled', newValue, this.$.label);
var labelHr = this.$$('#labelHr');
if (labelHr) {
this.toggleClass('disabled', newValue, labelHr);
}
var fieldsContainer = this.$.insertPoint;
var fieldElement;
var properties = this.schema.properties;
var propertyNames = properties ? Object.keys(properties) : [];
var parsedValue = schemaHelpers.parseBool(newValue);
var self = this;
propertyNames.forEach(function(propertyName) {
fieldElement = self.getElement(propertyName);
if (fieldElement) {
fieldElement.disabled = parsedValue || schemaHelpers.parseBool(properties[propertyName].disabled);
}
});
// When at-form-complex disabled state changes from true to false all elements are enabled
// But, a rule can exist that that disables a specific element on at-form-complex
// so rules are evaluated to restore the disabled state of the specific element to a state when at-form-complex was enabled
if (oldValue == true && newValue == false) {
this._executeRuleEvaluation(this.schema);
}
},
_hideChanged: function(newValue, oldValue) {
var wrapper = this.$.atContainer;
this.toggleClass('hidden', newValue, wrapper);
if (!this._elementsToValidate) return;
this._elementsToValidate.forEach(function(element) {
element.hide = newValue;
});
},
focus: function() {
if (this.schema && this.schema.properties) {
var properties = this.schema.properties;
var propertyNames = properties ? Object.keys(properties) : [];
if (propertyNames.length > 0) {
var propName = propertyNames[0];
var element = this.getElement(propName);
if (element) {
element.focus();
}
}
}
},
_clearUIValidState: function() {
if (!this._isObject(this.schema)) return;
if (!this._isObject(this.schema.properties)) return;
var properties = this.schema.properties;
var propertyNames = Object.keys(properties);
var self = this;
propertyNames.forEach(function(properyName) {
var element = self.getElement(properyName);
if (element && element.clearUIValidState) {
element.clearUIValidState();
} else if (element && element._clearUIValidState) {
element._clearUIValidState();
}
});
},
/*
* Validates the form
* It calls validate method of each element in elementsToValidate array
* Form is valid if all elements are valid. Form is invalid if at least one element is invalid.
*/
validate: function(showError) {
var isFunction = function(obj) {
return Object.prototype.toString.apply(obj) === "[object Function]";
}
var isValid = true;
if (showError === undefined) { showError = this.autoValidate; }
if (this._elementsToValidate) {
this._elementsToValidate.forEach(function(element) {
if (!element.disabled && !element.hide && isFunction(element.validate)) {
var elementValid = element.validate(showError);
isValid = isValid && elementValid;
}
});
}
return isValid;
},
/**
* _layoutChanged <br/>
* switches classes for vertical and horizontal layout
*/
_layoutChanged: function(newValue, oldValue) {
var fieldsContainer = this.$.insertPoint;
var isVertical = newValue === "vertical";
this.toggleClass("vertical", isVertical, fieldsContainer);
if (this._isFormArrayRow) {
this.toggleClass("horizontal", !isVertical, fieldsContainer);
this.hideLabelsForElements();
}
},
/**
* Hides the labels for all elements on the form-complex
*/
hideLabelsForElements: function() {
this._iterateElements(function(element) {
element.hideLabel = true;
});
},
/**
* Shows the labels for all elements on the form-complex