2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
20 import { animate, state, style, transition, trigger } from '@angular/animations';
21 import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
22 import { MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { MatMenuTrigger } from '@angular/material/menu';
24 import { JsonPointer } from 'angular6-json-schema-form';
25 import * as uuid from 'uuid';
26 import { PolicyInstance, PolicyType } from '../interfaces/policy.types';
27 import { PolicyService } from '../services/policy/policy.service';
28 import { ErrorDialogService } from '../services/ui/error-dialog.service';
29 import { NotificationService } from './../services/ui/notification.service';
30 import { UiService } from '../services/ui/ui.service';
34 selector: 'rd-policy-instance-dialog',
35 templateUrl: './policy-instance-dialog.component.html',
36 styleUrls: ['./policy-instance-dialog.component.scss'],
38 trigger('expandSection', [
39 state('in', style({ height: '*' })),
40 transition(':enter', [
41 style({ height: 0 }), animate(100),
43 transition(':leave', [
44 style({ height: '*' }),
45 animate(100, style({ height: 0 })),
50 export class PolicyInstanceDialogComponent implements OnInit, AfterViewInit {
59 jsonFormStatusMessage = 'Loading form...';
60 jsonSchemaObject: any = {};
64 jsonFormOptions: any = {
65 addSubmit: false, // Add a submit button if layout does not have one
66 debug: false, // Don't show inline debugging information
67 loadExternalAssets: true, // Load external css and JavaScript for frameworks
68 returnEmptyFields: false, // Don't return values for empty input fields
69 setSchemaDefaults: true, // Always use schema defaults for empty fields
70 defautWidgetOptions: { feedback: true }, // Show inline feedback icons
73 liveFormData: any = {};
74 formValidationErrors: any;
78 @ViewChild(MatMenuTrigger, { static: true }) menuTrigger: MatMenuTrigger;
80 public policyInstanceId: string;
81 public policyTypeName: string;
83 private policyTypeId: number;
87 private dataService: PolicyService,
88 private errorService: ErrorDialogService,
89 private notificationService: NotificationService,
90 @Inject(MAT_DIALOG_DATA) private data,
91 private dialogRef: MatDialogRef<PolicyInstanceDialogComponent>,
92 private ui: UiService) {
93 this.formActive = false;
94 this.policyInstanceId = data.instanceId;
95 this.policyTypeName = data.name;
96 this.policyTypeId = data.policyTypeId;
97 this.jsonSchemaObject = data.createSchema;
98 this.jsonObject = this.parseJson(data.instanceJson);
102 this.jsonFormStatusMessage = 'Init';
103 this.formActive = true;
104 this.ui.darkModeState.subscribe((isDark) => {
105 this.darkMode = isDark;
113 if (this.policyInstanceId == null) {
114 this.policyInstanceId = uuid.v4();
116 const policyJson: string = this.prettyLiveFormData;
117 const self: PolicyInstanceDialogComponent = this;
118 this.dataService.putPolicy(this.policyTypeId, this.policyInstanceId, policyJson).subscribe(
121 self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId + ' submitted');
124 self.errorService.displayError('updatePolicy failed: ' + error.message);
131 this.dialogRef.close();
134 public onChanges(formData: any) {
135 this.liveFormData = formData;
138 get prettyLiveFormData() {
139 return JSON.stringify(this.liveFormData, null, 2);
142 get schemaAsString() {
143 return JSON.stringify(this.jsonSchemaObject, null, 2);
147 return JSON.stringify(this.jsonObject, null, 2);
150 isValid(isValid: boolean): void {
151 this.formIsValid = isValid;
154 validationErrors(validationErrors: any): void {
155 this.formValidationErrors = validationErrors;
158 get prettyValidationErrors() {
159 if (!this.formValidationErrors) { return null; }
160 const errorArray = [];
161 for (const error of this.formValidationErrors) {
162 const message = error.message;
163 const dataPathArray = JsonPointer.parse(error.dataPath);
164 if (dataPathArray.length) {
165 let field = dataPathArray[0];
166 for (let i = 1; i < dataPathArray.length; i++) {
167 const key = dataPathArray[i];
168 field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
170 errorArray.push(`${field}: ${message}`);
172 errorArray.push(message);
175 return errorArray.join('<br>');
178 private parseJson(str: string): string {
181 return JSON.parse(str);
183 } catch (jsonError) {
184 this.jsonFormStatusMessage =
186 'parser returned:\n\n' + jsonError;
191 public toggleVisible(item: string) {
192 this.isVisible[item] = !this.isVisible[item];
196 export function getPolicyDialogProperties(policyType: PolicyType, instance: PolicyInstance, darkMode: boolean): MatDialogConfig {
197 const policyTypeId = policyType.policy_type_id;
198 const createSchema = policyType.schemaObject;
199 const instanceId = instance ? instance.instanceId : null;
200 const instanceJson = instance ? instance.instance : null;
201 const name = policyType.name;
208 panelClass: darkMode ? 'dark-theme' : '',