1 define(function(require) {
5 var $ = require('libs/jquery'),
6 _ = require('libs/underscore');
9 var Fragment = function(document) {
10 this.document = document;
12 $.extend(Fragment.prototype, {
19 var NodeFragment = function(document, params) {
20 Fragment.call(this, document);
21 this.node = params.node;
23 NodeFragment.prototype = Object.create(Fragment.prototype);
24 $.extend(NodeFragment.prototype, {
26 return this.document.containsNode(this.node);
31 var CaretFragment = function(document, params) {
32 NodeFragment.call(this, document, params);
33 this.offset = params.offset;
36 CaretFragment.prototype = Object.create(NodeFragment.prototype);
37 $.extend(CaretFragment.prototype, {
40 return NodeFragment.prototype.isValid.call(this) &&
41 this.node.nodeType === Node.TEXT_NODE &&
42 _.isNumber(this.offset);
48 var RangeFragment = function(document, params) {
49 Fragment.call(this, document);
51 if(params.node1.sameNode(params.node2)) {
52 this.startNode = this.endNode = params.node1;
54 /*jshint bitwise: false*/
56 var node1First = params.node1.nativeNode.compareDocumentPosition(params.node2.nativeNode) & Node.DOCUMENT_POSITION_FOLLOWING;
57 (node1First ? ['start', 'end'] : ['end','start']).forEach(function(prefix, idx) {
58 this[prefix + 'Node'] = params['node'+(idx+1)];
62 RangeFragment.prototype = Object.create(Fragment.prototype);
63 $.extend(RangeFragment.prototype, {
65 return this.document.containsNode(this.startNode) && this.document.containsNode(this.endNode);
67 hasSiblingBoundries: function() {
68 return this.isValid() && this.startNode.isSiblingOf(this.endNode);
70 boundriesSiblingParents: function() {
71 return this.startNode.document.getSiblingParents({
72 node1: this.startNode,
76 getCommonParent: function() {
77 var siblingParents = this.boundriesSiblingParents();
79 return siblingParents.node1.parent();
84 var TextRangeFragment = function(document, params) {
87 RangeFragment.call(this, document, params);
89 if(this.startNode.sameNode(this.endNode)) {
90 this.startOffset = Math.min(params.offset1, params.offset2);
91 this.endOffset = Math.max(params.offset1, params.offset2);
93 orderChanged = !params.node1.sameNode(this.startNode);
94 this.startOffset = orderChanged ? params.offset2 : params.offset1;
95 this.endOffset = orderChanged ? params.offset1 : params.offset2;
98 TextRangeFragment.prototype = Object.create(RangeFragment.prototype);
99 $.extend(TextRangeFragment.prototype, {
100 isValid: function() {
101 return RangeFragment.prototype.isValid.call(this) &&
102 _.isNumber(this.startOffset) &&
103 _.isNumber(this.endOffset);
107 var FragmentTypes = {
109 NodeFragment: NodeFragment,
110 CaretFragment: CaretFragment,
111 RangeFragment: RangeFragment,
112 TextRangeFragment: TextRangeFragment
114 _.values(FragmentTypes).forEach(function(Type) {
115 $.extend(Type.prototype, FragmentTypes);
118 return FragmentTypes;