Skip to content

Commit

Permalink
Prevent page exit on the create page when there are unsaved changes (#…
Browse files Browse the repository at this point in the history
…6566)

* fix: prevent page exit with unsaved changes in create page

* fix: remove unsaved changes confirm dialog on create page submit

* Refactor code and use custom dialog for internal view change

* Update conditions

Co-authored-by: Sebastian Florek <sebastian.florek@kubermatic.com>
  • Loading branch information
avinashupadhya99 and Sebastian Florek authored Dec 22, 2021
1 parent 0cb2f25 commit 254b752
Show file tree
Hide file tree
Showing 12 changed files with 234 additions and 54 deletions.
29 changes: 29 additions & 0 deletions src/app/frontend/common/dialogs/config/dialog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// 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.

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';

export interface ConfirmDialogConfig {
title: string;
message: string;
}

@Component({
selector: 'kd-confirm-dialog',
templateUrl: 'template.html',
})
export class ConfirmDialog {
constructor(@Inject(MAT_DIALOG_DATA) public data: ConfirmDialogConfig) {}
}
27 changes: 27 additions & 0 deletions src/app/frontend/common/dialogs/config/template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!--
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.
-->

<h2 mat-dialog-title>{{data.title}}</h2>
<mat-dialog-content class="kd-dialog-text">{{data.message}}</mat-dialog-content>
<mat-dialog-actions>
<button mat-button
color="secondary"
[mat-dialog-close]="false">No</button>

<button mat-button
color="primary"
[mat-dialog-close]="true">Yes</button>
</mat-dialog-actions>
2 changes: 2 additions & 0 deletions src/app/frontend/common/dialogs/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

import {NgModule} from '@angular/core';
import {ConfirmDialog} from '@common/dialogs/config/dialog';

import {SharedModule} from '../../shared.module';
import {ComponentsModule} from '../components/module';
Expand All @@ -35,6 +36,7 @@ import {TriggerResourceDialog} from './triggerresource/dialog';
RestartResourceDialog,
ScaleResourceDialog,
TriggerResourceDialog,
ConfirmDialog,
],
exports: [
AlertDialog,
Expand Down
27 changes: 27 additions & 0 deletions src/app/frontend/common/interfaces/candeactivate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 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.

import {Directive, HostListener} from '@angular/core';

@Directive()
export abstract class ICanDeactivate {
abstract canDeactivate(): boolean;

@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = true;
}
}
}
38 changes: 38 additions & 0 deletions src/app/frontend/common/services/guard/candeactivate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// 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.

import {Injectable} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {CanDeactivate} from '@angular/router';
import {ConfirmDialog, ConfirmDialogConfig} from '@common/dialogs/config/dialog';
import {ICanDeactivate} from '@common/interfaces/candeactivate';
import {Observable, of} from 'rxjs';

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<ICanDeactivate> {
constructor(private readonly dialog_: MatDialog) {}

canDeactivate(component: ICanDeactivate): Observable<boolean> {
if (component.canDeactivate()) {
return of(true);
}

const config = {
title: 'Unsaved changes',
message: 'The form has not been submitted yet, do you really want to leave?',
} as ConfirmDialogConfig;

return this.dialog_.open(ConfirmDialog, {data: config}).afterClosed();
}
}
16 changes: 14 additions & 2 deletions src/app/frontend/create/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import {Component} from '@angular/core';
import {Component, ViewChild} from '@angular/core';
import {ICanDeactivate} from '@common/interfaces/candeactivate';
import {CreateFromFileComponent} from './from/file/component';
import {CreateFromFormComponent} from './from/form/component';
import {CreateFromInputComponent} from './from/input/component';

