Debian Codegraph @

richtext-editor/src/js/squire-raw.js

raw symbols SCIP
1 /* Copyright © 2011-2015 by Neil Jenkins. MIT Licensed. */
2
3 ( function ( doc, undefined ) {
4
5 "use strict";
6
7 var DOCUMENT_POSITION_PRECEDING = 2; // Node.DOCUMENT_POSITION_PRECEDING
8 var ELEMENT_NODE = 1; // Node.ELEMENT_NODE;
9 var TEXT_NODE = 3; // Node.TEXT_NODE;
10 var DOCUMENT_NODE = 9; // Node.DOCUMENT_NODE;
11 var DOCUMENT_FRAGMENT_NODE = 11; // Node.DOCUMENT_FRAGMENT_NODE;
12 var SHOW_ELEMENT = 1; // NodeFilter.SHOW_ELEMENT;
13 var SHOW_TEXT = 4; // NodeFilter.SHOW_TEXT;
14
15 var START_TO_START = 0; // Range.START_TO_START
16 var START_TO_END = 1; // Range.START_TO_END
17 var END_TO_END = 2; // Range.END_TO_END
18 var END_TO_START = 3; // Range.END_TO_START
19
20 var HIGHLIGHT_CLASS = 'highlight';
21 var COLOUR_CLASS = 'colour';
22 var FONT_FAMILY_CLASS = 'font';
23 var FONT_SIZE_CLASS = 'size';
24
25 var ZWS = '\u200B';
26
27 var win = doc.defaultView;
28
29 var ua = navigator.userAgent;
30
31 var isAndroid = /Android/.test( ua );
32 var isIOS = /iP(?:ad|hone|od)/.test( ua );
33 var isMac = /Mac OS X/.test( ua );
34 var isWin = /Windows NT/.test( ua );
35
36 var isGecko = /Gecko\//.test( ua );
37 var isIElt11 = /Trident\/[456]\./.test( ua );
38 var isPresto = !!win.opera;
39 var isEdge = /Edge\//.test( ua );
40 var isWebKit = !isEdge && /WebKit\//.test( ua );
41 var isIE = /Trident\/[4567]\./.test( ua );
42
43 var ctrlKey = isMac ? 'meta-' : 'ctrl-';
44
45 var useTextFixer = isIElt11 || isPresto;
46 var cantFocusEmptyTextNodes = isIElt11 || isWebKit;
47 var losesSelectionOnBlur = isIElt11;
48
49 var canObserveMutations = typeof MutationObserver !== 'undefined';
50 var canWeakMap = typeof WeakMap !== 'undefined';
51
52 // Use [^ \t\r\n] instead of \S so that nbsp does not count as white-space
53 var notWS = /[^ \t\r\n]/;
54
55 var indexOf = Array.prototype.indexOf;
56
57 // Polyfill for FF3.5
58 if ( !Object.create ) {
59 Object.create = function ( proto ) {
60 var F = function () {};
61 F.prototype = proto;
62 return new F();
63 };
64 }
65
66 /*
67 Native TreeWalker is buggy in IE and Opera:
68 * IE9/10 sometimes throw errors when calling TreeWalker#nextNode or
69 TreeWalker#previousNode. No way to feature detect this.
70 * Some versions of Opera have a bug in TreeWalker#previousNode which makes
71 it skip to the wrong node.
72
73 Rather than risk further bugs, it's easiest just to implement our own
74 (subset) of the spec in all browsers.
75 */
76
77 var typeToBitArray = {
78 // ELEMENT_NODE
79 1: 1,
80 // ATTRIBUTE_NODE
81 2: 2,
82 // TEXT_NODE
83 3: 4,
84 // COMMENT_NODE
85 8: 128,
86 // DOCUMENT_NODE
87 9: 256,
88 // DOCUMENT_FRAGMENT_NODE
89 11: 1024
90 };
91
92 function TreeWalker ( root, nodeType, filter ) {
93 this.root = this.currentNode = root;
94 this.nodeType = nodeType;
95 this.filter = filter;
96 }
97
98 TreeWalker.prototype.nextNode = function () {
99 var current = this.currentNode,
100 root = this.root,
101 nodeType = this.nodeType,
102 filter = this.filter,
103 node;
104 while ( true ) {
105 node = current.firstChild;
106 while ( !node && current ) {
107 if ( current === root ) {
108 break;
109 }
110 node = current.nextSibling;
111 if ( !node ) { current = current.parentNode; }
112 }
113 if ( !node ) {
114 return null;
115 }
116 if ( ( typeToBitArray[ node.nodeType ] & nodeType ) &&
117 filter( node ) ) {
118 this.currentNode = node;
119 return node;
120 }
121 current = node;
122 }
123 };
124
125 TreeWalker.prototype.previousNode = function () {
126 var current = this.currentNode,
127 root = this.root,
128 nodeType = this.nodeType,
129 filter = this.filter,
130 node;
131 while ( true ) {
132 if ( current === root ) {
133 return null;
134 }
135 node = current.previousSibling;
136 if ( node ) {
137 while ( current = node.lastChild ) {
138 node = current;
139 }
140 } else {
141 node = current.parentNode;
142 }
143 if ( !node ) {
144 return null;
145 }
146 if ( ( typeToBitArray[ node.nodeType ] & nodeType ) &&
147 filter( node ) ) {
148 this.currentNode = node;
149 return node;
150 }
151 current = node;
152 }
153 };
154
155 // Previous node in post-order.
156 TreeWalker.prototype.previousPONode = function () {
157 var current = this.currentNode,
158 root = this.root,
159 nodeType = this.nodeType,
160 filter = this.filter,
161 node;
162 while ( true ) {
163 node = current.lastChild;
164 while ( !node && current ) {
165 if ( current === root ) {
166 break;
167 }
168 node = current.previousSibling;
169 if ( !node ) { current = current.parentNode; }
170 }
171 if ( !node ) {
172 return null;
173 }
174 if ( ( typeToBitArray[ node.nodeType ] & nodeType ) &&
175 filter( node ) ) {
176 this.currentNode = node;
177 return node;
178 }
179 current = node;
180 }
181 };
182
183 var inlineNodeNames = /^(?:#text|A(?:BBR|CRONYM)?|B(?:R|D[IO])?|C(?:ITE|ODE)|D(?:ATA|EL|FN)|EM|FONT|HR|I(?:FRAME|MG|NPUT|NS)?|KBD|Q|R(?:P|T|UBY)|S(?:AMP|MALL|PAN|TR(?:IKE|ONG)|U[BP])?|TIME|U|VAR|WBR)$/;
184
185 var leafNodeNames = {
186 BR: 1,
187 HR: 1,
188 IFRAME: 1,
189 IMG: 1,
190 INPUT: 1
191 };
192
193 function every ( nodeList, fn ) {
194 var l = nodeList.length;
195 while ( l-- ) {
196 if ( !fn( nodeList[l] ) ) {
197 return false;
198 }
199 }
200 return true;
201 }
202
203 // ---
204
205 var UNKNOWN = 0;
206 var INLINE = 1;
207 var BLOCK = 2;
208 var CONTAINER = 3;
209
210 var nodeCategoryCache = canWeakMap ? new WeakMap() : null;
211
212 function isLeaf ( node ) {
213 return node.nodeType === ELEMENT_NODE && !!leafNodeNames[ node.nodeName ];
214 }
215 function getNodeCategory ( node ) {
216 switch ( node.nodeType ) {
217 case TEXT_NODE:
218 return INLINE;
219 case ELEMENT_NODE:
220 case DOCUMENT_FRAGMENT_NODE:
221 if ( canWeakMap && nodeCategoryCache.has( node ) ) {
222 return nodeCategoryCache.get( node );
223 }
224 break;
225 default:
226 return UNKNOWN;
227 }
228
229 var nodeCategory;
230 if ( !every( node.childNodes, isInline ) ) {
231 // Malformed HTML can have block tags inside inline tags. Need to treat
232 // these as containers rather than inline. See #239.
233 nodeCategory = CONTAINER;
234 } else if ( inlineNodeNames.test( node.nodeName ) ) {
235 nodeCategory = INLINE;
236 } else {
237 nodeCategory = BLOCK;
238 }
239 if ( canWeakMap ) {
240 nodeCategoryCache.set( node, nodeCategory );
241 }
242 return nodeCategory;
243 }
244 function isInline ( node ) {
245 return getNodeCategory( node ) === INLINE;
246 }
247 function isBlock ( node ) {
248 return getNodeCategory( node ) === BLOCK;
249 }
250 function isContainer ( node ) {
251 return getNodeCategory( node ) === CONTAINER;
252 }
253
254 function getBlockWalker ( node, root ) {
255 var walker = new TreeWalker( root, SHOW_ELEMENT, isBlock );
256 walker.currentNode = node;
257 return walker;
258 }
259 function getPreviousBlock ( node, root ) {
260 node = getBlockWalker( node, root ).previousNode();
261 return node !== root ? node : null;
262 }
263 function getNextBlock ( node, root ) {
264 node = getBlockWalker( node, root ).nextNode();
265 return node !== root ? node : null;
266 }
267
268 function isEmptyBlock ( block ) {
269 return !block.textContent && !block.querySelector( 'IMG' );
270 }
271
272 function areAlike ( node, node2 ) {
273 return !isLeaf( node ) && (
274 node.nodeType === node2.nodeType &&
275 node.nodeName === node2.nodeName &&
276 node.nodeName !== 'A' &&
277 node.className === node2.className &&
278 ( ( !node.style && !node2.style ) ||
279 node.style.cssText === node2.style.cssText )
280 );
281 }
282 function hasTagAttributes ( node, tag, attributes ) {
283 if ( node.nodeName !== tag ) {
284 return false;
285 }
286 for ( var attr in attributes ) {
287 if ( node.getAttribute( attr ) !== attributes[ attr ] ) {
288 return false;
289 }
290 }
291 return true;
292 }
293 function getNearest ( node, root, tag, attributes ) {
294 while ( node && node !== root ) {
295 if ( hasTagAttributes( node, tag, attributes ) ) {
296 return node;
297 }
298 node = node.parentNode;
299 }
300 return null;
301 }
302 function isOrContains ( parent, node ) {
303 while ( node ) {
304 if ( node === parent ) {
305 return true;
306 }
307 node = node.parentNode;
308 }
309 return false;
310 }
311
312 function getPath ( node, root ) {
313 var path = '';
314 var id, className, classNames, dir;
315 if ( node && node !== root ) {
316 path = getPath( node.parentNode, root );
317 if ( node.nodeType === ELEMENT_NODE ) {
318 path += ( path ? '>' : '' ) + node.nodeName;
319 if ( id = node.id ) {
320 path += '#' + id;
321 }
322 if ( className = node.className.trim() ) {
323 classNames = className.split( /\s\s*/ );
324 classNames.sort();
325 path += '.';
326 path += classNames.join( '.' );
327 }
328 if ( dir = node.dir ) {
329 path += '[dir=' + dir + ']';
330 }
331 if ( classNames ) {
332 if ( indexOf.call( classNames, HIGHLIGHT_CLASS ) > -1 ) {
333 path += '[backgroundColor=' +
334 node.style.backgroundColor.replace( / /g,'' ) + ']';
335 }
336 if ( indexOf.call( classNames, COLOUR_CLASS ) > -1 ) {
337 path += '[color=' +
338 node.style.color.replace( / /g,'' ) + ']';
339 }
340 if ( indexOf.call( classNames, FONT_FAMILY_CLASS ) > -1 ) {
341 path += '[fontFamily=' +
342 node.style.fontFamily.replace( / /g,'' ) + ']';
343 }
344 if ( indexOf.call( classNames, FONT_SIZE_CLASS ) > -1 ) {
345 path += '[fontSize=' + node.style.fontSize + ']';
346 }
347 }
348 }
349 }
350 return path;
351 }
352
353 function getLength ( node ) {
354 var nodeType = node.nodeType;
355 return nodeType === ELEMENT_NODE || nodeType === DOCUMENT_FRAGMENT_NODE ?
356 node.childNodes.length : node.length || 0;
357 }
358
359 function detach ( node ) {
360 var parent = node.parentNode;
361 if ( parent ) {
362 parent.removeChild( node );
363 }
364 return node;
365 }
366 function replaceWith ( node, node2 ) {
367 var parent = node.parentNode;
368 if ( parent ) {
369 parent.replaceChild( node2, node );
370 }
371 }
372 function empty ( node ) {
373 var frag = node.ownerDocument.createDocumentFragment(),
374 childNodes = node.childNodes,
375 l = childNodes ? childNodes.length : 0;
376 while ( l-- ) {
377 frag.appendChild( node.firstChild );
378 }
379 return frag;
380 }
381
382 function createElement ( doc, tag, props, children ) {
383 var el = doc.createElement( tag ),
384 attr, value, i, l;
385 if ( props instanceof Array ) {
386 children = props;
387 props = null;
388 }
389 if ( props ) {
390 for ( attr in props ) {
391 value = props[ attr ];
392 if ( value !== undefined ) {
393 el.setAttribute( attr, props[ attr ] );
394 }
395 }
396 }
397 if ( children ) {
398 for ( i = 0, l = children.length; i < l; i += 1 ) {
399 el.appendChild( children[i] );
400 }
401 }
402 return el;
403 }
404
405 function fixCursor ( node, root ) {
406 // In Webkit and Gecko, block level elements are collapsed and
407 // unfocussable if they have no content. To remedy this, a <BR> must be
408 // inserted. In Opera and IE, we just need a textnode in order for the
409 // cursor to appear.
410 var self = root.__squire__;
411 var doc = node.ownerDocument;
412 var originalNode = node;
413 var fixer, child;
414
415 if ( node === root ) {
416 if ( !( child = node.firstChild ) || child.nodeName === 'BR' ) {
417 fixer = self.createDefaultBlock();
418 if ( child ) {
419 node.replaceChild( fixer, child );
420 }
421 else {
422 node.appendChild( fixer );
423 }
424 node = fixer;
425 fixer = null;
426 }
427 }
428
429 if ( node.nodeType === TEXT_NODE ) {
430 return originalNode;
431 }
432
433 if ( isInline( node ) ) {
434 child = node.firstChild;
435 while ( cantFocusEmptyTextNodes && child &&
436 child.nodeType === TEXT_NODE && !child.data ) {
437 node.removeChild( child );
438 child = node.firstChild;
439 }
440 if ( !child ) {
441 if ( cantFocusEmptyTextNodes ) {
442 fixer = doc.createTextNode( ZWS );
443 self._didAddZWS();
444 } else {
445 fixer = doc.createTextNode( '' );
446 }
447 }
448 } else {
449 if ( useTextFixer ) {
450 while ( node.nodeType !== TEXT_NODE && !isLeaf( node ) ) {
451 child = node.firstChild;
452 if ( !child ) {
453 fixer = doc.createTextNode( '' );
454 break;
455 }
456 node = child;
457 }
458 if ( node.nodeType === TEXT_NODE ) {
459 // Opera will collapse the block element if it contains
460 // just spaces (but not if it contains no data at all).
461 if ( /^ +$/.test( node.data ) ) {
462 node.data = '';
463 }
464 } else if ( isLeaf( node ) ) {
465 node.parentNode.insertBefore( doc.createTextNode( '' ), node );
466 }
467 }
468 else if ( !node.querySelector( 'BR' ) ) {
469 fixer = createElement( doc, 'BR' );
470 while ( ( child = node.lastElementChild ) && !isInline( child ) ) {
471 node = child;
472 }
473 }
474 }
475 if ( fixer ) {
476 try {
477 node.appendChild( fixer );
478 } catch ( error ) {
479 self.didError({
480 name: 'Squire: fixCursor – ' + error,
481 message: 'Parent: ' + node.nodeName + '/' + node.innerHTML +
482 ' appendChild: ' + fixer.nodeName
483 });
484 }
485 }
486
487 return originalNode;
488 }
489
490 // Recursively examine container nodes and wrap any inline children.
491 function fixContainer ( container, root ) {
492 var children = container.childNodes;
493 var doc = container.ownerDocument;
494 var wrapper = null;
495 var i, l, child, isBR;
496 var config = root.__squire__._config;
497
498 for ( i = 0, l = children.length; i < l; i += 1 ) {
499 child = children[i];
500 isBR = child.nodeName === 'BR';
501 if ( !isBR && isInline( child ) ) {
502 if ( !wrapper ) {
503 wrapper = createElement( doc,
504 config.blockTag, config.blockAttributes );
505 }
506 wrapper.appendChild( child );
507 i -= 1;
508 l -= 1;
509 } else if ( isBR || wrapper ) {
510 if ( !wrapper ) {
511 wrapper = createElement( doc,
512 config.blockTag, config.blockAttributes );
513 }
514 fixCursor( wrapper, root );
515 if ( isBR ) {
516 container.replaceChild( wrapper, child );
517 } else {
518 container.insertBefore( wrapper, child );
519 i += 1;
520 l += 1;
521 }
522 wrapper = null;
523 }
524 if ( isContainer( child ) ) {
525 fixContainer( child, root );
526 }
527 }
528 if ( wrapper ) {
529 container.appendChild( fixCursor( wrapper, root ) );
530 }
531 return container;
532 }
533
534 function split ( node, offset, stopNode, root ) {
535 var nodeType = node.nodeType,
536 parent, clone, next;
537 if ( nodeType === TEXT_NODE && node !== stopNode ) {
538 return split(
539 node.parentNode, node.splitText( offset ), stopNode, root );
540 }
541 if ( nodeType === ELEMENT_NODE ) {
542 if ( typeof( offset ) === 'number' ) {
543 offset = offset < node.childNodes.length ?
544 node.childNodes[ offset ] : null;
545 }
546 if ( node === stopNode ) {
547 return offset;
548 }
549
550 // Clone node without children
551 parent = node.parentNode;
552 clone = node.cloneNode( false );
553
554 // Add right-hand siblings to the clone
555 while ( offset ) {
556 next = offset.nextSibling;
557 clone.appendChild( offset );
558 offset = next;
559 }
560
561 // Maintain li numbering if inside a quote.
562 if ( node.nodeName === 'OL' &&
563 getNearest( node, root, 'BLOCKQUOTE' ) ) {
564 clone.start = ( +node.start || 1 ) + node.childNodes.length - 1;
565 }
566
567 // DO NOT NORMALISE. This may undo the fixCursor() call
568 // of a node lower down the tree!
569
570 // We need something in the element in order for the cursor to appear.
571 fixCursor( node, root );
572 fixCursor( clone, root );
573
574 // Inject clone after original node
575 if ( next = node.nextSibling ) {
576 parent.insertBefore( clone, next );
577 } else {
578 parent.appendChild( clone );
579 }
580
581 // Keep on splitting up the tree
582 return split( parent, clone, stopNode, root );
583 }
584 return offset;
585 }
586
587 function _mergeInlines ( node, fakeRange ) {
588 var children = node.childNodes,
589 l = children.length,
590 frags = [],
591 child, prev, len;
592 while ( l-- ) {
593 child = children[l];
594 prev = l && children[ l - 1 ];
595 if ( l && isInline( child ) && areAlike( child, prev ) &&
596 !leafNodeNames[ child.nodeName ] ) {
597 if ( fakeRange.startContainer === child ) {
598 fakeRange.startContainer = prev;
599 fakeRange.startOffset += getLength( prev );
600 }
601 if ( fakeRange.endContainer === child ) {
602 fakeRange.endContainer = prev;
603 fakeRange.endOffset += getLength( prev );
604 }
605 if ( fakeRange.startContainer === node ) {
606 if ( fakeRange.startOffset > l ) {
607 fakeRange.startOffset -= 1;
608 }
609 else if ( fakeRange.startOffset === l ) {
610 fakeRange.startContainer = prev;
611 fakeRange.startOffset = getLength( prev );
612 }
613 }
614 if ( fakeRange.endContainer === node ) {
615 if ( fakeRange.endOffset > l ) {
616 fakeRange.endOffset -= 1;
617 }
618 else if ( fakeRange.endOffset === l ) {
619 fakeRange.endContainer = prev;
620 fakeRange.endOffset = getLength( prev );
621 }
622 }
623 detach( child );
624 if ( child.nodeType === TEXT_NODE ) {
625 prev.appendData( child.data );
626 }
627 else {
628 frags.push( empty( child ) );
629 }
630 }
631 else if ( child.nodeType === ELEMENT_NODE ) {
632 len = frags.length;
633 while ( len-- ) {
634 child.appendChild( frags.pop() );
635 }
636 _mergeInlines( child, fakeRange );
637 }
638 }
639 }
640
641 function mergeInlines ( node, range ) {
642 if ( node.nodeType === TEXT_NODE ) {
643 node = node.parentNode;
644 }
645 if ( node.nodeType === ELEMENT_NODE ) {
646 var fakeRange = {
647 startContainer: range.startContainer,
648 startOffset: range.startOffset,
649 endContainer: range.endContainer,
650 endOffset: range.endOffset
651 };
652 _mergeInlines( node, fakeRange );
653 range.setStart( fakeRange.startContainer, fakeRange.startOffset );
654 range.setEnd( fakeRange.endContainer, fakeRange.endOffset );
655 }
656 }
657
658 function mergeWithBlock ( block, next, range, root ) {
659 var container = next;
660 var parent, last, offset;
661 while ( ( parent = container.parentNode ) &&
662 parent !== root &&
663 parent.nodeType === ELEMENT_NODE &&
664 parent.childNodes.length === 1 ) {
665 container = parent;
666 }
667 detach( container );
668
669 offset = block.childNodes.length;
670
671 // Remove extra <BR> fixer if present.
672 last = block.lastChild;
673 if ( last && last.nodeName === 'BR' ) {
674 block.removeChild( last );
675 offset -= 1;
676 }
677
678 block.appendChild( empty( next ) );
679
680 range.setStart( block, offset );
681 range.collapse( true );
682 mergeInlines( block, range );
683
684 // Opera inserts a BR if you delete the last piece of text
685 // in a block-level element. Unfortunately, it then gets
686 // confused when setting the selection subsequently and
687 // refuses to accept the range that finishes just before the
688 // BR. Removing the BR fixes the bug.
689 // Steps to reproduce bug: Type "a-b-c" (where - is return)
690 // then backspace twice. The cursor goes to the top instead
691 // of after "b".
692 if ( isPresto && ( last = block.lastChild ) && last.nodeName === 'BR' ) {
693 block.removeChild( last );
694 }
695 }
696
697 function mergeContainers ( node, root ) {
698 var prev = node.previousSibling,
699 first = node.firstChild,
700 doc = node.ownerDocument,
701 isListItem = ( node.nodeName === 'LI' ),
702 needsFix, block;
703
704 // Do not merge LIs, unless it only contains a UL
705 if ( isListItem && ( !first || !/^[OU]L$/.test( first.nodeName ) ) ) {
706 return;
707 }
708
709 if ( prev && areAlike( prev, node ) ) {
710 if ( !isContainer( prev ) ) {
711 if ( isListItem ) {
712 block = createElement( doc, 'DIV' );
713 block.appendChild( empty( prev ) );
714 prev.appendChild( block );
715 } else {
716 return;
717 }
718 }
719 detach( node );
720 needsFix = !isContainer( node );
721 prev.appendChild( empty( node ) );
722 if ( needsFix ) {
723 fixContainer( prev, root );
724 }
725 if ( first ) {
726 mergeContainers( first, root );
727 }
728 } else if ( isListItem ) {
729 prev = createElement( doc, 'DIV' );
730 node.insertBefore( prev, first );
731 fixCursor( prev, root );
732 }
733 }
734
735 var getNodeBefore = function ( node, offset ) {
736 var children = node.childNodes;
737 while ( offset && node.nodeType === ELEMENT_NODE ) {
738 node = children[ offset - 1 ];
739 children = node.childNodes;
740 offset = children.length;
741 }
742 return node;
743 };
744
745 var getNodeAfter = function ( node, offset ) {
746 if ( node.nodeType === ELEMENT_NODE ) {
747 var children = node.childNodes;
748 if ( offset < children.length ) {
749 node = children[ offset ];
750 } else {
751 while ( node && !node.nextSibling ) {
752 node = node.parentNode;
753 }
754 if ( node ) { node = node.nextSibling; }
755 }
756 }
757 return node;
758 };
759
760 // ---
761
762 var insertNodeInRange = function ( range, node ) {
763 // Insert at start.
764 var startContainer = range.startContainer,
765 startOffset = range.startOffset,
766 endContainer = range.endContainer,
767 endOffset = range.endOffset,
768 parent, children, childCount, afterSplit;
769
770 // If part way through a text node, split it.
771 if ( startContainer.nodeType === TEXT_NODE ) {
772 parent = startContainer.parentNode;
773 children = parent.childNodes;
774 if ( startOffset === startContainer.length ) {
775 startOffset = indexOf.call( children, startContainer ) + 1;
776 if ( range.collapsed ) {
777 endContainer = parent;
778 endOffset = startOffset;
779 }
780 } else {
781 if ( startOffset ) {
782 afterSplit = startContainer.splitText( startOffset );
783 if ( endContainer === startContainer ) {
784 endOffset -= startOffset;
785 endContainer = afterSplit;
786 }
787 else if ( endContainer === parent ) {
788 endOffset += 1;
789 }
790 startContainer = afterSplit;
791 }
792 startOffset = indexOf.call( children, startContainer );
793 }
794 startContainer = parent;
795 } else {
796 children = startContainer.childNodes;
797 }
798
799 childCount = children.length;
800
801 if ( startOffset === childCount ) {
802 startContainer.appendChild( node );
803 } else {
804 startContainer.insertBefore( node, children[ startOffset ] );
805 }
806
807 if ( startContainer === endContainer ) {
808 endOffset += children.length - childCount;
809 }
810
811 range.setStart( startContainer, startOffset );
812 range.setEnd( endContainer, endOffset );
813 };
814
815 var extractContentsOfRange = function ( range, common, root ) {
816 var startContainer = range.startContainer,
817 startOffset = range.startOffset,
818 endContainer = range.endContainer,
819 endOffset = range.endOffset;
820
821 if ( !common ) {
822 common = range.commonAncestorContainer;
823 }
824
825 if ( common.nodeType === TEXT_NODE ) {
826 common = common.parentNode;
827 }
828
829 var endNode = split( endContainer, endOffset, common, root ),
830 startNode = split( startContainer, startOffset, common, root ),
831 frag = common.ownerDocument.createDocumentFragment(),
832 next, before, after;
833
834 // End node will be null if at end of child nodes list.
835 while ( startNode !== endNode ) {
836 next = startNode.nextSibling;
837 frag.appendChild( startNode );
838 startNode = next;
839 }
840
841 startContainer = common;
842 startOffset = endNode ?
843 indexOf.call( common.childNodes, endNode ) :
844 common.childNodes.length;
845
846 // Merge text nodes if adjacent. IE10 in particular will not focus
847 // between two text nodes
848 after = common.childNodes[ startOffset ];
849 before = after && after.previousSibling;
850 if ( before &&
851 before.nodeType === TEXT_NODE &&
852 after.nodeType === TEXT_NODE ) {
853 startContainer = before;
854 startOffset = before.length;
855 before.appendData( after.data );
856 detach( after );
857 }
858
859 range.setStart( startContainer, startOffset );
860 range.collapse( true );
861
862 fixCursor( common, root );
863
864 return frag;
865 };
866
867 var deleteContentsOfRange = function ( range, root ) {
868 var startBlock = getStartBlockOfRange( range, root );
869 var endBlock = getEndBlockOfRange( range, root );
870 var needsMerge = ( startBlock !== endBlock );
871 var frag, child;
872
873 // Move boundaries up as much as possible without exiting block,
874 // to reduce need to split.
875 moveRangeBoundariesDownTree( range );
876 moveRangeBoundariesUpTree( range, startBlock, endBlock, root );
877
878 // Remove selected range
879 frag = extractContentsOfRange( range, null, root );
880
881 // Move boundaries back down tree as far as possible.
882 moveRangeBoundariesDownTree( range );
883
884 // If we split into two different blocks, merge the blocks.
885 if ( needsMerge ) {
886 // endBlock will have been split, so need to refetch
887 endBlock = getEndBlockOfRange( range, root );
888 if ( startBlock && endBlock && startBlock !== endBlock ) {
889 mergeWithBlock( startBlock, endBlock, range, root );
890 }
891 }
892
893 // Ensure block has necessary children
894 if ( startBlock ) {
895 fixCursor( startBlock, root );
896 }
897
898 // Ensure root has a block-level element in it.
899 child = root.firstChild;
900 if ( !child || child.nodeName === 'BR' ) {
901 fixCursor( root, root );
902 range.selectNodeContents( root.firstChild );
903 } else {
904 range.collapse( true );
905 }
906 return frag;
907 };
908
909 // ---
910
911 // Contents of range will be deleted.
912 // After method, range will be around inserted content
913 var insertTreeFragmentIntoRange = function ( range, frag, root ) {
914 var node, block, blockContentsAfterSplit, stopPoint, container, offset;
915 var replaceBlock, firstBlockInFrag, nodeAfterSplit, nodeBeforeSplit;
916 var tempRange;
917
918 // Fixup content: ensure no top-level inline, and add cursor fix elements.
919 fixContainer( frag, root );
920 node = frag;
921 while ( ( node = getNextBlock( node, root ) ) ) {
922 fixCursor( node, root );
923 }
924
925 // Delete any selected content.
926 if ( !range.collapsed ) {
927 deleteContentsOfRange( range, root );
928 }
929
930 // Move range down into text nodes.
931 moveRangeBoundariesDownTree( range );
932 range.collapse( false ); // collapse to end
933
934 // Where will we split up to? First blockquote parent, otherwise root.
935 stopPoint = getNearest( range.endContainer, root, 'BLOCKQUOTE' ) || root;
936
937 // Merge the contents of the first block in the frag with the focused block.
938 // If there are contents in the block after the focus point, collect this
939 // up to insert in the last block later. If the block is empty, replace
940 // it instead of merging.
941 block = getStartBlockOfRange( range, root );
942 firstBlockInFrag = getNextBlock( frag, frag );
943 replaceBlock = !!block && isEmptyBlock( block );
944 if ( block && firstBlockInFrag && !replaceBlock &&
945 // Don't merge table cells or PRE elements into block
946 !getNearest( firstBlockInFrag, frag, 'PRE' ) &&
947 !getNearest( firstBlockInFrag, frag, 'TABLE' ) ) {
948 moveRangeBoundariesUpTree( range, block, block, root );
949 range.collapse( true ); // collapse to start
950 container = range.endContainer;
951 offset = range.endOffset;
952 // Remove trailing <br> – we don't want this considered content to be
953 // inserted again later
954 cleanupBRs( block, root, false );
955 if ( isInline( container ) ) {
956 // Split up to block parent.
957 nodeAfterSplit = split(
958 container, offset, getPreviousBlock( container, root ), root );
959 container = nodeAfterSplit.parentNode;
960 offset = indexOf.call( container.childNodes, nodeAfterSplit );
961 }
962 if ( /*isBlock( container ) && */offset !== getLength( container ) ) {
963 // Collect any inline contents of the block after the range point
964 blockContentsAfterSplit =
965 root.ownerDocument.createDocumentFragment();
966 while ( ( node = container.childNodes[ offset ] ) ) {
967 blockContentsAfterSplit.appendChild( node );
968 }
969 }
970 // And merge the first block in.
971 mergeWithBlock( container, firstBlockInFrag, range, root );
972
973 // And where we will insert
974 offset = indexOf.call( container.parentNode.childNodes, container ) + 1;
975 container = container.parentNode;
976 range.setEnd( container, offset );
977 }
978
979 // Is there still any content in the fragment?
980 if ( getLength( frag ) ) {
981 if ( replaceBlock ) {
982 range.setEndBefore( block );
983 range.collapse( false );
984 detach( block );
985 }
986 moveRangeBoundariesUpTree( range, stopPoint, stopPoint, root );
987 // Now split after block up to blockquote (if a parent) or root
988 nodeAfterSplit = split(
989 range.endContainer, range.endOffset, stopPoint, root );
990 nodeBeforeSplit = nodeAfterSplit ?
991 nodeAfterSplit.previousSibling :
992 stopPoint.lastChild;
993 stopPoint.insertBefore( frag, nodeAfterSplit );
994 if ( nodeAfterSplit ) {
995 range.setEndBefore( nodeAfterSplit );
996 } else {
997 range.setEnd( stopPoint, getLength( stopPoint ) );
998 }
999 block = getEndBlockOfRange( range, root );
1000
1001 // Get a reference that won't be invalidated if we merge containers.
1002 moveRangeBoundariesDownTree( range );
1003 container = range.endContainer;
1004 offset = range.endOffset;
1005
1006 // Merge inserted containers with edges of split
1007 if ( nodeAfterSplit && isContainer( nodeAfterSplit ) ) {
1008 mergeContainers( nodeAfterSplit, root );
1009 }
1010 nodeAfterSplit = nodeBeforeSplit && nodeBeforeSplit.nextSibling;
1011 if ( nodeAfterSplit && isContainer( nodeAfterSplit ) ) {
1012 mergeContainers( nodeAfterSplit, root );
1013 }
1014 range.setEnd( container, offset );
1015 }
1016
1017 // Insert inline content saved from before.
1018 if ( blockContentsAfterSplit ) {
1019 tempRange = range.cloneRange();
1020 mergeWithBlock( block, blockContentsAfterSplit, tempRange, root );
1021 range.setEnd( tempRange.endContainer, tempRange.endOffset );
1022 }
1023 moveRangeBoundariesDownTree( range );
1024 };
1025
1026 // ---
1027
1028 var isNodeContainedInRange = function ( range, node, partial ) {
1029 var nodeRange = node.ownerDocument.createRange();
1030
1031 nodeRange.selectNode( node );
1032
1033 if ( partial ) {
1034 // Node must not finish before range starts or start after range
1035 // finishes.
1036 var nodeEndBeforeStart = ( range.compareBoundaryPoints(
1037 END_TO_START, nodeRange ) > -1 ),
1038 nodeStartAfterEnd = ( range.compareBoundaryPoints(
1039 START_TO_END, nodeRange ) < 1 );
1040 return ( !nodeEndBeforeStart && !nodeStartAfterEnd );
1041 }
1042 else {
1043 // Node must start after range starts and finish before range
1044 // finishes
1045 var nodeStartAfterStart = ( range.compareBoundaryPoints(
1046 START_TO_START, nodeRange ) < 1 ),
1047 nodeEndBeforeEnd = ( range.compareBoundaryPoints(
1048 END_TO_END, nodeRange ) > -1 );
1049 return ( nodeStartAfterStart && nodeEndBeforeEnd );
1050 }
1051 };
1052
1053 var moveRangeBoundariesDownTree = function ( range ) {
1054 var startContainer = range.startContainer,
1055 startOffset = range.startOffset,
1056 endContainer = range.endContainer,
1057 endOffset = range.endOffset,
1058 maySkipBR = true,
1059 child;
1060
1061 while ( startContainer.nodeType !== TEXT_NODE ) {
1062 child = startContainer.childNodes[ startOffset ];
1063 if ( !child || isLeaf( child ) ) {
1064 break;
1065 }
1066 startContainer = child;
1067 startOffset = 0;
1068 }
1069 if ( endOffset ) {
1070 while ( endContainer.nodeType !== TEXT_NODE ) {
1071 child = endContainer.childNodes[ endOffset - 1 ];
1072 if ( !child || isLeaf( child ) ) {
1073 if ( maySkipBR && child && child.nodeName === 'BR' ) {
1074 endOffset -= 1;
1075 maySkipBR = false;
1076 continue;
1077 }
1078 break;
1079 }
1080 endContainer = child;
1081 endOffset = getLength( endContainer );
1082 }
1083 } else {
1084 while ( endContainer.nodeType !== TEXT_NODE ) {
1085 child = endContainer.firstChild;
1086 if ( !child || isLeaf( child ) ) {
1087 break;
1088 }
1089 endContainer = child;
1090 }
1091 }
1092
1093 // If collapsed, this algorithm finds the nearest text node positions
1094 // *outside* the range rather than inside, but also it flips which is
1095 // assigned to which.
1096 if ( range.collapsed ) {
1097 range.setStart( endContainer, endOffset );
1098 range.setEnd( startContainer, startOffset );
1099 } else {
1100 range.setStart( startContainer, startOffset );
1101 range.setEnd( endContainer, endOffset );
1102 }
1103 };
1104
1105 var moveRangeBoundariesUpTree = function ( range, startMax, endMax, root ) {
1106 var startContainer = range.startContainer;
1107 var startOffset = range.startOffset;
1108 var endContainer = range.endContainer;
1109 var endOffset = range.endOffset;
1110 var maySkipBR = true;
1111 var parent;
1112
1113 if ( !startMax ) {
1114 startMax = range.commonAncestorContainer;
1115 }
1116 if ( !endMax ) {
1117 endMax = startMax;
1118 }
1119
1120 while ( !startOffset &&
1121 startContainer !== startMax &&
1122 startContainer !== root ) {
1123 parent = startContainer.parentNode;
1124 startOffset = indexOf.call( parent.childNodes, startContainer );
1125 startContainer = parent;
1126 }
1127
1128 while ( true ) {
1129 if ( maySkipBR &&
1130 endContainer.nodeType !== TEXT_NODE &&
1131 endContainer.childNodes[ endOffset ] &&
1132 endContainer.childNodes[ endOffset ].nodeName === 'BR' ) {
1133 endOffset += 1;
1134 maySkipBR = false;
1135 }
1136 if ( endContainer === endMax ||
1137 endContainer === root ||
1138 endOffset !== getLength( endContainer ) ) {
1139 break;
1140 }
1141 parent = endContainer.parentNode;
1142 endOffset = indexOf.call( parent.childNodes, endContainer ) + 1;
1143 endContainer = parent;
1144 }
1145
1146 range.setStart( startContainer, startOffset );
1147 range.setEnd( endContainer, endOffset );
1148 };
1149
1150 // Returns the first block at least partially contained by the range,
1151 // or null if no block is contained by the range.
1152 var getStartBlockOfRange = function ( range, root ) {
1153 var container = range.startContainer,
1154 block;
1155
1156 // If inline, get the containing block.
1157 if ( isInline( container ) ) {
1158 block = getPreviousBlock( container, root );
1159 } else if ( container !== root && isBlock( container ) ) {
1160 block = container;
1161 } else {
1162 block = getNodeBefore( container, range.startOffset );
1163 block = getNextBlock( block, root );
1164 }
1165 // Check the block actually intersects the range
1166 return block && isNodeContainedInRange( range, block, true ) ? block : null;
1167 };
1168
1169 // Returns the last block at least partially contained by the range,
1170 // or null if no block is contained by the range.
1171 var getEndBlockOfRange = function ( range, root ) {
1172 var container = range.endContainer,
1173 block, child;
1174
1175 // If inline, get the containing block.
1176 if ( isInline( container ) ) {
1177 block = getPreviousBlock( container, root );
1178 } else if ( container !== root && isBlock( container ) ) {
1179 block = container;
1180 } else {
1181 block = getNodeAfter( container, range.endOffset );
1182 if ( !block || !isOrContains( root, block ) ) {
1183 block = root;
1184 while ( child = block.lastChild ) {
1185 block = child;
1186 }
1187 }
1188 block = getPreviousBlock( block, root );
1189 }
1190 // Check the block actually intersects the range
1191 return block && isNodeContainedInRange( range, block, true ) ? block : null;
1192 };
1193
1194 var contentWalker = new TreeWalker( null,
1195 SHOW_TEXT|SHOW_ELEMENT,
1196 function ( node ) {
1197 return node.nodeType === TEXT_NODE ?
1198 notWS.test( node.data ) :
1199 node.nodeName === 'IMG';
1200 }
1201 );
1202
1203 var rangeDoesStartAtBlockBoundary = function ( range, root ) {
1204 var startContainer = range.startContainer;
1205 var startOffset = range.startOffset;
1206 var nodeAfterCursor;
1207
1208 // If in the middle or end of a text node, we're not at the boundary.
1209 contentWalker.root = null;
1210 if ( startContainer.nodeType === TEXT_NODE ) {
1211 if ( startOffset ) {
1212 return false;
1213 }
1214 nodeAfterCursor = startContainer;
1215 } else {
1216 nodeAfterCursor = getNodeAfter( startContainer, startOffset );
1217 if ( nodeAfterCursor && !isOrContains( root, nodeAfterCursor ) ) {
1218 nodeAfterCursor = null;
1219 }
1220 // The cursor was right at the end of the document
1221 if ( !nodeAfterCursor ) {
1222 nodeAfterCursor = getNodeBefore( startContainer, startOffset );
1223 if ( nodeAfterCursor.nodeType === TEXT_NODE &&
1224 nodeAfterCursor.length ) {
1225 return false;
1226 }
1227 }
1228 }
1229
1230 // Otherwise, look for any previous content in the same block.
1231 contentWalker.currentNode = nodeAfterCursor;
1232 contentWalker.root = getStartBlockOfRange( range, root );
1233
1234 return !contentWalker.previousNode();
1235 };
1236
1237 var rangeDoesEndAtBlockBoundary = function ( range, root ) {
1238 var endContainer = range.endContainer,
1239 endOffset = range.endOffset,
1240 length;
1241
1242 // If in a text node with content, and not at the end, we're not
1243 // at the boundary
1244 contentWalker.root = null;
1245 if ( endContainer.nodeType === TEXT_NODE ) {
1246 length = endContainer.data.length;
1247 if ( length && endOffset < length ) {
1248 return false;
1249 }
1250 contentWalker.currentNode = endContainer;
1251 } else {
1252 contentWalker.currentNode = getNodeBefore( endContainer, endOffset );
1253 }
1254
1255 // Otherwise, look for any further content in the same block.
1256 contentWalker.root = getEndBlockOfRange( range, root );
1257
1258 return !contentWalker.nextNode();
1259 };
1260
1261 var expandRangeToBlockBoundaries = function ( range, root ) {
1262 var start = getStartBlockOfRange( range, root ),
1263 end = getEndBlockOfRange( range, root ),
1264 parent;
1265
1266 if ( start && end ) {
1267 parent = start.parentNode;
1268 range.setStart( parent, indexOf.call( parent.childNodes, start ) );
1269 parent = end.parentNode;
1270 range.setEnd( parent, indexOf.call( parent.childNodes, end ) + 1 );
1271 }
1272 };
1273
1274 var keys = {
1275 8: 'backspace',
1276 9: 'tab',
1277 13: 'enter',
1278 32: 'space',
1279 33: 'pageup',
1280 34: 'pagedown',
1281 37: 'left',
1282 39: 'right',
1283 46: 'delete',
1284 219: '[',
1285 221: ']'
1286 };
1287
1288 // Ref: http://unixpapa.com/js/key.html
1289 var onKey = function ( event ) {
1290 var code = event.keyCode,
1291 key = keys[ code ],
1292 modifiers = '',
1293 range = this.getSelection();
1294
1295 if ( event.defaultPrevented ) {
1296 return;
1297 }
1298
1299 if ( !key ) {
1300 key = String.fromCharCode( code ).toLowerCase();
1301 // Only reliable for letters and numbers
1302 if ( !/^[A-Za-z0-9]$/.test( key ) ) {
1303 key = '';
1304 }
1305 }
1306
1307 // On keypress, delete and '.' both have event.keyCode 46
1308 // Must check event.which to differentiate.
1309 if ( isPresto && event.which === 46 ) {
1310 key = '.';
1311 }
1312
1313 // Function keys
1314 if ( 111 < code && code < 124 ) {
1315 key = 'f' + ( code - 111 );
1316 }
1317
1318 // We need to apply the backspace/delete handlers regardless of
1319 // control key modifiers.
1320 if ( key !== 'backspace' && key !== 'delete' ) {
1321 if ( event.altKey ) { modifiers += 'alt-'; }
1322 if ( event.ctrlKey ) { modifiers += 'ctrl-'; }
1323 if ( event.metaKey ) { modifiers += 'meta-'; }
1324 }
1325 // However, on Windows, shift-delete is apparently "cut" (WTF right?), so
1326 // we want to let the browser handle shift-delete.
1327 if ( event.shiftKey ) { modifiers += 'shift-'; }
1328
1329 key = modifiers + key;
1330
1331 if ( this._keyHandlers[ key ] ) {
1332 this._keyHandlers[ key ]( this, event, range );
1333 } else if ( key.length === 1 && !range.collapsed ) {
1334 // Record undo checkpoint.
1335 this.saveUndoState( range );
1336 // Delete the selection
1337 deleteContentsOfRange( range, this._root );
1338 this._ensureBottomLine();
1339 this.setSelection( range );
1340 this._updatePath( range, true );
1341 }
1342 };
1343
1344 var mapKeyTo = function ( method ) {
1345 return function ( self, event ) {
1346 event.preventDefault();
1347 self[ method ]();
1348 };
1349 };
1350
1351 var mapKeyToFormat = function ( tag, remove ) {
1352 remove = remove || null;
1353 return function ( self, event ) {
1354 event.preventDefault();
1355 var range = self.getSelection();
1356 if ( self.hasFormat( tag, null, range ) ) {
1357 self.changeFormat( null, { tag: tag }, range );
1358 } else {
1359 self.changeFormat( { tag: tag }, remove, range );
1360 }
1361 };
1362 };
1363
1364 // If you delete the content inside a span with a font styling, Webkit will
1365 // replace it with a <font> tag (!). If you delete all the text inside a
1366 // link in Opera, it won't delete the link. Let's make things consistent. If
1367 // you delete all text inside an inline tag, remove the inline tag.
1368 var afterDelete = function ( self, range ) {
1369 try {
1370 if ( !range ) { range = self.getSelection(); }
1371 var node = range.startContainer,
1372 parent;
1373 // Climb the tree from the focus point while we are inside an empty
1374 // inline element
1375 if ( node.nodeType === TEXT_NODE ) {
1376 node = node.parentNode;
1377 }
1378 parent = node;
1379 while ( isInline( parent ) &&
1380 ( !parent.textContent || parent.textContent === ZWS ) ) {
1381 node = parent;
1382 parent = node.parentNode;
1383 }
1384 // If focused in empty inline element
1385 if ( node !== parent ) {
1386 // Move focus to just before empty inline(s)
1387 range.setStart( parent,
1388 indexOf.call( parent.childNodes, node ) );
1389 range.collapse( true );
1390 // Remove empty inline(s)
1391 parent.removeChild( node );
1392 // Fix cursor in block
1393 if ( !isBlock( parent ) ) {
1394 parent = getPreviousBlock( parent, self._root );
1395 }
1396 fixCursor( parent, self._root );
1397 // Move cursor into text node
1398 moveRangeBoundariesDownTree( range );
1399 }
1400 // If you delete the last character in the sole <div> in Chrome,
1401 // it removes the div and replaces it with just a <br> inside the
1402 // root. Detach the <br>; the _ensureBottomLine call will insert a new
1403 // block.
1404 if ( node === self._root &&
1405 ( node = node.firstChild ) && node.nodeName === 'BR' ) {
1406 detach( node );
1407 }
1408 self._ensureBottomLine();
1409 self.setSelection( range );
1410 self._updatePath( range, true );
1411 } catch ( error ) {
1412 self.didError( error );
1413 }
1414 };
1415
1416 var keyHandlers = {
1417 enter: function ( self, event, range ) {
1418 var root = self._root;
1419 var block, parent, nodeAfterSplit;
1420
1421 // We handle this ourselves
1422 event.preventDefault();
1423
1424 // Save undo checkpoint and add any links in the preceding section.
1425 // Remove any zws so we don't think there's content in an empty
1426 // block.
1427 self._recordUndoState( range );
1428 addLinks( range.startContainer, root, self );
1429 self._removeZWS();
1430 self._getRangeAndRemoveBookmark( range );
1431
1432 // Selected text is overwritten, therefore delete the contents
1433 // to collapse selection.
1434 if ( !range.collapsed ) {
1435 deleteContentsOfRange( range, root );
1436 }
1437
1438 block = getStartBlockOfRange( range, root );
1439
1440 // If this is a malformed bit of document or in a table;
1441 // just play it safe and insert a <br>.
1442 if ( !block || /^T[HD]$/.test( block.nodeName ) ) {
1443 // If inside an <a>, move focus out
1444 parent = getNearest( range.endContainer, root, 'A' );
1445 if ( parent ) {
1446 parent = parent.parentNode;
1447 moveRangeBoundariesUpTree( range, parent, parent, root );
1448 range.collapse( false );
1449 }
1450 insertNodeInRange( range, self.createElement( 'BR' ) );
1451 range.collapse( false );
1452 self.setSelection( range );
1453 self._updatePath( range, true );
1454 return;
1455 }
1456
1457 // If in a list, we'll split the LI instead.
1458 if ( parent = getNearest( block, root, 'LI' ) ) {
1459 block = parent;
1460 }
1461
1462 if ( isEmptyBlock( block ) ) {
1463 // Break list
1464 if ( getNearest( block, root, 'UL' ) ||
1465 getNearest( block, root, 'OL' ) ) {
1466 return self.decreaseListLevel( range );
1467 }
1468 // Break blockquote
1469 else if ( getNearest( block, root, 'BLOCKQUOTE' ) ) {
1470 return self.modifyBlocks( removeBlockQuote, range );
1471 }
1472 }
1473
1474 // Otherwise, split at cursor point.
1475 nodeAfterSplit = splitBlock( self, block,
1476 range.startContainer, range.startOffset );
1477
1478 // Clean up any empty inlines if we hit enter at the beginning of the
1479 // block
1480 removeZWS( block );
1481 removeEmptyInlines( block );
1482 fixCursor( block, root );
1483
1484 // Focus cursor
1485 // If there's a <b>/<i> etc. at the beginning of the split
1486 // make sure we focus inside it.
1487 while ( nodeAfterSplit.nodeType === ELEMENT_NODE ) {
1488 var child = nodeAfterSplit.firstChild,
1489 next;
1490
1491 // Don't continue links over a block break; unlikely to be the
1492 // desired outcome.
1493 if ( nodeAfterSplit.nodeName === 'A' &&
1494 ( !nodeAfterSplit.textContent ||
1495 nodeAfterSplit.textContent === ZWS ) ) {
1496 child = self._doc.createTextNode( '' );
1497 replaceWith( nodeAfterSplit, child );
1498 nodeAfterSplit = child;
1499 break;
1500 }
1501
1502 while ( child && child.nodeType === TEXT_NODE && !child.data ) {
1503 next = child.nextSibling;
1504 if ( !next || next.nodeName === 'BR' ) {
1505 break;
1506 }
1507 detach( child );
1508 child = next;
1509 }
1510
1511 // 'BR's essentially don't count; they're a browser hack.
1512 // If you try to select the contents of a 'BR', FF will not let
1513 // you type anything!
1514 if ( !child || child.nodeName === 'BR' ||
1515 ( child.nodeType === TEXT_NODE && !isPresto ) ) {
1516 break;
1517 }
1518 nodeAfterSplit = child;
1519 }
1520 range = self._createRange( nodeAfterSplit, 0 );
1521 self.setSelection( range );
1522 self._updatePath( range, true );
1523 },
1524 backspace: function ( self, event, range ) {
1525 var root = self._root;
1526 self._removeZWS();
1527 // Record undo checkpoint.
1528 self.saveUndoState( range );
1529 // If not collapsed, delete contents
1530 if ( !range.collapsed ) {
1531 event.preventDefault();
1532 deleteContentsOfRange( range, root );
1533 afterDelete( self, range );
1534 }
1535 // If at beginning of block, merge with previous
1536 else if ( rangeDoesStartAtBlockBoundary( range, root ) ) {
1537 event.preventDefault();
1538 var current = getStartBlockOfRange( range, root );
1539 var previous;
1540 if ( !current ) {
1541 return;
1542 }
1543 // In case inline data has somehow got between blocks.
1544 fixContainer( current.parentNode, root );
1545 // Now get previous block
1546 previous = getPreviousBlock( current, root );
1547 // Must not be at the very beginning of the text area.
1548 if ( previous ) {
1549 // If not editable, just delete whole block.
1550 if ( !previous.isContentEditable ) {
1551 detach( previous );
1552 return;
1553 }
1554 // Otherwise merge.
1555 mergeWithBlock( previous, current, range, root );
1556 // If deleted line between containers, merge newly adjacent
1557 // containers.
1558 current = previous.parentNode;
1559 while ( current !== root && !current.nextSibling ) {
1560 current = current.parentNode;
1561 }
1562 if ( current !== root && ( current = current.nextSibling ) ) {
1563 mergeContainers( current, root );
1564 }
1565 self.setSelection( range );
1566 }
1567 // If at very beginning of text area, allow backspace
1568 // to break lists/blockquote.
1569 else if ( current ) {
1570 // Break list
1571 if ( getNearest( current, root, 'UL' ) ||
1572 getNearest( current, root, 'OL' ) ) {
1573 return self.decreaseListLevel( range );
1574 }
1575 // Break blockquote
1576 else if ( getNearest( current, root, 'BLOCKQUOTE' ) ) {
1577 return self.modifyBlocks( decreaseBlockQuoteLevel, range );
1578 }
1579 self.setSelection( range );
1580 self._updatePath( range, true );
1581 }
1582 }
1583 // Otherwise, leave to browser but check afterwards whether it has
1584 // left behind an empty inline tag.
1585 else {
1586 self.setSelection( range );
1587 setTimeout( function () { afterDelete( self ); }, 0 );
1588 }
1589 },
1590 'delete': function ( self, event, range ) {
1591 var root = self._root;
1592 var current, next, originalRange,
1593 cursorContainer, cursorOffset, nodeAfterCursor;
1594 self._removeZWS();
1595 // Record undo checkpoint.
1596 self.saveUndoState( range );
1597 // If not collapsed, delete contents
1598 if ( !range.collapsed ) {
1599 event.preventDefault();
1600 deleteContentsOfRange( range, root );
1601 afterDelete( self, range );
1602 }
1603 // If at end of block, merge next into this block
1604 else if ( rangeDoesEndAtBlockBoundary( range, root ) ) {
1605 event.preventDefault();
1606 current = getStartBlockOfRange( range, root );
1607 if ( !current ) {
1608 return;
1609 }
1610 // In case inline data has somehow got between blocks.
1611 fixContainer( current.parentNode, root );
1612 // Now get next block
1613 next = getNextBlock( current, root );
1614 // Must not be at the very end of the text area.
1615 if ( next ) {
1616 // If not editable, just delete whole block.
1617 if ( !next.isContentEditable ) {
1618 detach( next );
1619 return;
1620 }
1621 // Otherwise merge.
1622 mergeWithBlock( current, next, range, root );
1623 // If deleted line between containers, merge newly adjacent
1624 // containers.
1625 next = current.parentNode;
1626 while ( next !== root && !next.nextSibling ) {
1627 next = next.parentNode;
1628 }
1629 if ( next !== root && ( next = next.nextSibling ) ) {
1630 mergeContainers( next, root );
1631 }
1632 self.setSelection( range );
1633 self._updatePath( range, true );
1634 }
1635 }
1636 // Otherwise, leave to browser but check afterwards whether it has
1637 // left behind an empty inline tag.
1638 else {
1639 // But first check if the cursor is just before an IMG tag. If so,
1640 // delete it ourselves, because the browser won't if it is not
1641 // inline.
1642 originalRange = range.cloneRange();
1643 moveRangeBoundariesUpTree( range, root, root, root );
1644 cursorContainer = range.endContainer;
1645 cursorOffset = range.endOffset;
1646 if ( cursorContainer.nodeType === ELEMENT_NODE ) {
1647 nodeAfterCursor = cursorContainer.childNodes[ cursorOffset ];
1648 if ( nodeAfterCursor && nodeAfterCursor.nodeName === 'IMG' ) {
1649 event.preventDefault();
1650 detach( nodeAfterCursor );
1651 moveRangeBoundariesDownTree( range );
1652 afterDelete( self, range );
1653 return;
1654 }
1655 }
1656 self.setSelection( originalRange );
1657 setTimeout( function () { afterDelete( self ); }, 0 );
1658 }
1659 },
1660 tab: function ( self, event, range ) {
1661 var root = self._root;
1662 var node, parent;
1663 self._removeZWS();
1664 // If no selection and at start of block
1665 if ( range.collapsed && rangeDoesStartAtBlockBoundary( range, root ) ) {
1666 node = getStartBlockOfRange( range, root );
1667 // Iterate through the block's parents
1668 while ( ( parent = node.parentNode ) ) {
1669 // If we find a UL or OL (so are in a list, node must be an LI)
1670 if ( parent.nodeName === 'UL' || parent.nodeName === 'OL' ) {
1671 // Then increase the list level
1672 event.preventDefault();
1673 self.increaseListLevel( range );
1674 break;
1675 }
1676 node = parent;
1677 }
1678 }
1679 },
1680 'shift-tab': function ( self, event, range ) {
1681 var root = self._root;
1682 var node;
1683 self._removeZWS();
1684 // If no selection and at start of block
1685 if ( range.collapsed && rangeDoesStartAtBlockBoundary( range, root ) ) {
1686 // Break list
1687 node = range.startContainer;
1688 if ( getNearest( node, root, 'UL' ) ||
1689 getNearest( node, root, 'OL' ) ) {
1690 event.preventDefault();
1691 self.decreaseListLevel( range );
1692 }
1693 }
1694 },
1695 space: function ( self, _, range ) {
1696 var node, parent;
1697 self._recordUndoState( range );
1698 addLinks( range.startContainer, self._root, self );
1699 self._getRangeAndRemoveBookmark( range );
1700
1701 // If the cursor is at the end of a link (<a>foo|</a>) then move it
1702 // outside of the link (<a>foo</a>|) so that the space is not part of
1703 // the link text.
1704 node = range.endContainer;
1705 parent = node.parentNode;
1706 if ( range.collapsed && parent.nodeName === 'A' &&
1707 !node.nextSibling && range.endOffset === getLength( node ) ) {
1708 range.setStartAfter( parent );
1709 }
1710 // Delete the selection if not collapsed
1711 else if ( !range.collapsed ) {
1712 deleteContentsOfRange( range, self._root );
1713 self._ensureBottomLine();
1714 self.setSelection( range );
1715 self._updatePath( range, true );
1716 }
1717
1718 self.setSelection( range );
1719 },
1720 left: function ( self ) {
1721 self._removeZWS();
1722 },
1723 right: function ( self ) {
1724 self._removeZWS();
1725 }
1726 };
1727
1728 // Firefox pre v29 incorrectly handles Cmd-left/Cmd-right on Mac:
1729 // it goes back/forward in history! Override to do the right
1730 // thing.
1731 // https://bugzilla.mozilla.org/show_bug.cgi?id=289384
1732 if ( isMac && isGecko ) {
1733 keyHandlers[ 'meta-left' ] = function ( self, event ) {
1734 event.preventDefault();
1735 var sel = getWindowSelection( self );
1736 if ( sel && sel.modify ) {
1737 sel.modify( 'move', 'backward', 'lineboundary' );
1738 }
1739 };
1740 keyHandlers[ 'meta-right' ] = function ( self, event ) {
1741 event.preventDefault();
1742 var sel = getWindowSelection( self );
1743 if ( sel && sel.modify ) {
1744 sel.modify( 'move', 'forward', 'lineboundary' );
1745 }
1746 };
1747 }
1748
1749 // System standard for page up/down on Mac is to just scroll, not move the
1750 // cursor. On Linux/Windows, it should move the cursor, but some browsers don't
1751 // implement this natively. Override to support it.
1752 if ( !isMac ) {
1753 keyHandlers.pageup = function ( self ) {
1754 self.moveCursorToStart();
1755 };
1756 keyHandlers.pagedown = function ( self ) {
1757 self.moveCursorToEnd();
1758 };
1759 }
1760
1761 keyHandlers[ ctrlKey + 'b' ] = mapKeyToFormat( 'B' );
1762 keyHandlers[ ctrlKey + 'i' ] = mapKeyToFormat( 'I' );
1763 keyHandlers[ ctrlKey + 'u' ] = mapKeyToFormat( 'U' );
1764 keyHandlers[ ctrlKey + 'shift-7' ] = mapKeyToFormat( 'S' );
1765 keyHandlers[ ctrlKey + 'shift-5' ] = mapKeyToFormat( 'SUB', { tag: 'SUP' } );
1766 keyHandlers[ ctrlKey + 'shift-6' ] = mapKeyToFormat( 'SUP', { tag: 'SUB' } );
1767 keyHandlers[ ctrlKey + 'shift-8' ] = mapKeyTo( 'makeUnorderedList' );
1768 keyHandlers[ ctrlKey + 'shift-9' ] = mapKeyTo( 'makeOrderedList' );
1769 keyHandlers[ ctrlKey + '[' ] = mapKeyTo( 'decreaseQuoteLevel' );
1770 keyHandlers[ ctrlKey + ']' ] = mapKeyTo( 'increaseQuoteLevel' );
1771 keyHandlers[ ctrlKey + 'y' ] = mapKeyTo( 'redo' );
1772 keyHandlers[ ctrlKey + 'z' ] = mapKeyTo( 'undo' );
1773 keyHandlers[ ctrlKey + 'shift-z' ] = mapKeyTo( 'redo' );
1774
1775 var fontSizes = {
1776 1: 10,
1777 2: 13,
1778 3: 16,
1779 4: 18,
1780 5: 24,
1781 6: 32,
1782 7: 48
1783 };
1784
1785 var styleToSemantic = {
1786 backgroundColor: {
1787 regexp: notWS,
1788 replace: function ( doc, colour ) {
1789 return createElement( doc, 'SPAN', {
1790 'class': HIGHLIGHT_CLASS,
1791 style: 'background-color:' + colour
1792 });
1793 }
1794 },
1795 color: {
1796 regexp: notWS,
1797 replace: function ( doc, colour ) {
1798 return createElement( doc, 'SPAN', {
1799 'class': COLOUR_CLASS,
1800 style: 'color:' + colour
1801 });
1802 }
1803 },
1804 fontWeight: {
1805 regexp: /^bold|^700/i,
1806 replace: function ( doc ) {
1807 return createElement( doc, 'B' );
1808 }
1809 },
1810 fontStyle: {
1811 regexp: /^italic/i,
1812 replace: function ( doc ) {
1813 return createElement( doc, 'I' );
1814 }
1815 },
1816 fontFamily: {
1817 regexp: notWS,
1818 replace: function ( doc, family ) {
1819 return createElement( doc, 'SPAN', {
1820 'class': FONT_FAMILY_CLASS,
1821 style: 'font-family:' + family
1822 });
1823 }
1824 },
1825 fontSize: {
1826 regexp: notWS,
1827 replace: function ( doc, size ) {
1828 return createElement( doc, 'SPAN', {
1829 'class': FONT_SIZE_CLASS,
1830 style: 'font-size:' + size
1831 });
1832 }
1833 },
1834 textDecoration: {
1835 regexp: /^underline/i,
1836 replace: function ( doc ) {
1837 return createElement( doc, 'U' );
1838 }
1839 }
1840 };
1841
1842 var replaceWithTag = function ( tag ) {
1843 return function ( node, parent ) {
1844 var el = createElement( node.ownerDocument, tag );
1845 parent.replaceChild( el, node );
1846 el.appendChild( empty( node ) );
1847 return el;
1848 };
1849 };
1850
1851 var replaceStyles = function ( node, parent ) {
1852 var style = node.style;
1853 var doc = node.ownerDocument;
1854 var attr, converter, css, newTreeBottom, newTreeTop, el;
1855
1856 for ( attr in styleToSemantic ) {
1857 converter = styleToSemantic[ attr ];
1858 css = style[ attr ];
1859 if ( css && converter.regexp.test( css ) ) {
1860 el = converter.replace( doc, css );
1861 if ( !newTreeTop ) {
1862 newTreeTop = el;
1863 }
1864 if ( newTreeBottom ) {
1865 newTreeBottom.appendChild( el );
1866 }
1867 newTreeBottom = el;
1868 node.style[ attr ] = '';
1869 }
1870 }
1871
1872 if ( newTreeTop ) {
1873 newTreeBottom.appendChild( empty( node ) );
1874 if ( node.nodeName === 'SPAN' ) {
1875 parent.replaceChild( newTreeTop, node );
1876 } else {
1877 node.appendChild( newTreeTop );
1878 }
1879 }
1880
1881 return newTreeBottom || node;
1882 };
1883
1884 var stylesRewriters = {
1885 P: replaceStyles,
1886 SPAN: replaceStyles,
1887 STRONG: replaceWithTag( 'B' ),
1888 EM: replaceWithTag( 'I' ),
1889 INS: replaceWithTag( 'U' ),
1890 STRIKE: replaceWithTag( 'S' ),
1891 FONT: function ( node, parent ) {
1892 var face = node.face,
1893 size = node.size,
1894 colour = node.color,
1895 doc = node.ownerDocument,
1896 fontSpan, sizeSpan, colourSpan,
1897 newTreeBottom, newTreeTop;
1898 if ( face ) {
1899 fontSpan = createElement( doc, 'SPAN', {
1900 'class': FONT_FAMILY_CLASS,
1901 style: 'font-family:' + face
1902 });
1903 newTreeTop = fontSpan;
1904 newTreeBottom = fontSpan;
1905 }
1906 if ( size ) {
1907 sizeSpan = createElement( doc, 'SPAN', {
1908 'class': FONT_SIZE_CLASS,
1909 style: 'font-size:' + fontSizes[ size ] + 'px'
1910 });
1911 if ( !newTreeTop ) {
1912 newTreeTop = sizeSpan;
1913 }
1914 if ( newTreeBottom ) {
1915 newTreeBottom.appendChild( sizeSpan );
1916 }
1917 newTreeBottom = sizeSpan;
1918 }
1919 if ( colour && /^#?([\dA-F]{3}){1,2}$/i.test( colour ) ) {
1920 if ( colour.charAt( 0 ) !== '#' ) {
1921 colour = '#' + colour;
1922 }
1923 colourSpan = createElement( doc, 'SPAN', {
1924 'class': COLOUR_CLASS,
1925 style: 'color:' + colour
1926 });
1927 if ( !newTreeTop ) {
1928 newTreeTop = colourSpan;
1929 }
1930 if ( newTreeBottom ) {
1931 newTreeBottom.appendChild( colourSpan );
1932 }
1933 newTreeBottom = colourSpan;
1934 }
1935 if ( !newTreeTop ) {
1936 newTreeTop = newTreeBottom = createElement( doc, 'SPAN' );
1937 }
1938 parent.replaceChild( newTreeTop, node );
1939 newTreeBottom.appendChild( empty( node ) );
1940 return newTreeBottom;
1941 },
1942 TT: function ( node, parent ) {
1943 var el = createElement( node.ownerDocument, 'SPAN', {
1944 'class': FONT_FAMILY_CLASS,
1945 style: 'font-family:menlo,consolas,"courier new",monospace'
1946 });
1947 parent.replaceChild( el, node );
1948 el.appendChild( empty( node ) );
1949 return el;
1950 }
1951 };
1952
1953 var allowedBlock = /^(?:A(?:DDRESS|RTICLE|SIDE|UDIO)|BLOCKQUOTE|CAPTION|D(?:[DLT]|IV)|F(?:IGURE|IGCAPTION|OOTER)|H[1-6]|HEADER|L(?:ABEL|EGEND|I)|O(?:L|UTPUT)|P(?:RE)?|SECTION|T(?:ABLE|BODY|D|FOOT|H|HEAD|R)|COL(?:GROUP)?|UL)$/;
1954
1955 var blacklist = /^(?:HEAD|META|STYLE)/;
1956
1957 var walker = new TreeWalker( null, SHOW_TEXT|SHOW_ELEMENT, function () {
1958 return true;
1959 });
1960
1961 /*
1962 Two purposes:
1963
1964 1. Remove nodes we don't want, such as weird <o:p> tags, comment nodes
1965 and whitespace nodes.
1966 2. Convert inline tags into our preferred format.
1967 */
1968 var cleanTree = function cleanTree ( node, preserveWS ) {
1969 var children = node.childNodes,
1970 nonInlineParent, i, l, child, nodeName, nodeType, rewriter, childLength,
1971 startsWithWS, endsWithWS, data, sibling;
1972
1973 nonInlineParent = node;
1974 while ( isInline( nonInlineParent ) ) {
1975 nonInlineParent = nonInlineParent.parentNode;
1976 }
1977 walker.root = nonInlineParent;
1978
1979 for ( i = 0, l = children.length; i < l; i += 1 ) {
1980 child = children[i];
1981 nodeName = child.nodeName;
1982 nodeType = child.nodeType;
1983 rewriter = stylesRewriters[ nodeName ];
1984 if ( nodeType === ELEMENT_NODE ) {
1985 childLength = child.childNodes.length;
1986 if ( rewriter ) {
1987 child = rewriter( child, node );
1988 } else if ( blacklist.test( nodeName ) ) {
1989 node.removeChild( child );
1990 i -= 1;
1991 l -= 1;
1992 continue;
1993 } else if ( !allowedBlock.test( nodeName ) && !isInline( child ) ) {
1994 i -= 1;
1995 l += childLength - 1;
1996 node.replaceChild( empty( child ), child );
1997 continue;
1998 }
1999 if ( childLength ) {
2000 cleanTree( child, preserveWS || ( nodeName === 'PRE' ) );
2001 }
2002 } else {
2003 if ( nodeType === TEXT_NODE ) {
2004 data = child.data;
2005 startsWithWS = !notWS.test( data.charAt( 0 ) );
2006 endsWithWS = !notWS.test( data.charAt( data.length - 1 ) );
2007 if ( preserveWS || ( !startsWithWS && !endsWithWS ) ) {
2008 continue;
2009 }
2010 // Iterate through the nodes; if we hit some other content
2011 // before the start of a new block we don't trim
2012 if ( startsWithWS ) {
2013 walker.currentNode = child;
2014 while ( sibling = walker.previousPONode() ) {
2015 nodeName = sibling.nodeName;
2016 if ( nodeName === 'IMG' ||
2017 ( nodeName === '#text' &&
2018 notWS.test( sibling.data ) ) ) {
2019 break;
2020 }
2021 if ( !isInline( sibling ) ) {
2022 sibling = null;
2023 break;
2024 }
2025 }
2026 data = data.replace( /^[ \t\r\n]+/g, sibling ? ' ' : '' );
2027 }
2028 if ( endsWithWS ) {
2029 walker.currentNode = child;
2030 while ( sibling = walker.nextNode() ) {
2031 if ( nodeName === 'IMG' ||
2032 ( nodeName === '#text' &&
2033 notWS.test( sibling.data ) ) ) {
2034 break;
2035 }
2036 if ( !isInline( sibling ) ) {
2037 sibling = null;
2038 break;
2039 }
2040 }
2041 data = data.replace( /[ \t\r\n]+$/g, sibling ? ' ' : '' );
2042 }
2043 if ( data ) {
2044 child.data = data;
2045 continue;
2046 }
2047 }
2048 node.removeChild( child );
2049 i -= 1;
2050 l -= 1;
2051 }
2052 }
2053 return node;
2054 };
2055
2056 // ---
2057
2058 var removeEmptyInlines = function removeEmptyInlines ( node ) {
2059 var children = node.childNodes,
2060 l = children.length,
2061 child;
2062 while ( l-- ) {
2063 child = children[l];
2064 if ( child.nodeType === ELEMENT_NODE && !isLeaf( child ) ) {
2065 removeEmptyInlines( child );
2066 if ( isInline( child ) && !child.firstChild ) {
2067 node.removeChild( child );
2068 }
2069 } else if ( child.nodeType === TEXT_NODE && !child.data ) {
2070 node.removeChild( child );
2071 }
2072 }
2073 };
2074
2075 // ---
2076
2077 var notWSTextNode = function ( node ) {
2078 return node.nodeType === ELEMENT_NODE ?
2079 node.nodeName === 'BR' :
2080 notWS.test( node.data );
2081 };
2082 var isLineBreak = function ( br, isLBIfEmptyBlock ) {
2083 var block = br.parentNode;
2084 var walker;
2085 while ( isInline( block ) ) {
2086 block = block.parentNode;
2087 }
2088 walker = new TreeWalker(
2089 block, SHOW_ELEMENT|SHOW_TEXT, notWSTextNode );
2090 walker.currentNode = br;
2091 return !!walker.nextNode() ||
2092 ( isLBIfEmptyBlock && !walker.previousNode() );
2093 };
2094
2095 // <br> elements are treated specially, and differently depending on the
2096 // browser, when in rich text editor mode. When adding HTML from external
2097 // sources, we must remove them, replacing the ones that actually affect
2098 // line breaks by wrapping the inline text in a <div>. Browsers that want <br>
2099 // elements at the end of each block will then have them added back in a later
2100 // fixCursor method call.
2101 var cleanupBRs = function ( node, root, keepForBlankLine ) {
2102 var brs = node.querySelectorAll( 'BR' );
2103 var brBreaksLine = [];
2104 var l = brs.length;
2105 var i, br, parent;
2106
2107 // Must calculate whether the <br> breaks a line first, because if we
2108 // have two <br>s next to each other, after the first one is converted
2109 // to a block split, the second will be at the end of a block and
2110 // therefore seem to not be a line break. But in its original context it
2111 // was, so we should also convert it to a block split.
2112 for ( i = 0; i < l; i += 1 ) {
2113 brBreaksLine[i] = isLineBreak( brs[i], keepForBlankLine );
2114 }
2115 while ( l-- ) {
2116 br = brs[l];
2117 // Cleanup may have removed it
2118 parent = br.parentNode;
2119 if ( !parent ) { continue; }
2120 // If it doesn't break a line, just remove it; it's not doing
2121 // anything useful. We'll add it back later if required by the
2122 // browser. If it breaks a line, wrap the content in div tags
2123 // and replace the brs.
2124 if ( !brBreaksLine[l] ) {
2125 detach( br );
2126 } else if ( !isInline( parent ) ) {
2127 fixContainer( parent, root );
2128 }
2129 }
2130 };
2131
2132 // The (non-standard but supported enough) innerText property is based on the
2133 // render tree in Firefox and possibly other browsers, so we must insert the
2134 // DOM node into the document to ensure the text part is correct.
2135 var setClipboardData = function ( clipboardData, node, root ) {
2136 var body = node.ownerDocument.body;
2137 var html, text;
2138
2139 // Firefox will add an extra new line for BRs at the end of block when
2140 // calculating innerText, even though they don't actually affect display.
2141 // So we need to remove them first.
2142 cleanupBRs( node, root, true );
2143
2144 node.setAttribute( 'style',
2145 'position:fixed;overflow:hidden;bottom:100%;right:100%;' );
2146 body.appendChild( node );
2147 html = node.innerHTML;
2148 text = node.innerText || node.textContent;
2149
2150 // Firefox (and others?) returns unix line endings (\n) even on Windows.
2151 // If on Windows, normalise to \r\n, since Notepad and some other crappy
2152 // apps do not understand just \n.
2153 if ( isWin ) {
2154 text = text.replace( /\r?\n/g, '\r\n' );
2155 }
2156
2157 clipboardData.setData( 'text/html', html );
2158 clipboardData.setData( 'text/plain', text );
2159
2160 body.removeChild( node );
2161 };
2162
2163 var onCut = function ( event ) {
2164 var clipboardData = event.clipboardData;
2165 var range = this.getSelection();
2166 var root = this._root;
2167 var self = this;
2168 var startBlock, endBlock, copyRoot, contents, parent, newContents, node;
2169
2170 // Nothing to do
2171 if ( range.collapsed ) {
2172 event.preventDefault();
2173 return;
2174 }
2175
2176 // Save undo checkpoint
2177 this.saveUndoState( range );
2178
2179 // Edge only seems to support setting plain text as of 2016-03-11.
2180 // Mobile Safari flat out doesn't work:
2181 // https://bugs.webkit.org/show_bug.cgi?id=143776
2182 if ( !isEdge && !isIOS && clipboardData ) {
2183 // Clipboard content should include all parents within block, or all
2184 // parents up to root if selection across blocks
2185 startBlock = getStartBlockOfRange( range, root );
2186 endBlock = getEndBlockOfRange( range, root );
2187 copyRoot = ( ( startBlock === endBlock ) && startBlock ) || root;
2188 // Extract the contents
2189 contents = deleteContentsOfRange( range, root );
2190 // Add any other parents not in extracted content, up to copy root
2191 parent = range.commonAncestorContainer;
2192 if ( parent.nodeType === TEXT_NODE ) {
2193 parent = parent.parentNode;
2194 }
2195 while ( parent && parent !== copyRoot ) {
2196 newContents = parent.cloneNode( false );
2197 newContents.appendChild( contents );
2198 contents = newContents;
2199 parent = parent.parentNode;
2200 }
2201 // Set clipboard data
2202 node = this.createElement( 'div' );
2203 node.appendChild( contents );
2204 setClipboardData( clipboardData, node, root );
2205 event.preventDefault();
2206 } else {
2207 setTimeout( function () {
2208 try {
2209 // If all content removed, ensure div at start of root.
2210 self._ensureBottomLine();
2211 } catch ( error ) {
2212 self.didError( error );
2213 }
2214 }, 0 );
2215 }
2216
2217 this.setSelection( range );
2218 };
2219
2220 var onCopy = function ( event ) {
2221 var clipboardData = event.clipboardData;
2222 var range = this.getSelection();
2223 var root = this._root;
2224 var startBlock, endBlock, copyRoot, contents, parent, newContents, node;
2225
2226 // Edge only seems to support setting plain text as of 2016-03-11.
2227 // Mobile Safari flat out doesn't work:
2228 // https://bugs.webkit.org/show_bug.cgi?id=143776
2229 if ( !isEdge && !isIOS && clipboardData ) {
2230 // Clipboard content should include all parents within block, or all
2231 // parents up to root if selection across blocks
2232 startBlock = getStartBlockOfRange( range, root );
2233 endBlock = getEndBlockOfRange( range, root );
2234 copyRoot = ( ( startBlock === endBlock ) && startBlock ) || root;
2235 // Clone range to mutate, then move up as high as possible without
2236 // passing the copy root node.
2237 range = range.cloneRange();
2238 moveRangeBoundariesDownTree( range );
2239 moveRangeBoundariesUpTree( range, copyRoot, copyRoot, root );
2240 // Extract the contents
2241 contents = range.cloneContents();
2242 // Add any other parents not in extracted content, up to copy root
2243 parent = range.commonAncestorContainer;
2244 if ( parent.nodeType === TEXT_NODE ) {
2245 parent = parent.parentNode;
2246 }
2247 while ( parent && parent !== copyRoot ) {
2248 newContents = parent.cloneNode( false );
2249 newContents.appendChild( contents );
2250 contents = newContents;
2251 parent = parent.parentNode;
2252 }
2253 // Set clipboard data
2254 node = this.createElement( 'div' );
2255 node.appendChild( contents );
2256 setClipboardData( clipboardData, node, root );
2257 event.preventDefault();
2258 }
2259 };
2260
2261 // Need to monitor for shift key like this, as event.shiftKey is not available
2262 // in paste event.
2263 function monitorShiftKey ( event ) {
2264 this.isShiftDown = event.shiftKey;
2265 }
2266
2267 var onPaste = function ( event ) {
2268 var clipboardData = event.clipboardData;
2269 var items = clipboardData && clipboardData.items;
2270 var choosePlain = this.isShiftDown;
2271 var fireDrop = false;
2272 var hasImage = false;
2273 var plainItem = null;
2274 var self = this;
2275 var l, item, type, types, data;
2276
2277 // Current HTML5 Clipboard interface
2278 // ---------------------------------
2279 // https://html.spec.whatwg.org/multipage/interaction.html
2280
2281 // Edge only provides access to plain text as of 2016-03-11 and gives no
2282 // indication there should be an HTML part. However, it does support access
2283 // to image data, so check if this is present and use if so.
2284 if ( isEdge && items ) {
2285 l = items.length;
2286 while ( l-- ) {
2287 if ( !choosePlain && /^image\/.*/.test( items[l].type ) ) {
2288 hasImage = true;
2289 }
2290 }
2291 if ( !hasImage ) {
2292 items = null;
2293 }
2294 }
2295 if ( items ) {
2296 event.preventDefault();
2297 l = items.length;
2298 while ( l-- ) {
2299 item = items[l];
2300 type = item.type;
2301 if ( !choosePlain && type === 'text/html' ) {
2302 /*jshint loopfunc: true */
2303 item.getAsString( function ( html ) {
2304 self.insertHTML( html, true );
2305 });
2306 /*jshint loopfunc: false */
2307 return;
2308 }
2309 if ( type === 'text/plain' ) {
2310 plainItem = item;
2311 }
2312 if ( !choosePlain && /^image\/.*/.test( type ) ) {
2313 hasImage = true;
2314 }
2315 }
2316 // Treat image paste as a drop of an image file.
2317 if ( hasImage ) {
2318 this.fireEvent( 'dragover', {
2319 dataTransfer: clipboardData,
2320 /*jshint loopfunc: true */
2321 preventDefault: function () {
2322 fireDrop = true;
2323 }
2324 /*jshint loopfunc: false */
2325 });
2326 if ( fireDrop ) {
2327 this.fireEvent( 'drop', {
2328 dataTransfer: clipboardData
2329 });
2330 }
2331 } else if ( plainItem ) {
2332 plainItem.getAsString( function ( text ) {
2333 self.insertPlainText( text, true );
2334 });
2335 }
2336 return;
2337 }
2338
2339 // Old interface
2340 // -------------
2341
2342 // Safari (and indeed many other OS X apps) copies stuff as text/rtf
2343 // rather than text/html; even from a webpage in Safari. The only way
2344 // to get an HTML version is to fallback to letting the browser insert
2345 // the content. Same for getting image data. *Sigh*.
2346 //
2347 // Firefox is even worse: it doesn't even let you know that there might be
2348 // an RTF version on the clipboard, but it will also convert to HTML if you
2349 // let the browser insert the content. I've filed
2350 // https://bugzilla.mozilla.org/show_bug.cgi?id=1254028
2351 types = clipboardData && clipboardData.types;
2352 if ( !isEdge && types && (
2353 indexOf.call( types, 'text/html' ) > -1 || (
2354 !isGecko &&
2355 indexOf.call( types, 'text/plain' ) > -1 &&
2356 indexOf.call( types, 'text/rtf' ) < 0 )
2357 )) {
2358 event.preventDefault();
2359 // Abiword on Linux copies a plain text and html version, but the HTML
2360 // version is the empty string! So always try to get HTML, but if none,
2361 // insert plain text instead. On iOS, Facebook (and possibly other
2362 // apps?) copy links as type text/uri-list, but also insert a **blank**
2363 // text/plain item onto the clipboard. Why? Who knows.
2364 if ( !choosePlain && ( data = clipboardData.getData( 'text/html' ) ) ) {
2365 this.insertHTML( data, true );
2366 } else if (
2367 ( data = clipboardData.getData( 'text/plain' ) ) ||
2368 ( data = clipboardData.getData( 'text/uri-list' ) ) ) {
2369 this.insertPlainText( data, true );
2370 }
2371 return;
2372 }
2373
2374 // No interface. Includes all versions of IE :(
2375 // --------------------------------------------
2376
2377 this._awaitingPaste = true;
2378
2379 var body = this._doc.body,
2380 range = this.getSelection(),
2381 startContainer = range.startContainer,
2382 startOffset = range.startOffset,
2383 endContainer = range.endContainer,
2384 endOffset = range.endOffset;
2385
2386 // We need to position the pasteArea in the visible portion of the screen
2387 // to stop the browser auto-scrolling.
2388 var pasteArea = this.createElement( 'DIV', {
2389 contenteditable: 'true',
2390 style: 'position:fixed; overflow:hidden; top:0; right:100%; width:1px; height:1px;'
2391 });
2392 body.appendChild( pasteArea );
2393 range.selectNodeContents( pasteArea );
2394 this.setSelection( range );
2395
2396 // A setTimeout of 0 means this is added to the back of the
2397 // single javascript thread, so it will be executed after the
2398 // paste event.
2399 setTimeout( function () {
2400 try {
2401 // IE sometimes fires the beforepaste event twice; make sure it is
2402 // not run again before our after paste function is called.
2403 self._awaitingPaste = false;
2404
2405 // Get the pasted content and clean
2406 var html = '',
2407 next = pasteArea,
2408 first, range;
2409
2410 // #88: Chrome can apparently split the paste area if certain
2411 // content is inserted; gather them all up.
2412 while ( pasteArea = next ) {
2413 next = pasteArea.nextSibling;
2414 detach( pasteArea );
2415 // Safari and IE like putting extra divs around things.
2416 first = pasteArea.firstChild;
2417 if ( first && first === pasteArea.lastChild &&
2418 first.nodeName === 'DIV' ) {
2419 pasteArea = first;
2420 }
2421 html += pasteArea.innerHTML;
2422 }
2423
2424 range = self._createRange(
2425 startContainer, startOffset, endContainer, endOffset );
2426 self.setSelection( range );
2427
2428 if ( html ) {
2429 self.insertHTML( html, true );
2430 }
2431 } catch ( error ) {
2432 self.didError( error );
2433 }
2434 }, 0 );
2435 };
2436
2437 // On Windows you can drag an drop text. We can't handle this ourselves, because
2438 // as far as I can see, there's no way to get the drop insertion point. So just
2439 // save an undo state and hope for the best.
2440 var onDrop = function ( event ) {
2441 var types = event.dataTransfer.types;
2442 var l = types.length;
2443 var hasPlain = false;
2444 var hasHTML = false;
2445 while ( l-- ) {
2446 switch ( types[l] ) {
2447 case 'text/plain':
2448 hasPlain = true;
2449 break;
2450 case 'text/html':
2451 hasHTML = true;
2452 break;
2453 default:
2454 return;
2455 }
2456 }
2457 if ( hasHTML || hasPlain ) {
2458 this.saveUndoState();
2459 }
2460 };
2461
2462 function mergeObjects ( base, extras, mayOverride ) {
2463 var prop, value;
2464 if ( !base ) {
2465 base = {};
2466 }
2467 if ( extras ) {
2468 for ( prop in extras ) {
2469 if ( mayOverride || !( prop in base ) ) {
2470 value = extras[ prop ];
2471 base[ prop ] = ( value && value.constructor === Object ) ?
2472 mergeObjects( base[ prop ], value, mayOverride ) :
2473 value;
2474 }
2475 }
2476 }
2477 return base;
2478 }
2479
2480 function Squire ( root, config ) {
2481 if ( root.nodeType === DOCUMENT_NODE ) {
2482 root = root.body;
2483 }
2484 var doc = root.ownerDocument;
2485 var win = doc.defaultView;
2486 var mutation;
2487
2488 this._win = win;
2489 this._doc = doc;
2490 this._root = root;
2491
2492 this._events = {};
2493
2494 this._isFocused = false;
2495 this._lastSelection = null;
2496
2497 // IE loses selection state of iframe on blur, so make sure we
2498 // cache it just before it loses focus.
2499 if ( losesSelectionOnBlur ) {
2500 this.addEventListener( 'beforedeactivate', this.getSelection );
2501 }
2502
2503 this._hasZWS = false;
2504
2505 this._lastAnchorNode = null;
2506 this._lastFocusNode = null;
2507 this._path = '';
2508 this._willUpdatePath = false;
2509
2510 if ( 'onselectionchange' in doc ) {
2511 this.addEventListener( 'selectionchange', this._updatePathOnEvent );
2512 } else {
2513 this.addEventListener( 'keyup', this._updatePathOnEvent );
2514 this.addEventListener( 'mouseup', this._updatePathOnEvent );
2515 }
2516
2517 this._undoIndex = -1;
2518 this._undoStack = [];
2519 this._undoStackLength = 0;
2520 this._isInUndoState = false;
2521 this._ignoreChange = false;
2522 this._ignoreAllChanges = false;
2523
2524 if ( canObserveMutations ) {
2525 mutation = new MutationObserver( this._docWasChanged.bind( this ) );
2526 mutation.observe( root, {
2527 childList: true,
2528 attributes: true,
2529 characterData: true,
2530 subtree: true
2531 });
2532 this._mutation = mutation;
2533 } else {
2534 this.addEventListener( 'keyup', this._keyUpDetectChange );
2535 }
2536
2537 // On blur, restore focus except if the user taps or clicks to focus a
2538 // specific point. Can't actually use click event because focus happens
2539 // before click, so use mousedown/touchstart
2540 this._restoreSelection = false;
2541 this.addEventListener( 'blur', enableRestoreSelection );
2542 this.addEventListener( 'mousedown', disableRestoreSelection );
2543 this.addEventListener( 'touchstart', disableRestoreSelection );
2544 this.addEventListener( 'focus', restoreSelection );
2545
2546 // IE sometimes fires the beforepaste event twice; make sure it is not run
2547 // again before our after paste function is called.
2548 this._awaitingPaste = false;
2549 this.addEventListener( isIElt11 ? 'beforecut' : 'cut', onCut );
2550 this.addEventListener( 'copy', onCopy );
2551 this.addEventListener( 'keydown', monitorShiftKey );
2552 this.addEventListener( 'keyup', monitorShiftKey );
2553 this.addEventListener( isIElt11 ? 'beforepaste' : 'paste', onPaste );
2554 this.addEventListener( 'drop', onDrop );
2555
2556 // Opera does not fire keydown repeatedly.
2557 this.addEventListener( isPresto ? 'keypress' : 'keydown', onKey );
2558
2559 // Add key handlers
2560 this._keyHandlers = Object.create( keyHandlers );
2561
2562 // Override default properties
2563 this.setConfig( config );
2564
2565 // Fix IE<10's buggy implementation of Text#splitText.
2566 // If the split is at the end of the node, it doesn't insert the newly split
2567 // node into the document, and sets its value to undefined rather than ''.
2568 // And even if the split is not at the end, the original node is removed
2569 // from the document and replaced by another, rather than just having its
2570 // data shortened.
2571 // We used to feature test for this, but then found the feature test would
2572 // sometimes pass, but later on the buggy behaviour would still appear.
2573 // I think IE10 does not have the same bug, but it doesn't hurt to replace
2574 // its native fn too and then we don't need yet another UA category.
2575 if ( isIElt11 ) {
2576 win.Text.prototype.splitText = function ( offset ) {
2577 var afterSplit = this.ownerDocument.createTextNode(
2578 this.data.slice( offset ) ),
2579 next = this.nextSibling,
2580 parent = this.parentNode,
2581 toDelete = this.length - offset;
2582 if ( next ) {
2583 parent.insertBefore( afterSplit, next );
2584 } else {
2585 parent.appendChild( afterSplit );
2586 }
2587 if ( toDelete ) {
2588 this.deleteData( offset, toDelete );
2589 }
2590 return afterSplit;
2591 };
2592 }
2593
2594 root.setAttribute( 'contenteditable', 'true' );
2595
2596 // Remove Firefox's built-in controls
2597 try {
2598 doc.execCommand( 'enableObjectResizing', false, 'false' );
2599 doc.execCommand( 'enableInlineTableEditing', false, 'false' );
2600 } catch ( error ) {}
2601
2602 root.__squire__ = this;
2603
2604 // Need to register instance before calling setHTML, so that the fixCursor
2605 // function can lookup any default block tag options set.
2606 this.setHTML( '' );
2607 }
2608
2609 var proto = Squire.prototype;
2610
2611 var sanitizeToDOMFragment = function ( html, isPaste, self ) {
2612 var doc = self._doc;
2613 var frag = html ? DOMPurify.sanitize( html, {
2614 ALLOW_UNKNOWN_PROTOCOLS: true,
2615 WHOLE_DOCUMENT: false,
2616 RETURN_DOM: true,
2617 RETURN_DOM_FRAGMENT: true
2618 }) : null;
2619 return frag ? doc.importNode( frag, true ) : doc.createDocumentFragment();
2620 };
2621
2622 proto.setConfig = function ( config ) {
2623 config = mergeObjects({
2624 blockTag: 'DIV',
2625 blockAttributes: null,
2626 tagAttributes: {
2627 blockquote: null,
2628 ul: null,
2629 ol: null,
2630 li: null,
2631 a: null
2632 },
2633 leafNodeNames: leafNodeNames,
2634 undo: {
2635 documentSizeThreshold: -1, // -1 means no threshold
2636 undoLimit: -1 // -1 means no limit
2637 },
2638 isInsertedHTMLSanitized: true,
2639 isSetHTMLSanitized: true,
2640 sanitizeToDOMFragment:
2641 typeof DOMPurify !== 'undefined' && DOMPurify.isSupported ?
2642 sanitizeToDOMFragment : null
2643
2644 }, config, true );
2645
2646 // Users may specify block tag in lower case
2647 config.blockTag = config.blockTag.toUpperCase();
2648
2649 this._config = config;
2650
2651 return this;
2652 };
2653
2654 proto.createElement = function ( tag, props, children ) {
2655 return createElement( this._doc, tag, props, children );
2656 };
2657
2658 proto.createDefaultBlock = function ( children ) {
2659 var config = this._config;
2660 return fixCursor(
2661 this.createElement( config.blockTag, config.blockAttributes, children ),
2662 this._root
2663 );
2664 };
2665
2666 proto.didError = function ( error ) {
2667 console.log( error );
2668 };
2669
2670 proto.getDocument = function () {
2671 return this._doc;
2672 };
2673 proto.getRoot = function () {
2674 return this._root;
2675 };
2676
2677 proto.modifyDocument = function ( modificationCallback ) {
2678 var mutation = this._mutation;
2679 if ( mutation ) {
2680 if ( mutation.takeRecords().length ) {
2681 this._docWasChanged();
2682 }
2683 mutation.disconnect();
2684 }
2685
2686 this._ignoreAllChanges = true;
2687 modificationCallback();
2688 this._ignoreAllChanges = false;
2689
2690 if ( mutation ) {
2691 mutation.observe( this._root, {
2692 childList: true,
2693 attributes: true,
2694 characterData: true,
2695 subtree: true
2696 });
2697 this._ignoreChange = false;
2698 }
2699 };
2700
2701 // --- Events ---
2702
2703 // Subscribing to these events won't automatically add a listener to the
2704 // document node, since these events are fired in a custom manner by the
2705 // editor code.
2706 var customEvents = {
2707 pathChange: 1, select: 1, input: 1, undoStateChange: 1
2708 };
2709
2710 proto.fireEvent = function ( type, event ) {
2711 var handlers = this._events[ type ];
2712 var isFocused, l, obj;
2713 // UI code, especially modal views, may be monitoring for focus events and
2714 // immediately removing focus. In certain conditions, this can cause the
2715 // focus event to fire after the blur event, which can cause an infinite
2716 // loop. So we detect whether we're actually focused/blurred before firing.
2717 if ( /^(?:focus|blur)/.test( type ) ) {
2718 isFocused = this._root === this._doc.activeElement;
2719 if ( type === 'focus' ) {
2720 if ( !isFocused || this._isFocused ) {
2721 return this;
2722 }
2723 this._isFocused = true;
2724 } else {
2725 if ( isFocused || !this._isFocused ) {
2726 return this;
2727 }
2728 this._isFocused = false;
2729 }
2730 }
2731 if ( !event ) {
2732 event = {};
2733 }
2734 if ( event.type !== type ) {
2735 event.type = type;
2736 }
2737 oxide.sendMessage(type, event)
2738 if ( handlers ) {
2739 // Clone handlers array, so any handlers added/removed do not affect it.
2740 handlers = handlers.slice();
2741 l = handlers.length;
2742 while ( l-- ) {
2743 obj = handlers[l];
2744 try {
2745 if ( obj.handleEvent ) {
2746 obj.handleEvent( event );
2747 } else {
2748 obj.call( this, event );
2749 }
2750 } catch ( error ) {
2751 error.details = 'Squire: fireEvent error. Event type: ' + type;
2752 this.didError( error );
2753 }
2754 }
2755 }
2756 return this;
2757 };
2758
2759 proto.destroy = function () {
2760 var events = this._events;
2761 var type;
2762
2763 for ( type in events ) {
2764 this.removeEventListener( type );
2765 }
2766 if ( this._mutation ) {
2767 this._mutation.disconnect();
2768 }
2769 delete this._root.__squire__;
2770
2771 // Destroy undo stack
2772 this._undoIndex = -1;
2773 this._undoStack = [];
2774 this._undoStackLength = 0;
2775 };
2776
2777 proto.handleEvent = function ( event ) {
2778 this.fireEvent( event.type, event );
2779 };
2780
2781 proto.addEventListener = function ( type, fn ) {
2782 var handlers = this._events[ type ];
2783 var target = this._root;
2784 if ( !fn ) {
2785 this.didError({
2786 name: 'Squire: addEventListener with null or undefined fn',
2787 message: 'Event type: ' + type
2788 });
2789 return this;
2790 }
2791 if ( !handlers ) {
2792 handlers = this._events[ type ] = [];
2793 if ( !customEvents[ type ] ) {
2794 if ( type === 'selectionchange' ) {
2795 target = this._doc;
2796 }
2797 target.addEventListener( type, this, true );
2798 }
2799 }
2800 handlers.push( fn );
2801 return this;
2802 };
2803
2804 proto.removeEventListener = function ( type, fn ) {
2805 var handlers = this._events[ type ];
2806 var target = this._root;
2807 var l;
2808 if ( handlers ) {
2809 if ( fn ) {
2810 l = handlers.length;
2811 while ( l-- ) {
2812 if ( handlers[l] === fn ) {
2813 handlers.splice( l, 1 );
2814 }
2815 }
2816 } else {
2817 handlers.length = 0;
2818 }
2819 if ( !handlers.length ) {
2820 delete this._events[ type ];
2821 if ( !customEvents[ type ] ) {
2822 if ( type === 'selectionchange' ) {
2823 target = this._doc;
2824 }
2825 target.removeEventListener( type, this, true );
2826 }
2827 }
2828 }
2829 return this;
2830 };
2831
2832 // --- Selection and Path ---
2833
2834 proto._createRange =
2835 function ( range, startOffset, endContainer, endOffset ) {
2836 if ( range instanceof this._win.Range ) {
2837 return range.cloneRange();
2838 }
2839 var domRange = this._doc.createRange();
2840 domRange.setStart( range, startOffset );
2841 if ( endContainer ) {
2842 domRange.setEnd( endContainer, endOffset );
2843 } else {
2844 domRange.setEnd( range, startOffset );
2845 }
2846 return domRange;
2847 };
2848
2849 proto.getCursorPosition = function ( range ) {
2850 if ( ( !range && !( range = this.getSelection() ) ) ||
2851 !range.getBoundingClientRect ) {
2852 return null;
2853 }
2854 // Get the bounding rect
2855 var rect = range.getBoundingClientRect();
2856 var node, parent;
2857 if ( rect && !rect.top ) {
2858 this._ignoreChange = true;
2859 node = this._doc.createElement( 'SPAN' );
2860 node.textContent = ZWS;
2861 insertNodeInRange( range, node );
2862 rect = node.getBoundingClientRect();
2863 parent = node.parentNode;
2864 parent.removeChild( node );
2865 mergeInlines( parent, range );
2866 }
2867 return rect;
2868 };
2869
2870 proto._moveCursorTo = function ( toStart ) {
2871 var root = this._root,
2872 range = this._createRange( root, toStart ? 0 : root.childNodes.length );
2873 moveRangeBoundariesDownTree( range );
2874 this.setSelection( range );
2875 return this;
2876 };
2877 proto.moveCursorToStart = function () {
2878 return this._moveCursorTo( true );
2879 };
2880 proto.moveCursorToEnd = function () {
2881 return this._moveCursorTo( false );
2882 };
2883
2884 var getWindowSelection = function ( self ) {
2885 return self._win.getSelection() || null;
2886 };
2887
2888 proto.setSelection = function ( range ) {
2889 if ( range ) {
2890 this._lastSelection = range;
2891 // If we're setting selection, that automatically, and synchronously, // triggers a focus event. So just store the selection and mark it as
2892 // needing restore on focus.
2893 if ( !this._isFocused ) {
2894 enableRestoreSelection.call( this );
2895 } else if ( isAndroid && !this._restoreSelection ) {
2896 // Android closes the keyboard on removeAllRanges() and doesn't
2897 // open it again when addRange() is called, sigh.
2898 // Since Android doesn't trigger a focus event in setSelection(),
2899 // use a blur/focus dance to work around this by letting the
2900 // selection be restored on focus.
2901 // Need to check for !this._restoreSelection to avoid infinite loop
2902 enableRestoreSelection.call( this );
2903 this.blur();
2904 this.focus();
2905 } else {
2906 // iOS bug: if you don't focus the iframe before setting the
2907 // selection, you can end up in a state where you type but the input
2908 // doesn't get directed into the contenteditable area but is instead
2909 // lost in a black hole. Very strange.
2910 if ( isIOS ) {
2911 this._win.focus();
2912 }
2913 var sel = getWindowSelection( this );
2914 if ( sel ) {
2915 sel.removeAllRanges();
2916 sel.addRange( range );
2917 }
2918 }
2919 }
2920 return this;
2921 };
2922
2923 proto.getSelection = function () {
2924 var sel = getWindowSelection( this );
2925 var root = this._root;
2926 var selection, startContainer, endContainer, node;
2927 // If not focused, always rely on cached selection; another function may
2928 // have set it but the DOM is not modified until focus again
2929 if ( this._isFocused && sel && sel.rangeCount ) {
2930 selection = sel.getRangeAt( 0 ).cloneRange();
2931 startContainer = selection.startContainer;
2932 endContainer = selection.endContainer;
2933 // FF can return the selection as being inside an <img>. WTF?
2934 if ( startContainer && isLeaf( startContainer ) ) {
2935 selection.setStartBefore( startContainer );
2936 }
2937 if ( endContainer && isLeaf( endContainer ) ) {
2938 selection.setEndBefore( endContainer );
2939 }
2940 }
2941 if ( selection &&
2942 isOrContains( root, selection.commonAncestorContainer ) ) {
2943 this._lastSelection = selection;
2944 } else {
2945 selection = this._lastSelection;
2946 node = selection.commonAncestorContainer;
2947 // Check the editor is in the live document; if not, the range has
2948 // probably been rewritten by the browser and is bogus
2949 if ( !isOrContains( node.ownerDocument, node ) ) {
2950 selection = null;
2951 }
2952 }
2953 if ( !selection ) {
2954 selection = this._createRange( root.firstChild, 0 );
2955 }
2956 return selection;
2957 };
2958
2959 function enableRestoreSelection () {
2960 this._restoreSelection = true;
2961 }
2962 function disableRestoreSelection () {
2963 this._restoreSelection = false;
2964 }
2965 function restoreSelection () {
2966 if ( this._restoreSelection ) {
2967 this.setSelection( this._lastSelection );
2968 }
2969 }
2970
2971 proto.getSelectedText = function () {
2972 var range = this.getSelection();
2973 if ( !range || range.collapsed ) {
2974 return '';
2975 }
2976 var walker = new TreeWalker(
2977 range.commonAncestorContainer,
2978 SHOW_TEXT|SHOW_ELEMENT,
2979 function ( node ) {
2980 return isNodeContainedInRange( range, node, true );
2981 }
2982 );
2983 var startContainer = range.startContainer;
2984 var endContainer = range.endContainer;
2985 var node = walker.currentNode = startContainer;
2986 var textContent = '';
2987 var addedTextInBlock = false;
2988 var value;
2989
2990 if ( !walker.filter( node ) ) {
2991 node = walker.nextNode();
2992 }
2993
2994 while ( node ) {
2995 if ( node.nodeType === TEXT_NODE ) {
2996 value = node.data;
2997 if ( value && ( /\S/.test( value ) ) ) {
2998 if ( node === endContainer ) {
2999 value = value.slice( 0, range.endOffset );
3000 }
3001 if ( node === startContainer ) {
3002 value = value.slice( range.startOffset );
3003 }
3004 textContent += value;
3005 addedTextInBlock = true;
3006 }
3007 } else if ( node.nodeName === 'BR' ||
3008 addedTextInBlock && !isInline( node ) ) {
3009 textContent += '\n';
3010 addedTextInBlock = false;
3011 }
3012 node = walker.nextNode();
3013 }
3014
3015 return textContent;
3016 };
3017
3018 proto.getPath = function () {
3019 return this._path;
3020 };
3021
3022 // --- Workaround for browsers that can't focus empty text nodes ---
3023
3024 // WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=15256
3025
3026 // Walk down the tree starting at the root and remove any ZWS. If the node only
3027 // contained ZWS space then remove it too. We may want to keep one ZWS node at
3028 // the bottom of the tree so the block can be selected. Define that node as the
3029 // keepNode.
3030 var removeZWS = function ( root, keepNode ) {
3031 var walker = new TreeWalker( root, SHOW_TEXT, function () {
3032 return true;
3033 }, false ),
3034 parent, node, index;
3035 while ( node = walker.nextNode() ) {
3036 while ( ( index = node.data.indexOf( ZWS ) ) > -1 &&
3037 ( !keepNode || node.parentNode !== keepNode ) ) {
3038 if ( node.length === 1 ) {
3039 do {
3040 parent = node.parentNode;
3041 parent.removeChild( node );
3042 node = parent;
3043 walker.currentNode = parent;
3044 } while ( isInline( node ) && !getLength( node ) );
3045 break;
3046 } else {
3047 node.deleteData( index, 1 );
3048 }
3049 }
3050 }
3051 };
3052
3053 proto._didAddZWS = function () {
3054 this._hasZWS = true;
3055 };
3056 proto._removeZWS = function () {
3057 if ( !this._hasZWS ) {
3058 return;
3059 }
3060 removeZWS( this._root );
3061 this._hasZWS = false;
3062 };
3063
3064 // --- Path change events ---
3065
3066 proto._updatePath = function ( range, force ) {
3067 if ( !range ) {
3068 return;
3069 }
3070 var anchor = range.startContainer,
3071 focus = range.endContainer,
3072 newPath;
3073 if ( force || anchor !== this._lastAnchorNode ||
3074 focus !== this._lastFocusNode ) {
3075 this._lastAnchorNode = anchor;
3076 this._lastFocusNode = focus;
3077 newPath = ( anchor && focus ) ? ( anchor === focus ) ?
3078 getPath( focus, this._root ) : '(selection)' : '';
3079 if ( this._path !== newPath ) {
3080 this._path = newPath;
3081 this.fireEvent( 'pathChange', { path: newPath } );
3082 // oxide.sendMessage('pathChanged', { path: newPath });
3083 }
3084 }
3085 this.fireEvent( range.collapsed ? 'cursor' : 'select', {
3086 range: range
3087 });
3088 };
3089
3090 // selectionchange is fired synchronously in IE when removing current selection
3091 // and when setting new selection; keyup/mouseup may have processing we want
3092 // to do first. Either way, send to next event loop.
3093 proto._updatePathOnEvent = function ( event ) {
3094 var self = this;
3095 if ( self._isFocused && !self._willUpdatePath ) {
3096 self._willUpdatePath = true;
3097 setTimeout( function () {
3098 self._willUpdatePath = false;
3099 self._updatePath( self.getSelection() );
3100 }, 0 );
3101 }
3102 };
3103
3104 // --- Focus ---
3105
3106 proto.focus = function () {
3107 this._root.focus();
3108
3109 if ( isIE ) {
3110 this.fireEvent( 'focus' );
3111 }
3112
3113 return this;
3114 };
3115
3116 proto.blur = function () {
3117 this._root.blur();
3118
3119 if ( isIE ) {
3120 this.fireEvent( 'blur' );
3121 }
3122
3123 return this;
3124 };
3125
3126 // --- Bookmarking ---
3127
3128 var startSelectionId = 'squire-selection-start';
3129 var endSelectionId = 'squire-selection-end';
3130
3131 proto._saveRangeToBookmark = function ( range ) {
3132 var startNode = this.createElement( 'INPUT', {
3133 id: startSelectionId,
3134 type: 'hidden'
3135 }),
3136 endNode = this.createElement( 'INPUT', {
3137 id: endSelectionId,
3138 type: 'hidden'
3139 }),
3140 temp;
3141
3142 insertNodeInRange( range, startNode );
3143 range.collapse( false );
3144 insertNodeInRange( range, endNode );
3145
3146 // In a collapsed range, the start is sometimes inserted after the end!
3147 if ( startNode.compareDocumentPosition( endNode ) &
3148 DOCUMENT_POSITION_PRECEDING ) {
3149 startNode.id = endSelectionId;
3150 endNode.id = startSelectionId;
3151 temp = startNode;
3152 startNode = endNode;
3153 endNode = temp;
3154 }
3155
3156 range.setStartAfter( startNode );
3157 range.setEndBefore( endNode );
3158 };
3159
3160 proto._getRangeAndRemoveBookmark = function ( range ) {
3161 var root = this._root,
3162 start = root.querySelector( '#' + startSelectionId ),
3163 end = root.querySelector( '#' + endSelectionId );
3164
3165 if ( start && end ) {
3166 var startContainer = start.parentNode,
3167 endContainer = end.parentNode,
3168 startOffset = indexOf.call( startContainer.childNodes, start ),
3169 endOffset = indexOf.call( endContainer.childNodes, end );
3170
3171 if ( startContainer === endContainer ) {
3172 endOffset -= 1;
3173 }
3174
3175 detach( start );
3176 detach( end );
3177
3178 if ( !range ) {
3179 range = this._doc.createRange();
3180 }
3181 range.setStart( startContainer, startOffset );
3182 range.setEnd( endContainer, endOffset );
3183
3184 // Merge any text nodes we split
3185 mergeInlines( startContainer, range );
3186 if ( startContainer !== endContainer ) {
3187 mergeInlines( endContainer, range );
3188 }
3189
3190 // If we didn't split a text node, we should move into any adjacent
3191 // text node to current selection point
3192 if ( range.collapsed ) {
3193 startContainer = range.startContainer;
3194 if ( startContainer.nodeType === TEXT_NODE ) {
3195 endContainer = startContainer.childNodes[ range.startOffset ];
3196 if ( !endContainer || endContainer.nodeType !== TEXT_NODE ) {
3197 endContainer =
3198 startContainer.childNodes[ range.startOffset - 1 ];
3199 }
3200 if ( endContainer && endContainer.nodeType === TEXT_NODE ) {
3201 range.setStart( endContainer, 0 );
3202 range.collapse( true );
3203 }
3204 }
3205 }
3206 }
3207 return range || null;
3208 };
3209
3210 // --- Undo ---
3211
3212 proto._keyUpDetectChange = function ( event ) {
3213 var code = event.keyCode;
3214 // Presume document was changed if:
3215 // 1. A modifier key (other than shift) wasn't held down
3216 // 2. The key pressed is not in range 16<=x<=20 (control keys)
3217 // 3. The key pressed is not in range 33<=x<=45 (navigation keys)
3218 if ( !event.ctrlKey && !event.metaKey && !event.altKey &&
3219 ( code < 16 || code > 20 ) &&
3220 ( code < 33 || code > 45 ) ) {
3221 this._docWasChanged();
3222 }
3223 };
3224
3225 proto._docWasChanged = function () {
3226 if ( canWeakMap ) {
3227 nodeCategoryCache = new WeakMap();
3228 }
3229 if ( this._ignoreAllChanges ) {
3230 return;
3231 }
3232
3233 if ( canObserveMutations && this._ignoreChange ) {
3234 this._ignoreChange = false;
3235 return;
3236 }
3237 if ( this._isInUndoState ) {
3238 this._isInUndoState = false;
3239 this.fireEvent( 'undoStateChange', {
3240 canUndo: true,
3241 canRedo: false
3242 });
3243 }
3244 this.fireEvent( 'input' );
3245 };
3246
3247 // Leaves bookmark
3248 proto._recordUndoState = function ( range, replace ) {
3249 // Don't record if we're already in an undo state
3250 if ( !this._isInUndoState|| replace ) {
3251 // Advance pointer to new position
3252 var undoIndex = this._undoIndex;
3253 var undoStack = this._undoStack;
3254 var undoConfig = this._config.undo;
3255 var undoThreshold = undoConfig.documentSizeThreshold;
3256 var undoLimit = undoConfig.undoLimit;
3257 var html;
3258
3259 if ( !replace ) {
3260 undoIndex += 1;
3261 }
3262
3263 // Truncate stack if longer (i.e. if has been previously undone)
3264 if ( undoIndex < this._undoStackLength ) {
3265 undoStack.length = this._undoStackLength = undoIndex;
3266 }
3267
3268 // Get data
3269 if ( range ) {
3270 this._saveRangeToBookmark( range );
3271 }
3272 html = this._getHTML();
3273
3274 // If this document is above the configured size threshold,
3275 // limit the number of saved undo states.
3276 // Threshold is in bytes, JS uses 2 bytes per character
3277 if ( undoThreshold > -1 && html.length * 2 > undoThreshold ) {
3278 if ( undoLimit > -1 && undoIndex > undoLimit ) {
3279 undoStack.splice( 0, undoIndex - undoLimit );
3280 undoIndex = undoLimit;
3281 this._undoStackLength = undoLimit;
3282 }
3283 }
3284
3285 // Save data
3286 undoStack[ undoIndex ] = html;
3287 this._undoIndex = undoIndex;
3288 this._undoStackLength += 1;
3289 this._isInUndoState = true;
3290 }
3291 };
3292
3293 proto.saveUndoState = function ( range ) {
3294 if ( range === undefined ) {
3295 range = this.getSelection();
3296 }
3297 this._recordUndoState( range, this._isInUndoState );
3298 this._getRangeAndRemoveBookmark( range );
3299
3300 return this;
3301 };
3302
3303 proto.undo = function () {
3304 // Sanity check: must not be at beginning of the history stack
3305 if ( this._undoIndex !== 0 || !this._isInUndoState ) {
3306 // Make sure any changes since last checkpoint are saved.
3307 this._recordUndoState( this.getSelection(), false );
3308
3309 this._undoIndex -= 1;
3310 this._setHTML( this._undoStack[ this._undoIndex ] );
3311 var range = this._getRangeAndRemoveBookmark();
3312 if ( range ) {
3313 this.setSelection( range );
3314 }
3315 this._isInUndoState = true;
3316 this.fireEvent( 'undoStateChange', {
3317 canUndo: this._undoIndex !== 0,
3318 canRedo: true
3319 });
3320 this.fireEvent( 'input' );
3321 }
3322 return this;
3323 };
3324
3325 proto.redo = function () {
3326 // Sanity check: must not be at end of stack and must be in an undo
3327 // state.
3328 var undoIndex = this._undoIndex,
3329 undoStackLength = this._undoStackLength;
3330 if ( undoIndex + 1 < undoStackLength && this._isInUndoState ) {
3331 this._undoIndex += 1;
3332 this._setHTML( this._undoStack[ this._undoIndex ] );
3333 var range = this._getRangeAndRemoveBookmark();
3334 if ( range ) {
3335 this.setSelection( range );
3336 }
3337 this.fireEvent( 'undoStateChange', {
3338 canUndo: true,
3339 canRedo: undoIndex + 2 < undoStackLength
3340 });
3341 this.fireEvent( 'input' );
3342 }
3343 return this;
3344 };
3345
3346 // --- Inline formatting ---
3347
3348 // Looks for matching tag and attributes, so won't work
3349 // if <strong> instead of <b> etc.
3350 proto.hasFormat = function ( tag, attributes, range ) {
3351 // 1. Normalise the arguments and get selection
3352 tag = tag.toUpperCase();
3353 if ( !attributes ) { attributes = {}; }
3354 if ( !range && !( range = this.getSelection() ) ) {
3355 return false;
3356 }
3357
3358 // Sanitize range to prevent weird IE artifacts
3359 if ( !range.collapsed &&
3360 range.startContainer.nodeType === TEXT_NODE &&
3361 range.startOffset === range.startContainer.length &&
3362 range.startContainer.nextSibling ) {
3363 range.setStartBefore( range.startContainer.nextSibling );
3364 }
3365 if ( !range.collapsed &&
3366 range.endContainer.nodeType === TEXT_NODE &&
3367 range.endOffset === 0 &&
3368 range.endContainer.previousSibling ) {
3369 range.setEndAfter( range.endContainer.previousSibling );
3370 }
3371
3372 // If the common ancestor is inside the tag we require, we definitely
3373 // have the format.
3374 var root = this._root;
3375 var common = range.commonAncestorContainer;
3376 var walker, node;
3377 if ( getNearest( common, root, tag, attributes ) ) {
3378 return true;
3379 }
3380
3381 // If common ancestor is a text node and doesn't have the format, we
3382 // definitely don't have it.
3383 if ( common.nodeType === TEXT_NODE ) {
3384 return false;
3385 }
3386
3387 // Otherwise, check each text node at least partially contained within
3388 // the selection and make sure all of them have the format we want.
3389 walker = new TreeWalker( common, SHOW_TEXT, function ( node ) {
3390 return isNodeContainedInRange( range, node, true );
3391 }, false );
3392
3393 var seenNode = false;
3394 while ( node = walker.nextNode() ) {
3395 if ( !getNearest( node, root, tag, attributes ) ) {
3396 return false;
3397 }
3398 seenNode = true;
3399 }
3400
3401 return seenNode;
3402 };
3403
3404 // Extracts the font-family and font-size (if any) of the element
3405 // holding the cursor. If there's a selection, returns an empty object.
3406 proto.getFontInfo = function ( range ) {
3407 var fontInfo = {
3408 color: undefined,
3409 backgroundColor: undefined,
3410 family: undefined,
3411 size: undefined
3412 };
3413 var seenAttributes = 0;
3414 var element, style, attr;
3415
3416 if ( !range && !( range = this.getSelection() ) ) {
3417 return fontInfo;
3418 }
3419
3420 element = range.commonAncestorContainer;
3421 if ( range.collapsed || element.nodeType === TEXT_NODE ) {
3422 if ( element.nodeType === TEXT_NODE ) {
3423 element = element.parentNode;
3424 }
3425 while ( seenAttributes < 4 && element ) {
3426 if ( style = element.style ) {
3427 if ( !fontInfo.color && ( attr = style.color ) ) {
3428 fontInfo.color = attr;
3429 seenAttributes += 1;
3430 }
3431 if ( !fontInfo.backgroundColor &&
3432 ( attr = style.backgroundColor ) ) {
3433 fontInfo.backgroundColor = attr;
3434 seenAttributes += 1;
3435 }
3436 if ( !fontInfo.family && ( attr = style.fontFamily ) ) {
3437 fontInfo.family = attr;
3438 seenAttributes += 1;
3439 }
3440 if ( !fontInfo.size && ( attr = style.fontSize ) ) {
3441 fontInfo.size = attr;
3442 seenAttributes += 1;
3443 }
3444 }
3445 element = element.parentNode;
3446 }
3447 }
3448 return fontInfo;
3449 };
3450
3451 proto._addFormat = function ( tag, attributes, range ) {
3452 // If the range is collapsed we simply insert the node by wrapping
3453 // it round the range and focus it.
3454 var root = this._root;
3455 var el, walker, startContainer, endContainer, startOffset, endOffset,
3456 node, needsFormat, block;
3457
3458 if ( range.collapsed ) {
3459 el = fixCursor( this.createElement( tag, attributes ), root );
3460 insertNodeInRange( range, el );
3461 range.setStart( el.firstChild, el.firstChild.length );
3462 range.collapse( true );
3463
3464 // Clean up any previous formats that may have been set on this block
3465 // that are unused.
3466 block = el;
3467 while ( isInline( block ) ) {
3468 block = block.parentNode;
3469 }
3470 removeZWS( block, el );
3471 }
3472 // Otherwise we find all the textnodes in the range (splitting
3473 // partially selected nodes) and if they're not already formatted
3474 // correctly we wrap them in the appropriate tag.
3475 else {
3476 // Create an iterator to walk over all the text nodes under this
3477 // ancestor which are in the range and not already formatted
3478 // correctly.
3479 //
3480 // In Blink/WebKit, empty blocks may have no text nodes, just a <br>.
3481 // Therefore we wrap this in the tag as well, as this will then cause it
3482 // to apply when the user types something in the block, which is
3483 // presumably what was intended.
3484 //
3485 // IMG tags are included because we may want to create a link around
3486 // them, and adding other styles is harmless.
3487 walker = new TreeWalker(
3488 range.commonAncestorContainer,
3489 SHOW_TEXT|SHOW_ELEMENT,
3490 function ( node ) {
3491 return ( node.nodeType === TEXT_NODE ||
3492 node.nodeName === 'BR' ||
3493 node.nodeName === 'IMG'
3494 ) && isNodeContainedInRange( range, node, true );
3495 },
3496 false
3497 );
3498
3499 // Start at the beginning node of the range and iterate through
3500 // all the nodes in the range that need formatting.
3501 startContainer = range.startContainer;
3502 startOffset = range.startOffset;
3503 endContainer = range.endContainer;
3504 endOffset = range.endOffset;
3505
3506 // Make sure we start with a valid node.
3507 walker.currentNode = startContainer;
3508 if ( !walker.filter( startContainer ) ) {
3509 startContainer = walker.nextNode();
3510 startOffset = 0;
3511 }
3512
3513 // If there are no interesting nodes in the selection, abort
3514 if ( !startContainer ) {
3515 return range;
3516 }
3517
3518 do {
3519 node = walker.currentNode;
3520 needsFormat = !getNearest( node, root, tag, attributes );
3521 if ( needsFormat ) {
3522 // <br> can never be a container node, so must have a text node
3523 // if node == (end|start)Container
3524 if ( node === endContainer && node.length > endOffset ) {
3525 node.splitText( endOffset );
3526 }
3527 if ( node === startContainer && startOffset ) {
3528 node = node.splitText( startOffset );
3529 if ( endContainer === startContainer ) {
3530 endContainer = node;
3531 endOffset -= startOffset;
3532 }
3533 startContainer = node;
3534 startOffset = 0;
3535 }
3536 el = this.createElement( tag, attributes );
3537 replaceWith( node, el );
3538 el.appendChild( node );
3539 }
3540 } while ( walker.nextNode() );
3541
3542 // If we don't finish inside a text node, offset may have changed.
3543 if ( endContainer.nodeType !== TEXT_NODE ) {
3544 if ( node.nodeType === TEXT_NODE ) {
3545 endContainer = node;
3546 endOffset = node.length;
3547 } else {
3548 // If <br>, we must have just wrapped it, so it must have only
3549 // one child
3550 endContainer = node.parentNode;
3551 endOffset = 1;
3552 }
3553 }
3554
3555 // Now set the selection to as it was before
3556 range = this._createRange(
3557 startContainer, startOffset, endContainer, endOffset );
3558 }
3559 return range;
3560 };
3561
3562 proto._removeFormat = function ( tag, attributes, range, partial ) {
3563 // Add bookmark
3564 this._saveRangeToBookmark( range );
3565
3566 // We need a node in the selection to break the surrounding
3567 // formatted text.
3568 var doc = this._doc,
3569 fixer;
3570 if ( range.collapsed ) {
3571 if ( cantFocusEmptyTextNodes ) {
3572 fixer = doc.createTextNode( ZWS );
3573 this._didAddZWS();
3574 } else {
3575 fixer = doc.createTextNode( '' );
3576 }
3577 insertNodeInRange( range, fixer );
3578 }
3579
3580 // Find block-level ancestor of selection
3581 var root = range.commonAncestorContainer;
3582 while ( isInline( root ) ) {
3583 root = root.parentNode;
3584 }
3585
3586 // Find text nodes inside formatTags that are not in selection and
3587 // add an extra tag with the same formatting.
3588 var startContainer = range.startContainer,
3589 startOffset = range.startOffset,
3590 endContainer = range.endContainer,
3591 endOffset = range.endOffset,
3592 toWrap = [],
3593 examineNode = function ( node, exemplar ) {
3594 // If the node is completely contained by the range then
3595 // we're going to remove all formatting so ignore it.
3596 if ( isNodeContainedInRange( range, node, false ) ) {
3597 return;
3598 }
3599
3600 var isText = ( node.nodeType === TEXT_NODE ),
3601 child, next;
3602
3603 // If not at least partially contained, wrap entire contents
3604 // in a clone of the tag we're removing and we're done.
3605 if ( !isNodeContainedInRange( range, node, true ) ) {
3606 // Ignore bookmarks and empty text nodes
3607 if ( node.nodeName !== 'INPUT' &&
3608 ( !isText || node.data ) ) {
3609 toWrap.push([ exemplar, node ]);
3610 }
3611 return;
3612 }
3613
3614 // Split any partially selected text nodes.
3615 if ( isText ) {
3616 if ( node === endContainer && endOffset !== node.length ) {
3617 toWrap.push([ exemplar, node.splitText( endOffset ) ]);
3618 }
3619 if ( node === startContainer && startOffset ) {
3620 node.splitText( startOffset );
3621 toWrap.push([ exemplar, node ]);
3622 }
3623 }
3624 // If not a text node, recurse onto all children.
3625 // Beware, the tree may be rewritten with each call
3626 // to examineNode, hence find the next sibling first.
3627 else {
3628 for ( child = node.firstChild; child; child = next ) {
3629 next = child.nextSibling;
3630 examineNode( child, exemplar );
3631 }
3632 }
3633 },
3634 formatTags = Array.prototype.filter.call(
3635 root.getElementsByTagName( tag ), function ( el ) {
3636 return isNodeContainedInRange( range, el, true ) &&
3637 hasTagAttributes( el, tag, attributes );
3638 }
3639 );
3640
3641 if ( !partial ) {
3642 formatTags.forEach( function ( node ) {
3643 examineNode( node, node );
3644 });
3645 }
3646
3647 // Now wrap unselected nodes in the tag
3648 toWrap.forEach( function ( item ) {
3649 // [ exemplar, node ] tuple
3650 var el = item[0].cloneNode( false ),
3651 node = item[1];
3652 replaceWith( node, el );
3653 el.appendChild( node );
3654 });
3655 // and remove old formatting tags.
3656 formatTags.forEach( function ( el ) {
3657 replaceWith( el, empty( el ) );
3658 });
3659
3660 // Merge adjacent inlines:
3661 this._getRangeAndRemoveBookmark( range );
3662 if ( fixer ) {
3663 range.collapse( false );
3664 }
3665 mergeInlines( root, range );
3666
3667 return range;
3668 };
3669
3670 proto.changeFormat = function ( add, remove, range, partial ) {
3671 // Normalise the arguments and get selection
3672 if ( !range && !( range = this.getSelection() ) ) {
3673 return this;
3674 }
3675
3676 // Save undo checkpoint
3677 this.saveUndoState( range );
3678
3679 if ( remove ) {
3680 range = this._removeFormat( remove.tag.toUpperCase(),
3681 remove.attributes || {}, range, partial );
3682 }
3683 if ( add ) {
3684 range = this._addFormat( add.tag.toUpperCase(),
3685 add.attributes || {}, range );
3686 }
3687
3688 this.setSelection( range );
3689 this._updatePath( range, true );
3690
3691 // We're not still in an undo state
3692 if ( !canObserveMutations ) {
3693 this._docWasChanged();
3694 }
3695
3696 return this;
3697 };
3698
3699 // --- Block formatting ---
3700
3701 var tagAfterSplit = {
3702 DT: 'DD',
3703 DD: 'DT',
3704 LI: 'LI',
3705 PRE: 'PRE'
3706 };
3707
3708 var splitBlock = function ( self, block, node, offset ) {
3709 var splitTag = tagAfterSplit[ block.nodeName ],
3710 splitProperties = null,
3711 nodeAfterSplit = split( node, offset, block.parentNode, self._root ),
3712 config = self._config;
3713
3714 if ( !splitTag ) {
3715 splitTag = config.blockTag;
3716 splitProperties = config.blockAttributes;
3717 }
3718
3719 // Make sure the new node is the correct type.
3720 if ( !hasTagAttributes( nodeAfterSplit, splitTag, splitProperties ) ) {
3721 block = createElement( nodeAfterSplit.ownerDocument,
3722 splitTag, splitProperties );
3723 if ( nodeAfterSplit.dir ) {
3724 block.dir = nodeAfterSplit.dir;
3725 }
3726 replaceWith( nodeAfterSplit, block );
3727 block.appendChild( empty( nodeAfterSplit ) );
3728 nodeAfterSplit = block;
3729 }
3730 return nodeAfterSplit;
3731 };
3732
3733 proto.forEachBlock = function ( fn, mutates, range ) {
3734 if ( !range && !( range = this.getSelection() ) ) {
3735 return this;
3736 }
3737
3738 // Save undo checkpoint
3739 if ( mutates ) {
3740 this.saveUndoState( range );
3741 }
3742
3743 var root = this._root;
3744 var start = getStartBlockOfRange( range, root );
3745 var end = getEndBlockOfRange( range, root );
3746 if ( start && end ) {
3747 do {
3748 if ( fn( start ) || start === end ) { break; }
3749 } while ( start = getNextBlock( start, root ) );
3750 }
3751
3752 if ( mutates ) {
3753 this.setSelection( range );
3754
3755 // Path may have changed
3756 this._updatePath( range, true );
3757
3758 // We're not still in an undo state
3759 if ( !canObserveMutations ) {
3760 this._docWasChanged();
3761 }
3762 }
3763 return this;
3764 };
3765
3766 proto.modifyBlocks = function ( modify, range ) {
3767 if ( !range && !( range = this.getSelection() ) ) {
3768 return this;
3769 }
3770
3771 // 1. Save undo checkpoint and bookmark selection
3772 this._recordUndoState( range, this._isInUndoState );
3773
3774 var root = this._root;
3775 var frag;
3776
3777 // 2. Expand range to block boundaries
3778 expandRangeToBlockBoundaries( range, root );
3779
3780 // 3. Remove range.
3781 moveRangeBoundariesUpTree( range, root, root, root );
3782 frag = extractContentsOfRange( range, root, root );
3783
3784 // 4. Modify tree of fragment and reinsert.
3785 insertNodeInRange( range, modify.call( this, frag ) );
3786
3787 // 5. Merge containers at edges
3788 if ( range.endOffset < range.endContainer.childNodes.length ) {
3789 mergeContainers( range.endContainer.childNodes[ range.endOffset ], root );
3790 }
3791 mergeContainers( range.startContainer.childNodes[ range.startOffset ], root );
3792
3793 // 6. Restore selection
3794 this._getRangeAndRemoveBookmark( range );
3795 this.setSelection( range );
3796 this._updatePath( range, true );
3797
3798 // 7. We're not still in an undo state
3799 if ( !canObserveMutations ) {
3800 this._docWasChanged();
3801 }
3802
3803 return this;
3804 };
3805
3806 var increaseBlockQuoteLevel = function ( frag ) {
3807 return this.createElement( 'BLOCKQUOTE',
3808 this._config.tagAttributes.blockquote, [
3809 frag
3810 ]);
3811 };
3812
3813 var decreaseBlockQuoteLevel = function ( frag ) {
3814 var root = this._root;
3815 var blockquotes = frag.querySelectorAll( 'blockquote' );
3816 Array.prototype.filter.call( blockquotes, function ( el ) {
3817 return !getNearest( el.parentNode, root, 'BLOCKQUOTE' );
3818 }).forEach( function ( el ) {
3819 replaceWith( el, empty( el ) );
3820 });
3821 return frag;
3822 };
3823
3824 var removeBlockQuote = function (/* frag */) {
3825 return this.createDefaultBlock([
3826 this.createElement( 'INPUT', {
3827 id: startSelectionId,
3828 type: 'hidden'
3829 }),
3830 this.createElement( 'INPUT', {
3831 id: endSelectionId,
3832 type: 'hidden'
3833 })
3834 ]);
3835 };
3836
3837 var makeList = function ( self, frag, type ) {
3838 var walker = getBlockWalker( frag, self._root ),
3839 node, tag, prev, newLi,
3840 tagAttributes = self._config.tagAttributes,
3841 listAttrs = tagAttributes[ type.toLowerCase() ],
3842 listItemAttrs = tagAttributes.li;
3843
3844 while ( node = walker.nextNode() ) {
3845 if ( node.parentNode.nodeName === 'LI' ) {
3846 node = node.parentNode;
3847 walker.currentNode = node.lastChild;
3848 }
3849 if ( node.nodeName !== 'LI' ) {
3850 newLi = self.createElement( 'LI', listItemAttrs );
3851 if ( node.dir ) {
3852 newLi.dir = node.dir;
3853 }
3854
3855 // Have we replaced the previous block with a new <ul>/<ol>?
3856 if ( ( prev = node.previousSibling ) && prev.nodeName === type ) {
3857 prev.appendChild( newLi );
3858 detach( node );
3859 }
3860 // Otherwise, replace this block with the <ul>/<ol>
3861 else {
3862 replaceWith(
3863 node,
3864 self.createElement( type, listAttrs, [
3865 newLi
3866 ])
3867 );
3868 }
3869 newLi.appendChild( empty( node ) );
3870 walker.currentNode = newLi;
3871 } else {
3872 node = node.parentNode;
3873 tag = node.nodeName;
3874 if ( tag !== type && ( /^[OU]L$/.test( tag ) ) ) {
3875 replaceWith( node,
3876 self.createElement( type, listAttrs, [ empty( node ) ] )
3877 );
3878 }
3879 }
3880 }
3881 };
3882
3883 var makeUnorderedList = function ( frag ) {
3884 makeList( this, frag, 'UL' );
3885 return frag;
3886 };
3887
3888 var makeOrderedList = function ( frag ) {
3889 makeList( this, frag, 'OL' );
3890 return frag;
3891 };
3892
3893 var removeList = function ( frag ) {
3894 var lists = frag.querySelectorAll( 'UL, OL' ),
3895 items = frag.querySelectorAll( 'LI' ),
3896 root = this._root,
3897 i, l, list, listFrag, item;
3898 for ( i = 0, l = lists.length; i < l; i += 1 ) {
3899 list = lists[i];
3900 listFrag = empty( list );
3901 fixContainer( listFrag, root );
3902 replaceWith( list, listFrag );
3903 }
3904
3905 for ( i = 0, l = items.length; i < l; i += 1 ) {
3906 item = items[i];
3907 if ( isBlock( item ) ) {
3908 replaceWith( item,
3909 this.createDefaultBlock([ empty( item ) ])
3910 );
3911 } else {
3912 fixContainer( item, root );
3913 replaceWith( item, empty( item ) );
3914 }
3915 }
3916 return frag;
3917 };
3918
3919 var getListSelection = function ( range, root ) {
3920 // Get start+end li in single common ancestor
3921 var list = range.commonAncestorContainer;
3922 var startLi = range.startContainer;
3923 var endLi = range.endContainer;
3924 while ( list && list !== root && !/^[OU]L$/.test( list.nodeName ) ) {
3925 list = list.parentNode;
3926 }
3927 if ( !list || list === root ) {
3928 return null;
3929 }
3930 if ( startLi === list ) {
3931 startLi = startLi.childNodes[ range.startOffset ];
3932 }
3933 if ( endLi === list ) {
3934 endLi = endLi.childNodes[ range.endOffset ];
3935 }
3936 while ( startLi && startLi.parentNode !== list ) {
3937 startLi = startLi.parentNode;
3938 }
3939 while ( endLi && endLi.parentNode !== list ) {
3940 endLi = endLi.parentNode;
3941 }
3942 return [ list, startLi, endLi ];
3943 };
3944
3945 proto.increaseListLevel = function ( range ) {
3946 if ( !range && !( range = this.getSelection() ) ) {
3947 return this.focus();
3948 }
3949
3950 var root = this._root;
3951 var listSelection = getListSelection( range, root );
3952 if ( !listSelection ) {
3953 return this.focus();
3954 }
3955
3956 var list = listSelection[0];
3957 var startLi = listSelection[1];
3958 var endLi = listSelection[2];
3959 if ( !startLi || startLi === list.firstChild ) {
3960 return this.focus();
3961 }
3962
3963 // Save undo checkpoint and bookmark selection
3964 this._recordUndoState( range, this._isInUndoState );
3965
3966 // Increase list depth
3967 var type = list.nodeName;
3968 var newParent = startLi.previousSibling;
3969 var listAttrs, next;
3970 if ( newParent.nodeName !== type ) {
3971 listAttrs = this._config.tagAttributes[ type.toLowerCase() ];
3972 newParent = this.createElement( type, listAttrs );
3973 list.insertBefore( newParent, startLi );
3974 }
3975 do {
3976 next = startLi === endLi ? null : startLi.nextSibling;
3977 newParent.appendChild( startLi );
3978 } while ( ( startLi = next ) );
3979 next = newParent.nextSibling;
3980 if ( next ) {
3981 mergeContainers( next, root );
3982 }
3983
3984 // Restore selection
3985 this._getRangeAndRemoveBookmark( range );
3986 this.setSelection( range );
3987 this._updatePath( range, true );
3988
3989 // We're not still in an undo state
3990 if ( !canObserveMutations ) {
3991 this._docWasChanged();
3992 }
3993
3994 return this.focus();
3995 };
3996
3997 proto.decreaseListLevel = function ( range ) {
3998 if ( !range && !( range = this.getSelection() ) ) {
3999 return this.focus();
4000 }
4001
4002 var root = this._root;
4003 var listSelection = getListSelection( range, root );
4004 if ( !listSelection ) {
4005 return this.focus();
4006 }
4007
4008 var list = listSelection[0];
4009 var startLi = listSelection[1];
4010 var endLi = listSelection[2];
4011 if ( !startLi ) {
4012 startLi = list.firstChild;
4013 }
4014 if ( !endLi ) {
4015 endLi = list.lastChild;
4016 }
4017
4018 // Save undo checkpoint and bookmark selection
4019 this._recordUndoState( range, this._isInUndoState );
4020
4021 // Find the new parent list node
4022 var newParent = list.parentNode;
4023 var next;
4024
4025 // Split list if necesary
4026 var insertBefore = !endLi.nextSibling ?
4027 list.nextSibling :
4028 split( list, endLi.nextSibling, newParent, root );
4029
4030 if ( newParent !== root && newParent.nodeName === 'LI' ) {
4031 newParent = newParent.parentNode;
4032 while ( insertBefore ) {
4033 next = insertBefore.nextSibling;
4034 endLi.appendChild( insertBefore );
4035 insertBefore = next;
4036 }
4037 insertBefore = list.parentNode.nextSibling;
4038 }
4039
4040 var makeNotList = !/^[OU]L$/.test( newParent.nodeName );
4041 do {
4042 next = startLi === endLi ? null : startLi.nextSibling;
4043 list.removeChild( startLi );
4044 if ( makeNotList && startLi.nodeName === 'LI' ) {
4045 startLi = this.createDefaultBlock([ empty( startLi ) ]);
4046 }
4047 newParent.insertBefore( startLi, insertBefore );
4048 } while ( ( startLi = next ) );
4049
4050 if ( !list.firstChild ) {
4051 detach( list );
4052 }
4053
4054 if ( insertBefore ) {
4055 mergeContainers( insertBefore, root );
4056 }
4057
4058 // Restore selection
4059 this._getRangeAndRemoveBookmark( range );
4060 this.setSelection( range );
4061 this._updatePath( range, true );
4062
4063 // We're not still in an undo state
4064 if ( !canObserveMutations ) {
4065 this._docWasChanged();
4066 }
4067
4068 return this.focus();
4069 };
4070
4071 proto._ensureBottomLine = function () {
4072 var root = this._root;
4073 var last = root.lastElementChild;
4074 if ( !last ||
4075 last.nodeName !== this._config.blockTag || !isBlock( last ) ) {
4076 root.appendChild( this.createDefaultBlock() );
4077 }
4078 };
4079
4080 // --- Keyboard interaction ---
4081
4082 proto.setKeyHandler = function ( key, fn ) {
4083 this._keyHandlers[ key ] = fn;
4084 return this;
4085 };
4086
4087 // --- Get/Set data ---
4088
4089 proto._getHTML = function () {
4090 return this._root.innerHTML;
4091 };
4092
4093 proto._setHTML = function ( html ) {
4094 var root = this._root;
4095 var node = root;
4096 node.innerHTML = html;
4097 do {
4098 fixCursor( node, root );
4099 } while ( node = getNextBlock( node, root ) );
4100 this._ignoreChange = true;
4101 };
4102
4103 proto.getHTML = function ( withBookMark ) {
4104 var brs = [],
4105 root, node, fixer, html, l, range;
4106 if ( withBookMark && ( range = this.getSelection() ) ) {
4107 this._saveRangeToBookmark( range );
4108 }
4109 if ( useTextFixer ) {
4110 root = this._root;
4111 node = root;
4112 while ( node = getNextBlock( node, root ) ) {
4113 if ( !node.textContent && !node.querySelector( 'BR' ) ) {
4114 fixer = this.createElement( 'BR' );
4115 node.appendChild( fixer );
4116 brs.push( fixer );
4117 }
4118 }
4119 }
4120 html = this._getHTML().replace( /\u200B/g, '' );
4121 if ( useTextFixer ) {
4122 l = brs.length;
4123 while ( l-- ) {
4124 detach( brs[l] );
4125 }
4126 }
4127 if ( range ) {
4128 this._getRangeAndRemoveBookmark( range );
4129 }
4130 return html;
4131 };
4132
4133 proto.setHTML = function ( html ) {
4134 var config = this._config;
4135 var sanitizeToDOMFragment = config.isSetHTMLSanitized ?
4136 config.sanitizeToDOMFragment : null;
4137 var root = this._root;
4138 var div, frag, child;
4139
4140 // Parse HTML into DOM tree
4141 if ( typeof sanitizeToDOMFragment === 'function' ) {
4142 frag = sanitizeToDOMFragment( html, false, this );
4143 } else {
4144 div = this.createElement( 'DIV' );
4145 div.innerHTML = html;
4146 frag = this._doc.createDocumentFragment();
4147 frag.appendChild( empty( div ) );
4148 }
4149
4150 cleanTree( frag );
4151 cleanupBRs( frag, root, false );
4152
4153 fixContainer( frag, root );
4154
4155 // Fix cursor
4156 var node = frag;
4157 while ( node = getNextBlock( node, root ) ) {
4158 fixCursor( node, root );
4159 }
4160
4161 // Don't fire an input event
4162 this._ignoreChange = true;
4163
4164 // Remove existing root children
4165 while ( child = root.lastChild ) {
4166 root.removeChild( child );
4167 }
4168
4169 // And insert new content
4170 root.appendChild( frag );
4171 fixCursor( root, root );
4172
4173 // Reset the undo stack
4174 this._undoIndex = -1;
4175 this._undoStack.length = 0;
4176 this._undoStackLength = 0;
4177 this._isInUndoState = false;
4178
4179 // Record undo state
4180 var range = this._getRangeAndRemoveBookmark() ||
4181 this._createRange( root.firstChild, 0 );
4182 this.saveUndoState( range );
4183 // IE will also set focus when selecting text so don't use
4184 // setSelection. Instead, just store it in lastSelection, so if
4185 // anything calls getSelection before first focus, we have a range
4186 // to return.
4187 this._lastSelection = range;
4188 enableRestoreSelection.call( this );
4189 this._updatePath( range, true );
4190
4191 return this;
4192 };
4193
4194 proto.insertElement = function ( el, range ) {
4195 if ( !range ) {
4196 range = this.getSelection();
4197 }
4198 range.collapse( true );
4199 if ( isInline( el ) ) {
4200 insertNodeInRange( range, el );
4201 range.setStartAfter( el );
4202 } else {
4203 // Get containing block node.
4204 var root = this._root;
4205 var splitNode = getStartBlockOfRange( range, root ) || root;
4206 var parent, nodeAfterSplit;
4207 // While at end of container node, move up DOM tree.
4208 while ( splitNode !== root && !splitNode.nextSibling ) {
4209 splitNode = splitNode.parentNode;
4210 }
4211 // If in the middle of a container node, split up to root.
4212 if ( splitNode !== root ) {
4213 parent = splitNode.parentNode;
4214 nodeAfterSplit = split( parent, splitNode.nextSibling, root, root );
4215 }
4216 if ( nodeAfterSplit ) {
4217 root.insertBefore( el, nodeAfterSplit );
4218 } else {
4219 root.appendChild( el );
4220 // Insert blank line below block.
4221 nodeAfterSplit = this.createDefaultBlock();
4222 root.appendChild( nodeAfterSplit );
4223 }
4224 range.setStart( nodeAfterSplit, 0 );
4225 range.setEnd( nodeAfterSplit, 0 );
4226 moveRangeBoundariesDownTree( range );
4227 }
4228 this.focus();
4229 this.setSelection( range );
4230 this._updatePath( range );
4231
4232 if ( !canObserveMutations ) {
4233 this._docWasChanged();
4234 }
4235
4236 return this;
4237 };
4238
4239 proto.insertImage = function ( src, attributes ) {
4240 var img = this.createElement( 'IMG', mergeObjects({
4241 src: src
4242 }, attributes, true ));
4243 this.insertElement( img );
4244 return img;
4245 };
4246
4247 var linkRegExp = /\b((?:(?:ht|f)tps?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))|([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,}\b)/i;
4248
4249 var addLinks = function ( frag, root, self ) {
4250 var doc = frag.ownerDocument,
4251 walker = new TreeWalker( frag, SHOW_TEXT,
4252 function ( node ) {
4253 return !getNearest( node, root, 'A' );
4254 }, false ),
4255 defaultAttributes = self._config.tagAttributes.a,
4256 node, data, parent, match, index, endIndex, child;
4257 while ( node = walker.nextNode() ) {
4258 data = node.data;
4259 parent = node.parentNode;
4260 while ( match = linkRegExp.exec( data ) ) {
4261 index = match.index;
4262 endIndex = index + match[0].length;
4263 if ( index ) {
4264 child = doc.createTextNode( data.slice( 0, index ) );
4265 parent.insertBefore( child, node );
4266 }
4267 child = self.createElement( 'A', mergeObjects({
4268 href: match[1] ?
4269 /^(?:ht|f)tps?:/.test( match[1] ) ?
4270 match[1] :
4271 'http://' + match[1] :
4272 'mailto:' + match[2]
4273 }, defaultAttributes, false ));
4274 child.textContent = data.slice( index, endIndex );
4275 parent.insertBefore( child, node );
4276 node.data = data = data.slice( endIndex );
4277 }
4278 }
4279 };
4280
4281 // Insert HTML at the cursor location. If the selection is not collapsed
4282 // insertTreeFragmentIntoRange will delete the selection so that it is replaced
4283 // by the html being inserted.
4284 proto.insertHTML = function ( html, isPaste ) {
4285 var config = this._config;
4286 var sanitizeToDOMFragment = config.isInsertedHTMLSanitized ?
4287 config.sanitizeToDOMFragment : null;
4288 var range = this.getSelection();
4289 var doc = this._doc;
4290 var startFragmentIndex, endFragmentIndex;
4291 var div, frag, root, node, event;
4292
4293 // Edge doesn't just copy the fragment, but includes the surrounding guff
4294 // including the full <head> of the page. Need to strip this out. If
4295 // available use DOMPurify to parse and sanitise.
4296 if ( typeof sanitizeToDOMFragment === 'function' ) {
4297 frag = sanitizeToDOMFragment( html, isPaste, this );
4298 } else {
4299 if ( isPaste ) {
4300 startFragmentIndex = html.indexOf( '<!--StartFragment-->' );
4301 endFragmentIndex = html.lastIndexOf( '<!--EndFragment-->' );
4302 if ( startFragmentIndex > -1 && endFragmentIndex > -1 ) {
4303 html = html.slice( startFragmentIndex + 20, endFragmentIndex );
4304 }
4305 }
4306 // Wrap with <tr> if html contains dangling <td> tags
4307 if ( /<\/td>((?!<\/tr>)[\s\S])*$/i.test( html ) ) {
4308 html = '<TR>' + html + '</TR>';
4309 }
4310 // Wrap with <table> if html contains dangling <tr> tags
4311 if ( /<\/tr>((?!<\/table>)[\s\S])*$/i.test( html ) ) {
4312 html = '<TABLE>' + html + '</TABLE>';
4313 }
4314 // Parse HTML into DOM tree
4315 div = this.createElement( 'DIV' );
4316 div.innerHTML = html;
4317 frag = doc.createDocumentFragment();
4318 frag.appendChild( empty( div ) );
4319 }
4320
4321 // Record undo checkpoint
4322 this.saveUndoState( range );
4323
4324 try {
4325 root = this._root;
4326 node = frag;
4327 event = {
4328 fragment: frag,
4329 preventDefault: function () {
4330 this.defaultPrevented = true;
4331 },
4332 defaultPrevented: false
4333 };
4334
4335 addLinks( frag, frag, this );
4336 cleanTree( frag );
4337 cleanupBRs( frag, root, false );
4338 removeEmptyInlines( frag );
4339 frag.normalize();
4340
4341 while ( node = getNextBlock( node, frag ) ) {
4342 fixCursor( node, root );
4343 }
4344
4345 if ( isPaste ) {
4346 this.fireEvent( 'willPaste', event );
4347 }
4348
4349 if ( !event.defaultPrevented ) {
4350 insertTreeFragmentIntoRange( range, event.fragment, root );
4351 if ( !canObserveMutations ) {
4352 this._docWasChanged();
4353 }
4354 range.collapse( false );
4355 this._ensureBottomLine();
4356 }
4357
4358 this.setSelection( range );
4359 this._updatePath( range, true );
4360 // Safari sometimes loses focus after paste. Weird.
4361 if ( isPaste ) {
4362 this.focus();
4363 }
4364 } catch ( error ) {
4365 this.didError( error );
4366 }
4367 return this;
4368 };
4369
4370 var escapeHTMLFragement = function ( text ) {
4371 return text.split( '&' ).join( '&amp;' )
4372 .split( '<' ).join( '&lt;' )
4373 .split( '>' ).join( '&gt;' )
4374 .split( '"' ).join( '&quot;' );
4375 };
4376
4377 proto.insertPlainText = function ( plainText, isPaste ) {
4378 var lines = plainText.split( '\n' );
4379 var config = this._config;
4380 var tag = config.blockTag;
4381 var attributes = config.blockAttributes;
4382 var closeBlock = '</' + tag + '>';
4383 var openBlock = '<' + tag;
4384 var attr, i, l, line;
4385
4386 for ( attr in attributes ) {
4387 openBlock += ' ' + attr + '="' +
4388 escapeHTMLFragement( attributes[ attr ] ) +
4389 '"';
4390 }
4391 openBlock += '>';
4392
4393 for ( i = 0, l = lines.length; i < l; i += 1 ) {
4394 line = lines[i];
4395 line = escapeHTMLFragement( line ).replace( / (?= )/g, '&nbsp;' );
4396 // Wrap each line in <div></div>
4397 lines[i] = openBlock + ( line || '<BR>' ) + closeBlock;
4398 }
4399 return this.insertHTML( lines.join( '' ), isPaste );
4400 };
4401
4402 // --- Formatting ---
4403
4404 var command = function ( method, arg, arg2 ) {
4405 return function () {
4406 this[ method ]( arg, arg2 );
4407 return this.focus();
4408 };
4409 };
4410
4411 proto.addStyles = function ( styles ) {
4412 if ( styles ) {
4413 var head = this._doc.documentElement.firstChild,
4414 style = this.createElement( 'STYLE', {
4415 type: 'text/css'
4416 });
4417 style.appendChild( this._doc.createTextNode( styles ) );
4418 head.appendChild( style );
4419 }
4420 return this;
4421 };
4422
4423 proto.bold = command( 'changeFormat', { tag: 'B' } );
4424 proto.italic = command( 'changeFormat', { tag: 'I' } );
4425 proto.underline = command( 'changeFormat', { tag: 'U' } );
4426 proto.strikethrough = command( 'changeFormat', { tag: 'S' } );
4427 proto.subscript = command( 'changeFormat', { tag: 'SUB' }, { tag: 'SUP' } );
4428 proto.superscript = command( 'changeFormat', { tag: 'SUP' }, { tag: 'SUB' } );
4429
4430 proto.removeBold = command( 'changeFormat', null, { tag: 'B' } );
4431 proto.removeItalic = command( 'changeFormat', null, { tag: 'I' } );
4432 proto.removeUnderline = command( 'changeFormat', null, { tag: 'U' } );
4433 proto.removeStrikethrough = command( 'changeFormat', null, { tag: 'S' } );
4434 proto.removeSubscript = command( 'changeFormat', null, { tag: 'SUB' } );
4435 proto.removeSuperscript = command( 'changeFormat', null, { tag: 'SUP' } );
4436
4437 proto.makeLink = function ( url, attributes ) {
4438 var range = this.getSelection();
4439 if ( range.collapsed ) {
4440 var protocolEnd = url.indexOf( ':' ) + 1;
4441 if ( protocolEnd ) {
4442 while ( url[ protocolEnd ] === '/' ) { protocolEnd += 1; }
4443 }
4444 insertNodeInRange(
4445 range,
4446 this._doc.createTextNode( url.slice( protocolEnd ) )
4447 );
4448 }
4449 attributes = mergeObjects(
4450 mergeObjects({
4451 href: url
4452 }, attributes, true ),
4453 this._config.tagAttributes.a,
4454 false
4455 );
4456
4457 this.changeFormat({
4458 tag: 'A',
4459 attributes: attributes
4460 }, {
4461 tag: 'A'
4462 }, range );
4463 return this.focus();
4464 };
4465 proto.removeLink = function () {
4466 this.changeFormat( null, {
4467 tag: 'A'
4468 }, this.getSelection(), true );
4469 return this.focus();
4470 };
4471
4472 proto.setFontFace = function ( name ) {
4473 this.changeFormat( name ? {
4474 tag: 'SPAN',
4475 attributes: {
4476 'class': FONT_FAMILY_CLASS,
4477 style: 'font-family: ' + name + ', sans-serif;'
4478 }
4479 } : null, {
4480 tag: 'SPAN',
4481 attributes: { 'class': FONT_FAMILY_CLASS }
4482 });
4483 return this.focus();
4484 };
4485 proto.setFontSize = function ( size ) {
4486 this.changeFormat( size ? {
4487 tag: 'SPAN',
4488 attributes: {
4489 'class': FONT_SIZE_CLASS,
4490 style: 'font-size: ' +
4491 ( typeof size === 'number' ? size + 'px' : size )
4492 }
4493 } : null, {
4494 tag: 'SPAN',
4495 attributes: { 'class': FONT_SIZE_CLASS }
4496 });
4497 return this.focus();
4498 };
4499
4500 proto.setTextColour = function ( colour ) {
4501 this.changeFormat( colour ? {
4502 tag: 'SPAN',
4503 attributes: {
4504 'class': COLOUR_CLASS,
4505 style: 'color:' + colour
4506 }
4507 } : null, {
4508 tag: 'SPAN',
4509 attributes: { 'class': COLOUR_CLASS }
4510 });
4511 return this.focus();
4512 };
4513
4514 proto.setHighlightColour = function ( colour ) {
4515 this.changeFormat( colour ? {
4516 tag: 'SPAN',
4517 attributes: {
4518 'class': HIGHLIGHT_CLASS,
4519 style: 'background-color:' + colour
4520 }
4521 } : colour, {
4522 tag: 'SPAN',
4523 attributes: { 'class': HIGHLIGHT_CLASS }
4524 });
4525 return this.focus();
4526 };
4527
4528 proto.setTextAlignment = function ( alignment ) {
4529 this.forEachBlock( function ( block ) {
4530 var className = block.className
4531 .split( /\s+/ )
4532 .filter( function ( klass ) {
4533 return !!klass && !/^align/.test( klass );
4534 })
4535 .join( ' ' );
4536 if ( alignment ) {
4537 block.className = className + ' align-' + alignment;
4538 block.style.textAlign = alignment;
4539 } else {
4540 block.className = className;
4541 block.style.textAlign = '';
4542 }
4543 }, true );
4544 return this.focus();
4545 };
4546
4547 proto.setTextDirection = function ( direction ) {
4548 this.forEachBlock( function ( block ) {
4549 if ( direction ) {
4550 block.dir = direction;
4551 } else {
4552 block.removeAttribute( 'dir' );
4553 }
4554 }, true );
4555 return this.focus();
4556 };
4557
4558 function removeFormatting ( self, root, clean ) {
4559 var node, next;
4560 for ( node = root.firstChild; node; node = next ) {
4561 next = node.nextSibling;
4562 if ( isInline( node ) ) {
4563 if ( node.nodeType === TEXT_NODE || node.nodeName === 'BR' || node.nodeName === 'IMG' ) {
4564 clean.appendChild( node );
4565 continue;
4566 }
4567 } else if ( isBlock( node ) ) {
4568 clean.appendChild( self.createDefaultBlock([
4569 removeFormatting(
4570 self, node, self._doc.createDocumentFragment() )
4571 ]));
4572 continue;
4573 }
4574 removeFormatting( self, node, clean );
4575 }
4576 return clean;
4577 }
4578
4579 proto.removeAllFormatting = function ( range ) {
4580 if ( !range && !( range = this.getSelection() ) || range.collapsed ) {
4581 return this;
4582 }
4583
4584 var root = this._root;
4585 var stopNode = range.commonAncestorContainer;
4586 while ( stopNode && !isBlock( stopNode ) ) {
4587 stopNode = stopNode.parentNode;
4588 }
4589 if ( !stopNode ) {
4590 expandRangeToBlockBoundaries( range, root );
4591 stopNode = root;
4592 }
4593 if ( stopNode.nodeType === TEXT_NODE ) {
4594 return this;
4595 }
4596
4597 // Record undo point
4598 this.saveUndoState( range );
4599
4600 // Avoid splitting where we're already at edges.
4601 moveRangeBoundariesUpTree( range, stopNode, stopNode, root );
4602
4603 // Split the selection up to the block, or if whole selection in same
4604 // block, expand range boundaries to ends of block and split up to root.
4605 var doc = stopNode.ownerDocument;
4606 var startContainer = range.startContainer;
4607 var startOffset = range.startOffset;
4608 var endContainer = range.endContainer;
4609 var endOffset = range.endOffset;
4610
4611 // Split end point first to avoid problems when end and start
4612 // in same container.
4613 var formattedNodes = doc.createDocumentFragment();
4614 var cleanNodes = doc.createDocumentFragment();
4615 var nodeAfterSplit = split( endContainer, endOffset, stopNode, root );
4616 var nodeInSplit = split( startContainer, startOffset, stopNode, root );
4617 var nextNode, childNodes;
4618
4619 // Then replace contents in split with a cleaned version of the same:
4620 // blocks become default blocks, text and leaf nodes survive, everything
4621 // else is obliterated.
4622 while ( nodeInSplit !== nodeAfterSplit ) {
4623 nextNode = nodeInSplit.nextSibling;
4624 formattedNodes.appendChild( nodeInSplit );
4625 nodeInSplit = nextNode;
4626 }
4627 removeFormatting( this, formattedNodes, cleanNodes );
4628 cleanNodes.normalize();
4629 nodeInSplit = cleanNodes.firstChild;
4630 nextNode = cleanNodes.lastChild;
4631
4632 // Restore selection
4633 childNodes = stopNode.childNodes;
4634 if ( nodeInSplit ) {
4635 stopNode.insertBefore( cleanNodes, nodeAfterSplit );
4636 startOffset = indexOf.call( childNodes, nodeInSplit );
4637 endOffset = indexOf.call( childNodes, nextNode ) + 1;
4638 } else {
4639 startOffset = indexOf.call( childNodes, nodeAfterSplit );
4640 endOffset = startOffset;
4641 }
4642
4643 // Merge text nodes at edges, if possible
4644 range.setStart( stopNode, startOffset );
4645 range.setEnd( stopNode, endOffset );
4646 mergeInlines( stopNode, range );
4647
4648 // And move back down the tree
4649 moveRangeBoundariesDownTree( range );
4650
4651 this.setSelection( range );
4652 this._updatePath( range, true );
4653
4654 return this.focus();
4655 };
4656
4657 proto.increaseQuoteLevel = command( 'modifyBlocks', increaseBlockQuoteLevel );
4658 proto.decreaseQuoteLevel = command( 'modifyBlocks', decreaseBlockQuoteLevel );
4659
4660 proto.makeUnorderedList = command( 'modifyBlocks', makeUnorderedList );
4661 proto.makeOrderedList = command( 'modifyBlocks', makeOrderedList );
4662 proto.removeList = command( 'modifyBlocks', removeList );
4663
4664 // Node.js exports
4665 Squire.isInline = isInline;
4666 Squire.isBlock = isBlock;
4667 Squire.isContainer = isContainer;
4668 Squire.getBlockWalker = getBlockWalker;
4669 Squire.getPreviousBlock = getPreviousBlock;
4670 Squire.getNextBlock = getNextBlock;
4671 Squire.areAlike = areAlike;
4672 Squire.hasTagAttributes = hasTagAttributes;
4673 Squire.getNearest = getNearest;
4674 Squire.isOrContains = isOrContains;
4675 Squire.detach = detach;
4676 Squire.replaceWith = replaceWith;
4677 Squire.empty = empty;
4678
4679 // Range.js exports
4680 Squire.getNodeBefore = getNodeBefore;
4681 Squire.getNodeAfter = getNodeAfter;
4682 Squire.insertNodeInRange = insertNodeInRange;
4683 Squire.extractContentsOfRange = extractContentsOfRange;
4684 Squire.deleteContentsOfRange = deleteContentsOfRange;
4685 Squire.insertTreeFragmentIntoRange = insertTreeFragmentIntoRange;
4686 Squire.isNodeContainedInRange = isNodeContainedInRange;
4687 Squire.moveRangeBoundariesDownTree = moveRangeBoundariesDownTree;
4688 Squire.moveRangeBoundariesUpTree = moveRangeBoundariesUpTree;
4689 Squire.getStartBlockOfRange = getStartBlockOfRange;
4690 Squire.getEndBlockOfRange = getEndBlockOfRange;
4691 Squire.contentWalker = contentWalker;
4692 Squire.rangeDoesStartAtBlockBoundary = rangeDoesStartAtBlockBoundary;
4693 Squire.rangeDoesEndAtBlockBoundary = rangeDoesEndAtBlockBoundary;
4694 Squire.expandRangeToBlockBoundaries = expandRangeToBlockBoundaries;
4695
4696 // Clipboard.js exports
4697 Squire.onPaste = onPaste;
4698
4699 // Editor.js exports
4700 Squire.addLinks = addLinks;
4701 Squire.splitBlock = splitBlock;
4702 Squire.startSelectionId = startSelectionId;
4703 Squire.endSelectionId = endSelectionId;
4704
4705 if ( typeof exports === 'object' ) {
4706 module.exports = Squire;
4707 } else if ( typeof define === 'function' && define.amd ) {
4708 define( function () {
4709 return Squire;
4710 });
4711 } else {
4712 win.Squire = Squire;
4713
4714 if ( top !== win &&
4715 doc.documentElement.getAttribute( 'data-squireinit' ) === 'true' ) {
4716 win.editor = new Squire( doc );
4717 if ( win.onEditorLoad ) {
4718 win.onEditorLoad( win.editor );
4719 win.onEditorLoad = null;
4720 }
4721 }
4722 }
4723
4724 }( document ) );
4725
4726 window.editor = new Squire(document.body);
4727 oxide.addMessageHandler("focus", function(msg) { window.editor.focus(); });
4728 oxide.addMessageHandler("blur", function(msg) { window.editor.blur(); });
4729 oxide.addMessageHandler("bold", function(msg) {
4730 var e = window.editor;
4731 if (!e.hasFormat('B')) {
4732 window.editor.bold();
4733 }
4734 });
4735 oxide.addMessageHandler("removeBold", function(msg) {
4736 var e = window.editor;
4737 if (e.hasFormat('B')) {
4738 window.editor.removeBold();
4739 }
4740 });
4741 oxide.addMessageHandler("italic", function(msg) {
4742 var e = window.editor;
4743 if (!e.hasFormat('I')) {
4744 window.editor.italic();
4745 }
4746 });
4747 oxide.addMessageHandler("removeItalic", function(msg) {
4748 var e = window.editor;
4749 if (e.hasFormat('I')) {
4750 window.editor.removeItalic();
4751 }
4752 });
4753 oxide.addMessageHandler("underline", function(msg) {
4754 var e = window.editor;
4755 if (!e.hasFormat('U')) {
4756 window.editor.underline();
4757 }
4758 });
4759 oxide.addMessageHandler("removeUnderline", function(msg) {
4760 var e = window.editor;
4761 if (e.hasFormat('U')) {
4762 window.editor.removeUnderline();
4763 }
4764 });
4765 oxide.addMessageHandler("strikethrough", function(msg) { window.editor.strikethrough(); });
4766 oxide.addMessageHandler("removeStrikethrough", function(msg) { window.editor.removeStrikethrough(); });
4767 oxide.addMessageHandler("subscript", function(msg) { window.editor.subscript(); });
4768 oxide.addMessageHandler("removeSubscript", function(msg) { window.editor.removeSubscript(); });
4769 oxide.addMessageHandler("superscript", function(msg) { window.editor.superscript(); });
4770 oxide.addMessageHandler("removeSuperscript", function(msg) { window.editor.removeSuperscript(); });
4771 oxide.addMessageHandler("hasFormat", function(msg) { msg.reply({ 'prop': msg.payload, 'value': window.editor.hasFormat(msg.payload)}); });
4772 oxide.addMessageHandler("undo", function(msg) { window.editor.undo(); });
4773 oxide.addMessageHandler("redo", function(msg) { window.editor.redo(); });
4774 oxide.addMessageHandler("getHTML", function(msg) { msg.reply(window.editor.getHTML()); });
4775 oxide.addMessageHandler("setHTML", function(msg) { window.editor.setHTML(msg.payload); });
4776 oxide.addMessageHandler("getCursorPosition", function(msg) { msg.reply(window.editor.getCursorPosition()); });
4777 oxide.addMessageHandler('makeLink', function(msg) { window.editor.makeLink(msg.payload.url, msg.payload.attrs); });
4778 oxide.addMessageHandler('setTextAlignment', function(msg) { window.editor.setTextAlignment(msg.payload); });
4779 oxide.addMessageHandler('setTextDirection', function(msg) { window.editor.setTextDirection(msg.payload); });
4780 oxide.addMessageHandler('increaseQuoteLevel', function(msg) { window.editor.increaseQuoteLevel(); });
4781 oxide.addMessageHandler('decreaseQuoteLevel', function(msg) { window.editor.decreaseQuoteLevel(); });
4782 oxide.addMessageHandler('makeUnorderedList', function(msg) { window.editor.makeUnorderedList(); });
4783 oxide.addMessageHandler('makeOrderedList', function(msg) { window.editor.makeOrderedList(); });
4784 oxide.addMessageHandler('removeList', function(msg) { window.editor.removeList(); });
4785 oxide.addMessageHandler('increaseListLevel', function(msg) { window.editor.increaseListLevel(); });
4786 oxide.addMessageHandler('decreaseListLevel', function(msg) { window.editor.decreaseListLevel(); });
4787 oxide.addMessageHandler('removeAllFormatting', function(msg) { window.editor.removeAllFormatting(); });