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.createDocumentNode(this._$.clone(true, true)[0]);
43 getPath: function(ancestor) {
44 var nodePath = [this].concat(this.parents()),
46 ancestor = ancestor || this.document.root;
48 nodePath.some(function(node, i) {
49 if(node.sameNode(ancestor)) {
55 if(idx !== 'undefined') {
56 nodePath = nodePath.slice(0, idx);
58 toret = nodePath.map(function(node) {return node.getIndex(); });
64 return this.document.root.sameNode(this);
68 var parent = this.parent();
70 this.triggerChangeEvent('nodeDetached', {parent: parent});
74 sameNode: function(otherNode) {
75 return otherNode && this.nativeNode === otherNode.nativeNode;
79 var parentNode = this.nativeNode.parentNode;
80 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
81 return this.document.createDocumentNode(parentNode);
87 var parent = this.parent(),
88 parents = parent ? parent.parents() : [];
90 parents.unshift(parent);
96 var myIdx = this.getIndex();
97 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
104 var myIdx = this.getIndex(),
105 parentContents = this.parent().contents();
106 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
109 isSurroundedByTextElements: function() {
110 var prev = this.prev(),
112 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
115 after: INSERTION(function(nativeNode) {
116 return this._$.after(nativeNode);
119 before: INSERTION(function(nativeNode) {
120 return this._$.before(nativeNode);
123 wrapWith: function(node) {
124 var insertion = this.getNodeInsertion(node);
126 this.before(insertion.ofNode);
128 insertion.ofNode.append(this);
129 return insertion.ofNode;
133 * Removes parent of a node if node has no siblings.
139 var parent = this.parent(),
141 if(parent.contents().length === 1) {
142 grandParent = parent.parent();
143 parent.unwrapContent();
148 triggerChangeEvent: function(type, metaData) {
149 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
150 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
151 this.document.trigger('change', event);
155 getNodeInsertion: function(node) {
157 if(node instanceof DocumentNode) {
158 insertion.ofNode = node;
159 insertion.insertsNew = !this.document.containsNode(node);
161 insertion.ofNode = this.document.createDocumentNode(node);
162 insertion.insertsNew = true;
167 getIndex: function() {
171 return this.parent().indexOf(this);
175 var ElementNode = function(nativeNode, document) {
176 DocumentNode.call(this, nativeNode, document);
178 ElementNode.prototype = Object.create(DocumentNode.prototype);
180 $.extend(ElementNode.prototype, {
181 nodeType: Node.ELEMENT_NODE,
185 if(parent && this.isSurroundedByTextElements()) {
187 this.prev().appendText(next.getText());
190 return DocumentNode.prototype.detach.call(this);
193 setData: function(key, value) {
194 if(value !== undefined) {
195 this._$.data(key, value);
197 this._$.removeData(_.keys(this._$.data()));
202 getData: function(key) {
204 return this._$.data(key);
206 return this._$.data();
209 getTagName: function() {
210 return this.nativeNode.tagName.toLowerCase();
213 contents: function() {
215 document = this.document;
216 this._$.contents().each(function() {
217 toret.push(document.createDocumentNode(this));
222 indexOf: function(node) {
223 return this._$.contents().index(node._$);
226 setTag: function(tagName) {
227 var node = this.document.createDocumentNode({tagName: tagName}),
228 oldTagName = this.getTagName(),
229 myContents = this._$.contents();
231 this.getAttrs().forEach(function(attribute) {
232 node.setAttr(attribute.name, attribute.value, true);
234 node.setData(this.getData());
236 if(this.sameNode(this.document.root)) {
237 defineDocumentProperties(this.document, node._$);
239 this._$.replaceWith(node._$);
240 this._setNativeNode(node._$[0]);
241 this._$.append(myContents);
242 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
245 getAttr: function(name) {
246 return this._$.attr(name);
249 setAttr: function(name, value, silent) {
250 var oldVal = this.getAttr(name);
251 this._$.attr(name, value);
253 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
257 getAttrs: function() {
259 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
260 toret.push(this.nativeNode.attributes[i]);
265 append: INSERTION(function(nativeNode) {
266 this._$.append(nativeNode);
269 prepend: INSERTION(function(nativeNode) {
270 this._$.prepend(nativeNode);
273 unwrapContent: function() {
274 var parent = this.parent();
279 var myContents = this.contents(),
280 myIdx = parent.indexOf(this);
283 if(myContents.length === 0) {
284 return this.detach();
287 var prev = this.prev(),
289 moveLeftRange, moveRightRange, leftMerged;
291 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
292 prev.appendText(myContents[0].getText());
293 myContents[0].detach();
294 moveLeftRange = true;
300 if(!(leftMerged && myContents.length === 1)) {
301 var lastContents = _.last(myContents);
302 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
303 next.prependText(lastContents.getText());
304 lastContents.detach();
305 moveRightRange = true;
309 var childrenLength = this.contents().length;
310 this.contents().forEach(function(child) {
317 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
318 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
322 wrapText: function(params) {
323 return this.document._wrapText(_.extend({inside: this}, params));
327 var wrapper = $('<div>');
328 wrapper.append(this._getXMLDOMToDump());
329 return wrapper.html();
332 _getXMLDOMToDump: function() {
337 var TextNode = function(nativeNode, document) {
338 DocumentNode.call(this, nativeNode, document);
340 TextNode.prototype = Object.create(DocumentNode.prototype);
342 $.extend(TextNode.prototype, {
343 nodeType: Node.TEXT_NODE,
345 getText: function() {
346 return this.nativeNode.data;
349 setText: function(text) {
350 this.nativeNode.data = text;
351 this.triggerTextChangeEvent();
354 appendText: function(text) {
355 this.nativeNode.data = this.nativeNode.data + text;
356 this.triggerTextChangeEvent();
359 prependText: function(text) {
360 this.nativeNode.data = text + this.nativeNode.data;
361 this.triggerTextChangeEvent();
364 wrapWith: function(desc) {
365 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
366 return this.document._wrapText({
367 inside: this.parent(),
368 textNodeIdx: this.parent().indexOf(this),
369 offsetStart: Math.min(desc.start, desc.end),
370 offsetEnd: Math.max(desc.start, desc.end),
371 _with: {tagName: desc.tagName, attrs: desc.attrs}
374 return DocumentNode.prototype.wrapWith.call(this, desc);
378 split: function(params) {
379 var parentElement = this.parent(),
381 succeedingChildren = [],
382 prefix = this.getText().substr(0, params.offset),
383 suffix = this.getText().substr(params.offset);
385 parentElement.contents().forEach(function(child) {
387 succeedingChildren.push(child);
389 if(child.sameNode(this)) {
394 if(prefix.length > 0) {
395 this.setText(prefix);
402 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
403 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
404 parentElement.after(newElement);
406 if(suffix.length > 0) {
407 newElement.append({text: suffix});
409 succeedingChildren.forEach(function(child) {
410 newElement.append(child);
413 return {first: parentElement, second: newElement};
416 triggerTextChangeEvent: function() {
417 var event = new events.ChangeEvent('nodeTextChange', {node: this});
418 this.document.trigger('change', event);
423 var parseXML = function(xml) {
424 return $($.trim(xml))[0];
427 var Document = function(xml) {
431 $.extend(Document.prototype, Backbone.Events, {
432 ElementNodeFactory: ElementNode,
433 TextNodeFactory: TextNode,
435 createDocumentNode: function(from) {
436 if(!(from instanceof Node)) {
437 if(from.text !== undefined) {
438 from = document.createTextNode(from.text);
440 var node = $('<' + from.tagName + '>');
442 _.keys(from.attrs || {}).forEach(function(key) {
443 node.attr(key, from.attrs[key]);
450 if(from.nodeType === Node.TEXT_NODE) {
451 Factory = this.TextNodeFactory;
452 } else if(from.nodeType === Node.ELEMENT_NODE) {
453 Factory = this.ElementNodeFactory;
455 return new Factory(from, this);
458 loadXML: function(xml, options) {
459 options = options || {};
460 defineDocumentProperties(this, $(parseXML(xml)));
461 if(!options.silent) {
462 this.trigger('contentSet');
467 return this.root.toXML();
470 containsNode: function(node) {
471 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
474 wrapNodes: function(params) {
475 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
476 throw new Error('Wrapping non-sibling nodes not supported.');
479 var parent = params.element1.parent(),
480 parentContents = parent.contents(),
481 wrapper = this.createDocumentNode({
482 tagName: params._with.tagName,
483 attrs: params._with.attrs}),
484 idx1 = parent.indexOf(params.element1),
485 idx2 = parent.indexOf(params.element2);
493 var insertingMethod, insertingTarget;
495 insertingMethod = 'prepend';
496 insertingTarget = parent;
498 insertingMethod = 'after';
499 insertingTarget = parentContents[idx1-1];
502 for(var i = idx1; i <= idx2; i++) {
503 wrapper.append(parentContents[i].detach());
506 insertingTarget[insertingMethod](wrapper);
510 getSiblingParents: function(params) {
511 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
512 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
513 noSiblingParents = null;
515 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
516 return noSiblingParents;
520 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
521 if(parents1[i].sameNode(parents2[i])) {
526 return {node1: parents1[i], node2: parents2[i]};
529 _wrapText: function(params) {
530 params = _.extend({textNodeIdx: 0}, params);
531 if(typeof params.textNodeIdx === 'number') {
532 params.textNodeIdx = [params.textNodeIdx];
535 var contentsInside = params.inside.contents(),
536 idx1 = Math.min.apply(Math, params.textNodeIdx),
537 idx2 = Math.max.apply(Math, params.textNodeIdx),
538 textNode1 = contentsInside[idx1],
539 textNode2 = contentsInside[idx2],
540 sameNode = textNode1.sameNode(textNode2),
541 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
542 prefixInside = textNode1.getText().substr(params.offsetStart),
543 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
544 suffixOutside = textNode2.getText().substr(params.offsetEnd)
547 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
548 throw new Error('Wrapping text in non-sibling text nodes not supported.');
551 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
552 textNode1.after(wrapperElement);
555 if(prefixOutside.length > 0) {
556 wrapperElement.before({text:prefixOutside});
559 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
560 wrapperElement.append({text: core});
563 if(prefixInside.length > 0) {
564 wrapperElement.append({text: prefixInside});
566 for(var i = idx1 + 1; i < idx2; i++) {
567 wrapperElement.append(contentsInside[i]);
569 if(suffixInside.length > 0) {
570 wrapperElement.append({text: suffixInside});
573 if(suffixOutside.length > 0) {
574 wrapperElement.after({text: suffixOutside});
576 return wrapperElement;
579 trigger: function() {
580 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
581 Backbone.Events.trigger.apply(this, arguments);
585 var defineDocumentProperties = function(doc, $document) {
586 Object.defineProperty(doc, 'root', {get: function() {
587 return doc.createDocumentNode($document[0]);
588 }, configurable: true});
589 Object.defineProperty(doc, 'dom', {get: function() {
591 }, configurable: true});
595 documentFromXML: function(xml) {
596 return new Document(xml);
599 elementNodeFromXML: function(xml) {
600 return this.documentFromXML(xml).root;
604 DocumentNode: DocumentNode,
605 ElementNode: ElementNode