Debian Codegraph @

src/actions/copy.js

raw
1 import select from 'select';
2 import command from '../common/command';
3 import createFakeElement from '../common/create-fake-element';
4
5 /**
6 * Create fake copy action wrapper using a fake element.
7 * @param {String} target
8 * @param {Object} options
9 * @return {String}
10 */
11 const fakeCopyAction = (value, options) => {
12 const fakeElement = createFakeElement(value);
13 options.container.appendChild(fakeElement);
14 const selectedText = select(fakeElement);
15 command('copy');
16 fakeElement.remove();
17
18 return selectedText;
19 };
20
21 /**
22 * Copy action wrapper.
23 * @param {String|HTMLElement} target
24 * @param {Object} options
25 * @return {String}
26 */
27 const ClipboardActionCopy = (
28 target,
29 options = { container: document.body }
30 ) => {
31 let selectedText = '';
32 if (typeof target === 'string') {
33 selectedText = fakeCopyAction(target, options);
34 } else if (
35 target instanceof HTMLInputElement &&
36 !['text', 'search', 'url', 'tel', 'password'].includes(target?.type)
37 ) {
38 // If input type doesn't support `setSelectionRange`. Simulate it. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
39 selectedText = fakeCopyAction(target.value, options);
40 } else {
41 selectedText = select(target);
42 command('copy');
43 }
44 return selectedText;
45 };
46
47 export default ClipboardActionCopy;