Files
mempool/frontend/src/app/components/clipboard/clipboard.component.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-clipboard',
templateUrl: './clipboard.component.html',
2020-08-09 10:39:27 +07:00
styleUrls: ['./clipboard.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ClipboardComponent {
2022-09-19 18:21:31 +02:00
@Input() button = false;
@Input() class = 'btn btn-secondary ml-1';
@Input() size: 'small' | 'normal' | 'large' = 'normal';
@Input() text: string;
2022-08-29 19:02:22 +02:00
@Input() leftPadding = true;
2020-12-03 18:34:19 +07:00
copiedMessage: string = $localize`:@@clipboard.copied-message:Copied!`;
showMessage = false;
widths = {
small: '10',
normal: '13',
large: '18',
};
constructor(
private cd: ChangeDetectorRef,
) { }
async copyText() {
if (this.text && !this.showMessage) {
try {
await this.copyToClipboard(this.text);
this.showMessage = true;
this.cd.markForCheck();
setTimeout(() => {
this.showMessage = false;
this.cd.markForCheck();
}, 1000);
} catch (error) {
console.error('Clipboard copy failed:', error);
}
}
}
async copyToClipboard(text: string) {
if (navigator.clipboard) {
await navigator.clipboard.writeText(text);
} else {
// Use the 'out of viewport hidden text area' trick on non-secure contexts
const textarea = document.createElement('textarea');
textarea.value = this.text;
textarea.style.opacity = '0';
textarea.setAttribute('readonly', 'true'); // Don't trigger keyboard on mobile
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
}
}
}