]>
Commit | Line | Data |
---|---|---|
11fdf7f2 | 1 | import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core'; |
e306af50 | 2 | import { I18n } from '@ngx-translate/i18n-polyfill'; |
11fdf7f2 | 3 | |
f91f0fd5 | 4 | import { detect } from 'detect-browser'; |
494da23a | 5 | import { ToastrService } from 'ngx-toastr'; |
11fdf7f2 TL |
6 | |
7 | @Directive({ | |
8 | selector: '[cdCopy2ClipboardButton]' | |
9 | }) | |
10 | export class Copy2ClipboardButtonDirective implements OnInit { | |
11 | @Input() | |
12 | private cdCopy2ClipboardButton: string; | |
13 | ||
14 | constructor( | |
15 | private elementRef: ElementRef, | |
16 | private renderer: Renderer2, | |
e306af50 TL |
17 | private toastr: ToastrService, |
18 | private i18n: I18n | |
11fdf7f2 TL |
19 | ) {} |
20 | ||
21 | ngOnInit() { | |
22 | const iElement = this.renderer.createElement('i'); | |
11fdf7f2 TL |
23 | this.renderer.addClass(iElement, 'fa'); |
24 | this.renderer.addClass(iElement, 'fa-clipboard'); | |
e306af50 | 25 | this.renderer.setAttribute(iElement, 'title', this.i18n('Copy to clipboard')); |
11fdf7f2 TL |
26 | this.renderer.appendChild(this.elementRef.nativeElement, iElement); |
27 | } | |
28 | ||
f91f0fd5 TL |
29 | private getText(): string { |
30 | const element = document.getElementById(this.cdCopy2ClipboardButton) as HTMLInputElement; | |
31 | return element.value; | |
11fdf7f2 TL |
32 | } |
33 | ||
34 | @HostListener('click') | |
35 | onClick() { | |
36 | try { | |
f91f0fd5 TL |
37 | const browser = detect(); |
38 | const text = this.getText(); | |
39 | const toastrFn = () => { | |
40 | this.toastr.success('Copied text to the clipboard successfully.'); | |
41 | }; | |
42 | if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) { | |
43 | // Various browsers do not support the `Permissions API`. | |
44 | // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility | |
45 | navigator.clipboard.writeText(text).then(() => toastrFn()); | |
46 | } else { | |
47 | // Checking if we have the clipboard-write permission | |
48 | navigator.permissions | |
49 | .query({ name: 'clipboard-write' as PermissionName }) | |
50 | .then((result: any) => { | |
51 | if (result.state === 'granted' || result.state === 'prompt') { | |
52 | navigator.clipboard.writeText(text).then(() => toastrFn()); | |
53 | } | |
54 | }); | |
55 | } | |
56 | } catch (_) { | |
11fdf7f2 TL |
57 | this.toastr.error('Failed to copy text to the clipboard.'); |
58 | } | |
59 | } | |
60 | } |