First version of policy editor components
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy / no-type-policy-editor / no-type-policy-editor.component.ts
1 import { Component, Input, OnInit } from '@angular/core';
2 import { AbstractControl, ControlContainer, FormBuilder, FormControl, FormGroup, FormGroupDirective, ValidatorFn, Validators } from '@angular/forms';
3
4 @Component({
5   selector: 'nrcp-no-type-policy-editor',
6   templateUrl: './no-type-policy-editor.component.html',
7   styleUrls: ['./no-type-policy-editor.component.scss'],
8   viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
9 })
10 export class NoTypePolicyEditorComponent implements OnInit {
11
12   @Input() instanceForm: FormGroup;
13   @Input() policyJson: string;
14
15   constructor(
16     private formBuilder: FormBuilder) { }
17
18   ngOnInit(): void {
19     this.instanceForm.addControl(
20       'policyJsonTextArea', new FormControl(this.policyJson, [
21         Validators.required,
22         jsonValidator()
23       ])
24     )
25   }
26
27   get policyJsonTextArea(): AbstractControl {
28     return this.instanceForm ? this.instanceForm.get('policyJsonTextArea') : null;
29   }
30
31   formatJsonInput(): void {
32     this.policyJson = formatJsonString(JSON.parse(this.policyJsonTextArea.value));
33   }
34 }
35
36 export function formatJsonString(jsonToFormat: any): string {
37   return JSON.stringify(jsonToFormat, null, 2);
38 }
39
40 export function jsonValidator(): ValidatorFn {
41   return (control: AbstractControl): { [key: string]: any } | null => {
42     const notValid = !isJsonValid(control.value);
43     return notValid ? { 'invalidJson': { value: control.value } } : null;
44   };
45 }
46
47 export function isJsonValid(json: string): boolean {
48   try {
49     if (json != null) {
50       JSON.parse(json);
51       return true;
52     } else {
53       return false;
54     }
55   } catch (jsonError) {
56     return false;
57   }
58 }