UNPKG

jupyterlab-emrys

Version:

A computational environment for Jupyter. Powered by Emrys

58 lines (57 loc) 1.84 kB
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. "use strict"; /** * Copy text to the system clipboard. * * #### Notes * This can only be called in response to a user input event. */ function copyToClipboard(text) { var node = document.body; var handler = function (event) { var data = event.clipboardData || window.clipboardData; data.setData('text', text); event.preventDefault(); node.removeEventListener('copy', handler); }; node.addEventListener('copy', handler); generateClipboardEvent(node); } exports.copyToClipboard = copyToClipboard; /** * Generate a clipboard event on a node. * * @param node - The element on which to generate the event. * * @param type - The type of event to generate: `'copy'` or `'cut'`. * `'paste'` events cannot be programmatically generated. * * #### Notes * This can only be called in response to a user input event. */ function generateClipboardEvent(node, type) { // http://stackoverflow.com/a/5210367 if (type === void 0) { type = 'copy'; } // Identify selected text. var sel = window.getSelection(); // Save the current selection. var savedRanges = []; for (var i = 0, len = sel.rangeCount; i < len; ++i) { savedRanges[i] = sel.getRangeAt(i).cloneRange(); } // Select the node content. var range = document.createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); // Execute the command. document.execCommand(type); // Restore the previous selection. sel = window.getSelection(); sel.removeAllRanges(); for (var i = 0, len = savedRanges.length; i < len; ++i) { sel.addRange(savedRanges[i]); } } exports.generateClipboardEvent = generateClipboardEvent;