add fallback for copying to clipboard over http (#1)

This commit is contained in:
Nathan Fretz 2023-08-15 15:42:26 -07:00 committed by GitHub
parent b45347173e
commit 8916066541
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 18 deletions

View File

@ -102,15 +102,30 @@ export const ChatMessage: FC<Props> = memo(({ message, messageIndex, onEdit }) =
};
const copyOnClick = () => {
if (!navigator.clipboard) return;
navigator.clipboard.writeText(message.content).then(() => {
setMessageCopied(true);
setTimeout(() => {
setMessageCopied(false);
}, 2000);
});
// fallback to allow copying to clipboard over http
const copyToClipboardFallback = (text: string) => {
let textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
};
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(message.content);
} else {
copyToClipboardFallback(message.content);
}
setMessageCopied(true);
setTimeout(() => {
setMessageCopied(false);
}, 2000);
};
useEffect(() => {
setMessageContent(message.content);

View File

@ -20,17 +20,28 @@ export const CodeBlock: FC<Props> = memo(({ language, value }) => {
const [isCopied, setIsCopied] = useState<Boolean>(false);
const copyToClipboard = () => {
if (!navigator.clipboard || !navigator.clipboard.writeText) {
return;
// fallback to allow copying to clipboard over http
const copyToClipboardFallback = (text: string) => {
let textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
textArea.remove();
};
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(value);
} else {
copyToClipboardFallback(value);
}
navigator.clipboard.writeText(value).then(() => {
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 2000);
});
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 2000);
};
const downloadAsFile = () => {
const fileExtension = programmingLanguages[language] || '.file';