@Component({
selector: 'kd-create',
templateUrl: './template.html',
styleUrls: ['./style.scss'],
})
export class CreateComponent {}
export class CreateComponent extends ICanDeactivate {
@ViewChild(CreateFromInputComponent) fromInput: CreateFromInputComponent;
@ViewChild(CreateFromFileComponent) fromFile: CreateFromFileComponent;
@ViewChild(CreateFromFormComponent) fromForm: CreateFromFormComponent;

canDeactivate(): boolean {
return this.fromInput.canDeactivate() && this.fromFile.canDeactivate() && this.fromForm.canDeactivate();
}
}
20 changes: 16 additions & 4 deletions src/app/frontend/create/from/file/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import {Component, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';
import {KdFile} from '@api/root.ui';
import {ICanDeactivate} from '@common/interfaces/candeactivate';

import {CreateService} from '@common/services/create/service';
import {HistoryService} from '@common/services/global/history';
Expand All @@ -25,22 +26,29 @@ import {NamespaceService} from '@common/services/global/namespace';
templateUrl: './template.html',
styleUrls: ['./style.scss'],
})
export class CreateFromFileComponent {
@ViewChild(NgForm, {static: true}) private readonly ngForm: NgForm;
export class CreateFromFileComponent extends ICanDeactivate {
file: KdFile;
@ViewChild(NgForm, {static: true}) private readonly ngForm: NgForm;
private creating_ = false;

constructor(
private readonly namespace_: NamespaceService,
private readonly create_: CreateService,
private readonly history_: HistoryService
) {}
) {
super();
}

isCreateDisabled(): boolean {
return !this.file || this.file.content.length === 0 || this.create_.isDeployDisabled();
}

create(): void {
this.create_.createContent(this.file.content, true, this.file.name);
this.creating_ = true;
this.create_
.createContent(this.file.content, true, this.file.name)
.then(() => (this.creating_ = false))
.finally(() => (this.creating_ = false));
}

onFileLoad(file: KdFile): void {
Expand All @@ -54,4 +62,8 @@ export class CreateFromFileComponent {
areMultipleNamespacesSelected(): boolean {
return this.namespace_.areMultipleNamespacesSelected();
}

canDeactivate(): boolean {
return this.isCreateDisabled() && !this.creating_;
}
}
1 change: 0 additions & 1 deletion src/app/frontend/create/from/file/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
</kd-upload-file>

<button type="button"
type="submit"
[disabled]="isCreateDisabled()"
color="primary"
mat-raised-button
Expand Down
106 changes: 62 additions & 44 deletions src/app/frontend/create/from/form/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ import {
Protocols,
SecretList,
} from '@api/root.api';
import {take} from 'rxjs/operators';
import {ICanDeactivate} from '@common/interfaces/candeactivate';

import {CreateService} from '@common/services/create/service';
import {HistoryService} from '@common/services/global/history';
import {NamespaceService} from '@common/services/global/namespace';
import {take} from 'rxjs/operators';

import {CreateNamespaceDialog} from './createnamespace/dialog';
import {CreateSecretDialog} from './createsecret/dialog';
Expand All @@ -46,7 +47,7 @@ const APP_LABEL_KEY = 'k8s-app';
templateUrl: './template.html',
styleUrls: ['./style.scss'],
})
export class CreateFromFormComponent implements OnInit {
export class CreateFromFormComponent extends ICanDeactivate implements OnInit {
readonly nameMaxLength = 24;

showMoreOptions_ = false;
Expand All @@ -55,9 +56,10 @@ export class CreateFromFormComponent implements OnInit {
secrets: string[];
isExternal = false;
labelArr: DeployLabel[] = [];

form: FormGroup;

private creating_ = false;

constructor(
private readonly namespace_: NamespaceService,
private readonly create_: CreateService,
Expand All @@ -66,46 +68,8 @@ export class CreateFromFormComponent implements OnInit {
private readonly route_: ActivatedRoute,
private readonly fb_: FormBuilder,
private readonly dialog_: MatDialog
) {}

ngOnInit(): void {
this.form = this.fb_.group({
name: ['', Validators.compose([Validators.required, FormValidators.namePattern])],
containerImage: ['', Validators.required],
replicas: [1, Validators.compose([Validators.required, FormValidators.isInteger])],
description: [''],
namespace: [this.route_.snapshot.params.namespace || '', Validators.required],
imagePullSecret: [''],
cpuRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
memoryRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
containerCommand: [''],
containerCommandArgs: [''],
runAsPrivileged: [false],
portMappings: this.fb_.control([]),
variables: this.fb_.control([]),
labels: this.fb_.control([]),
});
this.labelArr = [new DeployLabel(APP_LABEL_KEY, '', false), new DeployLabel()];
this.name.valueChanges.subscribe(v => {
this.labelArr[0].value = v;
this.labels.patchValue([{index: 0, value: v}]);
});
this.namespace.valueChanges.subscribe((namespace: string) => {
this.name.clearAsyncValidators();
this.name.setAsyncValidators(validateUniqueName(this.http_, namespace));
this.name.updateValueAndValidity();
});
this.http_.get('api/v1/namespace').subscribe((result: NamespaceList) => {
this.namespaces = result.namespaces.map((namespace: Namespace) => namespace.objectMeta.name);
this.namespace.patchValue(
!this.namespace_.areMultipleNamespacesSelected()
? this.route_.snapshot.params.namespace || this.namespaces[0]
: this.namespaces[0]
);
});
this.http_
.get('api/v1/appdeployment/protocols')
.subscribe((protocols: Protocols) => (this.protocols = protocols.protocols));
) {
super();
}

get name(): AbstractControl {
Expand Down Expand Up @@ -164,6 +128,47 @@ export class CreateFromFormComponent implements OnInit {
return this.form.get('labels') as FormArray;
}

ngOnInit(): void {
this.form = this.fb_.group({
name: ['', Validators.compose([Validators.required, FormValidators.namePattern])],
containerImage: ['', Validators.required],
replicas: [1, Validators.compose([Validators.required, FormValidators.isInteger])],
description: [''],
namespace: [this.route_.snapshot.params.namespace || '', Validators.required],
imagePullSecret: [''],
cpuRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
memoryRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
containerCommand: [''],
containerCommandArgs: [''],
runAsPrivileged: [false],
portMappings: this.fb_.control([]),
variables: this.fb_.control([]),
labels: this.fb_.control([]),
});
this.labelArr = [new DeployLabel(APP_LABEL_KEY, '', false), new DeployLabel()];
this.name.valueChanges.subscribe(v => {
this.labelArr[0].value = v;
this.labels.patchValue([{index: 0, value: v}]);
});
this.namespace.valueChanges.subscribe((namespace: string) => {
this.name.clearAsyncValidators();
this.name.setAsyncValidators(validateUniqueName(this.http_, namespace));
this.name.updateValueAndValidity();
});
this.http_.get('api/v1/namespace').subscribe((result: NamespaceList) => {
this.namespaces = result.namespaces.map((namespace: Namespace) => namespace.objectMeta.name);
this.namespace.patchValue(
!this.namespace_.areMultipleNamespacesSelected()
? this.route_.snapshot.params.namespace || this.namespaces[0]
: this.namespaces[0]
);
this.form.markAsPristine();
});
this.http_
.get('api/v1/appdeployment/protocols')
.subscribe((protocols: Protocols) => (this.protocols = protocols.protocols));
}

changeExternal(isExternal: boolean): void {
this.isExternal = isExternal;
}
Expand All @@ -172,6 +177,10 @@ export class CreateFromFormComponent implements OnInit {
this.imagePullSecret.patchValue('');
}

hasUnsavedChanges(): boolean {
return this.form.dirty;
}

isCreateDisabled(): boolean {
return !this.form.valid || this.create_.isDeployDisabled();
}
Expand Down Expand Up @@ -273,6 +282,7 @@ export class CreateFromFormComponent implements OnInit {
}

deploy(): void {
this.creating_ = true;
const portMappings = this.portMappings.value.portMappings || [];
const variables = this.variables.value.variables || [];
const labels = this.labels.value.labels || [];
Expand All @@ -293,6 +303,14 @@ export class CreateFromFormComponent implements OnInit {
labels: this.toBackendApiLabels(labels),
runAsPrivileged: this.runAsPrivileged.value,
};
this.create_.deploy(spec);

this.create_
.deploy(spec)
.then(() => (this.creating_ = false))
.finally(() => (this.creating_ = false));
}

canDeactivate(): boolean {
return !this.hasUnsavedChanges() && !this.creating_;
}
}
Loading

0 comments on commit 254b752

Please sign in to comment.