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.createDocumentNode(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.createDocumentNode(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 toret.push(document.createDocumentNode(this));
198 indexOf: function(node) {
199 return this._$.contents().index(node._$);
202 setTag: function(tagName) {
203 var node = this.document.createDocumentNode({tagName: tagName}),
204 oldTagName = this.getTagName(),
205 myContents = this._$.contents();
207 this.getAttrs().forEach(function(attribute) {
208 node.setAttr(attribute.name, attribute.value, true);
210 node.setData(this.getData());
212 if(this.sameNode(this.document.root)) {
213 defineDocumentProperties(this.document, node._$);
215 this._$.replaceWith(node._$);
216 this._setNativeNode(node._$[0]);
217 this._$.append(myContents);
218 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
221 getAttr: function(name) {
222 return this._$.attr(name);
225 setAttr: function(name, value, silent) {
226 var oldVal = this.getAttr(name);
227 this._$.attr(name, value);
229 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
233 getAttrs: function() {
235 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
236 toret.push(this.nativeNode.attributes[i]);
241 append: INSERTION(function(nativeNode) {
242 this._$.append(nativeNode);
245 prepend: INSERTION(function(nativeNode) {
246 this._$.prepend(nativeNode);
249 unwrapContent: function() {
250 var parent = this.parent();
255 var myContents = this.contents(),
256 myIdx = parent.indexOf(this);
259 if(myContents.length === 0) {
260 return this.detach();
263 var prev = this.prev(),
265 moveLeftRange, moveRightRange, leftMerged;
267 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
268 prev.appendText(myContents[0].getText());
269 myContents[0].detach();
270 moveLeftRange = true;
276 if(!(leftMerged && myContents.length === 1)) {
277 var lastContents = _.last(myContents);
278 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
279 next.prependText(lastContents.getText());
280 lastContents.detach();
281 moveRightRange = true;
285 var childrenLength = this.contents().length;
286 this.contents().forEach(function(child) {
293 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
294 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
298 wrapText: function(params) {
299 return this.document._wrapText(_.extend({inside: this}, params));
303 var wrapper = $('<div>');
304 wrapper.append(this._getXMLDOMToDump());
305 return wrapper.html();
308 _getXMLDOMToDump: function() {
313 var TextNode = function(nativeNode, document) {
314 DocumentNode.call(this, nativeNode, document);
316 TextNode.prototype = Object.create(DocumentNode.prototype);
318 $.extend(TextNode.prototype, {
319 nodeType: Node.TEXT_NODE,
321 getText: function() {
322 return this.nativeNode.data;
325 setText: function(text) {
326 this.nativeNode.data = text;
327 this.triggerTextChangeEvent();
330 appendText: function(text) {
331 this.nativeNode.data = this.nativeNode.data + text;
332 this.triggerTextChangeEvent();
335 prependText: function(text) {
336 this.nativeNode.data = text + this.nativeNode.data;
337 this.triggerTextChangeEvent();
340 wrapWith: function(desc) {
341 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
342 return this.document._wrapText({
343 inside: this.parent(),
344 textNodeIdx: this.parent().indexOf(this),
345 offsetStart: Math.min(desc.start, desc.end),
346 offsetEnd: Math.max(desc.start, desc.end),
347 _with: {tagName: desc.tagName, attrs: desc.attrs}
350 return DocumentNode.prototype.wrapWith.call(this, desc);
354 split: function(params) {
355 var parentElement = this.parent(),
357 succeedingChildren = [],
358 prefix = this.getText().substr(0, params.offset),
359 suffix = this.getText().substr(params.offset);
361 parentElement.contents().forEach(function(child) {
363 succeedingChildren.push(child);
365 if(child.sameNode(this)) {
370 if(prefix.length > 0) {
371 this.setText(prefix);
378 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
379 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
380 parentElement.after(newElement);
382 if(suffix.length > 0) {
383 newElement.append({text: suffix});
385 succeedingChildren.forEach(function(child) {
386 newElement.append(child);
389 return {first: parentElement, second: newElement};
392 triggerTextChangeEvent: function() {
393 var event = new events.ChangeEvent('nodeTextChange', {node: this});
394 this.document.trigger('change', event);
399 var parseXML = function(xml) {
400 return $($.trim(xml))[0];
403 var Document = function(xml) {
407 $.extend(Document.prototype, Backbone.Events, {
408 ElementNodeFactory: ElementNode,
409 TextNodeFactory: TextNode,
411 createDocumentNode: function(from) {
412 if(!(from instanceof Node)) {
413 if(from.text !== undefined) {
414 from = document.createTextNode(from.text);
416 var node = $('<' + from.tagName + '>');
418 _.keys(from.attrs || {}).forEach(function(key) {
419 node.attr(key, from.attrs[key]);
426 if(from.nodeType === Node.TEXT_NODE) {
427 Factory = this.TextNodeFactory;
428 } else if(from.nodeType === Node.ELEMENT_NODE) {
429 Factory = this.ElementNodeFactory;
431 return new Factory(from, this);
434 loadXML: function(xml, options) {
435 options = options || {};
436 defineDocumentProperties(this, $(parseXML(xml)));
437 if(!options.silent) {
438 this.trigger('contentSet');
443 return this.root.toXML();
446 containsNode: function(node) {
447 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
450 wrapNodes: function(params) {
451 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
452 throw new Error('Wrapping non-sibling nodes not supported.');
455 var parent = params.element1.parent(),
456 parentContents = parent.contents(),
457 wrapper = this.createDocumentNode({
458 tagName: params._with.tagName,
459 attrs: params._with.attrs}),
460 idx1 = parent.indexOf(params.element1),
461 idx2 = parent.indexOf(params.element2);
469 var insertingMethod, insertingTarget;
471 insertingMethod = 'prepend';
472 insertingTarget = parent;
474 insertingMethod = 'after';
475 insertingTarget = parentContents[idx1-1];
478 for(var i = idx1; i <= idx2; i++) {
479 wrapper.append(parentContents[i].detach());
482 insertingTarget[insertingMethod](wrapper);
486 getSiblingParents: function(params) {
487 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
488 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
489 noSiblingParents = null;
491 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
492 return noSiblingParents;
496 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
497 if(parents1[i].sameNode(parents2[i])) {
502 return {node1: parents1[i], node2: parents2[i]};
505 _wrapText: function(params) {
506 params = _.extend({textNodeIdx: 0}, params);
507 if(typeof params.textNodeIdx === 'number') {
508 params.textNodeIdx = [params.textNodeIdx];
511 var contentsInside = params.inside.contents(),
512 idx1 = Math.min.apply(Math, params.textNodeIdx),
513 idx2 = Math.max.apply(Math, params.textNodeIdx),
514 textNode1 = contentsInside[idx1],
515 textNode2 = contentsInside[idx2],
516 sameNode = textNode1.sameNode(textNode2),
517 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
518 prefixInside = textNode1.getText().substr(params.offsetStart),
519 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
520 suffixOutside = textNode2.getText().substr(params.offsetEnd)
523 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
524 throw new Error('Wrapping text in non-sibling text nodes not supported.');
527 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
528 textNode1.after(wrapperElement);
531 if(prefixOutside.length > 0) {
532 wrapperElement.before({text:prefixOutside});
535 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
536 wrapperElement.append({text: core});
539 if(prefixInside.length > 0) {
540 wrapperElement.append({text: prefixInside});
542 for(var i = idx1 + 1; i < idx2; i++) {
543 wrapperElement.append(contentsInside[i]);
545 if(suffixInside.length > 0) {
546 wrapperElement.append({text: suffixInside});
549 if(suffixOutside.length > 0) {
550 wrapperElement.after({text: suffixOutside});
552 return wrapperElement;
555 trigger: function() {
556 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
557 Backbone.Events.trigger.apply(this, arguments);
561 var defineDocumentProperties = function(doc, $document) {
562 Object.defineProperty(doc, 'root', {get: function() {
563 return doc.createDocumentNode($document[0]);
564 }, configurable: true});
565 Object.defineProperty(doc, 'dom', {get: function() {
567 }, configurable: true});
571 documentFromXML: function(xml) {
572 return new Document(xml);
575 elementNodeFromXML: function(xml) {
576 return this.documentFromXML(xml).root;
580 DocumentNode: DocumentNode,
581 ElementNode: ElementNode