We are using new clipboard API to implement the browser/operating system wide copy paste.
We have a set of components (Assume it like a flow charts which have connected div) and that is build from a simple json.
Our goal is to implement Copy and paste. We have a underlying JsON in hand, i tried to save the Json file in clipboard.
Now the real problem starts:
1: Copy and Paste is operating system wide, so how can i know that, currently copied element is json and that is what we needed to build the flow. Eg: a user can copy whatever they want, but i only want the data which my system can parse.
2: How generally these type of applications works, for example, on Slack, i copied a formatted markdown message into my clipboard and i pasted the same into a text editor, but i don't see any markdown command on the selected text, but somehow i pasted the same thing in slack, i got the same message which i copied earlier.
Is anyone have done Copy/Paste of components, Any help highly appreciated.
Here's a basic example for how to do clipboard manipulation. Read up on paste and copy events for more detailed info. You could also try to set a different content-type for the clipboard data. This is probably how Slack does it: Set one clipboard entry in plain text (without markdown formatting) and one in Markdown.
const input = document.getElementById("testInput");
input.addEventListener("copy", (e) => {
console.log("copied!");
e.clipboardData.setData('text/plain', JSON.stringify({
test: "value"
}));
e.preventDefault();
});
input.addEventListener("paste", (e) => {
console.log("pasted!");
//console.log(e);
if (e.clipboardData.types[0] == "text/plain") {
const txt = e.clipboardData.getData('text')
try {
const json = JSON.parse(txt);
// TODO: validate that object has correct keys
console.log(json);
e.preventDefault();
// I added prevent default, since you probably want to have your own logic for rendering the clipboard content
} catch (e) {
console.error("text is not JSON parseable: " + txt);
}
}
});
<input id="testInput"></input>