-
Notifications
You must be signed in to change notification settings - Fork 556
/
field-expression.ts
251 lines (214 loc) Β· 8.29 KB
/
field-expression.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
import { FormlyFieldConfig, FormlyValueChangeEvent, FormlyFieldConfigCache } from '../../components/formly.field.config';
import { isObject, isNullOrUndefined, isFunction, defineHiddenProp, wrapProperty, reduceFormUpdateValidityCalls } from '../../utils';
import { evalExpression, evalStringExpression } from './utils';
import { Observable } from 'rxjs';
import { FormlyExtension } from '../../services/formly.config';
import { unregisterControl, registerControl, updateValidity } from '../field-form/utils';
/** @experimental */
export class FieldExpressionExtension implements FormlyExtension {
prePopulate(field: FormlyFieldConfigCache) {
if (field.parent || field.options._checkField) {
return;
}
field.options._checkField = (f, ignoreCache) => {
reduceFormUpdateValidityCalls(
f.formControl,
() => this.checkField(f, ignoreCache),
);
};
}
onPopulate(field: FormlyFieldConfigCache) {
if (!field.parent || field._expressionProperties) {
return;
}
// cache built expression
defineHiddenProp(field, '_expressionProperties', {});
if (field.expressionProperties) {
for (const key in field.expressionProperties) {
const expressionProperty = field.expressionProperties[key];
if (typeof expressionProperty === 'string' || isFunction(expressionProperty)) {
field._expressionProperties[key] = {
expression: this._evalExpression(
expressionProperty,
key === 'templateOptions.disabled' && field.parent.expressionProperties && field.parent.expressionProperties.hasOwnProperty('templateOptions.disabled')
? () => field.parent.templateOptions.disabled
: undefined,
),
};
if (key === 'templateOptions.disabled') {
Object.defineProperty(field._expressionProperties[key], 'expressionValue', {
get: () => field.templateOptions.disabled,
set: () => { },
enumerable: true,
configurable: true,
});
}
} else if (expressionProperty instanceof Observable) {
const subscription = (expressionProperty as Observable<any>)
.subscribe(v => {
this.setExprValue(field, key, v);
if (field.options && field.options._markForCheck) {
field.options._markForCheck(field);
}
});
const onDestroy = field.hooks.onDestroy;
field.hooks.onDestroy = (field) => {
onDestroy && onDestroy(field);
subscription.unsubscribe();
};
}
}
}
if (field.hideExpression) {
// delete hide value in order to force re-evaluate it in FormlyFormExpression.
delete field.hide;
let parent = field.parent;
while (parent && !parent.hideExpression) {
parent = parent.parent;
}
field.hideExpression = this._evalExpression(
field.hideExpression,
parent && parent.hideExpression ? () => parent.hide : undefined,
);
} else {
wrapProperty(field, 'hide', ({ currentValue, firstChange }) => {
field._hide = currentValue;
if (!firstChange || (firstChange && currentValue === true)) {
field.options._hiddenFieldsForCheck.push(field);
}
});
}
}
private _evalExpression(expression, parentExpression?) {
expression = expression || (() => false);
if (typeof expression === 'string') {
expression = evalStringExpression(expression, ['model', 'formState', 'field']);
}
return parentExpression
? (model: any, formState: any, field: FormlyFieldConfig) => parentExpression() || expression(model, formState, field)
: expression;
}
private checkField(field: FormlyFieldConfigCache, ignoreCache = false) {
this._checkField(field, ignoreCache);
field.options._hiddenFieldsForCheck
.sort(f => f.hide ? -1 : 1)
.forEach(f => this.toggleFormControl(f, f.hide));
field.options._hiddenFieldsForCheck = [];
}
private _checkField(field: FormlyFieldConfigCache, ignoreCache = false) {
let markForCheck = false;
field.fieldGroup.forEach(f => {
this.checkFieldExpressionChange(f, ignoreCache) && (markForCheck = true);
if (this.checkFieldVisibilityChange(f, ignoreCache)) {
field.options._hiddenFieldsForCheck.push(f);
markForCheck = true;
}
if (f.fieldGroup && f.fieldGroup.length > 0) {
this._checkField(f, ignoreCache);
}
});
if (markForCheck && field.options && field.options._markForCheck) {
field.options._markForCheck(field);
}
}
private checkFieldExpressionChange(field: FormlyFieldConfigCache, ignoreCache): boolean {
if (!field || !field._expressionProperties) {
return false;
}
let markForCheck = false;
const expressionProperties = field._expressionProperties;
for (const key in expressionProperties) {
let expressionValue = evalExpression(expressionProperties[key].expression, { field }, [field.model, field.options.formState, field]);
if (key === 'templateOptions.disabled') {
expressionValue = !!expressionValue;
}
if (
ignoreCache || (
expressionProperties[key].expressionValue !== expressionValue
&& (!isObject(expressionValue) || JSON.stringify(expressionValue) !== JSON.stringify(expressionProperties[key].expressionValue))
)
) {
markForCheck = true;
expressionProperties[key].expressionValue = expressionValue;
this.setExprValue(field, key, expressionValue);
}
}
return markForCheck;
}
private checkFieldVisibilityChange(field: FormlyFieldConfigCache, ignoreCache): boolean {
if (!field || isNullOrUndefined(field.hideExpression)) {
return false;
}
const hideExpressionResult: boolean = !!evalExpression(
field.hideExpression,
{ field },
[field.model, field.options.formState, field],
);
let markForCheck = false;
if (hideExpressionResult !== field.hide || ignoreCache) {
markForCheck = true;
// toggle hide
field.hide = hideExpressionResult;
field.templateOptions.hidden = hideExpressionResult;
}
return markForCheck;
}
private setDisabledState(field: FormlyFieldConfig, value: boolean) {
if (field.fieldGroup) {
field.fieldGroup
.filter(f => !f.expressionProperties || !f.expressionProperties.hasOwnProperty('templateOptions.disabled'))
.forEach(f => this.setDisabledState(f, value));
}
if (field.key && field.templateOptions.disabled !== value) {
field.templateOptions.disabled = value;
}
}
private toggleFormControl(field: FormlyFieldConfigCache, hide: boolean) {
if (field.formControl && field.key) {
defineHiddenProp(field, '_hide', !!(hide || field.hide));
const c = field.formControl;
if (c['_fields'].length > 1) {
updateValidity(c);
}
hide === true && c['_fields'].every(f => !!f._hide)
? unregisterControl(field)
: registerControl(field);
}
if (field.fieldGroup) {
field.fieldGroup
.filter(f => !f.hideExpression)
.forEach(f => this.toggleFormControl(f, hide));
}
if (field.options.fieldChanges) {
field.options.fieldChanges.next(<FormlyValueChangeEvent> { field: field, type: 'hidden', value: hide });
}
}
private setExprValue(field: FormlyFieldConfigCache, prop: string, value: any) {
try {
let target = field;
const paths = prop.split('.');
const lastIndex = paths.length - 1;
for (let i = 0; i < lastIndex; i++) {
target = target[paths[i]];
}
target[paths[lastIndex]] = value;
} catch (error) {
error.message = `[Formly Error] [Expression "${prop}"] ${error.message}`;
throw error;
}
if (prop === 'templateOptions.disabled' && field.key) {
this.setDisabledState(field, value);
}
if (prop.indexOf('model.') === 0) {
const path = prop.replace(/^model\./, ''),
control = field.key && prop === path ? field.formControl : field.parent.formControl.get(path);
if (
control
&& !(isNullOrUndefined(control.value) && isNullOrUndefined(value))
&& control.value !== value
) {
control.patchValue(value, { emitEvent: false });
}
}
}
}