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 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
46 return insertion.ofNode;
49 before: function(node) {
50 var insertion = this.getNodeInsertion(node);
51 this._$.before(insertion.ofNode.nativeNode);
52 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
53 return insertion.ofNode;
56 wrapWith: function(node) {
57 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
66 triggerChangeEvent: function(type, metaData) {
67 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
68 this.document.trigger('change', event);
71 getNodeInsertion: function(node) {
73 if(node instanceof DocumentNode) {
74 insertion.ofNode = node;
75 insertion.insertsNew = !this.document.containsNode(node);
77 insertion.ofNode = this.document.createElementNode(node);
78 insertion.insertsNew = true;
83 getIndex: function() {
84 return this.parent().indexOf(this);
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 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
177 return insertion.ofNode;
180 prepend: function(node) {
181 var insertion = this.getNodeInsertion(node);
182 this._$.prepend(insertion.ofNode.nativeNode);
183 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
184 return insertion.ofNode;
187 unwrapContent: function() {
188 var parent = this.parent();
193 var parentContents = parent.contents(),
194 myContents = this.contents(),
195 myIdx = parent.indexOf(this);
197 if(myContents.length === 0) {
198 return this.detach();
201 var moveLeftRange, moveRightRange, leftMerged;
203 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
204 parentContents[myIdx-1].appendText(myContents[0].getText());
205 myContents[0].detach();
206 moveLeftRange = true;
212 if(!(leftMerged && myContents.length === 1)) {
213 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
214 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
215 myContents[myContents.length-1].detach();
216 moveRightRange = true;
220 var childrenLength = this.contents().length;
221 this.contents().forEach(function(child) {
228 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
229 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
233 wrapText: function(params) {
234 return this.document._wrapText(_.extend({inside: this}, params));
238 var wrapper = $('<div>');
239 wrapper.append(this._getXMLDOMToDump());
240 return wrapper.html();
243 _getXMLDOMToDump: function() {
248 var TextNode = function(nativeNode, document) {
249 DocumentNode.call(this, nativeNode, document);
251 TextNode.prototype = Object.create(DocumentNode.prototype);
253 $.extend(TextNode.prototype, {
254 nodeType: Node.TEXT_NODE,
256 getText: function() {
257 return this.nativeNode.data;
260 setText: function(text) {
261 this.nativeNode.data = text;
262 this.triggerTextChangeEvent();
265 appendText: function(text) {
266 this.nativeNode.data = this.nativeNode.data + text;
267 this.triggerTextChangeEvent();
270 prependText: function(text) {
271 this.nativeNode.data = text + this.nativeNode.data;
272 this.triggerTextChangeEvent();
275 wrapWith: function(desc) {
276 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
277 return this.document._wrapText({
278 inside: this.parent(),
279 textNodeIdx: this.parent().indexOf(this),
280 offsetStart: Math.min(desc.start, desc.end),
281 offsetEnd: Math.max(desc.start, desc.end),
282 _with: {tagName: desc.tagName, attrs: desc.attrs}
285 return DocumentNode.prototype.wrapWith.call(this, desc);
289 triggerTextChangeEvent: function() {
290 var event = new events.ChangeEvent('nodeTextChange', {node: this});
291 this.document.trigger('change', event);
296 var parseXML = function(xml) {
300 var Document = function(xml) {
304 $.extend(Document.prototype, Backbone.Events, {
305 ElementNodeFactory: ElementNode,
306 TextNodeFactory: TextNode,
308 createElementNode: function(from) {
309 if(!(from instanceof HTMLElement)) {
311 from = document.createTextNode(from.text);
313 var node = $('<' + from.tagName + '>');
315 _.keys(from.attrs || {}).forEach(function(key) {
316 node.attr(key, from.attrs[key]);
322 return new this.ElementNodeFactory(from, this);
325 createTextNode: function(nativeNode) {
326 return new this.TextNodeFactory(nativeNode, this);
329 loadXML: function(xml, options) {
330 options = options || {};
331 defineDocumentProperties(this, $(parseXML(xml)));
332 if(!options.silent) {
333 this.trigger('contentSet');
338 return this.root.toXML();
341 containsNode: function(node) {
342 return node._$.parents().index(this.root._$) !== -1;
345 wrapNodes: function(params) {
346 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
347 throw new Error('Wrapping non-sibling nodes not supported.');
350 var parent = params.element1.parent(),
351 parentContents = parent.contents(),
352 wrapper = this.createElementNode({
353 tagName: params._with.tagName,
354 attrs: params._with.attrs}),
355 idx1 = parent.indexOf(params.element1),
356 idx2 = parent.indexOf(params.element2);
364 var insertingMethod, insertingTarget;
366 insertingMethod = 'prepend';
367 insertingTarget = parent;
369 insertingMethod = 'after';
370 insertingTarget = parentContents[idx1-1];
373 for(var i = idx1; i <= idx2; i++) {
374 wrapper.append(parentContents[i].detach());
377 insertingTarget[insertingMethod](wrapper);
381 _wrapText: function(params) {
382 params = _.extend({textNodeIdx: 0}, params);
383 if(typeof params.textNodeIdx === 'number') {
384 params.textNodeIdx = [params.textNodeIdx];
387 var contentsInside = params.inside.contents(),
388 idx1 = Math.min.apply(Math, params.textNodeIdx),
389 idx2 = Math.max.apply(Math, params.textNodeIdx),
390 textNode1 = contentsInside[idx1],
391 textNode2 = contentsInside[idx2],
392 sameNode = textNode1.sameNode(textNode2),
393 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
394 prefixInside = textNode1.getText().substr(params.offsetStart),
395 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
396 suffixOutside = textNode2.getText().substr(params.offsetEnd)
399 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
400 throw new Error('Wrapping text in non-sibling text nodes not supported.');
403 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
404 textNode1.after(wrapperElement);
407 if(prefixOutside.length > 0) {
408 wrapperElement.before({text:prefixOutside});
411 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
412 wrapperElement.append({text: core});
415 if(prefixInside.length > 0) {
416 wrapperElement.append({text: prefixInside});
418 for(var i = idx1 + 1; i < idx2; i++) {
419 wrapperElement.append(contentsInside[i]);
421 if(suffixInside.length > 0) {
422 wrapperElement.append({text: suffixInside});
425 if(suffixOutside.length > 0) {
426 wrapperElement.after({text: suffixOutside});
428 return wrapperElement;
432 var defineDocumentProperties = function(doc, $document) {
433 Object.defineProperty(doc, 'root', {get: function() {
434 return doc.createElementNode($document[0]);
435 }, configurable: true});
436 Object.defineProperty(doc, 'dom', {get: function() {
438 }, configurable: true});
442 documentFromXML: function(xml) {
443 return new Document(parseXML(xml));
446 elementNodeFromXML: function(xml) {
447 return this.documentFromXML(xml).root;
451 DocumentNode: DocumentNode,
452 ElementNode: ElementNode