]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
80c7acbf28aeae227a012cd1ede7b5ab90dcadad
[ceph.git] /
1 import { Component, HostListener, Input } from '@angular/core';
2
3 import { detect } from 'detect-browser';
4 import { ToastrService } from 'ngx-toastr';
5
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']
12 })
13 export class Copy2ClipboardButtonComponent {
14   @Input()
15   private source: string;
16
17   @Input()
18   byId = true;
19
20   @Input()
21   showIconOnly = false;
22
23   icons = Icons;
24
25   constructor(private toastr: ToastrService) {}
26
27   private getText(): string {
28     const element = document.getElementById(this.source) as HTMLInputElement;
29     return element.value;
30   }
31
32   @HostListener('click')
33   onClick() {
34     try {
35       const browser = detect();
36       const text = this.byId ? this.getText() : this.source;
37       const toastrFn = () => {
38         this.toastr.success('Copied text to the clipboard successfully.');
39       };
40       if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) {
41         // Various browsers do not support the `Permissions API`.
42         // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility
43         navigator.clipboard.writeText(text).then(() => toastrFn());
44       } else {
45         // Checking if we have the clipboard-write permission
46         navigator.permissions
47           .query({ name: 'clipboard-write' as PermissionName })
48           .then((result: any) => {
49             if (result.state === 'granted' || result.state === 'prompt') {
50               navigator.clipboard.writeText(text).then(() => toastrFn());
51             }
52           });
53       }
54     } catch (_) {
55       this.toastr.error('Failed to copy text to the clipboard.');
56     }
57   }
58 }