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);
49 var parent = this.parent(),
50 parents = parent ? parent.parents() : [];
52 parents.unshift(parent);
57 after: function(node) {
58 var insertion = this.getNodeInsertion(node);
59 this._$.after(insertion.ofNode.nativeNode);
60 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
61 return insertion.ofNode;
64 before: function(node) {
65 var insertion = this.getNodeInsertion(node);
66 this._$.before(insertion.ofNode.nativeNode);
67 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
68 return insertion.ofNode;
71 wrapWith: function(node) {
72 node = node instanceof ElementNode ? node : this.document.createElementNode(node);
81 triggerChangeEvent: function(type, metaData) {
82 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
83 this.document.trigger('change', event);
86 getNodeInsertion: function(node) {
88 if(node instanceof DocumentNode) {
89 insertion.ofNode = node;
90 insertion.insertsNew = !this.document.containsNode(node);
92 insertion.ofNode = this.document.createElementNode(node);
93 insertion.insertsNew = true;
98 getIndex: function() {
99 return this.parent().indexOf(this);
103 var ElementNode = function(nativeNode, document) {
104 DocumentNode.call(this, nativeNode, document);
106 ElementNode.prototype = Object.create(DocumentNode.prototype);
108 $.extend(ElementNode.prototype, {
109 nodeType: Node.ELEMENT_NODE,
111 setData: function(key, value) {
112 if(value !== undefined) {
113 this._$.data(key, value);
115 this._$.removeData(_.keys(this._$.data()));
120 getData: function(key) {
122 return this._$.data(key);
124 return this._$.data();
127 getTagName: function() {
128 return this.nativeNode.tagName.toLowerCase();
131 contents: function() {
133 document = this.document;
134 this._$.contents().each(function() {
135 if(this.nodeType === Node.ELEMENT_NODE) {
136 toret.push(document.createElementNode(this));
138 else if(this.nodeType === Node.TEXT_NODE) {
139 toret.push(document.createTextNode(this));
145 indexOf: function(node) {
146 return this._$.contents().index(node._$);
149 setTag: function(tagName) {
150 var node = this.document.createElementNode({tagName: tagName}),
151 oldTagName = this.getTagName(),
152 myContents = this._$.contents();
154 this.getAttrs().forEach(function(attribute) {
155 node.setAttr(attribute.name, attribute.value, true);
157 node.setData(this.getData());
159 if(this.sameNode(this.document.root)) {
160 defineDocumentProperties(this.document, node._$);
162 this._$.replaceWith(node._$);
163 this._setNativeNode(node._$[0]);
164 this._$.append(myContents);
165 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
168 getAttr: function(name) {
169 return this._$.attr(name);
172 setAttr: function(name, value, silent) {
173 var oldVal = this.getAttr(name);
174 this._$.attr(name, value);
176 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
180 getAttrs: function() {
182 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
183 toret.push(this.nativeNode.attributes[i]);
188 append: function(node) {
189 var insertion = this.getNodeInsertion(node);
190 this._$.append(insertion.ofNode.nativeNode);
191 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
192 return insertion.ofNode;
195 prepend: function(node) {
196 var insertion = this.getNodeInsertion(node);
197 this._$.prepend(insertion.ofNode.nativeNode);
198 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
199 return insertion.ofNode;
202 unwrapContent: function() {
203 var parent = this.parent();
208 var parentContents = parent.contents(),
209 myContents = this.contents(),
210 myIdx = parent.indexOf(this);
212 if(myContents.length === 0) {
213 return this.detach();
216 var moveLeftRange, moveRightRange, leftMerged;
218 if(myIdx > 0 && (parentContents[myIdx-1].nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
219 parentContents[myIdx-1].appendText(myContents[0].getText());
220 myContents[0].detach();
221 moveLeftRange = true;
227 if(!(leftMerged && myContents.length === 1)) {
228 if(myIdx < parentContents.length - 1 && (parentContents[myIdx+1].nodeType === TEXT_NODE) && (myContents[myContents.length-1].nodeType === TEXT_NODE)) {
229 parentContents[myIdx+1].prependText(myContents[myContents.length-1].getText());
230 myContents[myContents.length-1].detach();
231 moveRightRange = true;
235 var childrenLength = this.contents().length;
236 this.contents().forEach(function(child) {
243 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
244 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
248 wrapText: function(params) {
249 return this.document._wrapText(_.extend({inside: this}, params));
253 var wrapper = $('<div>');
254 wrapper.append(this._getXMLDOMToDump());
255 return wrapper.html();
258 _getXMLDOMToDump: function() {
263 var TextNode = function(nativeNode, document) {
264 DocumentNode.call(this, nativeNode, document);
266 TextNode.prototype = Object.create(DocumentNode.prototype);
268 $.extend(TextNode.prototype, {
269 nodeType: Node.TEXT_NODE,
271 getText: function() {
272 return this.nativeNode.data;
275 setText: function(text) {
276 this.nativeNode.data = text;
277 this.triggerTextChangeEvent();
280 appendText: function(text) {
281 this.nativeNode.data = this.nativeNode.data + text;
282 this.triggerTextChangeEvent();
285 prependText: function(text) {
286 this.nativeNode.data = text + this.nativeNode.data;
287 this.triggerTextChangeEvent();
290 wrapWith: function(desc) {
291 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
292 return this.document._wrapText({
293 inside: this.parent(),
294 textNodeIdx: this.parent().indexOf(this),
295 offsetStart: Math.min(desc.start, desc.end),
296 offsetEnd: Math.max(desc.start, desc.end),
297 _with: {tagName: desc.tagName, attrs: desc.attrs}
300 return DocumentNode.prototype.wrapWith.call(this, desc);
304 triggerTextChangeEvent: function() {
305 var event = new events.ChangeEvent('nodeTextChange', {node: this});
306 this.document.trigger('change', event);
311 var parseXML = function(xml) {
315 var Document = function(xml) {
319 $.extend(Document.prototype, Backbone.Events, {
320 ElementNodeFactory: ElementNode,
321 TextNodeFactory: TextNode,
323 createElementNode: function(from) {
324 if(!(from instanceof HTMLElement)) {
326 from = document.createTextNode(from.text);
328 var node = $('<' + from.tagName + '>');
330 _.keys(from.attrs || {}).forEach(function(key) {
331 node.attr(key, from.attrs[key]);
338 if(from.nodeType === Node.TEXT_NODE) {
339 Factory = this.TextNodeFactory;
340 } else if(from.nodeType === Node.ELEMENT_NODE) {
341 Factory = this.ElementNodeFactory;
343 return new Factory(from, this);
346 createTextNode: function(nativeNode) {
347 return new this.TextNodeFactory(nativeNode, this);
350 loadXML: function(xml, options) {
351 options = options || {};
352 defineDocumentProperties(this, $(parseXML(xml)));
353 if(!options.silent) {
354 this.trigger('contentSet');
359 return this.root.toXML();
362 containsNode: function(node) {
363 return node._$.parents().index(this.root._$) !== -1;
366 wrapNodes: function(params) {
367 if(!(params.element1.parent().sameNode(params.element2.parent()))) {
368 throw new Error('Wrapping non-sibling nodes not supported.');
371 var parent = params.element1.parent(),
372 parentContents = parent.contents(),
373 wrapper = this.createElementNode({
374 tagName: params._with.tagName,
375 attrs: params._with.attrs}),
376 idx1 = parent.indexOf(params.element1),
377 idx2 = parent.indexOf(params.element2);
385 var insertingMethod, insertingTarget;
387 insertingMethod = 'prepend';
388 insertingTarget = parent;
390 insertingMethod = 'after';
391 insertingTarget = parentContents[idx1-1];
394 for(var i = idx1; i <= idx2; i++) {
395 wrapper.append(parentContents[i].detach());
398 insertingTarget[insertingMethod](wrapper);
402 getSiblingParents: function(params) {
403 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
404 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
405 noSiblingParents = null;
407 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
408 return noSiblingParents;
412 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
413 if(parents1[i].sameNode(parents2[i])) {
418 return {node1: parents1[i], node2: parents2[i]};
421 _wrapText: function(params) {
422 params = _.extend({textNodeIdx: 0}, params);
423 if(typeof params.textNodeIdx === 'number') {
424 params.textNodeIdx = [params.textNodeIdx];
427 var contentsInside = params.inside.contents(),
428 idx1 = Math.min.apply(Math, params.textNodeIdx),
429 idx2 = Math.max.apply(Math, params.textNodeIdx),
430 textNode1 = contentsInside[idx1],
431 textNode2 = contentsInside[idx2],
432 sameNode = textNode1.sameNode(textNode2),
433 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
434 prefixInside = textNode1.getText().substr(params.offsetStart),
435 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
436 suffixOutside = textNode2.getText().substr(params.offsetEnd)
439 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
440 throw new Error('Wrapping text in non-sibling text nodes not supported.');
443 var wrapperElement = this.createElementNode({tagName: params._with.tagName, attrs: params._with.attrs});
444 textNode1.after(wrapperElement);
447 if(prefixOutside.length > 0) {
448 wrapperElement.before({text:prefixOutside});
451 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
452 wrapperElement.append({text: core});
455 if(prefixInside.length > 0) {
456 wrapperElement.append({text: prefixInside});
458 for(var i = idx1 + 1; i < idx2; i++) {
459 wrapperElement.append(contentsInside[i]);
461 if(suffixInside.length > 0) {
462 wrapperElement.append({text: suffixInside});
465 if(suffixOutside.length > 0) {
466 wrapperElement.after({text: suffixOutside});
468 return wrapperElement;
471 trigger: function() {
472 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
473 Backbone.Events.trigger.apply(this, arguments);
477 var defineDocumentProperties = function(doc, $document) {
478 Object.defineProperty(doc, 'root', {get: function() {
479 return doc.createElementNode($document[0]);
480 }, configurable: true});
481 Object.defineProperty(doc, 'dom', {get: function() {
483 }, configurable: true});
487 documentFromXML: function(xml) {
488 return new Document(parseXML(xml));
491 elementNodeFromXML: function(xml) {
492 return this.documentFromXML(xml).root;
496 DocumentNode: DocumentNode,
497 ElementNode: ElementNode