-
Notifications
You must be signed in to change notification settings - Fork 5
/
rangy-core.js
3899 lines (3306 loc) · 160 KB
/
rangy-core.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
/**
* Rangy, a cross-browser JavaScript range and selection library
* https://github.com/timdown/rangy
*
* Copyright 2024, Tim Down
* Licensed under the MIT license.
* Version: 1.3.2
* Build date: 2 November 2024
*/
(function(factory, root) {
if (typeof define == "function" && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof module != "undefined" && typeof exports == "object") {
// Node/CommonJS style
module.exports = factory();
} else {
// No AMD or CommonJS support so we place Rangy in (probably) the global variable
root.rangy = factory();
}
})(function() {
var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
// Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START
// are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113.
var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer"];
// Minimal set of methods required for DOM Level 2 Range compliance
var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
"setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
"extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
// Subset of TextRange's full set of methods that we're interested in
var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select",
"setEndPoint", "getBoundingClientRect"];
/*----------------------------------------------------------------------------------------------------------------*/
// Trio of functions taken from Peter Michaux's article:
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(o, p) {
var t = typeof o[p];
return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
}
function isHostObject(o, p) {
return !!(typeof o[p] == OBJECT && o[p]);
}
function isHostProperty(o, p) {
return typeof o[p] != UNDEFINED;
}
// Creates a convenience function to save verbose repeated calls to tests functions
function createMultiplePropertyTest(testFunc) {
return function(o, props) {
var i = props.length;
while (i--) {
if (!testFunc(o, props[i])) {
return false;
}
}
return true;
};
}
// Next trio of functions are a convenience to save verbose repeated calls to previous two functions
var areHostMethods = createMultiplePropertyTest(isHostMethod);
var areHostObjects = createMultiplePropertyTest(isHostObject);
var areHostProperties = createMultiplePropertyTest(isHostProperty);
function isTextRange(range) {
return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
}
function getBody(doc) {
return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
}
var forEach = [].forEach ?
function(arr, func) {
arr.forEach(func);
} :
function(arr, func) {
for (var i = 0, len = arr.length; i < len; ++i) {
func(arr[i], i);
}
};
var modules = {};
var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED);
var util = {
isHostMethod: isHostMethod,
isHostObject: isHostObject,
isHostProperty: isHostProperty,
areHostMethods: areHostMethods,
areHostObjects: areHostObjects,
areHostProperties: areHostProperties,
isTextRange: isTextRange,
getBody: getBody,
forEach: forEach
};
var api = {
version: "1.3.2",
initialized: false,
isBrowser: isBrowser,
supported: true,
util: util,
features: {},
modules: modules,
config: {
alertOnFail: false,
alertOnWarn: false,
preferTextRange: false,
autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize
}
};
function consoleLog(msg) {
if (typeof console != UNDEFINED && isHostMethod(console, "log")) {
console.log(msg);
}
}
function alertOrLog(msg, shouldAlert) {
if (isBrowser && shouldAlert) {
alert(msg);
} else {
consoleLog(msg);
}
}
function fail(reason) {
api.initialized = true;
api.supported = false;
alertOrLog("Rangy is not supported in this environment. Reason: " + reason, api.config.alertOnFail);
}
api.fail = fail;
function warn(msg) {
alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn);
}
api.warn = warn;
// Add utility extend() method
var extend;
if ({}.hasOwnProperty) {
util.extend = extend = function(obj, props, deep) {
var o, p;
for (var i in props) {
if (i === "__proto__" || i === "constructor" || i === "prototype") {
continue;
}
if (props.hasOwnProperty(i)) {
o = obj[i];
p = props[i];
if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") {
extend(o, p, true);
}
obj[i] = p;
}
}
// Special case for toString, which does not show up in for...in loops in IE <= 8
if (props.hasOwnProperty("toString")) {
obj.toString = props.toString;
}
return obj;
};
util.createOptions = function(optionsParam, defaults) {
var options = {};
extend(options, defaults);
if (optionsParam) {
extend(options, optionsParam);
}
return options;
};
} else {
fail("hasOwnProperty not supported");
}
// Test whether we're in a browser and bail out if not
if (!isBrowser) {
fail("Rangy can only run in a browser");
}
// Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not
(function() {
var toArray;
if (isBrowser) {
var el = document.createElement("div");
el.appendChild(document.createElement("span"));
var slice = [].slice;
try {
if (slice.call(el.childNodes, 0)[0].nodeType == 1) {
toArray = function(arrayLike) {
return slice.call(arrayLike, 0);
};
}
} catch (e) {}
}
if (!toArray) {
toArray = function(arrayLike) {
var arr = [];
for (var i = 0, len = arrayLike.length; i < len; ++i) {
arr[i] = arrayLike[i];
}
return arr;
};
}
util.toArray = toArray;
})();
// Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or
// normalization of event properties because we don't need this.
var addListener;
if (isBrowser) {
if (isHostMethod(document, "addEventListener")) {
addListener = function(obj, eventType, listener) {
obj.addEventListener(eventType, listener, false);
};
} else if (isHostMethod(document, "attachEvent")) {
addListener = function(obj, eventType, listener) {
obj.attachEvent("on" + eventType, listener);
};
} else {
fail("Document does not have required addEventListener or attachEvent method");
}
util.addListener = addListener;
}
var initListeners = [];
function getErrorDesc(ex) {
return ex.message || ex.description || String(ex);
}
// Initialization
function init() {
if (!isBrowser || api.initialized) {
return;
}
var testRange;
var implementsDomRange = false, implementsTextRange = false;
// First, perform basic feature tests
if (isHostMethod(document, "createRange")) {
testRange = document.createRange();
if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
implementsDomRange = true;
}
}
var body = getBody(document);
if (!body || body.nodeName.toLowerCase() != "body") {
fail("No body element found");
return;
}
if (body && isHostMethod(body, "createTextRange")) {
testRange = body.createTextRange();
if (isTextRange(testRange)) {
implementsTextRange = true;
}
}
if (!implementsDomRange && !implementsTextRange) {
fail("Neither Range nor TextRange are available");
return;
}
api.initialized = true;
api.features = {
implementsDomRange: implementsDomRange,
implementsTextRange: implementsTextRange
};
// Initialize modules
var module, errorMessage;
for (var moduleName in modules) {
if ( (module = modules[moduleName]) instanceof Module ) {
module.init(module, api);
}
}
// Call init listeners
for (var i = 0, len = initListeners.length; i < len; ++i) {
try {
initListeners[i](api);
} catch (ex) {
errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex);
consoleLog(errorMessage);
}
}
}
function deprecationNotice(deprecated, replacement, module) {
if (module) {
deprecated += " in module " + module.name;
}
api.warn("DEPRECATED: " + deprecated + " is deprecated. Please use " +
replacement + " instead.");
}
function createAliasForDeprecatedMethod(owner, deprecated, replacement, module) {
owner[deprecated] = function() {
deprecationNotice(deprecated, replacement, module);
return owner[replacement].apply(owner, util.toArray(arguments));
};
}
util.deprecationNotice = deprecationNotice;
util.createAliasForDeprecatedMethod = createAliasForDeprecatedMethod;
// Allow external scripts to initialize this library in case it's loaded after the document has loaded
api.init = init;
// Execute listener immediately if already initialized
api.addInitListener = function(listener) {
if (api.initialized) {
listener(api);
} else {
initListeners.push(listener);
}
};
var shimListeners = [];
api.addShimListener = function(listener) {
shimListeners.push(listener);
};
function shim(win) {
win = win || window;
init();
// Notify listeners
for (var i = 0, len = shimListeners.length; i < len; ++i) {
shimListeners[i](win);
}
}
if (isBrowser) {
api.shim = api.createMissingNativeApi = shim;
createAliasForDeprecatedMethod(api, "createMissingNativeApi", "shim");
}
function Module(name, dependencies, initializer) {
this.name = name;
this.dependencies = dependencies;
this.initialized = false;
this.supported = false;
this.initializer = initializer;
}
Module.prototype = {
init: function() {
var requiredModuleNames = this.dependencies || [];
for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) {
moduleName = requiredModuleNames[i];
requiredModule = modules[moduleName];
if (!requiredModule || !(requiredModule instanceof Module)) {
throw new Error("required module '" + moduleName + "' not found");
}
requiredModule.init();
if (!requiredModule.supported) {
throw new Error("required module '" + moduleName + "' not supported");
}
}
// Now run initializer
this.initializer(this);
},
fail: function(reason) {
this.initialized = true;
this.supported = false;
throw new Error(reason);
},
warn: function(msg) {
api.warn("Module " + this.name + ": " + msg);
},
deprecationNotice: function(deprecated, replacement) {
api.warn("DEPRECATED: " + deprecated + " in module " + this.name + " is deprecated. Please use " +
replacement + " instead");
},
createError: function(msg) {
return new Error("Error in Rangy " + this.name + " module: " + msg);
}
};
function createModule(name, dependencies, initFunc) {
var newModule = new Module(name, dependencies, function(module) {
if (!module.initialized) {
module.initialized = true;
try {
initFunc(api, module);
module.supported = true;
} catch (ex) {
var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex);
consoleLog(errorMessage);
if (ex.stack) {
consoleLog(ex.stack);
}
}
}
});
modules[name] = newModule;
return newModule;
}
api.createModule = function(name) {
// Allow 2 or 3 arguments (second argument is an optional array of dependencies)
var initFunc, dependencies;
if (arguments.length == 2) {
initFunc = arguments[1];
dependencies = [];
} else {
initFunc = arguments[2];
dependencies = arguments[1];
}
var module = createModule(name, dependencies, initFunc);
// Initialize the module immediately if the core is already initialized
if (api.initialized && api.supported) {
module.init();
}
};
api.createCoreModule = function(name, dependencies, initFunc) {
createModule(name, dependencies, initFunc);
};
/*----------------------------------------------------------------------------------------------------------------*/
// Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately
function RangePrototype() {}
api.RangePrototype = RangePrototype;
api.rangePrototype = new RangePrototype();
function SelectionPrototype() {}
api.selectionPrototype = new SelectionPrototype();
/*----------------------------------------------------------------------------------------------------------------*/
// DOM utility methods used by Rangy
api.createCoreModule("DomUtil", [], function(api, module) {
var UNDEF = "undefined";
var util = api.util;
var getBody = util.getBody;
// Perform feature tests
if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
module.fail("document missing a Node creation method");
}
if (!util.isHostMethod(document, "getElementsByTagName")) {
module.fail("document missing getElementsByTagName method");
}
var el = document.createElement("div");
if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
module.fail("Incomplete Element implementation");
}
// innerHTML is required for Range's createContextualFragment method
if (!util.isHostProperty(el, "innerHTML")) {
module.fail("Element is missing innerHTML property");
}
var textNode = document.createTextNode("test");
if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
!util.areHostProperties(textNode, ["data"]))) {
module.fail("Incomplete Text Node implementation");
}
/*----------------------------------------------------------------------------------------------------------------*/
// Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
// able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
// contains just the document as a single element and the value searched for is the document.
var arrayContains = /*Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
}:*/
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
};
// Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
function isHtmlNamespace(node) {
var ns;
return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
}
function parentElement(node) {
var parent = node.parentNode;
return (parent.nodeType == 1) ? parent : null;
}
function getNodeIndex(node) {
var i = 0;
while( (node = node.previousSibling) ) {
++i;
}
return i;
}
function getNodeLength(node) {
switch (node.nodeType) {
case 7:
case 10:
return 0;
case 3:
case 8:
return node.length;
default:
return node.childNodes.length;
}
}
function getCommonAncestor(node1, node2) {
var ancestors = [], n;
for (n = node1; n; n = n.parentNode) {
ancestors.push(n);
}
for (n = node2; n; n = n.parentNode) {
if (arrayContains(ancestors, n)) {
return n;
}
}
return null;
}
function isAncestorOf(ancestor, descendant, selfIsAncestor) {
var n = selfIsAncestor ? descendant : descendant.parentNode;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function isOrIsAncestorOf(ancestor, descendant) {
return isAncestorOf(ancestor, descendant, true);
}
function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
var p, n = selfIsAncestor ? node : node.parentNode;
while (n) {
p = n.parentNode;
if (p === ancestor) {
return n;
}
n = p;
}
return null;
}
function isCharacterDataNode(node) {
var t = node.nodeType;
return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
}
function isTextOrCommentNode(node) {
if (!node) {
return false;
}
var t = node.nodeType;
return t == 3 || t == 8 ; // Text or Comment
}
function insertAfter(node, precedingNode) {
var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
if (nextNode) {
parent.insertBefore(node, nextNode);
} else {
parent.appendChild(node);
}
return node;
}
// Note that we cannot use splitText() because it is bugridden in IE 9.
function splitDataNode(node, index, positionsToPreserve) {
var newNode = node.cloneNode(false);
newNode.deleteData(0, index);
node.deleteData(index, node.length - index);
insertAfter(newNode, node);
// Preserve positions
if (positionsToPreserve) {
for (var i = 0, position; position = positionsToPreserve[i++]; ) {
// Handle case where position was inside the portion of node after the split point
if (position.node == node && position.offset > index) {
position.node = newNode;
position.offset -= index;
}
// Handle the case where the position is a node offset within node's parent
else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) {
++position.offset;
}
}
}
return newNode;
}
function getDocument(node) {
if (node.nodeType == 9) {
return node;
} else if (typeof node.ownerDocument != UNDEF) {
return node.ownerDocument;
} else if (typeof node.document != UNDEF) {
return node.document;
} else if (node.parentNode) {
return getDocument(node.parentNode);
} else {
throw module.createError("getDocument: no document found for node");
}
}
function getWindow(node) {
var doc = getDocument(node);
if (typeof doc.defaultView != UNDEF) {
return doc.defaultView;
} else if (typeof doc.parentWindow != UNDEF) {
return doc.parentWindow;
} else {
throw module.createError("Cannot get a window object for node");
}
}
function getIframeDocument(iframeEl) {
if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument;
} else if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow.document;
} else {
throw module.createError("getIframeDocument: No Document object found for iframe element");
}
}
function getIframeWindow(iframeEl) {
if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow;
} else if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument.defaultView;
} else {
throw module.createError("getIframeWindow: No Window object found for iframe element");
}
}
// This looks bad. Is it worth it?
function isWindow(obj) {
return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document");
}
function getContentDocument(obj, module, methodName) {
var doc;
if (!obj) {
doc = document;
}
// Test if a DOM node has been passed and obtain a document object for it if so
else if (util.isHostProperty(obj, "nodeType")) {
doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe") ?
getIframeDocument(obj) : getDocument(obj);
}
// Test if the doc parameter appears to be a Window object
else if (isWindow(obj)) {
doc = obj.document;
}
if (!doc) {
throw module.createError(methodName + "(): Parameter must be a Window object or DOM node");
}
return doc;
}
function getRootContainer(node) {
var parent;
while ( (parent = node.parentNode) ) {
node = parent;
}
return node;
}
function comparePoints(nodeA, offsetA, nodeB, offsetB) {
// See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
var nodeC, root, childA, childB, n;
if (nodeA == nodeB) {
// Case 1: nodes are the same
return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
// Case 2: node C (container B or an ancestor) is a child node of A
return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
// Case 3: node C (container A or an ancestor) is a child node of B
return getNodeIndex(nodeC) < offsetB ? -1 : 1;
} else {
root = getCommonAncestor(nodeA, nodeB);
if (!root) {
throw new Error("comparePoints error: nodes have no common ancestor");
}
// Case 4: containers are siblings or descendants of siblings
childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
if (childA === childB) {
// This shouldn't be possible
throw module.createError("comparePoints got to case 4 and childA and childB are the same!");
} else {
n = root.firstChild;
while (n) {
if (n === childA) {
return -1;
} else if (n === childB) {
return 1;
}
n = n.nextSibling;
}
}
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried
var crashyTextNodes = false;
function isBrokenNode(node) {
var n;
try {
n = node.parentNode;
return false;
} catch (e) {
return true;
}
}
(function() {
var el = document.createElement("b");
el.innerHTML = "1";
var textNode = el.firstChild;
el.innerHTML = "<br />";
crashyTextNodes = isBrokenNode(textNode);
api.features.crashyTextNodes = crashyTextNodes;
})();
/*----------------------------------------------------------------------------------------------------------------*/
function inspectNode(node) {
if (!node) {
return "[No node]";
}
if (crashyTextNodes && isBrokenNode(node)) {
return "[Broken node]";
}
if (isCharacterDataNode(node)) {
return '"' + node.data + '"';
}
if (node.nodeType == 1) {
var idAttr = node.id ? ' id="' + node.id + '"' : "";
return "<" + node.nodeName + idAttr + ">[index:" + getNodeIndex(node) + ",length:" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]";
}
return node.nodeName;
}
function fragmentFromNodeChildren(node) {
var fragment = getDocument(node).createDocumentFragment(), child;
while ( (child = node.firstChild) ) {
fragment.appendChild(child);
}
return fragment;
}
var getComputedStyleProperty;
if (typeof window.getComputedStyle != UNDEF) {
getComputedStyleProperty = function(el, propName) {
return getWindow(el).getComputedStyle(el, null)[propName];
};
} else if (typeof document.documentElement.currentStyle != UNDEF) {
getComputedStyleProperty = function(el, propName) {
return el.currentStyle ? el.currentStyle[propName] : "";
};
} else {
module.fail("No means of obtaining computed style properties found");
}
function createTestElement(doc, html, contentEditable) {
var body = getBody(doc);
var el = doc.createElement("div");
el.contentEditable = "" + !!contentEditable;
if (html) {
el.innerHTML = html;
}
// Insert the test element at the start of the body to prevent scrolling to the bottom in iOS (issue #292)
var bodyFirstChild = body.firstChild;
if (bodyFirstChild) {
body.insertBefore(el, bodyFirstChild);
} else {
body.appendChild(el);
}
return el;
}
function removeNode(node) {
return node.parentNode.removeChild(node);
}
function NodeIterator(root) {
this.root = root;
this._next = root;
}
NodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
var n = this._current = this._next;
var child, next;
if (this._current) {
child = n.firstChild;
if (child) {
this._next = child;
} else {
next = null;
while ((n !== this.root) && !(next = n.nextSibling)) {
n = n.parentNode;
}
this._next = next;
}
}
return this._current;
},
detach: function() {
this._current = this._next = this.root = null;
}
};
function createIterator(root) {
return new NodeIterator(root);
}
function DomPosition(node, offset) {
this.node = node;
this.offset = offset;
}
DomPosition.prototype = {
equals: function(pos) {
return !!pos && this.node === pos.node && this.offset == pos.offset;
},
inspect: function() {
return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
},
toString: function() {
return this.inspect();
}
};
function DOMException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "DOMException: " + this.codeName;
}
DOMException.prototype = {
INDEX_SIZE_ERR: 1,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INVALID_STATE_ERR: 11,
INVALID_NODE_TYPE_ERR: 24
};
DOMException.prototype.toString = function() {
return this.message;
};
api.dom = {
arrayContains: arrayContains,
isHtmlNamespace: isHtmlNamespace,
parentElement: parentElement,
getNodeIndex: getNodeIndex,
getNodeLength: getNodeLength,
getCommonAncestor: getCommonAncestor,
isAncestorOf: isAncestorOf,
isOrIsAncestorOf: isOrIsAncestorOf,
getClosestAncestorIn: getClosestAncestorIn,
isCharacterDataNode: isCharacterDataNode,
isTextOrCommentNode: isTextOrCommentNode,
insertAfter: insertAfter,
splitDataNode: splitDataNode,
getDocument: getDocument,
getWindow: getWindow,
getIframeWindow: getIframeWindow,
getIframeDocument: getIframeDocument,
getBody: getBody,
isWindow: isWindow,
getContentDocument: getContentDocument,
getRootContainer: getRootContainer,
comparePoints: comparePoints,
isBrokenNode: isBrokenNode,
inspectNode: inspectNode,
getComputedStyleProperty: getComputedStyleProperty,
createTestElement: createTestElement,
removeNode: removeNode,
fragmentFromNodeChildren: fragmentFromNodeChildren,
createIterator: createIterator,
DomPosition: DomPosition
};
api.DOMException = DOMException;
});
/*----------------------------------------------------------------------------------------------------------------*/
// Pure JavaScript implementation of DOM Range
api.createCoreModule("DomRange", ["DomUtil"], function(api, module) {
var dom = api.dom;
var util = api.util;
var DomPosition = dom.DomPosition;
var DOMException = api.DOMException;
var isCharacterDataNode = dom.isCharacterDataNode;
var getNodeIndex = dom.getNodeIndex;
var isOrIsAncestorOf = dom.isOrIsAncestorOf;
var getDocument = dom.getDocument;
var comparePoints = dom.comparePoints;
var splitDataNode = dom.splitDataNode;
var getClosestAncestorIn = dom.getClosestAncestorIn;
var getNodeLength = dom.getNodeLength;
var arrayContains = dom.arrayContains;
var getRootContainer = dom.getRootContainer;
var crashyTextNodes = api.features.crashyTextNodes;
var removeNode = dom.removeNode;
/*----------------------------------------------------------------------------------------------------------------*/
// Utility functions
function isNonTextPartiallySelected(node, range) {
return (node.nodeType != 3) &&
(isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer));
}