Debian Codegraph @

src/actions/default.js

raw
1 import ClipboardActionCut from './cut';
2 import ClipboardActionCopy from './copy';
3
4 /**
5 * Inner function which performs selection from either `text` or `target`
6 * properties and then executes copy or cut operations.
7 * @param {Object} options
8 */
9 const ClipboardActionDefault = (options = {}) => {
10 // Defines base properties passed from constructor.
11 const { action = 'copy', container, target, text } = options;
12
13 // Sets the `action` to be performed which can be either 'copy' or 'cut'.
14 if (action !== 'copy' && action !== 'cut') {
15 throw new Error('Invalid "action" value, use either "copy" or "cut"');
16 }
17
18 // Sets the `target` property using an element that will be have its content copied.
19 if (target !== undefined) {
20 if (target && typeof target === 'object' && target.nodeType === 1) {
21 if (action === 'copy' && target.hasAttribute('disabled')) {
22 throw new Error(
23 'Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'
24 );
25 }
26
27 if (
28 action === 'cut' &&
29 (target.hasAttribute('readonly') || target.hasAttribute('disabled'))
30 ) {
31 throw new Error(
32 'Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'
33 );
34 }
35 } else {
36 throw new Error('Invalid "target" value, use a valid Element');
37 }
38 }
39
40 // Define selection strategy based on `text` property.
41 if (text) {
42 return ClipboardActionCopy(text, { container });
43 }
44
45 // Defines which selection strategy based on `target` property.
46 if (target) {
47 return action === 'cut'
48 ? ClipboardActionCut(target)
49 : ClipboardActionCopy(target, { container });
50 }
51 };
52
53 export default ClipboardActionDefault;