jpuri / react-draft-wysiwyg

A Wysiwyg editor build on top of ReactJS and DraftJS. https://jpuri.github.io/react-draft-wysiwyg
MIT License
6.38k stars 1.15k forks source link

Copying the formatted text #1356

Open Lvschaitanya opened 1 year ago

Lvschaitanya commented 1 year ago

Hi, Is there any way to copy all the text to the clipboard from the text editor along with all the styles. Currently, there is only editorState.getCurrentContent().getPlaintext() to get the plain text.

ZaharBerku commented 11 months ago

@Lvschaitanya if you want to save the text with formatting, then the problem is not in the library, but in the way you save, I assume you saved like this

const value = editorState.getCurrentContent().getPlaintext()
navigator.clipboard.writeText(value);

I did that at first too, but it's not correct. And then I decided to dig into the methods of navigator.clipboard and yes there is a method that is created for this write (navigator.clipboard.write()) here is my version of the code that works for me -

import { EditorState } from "react-draft-wysiwyg";
import { stateToHTML } from "draft-js-export-html";

const [clipboardItemData, setClipboardItemData] = useState<any>();
const copyFormattedText = () => {
    navigator.clipboard
      .write([clipboardItemData])
      .then(() => {
        console.log("Formatted text copied successfully!");
      })
      .catch((error) => {
        console.error("Unable to copy formatted text: ", error);
      });
  }

  const handleChangeEditor = async (
    state: EditorState
  ) => {
    const value = state.getCurrentContent().getPlainText();
    const valueHTML = stateToHTML(state.getCurrentContent());
    const data = new ClipboardItem({
      "text/plain": new Blob([value], { type: "text/plain" }),
      "text/html": new Blob([valueHTML], { type: "text/html" }),
    });
    setClipboardItemData(data);
  };

call the "copyFormattedText" function when you click on the "Copy" button

ZaharBerku commented 11 months ago

I think if you dig a little more in the library, this option can be improved