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 isSurroundedByTextElements: function() {
86 var prev = this.prev(),
88 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
91 after: INSERTION(function(nativeNode) {
92 return this._$.after(nativeNode);
95 before: INSERTION(function(nativeNode) {
96 return this._$.before(nativeNode);
99 wrapWith: function(node) {
100 var insertion = this.getNodeInsertion(node);
102 this.before(insertion.ofNode);
104 insertion.ofNode.append(this);
105 return insertion.ofNode;
109 * Removes parent of a node if node has no siblings.
115 var parent = this.parent(),
117 if(parent.contents().length === 1) {
118 grandParent = parent.parent();
119 parent.unwrapContent();
124 triggerChangeEvent: function(type, metaData) {
125 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
126 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
127 this.document.trigger('change', event);
131 getNodeInsertion: function(node) {
133 if(node instanceof DocumentNode) {
134 insertion.ofNode = node;
135 insertion.insertsNew = !this.document.containsNode(node);
137 insertion.ofNode = this.document.createElementNode(node);
138 insertion.insertsNew = true;
143 getIndex: function() {
147 return this.parent().indexOf(this);
151 var ElementNode = function(nativeNode, document) {
152 DocumentNode.call(this, nativeNode, document);
154 ElementNode.prototype = Object.create(DocumentNode.prototype);
156 $.extend(ElementNode.prototype, {
157 nodeType: Node.ELEMENT_NODE,
161 if(parent && this.isSurroundedByTextElements()) {
163 this.prev().appendText(next.getText());
166 return DocumentNode.prototype.detach.call(this);
169 setData: function(key, value) {
170 if(value !== undefined) {
171 this._$.data(key, value);
173 this._$.removeData(_.keys(this._$.data()));
178 getData: function(key) {
180 return this._$.data(key);
182 return this._$.data();
185 getTagName: function() {
186 return this.nativeNode.tagName.toLowerCase();
189 contents: function() {
191 document = this.document;
192 this._$.contents().each(function() {
193 if(this.nodeType === Node.ELEMENT_NODE) {
194 toret.push(document.createElementNode(this));
196 else if(this.nodeType === Node.TEXT_NODE) {
197 toret.push(document.createTextNode(this));
203 indexOf: function(node) {
204 return this._$.contents().index(node._$);
207 setTag: function(tagName) {
208 var node = this.document.createElementNode({tagName: tagName}),
209 oldTagName = this.getTagName(),
210 myContents = this._$.contents();
212 this.getAttrs().forEach(function(attribute) {
213 node.setAttr(attribute.name, attribute.value, true);
215 node.setData(this.getData());
217 if(this.sameNode(this.document.root)) {
218 defineDocumentProperties(this.document, node._$);
220 this._$.replaceWith(node._$);
221 this._setNativeNode(node._$[0]);
222 this._$.append(myContents);
223 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
226 getAttr: function(name) {
227 return this._$.attr(name);
230 setAttr: function(name, value, silent) {
231 var oldVal = this.getAttr(name);
232 this._$.attr(name, value);
234 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
238 getAttrs: function() {
240 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
241 toret.push(this.nativeNode.attributes[i]);
246 append: INSERTION(function(nativeNode) {
247 this._$.append(nativeNode);
250 prepend: INSERTION(function(nativeNode) {
251 this._$.prepend(nativeNode);
254 unwrapContent: function() {
255 var parent = this.parent();
260 var myContents = this.contents(),
261 myIdx = parent.indexOf(this);
264 if(myContents.length === 0) {
265 return this.detach();
268 var prev = this.prev(),
270 moveLeftRange, moveRightRange, leftMerged;
272 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
273 prev.appendText(myContents[0].getText());
274 myContents[0].detach();
275 moveLeftRange = true;
281 if(!(leftMerged && myContents.length === 1)) {
282 var lastContents = _.last(myContents);
283 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
284 next.prependText(lastContents.getText());
285 lastContents.detach();
286 moveRightRange = true;
290 var childrenLength = this.contents().length;
291 this.contents().forEach(function(child) {
298 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
299 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
303 wrapText: function(params) {
304 return this.document._wrapText(_.extend({inside: this}, params));
308 var wrapper = $('<div>');
309 wrapper.append(this._getXMLDOMToDump());
310 return wrapper.html();
313 _getXMLDOMToDump: function() {
318 var TextNode = function(nativeNode, document) {
319 DocumentNode.call(this, nativeNode, document);
321 TextNode.prototype = Object.create(DocumentNode.prototype);
323 $.extend(TextNode.prototype, {
324 nodeType: Node.TEXT_NODE,
326 getText: function() {
327 return this.nativeNode.data;
330 setText: function(text) {
331 this.nativeNode.data = text;
332 this.triggerTextChangeEvent();
335 appendText: function(text) {
336 this.nativeNode.data = this.nativeNode.data + text;
337 this.triggerTextChangeEvent();
340 prependText: function(text) {
341 this.nativeNode.data = text + this.nativeNode.data;
342 this.triggerTextChangeEvent();
345 wrapWith: function(desc) {
346 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
347 return this.document._wrapText({
348 inside: this.parent(),
349 textNodeIdx: this.parent().indexOf(this),
350 offsetStart: Math.min(desc.start, desc.end),
351 offsetEnd: Math.max(desc.start, desc.end),
352 _with: {tagName: desc.tagName, attrs: desc.attrs}
355 return DocumentNode.prototype.wrapWith.call(this, desc);
359 triggerTextChangeEvent: function() {
360 var event = new events.ChangeEvent('nodeTextChange', {node: this});
361 this.document.trigger('change', event);
366 var parseXML = function(xml) {
370 var Document = function(xml) {
374 $.extend(Document.prototype, Backbone.Events, {
375 ElementNodeFactory: ElementNode,
376 TextNodeFactory: TextNode,
378 createElementNode: function(from) {
379 if(!(from instanceof Node)) {
381 from = document.createTextNode(from.text);
383 var node = $('<' + from.tagName + '>');
385 _.keys(from.attrs || {}).forEach(function(key) {
386 node.attr(key, from.attrs[key]);
393 if(from.nodeType === Node.TEXT_NODE) {
394 Factory = this.TextNodeFactory;
395 } else if(from.nodeType === Node.ELEMENT_NODE) {
396 Factory = this.ElementNodeFactory;
398 return new Factory(from, this);
401 createTextNode: function(nativeNode) {
402 return new this.TextNodeFactory(nativeNode, this);
405 loadXML: function(xml, options) {
406 options = options || {};
407 defineDocumentProperties(this, $(parseXML(xml)));
408 if(!options.silent) {
409 this.trigger('contentSet');
414 return this.root.toXML();
417 containsNode: function(node) {
418 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
421 wrapNodes: function(params) {
422 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
423 throw new Error('Wrapping non-sibling nodes not supported.');
426 var parent = params.element1.parent(),
427 parentContents = parent.contents(),
428 wrapper = this.createElementNode({
429 tagName: params._with.tagName,
430 attrs: params._with.attrs}),
431 idx1 = parent.indexOf(params.element1),
432 idx2 = parent.indexOf(params.element2);
440 var insertingMethod, insertingTarget;
442 insertingMethod = 'prepend';
443 insertingTarget = parent;
445 insertingMethod = 'after';
446 insertingTarget = parentContents[idx1-1];
449 for(var i = idx1; i <= idx2; i++) {
450 wrapper.append(parentContents[i].detach());
453 insertingTarget[insertingMethod](wrapper);
457 getSiblingParents: function(params) {
458 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
459 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
460 noSiblingParents = null;
462 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
463 return noSiblingParents;
467 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
468 if(parents1[i].sameNode(parents2[i])) {
473 return {node1: parents1[i], node2: parents2[i]};
476 _wrapText: function(params) {
477 params = _.extend({textNodeIdx: 0}, params);
478 if(typeof params.textNodeIdx === 'number') {
479 params.textNodeIdx = [params.textNodeIdx];
482 var contentsInside = params.inside.contents(),
483 idx1 = Math.min.apply(Math, params.textNodeIdx),
484 idx2 = Math.max.apply(Math, params.textNodeIdx),
485 textNode1 = contentsInside[idx1],
486 textNode2 = contentsInside[idx2],
487 sameNode = textNode1.sameNode(textNode2),
488 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
489 prefixInside = textNode1.getText().substr(params.offsetStart),
490 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
491 suffixOutside = textNode2.getText().substr(params.offsetEnd)
494 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
495 throw new Error('Wrapping text in non-sibling text nodes not supported.');
498 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
499 textNode1.after(wrapperElement);
502 if(prefixOutside.length > 0) {
503 wrapperElement.before({text:prefixOutside});
506 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
507 wrapperElement.append({text: core});
510 if(prefixInside.length > 0) {
511 wrapperElement.append({text: prefixInside});
513 for(var i = idx1 + 1; i < idx2; i++) {
514 wrapperElement.append(contentsInside[i]);
516 if(suffixInside.length > 0) {
517 wrapperElement.append({text: suffixInside});
520 if(suffixOutside.length > 0) {
521 wrapperElement.after({text: suffixOutside});
523 return wrapperElement;
526 trigger: function() {
527 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
528 Backbone.Events.trigger.apply(this, arguments);
532 var defineDocumentProperties = function(doc, $document) {
533 Object.defineProperty(doc, 'root', {get: function() {
534 return doc.createElementNode($document[0]);
535 }, configurable: true});
536 Object.defineProperty(doc, 'dom', {get: function() {
538 }, configurable: true});
542 documentFromXML: function(xml) {
543 return new Document(parseXML(xml));
546 elementNodeFromXML: function(xml) {
547 return this.documentFromXML(xml).root;
551 DocumentNode: DocumentNode,
552 ElementNode: ElementNode