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 replaceWith: function(node) {
77 return this.document.replaceRoot(node);
79 toret = this.after(node);
84 sameNode: function(otherNode) {
85 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
89 var parentNode = this.nativeNode.parentNode;
90 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
91 return this.document.createDocumentNode(parentNode);
97 var parent = this.parent(),
98 parents = parent ? parent.parents() : [];
100 parents.unshift(parent);
106 var myIdx = this.getIndex();
107 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
114 var myIdx = this.getIndex(),
115 parentContents = this.parent().contents();
116 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
119 isSurroundedByTextElements: function() {
120 var prev = this.prev(),
122 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
125 after: INSERTION(function(nativeNode) {
126 return this._$.after(nativeNode);
129 before: INSERTION(function(nativeNode) {
130 return this._$.before(nativeNode);
133 wrapWith: function(node) {
134 var insertion = this.getNodeInsertion(node);
136 this.before(insertion.ofNode);
138 insertion.ofNode.append(this);
139 return insertion.ofNode;
143 * Removes parent of a node if node has no siblings.
149 var parent = this.parent(),
151 if(parent.contents().length === 1) {
152 grandParent = parent.parent();
153 parent.unwrapContent();
158 triggerChangeEvent: function(type, metaData) {
159 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
160 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
161 this.document.trigger('change', event);
165 getNodeInsertion: function(node) {
166 return this.document.getNodeInsertion(node);
169 getIndex: function() {
173 return this.parent().indexOf(this);
177 var ElementNode = function(nativeNode, document) {
178 DocumentNode.call(this, nativeNode, document);
180 ElementNode.prototype = Object.create(DocumentNode.prototype);
182 $.extend(ElementNode.prototype, {
183 nodeType: Node.ELEMENT_NODE,
187 if(this.parent() && this.isSurroundedByTextElements()) {
189 this.prev().appendText(next.getText());
192 return DocumentNode.prototype.detach.call(this);
195 setData: function(key, value) {
196 if(value !== undefined) {
197 this._$.data(key, value);
199 this._$.removeData(_.keys(this._$.data()));
204 getData: function(key) {
206 return this._$.data(key);
208 return this._$.data();
211 getTagName: function() {
212 return this.nativeNode.tagName.toLowerCase();
215 contents: function() {
217 document = this.document;
218 this._$.contents().each(function() {
219 toret.push(document.createDocumentNode(this));
224 indexOf: function(node) {
225 return this._$.contents().index(node._$);
228 setTag: function(tagName) {
229 var node = this.document.createDocumentNode({tagName: tagName}),
230 oldTagName = this.getTagName(),
231 myContents = this._$.contents();
233 this.getAttrs().forEach(function(attribute) {
234 node.setAttr(attribute.name, attribute.value, true);
236 node.setData(this.getData());
238 if(this.sameNode(this.document.root)) {
239 defineDocumentProperties(this.document, node._$);
241 this._$.replaceWith(node._$);
242 this._setNativeNode(node._$[0]);
243 this._$.append(myContents);
244 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
247 getAttr: function(name) {
248 return this._$.attr(name);
251 setAttr: function(name, value, silent) {
252 var oldVal = this.getAttr(name);
253 this._$.attr(name, value);
255 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
259 getAttrs: function() {
261 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
262 toret.push(this.nativeNode.attributes[i]);
267 append: INSERTION(function(nativeNode) {
268 this._$.append(nativeNode);
271 prepend: INSERTION(function(nativeNode) {
272 this._$.prepend(nativeNode);
275 insertAtIndex: function(nativeNode, index) {
276 var contents = this.contents();
277 if(index < contents.length) {
278 return contents[index].before(nativeNode);
279 } else if(index === contents.length) {
280 return this.append(nativeNode);
284 unwrapContent: function() {
285 var parent = this.parent();
290 var myContents = this.contents(),
291 myIdx = parent.indexOf(this);
294 if(myContents.length === 0) {
295 return this.detach();
298 var prev = this.prev(),
300 moveLeftRange, moveRightRange, leftMerged;
302 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
303 prev.appendText(myContents[0].getText());
304 myContents[0].detach();
305 moveLeftRange = true;
311 if(!(leftMerged && myContents.length === 1)) {
312 var lastContents = _.last(myContents);
313 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
314 next.prependText(lastContents.getText());
315 lastContents.detach();
316 moveRightRange = true;
320 var childrenLength = this.contents().length;
321 this.contents().forEach(function(child) {
328 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
329 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
333 wrapText: function(params) {
334 return this.document._wrapText(_.extend({inside: this}, params));
338 var wrapper = $('<div>');
339 wrapper.append(this._getXMLDOMToDump());
340 return wrapper.html();
343 _getXMLDOMToDump: function() {
348 var TextNode = function(nativeNode, document) {
349 DocumentNode.call(this, nativeNode, document);
351 TextNode.prototype = Object.create(DocumentNode.prototype);
353 $.extend(TextNode.prototype, {
354 nodeType: Node.TEXT_NODE,
356 getText: function() {
357 return this.nativeNode.data;
360 setText: function(text) {
361 this.nativeNode.data = text;
362 this.triggerTextChangeEvent();
365 appendText: function(text) {
366 this.nativeNode.data = this.nativeNode.data + text;
367 this.triggerTextChangeEvent();
370 prependText: function(text) {
371 this.nativeNode.data = text + this.nativeNode.data;
372 this.triggerTextChangeEvent();
375 wrapWith: function(desc) {
376 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
377 return this.document._wrapText({
378 inside: this.parent(),
379 textNodeIdx: this.parent().indexOf(this),
380 offsetStart: Math.min(desc.start, desc.end),
381 offsetEnd: Math.max(desc.start, desc.end),
382 _with: {tagName: desc.tagName, attrs: desc.attrs}
385 return DocumentNode.prototype.wrapWith.call(this, desc);
389 split: function(params) {
390 var parentElement = this.parent(),
392 succeedingChildren = [],
393 prefix = this.getText().substr(0, params.offset),
394 suffix = this.getText().substr(params.offset);
396 parentElement.contents().forEach(function(child) {
398 succeedingChildren.push(child);
400 if(child.sameNode(this)) {
405 if(prefix.length > 0) {
406 this.setText(prefix);
413 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
414 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
415 parentElement.after(newElement);
417 if(suffix.length > 0) {
418 newElement.append({text: suffix});
420 succeedingChildren.forEach(function(child) {
421 newElement.append(child);
424 return {first: parentElement, second: newElement};
427 triggerTextChangeEvent: function() {
428 var event = new events.ChangeEvent('nodeTextChange', {node: this});
429 this.document.trigger('change', event);
434 var parseXML = function(xml) {
435 return $($.trim(xml))[0];
438 var Document = function(xml) {
442 $.extend(Document.prototype, Backbone.Events, {
443 ElementNodeFactory: ElementNode,
444 TextNodeFactory: TextNode,
446 createDocumentNode: function(from) {
447 if(!(from instanceof Node)) {
448 if(from.text !== undefined) {
449 /* globals document */
450 from = document.createTextNode(from.text);
452 var node = $('<' + from.tagName + '>');
454 _.keys(from.attrs || {}).forEach(function(key) {
455 node.attr(key, from.attrs[key]);
462 if(from.nodeType === Node.TEXT_NODE) {
463 Factory = this.TextNodeFactory;
464 } else if(from.nodeType === Node.ELEMENT_NODE) {
465 Factory = this.ElementNodeFactory;
467 return new Factory(from, this);
470 loadXML: function(xml, options) {
471 options = options || {};
472 defineDocumentProperties(this, $(parseXML(xml)));
473 if(!options.silent) {
474 this.trigger('contentSet');
479 return this.root.toXML();
482 containsNode: function(node) {
483 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
486 wrapNodes: function(params) {
487 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
488 throw new Error('Wrapping non-sibling nodes not supported.');
491 var parent = params.node1.parent(),
492 parentContents = parent.contents(),
493 wrapper = this.createDocumentNode({
494 tagName: params._with.tagName,
495 attrs: params._with.attrs}),
496 idx1 = parent.indexOf(params.node1),
497 idx2 = parent.indexOf(params.node2);
505 var insertingMethod, insertingTarget;
507 insertingMethod = 'prepend';
508 insertingTarget = parent;
510 insertingMethod = 'after';
511 insertingTarget = parentContents[idx1-1];
514 for(var i = idx1; i <= idx2; i++) {
515 wrapper.append(parentContents[i].detach());
518 insertingTarget[insertingMethod](wrapper);
522 getSiblingParents: function(params) {
523 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
524 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
525 noSiblingParents = null;
527 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
528 return noSiblingParents;
532 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
533 if(parents1[i].sameNode(parents2[i])) {
538 return {node1: parents1[i], node2: parents2[i]};
541 _wrapText: function(params) {
542 params = _.extend({textNodeIdx: 0}, params);
543 if(typeof params.textNodeIdx === 'number') {
544 params.textNodeIdx = [params.textNodeIdx];
547 var contentsInside = params.inside.contents(),
548 idx1 = Math.min.apply(Math, params.textNodeIdx),
549 idx2 = Math.max.apply(Math, params.textNodeIdx),
550 textNode1 = contentsInside[idx1],
551 textNode2 = contentsInside[idx2],
552 sameNode = textNode1.sameNode(textNode2),
553 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
554 prefixInside = textNode1.getText().substr(params.offsetStart),
555 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
556 suffixOutside = textNode2.getText().substr(params.offsetEnd)
559 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
560 throw new Error('Wrapping text in non-sibling text nodes not supported.');
563 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
564 textNode1.after(wrapperElement);
567 if(prefixOutside.length > 0) {
568 wrapperElement.before({text:prefixOutside});
571 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
572 wrapperElement.append({text: core});
575 if(prefixInside.length > 0) {
576 wrapperElement.append({text: prefixInside});
578 for(var i = idx1 + 1; i < idx2; i++) {
579 wrapperElement.append(contentsInside[i]);
581 if(suffixInside.length > 0) {
582 wrapperElement.append({text: suffixInside});
585 if(suffixOutside.length > 0) {
586 wrapperElement.after({text: suffixOutside});
588 return wrapperElement;
591 trigger: function() {
592 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
593 Backbone.Events.trigger.apply(this, arguments);
596 getNodeInsertion: function(node) {
598 if(node instanceof DocumentNode) {
599 insertion.ofNode = node;
600 insertion.insertsNew = !this.containsNode(node);
602 insertion.ofNode = this.createDocumentNode(node);
603 insertion.insertsNew = true;
608 replaceRoot: function(node) {
609 var insertion = this.getNodeInsertion(node);
611 defineDocumentProperties(this, insertion.ofNode._$);
612 insertion.ofNode.triggerChangeEvent('nodeAdded');
613 return insertion.ofNode;
617 var defineDocumentProperties = function(doc, $document) {
618 Object.defineProperty(doc, 'root', {get: function() {
619 return doc.createDocumentNode($document[0]);
620 }, configurable: true});
621 Object.defineProperty(doc, 'dom', {get: function() {
623 }, configurable: true});
627 documentFromXML: function(xml) {
628 return new Document(xml);
631 elementNodeFromXML: function(xml) {
632 return this.documentFromXML(xml).root;
636 DocumentNode: DocumentNode,
637 ElementNode: ElementNode