6 ], function($, _, Backbone, events) {
11 var TEXT_NODE = Node.TEXT_NODE;
14 var INSERTION = function(implementation) {
15 var toret = function(node) {
16 var insertion = this.getNodeInsertion(node);
17 implementation.call(this, insertion.ofNode.nativeNode);
18 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode});
19 return insertion.ofNode;
24 var DocumentNode = function(nativeNode, document) {
26 throw new Error('undefined document for a node');
28 this.document = document;
29 this._setNativeNode(nativeNode);
33 $.extend(DocumentNode.prototype, {
34 _setNativeNode: function(nativeNode) {
35 this.nativeNode = nativeNode;
36 this._$ = $(nativeNode);
40 return this.document.createDocumentNode(this._$.clone(true, true)[0]);
43 getPath: function(ancestor) {
44 var nodePath = [this].concat(this.parents()),
46 ancestor = ancestor || this.document.root;
48 nodePath.some(function(node, i) {
49 if(node.sameNode(ancestor)) {
55 if(idx !== 'undefined') {
56 nodePath = nodePath.slice(0, idx);
58 toret = nodePath.map(function(node) {return node.getIndex(); });
64 return this.document.root.sameNode(this);
68 var parent = this.parent();
70 this.triggerChangeEvent('nodeDetached', {parent: parent});
74 replaceWith: function(node) {
77 return this.document.replaceRoot(node);
79 toret = this.after(node);
84 sameNode: function(otherNode) {
85 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
89 var parentNode = this.nativeNode.parentNode;
90 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
91 return this.document.createDocumentNode(parentNode);
97 var parent = this.parent(),
98 parents = parent ? parent.parents() : [];
100 parents.unshift(parent);
106 var myIdx = this.getIndex();
107 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
114 var myIdx = this.getIndex(),
115 parentContents = this.parent().contents();
116 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
119 isSurroundedByTextElements: function() {
120 var prev = this.prev(),
122 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
125 after: INSERTION(function(nativeNode) {
126 return this._$.after(nativeNode);
129 before: INSERTION(function(nativeNode) {
130 return this._$.before(nativeNode);
133 wrapWith: function(node) {
134 var insertion = this.getNodeInsertion(node);
136 this.before(insertion.ofNode);
138 insertion.ofNode.append(this);
139 return insertion.ofNode;
143 * Removes parent of a node if node has no siblings.
149 var parent = this.parent(),
151 if(parent.contents().length === 1) {
152 grandParent = parent.parent();
153 parent.unwrapContent();
158 triggerChangeEvent: function(type, metaData) {
159 var event = new events.ChangeEvent(type, $.extend({node: this}, metaData || {}));
160 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
161 this.document.trigger('change', event);
165 getNodeInsertion: function(node) {
166 return this.document.getNodeInsertion(node);
169 getIndex: function() {
173 return this.parent().indexOf(this);
177 var ElementNode = function(nativeNode, document) {
178 DocumentNode.call(this, nativeNode, document);
180 ElementNode.prototype = Object.create(DocumentNode.prototype);
182 $.extend(ElementNode.prototype, {
183 nodeType: Node.ELEMENT_NODE,
187 if(this.parent() && this.isSurroundedByTextElements()) {
189 this.prev().appendText(next.getText());
192 return DocumentNode.prototype.detach.call(this);
195 setData: function(key, value) {
196 if(value !== undefined) {
197 this._$.data(key, value);
199 this._$.removeData(_.keys(this._$.data()));
204 getData: function(key) {
206 return this._$.data(key);
208 return this._$.data();
211 getTagName: function() {
212 return this.nativeNode.tagName.toLowerCase();
215 contents: function() {
217 document = this.document;
218 this._$.contents().each(function() {
219 toret.push(document.createDocumentNode(this));
224 indexOf: function(node) {
225 return this._$.contents().index(node._$);
228 setTag: function(tagName) {
229 var node = this.document.createDocumentNode({tagName: tagName}),
230 oldTagName = this.getTagName(),
231 myContents = this._$.contents();
233 this.getAttrs().forEach(function(attribute) {
234 node.setAttr(attribute.name, attribute.value, true);
236 node.setData(this.getData());
238 if(this.sameNode(this.document.root)) {
239 defineDocumentProperties(this.document, node._$);
241 this._$.replaceWith(node._$);
242 this._setNativeNode(node._$[0]);
243 this._$.append(myContents);
244 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
247 getAttr: function(name) {
248 return this._$.attr(name);
251 setAttr: function(name, value, silent) {
252 var oldVal = this.getAttr(name);
253 this._$.attr(name, value);
255 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
259 getAttrs: function() {
261 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
262 toret.push(this.nativeNode.attributes[i]);
267 append: INSERTION(function(nativeNode) {
268 this._$.append(nativeNode);
271 prepend: INSERTION(function(nativeNode) {
272 this._$.prepend(nativeNode);
275 unwrapContent: function() {
276 var parent = this.parent();
281 var myContents = this.contents(),
282 myIdx = parent.indexOf(this);
285 if(myContents.length === 0) {
286 return this.detach();
289 var prev = this.prev(),
291 moveLeftRange, moveRightRange, leftMerged;
293 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
294 prev.appendText(myContents[0].getText());
295 myContents[0].detach();
296 moveLeftRange = true;
302 if(!(leftMerged && myContents.length === 1)) {
303 var lastContents = _.last(myContents);
304 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
305 next.prependText(lastContents.getText());
306 lastContents.detach();
307 moveRightRange = true;
311 var childrenLength = this.contents().length;
312 this.contents().forEach(function(child) {
319 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
320 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
324 wrapText: function(params) {
325 return this.document._wrapText(_.extend({inside: this}, params));
329 var wrapper = $('<div>');
330 wrapper.append(this._getXMLDOMToDump());
331 return wrapper.html();
334 _getXMLDOMToDump: function() {
339 var TextNode = function(nativeNode, document) {
340 DocumentNode.call(this, nativeNode, document);
342 TextNode.prototype = Object.create(DocumentNode.prototype);
344 $.extend(TextNode.prototype, {
345 nodeType: Node.TEXT_NODE,
347 getText: function() {
348 return this.nativeNode.data;
351 setText: function(text) {
352 this.nativeNode.data = text;
353 this.triggerTextChangeEvent();
356 appendText: function(text) {
357 this.nativeNode.data = this.nativeNode.data + text;
358 this.triggerTextChangeEvent();
361 prependText: function(text) {
362 this.nativeNode.data = text + this.nativeNode.data;
363 this.triggerTextChangeEvent();
366 wrapWith: function(desc) {
367 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
368 return this.document._wrapText({
369 inside: this.parent(),
370 textNodeIdx: this.parent().indexOf(this),
371 offsetStart: Math.min(desc.start, desc.end),
372 offsetEnd: Math.max(desc.start, desc.end),
373 _with: {tagName: desc.tagName, attrs: desc.attrs}
376 return DocumentNode.prototype.wrapWith.call(this, desc);
380 split: function(params) {
381 var parentElement = this.parent(),
383 succeedingChildren = [],
384 prefix = this.getText().substr(0, params.offset),
385 suffix = this.getText().substr(params.offset);
387 parentElement.contents().forEach(function(child) {
389 succeedingChildren.push(child);
391 if(child.sameNode(this)) {
396 if(prefix.length > 0) {
397 this.setText(prefix);
404 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
405 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
406 parentElement.after(newElement);
408 if(suffix.length > 0) {
409 newElement.append({text: suffix});
411 succeedingChildren.forEach(function(child) {
412 newElement.append(child);
415 return {first: parentElement, second: newElement};
418 triggerTextChangeEvent: function() {
419 var event = new events.ChangeEvent('nodeTextChange', {node: this});
420 this.document.trigger('change', event);
425 var parseXML = function(xml) {
426 return $($.trim(xml))[0];
429 var Document = function(xml) {
433 $.extend(Document.prototype, Backbone.Events, {
434 ElementNodeFactory: ElementNode,
435 TextNodeFactory: TextNode,
437 createDocumentNode: function(from) {
438 if(!(from instanceof Node)) {
439 if(from.text !== undefined) {
440 /* globals document */
441 from = document.createTextNode(from.text);
443 var node = $('<' + from.tagName + '>');
445 _.keys(from.attrs || {}).forEach(function(key) {
446 node.attr(key, from.attrs[key]);
453 if(from.nodeType === Node.TEXT_NODE) {
454 Factory = this.TextNodeFactory;
455 } else if(from.nodeType === Node.ELEMENT_NODE) {
456 Factory = this.ElementNodeFactory;
458 return new Factory(from, this);
461 loadXML: function(xml, options) {
462 options = options || {};
463 defineDocumentProperties(this, $(parseXML(xml)));
464 if(!options.silent) {
465 this.trigger('contentSet');
470 return this.root.toXML();
473 containsNode: function(node) {
474 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
477 wrapNodes: function(params) {
478 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
479 throw new Error('Wrapping non-sibling nodes not supported.');
482 var parent = params.node1.parent(),
483 parentContents = parent.contents(),
484 wrapper = this.createDocumentNode({
485 tagName: params._with.tagName,
486 attrs: params._with.attrs}),
487 idx1 = parent.indexOf(params.node1),
488 idx2 = parent.indexOf(params.node2);
496 var insertingMethod, insertingTarget;
498 insertingMethod = 'prepend';
499 insertingTarget = parent;
501 insertingMethod = 'after';
502 insertingTarget = parentContents[idx1-1];
505 for(var i = idx1; i <= idx2; i++) {
506 wrapper.append(parentContents[i].detach());
509 insertingTarget[insertingMethod](wrapper);
513 getSiblingParents: function(params) {
514 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
515 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
516 noSiblingParents = null;
518 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
519 return noSiblingParents;
523 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
524 if(parents1[i].sameNode(parents2[i])) {
529 return {node1: parents1[i], node2: parents2[i]};
532 _wrapText: function(params) {
533 params = _.extend({textNodeIdx: 0}, params);
534 if(typeof params.textNodeIdx === 'number') {
535 params.textNodeIdx = [params.textNodeIdx];
538 var contentsInside = params.inside.contents(),
539 idx1 = Math.min.apply(Math, params.textNodeIdx),
540 idx2 = Math.max.apply(Math, params.textNodeIdx),
541 textNode1 = contentsInside[idx1],
542 textNode2 = contentsInside[idx2],
543 sameNode = textNode1.sameNode(textNode2),
544 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
545 prefixInside = textNode1.getText().substr(params.offsetStart),
546 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
547 suffixOutside = textNode2.getText().substr(params.offsetEnd)
550 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
551 throw new Error('Wrapping text in non-sibling text nodes not supported.');
554 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
555 textNode1.after(wrapperElement);
558 if(prefixOutside.length > 0) {
559 wrapperElement.before({text:prefixOutside});
562 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
563 wrapperElement.append({text: core});
566 if(prefixInside.length > 0) {
567 wrapperElement.append({text: prefixInside});
569 for(var i = idx1 + 1; i < idx2; i++) {
570 wrapperElement.append(contentsInside[i]);
572 if(suffixInside.length > 0) {
573 wrapperElement.append({text: suffixInside});
576 if(suffixOutside.length > 0) {
577 wrapperElement.after({text: suffixOutside});
579 return wrapperElement;
582 trigger: function() {
583 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
584 Backbone.Events.trigger.apply(this, arguments);
587 getNodeInsertion: function(node) {
589 if(node instanceof DocumentNode) {
590 insertion.ofNode = node;
591 insertion.insertsNew = !this.containsNode(node);
593 insertion.ofNode = this.createDocumentNode(node);
594 insertion.insertsNew = true;
599 replaceRoot: function(node) {
600 var insertion = this.getNodeInsertion(node);
602 defineDocumentProperties(this, insertion.ofNode._$);
603 insertion.ofNode.triggerChangeEvent('nodeAdded');
604 return insertion.ofNode;
608 var defineDocumentProperties = function(doc, $document) {
609 Object.defineProperty(doc, 'root', {get: function() {
610 return doc.createDocumentNode($document[0]);
611 }, configurable: true});
612 Object.defineProperty(doc, 'dom', {get: function() {
614 }, configurable: true});
618 documentFromXML: function(xml) {
619 return new Document(xml);
622 elementNodeFromXML: function(xml) {
623 return this.documentFromXML(xml).root;
627 DocumentNode: DocumentNode,
628 ElementNode: ElementNode