1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-10-19 07:35:48 +02:00
bitwarden-browser/src/angular/components/modal.component.ts

79 lines
2.6 KiB
TypeScript
Raw Normal View History

2018-04-25 05:22:21 +02:00
import {
Component,
ComponentFactoryResolver,
EventEmitter,
OnDestroy,
Output,
Type,
ViewChild,
ViewContainerRef,
} from '@angular/core';
2019-04-02 15:02:08 +02:00
import { MessagingService } from '../../abstractions/messaging.service';
2018-04-25 05:22:21 +02:00
@Component({
selector: 'app-modal',
template: `<ng-template #container></ng-template>`,
})
export class ModalComponent implements OnDestroy {
@Output() onClose = new EventEmitter();
@Output() onClosed = new EventEmitter();
@Output() onShow = new EventEmitter();
@Output() onShown = new EventEmitter();
@ViewChild('container', { read: ViewContainerRef, static: true }) container: ViewContainerRef;
2018-04-25 05:22:21 +02:00
parentContainer: ViewContainerRef = null;
fade: boolean = true;
2019-04-02 15:02:08 +02:00
constructor(protected componentFactoryResolver: ComponentFactoryResolver,
protected messagingService: MessagingService) { }
2018-04-25 05:22:21 +02:00
ngOnDestroy() {
document.body.classList.remove('modal-open');
document.body.removeChild(document.querySelector('.modal-backdrop'));
}
2019-07-25 18:22:22 +02:00
show<T>(type: Type<T>, parentContainer: ViewContainerRef, fade: boolean = true,
setComponentParameters: (component: T) => void = null): T {
2018-04-25 05:22:21 +02:00
this.onShow.emit();
2019-04-02 15:02:08 +02:00
this.messagingService.send('modalShow');
2018-04-25 05:22:21 +02:00
this.parentContainer = parentContainer;
this.fade = fade;
document.body.classList.add('modal-open');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop' + (this.fade ? ' fade' : '');
document.body.appendChild(backdrop);
const factory = this.componentFactoryResolver.resolveComponentFactory<T>(type);
const componentRef = this.container.createComponent<T>(factory);
2019-07-25 18:22:22 +02:00
if (setComponentParameters != null) {
setComponentParameters(componentRef.instance);
}
2018-04-25 05:22:21 +02:00
document.querySelector('.modal-dialog').addEventListener('click', (e: Event) => {
e.stopPropagation();
});
2018-06-06 23:26:58 +02:00
const modals = Array.from(document.querySelectorAll('.modal, .modal *[data-dismiss="modal"]'));
for (const closeElement of modals) {
closeElement.addEventListener('click', event => {
2018-04-25 05:22:21 +02:00
this.close();
});
}
this.onShown.emit();
2019-04-02 15:02:08 +02:00
this.messagingService.send('modalShown');
2018-04-25 05:22:21 +02:00
return componentRef.instance;
}
close() {
this.onClose.emit();
2019-04-02 15:02:08 +02:00
this.messagingService.send('modalClose');
2018-04-25 05:22:21 +02:00
this.onClosed.emit();
2019-04-02 15:02:08 +02:00
this.messagingService.send('modalClosed');
2018-04-25 05:22:21 +02:00
if (this.parentContainer != null) {
this.parentContainer.clear();
}
}
}