]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/blob
2b82b76f5a512cb9de784507b5182e5dbf5af22d
[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   // The text to be copied
15   @Input()
16   private source: string;
17
18   // Optional: Extracts text to be copied by "id" attribute
19   @Input()
20   byId = true;
21
22   // Size of the button
23   @Input()
24   size = 'md';
25
26   // Optional: Adds text to the left of copy icon
27   @Input()
28   text?: string;
29
30   icons = Icons;
31
32   constructor(private toastr: ToastrService) {}
33
34   private getText(): string {
35     const element = document.getElementById(this.source) as HTMLInputElement;
36     return element?.value || element?.textContent;
37   }
38
39   @HostListener('click')
40   onClick() {
41     try {
42       const browser = detect();
43       const text = this.byId ? this.getText() : this.source;
44       const toastrFn = () => {
45         this.toastr.success('Copied text to the clipboard successfully.');
46       };
47       if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) {
48         // Various browsers do not support the `Permissions API`.
49         // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility
50         navigator.clipboard.writeText(text).then(() => toastrFn());
51       } else {
52         // Checking if we have the clipboard-write permission
53         navigator.permissions
54           .query({ name: 'clipboard-write' as PermissionName })
55           .then((result: any) => {
56             if (result.state === 'granted' || result.state === 'prompt') {
57               navigator.clipboard.writeText(text).then(() => toastrFn());
58             }
59           });
60       }
61     } catch (_) {
62       this.toastr.error('Failed to copy text to the clipboard.');
63     }
64   }
65 }