3 * ============LICENSE_START=======================================================
4 * Copyright (C) 2022 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
23 import {YamlFunction} from "../../../../../models/yaml-function";
24 import {FormControl, FormGroup, Validators, AbstractControl, ValidationErrors, ValidatorFn} from "@angular/forms";
25 import * as jsYaml from 'js-yaml';
28 selector: 'app-yaml-function',
29 templateUrl: './yaml-function.component.html',
30 styleUrls: ['./yaml-function.component.less']
32 export class YamlFunctionComponent implements OnInit {
34 @Input() yamlFunction: YamlFunction;
35 @Output() onValidityChange: EventEmitter<YamlFunctionValidationEvent> = new EventEmitter<YamlFunctionValidationEvent>();
37 yamlValueForm: FormControl = new FormControl('', [Validators.minLength(1), YamlValidator()]);
38 formGroup: FormGroup = new FormGroup(
40 'value': this.yamlValueForm
45 this.formGroup.valueChanges.subscribe(() => {
46 this.onValidityChange.emit({
47 isValid: this.formGroup.valid,
48 value: this.formGroup.valid ? this.buildYamlFunctionFromForm() : undefined
51 if (this.yamlFunction) {
52 this.yamlValueForm.setValue(this.yamlFunction.value);
56 private buildYamlFunctionFromForm(): YamlFunction {
57 const yamlFunction = new YamlFunction();
58 yamlFunction.value = this.yamlValueForm.value;
63 export class YamlFunctionValidationEvent {
68 export function YamlValidator(): ValidatorFn {
69 return (control: AbstractControl): ValidationErrors | null => {
71 return {invalidYaml: {value: control.value}};
74 jsYaml.load(control.value);
77 return {invalidYaml: {value: control.value}};