-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
squireExt.js
341 lines (266 loc) · 10.6 KB
/
squireExt.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* @fileoverview Implements
* @author Sungho Kim(sungho-kim@nhnent.com) FE Development Team/NHN Ent.
*/
import $ from 'jquery';
import util from 'tui-code-snippet';
import Squire from 'squire-rte';
import domUtils from './domUtils';
const FIND_BLOCK_TAGNAME_RX = /\b(H[\d]|LI|P|BLOCKQUOTE|TD)\b/;
const isIElt11 = /Trident\/[456]\./.test(navigator.userAgent);
/**
* Class SquireExt
* @extends {Squire}
*/
class SquireExt extends Squire {
/**
* Creates an instance of SquireExt.
* @augments Squire
* @memberof SquireExt
*/
constructor(...args) {
super(...args);
this._decorateHandlerToCancelable('copy');
this._decorateHandlerToCancelable(isIElt11 ? 'beforecut' : 'cut');
this._decorateHandlerToCancelable(isIElt11 ? 'beforepaste' : 'paste');
this.get$Body = () => {
this.$body = this.$body || $(this.getRoot());
return this.$body;
};
}
/**
* _decorateHandlerToCancelable
* Decorate squire handler to cancelable cuz sometimes, we dont need squire handler process
* event.preventDefault() will cancel squire and browser default behavior
* event.squirePrevented = true will cancel squire but allow browser default behavior
* @param {string} eventName event name
* @private
*/
_decorateHandlerToCancelable(eventName) {
const handlers = this._events[eventName];
if (handlers.length > 1) {
throw new Error(`too many${eventName}handlers in squire`);
}
const handler = handlers[0].bind(this);
handlers[0] = event => {
if (!event.defaultPrevented && !event.squirePrevented) {
handler(event);
}
};
}
changeBlockFormat(srcCondition, targetTagName) {
this.modifyBlocks(frag => {
let current, newFrag, newBlock, nextBlock, tagName, lastNodeOfNextBlock, appendChidToNextBlock;
// HR은 Block으로 치지 않아서 frag에나타나지 않는다
// 디폴트 블럭을 만들어준다.
if (frag.childNodes.length) {
current = frag.childNodes.item(0);
} else {
current = this.createDefaultBlock();
frag.appendChild(current);
}
if (srcCondition) {
// find last depth
while (current.firstChild) {
current = current.firstChild;
}
appendChidToNextBlock = node => {
nextBlock.appendChild(node);
};
// find tag
while (current !== frag) {
({tagName} = current);
if (util.isFunction(srcCondition) ? srcCondition(tagName) : (tagName === srcCondition)) {
nextBlock = current.childNodes.item(0);
// there is no next blocktag
// eslint-disable-next-line max-depth
if (!domUtils.isElemNode(nextBlock) || current.childNodes.length > 1) {
nextBlock = this.createDefaultBlock();
util.forEachArray(util.toArray(current.childNodes), appendChidToNextBlock);
lastNodeOfNextBlock = nextBlock.lastChild;
// remove unneccesary br
// eslint-disable-next-line max-depth
if (lastNodeOfNextBlock && domUtils.getNodeName(lastNodeOfNextBlock) === 'BR') {
nextBlock.removeChild(lastNodeOfNextBlock);
}
}
// eslint-disable-next-line max-depth
if (targetTagName) {
newBlock = this.createElement(targetTagName, [nextBlock]);
} else {
newBlock = nextBlock;
}
newFrag = this.getDocument().createDocumentFragment();
newFrag.appendChild(newBlock);
frag = newFrag;
break;
}
current = current.parentNode;
}
}
// if source condition node is not founded, we wrap current div node with node named targetTagName
if (
(!newFrag || !srcCondition)
&& targetTagName
&& domUtils.getNodeName(frag.childNodes[0]) === 'DIV'
) {
frag = this.createElement(targetTagName, [frag.childNodes[0]]);
}
return frag;
});
}
changeBlockFormatTo(targetTagName) {
this.changeBlockFormat(tagName => FIND_BLOCK_TAGNAME_RX.test(tagName), targetTagName);
}
getCaretPosition() {
return this.getCursorPosition();
}
replaceSelection(content, selection) {
if (selection) {
this.setSelection(selection);
}
this._ignoreChange = true;
this.insertHTML(content);
}
replaceRelativeOffset(content, offset, overwriteLength) {
const selection = this.getSelection().cloneRange();
this._replaceRelativeOffsetOfSelection(content, offset, overwriteLength, selection);
}
_replaceRelativeOffsetOfSelection(content, offset, overwriteLength, selection) {
let startSelectionInfo, endSelectionInfo, finalOffset;
let endOffsetNode = selection.endContainer;
let endTextOffset = selection.endOffset;
if (domUtils.getNodeName(endOffsetNode) !== 'TEXT') {
endOffsetNode = this._getClosestTextNode(endOffsetNode, endTextOffset);
if (endOffsetNode) {
if (domUtils.isTextNode(endOffsetNode)) {
endTextOffset = endOffsetNode.nodeValue.length;
} else {
endTextOffset = endOffsetNode.textContent.length;
}
}
}
if (endOffsetNode) {
startSelectionInfo = this.getSelectionInfoByOffset(endOffsetNode, endTextOffset + offset);
selection.setStart(startSelectionInfo.element, startSelectionInfo.offset);
finalOffset = endTextOffset + (offset + overwriteLength);
endSelectionInfo = this.getSelectionInfoByOffset(endOffsetNode, finalOffset);
selection.setEnd(endSelectionInfo.element, endSelectionInfo.offset);
this.replaceSelection(content, selection);
} else {
this.replaceSelection(content);
}
}
_getClosestTextNode(node, offset) {
let foundNode = domUtils.getChildNodeByOffset(node, offset - 1);
if (domUtils.getNodeName(foundNode) !== 'TEXT') {
foundNode = foundNode.previousSibling;
}
return foundNode;
}
getSelectionInfoByOffset(anchorElement, offset) {
let traceElement, traceElementLength, traceOffset, stepLength;
const direction = offset >= 0 ? 'next' : 'previous';
const offsetAbs = Math.abs(offset);
let latestAvailableElement = traceElement;
if (direction === 'next') {
traceElement = anchorElement;
} else {
traceElement = anchorElement.previousSibling;
}
traceOffset = offsetAbs;
stepLength = 0;
while (traceElement) {
if (domUtils.isTextNode(traceElement)) {
traceElementLength = traceElement.nodeValue.length;
} else {
traceElementLength = traceElement.textContent.length;
}
stepLength += traceElementLength;
if (offsetAbs <= stepLength) {
break;
}
traceOffset -= traceElementLength;
if (domUtils.getTextLength(traceElement) > 0) {
latestAvailableElement = traceElement;
}
traceElement = traceElement[`${direction}Sibling`];
}
if (!traceElement) {
traceElement = latestAvailableElement;
traceOffset = domUtils.getTextLength(traceElement);
}
if (direction === 'previous') {
traceOffset = domUtils.getTextLength(traceElement) - traceOffset;
}
return {
element: traceElement,
offset: traceOffset
};
}
getSelectionPosition(selection, style, offset) {
const marker = this.createElement('INPUT');
const range = selection.cloneRange();
const endSelectionInfo = this.getSelectionInfoByOffset(selection.endContainer,
selection.endOffset + (offset || 0));
range.setStart(range.startContainer, range.startOffset);
range.setEnd(endSelectionInfo.element, endSelectionInfo.offset);
// to prevent squire input event fire
this._ignoreChange = true;
this.insertElement(marker, range);
const pos = $(marker).offset();
if (style !== 'over') {
pos.top += $(marker).outerHeight();
}
marker.parentNode.removeChild(marker);
selection.setStart(selection.endContainer, selection.endOffset);
selection.collapse(true);
this.setSelection(selection);
return pos;
}
removeLastUndoStack() {
if (this._undoStack.length) {
this._undoStackLength -= 1;
this._undoIndex -= 1;
this._undoStack.pop();
this._isInUndoState = false;
}
}
replaceParent(node, from, to) {
const target = $(node).closest(from);
if (target.length) {
target.wrapInner(`<${to}/>`);
target.children().unwrap();
}
}
preserveLastLine() {
const lastBlock = this.get$Body().children().last();
if (domUtils.getNodeName(lastBlock[0]) !== 'DIV') {
this._ignoreChange = true;
$(this.createDefaultBlock()).insertAfter(lastBlock);
}
}
scrollTop(top) {
if (util.isUndefined(top)) {
return this.get$Body().scrollTop();
}
return this.get$Body().scrollTop(top);
}
isIgnoreChange() {
return this._ignoreChange;
}
focus() {
Squire.prototype.focus.call(this);
}
blockCommandShortcuts() {
const isMac = /Mac/.test(navigator.platform);
const meta = isMac ? 'meta' : 'ctrl';
const keys = ['b', 'i', 'u', 'shift-7', 'shift-5', 'shift-6', 'shift-8', 'shift-9', '[', ']'];
keys.forEach(key => {
this.setKeyHandler(`${meta}-${key}`, (editor, keyboardEvent) => {
keyboardEvent.preventDefault();
});
});
}
}
export default SquireExt;