6 ], function($, _, Backbone, events) {
11 var TEXT_NODE = Node.TEXT_NODE;
14 var INSERTION = function(implementation) {
15 var toret = function(node) {
16 var insertion = this.getNodeInsertion(node);
17 implementation.call(this, insertion.ofNode.nativeNode);
18 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
19 return insertion.ofNode;
24 var DocumentNode = function(nativeNode, document) {
26 throw new Error('undefined document for a node');
28 this.document = document;
29 this._setNativeNode(nativeNode);
33 $.extend(DocumentNode.prototype, {
34 _setNativeNode: function(nativeNode) {
35 this.nativeNode = nativeNode;
36 this._$ = $(nativeNode);
40 return this.document.root.sameNode(this);
44 var parent = this.parent();
46 this.triggerChangeEvent('nodeDetached', {parent: parent});
50 sameNode: function(otherNode) {
51 return otherNode && this.nativeNode === otherNode.nativeNode;
55 var parentNode = this.nativeNode.parentNode;
56 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
57 return this.document.createElementNode(parentNode);
63 var parent = this.parent(),
64 parents = parent ? parent.parents() : [];
66 parents.unshift(parent);
72 var myIdx = this.getIndex();
73 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
80 var myIdx = this.getIndex(),
81 parentContents = this.parent().contents();
82 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
85 after: INSERTION(function(nativeNode) {
86 return this._$.after(nativeNode);
89 before: INSERTION(function(nativeNode) {
90 return this._$.before(nativeNode);
93 wrapWith: function(node) {
94 var insertion = this.getNodeInsertion(node);
96 this.before(insertion.ofNode);
98 insertion.ofNode.append(this);
99 return insertion.ofNode;
103 * Removes parent of a node if node has no siblings.
109 var parent = this.parent(),
111 if(parent.contents().length === 1) {
112 grandParent = parent.parent();
113 parent.unwrapContent();
118 triggerChangeEvent: function(type, metaData) {
119 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
120 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
121 this.document.trigger('change', event);
125 getNodeInsertion: function(node) {
127 if(node instanceof DocumentNode) {
128 insertion.ofNode = node;
129 insertion.insertsNew = !this.document.containsNode(node);
131 insertion.ofNode = this.document.createElementNode(node);
132 insertion.insertsNew = true;
137 getIndex: function() {
141 return this.parent().indexOf(this);
145 var ElementNode = function(nativeNode, document) {
146 DocumentNode.call(this, nativeNode, document);
148 ElementNode.prototype = Object.create(DocumentNode.prototype);
150 $.extend(ElementNode.prototype, {
151 nodeType: Node.ELEMENT_NODE,
154 var prev = this.prev(),
157 if(prev && prev.nodeType === Node.TEXT_NODE && next && next.nodeType === Node.TEXT_NODE) {
158 prev.appendText(next.getText());
162 return DocumentNode.prototype.detach.call(this);
165 setData: function(key, value) {
166 if(value !== undefined) {
167 this._$.data(key, value);
169 this._$.removeData(_.keys(this._$.data()));
174 getData: function(key) {
176 return this._$.data(key);
178 return this._$.data();
181 getTagName: function() {
182 return this.nativeNode.tagName.toLowerCase();
185 contents: function() {
187 document = this.document;
188 this._$.contents().each(function() {
189 if(this.nodeType === Node.ELEMENT_NODE) {
190 toret.push(document.createElementNode(this));
192 else if(this.nodeType === Node.TEXT_NODE) {
193 toret.push(document.createTextNode(this));
199 indexOf: function(node) {
200 return this._$.contents().index(node._$);
203 setTag: function(tagName) {
204 var node = this.document.createElementNode({tagName: tagName}),
205 oldTagName = this.getTagName(),
206 myContents = this._$.contents();
208 this.getAttrs().forEach(function(attribute) {
209 node.setAttr(attribute.name, attribute.value, true);
211 node.setData(this.getData());
213 if(this.sameNode(this.document.root)) {
214 defineDocumentProperties(this.document, node._$);
216 this._$.replaceWith(node._$);
217 this._setNativeNode(node._$[0]);
218 this._$.append(myContents);
219 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
222 getAttr: function(name) {
223 return this._$.attr(name);
226 setAttr: function(name, value, silent) {
227 var oldVal = this.getAttr(name);
228 this._$.attr(name, value);
230 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
234 getAttrs: function() {
236 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
237 toret.push(this.nativeNode.attributes[i]);
242 append: INSERTION(function(nativeNode) {
243 this._$.append(nativeNode);
246 prepend: INSERTION(function(nativeNode) {
247 this._$.prepend(nativeNode);
250 unwrapContent: function() {
251 var parent = this.parent();
256 var parentContents = parent.contents(),
257 myContents = this.contents(),
258 myIdx = parent.indexOf(this);
261 if(myContents.length === 0) {
262 return this.detach();
265 var moveLeftRange, moveRightRange, leftMerged;
267 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
268 parentContents[myIdx-1].appendText(myContents[0].getText());
269 myContents[0].detach();
270 moveLeftRange = true;
276 if(!(leftMerged && myContents.length === 1)) {
277 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
278 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
279 myContents[myContents.length-1].detach();
280 moveRightRange = true;
284 var childrenLength = this.contents().length;
285 this.contents().forEach(function(child) {
292 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
293 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
297 wrapText: function(params) {
298 return this.document._wrapText(_.extend({inside: this}, params));
302 var wrapper = $('<div>');
303 wrapper.append(this._getXMLDOMToDump());
304 return wrapper.html();
307 _getXMLDOMToDump: function() {
312 var TextNode = function(nativeNode, document) {
313 DocumentNode.call(this, nativeNode, document);
315 TextNode.prototype = Object.create(DocumentNode.prototype);
317 $.extend(TextNode.prototype, {
318 nodeType: Node.TEXT_NODE,
320 getText: function() {
321 return this.nativeNode.data;
324 setText: function(text) {
325 this.nativeNode.data = text;
326 this.triggerTextChangeEvent();
329 appendText: function(text) {
330 this.nativeNode.data = this.nativeNode.data + text;
331 this.triggerTextChangeEvent();
334 prependText: function(text) {
335 this.nativeNode.data = text + this.nativeNode.data;
336 this.triggerTextChangeEvent();
339 wrapWith: function(desc) {
340 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
341 return this.document._wrapText({
342 inside: this.parent(),
343 textNodeIdx: this.parent().indexOf(this),
344 offsetStart: Math.min(desc.start, desc.end),
345 offsetEnd: Math.max(desc.start, desc.end),
346 _with: {tagName: desc.tagName, attrs: desc.attrs}
349 return DocumentNode.prototype.wrapWith.call(this, desc);
353 triggerTextChangeEvent: function() {
354 var event = new events.ChangeEvent('nodeTextChange', {node: this});
355 this.document.trigger('change', event);
360 var parseXML = function(xml) {
364 var Document = function(xml) {
368 $.extend(Document.prototype, Backbone.Events, {
369 ElementNodeFactory: ElementNode,
370 TextNodeFactory: TextNode,
372 createElementNode: function(from) {
373 if(!(from instanceof HTMLElement)) {
375 from = document.createTextNode(from.text);
377 var node = $('<' + from.tagName + '>');
379 _.keys(from.attrs || {}).forEach(function(key) {
380 node.attr(key, from.attrs[key]);
387 if(from.nodeType === Node.TEXT_NODE) {
388 Factory = this.TextNodeFactory;
389 } else if(from.nodeType === Node.ELEMENT_NODE) {
390 Factory = this.ElementNodeFactory;
392 return new Factory(from, this);
395 createTextNode: function(nativeNode) {
396 return new this.TextNodeFactory(nativeNode, this);
399 loadXML: function(xml, options) {
400 options = options || {};
401 defineDocumentProperties(this, $(parseXML(xml)));
402 if(!options.silent) {
403 this.trigger('contentSet');
408 return this.root.toXML();
411 containsNode: function(node) {
412 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
415 wrapNodes: function(params) {
416 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
417 throw new Error('Wrapping non-sibling nodes not supported.');
420 var parent = params.element1.parent(),
421 parentContents = parent.contents(),
422 wrapper = this.createElementNode({
423 tagName: params._with.tagName,
424 attrs: params._with.attrs}),
425 idx1 = parent.indexOf(params.element1),
426 idx2 = parent.indexOf(params.element2);
434 var insertingMethod, insertingTarget;
436 insertingMethod = 'prepend';
437 insertingTarget = parent;
439 insertingMethod = 'after';
440 insertingTarget = parentContents[idx1-1];
443 for(var i = idx1; i <= idx2; i++) {
444 wrapper.append(parentContents[i].detach());
447 insertingTarget[insertingMethod](wrapper);
451 getSiblingParents: function(params) {
452 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
453 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
454 noSiblingParents = null;
456 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
457 return noSiblingParents;
461 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
462 if(parents1[i].sameNode(parents2[i])) {
467 return {node1: parents1[i], node2: parents2[i]};
470 _wrapText: function(params) {
471 params = _.extend({textNodeIdx: 0}, params);
472 if(typeof params.textNodeIdx === 'number') {
473 params.textNodeIdx = [params.textNodeIdx];
476 var contentsInside = params.inside.contents(),
477 idx1 = Math.min.apply(Math, params.textNodeIdx),
478 idx2 = Math.max.apply(Math, params.textNodeIdx),
479 textNode1 = contentsInside[idx1],
480 textNode2 = contentsInside[idx2],
481 sameNode = textNode1.sameNode(textNode2),
482 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
483 prefixInside = textNode1.getText().substr(params.offsetStart),
484 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
485 suffixOutside = textNode2.getText().substr(params.offsetEnd)
488 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
489 throw new Error('Wrapping text in non-sibling text nodes not supported.');
492 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
493 textNode1.after(wrapperElement);
496 if(prefixOutside.length > 0) {
497 wrapperElement.before({text:prefixOutside});
500 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
501 wrapperElement.append({text: core});
504 if(prefixInside.length > 0) {
505 wrapperElement.append({text: prefixInside});
507 for(var i = idx1 + 1; i < idx2; i++) {
508 wrapperElement.append(contentsInside[i]);
510 if(suffixInside.length > 0) {
511 wrapperElement.append({text: suffixInside});
514 if(suffixOutside.length > 0) {
515 wrapperElement.after({text: suffixOutside});
517 return wrapperElement;
520 trigger: function() {
521 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
522 Backbone.Events.trigger.apply(this, arguments);
526 var defineDocumentProperties = function(doc, $document) {
527 Object.defineProperty(doc, 'root', {get: function() {
528 return doc.createElementNode($document[0]);
529 }, configurable: true});
530 Object.defineProperty(doc, 'dom', {get: function() {
532 }, configurable: true});
536 documentFromXML: function(xml) {
537 return new Document(parseXML(xml));
540 elementNodeFromXML: function(xml) {
541 return this.documentFromXML(xml).root;
545 DocumentNode: DocumentNode,
546 ElementNode: ElementNode