azure-devops-ui
Version:
React components for building web UI in Azure DevOps
54 lines (53 loc) • 2.04 kB
JavaScript
import * as React from "react";
import * as ReactDOM from "react-dom";
/**
* Copies the specified data to the clipboard in the TEXT format.
*
* @param data The data to copy.
* @param onCopy Callback after a copy is completed
*/
export function copyToClipboard(data, onCopy) {
if (data instanceof HTMLElement) {
copy(data, onCopy);
}
else {
const copyRoot = document.createElement("div");
// Make sure our element doesn't actually become visible to the user.
copyRoot.classList.add("visually-hidden");
copyRoot.setAttribute("aria-hidden", "true");
copyRoot.setAttribute("role", "presentation");
copyRoot.setAttribute("style", "{color: inherit; background-color: inherit;}");
document.body.appendChild(copyRoot);
// Render the contents to the new root node, once the component is mounted
// call the copy method,
const copyDiv = React.createElement("div", {
ref: (element) => {
if (element) {
// Execute the copy of the data from the mounted element
copy(element, onCopy);
// Unmount the element and ensure React is cleaned up after the ref call completes.
window.setTimeout(() => {
ReactDOM.unmountComponentAtNode(copyRoot);
document.body.removeChild(copyRoot);
}, 0);
}
},
style: {
whiteSpace: "pre",
color: "inherit",
backgroundColor: "inherit"
}
}, data);
ReactDOM.render(copyDiv, copyRoot);
}
}
function copy(element, onCopy) {
const range = document.createRange();
const sel = window.getSelection();
sel.removeAllRanges();
range.selectNodeContents(element);
sel.addRange(range);
document.execCommand("copy");
sel.removeAllRanges();
onCopy && onCopy();
}