]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/components/submit-button/submit-button.component.ts
update sources to ceph Nautilus 14.2.1
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / shared / components / submit-button / submit-button.component.ts
1 import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
2 import { AbstractControl, FormGroup, FormGroupDirective, NgForm } from '@angular/forms';
3
4 import * as _ from 'lodash';
5
6 /**
7 * This component will render a submit button with the given label.
8 *
9 * The button will disabled itself and show a loading icon when the user clicks
10 * it, usually initiating a request to the server, and it will stay in that
11 * state until the request is finished.
12 *
13 * To indicate that the request failed, returning the button to the enable
14 * state, you need to insert an error in the form with the 'cdSubmitButton' key.
15 * p.e.: this.rbdForm.setErrors({'cdSubmitButton': true});
16 *
17 * It will also check if the form is valid, when clicking the button, and will
18 * focus on the first invalid input.
19 *
20 * @export
21 * @class SubmitButtonComponent
22 * @implements {OnInit}
23 */
24 @Component({
25 selector: 'cd-submit-button',
26 templateUrl: './submit-button.component.html',
27 styleUrls: ['./submit-button.component.scss']
28 })
29 export class SubmitButtonComponent implements OnInit {
30 @Input()
31 form: FormGroup | NgForm;
32 @Input()
33 type = 'submit';
34 @Output()
35 submitAction = new EventEmitter();
36 @Input()
37 disabled = false;
38
39 loading = false;
40
41 constructor(private elRef: ElementRef) {}
42
43 ngOnInit() {
44 this.form.statusChanges.subscribe(() => {
45 if (_.has(this.form.errors, 'cdSubmitButton')) {
46 this.loading = false;
47 _.unset(this.form.errors, 'cdSubmitButton');
48 // Handle Reactive forms.
49 if (this.form instanceof AbstractControl) {
50 (<AbstractControl>this.form).updateValueAndValidity();
51 }
52 }
53 });
54 }
55
56 submit($event) {
57 this.focusButton();
58
59 // Special handling for Template driven forms.
60 if (this.form instanceof FormGroupDirective) {
61 (<FormGroupDirective>this.form).onSubmit($event);
62 }
63
64 if (this.form.invalid) {
65 this.focusInvalid();
66 return;
67 }
68
69 this.loading = true;
70 this.submitAction.emit();
71 }
72
73 focusButton() {
74 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
75 }
76
77 focusInvalid() {
78 const target = this.elRef.nativeElement.offsetParent.querySelector(
79 'input.ng-invalid, select.ng-invalid'
80 );
81
82 if (target) {
83 target.focus();
84 }
85 }
86 }