Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NAS-131790 / 25.04 / Defines SlideIn2CloseConfirmation interface for confirmation before closing slide-ins #11005

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/app/interfaces/slide-in-close-confirmation.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Observable } from 'rxjs';

export interface SlideIn2CloseConfirmation {
requiresConfirmationOnClose(): Observable<boolean>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import { MockComponent } from 'ng-mocks';
import {
Subject, of,
} from 'rxjs';
import { DialogService } from 'app/modules/dialog/dialog.service';
import { SlideIn2Component } from 'app/modules/slide-ins/components/slide-in2/slide-in2.component';
import { CloudSyncFormComponent } from 'app/pages/data-protection/cloudsync/cloudsync-form/cloudsync-form.component';
import { SshConnectionFormComponent } from 'app/pages/credentials/backup-credentials/ssh-connection-form/ssh-connection-form.component';
import { ChainedComponentResponse, ChainedSlideInService } from 'app/services/chained-slide-in.service';

describe('IxSlideIn2Component', () => {
Expand All @@ -21,9 +22,10 @@ describe('IxSlideIn2Component', () => {
A11yModule,
],
declarations: [
MockComponent(CloudSyncFormComponent),
MockComponent(SshConnectionFormComponent),
],
providers: [

mockProvider(ElementRef),
mockProvider(Renderer2),
mockProvider(ChainedSlideInService, {
Expand All @@ -43,12 +45,17 @@ describe('IxSlideIn2Component', () => {
});
});

function setupComponent(): void {
function setupComponent(confirm: boolean): void {
spectator = createComponent({
providers: [
mockProvider(DialogService, {
confirm: jest.fn(() => of(confirm)),
}),
],
props: {
componentInfo: {
close$,
component: CloudSyncFormComponent,
component: SshConnectionFormComponent,
id: 'id',
data: undefined,
isComponentAlive: true,
Expand All @@ -58,24 +65,74 @@ describe('IxSlideIn2Component', () => {
lastIndex: 0,
},
});
jest.spyOn(console, 'error').mockImplementation();
tick(10);
}

it('close slide-in when backdrop is clicked', fakeAsync(() => {
setupComponent();
setupComponent(true);
const form = spectator.query(SshConnectionFormComponent);
Object.defineProperty(form, 'requiresConfirmationOnClose', {
value: undefined,
});
const backdrop = spectator.query('.ix-slide-in2-background');
backdrop.dispatchEvent(new Event('click'));
spectator.detectChanges();
expect(close$.next).toHaveBeenCalledWith({ response: false, error: null });
expect(close$.complete).toHaveBeenCalled();
tick(305);
expect(console.error).toHaveBeenCalledWith('Confirmation before closing form not defined');
expect(spectator.inject(ChainedSlideInService).popComponent).toHaveBeenCalledWith('id');
discardPeriodicTasks();
}));

it('opens the slide in component', fakeAsync(() => {
setupComponent();
const form = spectator.query(CloudSyncFormComponent);
setupComponent(true);
const form = spectator.query(SshConnectionFormComponent);
expect(form).toExist();
}));

it('shows confirmation when required', fakeAsync(() => {
setupComponent(true);
const form = spectator.query(SshConnectionFormComponent);
jest.spyOn(form, 'requiresConfirmationOnClose').mockImplementation(() => of(true));
const backdrop = spectator.query('.ix-slide-in2-background');
backdrop.dispatchEvent(new Event('click'));
spectator.detectChanges();
expect(spectator.inject(DialogService).confirm).toHaveBeenCalledWith({
title: 'Unsaved Changes',
message: 'You have unsaved changes. Are you sure you want to close?',
cancelText: 'No',
buttonText: 'Yes',
buttonColor: 'red',
hideCheckbox: true,
});
expect(close$.next).toHaveBeenCalledWith({ response: false, error: null });
expect(close$.complete).toHaveBeenCalled();
tick(305);
expect(spectator.inject(ChainedSlideInService).popComponent).toHaveBeenCalledWith('id');
discardPeriodicTasks();
}));

it('doesnt close slidein if confirmation is false', fakeAsync(() => {
setupComponent(false);
const form = spectator.query(SshConnectionFormComponent);
jest.spyOn(form, 'requiresConfirmationOnClose').mockImplementation(() => of(true));
const backdrop = spectator.query('.ix-slide-in2-background');
backdrop.dispatchEvent(new Event('click'));
spectator.detectChanges();
expect(spectator.inject(DialogService).confirm).toHaveBeenCalledWith({
title: 'Unsaved Changes',
message: 'You have unsaved changes. Are you sure you want to close?',
cancelText: 'No',
buttonText: 'Yes',
buttonColor: 'red',
hideCheckbox: true,
});
expect(close$.next).not.toHaveBeenCalled();
expect(close$.complete).not.toHaveBeenCalled();
tick(305);
expect(spectator.inject(ChainedSlideInService).popComponent).not.toHaveBeenNthCalledWith(2);
discardPeriodicTasks();
}));
});
145 changes: 102 additions & 43 deletions src/app/modules/slide-ins/components/slide-in2/slide-in2.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CdkTrapFocus } from '@angular/cdk/a11y';
import {
ChangeDetectionStrategy, ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
HostListener,
Injector,
Expand All @@ -14,8 +15,13 @@ import {
ViewContainerRef,
} from '@angular/core';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { TranslateService } from '@ngx-translate/core';
import { cloneDeep } from 'lodash-es';
import { Subscription, timer } from 'rxjs';
import {
filter, Observable, of, Subscription, switchMap, timer,
} from 'rxjs';
import { SlideIn2CloseConfirmation } from 'app/interfaces/slide-in-close-confirmation.interface';
import { DialogService } from 'app/modules/dialog/dialog.service';
import { ChainedRef } from 'app/modules/slide-ins/chained-component-ref';
import {
ChainedComponentResponse,
Expand All @@ -37,6 +43,7 @@ export class SlideIn2Component implements OnInit, OnDestroy {
@Input() index: number;
@Input() lastIndex: number;
@ViewChild('chainedBody', { static: true, read: ViewContainerRef }) slideInBody: ViewContainerRef;
componentRef: ComponentRef<unknown>;

@HostListener('document:keydown.escape') onKeydownHandler(): void {
this.onBackdropClicked();
Expand All @@ -57,45 +64,42 @@ export class SlideIn2Component implements OnInit, OnDestroy {
private renderer: Renderer2,
private chainedSlideInService: ChainedSlideInService,
private cdr: ChangeDetectorRef,
private dialogService: DialogService,
private translate: TranslateService,
) {
this.element = this.el.nativeElement as HTMLElement;
}

ngOnInit(): void {
// ensure id attribute exists
if (!this.componentInfo.id) {
return;
}

// move element to bottom of page (just before </body>) so it can be displayed above everything else
document.body.appendChild(this.element);
if (this.componentInfo.component) {
this.openSlideIn(this.componentInfo.component, {
wide: this.componentInfo.wide, data: this.componentInfo.data,
});
}
this.chainedSlideInService.isTopComponentWide$.pipe(
untilDestroyed(this),
).subscribe((wide) => {
this.wide = wide;
private showConfirmDialog(): Observable<boolean> {
return this.dialogService.confirm({
title: this.translate.instant('Unsaved Changes'),
message: this.translate.instant('You have unsaved changes. Are you sure you want to close?'),
cancelText: this.translate.instant('No'),
buttonText: this.translate.instant('Yes'),
buttonColor: 'red',
hideCheckbox: true,
});
}

ngOnDestroy(): void {
this.chainedSlideInService.popComponent(this.componentInfo.id);
this.element.remove();
}

onBackdropClicked(): void {
if (!this.element || !this.isSlideInOpen) {
return;
private getConfirmation(): Observable<boolean> {
let shouldConfirm$: Observable<boolean>;
// TODO: Ideally, all forms should be of type `ShouldConfirmBeforeClosing`. Until they are not
// this preventative logic is needed
try {
shouldConfirm$ = (this.componentRef.instance as SlideIn2CloseConfirmation).requiresConfirmationOnClose();
if (!shouldConfirm$) {
shouldConfirm$ = of(false);
}
} catch {
console.error('Confirmation before closing form not defined');
shouldConfirm$ = of(false);
}
this.componentInfo.close$.next({ response: false, error: null });
this.componentInfo.close$.complete();
this.closeSlideIn();
return shouldConfirm$.pipe(
switchMap((shouldConfirm) => (shouldConfirm ? this.showConfirmDialog() : of(true))),
);
}

closeSlideIn(): void {
private closeSlideIn(): void {
this.isSlideInOpen = false;
this.renderer.removeStyle(document.body, 'overflow');
this.wasBodyCleared = true;
Expand All @@ -113,8 +117,8 @@ export class SlideIn2Component implements OnInit, OnDestroy {
});
}

openSlideIn<T, D>(
componentType: Type<T>,
private openSlideIn<T, D>(
componentType: Type<unknown>,
params?: { wide?: boolean; data?: D },
): void {
if (this.isSlideInOpen) {
Expand All @@ -139,7 +143,7 @@ export class SlideIn2Component implements OnInit, OnDestroy {
}

private createInjector<T, D>(
componentType: Type<T>,
componentType: Type<unknown>,
data?: D,
): void {
const injector = Injector.create({
Expand All @@ -148,18 +152,32 @@ export class SlideIn2Component implements OnInit, OnDestroy {
provide: ChainedRef<D>,
useValue: {
close: (response: ChainedComponentResponse) => {
this.componentInfo.close$.next(response);
this.componentInfo.close$.complete();
this.closeSlideIn();
this.getConfirmation().pipe(
filter(Boolean),
untilDestroyed(this),
).subscribe({
next: () => {
this.componentInfo.close$.next(response);
this.componentInfo.close$.complete();
this.closeSlideIn();
},
});
},
swap: (component: Type<unknown>, wide = false, incomingComponentData?: unknown) => {
this.chainedSlideInService.swapComponent({
swapComponentId: this.componentInfo.id,
component,
wide,
data: incomingComponentData,
this.getConfirmation().pipe(
filter(Boolean),
untilDestroyed(this),
).subscribe({
next: () => {
this.chainedSlideInService.swapComponent({
swapComponentId: this.componentInfo.id,
component,
wide,
data: incomingComponentData,
});
this.closeSlideIn();
},
});
this.closeSlideIn();
},
getData: (): D => {
return cloneDeep(data);
Expand All @@ -168,6 +186,47 @@ export class SlideIn2Component implements OnInit, OnDestroy {
},
],
});
this.slideInBody.createComponent<T>(componentType, { injector });
this.componentRef = this.slideInBody.createComponent<T>(componentType as Type<T>, { injector });
}

protected onBackdropClicked(): void {
if (!this.element || !this.isSlideInOpen) {
return;
}
this.getConfirmation().pipe(
filter(Boolean),
untilDestroyed(this),
).subscribe({
next: () => {
this.componentInfo.close$.next({ response: false, error: null });
this.componentInfo.close$.complete();
this.closeSlideIn();
},
});
}

ngOnInit(): void {
// ensure id attribute exists
if (!this.componentInfo.id) {
return;
}

// move element to bottom of page (just before </body>) so it can be displayed above everything else
document.body.appendChild(this.element);
if (this.componentInfo.component) {
this.openSlideIn(this.componentInfo.component, {
wide: this.componentInfo.wide, data: this.componentInfo.data,
});
}
this.chainedSlideInService.isTopComponentWide$.pipe(
untilDestroyed(this),
).subscribe((wide) => {
this.wide = wide;
});
}

ngOnDestroy(): void {
this.chainedSlideInService.popComponent(this.componentInfo.id);
this.element.remove();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import { MatButton } from '@angular/material/button';
import { MatCard, MatCardContent } from '@angular/material/card';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { TranslateService, TranslateModule } from '@ngx-translate/core';
import { combineLatest, of } from 'rxjs';
import {
combineLatest, Observable, of,
} from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { RequiresRolesDirective } from 'app/directives/requires-roles/requires-roles.directive';
import { CloudSyncProviderName } from 'app/enums/cloudsync-provider.enum';
Expand All @@ -20,6 +22,7 @@ import { helptextSystemCloudcredentials as helptext } from 'app/helptext/system/
import { CloudSyncCredential, CloudSyncCredentialUpdate } from 'app/interfaces/cloudsync-credential.interface';
import { CloudSyncProvider } from 'app/interfaces/cloudsync-provider.interface';
import { Option } from 'app/interfaces/option.interface';
import { SlideIn2CloseConfirmation } from 'app/interfaces/slide-in-close-confirmation.interface';
import { DialogService } from 'app/modules/dialog/dialog.service';
import { FormActionsComponent } from 'app/modules/forms/ix-forms/components/form-actions/form-actions.component';
import { IxFieldsetComponent } from 'app/modules/forms/ix-forms/components/ix-fieldset/ix-fieldset.component';
Expand Down Expand Up @@ -68,7 +71,7 @@ export interface CloudCredentialFormInput {
TranslateModule,
],
})
export class CloudCredentialsFormComponent implements OnInit {
export class CloudCredentialsFormComponent implements OnInit, SlideIn2CloseConfirmation {
protected readonly requiredRoles = [Role.CloudSyncWrite];

commonForm = this.formBuilder.group({
Expand Down Expand Up @@ -108,6 +111,10 @@ export class CloudCredentialsFormComponent implements OnInit {
this.setFormEvents();
}

requiresConfirmationOnClose(): Observable<boolean> {
return of(this.providerForm.form.dirty || this.commonForm.dirty);
}

get showProviderDescription(): boolean {
return this.commonForm.controls.provider.enabled
&& this.commonForm.controls.provider.value === CloudSyncProviderName.Storj;
Expand Down
Loading
Loading