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 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
103 triggerChangeEvent: function(type, metaData) {
104 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
105 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
106 this.document.trigger('change', event);
110 getNodeInsertion: function(node) {
112 if(node instanceof DocumentNode) {
113 insertion.ofNode = node;
114 insertion.insertsNew = !this.document.containsNode(node);
116 insertion.ofNode = this.document.createElementNode(node);
117 insertion.insertsNew = true;
122 getIndex: function() {
123 return this.parent().indexOf(this);
127 var ElementNode = function(nativeNode, document) {
128 DocumentNode.call(this, nativeNode, document);
130 ElementNode.prototype = Object.create(DocumentNode.prototype);
132 $.extend(ElementNode.prototype, {
133 nodeType: Node.ELEMENT_NODE,
136 var prev = this.prev(),
139 if(prev && prev.nodeType === Node.TEXT_NODE && next && next.nodeType === Node.TEXT_NODE) {
140 prev.appendText(next.getText());
144 return DocumentNode.prototype.detach.call(this);
147 setData: function(key, value) {
148 if(value !== undefined) {
149 this._$.data(key, value);
151 this._$.removeData(_.keys(this._$.data()));
156 getData: function(key) {
158 return this._$.data(key);
160 return this._$.data();
163 getTagName: function() {
164 return this.nativeNode.tagName.toLowerCase();
167 contents: function() {
169 document = this.document;
170 this._$.contents().each(function() {
171 if(this.nodeType === Node.ELEMENT_NODE) {
172 toret.push(document.createElementNode(this));
174 else if(this.nodeType === Node.TEXT_NODE) {
175 toret.push(document.createTextNode(this));
181 indexOf: function(node) {
182 return this._$.contents().index(node._$);
185 setTag: function(tagName) {
186 var node = this.document.createElementNode({tagName: tagName}),
187 oldTagName = this.getTagName(),
188 myContents = this._$.contents();
190 this.getAttrs().forEach(function(attribute) {
191 node.setAttr(attribute.name, attribute.value, true);
193 node.setData(this.getData());
195 if(this.sameNode(this.document.root)) {
196 defineDocumentProperties(this.document, node._$);
198 this._$.replaceWith(node._$);
199 this._setNativeNode(node._$[0]);
200 this._$.append(myContents);
201 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
204 getAttr: function(name) {
205 return this._$.attr(name);
208 setAttr: function(name, value, silent) {
209 var oldVal = this.getAttr(name);
210 this._$.attr(name, value);
212 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
216 getAttrs: function() {
218 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
219 toret.push(this.nativeNode.attributes[i]);
224 append: INSERTION(function(nativeNode) {
225 this._$.append(nativeNode);
228 prepend: INSERTION(function(nativeNode) {
229 this._$.prepend(nativeNode);
232 unwrapContent: function() {
233 var parent = this.parent();
238 var parentContents = parent.contents(),
239 myContents = this.contents(),
240 myIdx = parent.indexOf(this);
242 if(myContents.length === 0) {
243 return this.detach();
246 var moveLeftRange, moveRightRange, leftMerged;
248 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
249 parentContents[myIdx-1].appendText(myContents[0].getText());
250 myContents[0].detach();
251 moveLeftRange = true;
257 if(!(leftMerged && myContents.length === 1)) {
258 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
259 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
260 myContents[myContents.length-1].detach();
261 moveRightRange = true;
265 var childrenLength = this.contents().length;
266 this.contents().forEach(function(child) {
273 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
274 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
279 * Removes parent of a node if node has no siblings.
285 var parent = this.parent(),
287 if(parent.contents().length === 1) {
288 grandParent = parent.parent();
289 parent.unwrapContent();
294 wrapText: function(params) {
295 return this.document._wrapText(_.extend({inside: this}, params));
299 var wrapper = $('<div>');
300 wrapper.append(this._getXMLDOMToDump());
301 return wrapper.html();
304 _getXMLDOMToDump: function() {
309 var TextNode = function(nativeNode, document) {
310 DocumentNode.call(this, nativeNode, document);
312 TextNode.prototype = Object.create(DocumentNode.prototype);
314 $.extend(TextNode.prototype, {
315 nodeType: Node.TEXT_NODE,
317 getText: function() {
318 return this.nativeNode.data;
321 setText: function(text) {
322 this.nativeNode.data = text;
323 this.triggerTextChangeEvent();
326 appendText: function(text) {
327 this.nativeNode.data = this.nativeNode.data + text;
328 this.triggerTextChangeEvent();
331 prependText: function(text) {
332 this.nativeNode.data = text + this.nativeNode.data;
333 this.triggerTextChangeEvent();
336 wrapWith: function(desc) {
337 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
338 return this.document._wrapText({
339 inside: this.parent(),
340 textNodeIdx: this.parent().indexOf(this),
341 offsetStart: Math.min(desc.start, desc.end),
342 offsetEnd: Math.max(desc.start, desc.end),
343 _with: {tagName: desc.tagName, attrs: desc.attrs}
346 return DocumentNode.prototype.wrapWith.call(this, desc);
350 triggerTextChangeEvent: function() {
351 var event = new events.ChangeEvent('nodeTextChange', {node: this});
352 this.document.trigger('change', event);
357 var parseXML = function(xml) {
361 var Document = function(xml) {
365 $.extend(Document.prototype, Backbone.Events, {
366 ElementNodeFactory: ElementNode,
367 TextNodeFactory: TextNode,
369 createElementNode: function(from) {
370 if(!(from instanceof HTMLElement)) {
372 from = document.createTextNode(from.text);
374 var node = $('<' + from.tagName + '>');
376 _.keys(from.attrs || {}).forEach(function(key) {
377 node.attr(key, from.attrs[key]);
384 if(from.nodeType === Node.TEXT_NODE) {
385 Factory = this.TextNodeFactory;
386 } else if(from.nodeType === Node.ELEMENT_NODE) {
387 Factory = this.ElementNodeFactory;
389 return new Factory(from, this);
392 createTextNode: function(nativeNode) {
393 return new this.TextNodeFactory(nativeNode, this);
396 loadXML: function(xml, options) {
397 options = options || {};
398 defineDocumentProperties(this, $(parseXML(xml)));
399 if(!options.silent) {
400 this.trigger('contentSet');
405 return this.root.toXML();
408 containsNode: function(node) {
409 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
412 wrapNodes: function(params) {
413 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
414 throw new Error('Wrapping non-sibling nodes not supported.');
417 var parent = params.element1.parent(),
418 parentContents = parent.contents(),
419 wrapper = this.createElementNode({
420 tagName: params._with.tagName,
421 attrs: params._with.attrs}),
422 idx1 = parent.indexOf(params.element1),
423 idx2 = parent.indexOf(params.element2);
431 var insertingMethod, insertingTarget;
433 insertingMethod = 'prepend';
434 insertingTarget = parent;
436 insertingMethod = 'after';
437 insertingTarget = parentContents[idx1-1];
440 for(var i = idx1; i <= idx2; i++) {
441 wrapper.append(parentContents[i].detach());
444 insertingTarget[insertingMethod](wrapper);
448 getSiblingParents: function(params) {
449 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
450 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
451 noSiblingParents = null;
453 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
454 return noSiblingParents;
458 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
459 if(parents1[i].sameNode(parents2[i])) {
464 return {node1: parents1[i], node2: parents2[i]};
467 _wrapText: function(params) {
468 params = _.extend({textNodeIdx: 0}, params);
469 if(typeof params.textNodeIdx === 'number') {
470 params.textNodeIdx = [params.textNodeIdx];
473 var contentsInside = params.inside.contents(),
474 idx1 = Math.min.apply(Math, params.textNodeIdx),
475 idx2 = Math.max.apply(Math, params.textNodeIdx),
476 textNode1 = contentsInside[idx1],
477 textNode2 = contentsInside[idx2],
478 sameNode = textNode1.sameNode(textNode2),
479 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
480 prefixInside = textNode1.getText().substr(params.offsetStart),
481 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
482 suffixOutside = textNode2.getText().substr(params.offsetEnd)
485 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
486 throw new Error('Wrapping text in non-sibling text nodes not supported.');
489 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
490 textNode1.after(wrapperElement);
493 if(prefixOutside.length > 0) {
494 wrapperElement.before({text:prefixOutside});
497 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
498 wrapperElement.append({text: core});
501 if(prefixInside.length > 0) {
502 wrapperElement.append({text: prefixInside});
504 for(var i = idx1 + 1; i < idx2; i++) {
505 wrapperElement.append(contentsInside[i]);
507 if(suffixInside.length > 0) {
508 wrapperElement.append({text: suffixInside});
511 if(suffixOutside.length > 0) {
512 wrapperElement.after({text: suffixOutside});
514 return wrapperElement;
517 trigger: function() {
518 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
519 Backbone.Events.trigger.apply(this, arguments);
523 var defineDocumentProperties = function(doc, $document) {
524 Object.defineProperty(doc, 'root', {get: function() {
525 return doc.createElementNode($document[0]);
526 }, configurable: true});
527 Object.defineProperty(doc, 'dom', {get: function() {
529 }, configurable: true});
533 documentFromXML: function(xml) {
534 return new Document(parseXML(xml));
537 elementNodeFromXML: function(xml) {
538 return this.documentFromXML(xml).root;
542 DocumentNode: DocumentNode,
543 ElementNode: ElementNode