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);
104 * Removes parent of a node if node has no siblings.
110 var parent = this.parent(),
112 if(parent.contents().length === 1) {
113 grandParent = parent.parent();
114 parent.unwrapContent();
119 triggerChangeEvent: function(type, metaData) {
120 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
121 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
122 this.document.trigger('change', event);
126 getNodeInsertion: function(node) {
128 if(node instanceof DocumentNode) {
129 insertion.ofNode = node;
130 insertion.insertsNew = !this.document.containsNode(node);
132 insertion.ofNode = this.document.createElementNode(node);
133 insertion.insertsNew = true;
138 getIndex: function() {
139 return this.parent().indexOf(this);
143 var ElementNode = function(nativeNode, document) {
144 DocumentNode.call(this, nativeNode, document);
146 ElementNode.prototype = Object.create(DocumentNode.prototype);
148 $.extend(ElementNode.prototype, {
149 nodeType: Node.ELEMENT_NODE,
152 var prev = this.prev(),
155 if(prev && prev.nodeType === Node.TEXT_NODE && next && next.nodeType === Node.TEXT_NODE) {
156 prev.appendText(next.getText());
160 return DocumentNode.prototype.detach.call(this);
163 setData: function(key, value) {
164 if(value !== undefined) {
165 this._$.data(key, value);
167 this._$.removeData(_.keys(this._$.data()));
172 getData: function(key) {
174 return this._$.data(key);
176 return this._$.data();
179 getTagName: function() {
180 return this.nativeNode.tagName.toLowerCase();
183 contents: function() {
185 document = this.document;
186 this._$.contents().each(function() {
187 if(this.nodeType === Node.ELEMENT_NODE) {
188 toret.push(document.createElementNode(this));
190 else if(this.nodeType === Node.TEXT_NODE) {
191 toret.push(document.createTextNode(this));
197 indexOf: function(node) {
198 return this._$.contents().index(node._$);
201 setTag: function(tagName) {
202 var node = this.document.createElementNode({tagName: tagName}),
203 oldTagName = this.getTagName(),
204 myContents = this._$.contents();
206 this.getAttrs().forEach(function(attribute) {
207 node.setAttr(attribute.name, attribute.value, true);
209 node.setData(this.getData());
211 if(this.sameNode(this.document.root)) {
212 defineDocumentProperties(this.document, node._$);
214 this._$.replaceWith(node._$);
215 this._setNativeNode(node._$[0]);
216 this._$.append(myContents);
217 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
220 getAttr: function(name) {
221 return this._$.attr(name);
224 setAttr: function(name, value, silent) {
225 var oldVal = this.getAttr(name);
226 this._$.attr(name, value);
228 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
232 getAttrs: function() {
234 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
235 toret.push(this.nativeNode.attributes[i]);
240 append: INSERTION(function(nativeNode) {
241 this._$.append(nativeNode);
244 prepend: INSERTION(function(nativeNode) {
245 this._$.prepend(nativeNode);
248 unwrapContent: function() {
249 var parent = this.parent();
254 var parentContents = parent.contents(),
255 myContents = this.contents(),
256 myIdx = parent.indexOf(this);
258 if(myContents.length === 0) {
259 return this.detach();
262 var moveLeftRange, moveRightRange, leftMerged;
264 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
265 parentContents[myIdx-1].appendText(myContents[0].getText());
266 myContents[0].detach();
267 moveLeftRange = true;
273 if(!(leftMerged && myContents.length === 1)) {
274 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
275 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
276 myContents[myContents.length-1].detach();
277 moveRightRange = true;
281 var childrenLength = this.contents().length;
282 this.contents().forEach(function(child) {
289 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
290 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
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