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 = this.data.instanceId;
95 this.policyTypeName = this.data.name;
96 this.policyTypeId = this.data.policyTypeId;
97 this.parseJson(data.createSchema, data.instanceJson);
101 this.jsonFormStatusMessage = 'Init';
102 this.formActive = true;
103 this.ui.darkModeState.subscribe((isDark) => {
104 this.darkMode = isDark;
112 if (this.policyInstanceId == null) {
113 this.policyInstanceId = uuid.v4();
115 const policyJson: string = this.prettyLiveFormData;
116 const self: PolicyInstanceDialogComponent = this;
117 this.dataService.putPolicy(this.policyTypeId, this.policyInstanceId, policyJson).subscribe(
120 self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId + ' submitted');
123 self.errorService.displayError('updatePolicy failed: ' + error.message);
130 this.dialogRef.close();
133 public onChanges(data: any) {
134 this.liveFormData = data;
137 get prettyLiveFormData() {
138 return JSON.stringify(this.liveFormData, null, 2);
141 get schemaAsString() {
142 return JSON.stringify(this.jsonSchemaObject, null, 2);
146 return JSON.stringify(this.jsonObject, null, 2);
149 isValid(isValid: boolean): void {
150 this.formIsValid = isValid;
153 validationErrors(data: any): void {
154 this.formValidationErrors = data;
157 get prettyValidationErrors() {
158 if (!this.formValidationErrors) { return null; }
159 const errorArray = [];
160 for (const error of this.formValidationErrors) {
161 const message = error.message;
162 const dataPathArray = JsonPointer.parse(error.dataPath);
163 if (dataPathArray.length) {
164 let field = dataPathArray[0];
165 for (let i = 1; i < dataPathArray.length; i++) {
166 const key = dataPathArray[i];
167 field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
169 errorArray.push(`${field}: ${message}`);
171 errorArray.push(message);
174 return errorArray.join('<br>');
177 private parseJson(createSchema: string, instanceJson: string): void {
179 this.jsonSchemaObject = JSON.parse(createSchema);
180 if (this.data.instanceJson != null) {
181 this.jsonObject = JSON.parse(instanceJson);
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.create_schema;
199 const instanceId = instance ? instance.instanceId : null;
200 const instanceJson = instance ? instance.instance : null;
201 const name = policyType.name;
208 panelClass: darkMode ? 'dark-theme' : '',