-
Notifications
You must be signed in to change notification settings - Fork 9
/
django-form-content.component.ts
635 lines (595 loc) · 24.8 KB
/
django-form-content.component.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
import {ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {AbstractControl, FormArray, FormGroup, ValidatorFn} from '@angular/forms';
import {
DYNAMIC_FORM_CONTROL_INPUT_TYPE_DATE, DYNAMIC_FORM_CONTROL_INPUT_TYPE_NUMBER, DynamicCheckboxModel,
DynamicFormControlLayout,
DynamicFormControlModel, DynamicFormGroupModel, DynamicFormService, DynamicInputModel, DynamicRadioGroupModel,
DynamicSelectModel, DynamicTextAreaModel
} from '@ng-dynamic-forms/core';
import 'rxjs/add/operator/merge';
import {HttpClient} from '@angular/common/http';
import {ErrorService} from './error-service';
import {
ColumnsFieldConfig,
CompositeFieldTypes, EmailFieldConfig, FieldConfig, FieldSetConfig, FloatFieldConfig, IntegerFieldConfig,
RadioFieldConfig,
SelectFieldConfig, SimpleFieldTypes, StringFieldConfig, TextAreaFieldConfig
} from './django-form-iface';
import {DynamicFormControlLayoutConfig} from '@ng-dynamic-forms/core/src/model/misc/dynamic-form-control-layout.model';
/**
* Form component targeted on django rest framework
*/
@Component({
selector: 'django-form-content',
templateUrl: './django-form-content.component.html',
styleUrls: ['./django-form-content.component.scss']
})
export class DjangoFormContentComponent implements OnInit {
form_model: DynamicFormControlModel[] = [];
private autocompleters: AutoCompleter[] = [];
form_group: FormGroup;
private last_id = 0;
/**
* Returns submitted form data on enter
*
*/
@Output() submit_on_enter = new EventEmitter();
private _external_errors: { [s: string]: any; } = {};
private _initial_data: any = null;
@Input()
set layout(_layout: FieldConfig[]) {
if (_layout) {
this.form_model = [];
this.autocompleters = [];
this.form_model = this._generate_ui_control_array(_layout);
if (this.form_group) {
this.form_group = this.formService.createFormGroup(this.form_model);
this._bind_autocomplete();
this._update_initial_data();
}
this.check.detectChanges();
}
}
@Input()
set errors(_errors: any) {
if (_errors) {
Object.assign(this._external_errors, _errors);
for (const error_name of Object.getOwnPropertyNames(_errors)) {
const error_values = _errors[error_name];
const error_model = this.formService.findById(error_name, this.form_model) as DynamicInputModel;
// TODO: hack - do not know how to set up the validation message
if (error_model) {
(error_model as any).external_error = error_values[0];
}
// TODO: change this to support arrays
const error_control = this.getControlByName(error_name);
if (error_control) {
error_control.markAsDirty();
error_control.markAsTouched();
error_control.setValue(error_control.value);
} else {
console.log(`Can not set error of ${error_name} within`, this.form_group, error_model);
}
}
} else {
for (const prop of Object.getOwnPropertyNames(this._external_errors)) {
delete this._external_errors[prop];
}
}
}
@Input()
set initial_data(data: any) {
this._initial_data = data;
this._update_initial_data();
}
constructor(private formService: DynamicFormService, private httpClient: HttpClient,
private error_service: ErrorService,
private current_element: ElementRef,
private check: ChangeDetectorRef) {
}
ngOnInit() {
// create an empty form group, will be filled later
if (!this.form_group) {
this.form_group = this.formService.createFormGroup(this.form_model);
this._bind_autocomplete();
this._update_initial_data();
}
this._trigger_validation();
this.check.detectChanges();
}
private _bind_autocomplete() {
for (const autocompleter of this.autocompleters) {
const widget = this.form_group.get(this.formService.getPath(autocompleter.model));
if (widget) {
widget.valueChanges.subscribe(value => {
autocompleter.change(widget, value, this.value);
});
}
}
}
private _trigger_validation() {
if (this.form_group) {
Object.keys(this.form_group.controls).forEach(field => {
const control = this.form_group.get(field);
if (control) {
control.markAsTouched({onlySelf: true});
}
});
}
}
private _generate_ui_control_array(configs: FieldConfig[]): DynamicFormControlModel[] {
const model: DynamicFormControlModel[] = [];
for (const config of configs) {
const _control = this._generate_ui_control(config);
if (_control) {
model.push(_control);
}
}
return model;
}
private _generate_ui_control(field_config: FieldConfig): DynamicFormControlModel {
const id = field_config.id || '___undefined__id__at__config';
const label = field_config.label || '';
const type = field_config.type || SimpleFieldTypes.STRING;
const extra_layout: DynamicFormControlLayout = {
grid: {
host: `dadf-field-id-${id} dadf-field-type-${type}`
}
};
switch (type) {
case SimpleFieldTypes.STRING: {
const sfc = field_config as StringFieldConfig;
const model = new DynamicInputModel(
{
id: id,
placeholder: label,
required: field_config.required,
disabled: field_config.read_only,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
},
maxLength: sfc.max_length,
minLength: sfc.min_length
},
errorMessages: {
external_error: '{{external_error}}'
},
list: sfc.autocomplete_list
},
merge_layouts(field_config.layout, extra_layout)
);
if (sfc.autocomplete_list ||
sfc.autocomplete_url) {
this.autocompleters.push(
new AutoCompleter(this.httpClient, this.error_service,
sfc.autocomplete_list,
sfc.autocomplete_url,
model));
}
return model;
}
case SimpleFieldTypes.EMAIL: {
const sfc = field_config as EmailFieldConfig;
const model = new DynamicInputModel(
{
id: id,
placeholder: label,
required: field_config.required,
disabled: field_config.read_only,
inputType: 'email',
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
},
maxLength: sfc.max_length,
minLength: sfc.min_length
},
errorMessages: {
external_error: '{{external_error}}'
},
list: sfc.autocomplete_list
},
merge_layouts(field_config.layout, extra_layout)
);
if (sfc.autocomplete_list ||
sfc.autocomplete_url) {
this.autocompleters.push(
new AutoCompleter(this.httpClient, this.error_service,
sfc.autocomplete_list,
sfc.autocomplete_url,
model));
}
return model;
}
case SimpleFieldTypes.TEXTAREA:
return new DynamicTextAreaModel(
{
id: id,
placeholder: label,
required: field_config.required,
disabled: field_config.read_only,
rows: 5,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
},
maxLength: (field_config as TextAreaFieldConfig).max_length,
minLength: (field_config as TextAreaFieldConfig).min_length
},
errorMessages: {
external_error: '{{external_error}}'
},
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.DATE:
return new DynamicInputModel(
{
id: id,
placeholder: label,
inputType: DYNAMIC_FORM_CONTROL_INPUT_TYPE_DATE,
required: field_config.required,
disabled: field_config.read_only,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
}
},
errorMessages: {
external_error: '{{external_error}}'
},
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.INTEGER:
const ifc = (field_config as IntegerFieldConfig);
return new DynamicInputModel(
{
id: id,
placeholder: label,
inputType: DYNAMIC_FORM_CONTROL_INPUT_TYPE_NUMBER,
required: field_config.required,
disabled: field_config.read_only,
min: ifc.min_value,
max: ifc.max_value,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
},
min: ifc.min_value,
max: ifc.max_value
},
errorMessages: {
external_error: '{{external_error}}',
min: `Value must be in range ${ifc.min_value} - ${ifc.max_value}`,
max: `Value must be in range ${ifc.min_value} - ${ifc.max_value}`
}
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.FLOAT:
const ffc = (field_config as FloatFieldConfig);
return new DynamicInputModel(
{
id: id,
placeholder: label,
inputType: DYNAMIC_FORM_CONTROL_INPUT_TYPE_NUMBER,
required: field_config.required,
disabled: field_config.read_only,
min: ffc.min_value,
max: ffc.max_value,
step: 0.00000001,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
},
min: ffc.min_value,
max: ffc.max_value
},
errorMessages: {
external_error: '{{external_error}}',
min: `Value must be in range ${ffc.min_value} - ${ffc.max_value}`,
max: `Value must be in range ${ffc.min_value} - ${ffc.max_value}`
}
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.BOOLEAN:
return new DynamicCheckboxModel(
{
id: id,
label: label,
required: field_config.required,
disabled: field_config.read_only,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
}
},
errorMessages: {
external_error: '{{external_error}}'
}
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.RADIO:
return new DynamicRadioGroupModel(
{
id: id,
label: label,
options: (field_config as RadioFieldConfig).choices,
required: field_config.required,
disabled: field_config.read_only,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
}
},
errorMessages: {
external_error: '{{external_error}}'
}
},
merge_layouts(field_config.layout, extra_layout)
);
case SimpleFieldTypes.SELECT:
return new DynamicSelectModel(
{
id: id,
placeholder: label,
options: (field_config as SelectFieldConfig).choices,
required: field_config.required,
disabled: field_config.read_only,
validators: {
external_validator: {
name: external_validator.name,
args: {id: id, errors: this._external_errors}
}
},
errorMessages: {
external_error: '{{external_error}}'
}
},
merge_layouts(field_config.layout, extra_layout)
);
case CompositeFieldTypes.FIELDSET: {
const fieldset_layout = merge_layouts(field_config.layout, {
grid: {
label: 'dadf-fieldset'
}
});
return new DynamicFormGroupModel(
{
id: 'generated_' + this.last_id++,
label: label,
group: this._generate_ui_control_array((field_config as FieldSetConfig).controls)
},
merge_layouts(fieldset_layout, extra_layout)
);
}
case CompositeFieldTypes.GROUP: {
const group_layout = merge_layouts(field_config.layout, {
grid: {
label: 'group'
}
});
return new DynamicFormGroupModel(
{
id: 'generated_' + this.last_id++,
group: this._generate_ui_control_array((field_config as FieldSetConfig).controls)
},
merge_layouts(group_layout, extra_layout)
);
}
case CompositeFieldTypes.COLUMNS: {
const csf = (field_config as ColumnsFieldConfig);
const model: DynamicFormControlModel[] = [];
for (const config of csf.controls) {
const _control = this._generate_ui_control(
{
...config,
layout: merge_layouts(config.layout,
{
grid: {
host: `dadf-column-${csf.controls.length}`
}
}
)
});
if (_control) {
model.push(_control);
}
}
return new DynamicFormGroupModel(
{
id: 'generated_' + this.last_id++,
group: model
},
merge_layouts(
merge_layouts(
field_config.layout,
{
grid: {
control: `dadf-columns dadf-columns-${csf.controls.length}`
},
// element: {
// container: '---container',
// control: '---control',
// errors: '---errors',
// group: '---group',
// hint: '---hint',
// host: '---host',
// label: '---label',
// option: '---option'
// }
}
), extra_layout)
);
}
default:
throw new Error(`No ui control model for ${type}`);
}
}
private _update_initial_data() {
if (this._initial_data && this.form_group) {
this.iterateControls((name, control) => {
console.log(name, control);
if (name in this._initial_data) {
control.setValue(this._initial_data[name]);
}
});
}
}
public get valid() {
if (this.form_group) {
return this.form_group.valid;
}
return true;
}
public get value() {
if (this.form_group) {
return this.form_group.value;
}
return true;
}
public on_submit_on_enter() {
this.submit_on_enter.next(this.value);
}
private getControlByName(name: string): AbstractControl | undefined {
function getControl(control: AbstractControl, controlName: string): AbstractControl | undefined {
let ret: AbstractControl | undefined;
if (control instanceof FormGroup) {
const formGroup = control as FormGroup;
for (const childName in formGroup.controls) {
if (formGroup.controls.hasOwnProperty(childName)) {
const childControl = formGroup.controls[childName];
if (childName === controlName) {
return childControl;
} else {
ret = getControl(childControl, controlName);
if (ret) {
return ret;
}
}
}
}
}
if (control instanceof FormArray) {
console.error('Arrays are not yet supported !');
}
}
return getControl(this.form_group, name);
}
private iterateControls(visitor: (name: string, control: AbstractControl) => void) {
function iter(name: string, control: AbstractControl): void {
visitor(name, control);
if (control instanceof FormGroup) {
const formGroup = control as FormGroup;
for (const childName in formGroup.controls) {
if (formGroup.controls.hasOwnProperty(childName)) {
const childControl = formGroup.controls[childName];
iter(childName, childControl);
}
}
}
if (control instanceof FormArray) {
console.error('Arrays are not yet supported !');
}
}
return iter('---root---', this.form_group);
}
}
export function external_validator(conf: { id: string; errors: any }): ValidatorFn {
// noinspection JSUnusedLocalSymbols
return (_control: AbstractControl): { [key: string]: any } => {
if (conf.id in conf.errors) {
const ret = {external_error: {value: conf.errors[conf.id][0]}};
delete conf.errors[conf.id];
return ret;
} else {
return {};
}
};
}
class AutoCompleter {
constructor(private http: HttpClient,
private errors: ErrorService,
private autocompletion_list: any[] | undefined,
private autocompletion_url: string | undefined,
public model: any) {
}
public change(_widget: any, value: string, form_value: string) {
let filtered_list;
if (this.autocompletion_url) {
this.http
.post<any[]>(this.autocompletion_url + '?query=' + encodeURIComponent(value), form_value)
.catch(error => {
return this.errors.show_communication_error(error);
})
.subscribe(resp => {
resp = resp || [];
filtered_list = resp.map(x => x.label);
this.model.list = filtered_list;
});
} else {
if (this.autocompletion_list) {
filtered_list = this.autocompletion_list.filter(x => x.indexOf(value) >= 0);
this.model.list = filtered_list;
} else {
this.model.list = [];
}
}
}
}
function merge_layouts(layout1_or_undefined: DynamicFormControlLayout | undefined,
layout2_or_undefined: DynamicFormControlLayout | undefined): DynamicFormControlLayout | undefined {
if (layout1_or_undefined === undefined) {
return layout2_or_undefined;
}
if (layout2_or_undefined === undefined) {
return layout1_or_undefined;
}
function merge_classes(clz1_or_undefined: DynamicFormControlLayoutConfig | undefined,
clz2_or_undefined: DynamicFormControlLayoutConfig | undefined) {
if (clz1_or_undefined === undefined) {
return clz2_or_undefined;
}
if (clz2_or_undefined === undefined) {
return clz1_or_undefined;
}
const clz1 = clz1_or_undefined as DynamicFormControlLayoutConfig;
const clz2 = clz2_or_undefined as DynamicFormControlLayoutConfig;
const classes_ret: DynamicFormControlLayoutConfig = {...clz2};
for (const arg in clz1) {
if (classes_ret[arg]) {
classes_ret[arg] = `${classes_ret[arg]} ${clz1[arg]}`;
} else {
classes_ret[arg] = clz1[arg];
}
}
return classes_ret;
}
const layout1 = layout1_or_undefined as DynamicFormControlLayout;
const layout2 = layout2_or_undefined as DynamicFormControlLayout;
const ret = {
...layout2,
...layout1
};
const grid = merge_classes(layout1.grid, layout2.grid);
const element = merge_classes(layout1.element, layout2.element);
if (grid) {
ret.grid = grid;
}
if (element) {
ret.element = element;
}
return ret;
}