Skip to content

Commit

Permalink
add fallback for copying to clipboard over http (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
nmfretz authored Aug 15, 2023
1 parent b453471 commit 8916066
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 18 deletions.
31 changes: 23 additions & 8 deletions ui/components/Chat/ChatMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
31 changes: 21 additions & 10 deletions ui/components/Markdown/CodeBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down

0 comments on commit 8916066

Please sign in to comment.