6 ], function($, _, Backbone, events) {
11 var TEXT_NODE = Node.TEXT_NODE;
14 var DocumentNode = function(nativeNode, document) {
16 throw new Error('undefined document for a node');
18 this.document = document;
19 this._setNativeNode(nativeNode);
23 $.extend(DocumentNode.prototype, {
24 _setNativeNode: function(nativeNode) {
25 this.nativeNode = nativeNode;
26 this._$ = $(nativeNode);
34 sameNode: function(otherNode) {
35 return otherNode && this.nativeNode === otherNode.nativeNode;
39 return this.nativeNode.parentNode ? this.document.createElementNode(this.nativeNode.parentNode) : null;
42 after: function(node) {
43 var insertion = this.getNodeInsertion(node);
44 this._$.after(insertion.ofNode.nativeNode);
45 if(insertion.insertsNew) {
46 this.triggerChangeEvent('nodeAdded', {node: insertion.ofNode});
48 return insertion.ofNode;
51 before: function(node) {
52 var insertion = this.getNodeInsertion(node);
53 this._$.before(insertion.ofNode.nativeNode);
54 if(insertion.insertsNew) {
55 this.triggerChangeEvent('nodeAdded', {node: insertion.ofNode});
57 return insertion.ofNode;
60 wrapWith: function(node) {
61 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
70 triggerChangeEvent: function(type, metaData) {
71 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
72 this.document.trigger('change', event);
75 getNodeInsertion: function(node) {
77 if(node instanceof DocumentNode) {
78 insertion.ofNode = node;
79 insertion.insertsNew = !this.document.containsNode(node);
81 insertion.ofNode = this.document.createElementNode(node);
82 insertion.insertsNew = true;
88 var ElementNode = function(nativeNode, document) {
89 DocumentNode.call(this, nativeNode, document);
91 ElementNode.prototype = Object.create(DocumentNode.prototype);
93 $.extend(ElementNode.prototype, {
94 nodeType: Node.ELEMENT_NODE,
96 setData: function(key, value) {
97 if(value !== undefined) {
98 this._$.data(key, value);
100 this._$.removeData(_.keys(this._$.data()));
105 getData: function(key) {
107 return this._$.data(key);
109 return this._$.data();
112 getTagName: function() {
113 return this.nativeNode.tagName.toLowerCase();
116 contents: function() {
118 document = this.document;
119 this._$.contents().each(function() {
120 if(this.nodeType === Node.ELEMENT_NODE) {
121 toret.push(document.createElementNode(this));
123 else if(this.nodeType === Node.TEXT_NODE) {
124 toret.push(document.createTextNode(this));
130 indexOf: function(node) {
131 return this._$.contents().index(node._$);
134 setTag: function(tagName) {
135 var node = this.document.createElementNode({tagName: tagName}),
136 oldTagName = this.getTagName(),
137 myContents = this._$.contents();
139 this.getAttrs().forEach(function(attribute) {
140 node.setAttr(attribute.name, attribute.value, true);
142 node.setData(this.getData());
144 if(this.sameNode(this.document.root)) {
145 defineDocumentProperties(this.document, node._$);
147 this._$.replaceWith(node._$);
148 this._setNativeNode(node._$[0]);
149 this._$.append(myContents);
150 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
153 getAttr: function(name) {
154 return this._$.attr(name);
157 setAttr: function(name, value, silent) {
158 var oldVal = this.getAttr(name);
159 this._$.attr(name, value);
161 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
165 getAttrs: function() {
167 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
168 toret.push(this.nativeNode.attributes[i]);
173 append: function(node) {
174 var insertion = this.getNodeInsertion(node);
175 this._$.append(insertion.ofNode.nativeNode);
176 if(insertion.insertsNew) {
177 this.triggerChangeEvent('nodeAdded', {node: insertion.ofNode});
179 return insertion.ofNode;
182 prepend: function(node) {
183 var insertion = this.getNodeInsertion(node);
184 this._$.prepend(insertion.ofNode.nativeNode);
185 if(insertion.insertsNew) {
186 this.triggerChangeEvent('nodeAdded', {node: insertion.ofNode});
188 return insertion.ofNode;
191 unwrapContent: function() {
192 var parent = this.parent();
197 var parentContents = parent.contents(),
198 myContents = this.contents(),
199 myIdx = parent.indexOf(this);
201 if(myContents.length === 0) {
202 return this.detach();
205 var moveLeftRange, moveRightRange, leftMerged;
207 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
208 parentContents[myIdx-1].appendText(myContents[0].getText());
209 myContents[0].detach();
210 moveLeftRange = true;
216 if(!(leftMerged && myContents.length === 1)) {
217 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
218 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
219 myContents[myContents.length-1].detach();
220 moveRightRange = true;
224 var childrenLength = this.contents().length;
225 this.contents().forEach(function(child) {
232 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
233 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
237 wrapText: function(params) {
238 return this.document._wrapText(_.extend({inside: this}, params));
242 var wrapper = $('<div>');
243 wrapper.append(this._getXMLDOMToDump());
244 return wrapper.html();
247 _getXMLDOMToDump: function() {
252 var TextNode = function(nativeNode, document) {
253 DocumentNode.call(this, nativeNode, document);
255 TextNode.prototype = Object.create(DocumentNode.prototype);
257 $.extend(TextNode.prototype, {
258 nodeType: Node.TEXT_NODE,
260 getText: function() {
261 return this.nativeNode.data;
264 setText: function(text) {
265 this.nativeNode.data = text;
266 this.triggerTextChangeEvent();
269 appendText: function(text) {
270 this.nativeNode.data = this.nativeNode.data + text;
271 this.triggerTextChangeEvent();
274 prependText: function(text) {
275 this.nativeNode.data = text + this.nativeNode.data;
276 this.triggerTextChangeEvent();
279 wrapWith: function(desc) {
280 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
281 return this.document._wrapText({
282 inside: this.parent(),
283 textNodeIdx: this.parent().indexOf(this),
284 offsetStart: Math.min(desc.start, desc.end),
285 offsetEnd: Math.max(desc.start, desc.end),
286 _with: {tag: desc.tagName, attrs: desc.attrs}
289 return DocumentNode.prototype.wrapWith.call(this, desc);
293 triggerTextChangeEvent: function() {
294 var event = new events.ChangeEvent('nodeTextChange', {node: this});
295 this.document.trigger('change', event);
300 var parseXML = function(xml) {
304 var Document = function(xml) {
308 $.extend(Document.prototype, Backbone.Events, {
309 ElementNodeFactory: ElementNode,
310 TextNodeFactory: TextNode,
312 createElementNode: function(from) {
313 if(!(from instanceof HTMLElement)) {
315 from = document.createTextNode(from.text);
317 var node = $('<' + from.tagName + '>');
319 _.keys(from.attrs || {}).forEach(function(key) {
320 node.attr(key, from.attrs[key]);
326 return new this.ElementNodeFactory(from, this);
329 createTextNode: function(nativeNode) {
330 return new this.TextNodeFactory(nativeNode, this);
333 loadXML: function(xml, options) {
334 options = options || {};
335 defineDocumentProperties(this, $(parseXML(xml)));
336 if(!options.silent) {
337 this.trigger('contentSet');
342 return this.root.toXML();
345 containsNode: function(node) {
346 return node._$.parents().index(this.root._$) !== -1;
349 wrapNodes: function(params) {
350 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
351 throw new Error('Wrapping non-sibling nodes not supported.');
354 var parent = params.element1.parent(),
355 parentContents = parent.contents(),
356 wrapper = this.createElementNode({
357 tagName: params._with.tagName,
358 attrs: params._with.attrs}),
359 idx1 = parent.indexOf(params.element1),
360 idx2 = parent.indexOf(params.element2);
368 var insertingMethod, insertingTarget;
370 insertingMethod = 'prepend';
371 insertingTarget = parent;
373 insertingMethod = 'after';
374 insertingTarget = parentContents[idx1-1];
377 for(var i = idx1; i <= idx2; i++) {
378 wrapper.append(parentContents[i].detach());
381 insertingTarget[insertingMethod](wrapper);
385 _wrapText: function(params) {
386 params = _.extend({textNodeIdx: 0}, params);
387 if(typeof params.textNodeIdx === 'number') {
388 params.textNodeIdx = [params.textNodeIdx];
391 var contentsInside = params.inside.contents(),
392 idx1 = Math.min.apply(Math, params.textNodeIdx),
393 idx2 = Math.max.apply(Math, params.textNodeIdx),
394 textNode1 = contentsInside[idx1],
395 textNode2 = contentsInside[idx2],
396 sameNode = textNode1.sameNode(textNode2),
397 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
398 prefixInside = textNode1.getText().substr(params.offsetStart),
399 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
400 suffixOutside = textNode2.getText().substr(params.offsetEnd)
403 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
404 throw new Error('Wrapping text in non-sibling text nodes not supported.');
407 var wrapperElement = this.createElementNode({tagName: params._with.tag, attrs: params._with.attrs});
408 textNode1.after(wrapperElement);
411 if(prefixOutside.length > 0) {
412 wrapperElement.before({text:prefixOutside});
415 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
416 wrapperElement.append({text: core});
419 if(prefixInside.length > 0) {
420 wrapperElement.append({text: prefixInside});
422 for(var i = idx1 + 1; i < idx2; i++) {
423 wrapperElement.append(contentsInside[i]);
425 if(suffixInside.length > 0) {
426 wrapperElement.append({text: suffixInside});
429 if(suffixOutside.length > 0) {
430 wrapperElement.after({text: suffixOutside});
432 return wrapperElement;
436 var defineDocumentProperties = function(doc, $document) {
437 Object.defineProperty(doc, 'root', {get: function() {
438 return doc.createElementNode($document[0]);
439 }, configurable: true});
440 Object.defineProperty(doc, 'dom', {get: function() {
442 }, configurable: true});
446 documentFromXML: function(xml) {
447 return new Document(parseXML(xml));
450 elementNodeFromXML: function(xml) {
451 return this.documentFromXML(xml).root;
455 DocumentNode: DocumentNode,
456 ElementNode: ElementNode