]>
Commit | Line | Data |
---|---|---|
f67539c2 | 1 | import { Component, HostListener, Input } from '@angular/core'; |
11fdf7f2 | 2 | |
f91f0fd5 | 3 | import { detect } from 'detect-browser'; |
494da23a | 4 | import { ToastrService } from 'ngx-toastr'; |
11fdf7f2 | 5 | |
f67539c2 TL |
6 | import { Icons } from '~/app/shared/enum/icons.enum'; |
7 | ||
8 | @Component({ | |
9 | selector: 'cd-copy-2-clipboard-button', | |
10 | templateUrl: './copy2clipboard-button.component.html', | |
11 | styleUrls: ['./copy2clipboard-button.component.scss'] | |
11fdf7f2 | 12 | }) |
f67539c2 | 13 | export class Copy2ClipboardButtonComponent { |
11fdf7f2 | 14 | @Input() |
f67539c2 TL |
15 | private source: string; |
16 | ||
17 | @Input() | |
18 | byId = true; | |
19 | ||
20 | icons = Icons; | |
21 | ||
22 | constructor(private toastr: ToastrService) {} | |
11fdf7f2 | 23 | |
f91f0fd5 | 24 | private getText(): string { |
f67539c2 | 25 | const element = document.getElementById(this.source) as HTMLInputElement; |
f91f0fd5 | 26 | return element.value; |
11fdf7f2 TL |
27 | } |
28 | ||
29 | @HostListener('click') | |
30 | onClick() { | |
31 | try { | |
f91f0fd5 | 32 | const browser = detect(); |
f67539c2 | 33 | const text = this.byId ? this.getText() : this.source; |
f91f0fd5 TL |
34 | const toastrFn = () => { |
35 | this.toastr.success('Copied text to the clipboard successfully.'); | |
36 | }; | |
37 | if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) { | |
38 | // Various browsers do not support the `Permissions API`. | |
39 | // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility | |
40 | navigator.clipboard.writeText(text).then(() => toastrFn()); | |
41 | } else { | |
42 | // Checking if we have the clipboard-write permission | |
43 | navigator.permissions | |
44 | .query({ name: 'clipboard-write' as PermissionName }) | |
45 | .then((result: any) => { | |
46 | if (result.state === 'granted' || result.state === 'prompt') { | |
47 | navigator.clipboard.writeText(text).then(() => toastrFn()); | |
48 | } | |
49 | }); | |
50 | } | |
51 | } catch (_) { | |
11fdf7f2 TL |
52 | this.toastr.error('Failed to copy text to the clipboard.'); |
53 | } | |
54 | } | |
55 | } |