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 return this.nativeNode.parentNode ? this.document.createElementNode(this.nativeNode.parentNode) : null;
44 after: function(node) {
45 var insertion = this.getNodeInsertion(node);
46 this._$.after(insertion.ofNode.nativeNode);
47 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
48 return insertion.ofNode;
51 before: function(node) {
52 var insertion = this.getNodeInsertion(node);
53 this._$.before(insertion.ofNode.nativeNode);
54 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
55 return insertion.ofNode;
58 wrapWith: function(node) {
59 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
68 triggerChangeEvent: function(type, metaData) {
69 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
70 this.document.trigger('change', event);
73 getNodeInsertion: function(node) {
75 if(node instanceof DocumentNode) {
76 insertion.ofNode = node;
77 insertion.insertsNew = !this.document.containsNode(node);
79 insertion.ofNode = this.document.createElementNode(node);
80 insertion.insertsNew = true;
85 getIndex: function() {
86 return this.parent().indexOf(this);
90 var ElementNode = function(nativeNode, document) {
91 DocumentNode.call(this, nativeNode, document);
93 ElementNode.prototype = Object.create(DocumentNode.prototype);
95 $.extend(ElementNode.prototype, {
96 nodeType: Node.ELEMENT_NODE,
98 setData: function(key, value) {
99 if(value !== undefined) {
100 this._$.data(key, value);
102 this._$.removeData(_.keys(this._$.data()));
107 getData: function(key) {
109 return this._$.data(key);
111 return this._$.data();
114 getTagName: function() {
115 return this.nativeNode.tagName.toLowerCase();
118 contents: function() {
120 document = this.document;
121 this._$.contents().each(function() {
122 if(this.nodeType === Node.ELEMENT_NODE) {
123 toret.push(document.createElementNode(this));
125 else if(this.nodeType === Node.TEXT_NODE) {
126 toret.push(document.createTextNode(this));
132 indexOf: function(node) {
133 return this._$.contents().index(node._$);
136 setTag: function(tagName) {
137 var node = this.document.createElementNode({tagName: tagName}),
138 oldTagName = this.getTagName(),
139 myContents = this._$.contents();
141 this.getAttrs().forEach(function(attribute) {
142 node.setAttr(attribute.name, attribute.value, true);
144 node.setData(this.getData());
146 if(this.sameNode(this.document.root)) {
147 defineDocumentProperties(this.document, node._$);
149 this._$.replaceWith(node._$);
150 this._setNativeNode(node._$[0]);
151 this._$.append(myContents);
152 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
155 getAttr: function(name) {
156 return this._$.attr(name);
159 setAttr: function(name, value, silent) {
160 var oldVal = this.getAttr(name);
161 this._$.attr(name, value);
163 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
167 getAttrs: function() {
169 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
170 toret.push(this.nativeNode.attributes[i]);
175 append: function(node) {
176 var insertion = this.getNodeInsertion(node);
177 this._$.append(insertion.ofNode.nativeNode);
178 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
179 return insertion.ofNode;
182 prepend: function(node) {
183 var insertion = this.getNodeInsertion(node);
184 this._$.prepend(insertion.ofNode.nativeNode);
185 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
186 return insertion.ofNode;
189 unwrapContent: function() {
190 var parent = this.parent();
195 var parentContents = parent.contents(),
196 myContents = this.contents(),
197 myIdx = parent.indexOf(this);
199 if(myContents.length === 0) {
200 return this.detach();
203 var moveLeftRange, moveRightRange, leftMerged;
205 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
206 parentContents[myIdx-1].appendText(myContents[0].getText());
207 myContents[0].detach();
208 moveLeftRange = true;
214 if(!(leftMerged && myContents.length === 1)) {
215 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
216 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
217 myContents[myContents.length-1].detach();
218 moveRightRange = true;
222 var childrenLength = this.contents().length;
223 this.contents().forEach(function(child) {
230 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
231 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
235 wrapText: function(params) {
236 return this.document._wrapText(_.extend({inside: this}, params));
240 var wrapper = $('<div>');
241 wrapper.append(this._getXMLDOMToDump());
242 return wrapper.html();
245 _getXMLDOMToDump: function() {
250 var TextNode = function(nativeNode, document) {
251 DocumentNode.call(this, nativeNode, document);
253 TextNode.prototype = Object.create(DocumentNode.prototype);
255 $.extend(TextNode.prototype, {
256 nodeType: Node.TEXT_NODE,
258 getText: function() {
259 return this.nativeNode.data;
262 setText: function(text) {
263 this.nativeNode.data = text;
264 this.triggerTextChangeEvent();
267 appendText: function(text) {
268 this.nativeNode.data = this.nativeNode.data + text;
269 this.triggerTextChangeEvent();
272 prependText: function(text) {
273 this.nativeNode.data = text + this.nativeNode.data;
274 this.triggerTextChangeEvent();
277 wrapWith: function(desc) {
278 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
279 return this.document._wrapText({
280 inside: this.parent(),
281 textNodeIdx: this.parent().indexOf(this),
282 offsetStart: Math.min(desc.start, desc.end),
283 offsetEnd: Math.max(desc.start, desc.end),
284 _with: {tagName: desc.tagName, attrs: desc.attrs}
287 return DocumentNode.prototype.wrapWith.call(this, desc);
291 triggerTextChangeEvent: function() {
292 var event = new events.ChangeEvent('nodeTextChange', {node: this});
293 this.document.trigger('change', event);
298 var parseXML = function(xml) {
302 var Document = function(xml) {
306 $.extend(Document.prototype, Backbone.Events, {
307 ElementNodeFactory: ElementNode,
308 TextNodeFactory: TextNode,
310 createElementNode: function(from) {
311 if(!(from instanceof HTMLElement)) {
313 from = document.createTextNode(from.text);
315 var node = $('<' + from.tagName + '>');
317 _.keys(from.attrs || {}).forEach(function(key) {
318 node.attr(key, from.attrs[key]);
325 if(from.nodeType === Node.TEXT_NODE) {
326 Factory = this.TextNodeFactory;
327 } else if(from.nodeType === Node.ELEMENT_NODE) {
328 Factory = this.ElementNodeFactory;
330 return new Factory(from, this);
333 createTextNode: function(nativeNode) {
334 return new this.TextNodeFactory(nativeNode, this);
337 loadXML: function(xml, options) {
338 options = options || {};
339 defineDocumentProperties(this, $(parseXML(xml)));
340 if(!options.silent) {
341 this.trigger('contentSet');
346 return this.root.toXML();
349 containsNode: function(node) {
350 return node._$.parents().index(this.root._$) !== -1;
353 wrapNodes: function(params) {
354 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
355 throw new Error('Wrapping non-sibling nodes not supported.');
358 var parent = params.element1.parent(),
359 parentContents = parent.contents(),
360 wrapper = this.createElementNode({
361 tagName: params._with.tagName,
362 attrs: params._with.attrs}),
363 idx1 = parent.indexOf(params.element1),
364 idx2 = parent.indexOf(params.element2);
372 var insertingMethod, insertingTarget;
374 insertingMethod = 'prepend';
375 insertingTarget = parent;
377 insertingMethod = 'after';
378 insertingTarget = parentContents[idx1-1];
381 for(var i = idx1; i <= idx2; i++) {
382 wrapper.append(parentContents[i].detach());
385 insertingTarget[insertingMethod](wrapper);
389 _wrapText: function(params) {
390 params = _.extend({textNodeIdx: 0}, params);
391 if(typeof params.textNodeIdx === 'number') {
392 params.textNodeIdx = [params.textNodeIdx];
395 var contentsInside = params.inside.contents(),
396 idx1 = Math.min.apply(Math, params.textNodeIdx),
397 idx2 = Math.max.apply(Math, params.textNodeIdx),
398 textNode1 = contentsInside[idx1],
399 textNode2 = contentsInside[idx2],
400 sameNode = textNode1.sameNode(textNode2),
401 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
402 prefixInside = textNode1.getText().substr(params.offsetStart),
403 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
404 suffixOutside = textNode2.getText().substr(params.offsetEnd)
407 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
408 throw new Error('Wrapping text in non-sibling text nodes not supported.');
411 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
412 textNode1.after(wrapperElement);
415 if(prefixOutside.length > 0) {
416 wrapperElement.before({text:prefixOutside});
419 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
420 wrapperElement.append({text: core});
423 if(prefixInside.length > 0) {
424 wrapperElement.append({text: prefixInside});
426 for(var i = idx1 + 1; i < idx2; i++) {
427 wrapperElement.append(contentsInside[i]);
429 if(suffixInside.length > 0) {
430 wrapperElement.append({text: suffixInside});
433 if(suffixOutside.length > 0) {
434 wrapperElement.after({text: suffixOutside});
436 return wrapperElement;
440 var defineDocumentProperties = function(doc, $document) {
441 Object.defineProperty(doc, 'root', {get: function() {
442 return doc.createElementNode($document[0]);
443 }, configurable: true});
444 Object.defineProperty(doc, 'dom', {get: function() {
446 }, configurable: true});
450 documentFromXML: function(xml) {
451 return new Document(parseXML(xml));
454 elementNodeFromXML: function(xml) {
455 return this.documentFromXML(xml).root;
459 DocumentNode: DocumentNode,
460 ElementNode: ElementNode