Skip to content

Commit

Permalink
Add onCopy handler to Message component to prevent HTML from bein…
Browse files Browse the repository at this point in the history
…g copied to the clipboard (#182)
  • Loading branch information
andrewnguonly authored May 27, 2024
1 parent 6b1f799 commit 63ed516
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/components/ChatBar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { ChangeEvent, useEffect, useRef, useState } from "react";
import {
ChangeEvent,
ClipboardEvent,
useEffect,
useRef,
useState,
} from "react";

import {
Avatar,
Expand Down Expand Up @@ -440,7 +446,9 @@ const ChatBar: React.FC = () => {
case "c":
// copy last message
if (messages.length === 0) return;
navigator.clipboard.writeText(messages[messages.length - 1].message);
navigator.clipboard.writeText(
messages[messages.length - 1].message.trim(),
);
setShowSnackbar(true);
setSnackbarMessage("Copied!");
break;
Expand Down Expand Up @@ -474,6 +482,20 @@ const ChatBar: React.FC = () => {
}
};

/**
* This function is needed to prevent HTML elements (e.g. background color)
* from being copied to the clipboard. Only plain text should be copied to
* the clipboard.
*/
const handleMessageOnCopy = (event: ClipboardEvent<HTMLDivElement>) => {
event.preventDefault();

const selectedText = window.getSelection()?.toString() || "";
if (selectedText !== "") {
navigator.clipboard.writeText(selectedText);
}
};

const appendNonUserMessage = (
currentMessages: LumosMessage[],
sender: string,
Expand Down Expand Up @@ -685,6 +707,7 @@ const ChatBar: React.FC = () => {
}}
type="custom"
style={messageStyle}
onCopy={handleMessageOnCopy}
>
<Avatar
src={
Expand Down

0 comments on commit 63ed516

Please sign in to comment.