component.ts 7.0 KB
Newer Older
H
haijiao.yin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
import {HttpClient} from '@angular/common/http';
S
Shu Muto 已提交
16 17 18 19 20 21 22 23 24 25 26 27
import {Component, EventEmitter, forwardRef, Input, OnInit, Output} from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  NG_ASYNC_VALIDATORS,
  NG_VALUE_ACCESSOR,
  Validators,
} from '@angular/forms';
28 29 30 31 32
import {PortMapping} from '@api/backendapi';
import {Observable} from 'rxjs';
import {first, map, startWith} from 'rxjs/operators';
import {FormValidators} from '../validator/validators';
import {validateProtocol} from '../validator/validprotocol.validator';
H
haijiao.yin 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46

const i18n = {
  MSG_PORT_MAPPINGS_SERVICE_TYPE_NONE_LABEL: 'None',
  MSG_PORT_MAPPINGS_SERVICE_TYPE_INTERNAL_LABEL: 'Internal',
  MSG_PORT_MAPPINGS_SERVICE_TYPE_EXTERNAL_LABEL: 'External',
};

interface ServiceType {
  label: string;
  external: boolean;
}

const NO_SERVICE: ServiceType = {
  label: i18n.MSG_PORT_MAPPINGS_SERVICE_TYPE_NONE_LABEL,
S
Shu Muto 已提交
47
  external: false,
H
haijiao.yin 已提交
48 49 50 51
};

const INT_SERVICE: ServiceType = {
  label: i18n.MSG_PORT_MAPPINGS_SERVICE_TYPE_INTERNAL_LABEL,
S
Shu Muto 已提交
52
  external: false,
H
haijiao.yin 已提交
53 54 55 56
};

const EXT_SERVICE: ServiceType = {
  label: i18n.MSG_PORT_MAPPINGS_SERVICE_TYPE_EXTERNAL_LABEL,
S
Shu Muto 已提交
57
  external: true,
H
haijiao.yin 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
};

@Component({
  selector: 'kd-port-mappings',
  templateUrl: './template.html',
  styleUrls: ['./style.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PortMappingsComponent),
      multi: true,
    },
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => PortMappingsComponent),
      multi: true,
S
Shu Muto 已提交
74
    },
H
haijiao.yin 已提交
75 76 77
  ],
})
export class PortMappingsComponent implements OnInit, ControlValueAccessor {
78 79 80
  @Input() protocols: string[];
  @Input() isExternal: boolean;
  @Output() changeExternal: EventEmitter<boolean> = new EventEmitter<boolean>();
H
haijiao.yin 已提交
81

M
Marcin Maciaszczyk 已提交
82
  serviceTypes: ServiceType[];
H
haijiao.yin 已提交
83 84
  portMappingForm: FormGroup;

85
  constructor(private readonly fb_: FormBuilder, private readonly http_: HttpClient) {}
H
haijiao.yin 已提交
86 87 88 89

  ngOnInit(): void {
    this.serviceTypes = [NO_SERVICE, INT_SERVICE, EXT_SERVICE];

S
Shu Muto 已提交
90 91 92 93
    this.portMappingForm = this.fb_.group({
      serviceType: NO_SERVICE,
      portMappings: this.fb_.array([]),
    });
H
haijiao.yin 已提交
94 95 96 97 98 99 100 101
    this.serviceType.valueChanges.subscribe(() => {
      this.changeServiceType();
    });
    this.portMappingForm.valueChanges.subscribe(v => {
      this.propagateChange(v);
    });
  }

S
Shu Muto 已提交
102
  validate(_: FormControl): Observable<{[key: string]: boolean} | null> {
H
haijiao.yin 已提交
103
    return this.portMappingForm.statusChanges.pipe(
S
Shu Muto 已提交
104 105 106 107 108 109
      startWith(this.portMappingForm.status),
      first(() => !this.portMappingForm.pending),
      map(() => {
        return this.portMappingForm.invalid ? {error: true} : null;
      }),
    );
H
haijiao.yin 已提交
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
  }

