|
| 1 | +import {AfterViewInit, Component, OnDestroy, TemplateRef, ViewChild} from '@angular/core'; |
| 2 | +import {MatSnackBar} from '@angular/material/snack-bar'; |
| 3 | + |
| 4 | +const STORAGE_KEY = 'docs-cookies'; |
| 5 | + |
| 6 | +@Component({ |
| 7 | + selector: 'app-cookie-popup', |
| 8 | + templateUrl: './cookie-popup.html', |
| 9 | + styleUrls: ['./cookie-popup.scss'] |
| 10 | +}) |
| 11 | +export class CookiePopup implements AfterViewInit, OnDestroy { |
| 12 | + /** Reference to the content that will be shown in the snack bar. */ |
| 13 | + @ViewChild('content') |
| 14 | + private _content!: TemplateRef<unknown>; |
| 15 | + |
| 16 | + constructor(private _snackBar: MatSnackBar) {} |
| 17 | + |
| 18 | + /** Accepts the cookie disclaimer. */ |
| 19 | + accept() { |
| 20 | + this._snackBar.dismiss(); |
| 21 | + |
| 22 | + try { |
| 23 | + localStorage.setItem(STORAGE_KEY, 'true'); |
| 24 | + } catch {} |
| 25 | + } |
| 26 | + |
| 27 | + ngAfterViewInit() { |
| 28 | + let hasAccepted = false; |
| 29 | + |
| 30 | + // Needs to be in a try/catch, because some browsers will |
| 31 | + // throw when using `localStorage` in private mode. |
| 32 | + try { |
| 33 | + hasAccepted = localStorage.getItem(STORAGE_KEY) === 'true'; |
| 34 | + } catch {} |
| 35 | + |
| 36 | + if (!hasAccepted) { |
| 37 | + this._snackBar.openFromTemplate(this._content, { |
| 38 | + horizontalPosition: 'start', |
| 39 | + verticalPosition: 'bottom', |
| 40 | + // Turn off live announcements for now, because the snack bar wraps all of the |
| 41 | + // content in an `aria-live` element which will announce the buttons as well. |
| 42 | + politeness: 'off' |
| 43 | + }); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + ngOnDestroy() { |
| 48 | + this._snackBar.dismiss(); |
| 49 | + } |
| 50 | +} |
0 commit comments