summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/components/copy2clipboard-button/copy2clipboard-button.component.ts
blob: 2cc656bfccbe48e2703a1c6df3f3e72793806c89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Component, HostListener, Input } from '@angular/core';

import { detect } from 'detect-browser';
import { ToastrService } from 'ngx-toastr';

import { Icons } from '~/app/shared/enum/icons.enum';

@Component({
  selector: 'cd-copy-2-clipboard-button',
  templateUrl: './copy2clipboard-button.component.html',
  styleUrls: ['./copy2clipboard-button.component.scss']
})
export class Copy2ClipboardButtonComponent {
  @Input()
  private source: string;

  @Input()
  byId = true;

  icons = Icons;

  constructor(private toastr: ToastrService) {}

  private getText(): string {
    const element = document.getElementById(this.source) as HTMLInputElement;
    return element.value;
  }

  @HostListener('click')
  onClick() {
    try {
      const browser = detect();
      const text = this.byId ? this.getText() : this.source;
      const toastrFn = () => {
        this.toastr.success('Copied text to the clipboard successfully.');
      };
      if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) {
        // Various browsers do not support the `Permissions API`.
        // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility
        navigator.clipboard.writeText(text).then(() => toastrFn());
      } else {
        // Checking if we have the clipboard-write permission
        navigator.permissions
          .query({ name: 'clipboard-write' as PermissionName })
          .then((result: any) => {
            if (result.state === 'granted' || result.state === 'prompt') {
              navigator.clipboard.writeText(text).then(() => toastrFn());
            }
          });
      }
    } catch (_) {
      this.toastr.error('Failed to copy text to the clipboard.');
    }
  }
}