-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
range.js
2678 lines (2283 loc) · 87.7 KB
/
range.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* Represents a delimited piece of content in a DOM Document.
* It is contiguous in the sense that it can be characterized as selecting all
* of the content between a pair of boundary-points.
*
* This class shares much of the W3C
* [Document Object Model Range](http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html)
* ideas and features, adding several range manipulation tools to it, but it's
* not intended to be compatible with it.
*
* // Create a range for the entire contents of the editor document body.
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* // Delete the contents.
* range.deleteContents();
*
* Usually you will want to work on a ranges rooted in the editor's {@link CKEDITOR.editable editable}
* element. Such ranges can be created with a shorthand method – {@link CKEDITOR.editor#createRange editor.createRange}.
*
* var range = editor.createRange();
* range.root.equals( editor.editable() ); // -> true
*
* Note that the {@link #root} of a range is an important property, which limits many
* algorithms implemented in range's methods. Therefore it is crucial, especially
* when using ranges inside inline editors, to specify correct root, so using
* the {@link CKEDITOR.editor#createRange} method is highly recommended.
*
* ### Selection
*
* Range is only a logical representation of a piece of content in a DOM. It should not
* be confused with a {@link CKEDITOR.dom.selection selection} which represents "physically
* marked" content. It is possible to create unlimited number of various ranges, when
* only one real selection may exist at a time in a document. Ranges are used to read position
* of selection in the DOM and to move selection to new positions.
*
* The editor selection may be retrieved using the {@link CKEDITOR.editor#getSelection} method:
*
* var sel = editor.getSelection(),
* ranges = sel.getRange(); // CKEDITOR.dom.rangeList instance.
*
* var range = ranges[ 0 ];
* range.root; // -> editor's editable element.
*
* A range can also be selected:
*
* var range = editor.createRange();
* range.selectNodeContents( editor.editable() );
* sel.selectRanges( [ range ] );
*
* @class
* @constructor Creates a {@link CKEDITOR.dom.range} instance that can be used inside a specific DOM Document.
* @param {CKEDITOR.dom.document/CKEDITOR.dom.element} root The document or element
* within which the range will be scoped.
* @todo global "TODO" - precise algorithms descriptions needed for the most complex methods like #enlarge.
*/
CKEDITOR.dom.range = function( root ) {
/**
* Node within which the range begins.
*
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.startContainer.getName() ); // 'body'
*
* @readonly
* @property {CKEDITOR.dom.element/CKEDITOR.dom.text}
*/
this.startContainer = null;
/**
* Offset within the starting node of the range.
*
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.startOffset ); // 0
*
* @readonly
* @property {Number}
*/
this.startOffset = null;
/**
* Node within which the range ends.
*
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.endContainer.getName() ); // 'body'
*
* @readonly
* @property {CKEDITOR.dom.element/CKEDITOR.dom.text}
*/
this.endContainer = null;
/**
* Offset within the ending node of the range.
*
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.endOffset ); // == editor.document.getBody().getChildCount()
*
* @readonly
* @property {Number}
*/
this.endOffset = null;
/**
* Indicates that this is a collapsed range. A collapsed range has its
* start and end boundaries at the very same point so nothing is contained
* in it.
*
* var range = new CKEDITOR.dom.range( editor.document );
* range.selectNodeContents( editor.document.getBody() );
* alert( range.collapsed ); // false
* range.collapse();
* alert( range.collapsed ); // true
*
* @readonly
*/
this.collapsed = true;
var isDocRoot = root instanceof CKEDITOR.dom.document;
/**
* The document within which the range can be used.
*
* // Selects the body contents of the range document.
* range.selectNodeContents( range.document.getBody() );
*
* @readonly
* @property {CKEDITOR.dom.document}
*/
this.document = isDocRoot ? root : root.getDocument();
/**
* The ancestor DOM element within which the range manipulation are limited.
*
* @readonly
* @property {CKEDITOR.dom.element}
*/
this.root = isDocRoot ? root.getBody() : root;
};
( function() {
// Updates the "collapsed" property for the given range object.
var updateCollapsed = function( range ) {
range.collapsed = ( range.startContainer && range.endContainer && range.startContainer.equals( range.endContainer ) && range.startOffset == range.endOffset );
};
// This is a shared function used to delete, extract and clone the range
// contents.
// V2
var execContentsAction = function( range, action, docFrag, mergeThen ) {
range.optimizeBookmark();
var startNode = range.startContainer;
var endNode = range.endContainer;
var startOffset = range.startOffset;
var endOffset = range.endOffset;
var removeStartNode;
var removeEndNode;
// For text containers, we must simply split the node and point to the
// second part. The removal will be handled by the rest of the code .
if ( endNode.type == CKEDITOR.NODE_TEXT )
endNode = endNode.split( endOffset );
else {
// If the end container has children and the offset is pointing
// to a child, then we should start from it.
if ( endNode.getChildCount() > 0 ) {
// If the offset points after the last node.
if ( endOffset >= endNode.getChildCount() ) {
// Let's create a temporary node and mark it for removal.
endNode = endNode.append( range.document.createText( '' ) );
removeEndNode = true;
} else {
endNode = endNode.getChild( endOffset );
}
}
}
// For text containers, we must simply split the node. The removal will
// be handled by the rest of the code .
if ( startNode.type == CKEDITOR.NODE_TEXT ) {
startNode.split( startOffset );
// In cases the end node is the same as the start node, the above
// splitting will also split the end, so me must move the end to
// the second part of the split.
if ( startNode.equals( endNode ) )
endNode = startNode.getNext();
} else {
// If the start container has children and the offset is pointing
// to a child, then we should start from its previous sibling.
// If the offset points to the first node, we don't have a
// sibling, so let's use the first one, but mark it for removal.
if ( !startOffset ) {
// Let's create a temporary node and mark it for removal.
startNode = startNode.append( range.document.createText( '' ), 1 );
removeStartNode = true;
} else if ( startOffset >= startNode.getChildCount() ) {
// Let's create a temporary node and mark it for removal.
startNode = startNode.append( range.document.createText( '' ) );
removeStartNode = true;
} else {
startNode = startNode.getChild( startOffset ).getPrevious();
}
}
// Get the parent nodes tree for the start and end boundaries.
var startParents = startNode.getParents();
var endParents = endNode.getParents();
// Compare them, to find the top most siblings.
var i, topStart, topEnd;
for ( i = 0; i < startParents.length; i++ ) {
topStart = startParents[ i ];
topEnd = endParents[ i ];
// The compared nodes will match until we find the top most
// siblings (different nodes that have the same parent).
// "i" will hold the index in the parents array for the top
// most element.
if ( !topStart.equals( topEnd ) )
break;
}
var clone = docFrag,
levelStartNode, levelClone, currentNode, currentSibling;
// Remove all successive sibling nodes for every node in the
// startParents tree.
for ( var j = i; j < startParents.length; j++ ) {
levelStartNode = startParents[ j ];
// For Extract and Clone, we must clone this level.
if ( clone && !levelStartNode.equals( startNode ) ) // action = 0 = Delete
levelClone = clone.append( levelStartNode.clone() );
currentNode = levelStartNode.getNext();
while ( currentNode ) {
// Stop processing when the current node matches a node in the
// endParents tree or if it is the endNode.
if ( currentNode.equals( endParents[ j ] ) || currentNode.equals( endNode ) )
break;
// Cache the next sibling.
currentSibling = currentNode.getNext();
// If cloning, just clone it.
if ( action == 2 ) // 2 = Clone
clone.append( currentNode.clone( true ) );
else {
// Both Delete and Extract will remove the node.
currentNode.remove();
// When Extracting, move the removed node to the docFrag.
if ( action == 1 ) // 1 = Extract
clone.append( currentNode );
}
currentNode = currentSibling;
}
if ( clone )
clone = levelClone;
}
clone = docFrag;
// Remove all previous sibling nodes for every node in the
// endParents tree.
for ( var k = i; k < endParents.length; k++ ) {
levelStartNode = endParents[ k ];
// For Extract and Clone, we must clone this level.
if ( action > 0 && !levelStartNode.equals( endNode ) ) // action = 0 = Delete
levelClone = clone.append( levelStartNode.clone() );
// The processing of siblings may have already been done by the parent.
if ( !startParents[ k ] || levelStartNode.$.parentNode != startParents[ k ].$.parentNode ) {
currentNode = levelStartNode.getPrevious();
while ( currentNode ) {
// Stop processing when the current node matches a node in the
// startParents tree or if it is the startNode.
if ( currentNode.equals( startParents[ k ] ) || currentNode.equals( startNode ) )
break;
// Cache the next sibling.
currentSibling = currentNode.getPrevious();
// If cloning, just clone it.
if ( action == 2 ) // 2 = Clone
clone.$.insertBefore( currentNode.$.cloneNode( true ), clone.$.firstChild );
else {
// Both Delete and Extract will remove the node.
currentNode.remove();
// When Extracting, mode the removed node to the docFrag.
if ( action == 1 ) // 1 = Extract
clone.$.insertBefore( currentNode.$, clone.$.firstChild );
}
currentNode = currentSibling;
}
}
if ( clone )
clone = levelClone;
}
// 2 = Clone.
if ( action == 2 ) {
// No changes in the DOM should be done, so fix the split text (if any).
var startTextNode = range.startContainer;
if ( startTextNode.type == CKEDITOR.NODE_TEXT ) {
startTextNode.$.data += startTextNode.$.nextSibling.data;
startTextNode.$.parentNode.removeChild( startTextNode.$.nextSibling );
}
var endTextNode = range.endContainer;
if ( endTextNode.type == CKEDITOR.NODE_TEXT && endTextNode.$.nextSibling ) {
endTextNode.$.data += endTextNode.$.nextSibling.data;
endTextNode.$.parentNode.removeChild( endTextNode.$.nextSibling );
}
} else {
// Collapse the range.
// If a node has been partially selected, collapse the range between
// topStart and topEnd. Otherwise, simply collapse it to the start. (W3C specs).
if ( topStart && topEnd && ( startNode.$.parentNode != topStart.$.parentNode || endNode.$.parentNode != topEnd.$.parentNode ) ) {
var endIndex = topEnd.getIndex();
// If the start node is to be removed, we must correct the
// index to reflect the removal.
if ( removeStartNode && topEnd.$.parentNode == startNode.$.parentNode )
endIndex--;
// Merge splitted parents.
if ( mergeThen && topStart.type == CKEDITOR.NODE_ELEMENT ) {
var span = CKEDITOR.dom.element.createFromHtml( '<span ' +
'data-cke-bookmark="1" style="display:none"> </span>', range.document );
span.insertAfter( topStart );
topStart.mergeSiblings( false );
range.moveToBookmark( { startNode: span } );
} else {
range.setStart( topEnd.getParent(), endIndex );
}
}
// Collapse it to the start.
range.collapse( true );
}
// Cleanup any marked node.
if ( removeStartNode )
startNode.remove();
if ( removeEndNode && endNode.$.parentNode )
endNode.remove();
};
var inlineChildReqElements = {
abbr: 1, acronym: 1, b: 1, bdo: 1, big: 1, cite: 1, code: 1, del: 1,
dfn: 1, em: 1, font: 1, i: 1, ins: 1, label: 1, kbd: 1, q: 1, samp: 1, small: 1, span: 1, strike: 1,
strong: 1, sub: 1, sup: 1, tt: 1, u: 1, 'var': 1
};
// Creates the appropriate node evaluator for the dom walker used inside
// check(Start|End)OfBlock.
function getCheckStartEndBlockEvalFunction() {
var skipBogus = false,
whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmarkEvaluator = CKEDITOR.dom.walker.bookmark( true ),
isBogus = CKEDITOR.dom.walker.bogus();
return function( node ) {
// First skip empty nodes
if ( bookmarkEvaluator( node ) || whitespaces( node ) )
return true;
// Skip the bogus node at the end of block.
if ( isBogus( node ) && !skipBogus ) {
skipBogus = true;
return true;
}
// If there's any visible text, then we're not at the start.
if ( node.type == CKEDITOR.NODE_TEXT &&
( node.hasAscendant( 'pre' ) ||
CKEDITOR.tools.trim( node.getText() ).length ) ) {
return false;
}
// If there are non-empty inline elements (e.g. <img />), then we're not
// at the start.
if ( node.type == CKEDITOR.NODE_ELEMENT && !node.is( inlineChildReqElements ) )
return false;
return true;
};
}
var isBogus = CKEDITOR.dom.walker.bogus(),
nbspRegExp = /^[\t\r\n ]*(?: |\xa0)$/,
editableEval = CKEDITOR.dom.walker.editable(),
notIgnoredEval = CKEDITOR.dom.walker.ignored( true );
// Evaluator for CKEDITOR.dom.element::checkBoundaryOfElement, reject any
// text node and non-empty elements unless it's being bookmark text.
function elementBoundaryEval( checkStart ) {
var whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmark = CKEDITOR.dom.walker.bookmark( 1 );
return function( node ) {
// First skip empty nodes.
if ( bookmark( node ) || whitespaces( node ) )
return true;
// Tolerant bogus br when checking at the end of block.
// Reject any text node unless it's being bookmark
// OR it's spaces.
// Reject any element unless it's being invisible empty. (#3883)
return !checkStart && isBogus( node ) ||
node.type == CKEDITOR.NODE_ELEMENT &&
node.is( CKEDITOR.dtd.$removeEmpty );
};
}
function getNextEditableNode( isPrevious ) {
return function() {
var first;
return this[ isPrevious ? 'getPreviousNode' : 'getNextNode' ]( function( node ) {
// Cache first not ignorable node.
if ( !first && notIgnoredEval( node ) )
first = node;
// Return true if found editable node, but not a bogus next to start of our lookup (first != bogus).
return editableEval( node ) && !( isBogus( node ) && node.equals( first ) );
} );
};
}
CKEDITOR.dom.range.prototype = {
/**
* Clones this range.
*
* @returns {CKEDITOR.dom.range}
*/
clone: function() {
var clone = new CKEDITOR.dom.range( this.root );
clone._setStartContainer( this.startContainer );
clone.startOffset = this.startOffset;
clone._setEndContainer( this.endContainer );
clone.endOffset = this.endOffset;
clone.collapsed = this.collapsed;
return clone;
},
/**
* Makes range collapsed by moving its start point (or end point if `toStart==true`)
* to the second end.
*
* @param {Boolean} toStart Collapse range "to start".
*/
collapse: function( toStart ) {
if ( toStart ) {
this._setEndContainer( this.startContainer );
this.endOffset = this.startOffset;
} else {
this._setStartContainer( this.endContainer );
this.startOffset = this.endOffset;
}
this.collapsed = true;
},
/**
* The content nodes of the range are cloned and added to a document fragment, which is returned.
*
* **Note:** Text selection may lost after invoking this method (caused by text node splitting).
*
* @returns {CKEDITOR.dom.documentFragment} Document fragment containing clone of range's content.
*/
cloneContents: function() {
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
if ( !this.collapsed )
execContentsAction( this, 2, docFrag );
return docFrag;
},
/**
* Deletes the content nodes of the range permanently from the DOM tree.
*
* @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
*/
deleteContents: function( mergeThen ) {
if ( this.collapsed )
return;
execContentsAction( this, 0, null, mergeThen );
},
/**
* The content nodes of the range are cloned and added to a document fragment,
* meanwhile they are removed permanently from the DOM tree.
*
* @param {Boolean} [mergeThen] Merge any splitted elements result in DOM true due to partial selection.
* @returns {CKEDITOR.dom.documentFragment} Document fragment containing extracted content.
*/
extractContents: function( mergeThen ) {
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
if ( !this.collapsed )
execContentsAction( this, 1, docFrag, mergeThen );
return docFrag;
},
/**
* Creates a bookmark object, which can be later used to restore the
* range by using the {@link #moveToBookmark} function.
*
* This is an "intrusive" way to create a bookmark. It includes `<span>` tags
* in the range boundaries. The advantage of it is that it is possible to
* handle DOM mutations when moving back to the bookmark.
*
* **Note:** The inclusion of nodes in the DOM is a design choice and
* should not be changed as there are other points in the code that may be
* using those nodes to perform operations.
*
* @param {Boolean} [serializable] Indicates that the bookmark nodes
* must contain IDs, which can be used to restore the range even
* when these nodes suffer mutations (like cloning or `innerHTML` change).
* @returns {Object} And object representing a bookmark.
* @returns {CKEDITOR.dom.node/String} return.startNode Node or element ID.
* @returns {CKEDITOR.dom.node/String} return.endNode Node or element ID.
* @returns {Boolean} return.serializable
* @returns {Boolean} return.collapsed
*/
createBookmark: function( serializable ) {
var startNode, endNode;
var baseId;
var clone;
var collapsed = this.collapsed;
startNode = this.document.createElement( 'span' );
startNode.data( 'cke-bookmark', 1 );
startNode.setStyle( 'display', 'none' );
// For IE, it must have something inside, otherwise it may be
// removed during DOM operations.
startNode.setHtml( ' ' );
if ( serializable ) {
baseId = 'cke_bm_' + CKEDITOR.tools.getNextNumber();
startNode.setAttribute( 'id', baseId + ( collapsed ? 'C' : 'S' ) );
}
// If collapsed, the endNode will not be created.
if ( !collapsed ) {
endNode = startNode.clone();
endNode.setHtml( ' ' );
if ( serializable )
endNode.setAttribute( 'id', baseId + 'E' );
clone = this.clone();
clone.collapse();
clone.insertNode( endNode );
}
clone = this.clone();
clone.collapse( true );
clone.insertNode( startNode );
// Update the range position.
if ( endNode ) {
this.setStartAfter( startNode );
this.setEndBefore( endNode );
} else {
this.moveToPosition( startNode, CKEDITOR.POSITION_AFTER_END );
}
return {
startNode: serializable ? baseId + ( collapsed ? 'C' : 'S' ) : startNode,
endNode: serializable ? baseId + 'E' : endNode,
serializable: serializable,
collapsed: collapsed
};
},
/**
* Creates a "non intrusive" and "mutation sensible" bookmark. This
* kind of bookmark should be used only when the DOM is supposed to
* remain stable after its creation.
*
* @param {Boolean} [normalized] Indicates that the bookmark must
* be normalized. When normalized, the successive text nodes are
* considered a single node. To successfully load a normalized
* bookmark, the DOM tree must also be normalized before calling
* {@link #moveToBookmark}.
* @returns {Object} An object representing the bookmark.
* @returns {Array} return.start Start container's address (see {@link CKEDITOR.dom.node#getAddress}).
* @returns {Array} return.end Start container's address.
* @returns {Number} return.startOffset
* @returns {Number} return.endOffset
* @returns {Boolean} return.collapsed
* @returns {Boolean} return.normalized
* @returns {Boolean} return.is2 This is "bookmark2".
*/
createBookmark2: ( function() {
var isNotText = CKEDITOR.dom.walker.nodeType( CKEDITOR.NODE_TEXT, true );
// Returns true for limit anchored in element and placed between text nodes.
//
// v
// <p>[text node] [text node]</p> -> true
//
// v
// <p> [text node]</p> -> false
//
// v
// <p>[text node][text node]</p> -> false (limit is anchored in text node)
function betweenTextNodes( container, offset ) {
// Not anchored in element or limit is on the edge.
if ( container.type != CKEDITOR.NODE_ELEMENT || offset === 0 || offset == container.getChildCount() )
return 0;
return container.getChild( offset - 1 ).type == CKEDITOR.NODE_TEXT &&
container.getChild( offset ).type == CKEDITOR.NODE_TEXT;
}
// Sums lengths of all preceding text nodes.
function getLengthOfPrecedingTextNodes( node ) {
var sum = 0;
while ( ( node = node.getPrevious() ) && node.type == CKEDITOR.NODE_TEXT )
sum += node.getLength();
return sum;
}
function normalize( limit ) {
var container = limit.container,
offset = limit.offset;
// If limit is between text nodes move it to the end of preceding one,
// because they will be merged.
if ( betweenTextNodes( container, offset ) ) {
container = container.getChild( offset - 1 );
offset = container.getLength();
}
// Now, if limit is anchored in element and has at least two nodes before it,
// it may happen that some of them will be merged. Normalize the offset
// by setting it to normalized index of its preceding node.
if ( container.type == CKEDITOR.NODE_ELEMENT && offset > 1 )
offset = container.getChild( offset - 1 ).getIndex( true ) + 1;
// The last step - fix the offset inside text node by adding
// lengths of preceding text nodes which will be merged with container.
if ( container.type == CKEDITOR.NODE_TEXT ) {
var precedingLength = getLengthOfPrecedingTextNodes( container );
// Normal case - text node is not empty.
if ( container.getText() ) {
offset += precedingLength;
// Awful case - the text node is empty and thus will be totally lost.
// In this case we are trying to normalize the limit to the left:
// * either to the preceding text node,
// * or to the "gap" after the preceding element.
} else {
// Find the closest non-text sibling.
var precedingContainer = container.getPrevious( isNotText );
// If there are any characters on the left, that means that we can anchor
// there, because this text node will not be lost.
if ( precedingLength ) {
offset = precedingLength;
if ( precedingContainer ) {
// The text node is the first node after the closest non-text sibling.
container = precedingContainer.getNext();
} else {
// But if there was no non-text sibling, then the text node is the first child.
container = container.getParent().getFirst();
}
// If there are no characters on the left, then anchor after the previous non-text node.
// E.g. (see tests for a legend :D):
// <b>x</b>(foo)({}bar) -> <b>x</b>[](foo)(bar)
} else {
container = container.getParent();
offset = precedingContainer ? ( precedingContainer.getIndex( true ) + 1 ) : 0;
}
}
}
limit.container = container;
limit.offset = offset;
}
return function( normalized ) {
var collapsed = this.collapsed,
bmStart = {
container: this.startContainer,
offset: this.startOffset
},
bmEnd = {
container: this.endContainer,
offset: this.endOffset
};
if ( normalized ) {
normalize( bmStart );
if ( !collapsed )
normalize( bmEnd );
}
return {
start: bmStart.container.getAddress( normalized ),
end: collapsed ? null : bmEnd.container.getAddress( normalized ),
startOffset: bmStart.offset,
endOffset: bmEnd.offset,
normalized: normalized,
collapsed: collapsed,
is2: true // It's a createBookmark2 bookmark.
};
};
} )(),
/**
* Moves this range to the given bookmark. See {@link #createBookmark} and {@link #createBookmark2}.
*
* If serializable bookmark passed, then its `<span>` markers will be removed.
*
* @param {Object} bookmark
*/
moveToBookmark: function( bookmark ) {
// Created with createBookmark2().
if ( bookmark.is2 ) {
// Get the start information.
var startContainer = this.document.getByAddress( bookmark.start, bookmark.normalized ),
startOffset = bookmark.startOffset;
// Get the end information.
var endContainer = bookmark.end && this.document.getByAddress( bookmark.end, bookmark.normalized ),
endOffset = bookmark.endOffset;
// Set the start boundary.
this.setStart( startContainer, startOffset );
// Set the end boundary. If not available, collapse it.
if ( endContainer )
this.setEnd( endContainer, endOffset );
else
this.collapse( true );
}
// Created with createBookmark().
else {
var serializable = bookmark.serializable,
startNode = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode,
endNode = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode;
// Set the range start at the bookmark start node position.
this.setStartBefore( startNode );
// Remove it, because it may interfere in the setEndBefore call.
startNode.remove();
// Set the range end at the bookmark end node position, or simply
// collapse it if it is not available.
if ( endNode ) {
this.setEndBefore( endNode );
endNode.remove();
} else {
this.collapse( true );
}
}
},
/**
* Returns two nodes which are on the boundaries of this range.
*
* @returns {Object}
* @returns {CKEDITOR.dom.node} return.startNode
* @returns {CKEDITOR.dom.node} return.endNode
* @todo precise desc/algorithm
*/
getBoundaryNodes: function() {
var startNode = this.startContainer,
endNode = this.endContainer,
startOffset = this.startOffset,
endOffset = this.endOffset,
childCount;
if ( startNode.type == CKEDITOR.NODE_ELEMENT ) {
childCount = startNode.getChildCount();
if ( childCount > startOffset ) {
startNode = startNode.getChild( startOffset );
} else if ( childCount < 1 ) {
startNode = startNode.getPreviousSourceNode();
}
// startOffset > childCount but childCount is not 0
else {
// Try to take the node just after the current position.
startNode = startNode.$;
while ( startNode.lastChild )
startNode = startNode.lastChild;
startNode = new CKEDITOR.dom.node( startNode );
// Normally we should take the next node in DFS order. But it
// is also possible that we've already reached the end of
// document.
startNode = startNode.getNextSourceNode() || startNode;
}
}
if ( endNode.type == CKEDITOR.NODE_ELEMENT ) {
childCount = endNode.getChildCount();
if ( childCount > endOffset ) {
endNode = endNode.getChild( endOffset ).getPreviousSourceNode( true );
} else if ( childCount < 1 ) {
endNode = endNode.getPreviousSourceNode();
}
// endOffset > childCount but childCount is not 0.
else {
// Try to take the node just before the current position.
endNode = endNode.$;
while ( endNode.lastChild )
endNode = endNode.lastChild;
endNode = new CKEDITOR.dom.node( endNode );
}
}
// Sometimes the endNode will come right before startNode for collapsed
// ranges. Fix it. (#3780)
if ( startNode.getPosition( endNode ) & CKEDITOR.POSITION_FOLLOWING )
startNode = endNode;
return { startNode: startNode, endNode: endNode };
},
/**
* Find the node which fully contains the range.
*
* @param {Boolean} [includeSelf=false]
* @param {Boolean} [ignoreTextNode=false] Whether ignore {@link CKEDITOR#NODE_TEXT} type.
* @returns {CKEDITOR.dom.element}
*/
getCommonAncestor: function( includeSelf, ignoreTextNode ) {
var start = this.startContainer,
end = this.endContainer,
ancestor;
if ( start.equals( end ) ) {
if ( includeSelf && start.type == CKEDITOR.NODE_ELEMENT && this.startOffset == this.endOffset - 1 )
ancestor = start.getChild( this.startOffset );
else
ancestor = start;
} else {
ancestor = start.getCommonAncestor( end );
}
return ignoreTextNode && !ancestor.is ? ancestor.getParent() : ancestor;
},
/**
* Transforms the {@link #startContainer} and {@link #endContainer} properties from text
* nodes to element nodes, whenever possible. This is actually possible
* if either of the boundary containers point to a text node, and its
* offset is set to zero, or after the last char in the node.
*/
optimize: function() {
var container = this.startContainer;
var offset = this.startOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT ) {
if ( !offset )
this.setStartBefore( container );
else if ( offset >= container.getLength() )
this.setStartAfter( container );
}
container = this.endContainer;
offset = this.endOffset;
if ( container.type != CKEDITOR.NODE_ELEMENT ) {
if ( !offset )
this.setEndBefore( container );
else if ( offset >= container.getLength() )
this.setEndAfter( container );
}
},
/**
* Move the range out of bookmark nodes if they'd been the container.
*/
optimizeBookmark: function() {
var startNode = this.startContainer,
endNode = this.endContainer;
if ( startNode.is && startNode.is( 'span' ) && startNode.data( 'cke-bookmark' ) )
this.setStartAt( startNode, CKEDITOR.POSITION_BEFORE_START );
if ( endNode && endNode.is && endNode.is( 'span' ) && endNode.data( 'cke-bookmark' ) )
this.setEndAt( endNode, CKEDITOR.POSITION_AFTER_END );
},
/**
* @param {Boolean} [ignoreStart=false]
* @param {Boolean} [ignoreEnd=false]
* @todo precise desc/algorithm
*/
trim: function( ignoreStart, ignoreEnd ) {
var startContainer = this.startContainer,
startOffset = this.startOffset,
collapsed = this.collapsed;
if ( ( !ignoreStart || collapsed ) && startContainer && startContainer.type == CKEDITOR.NODE_TEXT ) {
// If the offset is zero, we just insert the new node before
// the start.
if ( !startOffset ) {
startOffset = startContainer.getIndex();
startContainer = startContainer.getParent();
}
// If the offset is at the end, we'll insert it after the text
// node.
else if ( startOffset >= startContainer.getLength() ) {
startOffset = startContainer.getIndex() + 1;
startContainer = startContainer.getParent();
}
// In other case, we split the text node and insert the new
// node at the split point.
else {
var nextText = startContainer.split( startOffset );
startOffset = startContainer.getIndex() + 1;
startContainer = startContainer.getParent();
// Check all necessity of updating the end boundary.
if ( this.startContainer.equals( this.endContainer ) )
this.setEnd( nextText, this.endOffset - this.startOffset );
else if ( startContainer.equals( this.endContainer ) )
this.endOffset += 1;
}
this.setStart( startContainer, startOffset );
if ( collapsed ) {
this.collapse( true );
return;
}
}
var endContainer = this.endContainer;
var endOffset = this.endOffset;
if ( !( ignoreEnd || collapsed ) && endContainer && endContainer.type == CKEDITOR.NODE_TEXT ) {
// If the offset is zero, we just insert the new node before
// the start.
if ( !endOffset ) {
endOffset = endContainer.getIndex();
endContainer = endContainer.getParent();
}
// If the offset is at the end, we'll insert it after the text
// node.
else if ( endOffset >= endContainer.getLength() ) {
endOffset = endContainer.getIndex() + 1;
endContainer = endContainer.getParent();
}
// In other case, we split the text node and insert the new
// node at the split point.
else {
endContainer.split( endOffset );
endOffset = endContainer.getIndex() + 1;
endContainer = endContainer.getParent();
}
this.setEnd( endContainer, endOffset );
}
},
/**