-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
range.js
3365 lines (2888 loc) · 116 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-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-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.getRanges(); // 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.
function updateCollapsed( 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 content.
//
// The outline of the algorithm:
//
// 1. Normalization. We handle special cases, split text nodes if we can, find boundary nodes (startNode and endNode).
// 2. Gathering data.
// * We start by creating two arrays of boundary nodes parents. You can imagine these arrays as lines limiting
// the tree from the left and right and thus marking the part which is selected by the range. The both lines
// start in the same node which is the range.root and end in startNode and endNode.
// * Then we find min level and max levels. Level represents all nodes which are equally far from the range.root.
// Min level is the level at which the left and right boundaries diverged (the first diverged level). And max levels
// are how deep the start and end nodes are nested.
// 3. Cloning/extraction.
// * We start iterating over start node parents (left branch) from min level and clone the parent (usually shallow clone,
// because we know that it's not fully selected) and its right siblings (deep clone, because they are fully selected).
// We iterate over siblings up to meeting end node parent or end of the siblings chain.
// * We clone level after level down to the startNode.
// * Then we do the same with end node parents (right branch), because it may contains notes we omit during the previous
// step, for example if the right branch is deeper then left branch. Things are more complicated here because we have to
// watch out for nodes that were already cloned.
// * ***Note:** Setting `cloneId` option to `false` for **extraction** works for partially selected elements only.
// See range.extractContents to know more.
// 4. Clean up.
// * There are two things we need to do - updating the range position and perform the action of the "mergeThen"
// param (see range.deleteContents or range.extractContents).
// See comments in mergeAndUpdate because this is lots of fun too.
function execContentsAction( range, action, docFrag, mergeThen, cloneId ) {
'use strict';
range.optimizeBookmark();
var isDelete = action === 0;
var isExtract = action == 1;
var isClone = action == 2;
var doClone = isClone || isExtract;
var startNode = range.startContainer;
var endNode = range.endContainer;
var startOffset = range.startOffset;
var endOffset = range.endOffset;
var cloneStartNode;
var cloneEndNode;
var doNotRemoveStartNode;
var doNotRemoveEndNode;
var cloneStartText;
var cloneEndText;
// Handle here an edge case where we clone a range which is located in one text node.
// This allows us to not think about startNode == endNode case later on.
// We do that only when cloning, because in other cases we can safely split this text node
// and hence we can easily handle this case as many others.
// We need to handle situation when selection startNode is type of NODE_ELEMENT (#426).
if ( isClone &&
endNode.type == CKEDITOR.NODE_TEXT &&
( startNode.equals( endNode ) || ( startNode.type === CKEDITOR.NODE_ELEMENT && startNode.getFirst().equals( endNode ) ) ) ) {
// Here we should always be inside one text node.
docFrag.append( range.document.createText( endNode.substring( startOffset, endOffset ) ) );
return;
}
// 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 ) {
// If Extract or Delete we can split the text node,
// but if Clone (2), then we cannot modify the DOM (https://dev.ckeditor.com/ticket/11586) so we mark the text node for cloning.
if ( !isClone ) {
endNode = endNode.split( endOffset );
} else {
cloneEndText = true;
}
} else {
// If there's no node after the range boundary we set endNode to the previous node
// and mark it to be cloned.
if ( endNode.getChildCount() > 0 ) {
// If the offset points after the last node.
if ( endOffset >= endNode.getChildCount() ) {
endNode = endNode.getChild( endOffset - 1 );
cloneEndNode = true;
} else {
endNode = endNode.getChild( endOffset );
}
}
// The end container is empty (<h1>]</h1>), but we want to clone it, although not remove.
else {
cloneEndNode = true;
doNotRemoveEndNode = true;
}
}
// 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 ) {
// If Extract or Delete we can split the text node,
// but if Clone (2), then we cannot modify the DOM (https://dev.ckeditor.com/ticket/11586) so we mark
// the text node for cloning.
if ( !isClone ) {
startNode.split( startOffset );
} else {
cloneStartText = true;
}
} else {
// If there's no node before the range boundary we set startNode to the next node
// and mark it to be cloned.
if ( startNode.getChildCount() > 0 ) {
if ( startOffset === 0 ) {
startNode = startNode.getChild( startOffset );
cloneStartNode = true;
} else {
startNode = startNode.getChild( startOffset - 1 );
}
}
// The start container is empty (<h1>[</h1>), but we want to clone it, although not remove.
else {
cloneStartNode = true;
doNotRemoveStartNode = true;
}
}
// Get the parent nodes tree for the start and end boundaries.
var startParents = startNode.getParents(),
endParents = endNode.getParents(),
// Level at which start and end boundaries diverged.
minLevel = findMinLevel(),
maxLevelLeft = startParents.length - 1,
maxLevelRight = endParents.length - 1,
// Keeps the frag/element which is parent of the level that we are currently cloning.
levelParent = docFrag,
nextLevelParent,
leftNode,
rightNode,
nextSibling,
// Keeps track of the last connected level (on which left and right branches are connected)
// Usually this is minLevel, but not always.
lastConnectedLevel = -1;
// THE LEFT BRANCH.
for ( var level = minLevel; level <= maxLevelLeft; level++ ) {
leftNode = startParents[ level ];
nextSibling = leftNode.getNext();
// 1.
// The first step is to handle partial selection of the left branch.
// Max depth of the left branch. It means that ( leftSibling == endNode ).
// We also check if the leftNode isn't only partially selected, because in this case
// we want to make a shallow clone of it (the else part).
if ( level == maxLevelLeft && !( leftNode.equals( endParents[ level ] ) && maxLevelLeft < maxLevelRight ) ) {
if ( cloneStartNode ) {
consume( leftNode, levelParent, false, doNotRemoveStartNode );
} else if ( cloneStartText ) {
levelParent.append( range.document.createText( leftNode.substring( startOffset ) ) );
}
} else if ( doClone ) {
nextLevelParent = levelParent.append( leftNode.clone( 0, cloneId ) );
}
// 2.
// The second step is to handle full selection of the content between the left branch and the right branch.
while ( nextSibling ) {
// We can't clone entire endParent just like we can't clone entire startParent -
// - they are not fully selected with the range. Partial endParent selection
// will be cloned in the next loop.
if ( nextSibling.equals( endParents[ level ] ) ) {
lastConnectedLevel = level;
break;
}
nextSibling = consume( nextSibling, levelParent );
}
levelParent = nextLevelParent;
}
// Reset levelParent, because we reset the level.
levelParent = docFrag;
// THE RIGHT BRANCH.
for ( level = minLevel; level <= maxLevelRight; level++ ) {
rightNode = endParents[ level ];
nextSibling = rightNode.getPrevious();
// Do not process this node if it is shared with the left branch
// because it was already processed.
//
// Note: Don't worry about text nodes selection - if the entire range was placed in a single text node
// it was handled as a special case at the beginning. In other cases when startNode == endNode
// or when on this level leftNode == rightNode (so rightNode.equals( startParents[ level ] ))
// this node was handled by the previous loop.
if ( !rightNode.equals( startParents[ level ] ) ) {
// 1.
// The first step is to handle partial selection of the right branch.
// Max depth of the right branch. It means that ( rightNode == endNode ).
// We also check if the rightNode isn't only partially selected, because in this case
// we want to make a shallow clone of it (the else part).
if ( level == maxLevelRight && !( rightNode.equals( startParents[ level ] ) && maxLevelRight < maxLevelLeft ) ) {
if ( cloneEndNode ) {
consume( rightNode, levelParent, false, doNotRemoveEndNode );
} else if ( cloneEndText ) {
levelParent.append( range.document.createText( rightNode.substring( 0, endOffset ) ) );
}
} else if ( doClone ) {
nextLevelParent = levelParent.append( rightNode.clone( 0, cloneId ) );
}
// 2.
// The second step is to handle all left (selected) siblings of the rightNode which
// have not yet been handled. If the level branches were connected, the previous loop
// already copied all siblings (except the current rightNode).
if ( level > lastConnectedLevel ) {
while ( nextSibling ) {
nextSibling = consume( nextSibling, levelParent, true );
}
}
levelParent = nextLevelParent;
} else if ( doClone ) {
// If this is "shared" node and we are in cloning mode we have to update levelParent to
// reflect that we visited the node (even though we didn't process it).
// If we don't do that, in next iterations nodes will be appended to wrong parent.
//
// We can just take first child because the algorithm guarantees
// that this will be the only child on this level. (https://dev.ckeditor.com/ticket/13568)
levelParent = levelParent.getChild( 0 );
}
}
// Delete or Extract.
// We need to update the range and if mergeThen was passed do it.
if ( !isClone ) {
mergeAndUpdate();
}
// Depending on an action:
// * clones node and adds to new parent,
// * removes node,
// * moves node to the new parent.
function consume( node, newParent, toStart, forceClone ) {
var nextSibling = toStart ? node.getPrevious() : node.getNext();
// We do not clone if we are only deleting, so do nothing.
if ( forceClone && isDelete ) {
return nextSibling;
}
// If cloning, just clone it.
if ( isClone || forceClone ) {
newParent.append( node.clone( true, cloneId ), toStart );
} else {
// Both Delete and Extract will remove the node.
node.remove();
// When Extracting, move the removed node to the docFrag.
if ( isExtract ) {
newParent.append( node, toStart );
}
}
return nextSibling;
}
// Finds a level number on which both branches starts diverging.
// If such level does not exist, return the last on which both branches have nodes.
function findMinLevel() {
// Compare them, to find the top most siblings.
var i, topStart, topEnd,
maxLevel = Math.min( startParents.length, endParents.length );
for ( i = 0; i < maxLevel; 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 ) ) {
return i;
}
}
// When startNode == endNode.
return i - 1;
}
// Executed only when deleting or extracting to update range position
// and perform the merge operation.
function mergeAndUpdate() {
var commonLevel = minLevel - 1,
boundariesInEmptyNode = doNotRemoveStartNode && doNotRemoveEndNode && !startNode.equals( endNode );
// If a node has been partially selected, collapse the range between
// startParents[ minLevel + 1 ] and endParents[ minLevel + 1 ] (the first diverged elements).
// Otherwise, simply collapse it to the start. (W3C specs).
//
// All clear, right?
//
// It took me few hours to truly understand a previous version of this condition.
// Mine seems to be more straightforward (even if it doesn't look so) and I could leave you here
// without additional comments, but I'm not that mean so here goes the explanation.
//
// We want to know if both ends of the range are anchored in the same element. Really. It's this simple.
// But why? Because we need to differentiate situations like:
//
// <p>foo[<b>x</b>bar]y</p> (commonLevel = p, maxLL = "foo", maxLR = "y")
// from:
// <p>foo<b>x[</b>bar]y</p> (commonLevel = p, maxLL = "x", maxLR = "y")
//
// In the first case we can collapse the range to the left, because simply everything between range's
// boundaries was removed.
// In the second case we must place the range after </b>, because <b> was only **partially selected**.
//
// * <b> is our startParents[ commonLevel + 1 ]
// * "y" is our endParents[ commonLevel + 1 ].
//
// By now "bar" is removed from the DOM so <b> is a direct sibling of "y":
// <p>foo<b>x</b>y</p>
//
// Therefore it's enough to place the range between <b> and "y".
//
// Now, what does the comparison mean? Why not just taking startNode and endNode and checking
// their parents? Because the tree is already changed and they may be gone. Plus, thanks to
// cloneStartNode and cloneEndNode, that would be reaaaaly tricky.
//
// So we play with levels which can give us the same information:
// * commonLevel - the level of common ancestor,
// * maxLevel - 1 - the level of range boundary parent (range boundary is here like a bookmark span).
// * commonLevel < maxLevel - 1 - whether the range boundary is not a child of common ancestor.
//
// There's also an edge case in which both range boundaries were placed in empty nodes like:
// <p>[</p><p>]</p>
// Those boundaries were not removed, but in this case start and end nodes are child of the common ancestor.
// We handle this edge case separately.
if ( commonLevel < ( maxLevelLeft - 1 ) || commonLevel < ( maxLevelRight - 1 ) || boundariesInEmptyNode ) {
if ( boundariesInEmptyNode ) {
range.moveToPosition( endNode, CKEDITOR.POSITION_BEFORE_START );
} else if ( ( maxLevelRight == commonLevel + 1 ) && cloneEndNode ) {
// The maxLevelRight + 1 element could be already removed so we use the fact that
// we know that it was the last element in its parent.
range.moveToPosition( endParents[ commonLevel ], CKEDITOR.POSITION_BEFORE_END );
} else {
range.moveToPosition( endParents[ commonLevel + 1 ], CKEDITOR.POSITION_BEFORE_START );
}
// Merge split parents.
if ( mergeThen ) {
// Find the first diverged node in the left branch.
var topLeft = startParents[ commonLevel + 1 ];
// TopLeft may simply not exist if commonLevel == maxLevel or may be a text node.
if ( topLeft && topLeft.type == CKEDITOR.NODE_ELEMENT ) {
var span = CKEDITOR.dom.element.createFromHtml( '<span ' +
'data-cke-bookmark="1" style="display:none"> </span>', range.document );
span.insertAfter( topLeft );
topLeft.mergeSiblings( false );
range.moveToBookmark( { startNode: span } );
}
}
} else {
// Collapse it to the start.
range.collapse( true );
}
}
}
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. (https://dev.ckeditor.com/ticket/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 the 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;
},
/**
* Clones content nodes of the range and adds them to a document fragment, which is returned.
*
* @param {Boolean} [cloneId=true] Whether to preserve ID attributes in the clone.
* @returns {CKEDITOR.dom.documentFragment} Document fragment containing a clone of range's content.
*/
cloneContents: function( cloneId ) {
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
cloneId = typeof cloneId == 'undefined' ? true : cloneId;
if ( !this.collapsed )
execContentsAction( this, 2, docFrag, false, cloneId );
return docFrag;
},
/**
* Deletes the content nodes of the range permanently from the DOM tree.
*
* @param {Boolean} [mergeThen] Merge any split 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.
*
* **Note:** Setting the `cloneId` parameter to `false` works for **partially** selected elements only.
* If an element with an ID attribute is **fully enclosed** in a range, it will keep the ID attribute
* regardless of the `cloneId` parameter value, because it is not cloned — it is moved to the returned
* document fragment.
*
* @param {Boolean} [mergeThen] Merge any split elements result in DOM true due to partial selection.
* @param {Boolean} [cloneId=true] Whether to preserve ID attributes in the extracted content.
* @returns {CKEDITOR.dom.documentFragment} Document fragment containing extracted content.
*/
extractContents: function( mergeThen, cloneId ) {
var docFrag = new CKEDITOR.dom.documentFragment( this.document );
cloneId = typeof cloneId == 'undefined' ? true : cloneId;
if ( !this.collapsed )
execContentsAction( this, 1, docFrag, mergeThen, cloneId );
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.getText().replace( CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE, '' ).length;
return sum;
}
function normalizeTextNodes( 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 one node before it,
// it may happen that some of them will be merged. Normalize the offset
// by setting it to normalized index of its preceding, safe node.
// (safe == one for which getIndex(true) does not return -1, so one which won't disappear).
if ( container.type == CKEDITOR.NODE_ELEMENT && offset > 0 ) {
offset = getPrecedingSafeNodeIndex( container, offset ) + 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;
}
function normalizeFCSeq( limit, root ) {
var fcseq = root.getCustomData( 'cke-fillingChar' );
if ( !fcseq ) {
return;
}
var container = limit.container;
if ( fcseq.equals( container ) ) {
limit.offset -= CKEDITOR.dom.selection.FILLING_CHAR_SEQUENCE.length;
// == 0 handles case when limit was at the end of FCS.
// < 0 handles all cases where limit was somewhere in the middle or at the beginning.
// > 0 (the "else" case) means cases where there are some more characters in the FCS node (FCSabc^def).
if ( limit.offset <= 0 ) {
limit.offset = container.getIndex();
limit.container = container.getParent();
}
return;
}
// And here goes the funny part - all other cases are handled inside node.getAddress() and getIndex() thanks to
// node.getIndex() being aware of FCS (handling it as an empty node).
}
// Finds a normalized index of a safe node preceding this one.
// Safe == one that will not disappear, so one for which getIndex( true ) does not return -1.
// Return -1 if there's no safe preceding node.
function getPrecedingSafeNodeIndex( container, offset ) {
var index;
while ( offset-- ) {
index = container.getChild( offset ).getIndex( true );
if ( index >= 0 )
return index;
}
return -1;
}
return function( normalized ) {
var collapsed = this.collapsed,
bmStart = {
container: this.startContainer,
offset: this.startOffset
},
bmEnd = {
container: this.endContainer,
offset: this.endOffset
};
if ( normalized ) {
normalizeTextNodes( bmStart );
normalizeFCSeq( bmStart, this.root );
if ( !collapsed ) {
normalizeTextNodes( bmEnd );
normalizeFCSeq( bmEnd, this.root );
}
}
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 );