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);
30 var parent = this.parent();
32 this.triggerChangeEvent('nodeDetached', {parent: parent});
36 sameNode: function(otherNode) {
37 return otherNode && this.nativeNode === otherNode.nativeNode;
41 var parentNode = this.nativeNode.parentNode;
42 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
43 return this.document.createElementNode(parentNode);
48 after: function(node) {
49 var insertion = this.getNodeInsertion(node);
50 this._$.after(insertion.ofNode.nativeNode);
51 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
52 return insertion.ofNode;
55 before: function(node) {
56 var insertion = this.getNodeInsertion(node);
57 this._$.before(insertion.ofNode.nativeNode);
58 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
59 return insertion.ofNode;
62 wrapWith: function(node) {
63 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
72 triggerChangeEvent: function(type, metaData) {
73 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
74 this.document.trigger('change', event);
77 getNodeInsertion: function(node) {
79 if(node instanceof DocumentNode) {
80 insertion.ofNode = node;
81 insertion.insertsNew = !this.document.containsNode(node);
83 insertion.ofNode = this.document.createElementNode(node);
84 insertion.insertsNew = true;
89 getIndex: function() {
90 return this.parent().indexOf(this);
94 var ElementNode = function(nativeNode, document) {
95 DocumentNode.call(this, nativeNode, document);
97 ElementNode.prototype = Object.create(DocumentNode.prototype);
99 $.extend(ElementNode.prototype, {
100 nodeType: Node.ELEMENT_NODE,
102 setData: function(key, value) {
103 if(value !== undefined) {
104 this._$.data(key, value);
106 this._$.removeData(_.keys(this._$.data()));
111 getData: function(key) {
113 return this._$.data(key);
115 return this._$.data();
118 getTagName: function() {
119 return this.nativeNode.tagName.toLowerCase();
122 contents: function() {
124 document = this.document;
125 this._$.contents().each(function() {
126 if(this.nodeType === Node.ELEMENT_NODE) {
127 toret.push(document.createElementNode(this));
129 else if(this.nodeType === Node.TEXT_NODE) {
130 toret.push(document.createTextNode(this));
136 indexOf: function(node) {
137 return this._$.contents().index(node._$);
140 setTag: function(tagName) {
141 var node = this.document.createElementNode({tagName: tagName}),
142 oldTagName = this.getTagName(),
143 myContents = this._$.contents();
145 this.getAttrs().forEach(function(attribute) {
146 node.setAttr(attribute.name, attribute.value, true);
148 node.setData(this.getData());
150 if(this.sameNode(this.document.root)) {
151 defineDocumentProperties(this.document, node._$);
153 this._$.replaceWith(node._$);
154 this._setNativeNode(node._$[0]);
155 this._$.append(myContents);
156 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
159 getAttr: function(name) {
160 return this._$.attr(name);
163 setAttr: function(name, value, silent) {
164 var oldVal = this.getAttr(name);
165 this._$.attr(name, value);
167 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
171 getAttrs: function() {
173 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
174 toret.push(this.nativeNode.attributes[i]);
179 append: function(node) {
180 var insertion = this.getNodeInsertion(node);
181 this._$.append(insertion.ofNode.nativeNode);
182 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
183 return insertion.ofNode;
186 prepend: function(node) {
187 var insertion = this.getNodeInsertion(node);
188 this._$.prepend(insertion.ofNode.nativeNode);
189 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
190 return insertion.ofNode;
193 unwrapContent: function() {
194 var parent = this.parent();
199 var parentContents = parent.contents(),
200 myContents = this.contents(),
201 myIdx = parent.indexOf(this);
203 if(myContents.length === 0) {
204 return this.detach();
207 var moveLeftRange, moveRightRange, leftMerged;
209 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
210 parentContents[myIdx-1].appendText(myContents[0].getText());
211 myContents[0].detach();
212 moveLeftRange = true;
218 if(!(leftMerged && myContents.length === 1)) {
219 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
220 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
221 myContents[myContents.length-1].detach();
222 moveRightRange = true;
226 var childrenLength = this.contents().length;
227 this.contents().forEach(function(child) {
234 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
235 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
239 wrapText: function(params) {
240 return this.document._wrapText(_.extend({inside: this}, params));
244 var wrapper = $('<div>');
245 wrapper.append(this._getXMLDOMToDump());
246 return wrapper.html();
249 _getXMLDOMToDump: function() {
254 var TextNode = function(nativeNode, document) {
255 DocumentNode.call(this, nativeNode, document);
257 TextNode.prototype = Object.create(DocumentNode.prototype);
259 $.extend(TextNode.prototype, {
260 nodeType: Node.TEXT_NODE,
262 getText: function() {
263 return this.nativeNode.data;
266 setText: function(text) {
267 this.nativeNode.data = text;
268 this.triggerTextChangeEvent();
271 appendText: function(text) {
272 this.nativeNode.data = this.nativeNode.data + text;
273 this.triggerTextChangeEvent();
276 prependText: function(text) {
277 this.nativeNode.data = text + this.nativeNode.data;
278 this.triggerTextChangeEvent();
281 wrapWith: function(desc) {
282 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
283 return this.document._wrapText({
284 inside: this.parent(),
285 textNodeIdx: this.parent().indexOf(this),
286 offsetStart: Math.min(desc.start, desc.end),
287 offsetEnd: Math.max(desc.start, desc.end),
288 _with: {tagName: desc.tagName, attrs: desc.attrs}
291 return DocumentNode.prototype.wrapWith.call(this, desc);
295 triggerTextChangeEvent: function() {
296 var event = new events.ChangeEvent('nodeTextChange', {node: this});
297 this.document.trigger('change', event);
302 var parseXML = function(xml) {
306 var Document = function(xml) {
310 $.extend(Document.prototype, Backbone.Events, {
311 ElementNodeFactory: ElementNode,
312 TextNodeFactory: TextNode,
314 createElementNode: function(from) {
315 if(!(from instanceof HTMLElement)) {
317 from = document.createTextNode(from.text);
319 var node = $('<' + from.tagName + '>');
321 _.keys(from.attrs || {}).forEach(function(key) {
322 node.attr(key, from.attrs[key]);
329 if(from.nodeType === Node.TEXT_NODE) {
330 Factory = this.TextNodeFactory;
331 } else if(from.nodeType === Node.ELEMENT_NODE) {
332 Factory = this.ElementNodeFactory;
334 return new Factory(from, this);
337 createTextNode: function(nativeNode) {
338 return new this.TextNodeFactory(nativeNode, this);
341 loadXML: function(xml, options) {
342 options = options || {};
343 defineDocumentProperties(this, $(parseXML(xml)));
344 if(!options.silent) {
345 this.trigger('contentSet');
350 return this.root.toXML();
353 containsNode: function(node) {
354 return node._$.parents().index(this.root._$) !== -1;
357 wrapNodes: function(params) {
358 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
359 throw new Error('Wrapping non-sibling nodes not supported.');
362 var parent = params.element1.parent(),
363 parentContents = parent.contents(),
364 wrapper = this.createElementNode({
365 tagName: params._with.tagName,
366 attrs: params._with.attrs}),
367 idx1 = parent.indexOf(params.element1),
368 idx2 = parent.indexOf(params.element2);
376 var insertingMethod, insertingTarget;
378 insertingMethod = 'prepend';
379 insertingTarget = parent;
381 insertingMethod = 'after';
382 insertingTarget = parentContents[idx1-1];
385 for(var i = idx1; i <= idx2; i++) {
386 wrapper.append(parentContents[i].detach());
389 insertingTarget[insertingMethod](wrapper);
393 _wrapText: function(params) {
394 params = _.extend({textNodeIdx: 0}, params);
395 if(typeof params.textNodeIdx === 'number') {
396 params.textNodeIdx = [params.textNodeIdx];
399 var contentsInside = params.inside.contents(),
400 idx1 = Math.min.apply(Math, params.textNodeIdx),
401 idx2 = Math.max.apply(Math, params.textNodeIdx),
402 textNode1 = contentsInside[idx1],
403 textNode2 = contentsInside[idx2],
404 sameNode = textNode1.sameNode(textNode2),
405 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
406 prefixInside = textNode1.getText().substr(params.offsetStart),
407 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
408 suffixOutside = textNode2.getText().substr(params.offsetEnd)
411 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
412 throw new Error('Wrapping text in non-sibling text nodes not supported.');
415 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
416 textNode1.after(wrapperElement);
419 if(prefixOutside.length > 0) {
420 wrapperElement.before({text:prefixOutside});
423 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
424 wrapperElement.append({text: core});
427 if(prefixInside.length > 0) {
428 wrapperElement.append({text: prefixInside});
430 for(var i = idx1 + 1; i < idx2; i++) {
431 wrapperElement.append(contentsInside[i]);
433 if(suffixInside.length > 0) {
434 wrapperElement.append({text: suffixInside});
437 if(suffixOutside.length > 0) {
438 wrapperElement.after({text: suffixOutside});
440 return wrapperElement;
444 var defineDocumentProperties = function(doc, $document) {
445 Object.defineProperty(doc, 'root', {get: function() {
446 return doc.createElementNode($document[0]);
447 }, configurable: true});
448 Object.defineProperty(doc, 'dom', {get: function() {
450 }, configurable: true});
454 documentFromXML: function(xml) {
455 return new Document(parseXML(xml));
458 elementNodeFromXML: function(xml) {
459 return this.documentFromXML(xml).root;
463 DocumentNode: DocumentNode,
464 ElementNode: ElementNode