1 | import ClipboardAction from './clipboard-action';
|
2 | import Emitter from 'tiny-emitter';
|
3 | import listen from 'good-listener';
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | class Clipboard extends Emitter {
|
10 | |
11 |
|
12 |
|
13 |
|
14 | constructor(trigger, options) {
|
15 | super();
|
16 |
|
17 | this.resolveOptions(options);
|
18 | this.listenClick(trigger);
|
19 | }
|
20 |
|
21 | |
22 |
|
23 |
|
24 |
|
25 |
|
26 | resolveOptions(options = {}) {
|
27 | this.action = (typeof options.action === 'function') ? options.action : this.defaultAction;
|
28 | this.target = (typeof options.target === 'function') ? options.target : this.defaultTarget;
|
29 | this.text = (typeof options.text === 'function') ? options.text : this.defaultText;
|
30 | this.container = (typeof options.container === 'object') ? options.container : document.body;
|
31 | }
|
32 |
|
33 | |
34 |
|
35 |
|
36 |
|
37 | listenClick(trigger) {
|
38 | this.listener = listen(trigger, 'click', (e) => this.onClick(e));
|
39 | }
|
40 |
|
41 | |
42 |
|
43 |
|
44 |
|
45 | onClick(e) {
|
46 | const trigger = e.delegateTarget || e.currentTarget;
|
47 |
|
48 | if (this.clipboardAction) {
|
49 | this.clipboardAction = null;
|
50 | }
|
51 |
|
52 | this.clipboardAction = new ClipboardAction({
|
53 | action : this.action(trigger),
|
54 | target : this.target(trigger),
|
55 | text : this.text(trigger),
|
56 | container : this.container,
|
57 | trigger : trigger,
|
58 | emitter : this
|
59 | });
|
60 | }
|
61 |
|
62 | |
63 |
|
64 |
|
65 |
|
66 | defaultAction(trigger) {
|
67 | return getAttributeValue('action', trigger);
|
68 | }
|
69 |
|
70 | |
71 |
|
72 |
|
73 |
|
74 | defaultTarget(trigger) {
|
75 | const selector = getAttributeValue('target', trigger);
|
76 |
|
77 | if (selector) {
|
78 | return document.querySelector(selector);
|
79 | }
|
80 | }
|
81 |
|
82 | |
83 |
|
84 |
|
85 |
|
86 |
|
87 | static isSupported(action = ['copy', 'cut']) {
|
88 | const actions = (typeof action === 'string') ? [action] : action;
|
89 | let support = !!document.queryCommandSupported;
|
90 |
|
91 | actions.forEach((action) => {
|
92 | support = support && !!document.queryCommandSupported(action);
|
93 | });
|
94 |
|
95 | return support;
|
96 | }
|
97 |
|
98 | |
99 |
|
100 |
|
101 |
|
102 | defaultText(trigger) {
|
103 | return getAttributeValue('text', trigger);
|
104 | }
|
105 |
|
106 | |
107 |
|
108 |
|
109 | destroy() {
|
110 | this.listener.destroy();
|
111 |
|
112 | if (this.clipboardAction) {
|
113 | this.clipboardAction.destroy();
|
114 | this.clipboardAction = null;
|
115 | }
|
116 | }
|
117 | }
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 | function getAttributeValue(suffix, element) {
|
126 | const attribute = `data-clipboard-${suffix}`;
|
127 |
|
128 | if (!element.hasAttribute(attribute)) {
|
129 | return;
|
130 | }
|
131 |
|
132 | return element.getAttribute(attribute);
|
133 | }
|
134 |
|
135 | module.exports = Clipboard;
|