-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathclipboard.js
292 lines (266 loc) · 9.3 KB
/
clipboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';
import { AlignAttribute, AlignStyle } from '../formats/align';
import { BackgroundStyle } from '../formats/background';
import { ColorStyle } from '../formats/color';
import { DirectionAttribute, DirectionStyle } from '../formats/direction';
import { FontStyle } from '../formats/font';
import { SizeStyle } from '../formats/size';
let debug = logger('quill:clipboard');
const CLIPBOARD_CONFIG = [
[Node.TEXT_NODE, matchText],
['br', matchBreak],
[Node.ELEMENT_NODE, matchNewline],
[Node.ELEMENT_NODE, matchBlot],
[Node.ELEMENT_NODE, matchSpacing],
[Node.ELEMENT_NODE, matchAttributor],
[Node.ELEMENT_NODE, matchStyles],
['b', matchAlias.bind(matchAlias, 'bold')],
['i', matchAlias.bind(matchAlias, 'italic')],
['style', matchIgnore]
];
const ATTRIBUTE_ATTRIBUTORS = [
AlignAttribute,
DirectionAttribute
].reduce(function(memo, attr) {
memo[attr.keyName] = attr;
return memo;
}, {});
const STYLE_ATTRIBUTORS = [
AlignStyle,
BackgroundStyle,
ColorStyle,
DirectionStyle,
FontStyle,
SizeStyle
].reduce(function(memo, attr) {
memo[attr.keyName] = attr;
return memo;
}, {});
class Clipboard extends Module {
constructor(quill, options) {
super(quill, options);
this.quill.root.addEventListener('paste', this.onPaste.bind(this));
this.container = this.quill.addContainer('ql-clipboard');
this.container.setAttribute('contenteditable', true);
this.container.setAttribute('tabindex', -1);
this.matchers = [];
CLIPBOARD_CONFIG.concat(this.options.matchers).forEach((pair) => {
this.addMatcher(...pair);
});
}
addMatcher(selector, matcher) {
this.matchers.push([selector, matcher]);
}
convert(html) {
const DOM_KEY = '__ql-matcher';
if (typeof html === 'string') {
this.container.innerHTML = html;
}
let textMatchers = [], elementMatchers = [];
this.matchers.forEach((pair) => {
let [selector, matcher] = pair;
switch (selector) {
case Node.TEXT_NODE:
textMatchers.push(matcher);
break;
case Node.ELEMENT_NODE:
elementMatchers.push(matcher);
break;
default:
[].forEach.call(this.container.querySelectorAll(selector), (node) => {
// TODO use weakmap
node[DOM_KEY] = node[DOM_KEY] || [];
node[DOM_KEY].push(matcher);
});
break;
}
});
let traverse = (node) => { // Post-order
if (node.nodeType === node.TEXT_NODE) {
return textMatchers.reduce(function(delta, matcher) {
return matcher(node, delta);
}, new Delta());
} else if (node.nodeType === node.ELEMENT_NODE) {
return [].reduce.call(node.childNodes || [], (delta, childNode) => {
let childrenDelta = traverse(childNode);
if (childNode.nodeType === node.ELEMENT_NODE) {
childrenDelta = elementMatchers.reduce(function(childrenDelta, matcher) {
return matcher(childNode, childrenDelta);
}, childrenDelta);
childrenDelta = (childNode[DOM_KEY] || []).reduce(function(childrenDelta, matcher) {
return matcher(childNode, childrenDelta);
}, childrenDelta);
}
return delta.concat(childrenDelta);
}, new Delta());
} else {
return new Delta();
}
};
let delta = traverse(this.container);
// Remove trailing newline
if (deltaEndsWith(delta, '\n') && delta.ops[delta.ops.length - 1].attributes == null) {
delta = delta.compose(new Delta().retain(delta.length() - 1).delete(1));
}
debug.log('convert', this.container.innerHTML, delta);
this.container.innerHTML = '';
return delta;
}
dangerouslyPasteHTML(index, html, source = Quill.sources.API) {
if (typeof index === 'string') {
return this.quill.setContents(this.convert(index), html);
} else {
let paste = this.convert(html);
return this.quill.updateContents(new Delta().retain(index).concat(paste), source);
}
}
onPaste(e) {
if (e.defaultPrevented) return;
let range = this.quill.getSelection();
let delta = new Delta().retain(range.index).delete(range.length);
let bodyTop = document.body.scrollTop;
this.container.focus();
setTimeout(() => {
this.quill.selection.update(Quill.sources.SILENT);
delta = delta.concat(this.convert());
this.quill.updateContents(delta, Quill.sources.USER);
// range.length contributes to delta.length()
this.quill.setSelection(delta.length() - range.length, Quill.sources.SILENT);
document.body.scrollTop = bodyTop;
this.quill.selection.scrollIntoView();
}, 1);
}
}
Clipboard.DEFAULTS = {
matchers: []
};
function computeStyle(node) {
if (node.nodeType !== Node.ELEMENT_NODE) return {};
const DOM_KEY = '__ql-computed-style';
return node[DOM_KEY] || (node[DOM_KEY] = window.getComputedStyle(node));
}
function deltaEndsWith(delta, text) {
let endText = "";
for (let i = delta.ops.length - 1; i >= 0 && endText.length < text.length; --i) {
let op = delta.ops[i];
if (typeof op.insert !== 'string') break;
endText = op.insert + endText;
}
return endText.slice(-1*text.length) === text;
}
function isLine(node) {
if (node.childNodes.length === 0) return false; // Exclude embed blocks
let style = computeStyle(node);
return ['block', 'list-item'].indexOf(style.display) > -1;
}
function matchAlias(format, node, delta) {
return delta.compose(new Delta().retain(delta.length(), { [format]: true }));
}
function matchAttributor(node, delta) {
let attributes = Parchment.Attributor.Attribute.keys(node);
let classes = Parchment.Attributor.Class.keys(node);
let styles = Parchment.Attributor.Style.keys(node);
let formats = {};
attributes.concat(classes).concat(styles).forEach((name) => {
let attr = Parchment.query(name, Parchment.Scope.ATTRIBUTE);
if (attr != null) {
formats[attr.attrName] = attr.value(node);
if (formats[attr.attrName]) return;
}
if (ATTRIBUTE_ATTRIBUTORS[name] != null) {
attr = ATTRIBUTE_ATTRIBUTORS[name];
formats[attr.attrName] = attr.value(node);
}
if (STYLE_ATTRIBUTORS[name] != null) {
attr = STYLE_ATTRIBUTORS[name];
formats[attr.attrName] = attr.value(node);
}
});
if (Object.keys(formats).length > 0) {
delta = delta.compose(new Delta().retain(delta.length(), formats));
}
return delta;
}
function matchBlot(node, delta) {
let match = Parchment.query(node);
if (match == null) return delta;
if (match.prototype instanceof Parchment.Embed) {
let embed = {};
let value = match.value(node);
if (value != null) {
embed[match.blotName] = value;
delta = new Delta().insert(embed, match.formats(node));
}
} else if (typeof match.formats === 'function') {
let formats = { [match.blotName]: match.formats(node) };
delta = delta.compose(new Delta().retain(delta.length(), formats));
}
return delta;
}
function matchBreak(node, delta) {
if (!deltaEndsWith(delta, '\n')) {
delta.insert('\n');
}
return delta;
}
function matchIgnore(node, delta) {
return new Delta();
}
function matchNewline(node, delta) {
if (isLine(node) && !deltaEndsWith(delta, '\n')) {
delta.insert('\n');
}
return delta;
}
function matchSpacing(node, delta) {
if (isLine(node) && node.nextElementSibling != null && !deltaEndsWith(delta, '\n\n')) {
let nodeHeight = node.offsetHeight + parseFloat(computeStyle(node).marginTop) + parseFloat(computeStyle(node).marginBottom);
if (node.nextElementSibling.offsetTop > node.offsetTop + nodeHeight*1.5) {
delta.insert('\n');
}
}
return delta;
}
function matchStyles(node, delta) {
let formats = {};
let style = node.style || {};
if (style.fontWeight && computeStyle(node).fontWeight === 'bold') {
formats.bold = true;
}
if (Object.keys(formats).length > 0) {
delta = delta.compose(new Delta().retain(delta.length(), formats));
}
if (parseFloat(style.textIndent || 0) > 0) { // Could be 0.5in
delta = new Delta().insert('\t').concat(delta);
}
return delta;
}
function matchText(node, delta) {
let text = node.data;
// Word represents empty line with <o:p> </o:p>
if (node.parentNode.tagName === 'O:P') {
return delta.insert(text.trim());
}
if (!computeStyle(node.parentNode).whiteSpace.startsWith('pre')) {
function replacer(collapse, match) {
match = match.replace(/[^\u00a0]/g, ''); // \u00a0 is nbsp;
return match.length < 1 && collapse ? ' ' : match;
}
text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
text = text.replace(/\s\s+/g, replacer.bind(replacer, true)); // collapse whitespace
if ((node.previousSibling == null && isLine(node.parentNode)) ||
(node.previousSibling != null && isLine(node.previousSibling))) {
text = text.replace(/^\s+/, replacer.bind(replacer, false));
}
if ((node.nextSibling == null && isLine(node.parentNode)) ||
(node.nextSibling != null && isLine(node.nextSibling))) {
text = text.replace(/\s+$/, replacer.bind(replacer, false));
}
}
return delta.insert(text);
}
export { Clipboard as default, matchAttributor, matchBlot, matchNewline, matchSpacing, matchText };