import { Alert } from "@store/hooks/Alert"
export class CopyToClipboard {
constructor (id, text) {
this.id = id
this.el = document.getElementById(id)
this.text = this.el?.getAttribute('copyOnClickText')
this.clipBoardText = text
if (this.el && this.clipBoardText && !this.text) {
this.copy(this.clipBoardText, this.id)
}
if (this.el && this.text && !this.clipBoardText) {
this.copy(this.text, this.id)
}
}
copy (text, id) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text)
return
}
navigator.clipboard.writeText(text).then(function() {
new Alert({id: id, color: "green", icon: ``, message: "Текст скопирован", delay: 2000})
}, function(err) {
new Alert({id: id, color: "yellow", icon: ``, message: "Ваш браузер не поддерживает копирование", delay: 2000})
console.error('Async: Could not copy text: ', err)
})
}
fallbackCopyTextToClipboard (text, id) {
var textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.top = "-2000px";
textArea.style.left = "-2000px";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
new Alert({id: id, color: "green", icon: ``, message: "Текст скопирован", delay: 2000})
} catch (err) {
new Alert({id: id, color: "yellow", icon: ``, message: "Ваш браузер не поддерживает копирование", delay: 2000})
}
document.body.removeChild(textArea);
}
}