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 var parent = this.parent();
42 this.triggerChangeEvent('nodeDetached', {parent: parent});
46 sameNode: function(otherNode) {
47 return otherNode && this.nativeNode === otherNode.nativeNode;
51 var parentNode = this.nativeNode.parentNode;
52 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
53 return this.document.createElementNode(parentNode);
59 var parent = this.parent(),
60 parents = parent ? parent.parents() : [];
62 parents.unshift(parent);
67 after: INSERTION(function(nativeNode) {
68 return this._$.after(nativeNode);
71 before: INSERTION(function(nativeNode) {
72 return this._$.before(nativeNode);
75 wrapWith: function(node) {
76 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
85 triggerChangeEvent: function(type, metaData) {
86 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
87 this.document.trigger('change', event);
90 getNodeInsertion: function(node) {
92 if(node instanceof DocumentNode) {
93 insertion.ofNode = node;
94 insertion.insertsNew = !this.document.containsNode(node);
96 insertion.ofNode = this.document.createElementNode(node);
97 insertion.insertsNew = true;
102 getIndex: function() {
103 return this.parent().indexOf(this);
107 var ElementNode = function(nativeNode, document) {
108 DocumentNode.call(this, nativeNode, document);
110 ElementNode.prototype = Object.create(DocumentNode.prototype);
112 $.extend(ElementNode.prototype, {
113 nodeType: Node.ELEMENT_NODE,
115 setData: function(key, value) {
116 if(value !== undefined) {
117 this._$.data(key, value);
119 this._$.removeData(_.keys(this._$.data()));
124 getData: function(key) {
126 return this._$.data(key);
128 return this._$.data();
131 getTagName: function() {
132 return this.nativeNode.tagName.toLowerCase();
135 contents: function() {
137 document = this.document;
138 this._$.contents().each(function() {
139 if(this.nodeType === Node.ELEMENT_NODE) {
140 toret.push(document.createElementNode(this));
142 else if(this.nodeType === Node.TEXT_NODE) {
143 toret.push(document.createTextNode(this));
149 indexOf: function(node) {
150 return this._$.contents().index(node._$);
153 setTag: function(tagName) {
154 var node = this.document.createElementNode({tagName: tagName}),
155 oldTagName = this.getTagName(),
156 myContents = this._$.contents();
158 this.getAttrs().forEach(function(attribute) {
159 node.setAttr(attribute.name, attribute.value, true);
161 node.setData(this.getData());
163 if(this.sameNode(this.document.root)) {
164 defineDocumentProperties(this.document, node._$);
166 this._$.replaceWith(node._$);
167 this._setNativeNode(node._$[0]);
168 this._$.append(myContents);
169 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
172 getAttr: function(name) {
173 return this._$.attr(name);
176 setAttr: function(name, value, silent) {
177 var oldVal = this.getAttr(name);
178 this._$.attr(name, value);
180 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
184 getAttrs: function() {
186 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
187 toret.push(this.nativeNode.attributes[i]);
192 append: INSERTION(function(nativeNode) {
193 this._$.append(nativeNode);
196 prepend: INSERTION(function(nativeNode) {
197 this._$.prepend(nativeNode);
200 unwrapContent: function() {
201 var parent = this.parent();
206 var parentContents = parent.contents(),
207 myContents = this.contents(),
208 myIdx = parent.indexOf(this);
210 if(myContents.length === 0) {
211 return this.detach();
214 var moveLeftRange, moveRightRange, leftMerged;
216 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
217 parentContents[myIdx-1].appendText(myContents[0].getText());
218 myContents[0].detach();
219 moveLeftRange = true;
225 if(!(leftMerged && myContents.length === 1)) {
226 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
227 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
228 myContents[myContents.length-1].detach();
229 moveRightRange = true;
233 var childrenLength = this.contents().length;
234 this.contents().forEach(function(child) {
241 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
242 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
246 wrapText: function(params) {
247 return this.document._wrapText(_.extend({inside: this}, params));
251 var wrapper = $('<div>');
252 wrapper.append(this._getXMLDOMToDump());
253 return wrapper.html();
256 _getXMLDOMToDump: function() {
261 var TextNode = function(nativeNode, document) {
262 DocumentNode.call(this, nativeNode, document);
264 TextNode.prototype = Object.create(DocumentNode.prototype);
266 $.extend(TextNode.prototype, {
267 nodeType: Node.TEXT_NODE,
269 getText: function() {
270 return this.nativeNode.data;
273 setText: function(text) {
274 this.nativeNode.data = text;
275 this.triggerTextChangeEvent();
278 appendText: function(text) {
279 this.nativeNode.data = this.nativeNode.data + text;
280 this.triggerTextChangeEvent();
283 prependText: function(text) {
284 this.nativeNode.data = text + this.nativeNode.data;
285 this.triggerTextChangeEvent();
288 wrapWith: function(desc) {
289 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
290 return this.document._wrapText({
291 inside: this.parent(),
292 textNodeIdx: this.parent().indexOf(this),
293 offsetStart: Math.min(desc.start, desc.end),
294 offsetEnd: Math.max(desc.start, desc.end),
295 _with: {tagName: desc.tagName, attrs: desc.attrs}
298 return DocumentNode.prototype.wrapWith.call(this, desc);
302 triggerTextChangeEvent: function() {
303 var event = new events.ChangeEvent('nodeTextChange', {node: this});
304 this.document.trigger('change', event);
309 var parseXML = function(xml) {
313 var Document = function(xml) {
317 $.extend(Document.prototype, Backbone.Events, {
318 ElementNodeFactory: ElementNode,
319 TextNodeFactory: TextNode,
321 createElementNode: function(from) {
322 if(!(from instanceof HTMLElement)) {
324 from = document.createTextNode(from.text);
326 var node = $('<' + from.tagName + '>');
328 _.keys(from.attrs || {}).forEach(function(key) {
329 node.attr(key, from.attrs[key]);
336 if(from.nodeType === Node.TEXT_NODE) {
337 Factory = this.TextNodeFactory;
338 } else if(from.nodeType === Node.ELEMENT_NODE) {
339 Factory = this.ElementNodeFactory;
341 return new Factory(from, this);
344 createTextNode: function(nativeNode) {
345 return new this.TextNodeFactory(nativeNode, this);
348 loadXML: function(xml, options) {
349 options = options || {};
350 defineDocumentProperties(this, $(parseXML(xml)));
351 if(!options.silent) {
352 this.trigger('contentSet');
357 return this.root.toXML();
360 containsNode: function(node) {
361 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
364 wrapNodes: function(params) {
365 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
366 throw new Error('Wrapping non-sibling nodes not supported.');
369 var parent = params.element1.parent(),
370 parentContents = parent.contents(),
371 wrapper = this.createElementNode({
372 tagName: params._with.tagName,
373 attrs: params._with.attrs}),
374 idx1 = parent.indexOf(params.element1),
375 idx2 = parent.indexOf(params.element2);
383 var insertingMethod, insertingTarget;
385 insertingMethod = 'prepend';
386 insertingTarget = parent;
388 insertingMethod = 'after';
389 insertingTarget = parentContents[idx1-1];
392 for(var i = idx1; i <= idx2; i++) {
393 wrapper.append(parentContents[i].detach());
396 insertingTarget[insertingMethod](wrapper);
400 getSiblingParents: function(params) {
401 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
402 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
403 noSiblingParents = null;
405 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
406 return noSiblingParents;
410 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
411 if(parents1[i].sameNode(parents2[i])) {
416 return {node1: parents1[i], node2: parents2[i]};
419 _wrapText: function(params) {
420 params = _.extend({textNodeIdx: 0}, params);
421 if(typeof params.textNodeIdx === 'number') {
422 params.textNodeIdx = [params.textNodeIdx];
425 var contentsInside = params.inside.contents(),
426 idx1 = Math.min.apply(Math, params.textNodeIdx),
427 idx2 = Math.max.apply(Math, params.textNodeIdx),
428 textNode1 = contentsInside[idx1],
429 textNode2 = contentsInside[idx2],
430 sameNode = textNode1.sameNode(textNode2),
431 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
432 prefixInside = textNode1.getText().substr(params.offsetStart),
433 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
434 suffixOutside = textNode2.getText().substr(params.offsetEnd)
437 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
438 throw new Error('Wrapping text in non-sibling text nodes not supported.');
441 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
442 textNode1.after(wrapperElement);
445 if(prefixOutside.length > 0) {
446 wrapperElement.before({text:prefixOutside});
449 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
450 wrapperElement.append({text: core});
453 if(prefixInside.length > 0) {
454 wrapperElement.append({text: prefixInside});
456 for(var i = idx1 + 1; i < idx2; i++) {
457 wrapperElement.append(contentsInside[i]);
459 if(suffixInside.length > 0) {
460 wrapperElement.append({text: suffixInside});
463 if(suffixOutside.length > 0) {
464 wrapperElement.after({text: suffixOutside});
466 return wrapperElement;
469 trigger: function() {
470 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
471 Backbone.Events.trigger.apply(this, arguments);
475 var defineDocumentProperties = function(doc, $document) {
476 Object.defineProperty(doc, 'root', {get: function() {
477 return doc.createElementNode($document[0]);
478 }, configurable: true});
479 Object.defineProperty(doc, 'dom', {get: function() {
481 }, configurable: true});
485 documentFromXML: function(xml) {
486 return new Document(parseXML(xml));
489 elementNodeFromXML: function(xml) {
490 return this.documentFromXML(xml).root;
494 DocumentNode: DocumentNode,
495 ElementNode: ElementNode