  changeServiceType(): void {
    // add or remove port mappings
    if (this.serviceType.value === NO_SERVICE) {
      const length = this.portMappings.length;
      for (let i = 0; i < length; i++) {
        this.portMappings.removeAt(0);
      }
    } else if (this.portMappings.length === 0) {
      this.portMappings.push(this.newEmptyPortMapping(this.protocols[0]));
    }

    // set flag
    this.isExternal = this.serviceType.value.external;
    this.changeExternal.emit(this.isExternal);

    for (let i = 0; i < this.portMappings.length; i++) {
      const ele = this.portMappings.at(i).get('protocol');
      ele.clearAsyncValidators();
      ele.setAsyncValidators(validateProtocol(this.http_, this.isExternal));
      ele.updateValueAndValidity();
    }
  }

  get portMappings(): FormArray {
    return this.portMappingForm.get('portMappings') as FormArray;
  }

  get serviceType(): AbstractControl {
    return this.portMappingForm.get('serviceType') as AbstractControl;
  }

  private newEmptyPortMapping(defaultProtocol: string): FormGroup {
    return this.fb_.group({
M
Marcin Maciaszczyk 已提交
145 146
      port: ['', Validators.compose([FormValidators.isInteger, Validators.min(1), Validators.max(65535)])],
      targetPort: ['', Validators.compose([FormValidators.isInteger, Validators.min(1), Validators.max(65535)])],
S
Shu Muto 已提交
147
      protocol: [defaultProtocol],
H
haijiao.yin 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    });
  }

  /**
   * Call checks on port mapping:
   *  - adds new port mapping when last empty port mapping has been filled
   *  - validates port mapping
   */
  checkPortMapping(portMappingIndex: number): void {
    this.addProtocolIfNeeed();
    this.validatePortMapping(portMappingIndex);
    this.portMappings.updateValueAndValidity();
  }

  addProtocolIfNeeed(): void {
163
    const lastPortMapping = this.portMappings.controls[this.portMappings.length - 1];
H
haijiao.yin 已提交
164 165 166 167 168 169 170 171 172
    if (this.isPortMappingFilled(lastPortMapping)) {
      this.portMappings.push(this.newEmptyPortMapping(this.protocols[0]));
    }
  }

  /**
   * Returns true when the given port mapping is filled by the user, i.e., is not empty.
   */
  private isPortMappingFilled(portMapping: AbstractControl): boolean {
S
Shu Muto 已提交
173
    return !!portMapping.get('port').value && !!portMapping.get('targetPort').value;
H
haijiao.yin 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  }

  /**
   * Validates port mapping. In case when only one port is specified it is considered as invalid.
   */
  private validatePortMapping(portIndex: number): void {
    if (portIndex === 0) {
      return;
    }
    const portMapping = this.portMappings.at(portIndex);

    const portElem = portMapping.get('port');
    const targetPortElem = portMapping.get('targetPort');
    const port = portElem.value;
    const targetPort = targetPortElem.value;

    const filledOrEmpty = this.isPortMappingFilledOrEmpty(port, targetPort);
    const isValidPort = filledOrEmpty || !!port;
    const isValidTargetPort = filledOrEmpty || !!targetPort;

194 195
    portElem.setErrors(isValidPort ? null : {required: true});
    targetPortElem.setErrors(isValidTargetPort ? null : {required: true});
H
haijiao.yin 已提交
196 197 198 199 200 201
    this.portMappingForm.updateValueAndValidity();
  }

  /**
   * Returns true when the given port mapping is filled or empty (both ports), false otherwise.
   */
202
  private isPortMappingFilledOrEmpty(port: number, targetPort: number): boolean {
H
haijiao.yin 已提交
203 204 205 206
    return !port === !targetPort;
  }

  isRemovable(index: number): boolean {
S
Shu Muto 已提交
207
    return index !== this.portMappings.length - 1;
H
haijiao.yin 已提交
208 209 210 211 212 213 214 215 216 217 218
  }

  remove(index: number): void {
    this.portMappings.removeAt(index);
  }

  /**
   * Returns true if the given port mapping is the first in the list.
   * @param {number} index
   */
  isFirst(index: number): boolean {
S
Shu Muto 已提交
219
    return index === 0;
H
haijiao.yin 已提交
220 221
  }

222
  propagateChange = (_: {portMappings: PortMapping[]}) => {};
H
haijiao.yin 已提交
223 224 225

  writeValue(): void {}

226
  registerOnChange(fn: (_: {portMappings: PortMapping[]}) => void): void {
H
haijiao.yin 已提交
227 228 229 230
    this.propagateChange = fn;
  }
  registerOnTouched(): void {}
}