-
Notifications
You must be signed in to change notification settings - Fork 855
/
Copy pathbase.ts
1281 lines (1261 loc) · 43.7 KB
/
base.ts
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
import { ILocalizableOwner, LocalizableString } from "./localizablestring";
import { Helpers, HashTable } from "./helpers";
import {
CustomPropertiesCollection,
JsonObject,
JsonObjectProperty,
JsonMetadataClass,
Serializer,
} from "./jsonobject";
import { settings } from "./settings";
import { ItemValue } from "./itemvalue";
import { IElement, IFindElement, IProgressInfo, ISurvey, ILoadFromJSONOptions, ISaveToJSONOptions } from "./base-interfaces";
import { ExpressionRunner } from "./conditions";
import { getLocaleString } from "./surveyStrings";
import { ConsoleWarnings } from "./console-warnings";
interface IExpressionRunnerInfo {
onExecute: (obj: Base, res: any) => void;
canRun?: (obj: Base) => boolean;
runner?: ExpressionRunner;
}
export class Bindings {
private properties: Array<JsonObjectProperty> = null;
private values: any = null;
constructor(private obj: Base) { }
public getType(): string {
return "bindings";
}
public get isSurveyObj(): boolean { return true; }
public getNames(): Array<string> {
var res: Array<string> = [];
this.fillProperties();
for (var i = 0; i < this.properties.length; i++) {
if (this.properties[i].isVisible("", this.obj)) {
res.push(this.properties[i].name);
}
}
return res;
}
public getProperties(): Array<JsonObjectProperty> {
var res: Array<JsonObjectProperty> = [];
this.fillProperties();
for (var i = 0; i < this.properties.length; i++) {
res.push(this.properties[i]);
}
return res;
}
public setBinding(propertyName: string, valueName: string) {
if (!this.values) this.values = {};
const oldValue = this.getJson();
if (oldValue === valueName) return;
if (!!valueName) {
this.values[propertyName] = valueName;
} else {
delete this.values[propertyName];
if (Object.keys(this.values).length == 0) {
this.values = null;
}
}
this.onChangedJSON(oldValue);
}
public clearBinding(propertyName: string) {
this.setBinding(propertyName, "");
}
public isEmpty(): boolean {
if (!this.values) return true;
for (var key in this.values) return false;
return true;
}
public getValueNameByPropertyName(propertyName: string): string {
if (!this.values) return undefined;
return this.values[propertyName];
}
public getPropertiesByValueName(valueName: string): Array<string> {
if (!this.values) return [];
var res: Array<string> = [];
for (var key in this.values) {
if (this.values[key] == valueName) {
res.push(key);
}
}
return res;
}
public getJson(): any {
if (this.isEmpty()) return undefined;
const res: any = {};
this.getNames().forEach(key => {
if(this.values[key] !== undefined) {
res[key] = this.values[key];
}
});
return res;
}
public setJson(value: any, isLoading?: boolean): void {
const oldValue = this.getJson();
this.values = null;
if (!!value) {
this.getNames().forEach(key => {
if(value[key] !== undefined) {
if(!this.values) this.values = {};
this.values[key] = value[key];
}
});
}
if (!isLoading && !Helpers.isTwoValueEquals(oldValue, this.values)) {
this.onChangedJSON(oldValue);
}
}
private fillProperties() {
if (this.properties !== null) return;
this.properties = [];
var objProperties = Serializer.getPropertiesByObj(this.obj);
for (var i = 0; i < objProperties.length; i++) {
if (objProperties[i].isBindable) {
this.properties.push(objProperties[i]);
}
}
}
private onChangedJSON(oldValue: any): void {
if (this.obj) {
this.obj.onBindingChanged(oldValue, this.getJson());
}
}
}
export class Dependencies {
private static DependenciesCount = 0;
constructor(public currentDependency: () => void, public target: Base, public property: string) {
}
dependencies: Array<{ obj: Base, prop: string, id: string }> = [];
id: string = "" + (++Dependencies.DependenciesCount);
addDependency(target: Base, property: string): void {
if (this.target === target && this.property === property)
return;
if (this.dependencies.some(dependency => dependency.obj === target && dependency.prop === property))
return;
this.dependencies.push({
obj: target,
prop: property,
id: this.id
});
target.registerPropertyChangedHandlers([property], this.currentDependency, this.id);
}
public dispose(): void {
this.dependencies.forEach(dependency => {
dependency.obj.unregisterPropertyChangedHandlers([dependency.prop], dependency.id);
});
// this.currentDependency = undefined;
}
}
export class ComputedUpdater<T = any> {
public static readonly ComputedUpdaterType = "__dependency_computed";
private dependencies: Dependencies = undefined;
constructor(private _updater: () => T) {
}
readonly type = ComputedUpdater.ComputedUpdaterType;
public get updater(): () => T {
return this._updater;
}
public setDependencies(dependencies: Dependencies): void {
this.clearDependencies();
this.dependencies = dependencies;
}
protected getDependencies(): Dependencies {
return this.dependencies;
}
private clearDependencies() {
if (this.dependencies) {
this.dependencies.dispose();
this.dependencies = undefined;
}
}
dispose(): any {
this.clearDependencies();
this._updater = undefined;
}
}
/**
* A base class for all SurveyJS objects.
*/
export class Base {
private static currentDependencis: Dependencies = undefined;
public static finishCollectDependencies(): Dependencies {
const deps = Base.currentDependencis;
Base.currentDependencis = undefined;
return deps;
}
public static startCollectDependencies(updater: () => void, target: Base, property: string): void {
if (Base.currentDependencis !== undefined) {
throw new Error("Attempt to collect nested dependencies. Nested dependencies are not supported.");
}
Base.currentDependencis = new Dependencies(updater, target, property);
}
protected static collectDependency(target: Base, property: string): void {
if (Base.currentDependencis === undefined) return;
Base.currentDependencis.addDependency(target, property);
}
public dependencies: { [key: string]: ComputedUpdater } = {};
public static get commentSuffix(): string {
return settings.commentSuffix;
}
public static set commentSuffix(val: string) {
settings.commentSuffix = val;
}
public static get commentPrefix(): string {
return Base.commentSuffix;
}
public static set commentPrefix(val: string) {
Base.commentSuffix = val;
}
public static createItemValue: (item: any, type?: string) => any;
public static itemValueLocStrChanged: (arr: Array<any>) => void;
/**
* Returns `true` if a passed `value` is an empty string, array, or object or if it equals to `undefined` or `null`.
*
* @param value A value to be checked.
* @param trimString *(Optional)* When this parameter is `true`, the method ignores whitespace characters at the beginning and end of a string value. Pass `false` to disable this functionality.
*/
public isValueEmpty(value: any, trimString: boolean = true): boolean {
if (trimString) {
value = this.trimValue(value);
}
return Helpers.isValueEmpty(value);
}
public equals(obj: Base): boolean {
if (!obj) return false;
if (this.isDisposed || obj.isDisposed) return false;
if (this.getType() != obj.getType()) return false;
return this.equalsCore(obj);
}
protected equalsCore(obj: Base): boolean {
if ((<any>this).name !== (<any>obj).name) return false;
return Helpers.isTwoValueEquals(this.toJSON(), obj.toJSON(), false, true, false);
}
protected trimValue(value: any): any {
if (!!value && (typeof value === "string" || value instanceof String))
return value.trim();
return value;
}
public static createPropertiesHash() {
return {};
}
private propertyHash: { [index: string]: any } = Base.createPropertiesHash();
private localizableStrings: { [index: string]: LocalizableString };
private arraysInfo: { [index: string]: any };
private eventList: Array<EventBase<any>> = [];
private expressionInfo: { [index: string]: IExpressionRunnerInfo };
private isDisposedValue: boolean;
private classMetaData: JsonMetadataClass;
private onPropChangeFunctions: Array<{
name: string,
func: (...args: any[]) => void,
key: string,
}>;
protected isLoadingFromJsonValue: boolean = false;
public loadingOwner: Base = null;
protected jsonObj: any;
/**
* An event that is raised when a property of this SurveyJS object has changed.
*
* Parameters:
*
* - `sender`: `this`\
* A SurveyJS object whose property has changed.
* - `options.name`: `string`\
* The name of the changed property.
* - `options.newValue`: `any`\
* A new value for the property.
* - `options.oldValue`: `any`\
* An old value of the property. If the property is an array, `oldValue` contains the same array as `newValue` does.
*
* If you need to add and remove property change event handlers dynamically, use the [`registerPropertyChangedHandlers`](#registerPropertyChangedHandlers) and [`unregisterPropertyChangedHandlers`](#unregisterPropertyChangedHandlers) methods instead.
*/
public onPropertyChanged: EventBase<Base> = this.addEvent<Base>();
/**
* An event that is raised when an [`ItemValue`](https://surveyjs.io/form-library/documentation/itemvalue) property is changed.
*
* Parameters:
*
* - `sender`: `this`\
* A SurveyJS object whose property contains an array of `ItemValue` objects.
* - `options.obj`: [`ItemValue`](https://surveyjs.io/form-library/documentation/itemvalue)\
* An `ItemValue` object.
* - `options.propertyName`: `string`\
* The name of the property to which an array of `ItemValue` objects is assigned (for example, `"choices"` or `"rows"`).
* - `options.name`: `"text"` | `"value"`\
* The name of the changed property.
* - `options.newValue`: `any`\
* A new value for the property.
*/
public onItemValuePropertyChanged: Event<
(sender: Base, options: any) => any,
Base,
any
> = this.addEvent<Base>();
getPropertyValueCoreHandler: (propertiesHash: any, name: string) => any;
setPropertyValueCoreHandler: (
propertiesHash: any,
name: string,
val: any
) => void;
createArrayCoreHandler: (propertiesHash: any, name: string) => Array<any>;
surveyChangedCallback: () => void;
private isCreating = true;
public constructor() {
CustomPropertiesCollection.createProperties(this);
this.onBaseCreating();
this.isCreating = false;
}
public dispose(): void {
for (var i = 0; i < this.eventList.length; i++) {
this.eventList[i].clear();
}
this.onPropertyValueChangedCallback = undefined;
this.isDisposedValue = true;
Object.keys(this.dependencies).forEach(key => this.dependencies[key].dispose());
// this.dependencies = {};
Object.keys(this.propertyHash).forEach(key => {
const propVal = this.getPropertyValueCore(this.propertyHash, key);
if (!!propVal && propVal.type == ComputedUpdater.ComputedUpdaterType) {
(propVal as ComputedUpdater).dispose();
}
});
}
public get isDisposed(): boolean {
return this.isDisposedValue === true;
}
public get isSurveyObj(): boolean { return true; }
protected addEvent<T, Options = any>(): EventBase<T, Options> {
const res = new EventBase<T, Options>();
this.eventList.push(res);
return res;
}
protected onBaseCreating(): void { }
/**
* Returns the object type as it is used in the JSON schema.
*/
public getType(): string {
return "base";
}
/**
* Use this method to find out if the current object is of a given `typeName` or inherited from it.
*
* @param typeName One of the values listed in the [getType()](https://surveyjs.io/form-library/documentation/question#getType) description.
* @returns `true` if the current object is of a given `typeName` or inherited from it.
* @see getType
*/
public isDescendantOf(typeName: string): boolean {
return Serializer.isDescendantOf(this.getType(), typeName);
}
public getSurvey(isLive: boolean = false): ISurvey {
return null;
}
/**
* Returns `true` if the survey is being designed in Survey Creator.
*/
public get isDesignMode(): boolean {
const survey = this.getSurvey();
return !!survey && survey.isDesignMode;
}
/**
* Returns `true` if the object is included in a survey.
*
* This property may return `false`, for example, when you [create a survey model dynamically](https://surveyjs.io/form-library/documentation/design-survey-create-a-simple-survey#create-or-change-a-survey-model-dynamically).
*/
public get inSurvey(): boolean {
return !!this.getSurvey(true);
}
private bindingsValue: Bindings;
public get bindings(): Bindings {
if(!this.bindingsValue) {
this.bindingsValue = new Bindings(this);
}
return this.bindingsValue;
}
protected isBindingEmpty(): boolean {
return !this.bindingsValue || this.bindingsValue.isEmpty();
}
checkBindings(valueName: string, value: any): void { }
protected updateBindings(propertyName: string, value: any): void {
if(!this.bindingsValue) return;
var valueName = this.bindings.getValueNameByPropertyName(propertyName);
if (!!valueName) {
this.updateBindingValue(valueName, value);
}
}
protected updateBindingValue(valueName: string, value: any) { }
public getTemplate(): string {
return this.getType();
}
/**
* Returns `true` if the object configuration is being loaded from JSON.
*/
public get isLoadingFromJson(): boolean {
return this.isLoadingFromJsonValue || this.getIsLoadingFromJson();
}
protected getIsLoadingFromJson(): boolean {
if (!!this.loadingOwner && this.loadingOwner.isLoadingFromJson) return true;
return this.isLoadingFromJsonValue;
}
startLoadingFromJson(json?: any): void {
this.isLoadingFromJsonValue = true;
this.jsonObj = json;
}
endLoadingFromJson() {
this.isLoadingFromJsonValue = false;
}
/**
* Returns a JSON object that corresponds to the current SurveyJS object.
* @see fromJSON
*/
public toJSON(options?: ISaveToJSONOptions): any {
return new JsonObject().toJsonObject(this, options);
}
/**
* Assigns a new configuration to the current SurveyJS object. This configuration is taken from a passed JSON object.
*
* The JSON object should contain only serializable properties of this SurveyJS object. Event handlers and properties that do not belong to the SurveyJS object are ignored.
*
* @param json A JSON object with properties that you want to apply to the current SurveyJS object.
* @param options An object with configuration options.
* @param {boolean} options.validatePropertyValues Pass `true` if you want to validate property values. Use the [`jsonErrors`](#jsonErrors) array to access validation errors.
* @see toJSON
*/
public fromJSON(json: any, options?: ILoadFromJSONOptions): void {
new JsonObject().toObject(json, this, options);
this.onSurveyLoad();
}
public onSurveyLoad() { }
/**
* Creates a new object that has the same type and properties as the current SurveyJS object.
*/
public clone(): Base {
var clonedObj = <Base>Serializer.createClass(this.getType());
clonedObj.fromJSON(this.toJSON());
return clonedObj;
}
/**
* Returns a `JsonObjectProperty` object with metadata about a serializable property that belongs to the current SurveyJS object.
*
* If the property is not found, this method returns `null`.
* @param propName A property name.
*/
public getPropertyByName(propName: string): JsonObjectProperty {
const type = this.getType();
if (!this.classMetaData || this.classMetaData.name !== type) {
this.classMetaData = Serializer.findClass(type);
}
return !!this.classMetaData ? this.classMetaData.findProperty(propName) : null;
}
public isPropertyVisible(propName: string): boolean {
const prop = this.getPropertyByName(propName);
return !!prop ? prop.isVisible("", this) : false;
}
public static createProgressInfo(): IProgressInfo {
return {
questionCount: 0,
answeredQuestionCount: 0,
requiredQuestionCount: 0,
requiredAnsweredQuestionCount: 0,
};
}
public getProgressInfo(): IProgressInfo {
return Base.createProgressInfo();
}
public localeChanged(): void { }
public locStrsChanged(): void {
if (!!this.arraysInfo) {
for (let key in this.arraysInfo) {
let item = this.arraysInfo[key];
if (item && item.isItemValues) {
var arr = this.getPropertyValue(key);
if (arr && !!Base.itemValueLocStrChanged)
Base.itemValueLocStrChanged(arr);
}
}
}
if (!!this.localizableStrings) {
for (let key in this.localizableStrings) {
let item = this.getLocalizableString(key);
if (item) item.strChanged();
}
}
}
/**
* Returns the value of a property with a specified name.
*
* If the property is not found or does not have a value, this method returns either `undefined`, `defaultValue` specified in the property configuration, or a value passed as the `defaultValue` parameter.
*
* @param name A property name.
* @param defaultValue *(Optional)* A value to return if the property is not found or does not have a value.
*/
public getPropertyValue(name: string, defaultValue?: any, calcFunc?: ()=> any): any {
const res = this.getPropertyValueWithoutDefault(name);
if (this.isValueUndefined(res)) {
const locStr = this.localizableStrings ? this.localizableStrings[name] : undefined;
if (locStr) return locStr.text;
if (!this.isValueUndefined(defaultValue)) return defaultValue;
if(!!calcFunc) {
const newVal = calcFunc();
if(newVal !== undefined) {
if(Array.isArray(newVal)) {
const array = this.createNewArray(name);
array.splice(0, 0, ...newVal);
return array;
} else {
this.setPropertyValueDirectly(name, newVal);
return newVal;
}
}
}
const propDefaultValue = this.getDefaultPropertyValue(name);
if (propDefaultValue !== undefined) return propDefaultValue;
}
return res;
}
protected isValueUndefined(value: any): boolean {
return Helpers.isValueUndefined(value);
}
public getDefaultPropertyValue(name: string): any {
const prop = this.getPropertyByName(name);
if (!prop || prop.isCustom && this.isCreating) return undefined;
if (!!prop.defaultValueFunc) return prop.defaultValueFunc(this);
const dValue = prop.getDefaultValue(this);
if (!this.isValueUndefined(dValue) && !Array.isArray(dValue)) return dValue;
const locStr = this.localizableStrings ? this.localizableStrings[name] : undefined;
if (locStr && locStr.localizationName) return this.getLocalizationString(locStr.localizationName);
if (prop.type == "boolean" || prop.type == "switch") return false;
if (prop.isCustom && !!prop.onGetValue) return prop.onGetValue(this);
return undefined;
}
public hasDefaultPropertyValue(name: string): boolean {
return this.getDefaultPropertyValue(name) !== undefined;
}
public resetPropertyValue(name: string): void {
const locStr = this.localizableStrings ? this.localizableStrings[name] : undefined;
if (locStr) {
this.setLocalizableStringText(name, undefined);
locStr.clear();
}
else {
this.setPropertyValue(name, undefined);
}
}
protected getPropertyValueWithoutDefault(name: string): any {
return this.getPropertyValueCore(this.propertyHash, name);
}
protected getPropertyValueCore(propertiesHash: any, name: string): any {
if (!this.isLoadingFromJson) {
Base.collectDependency(this, name);
}
if (this.getPropertyValueCoreHandler)
return this.getPropertyValueCoreHandler(propertiesHash, name);
else return propertiesHash[name];
}
public geValueFromHash(): any {
return this.propertyHash["value"];
}
protected setPropertyValueCore(propertiesHash: any, name: string, val: any): void {
if (this.setPropertyValueCoreHandler) {
if (!this.isDisposedValue) {
this.setPropertyValueCoreHandler(propertiesHash, name, val);
} else {
ConsoleWarnings.disposedObjectChangedProperty(name, this.getType());
}
}
else propertiesHash[name] = val;
}
public get isEditingSurveyElement(): boolean {
var survey = this.getSurvey();
return !!survey && survey.isEditingSurveyElement;
}
public iteratePropertiesHash(func: (hash: any, key: string) => void) {
var keys: string[] = [];
for (var key in this.propertyHash) {
if (
key === "value" &&
this.isEditingSurveyElement &&
Array.isArray((<any>this).value)
)
continue;
keys.push(key);
}
keys.forEach((key) => func(this.propertyHash, key));
}
/**
* Assigns a new value to a specified property.
* @param name A property name.
* @param val A new value for the property.
*/
public setPropertyValue(name: string, val: any): void {
if (this.isDisposedValue) return;
if (!this.isLoadingFromJson) {
const prop = this.getPropertyByName(name);
if (!!prop) {
val = prop.settingValue(this, val);
}
}
var oldValue = this.getPropertyValue(name);
if (
oldValue &&
Array.isArray(oldValue) &&
!!this.arraysInfo &&
(!val || Array.isArray(val))
) {
if (!this.isTwoValueEquals(oldValue, val)) {
this.setArrayPropertyDirectly(name, val);
}
} else {
if (val !== oldValue) {
this.setPropertyValueDirectly(name, val);
if (!this.isTwoValueEquals(oldValue, val)) {
this.propertyValueChanged(name, oldValue, val);
}
}
}
}
protected setArrayPropertyDirectly(name: string, val: any, sendNotification: boolean = true): void {
var arrayInfo = this.arraysInfo[name];
this.setArray(
name,
this.getPropertyValue(name),
val,
arrayInfo ? arrayInfo.isItemValues : false,
arrayInfo ? sendNotification && arrayInfo.onPush : null
);
}
protected setPropertyValueDirectly(name: string, val: any): void {
this.setPropertyValueCore(this.propertyHash, name, val);
}
protected clearPropertyValue(name: string) {
this.setPropertyValueCore(this.propertyHash, name, null);
delete this.propertyHash[name];
}
public onPropertyValueChangedCallback(
name: string,
oldValue: any,
newValue: any,
sender: Base,
arrayChanges: ArrayChanges
) { }
public itemValuePropertyChanged(
item: ItemValue,
name: string,
oldValue: any,
newValue: any
) {
this.onItemValuePropertyChanged.fire(this, {
obj: item,
name: name,
oldValue: oldValue,
newValue: newValue,
propertyName: item.ownerPropertyName,
});
}
protected onPropertyValueChanged(name: string, oldValue: any, newValue: any): void { }
protected propertyValueChanged(name: string, oldValue: any, newValue: any, arrayChanges?: ArrayChanges, target?: Base): void {
if (this.isLoadingFromJson) return;
this.updateBindings(name, newValue);
this.onPropertyValueChanged(name, oldValue, newValue);
this.onPropertyChanged.fire(this, {
name: name,
oldValue: oldValue,
newValue: newValue,
arrayChanges: arrayChanges,
target: target
});
this.doPropertyValueChangedCallback(
name,
oldValue,
newValue,
arrayChanges,
this
);
this.checkConditionPropertyChanged(name);
if (!this.onPropChangeFunctions) return;
for (var i = 0; i < this.onPropChangeFunctions.length; i++) {
if (this.onPropChangeFunctions[i].name == name)
this.onPropChangeFunctions[i].func(newValue, arrayChanges);
}
}
public onBindingChanged(oldValue: any, newValue: any): void {
if (this.isLoadingFromJson) return;
this.doPropertyValueChangedCallback("bindings", oldValue, newValue);
}
protected get isInternal(): boolean {
return false;
}
private doPropertyValueChangedCallback(
name: string,
oldValue: any,
newValue: any,
arrayChanges?: ArrayChanges,
target?: Base
) {
const fireCallback = (obj: Base): void => {
if (!!obj && !!obj.onPropertyValueChangedCallback) {
obj.onPropertyValueChangedCallback(name, oldValue, newValue, target, arrayChanges);
}
};
if (this.isInternal) {
fireCallback(this);
return;
}
if (!target) target = this;
var notifier: any = this.getSurvey();
if (!notifier) notifier = this;
fireCallback(notifier);
if (notifier !== this) {
fireCallback(this);
}
}
public addExpressionProperty(name: string, onExecute: (obj: Base, res: any) => void, canRun?: (obj: Base) => boolean): void {
if (!this.expressionInfo) {
this.expressionInfo = {};
}
this.expressionInfo[name] = { onExecute: onExecute, canRun: canRun };
}
public getDataFilteredValues(): any {
return {};
}
public getDataFilteredProperties(): any {
return {};
}
protected runConditionCore(values: HashTable<any>, properties: HashTable<any>): void {
if (!this.expressionInfo) return;
for (var key in this.expressionInfo) {
this.runConditionItemCore(key, values, properties);
}
}
protected canRunConditions(): boolean {
return !this.isDesignMode;
}
private checkConditionPropertyChanged(propName: string): void {
if (!this.expressionInfo || !this.expressionInfo[propName]) return;
if (!this.canRunConditions()) return;
this.runConditionItemCore(propName, this.getDataFilteredValues(), this.getDataFilteredProperties());
}
private runConditionItemCore(propName: string, values: HashTable<any>, properties: HashTable<any>): void {
const info = this.expressionInfo[propName];
const expression = this.getPropertyValue(propName);
if (!expression) return;
if (!!info.canRun && !info.canRun(this)) return;
if (!info.runner) {
info.runner = this.createExpressionRunner(expression);
info.runner.onRunComplete = (res: any) => {
info.onExecute(this, res);
};
}
info.runner.expression = expression;
info.runner.run(values, properties);
}
private asynExpressionHash: any;
private doBeforeAsynRun(id: number): void {
if (!this.asynExpressionHash) this.asynExpressionHash = {};
const isChanged = !this.isAsyncExpressionRunning;
this.asynExpressionHash[id] = true;
if (isChanged) {
this.onAsyncRunningChanged();
}
}
private doAfterAsynRun(id: number): void {
if (!!this.asynExpressionHash) {
delete this.asynExpressionHash[id];
if (!this.isAsyncExpressionRunning) {
this.onAsyncRunningChanged();
}
}
}
protected onAsyncRunningChanged(): void { }
public get isAsyncExpressionRunning(): boolean {
return !!this.asynExpressionHash && Object.keys(this.asynExpressionHash).length > 0;
}
protected createExpressionRunner(expression: string): ExpressionRunner {
const res = new ExpressionRunner(expression);
res.onBeforeAsyncRun = (id: number): void => { this.doBeforeAsynRun(id); };
res.onAfterAsyncRun = (id: number): void => { this.doAfterAsynRun(id); };
return res;
}
/**
* Registers a single value change handler for one or multiple properties.
*
* The `registerPropertyChangedHandlers` and [`unregisterPropertyChangedHandlers`](#unregisterPropertyChangedHandlers) methods allow you to manage property change event handlers dynamically. If you only need to attach an event handler without removing it afterwards, you can use the [`onPropertyChanged`](#onPropertyChanged) event instead.
* @param propertyNames An array of one or multiple property names.
* @param handler A function to call when one of the listed properties change. Accepts a new property value as an argument.
* @param key *(Optional)* A key that identifies the current registration. If a function for one of the properties is already registered with the same key, the function will be overwritten. You can also use the key to subsequently unregister handlers.
* @see unregisterPropertyChangedHandlers
*/
public registerPropertyChangedHandlers(propertyNames: Array<string>, handler: any, key: string = null): void {
for (var i = 0; i < propertyNames.length; i++) {
this.registerFunctionOnPropertyValueChanged(propertyNames[i], handler, key);
}
}
/**
* Unregisters value change event handlers for the specified properties.
* @param propertyNames An array of one or multiple property names.
* @param key *(Optional)* A key of the registration that you want to cancel.
* @see registerPropertyChangedHandlers
*/
public unregisterPropertyChangedHandlers(propertyNames: Array<string>, key: string = null): void {
for (var i = 0; i < propertyNames.length; i++) {
this.unRegisterFunctionOnPropertyValueChanged(propertyNames[i], key);
}
}
public registerFunctionOnPropertyValueChanged(name: string, func: any, key: string = null): void {
if (!this.onPropChangeFunctions) {
this.onPropChangeFunctions = [];
}
if (key) {
for (var i = 0; i < this.onPropChangeFunctions.length; i++) {
var item = this.onPropChangeFunctions[i];
if (item.name == name && item.key == key) {
item.func = func;
return;
}
}
}
this.onPropChangeFunctions.push({ name: name, func: func, key: key });
}
public registerFunctionOnPropertiesValueChanged(names: Array<string>, func: any, key: string = null): void {
this.registerPropertyChangedHandlers(names, func, key);
}
public unRegisterFunctionOnPropertyValueChanged(name: string, key: string = null): void {
if (!this.onPropChangeFunctions) return;
for (var i = 0; i < this.onPropChangeFunctions.length; i++) {
var item = this.onPropChangeFunctions[i];
if (item.name == name && item.key == key) {
this.onPropChangeFunctions.splice(i, 1);
return;
}
}
}
public unRegisterFunctionOnPropertiesValueChanged(names: Array<string>, key: string = null): void {
this.unregisterPropertyChangedHandlers(names, key);
}
public createCustomLocalizableObj(name: string): LocalizableString {
const locStr = this.getLocalizableString(name);
if (locStr) return locStr;
return this.createLocalizableString(name, <ILocalizableOwner>(<any>this), false, true);
}
public getLocale(): string {
const locOwner = this.getSurvey();
return !!locOwner ? locOwner.getLocale() : "";
}
public getLocalizationString(strName: string): string {
return getLocaleString(strName, this.getLocale());
}
public getLocalizationFormatString(strName: string, ...args: any[]): string {
const str: any = this.getLocalizationString(strName);
if (!str || !str.format) return "";
return str.format(...args);
}
protected createLocalizableString(
name: string,
owner: ILocalizableOwner,
useMarkDown: boolean = false,
defaultStr: boolean | string = false
): LocalizableString {
let locName = undefined;
if (defaultStr) {
locName = defaultStr === true ? name : defaultStr;
}
const locStr = new LocalizableString(owner, useMarkDown, name, locName);
locStr.onStrChanged = (oldValue: string, newValue: string) => {
this.propertyValueChanged(name, oldValue, newValue);
};
if (!this.localizableStrings) {
this.localizableStrings = {};
}
this.localizableStrings[name] = locStr;
const prop = this.getPropertyByName(name);
locStr.disableLocalization = prop && prop.isLocalizable === false;
return locStr;
}
protected removeLocalizableString(name: string): void {
if(this.localizableStrings) {
delete this.localizableStrings[name];
}
}
public getLocalizableString(name: string): LocalizableString {
return !!this.localizableStrings ? this.localizableStrings[name] : null;
}
public getLocalizableStringText(
name: string,
defaultStr: string = ""
): string {
Base.collectDependency(this, name);
var locStr = this.getLocalizableString(name);
if (!locStr) return "";
var res = locStr.text;
return res ? res : defaultStr;
}
public setLocalizableStringText(name: string, value: string) {
let locStr = this.getLocalizableString(name);
if (!locStr) return;
let oldValue = locStr.text;
if (oldValue != value) {
locStr.text = value;
// this.propertyValueChanged(name, oldValue, value);
}
}
public addUsedLocales(locales: Array<string>): void {
if (!!this.localizableStrings) {
for (let key in this.localizableStrings) {
let item = this.getLocalizableString(key);
if (item) this.AddLocStringToUsedLocales(item, locales);
}
}
if (!!this.arraysInfo) {
for (let key in this.arraysInfo) {
const prop = this.getPropertyByName(key);
if (!prop || !prop.isPropertySerializable(this)) continue;
let items = this.getPropertyValue(key);
if (!items || !items.length) continue;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item && item.addUsedLocales) {
item.addUsedLocales(locales);
}
}
}
}
}
public searchText(text: string, founded: Array<IFindElement>) {
var strs: Array<LocalizableString> = [];
this.getSearchableLocalizedStrings(strs);
for (var i = 0; i < strs.length; i++) {
if (strs[i].setFindText(text)) {
founded.push({ element: this, str: strs[i] });
}
}
}
private getSearchableLocalizedStrings(arr: Array<LocalizableString>) {
if (!!this.localizableStrings) {
let keys: Array<string> = [];
this.getSearchableLocKeys(keys);
for (var i = 0; i < keys.length; i++) {
let item = this.getLocalizableString(keys[i]);
if (item) arr.push(item);
}
}
if (!this.arraysInfo) return;
let keys: Array<string> = [];
this.getSearchableItemValueKeys(keys);
for (var i = 0; i < keys.length; i++) {
var items = this.getPropertyValue(keys[i]);
if (!items) continue;
for (var j = 0; j < items.length; j++) {
arr.push(items[j].locText);
}
}
}
protected getSearchableLocKeys(keys: Array<string>) { }
protected getSearchableItemValueKeys(keys: Array<string>) { }
protected AddLocStringToUsedLocales(
locStr: LocalizableString,
locales: Array<string>
) {
var locs = locStr.getLocales();
for (var i = 0; i < locs.length; i++) {
if (locales.indexOf(locs[i]) < 0) {
locales.push(locs[i]);
}
}
}
protected createItemValues(name: string): Array<any> {
var self = this;
var result = this.createNewArray(name, function (item: any) {
item.locOwner = self;
item.ownerPropertyName = name;
if (typeof item.getSurvey == "function") {
const survey: any = item.getSurvey();
if (!!survey && typeof survey.makeReactive == "function") {
survey.makeReactive(item);
}
}
});
this.arraysInfo[name].isItemValues = true;
return result;
}
private notifyArrayChanged(ar: any, arrayChanges: ArrayChanges) {
!!ar.onArrayChanged && ar.onArrayChanged(arrayChanges);
}
protected createNewArrayCore(name: string): Array<any> {
var res = null;
if (!!this.createArrayCoreHandler) {
res = this.createArrayCoreHandler(this.propertyHash, name);
}