82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import {
|
||
Directive,
|
||
ElementRef,
|
||
HostListener,
|
||
OnInit,
|
||
Renderer2,
|
||
} from '@angular/core';
|
||
|
||
import { MessageService } from 'primeng/api';
|
||
import { getTypeDevice, pwaInstalled } from 'src/app/utils';
|
||
|
||
@Directive({
|
||
selector: '[appDownloadApp]',
|
||
})
|
||
export class DownloadAppDirective implements OnInit {
|
||
public deviceType: 'ios' | 'android' | null = null;
|
||
public deferredPrompt: any;
|
||
|
||
constructor(
|
||
private messageService: MessageService,
|
||
public renderer: Renderer2,
|
||
private el: ElementRef,
|
||
) { }
|
||
|
||
ngOnInit(): void {
|
||
getTypeDevice();
|
||
if (this.deviceType === 'ios') {
|
||
this.el.nativeElement.style.display = 'block';
|
||
}
|
||
this.checkInstalled();
|
||
}
|
||
|
||
async checkInstalled(): Promise<void> {
|
||
if (window.matchMedia('(display-mode: standalone)').matches
|
||
|| await pwaInstalled()) {
|
||
this.el.nativeElement.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
@HostListener('window:beforeinstallprompt', ['$event'])
|
||
onBeforeInstallPrompt(e: any) {
|
||
e.preventDefault();
|
||
this.deferredPrompt = e;
|
||
if (this.deferredPrompt) {
|
||
this.el.nativeElement.style.display = 'block';
|
||
}
|
||
}
|
||
|
||
@HostListener('window:appinstalled', ['$event'])
|
||
onAppInstalled(e: any) {
|
||
// Prevent Chrome 67 and earlier from automatically showing the prompt
|
||
e.preventDefault();
|
||
// Stash the event so it can be triggered later.
|
||
this.deferredPrompt = e;
|
||
this.el.nativeElement.style.display = 'none';
|
||
}
|
||
|
||
@HostListener('click', ['$event'])
|
||
async downloadApp(event: MouseEvent) {
|
||
if (!this.deferredPrompt) {
|
||
this.messageService.clear();
|
||
this.messageService.add({
|
||
severity: 'error',
|
||
summary: 'Не поддерживается в Вашем браузере!',
|
||
});
|
||
return;
|
||
}
|
||
this.deferredPrompt.prompt();
|
||
this.deferredPrompt.userChoice.then((res: any) => {
|
||
if (res.outcome === 'accepted') {
|
||
this.messageService.clear();
|
||
this.messageService.add({
|
||
severity: 'success',
|
||
summary: 'Спасибо за установку!',
|
||
});
|
||
}
|
||
this.deferredPrompt = null;
|
||
});
|
||
}
|
||
|
||
}
|