6 'smartxml/transformations'
7 ], function($, _, Backbone, events, transformations) {
12 var TEXT_NODE = Node.TEXT_NODE;
15 var INSERTION = function(implementation) {
16 var toret = function(node) {
17 var insertion = this.getNodeInsertion(node),
19 if(!(this.document.containsNode(this))) {
20 nodeParent = insertion.ofNode.parent();
22 implementation.call(this, insertion.ofNode.nativeNode);
23 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent);
24 return insertion.ofNode;
29 var DocumentNode = function(nativeNode, document) {
31 throw new Error('undefined document for a node');
33 this.document = document;
34 this._setNativeNode(nativeNode);
38 $.extend(DocumentNode.prototype, {
40 transformations: new transformations.TransformationStorage(),
42 transform: function(name, args) {
43 var Transformation = this.transformations.get(name),
46 transformation = new Transformation(this.document, this, args);
48 return this.document.transform(transformation);
51 _setNativeNode: function(nativeNode) {
52 this.nativeNode = nativeNode;
53 this._$ = $(nativeNode);
57 var clone = this._$.clone(true, true);
58 // clone.find('*').addBack().each(function() {
60 // if(n.data('canvasElement')) {
61 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
62 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
65 return this.document.createDocumentNode(clone[0]);
68 getPath: function(ancestor) {
69 var nodePath = [this].concat(this.parents()),
71 ancestor = ancestor || this.document.root;
73 nodePath.some(function(node, i) {
74 if(node.sameNode(ancestor)) {
80 if(idx !== 'undefined') {
81 nodePath = nodePath.slice(0, idx);
83 toret = nodePath.map(function(node) {return node.getIndex(); });
89 return this.document.root.sameNode(this);
93 var parent = this.parent();
95 this.triggerChangeEvent('nodeDetached', {parent: parent});
99 replaceWith: function(node) {
102 return this.document.replaceRoot(node);
104 toret = this.after(node);
109 sameNode: function(otherNode) {
110 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
114 var parentNode = this.nativeNode.parentNode;
115 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
116 return this.document.createDocumentNode(parentNode);
121 parents: function() {
122 var parent = this.parent(),
123 parents = parent ? parent.parents() : [];
125 parents.unshift(parent);
131 var myIdx = this.getIndex();
132 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
139 var myIdx = this.getIndex(),
140 parentContents = this.parent().contents();
141 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
144 isSurroundedByTextElements: function() {
145 var prev = this.prev(),
147 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
150 after: INSERTION(function(nativeNode) {
151 return this._$.after(nativeNode);
154 before: INSERTION(function(nativeNode) {
155 return this._$.before(nativeNode);
158 wrapWith: function(node) {
159 var insertion = this.getNodeInsertion(node);
161 this.before(insertion.ofNode);
163 insertion.ofNode.append(this);
164 return insertion.ofNode;
168 * Removes parent of a node if node has no siblings.
174 var parent = this.parent(),
176 if(parent.contents().length === 1) {
177 grandParent = parent.parent();
178 parent.unwrapContent();
183 triggerChangeEvent: function(type, metaData, origParent) {
184 var node = (metaData && metaData.node) ? metaData.node : this,
185 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
186 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
187 this.document.trigger('change', event);
189 if((type === 'nodeAdded' || type === 'nodeMoved') && !(this.document.containsNode(this))) {
190 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
191 this.document.trigger('change', event);
195 getNodeInsertion: function(node) {
196 return this.document.getNodeInsertion(node);
199 getIndex: function() {
203 return this.parent().indexOf(this);
207 var ElementNode = function(nativeNode, document) {
208 DocumentNode.call(this, nativeNode, document);
210 ElementNode.prototype = Object.create(DocumentNode.prototype);
212 $.extend(ElementNode.prototype, {
213 nodeType: Node.ELEMENT_NODE,
217 if(this.parent() && this.isSurroundedByTextElements()) {
219 this.prev().appendText(next.getText());
222 return DocumentNode.prototype.detach.call(this);
225 setData: function(key, value) {
226 if(value !== undefined) {
227 this._$.data(key, value);
229 this._$.removeData(_.keys(this._$.data()));
234 getData: function(key) {
236 return this._$.data(key);
238 return this._$.data();
241 getTagName: function() {
242 return this.nativeNode.tagName.toLowerCase();
245 contents: function(selector) {
247 document = this.document;
249 this._$.children(selector).each(function() {
250 toret.push(document.createDocumentNode(this));
253 this._$.contents().each(function() {
254 toret.push(document.createDocumentNode(this));
260 indexOf: function(node) {
261 return this._$.contents().index(node._$);
264 setTag: function(tagName) {
265 var node = this.document.createDocumentNode({tagName: tagName}),
266 oldTagName = this.getTagName(),
267 myContents = this._$.contents();
269 this.getAttrs().forEach(function(attribute) {
270 node.setAttr(attribute.name, attribute.value, true);
272 node.setData(this.getData());
274 if(this.sameNode(this.document.root)) {
275 defineDocumentProperties(this.document, node._$);
277 this._$.replaceWith(node._$);
278 this._setNativeNode(node._$[0]);
279 this._$.append(myContents);
280 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
283 getAttr: function(name) {
284 return this._$.attr(name);
287 setAttr: function(name, value, silent) {
288 var oldVal = this.getAttr(name);
289 this._$.attr(name, value);
291 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
295 getAttrs: function() {
297 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
298 toret.push(this.nativeNode.attributes[i]);
303 append: INSERTION(function(nativeNode) {
304 this._$.append(nativeNode);
307 prepend: INSERTION(function(nativeNode) {
308 this._$.prepend(nativeNode);
311 insertAtIndex: function(nativeNode, index) {
312 var contents = this.contents();
313 if(index < contents.length) {
314 return contents[index].before(nativeNode);
315 } else if(index === contents.length) {
316 return this.append(nativeNode);
320 unwrapContent: function() {
321 var parent = this.parent();
326 var myContents = this.contents(),
327 myIdx = parent.indexOf(this);
330 if(myContents.length === 0) {
331 return this.detach();
334 var prev = this.prev(),
336 moveLeftRange, moveRightRange, leftMerged;
338 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
339 prev.appendText(myContents[0].getText());
340 myContents[0].detach();
341 moveLeftRange = true;
347 if(!(leftMerged && myContents.length === 1)) {
348 var lastContents = _.last(myContents);
349 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
350 next.prependText(lastContents.getText());
351 lastContents.detach();
352 moveRightRange = true;
356 var childrenLength = this.contents().length;
357 this.contents().forEach(function(child) {
364 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
365 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
369 wrapText: function(params) {
370 return this.document._wrapText(_.extend({inside: this}, params));
374 var wrapper = $('<div>');
375 wrapper.append(this._getXMLDOMToDump());
376 return wrapper.html();
379 _getXMLDOMToDump: function() {
386 // todo - split+append
388 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
389 name: 'smartxml.setAttr',
390 impl: function(args) {
391 this.setAttr(args.name, args.value);
393 getChangeRoot: function() {
398 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
399 name: 'smartxml.wrapWith',
400 getChangeRoot: function() {
401 return this.context.parent();
403 impl: function(args) {
404 return this.wrapWith(args);
408 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
409 name: 'smartxml.wrapText',
410 getChangeRoot: function() {
413 impl: function(args) {
414 return this.wrapText(args);
418 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
419 name: 'smartxml.detach',
420 getChangeRoot: function() {
421 return this.context.parent();
423 impl: function(args) {
424 return this.detach();
430 var TextNode = function(nativeNode, document) {
431 DocumentNode.call(this, nativeNode, document);
433 TextNode.prototype = Object.create(DocumentNode.prototype);
435 $.extend(TextNode.prototype, {
436 nodeType: Node.TEXT_NODE,
438 getText: function() {
439 return this.nativeNode.data;
442 setText: function(text) {
443 console.log('smartxml: ' + text);
444 this.nativeNode.data = text;
445 this.triggerTextChangeEvent();
448 appendText: function(text) {
449 this.nativeNode.data = this.nativeNode.data + text;
450 this.triggerTextChangeEvent();
453 prependText: function(text) {
454 this.nativeNode.data = text + this.nativeNode.data;
455 this.triggerTextChangeEvent();
458 wrapWith: function(desc) {
459 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
460 return this.document._wrapText({
461 inside: this.parent(),
462 textNodeIdx: this.parent().indexOf(this),
463 offsetStart: Math.min(desc.start, desc.end),
464 offsetEnd: Math.max(desc.start, desc.end),
465 _with: {tagName: desc.tagName, attrs: desc.attrs}
468 return DocumentNode.prototype.wrapWith.call(this, desc);
472 split: function(params) {
473 var parentElement = this.parent(),
475 succeedingChildren = [],
476 prefix = this.getText().substr(0, params.offset),
477 suffix = this.getText().substr(params.offset);
479 parentElement.contents().forEach(function(child) {
481 succeedingChildren.push(child);
483 if(child.sameNode(this)) {
488 if(prefix.length > 0) {
489 this.setText(prefix);
496 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
497 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
498 parentElement.after(newElement);
500 if(suffix.length > 0) {
501 newElement.append({text: suffix});
503 succeedingChildren.forEach(function(child) {
504 newElement.append(child);
507 return {first: parentElement, second: newElement};
510 triggerTextChangeEvent: function() {
511 var event = new events.ChangeEvent('nodeTextChange', {node: this});
512 this.document.trigger('change', event);
517 TextNode.prototype.transformations.register(transformations.createContextTransformation({
518 name: 'rng.breakContent',
519 // impl: function(args) {
520 // var node = this.context,
521 // newNodes, emptyNode, emptyText;
522 // newNodes = node.transform('smartxml.split', {offset: args.offset});
523 // [newNodes.first, newNodes.second].some(function(newNode) {
524 // if(!(newNode.contents().length)) {
525 // newNode.transform('smartxml.append', {text: ''});
526 // return true; // break
529 // return _.extend(newNodes, {emptyText: emptyText});
531 impl: function(args) {
533 newNodes, emptyNode, emptyText;
534 newNodes = node.split({offset: args.offset});
535 [newNodes.first, newNodes.second].some(function(newNode) {
536 if(!(newNode.contents().length)) {
537 newNode.append({text: ''});
538 return true; // break
541 return _.extend(newNodes, {emptyText: emptyText});
543 getChangeRoot: function() {
544 return this.context.parent().parent();
549 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
550 name: 'smartxml.setText',
551 impl: function(args) {
552 this.setText(args.text);
554 getChangeRoot: function() {
560 var parseXML = function(xml) {
561 return $($.trim(xml))[0];
564 var Document = function(xml) {
570 $.extend(Document.prototype, Backbone.Events, {
571 ElementNodeFactory: ElementNode,
572 TextNodeFactory: TextNode,
573 transformations: new transformations.TransformationStorage(),
575 createDocumentNode: function(from) {
576 if(!(from instanceof Node)) {
577 if(from.text !== undefined) {
578 /* globals document */
579 from = document.createTextNode(from.text);
581 var node = $('<' + from.tagName + '>');
583 _.keys(from.attrs || {}).forEach(function(key) {
584 node.attr(key, from.attrs[key]);
591 if(from.nodeType === Node.TEXT_NODE) {
592 Factory = this.TextNodeFactory;
593 } else if(from.nodeType === Node.ELEMENT_NODE) {
594 Factory = this.ElementNodeFactory;
596 return new Factory(from, this);
599 loadXML: function(xml, options) {
600 options = options || {};
601 defineDocumentProperties(this, $(parseXML(xml)));
602 if(!options.silent) {
603 this.trigger('contentSet');
608 return this.root.toXML();
611 containsNode: function(node) {
612 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
615 wrapNodes: function(params) {
616 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
617 throw new Error('Wrapping non-sibling nodes not supported.');
620 var parent = params.node1.parent(),
621 parentContents = parent.contents(),
622 wrapper = this.createDocumentNode({
623 tagName: params._with.tagName,
624 attrs: params._with.attrs}),
625 idx1 = parent.indexOf(params.node1),
626 idx2 = parent.indexOf(params.node2);
634 var insertingMethod, insertingTarget;
636 insertingMethod = 'prepend';
637 insertingTarget = parent;
639 insertingMethod = 'after';
640 insertingTarget = parentContents[idx1-1];
643 for(var i = idx1; i <= idx2; i++) {
644 wrapper.append(parentContents[i].detach());
647 insertingTarget[insertingMethod](wrapper);
651 getSiblingParents: function(params) {
652 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
653 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
654 noSiblingParents = null;
656 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
657 return noSiblingParents;
661 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
662 if(parents1[i].sameNode(parents2[i])) {
667 return {node1: parents1[i], node2: parents2[i]};
670 _wrapText: function(params) {
671 params = _.extend({textNodeIdx: 0}, params);
672 if(typeof params.textNodeIdx === 'number') {
673 params.textNodeIdx = [params.textNodeIdx];
676 var contentsInside = params.inside.contents(),
677 idx1 = Math.min.apply(Math, params.textNodeIdx),
678 idx2 = Math.max.apply(Math, params.textNodeIdx),
679 textNode1 = contentsInside[idx1],
680 textNode2 = contentsInside[idx2],
681 sameNode = textNode1.sameNode(textNode2),
682 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
683 prefixInside = textNode1.getText().substr(params.offsetStart),
684 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
685 suffixOutside = textNode2.getText().substr(params.offsetEnd)
688 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
689 throw new Error('Wrapping text in non-sibling text nodes not supported.');
692 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
693 textNode1.after(wrapperElement);
696 if(prefixOutside.length > 0) {
697 wrapperElement.before({text:prefixOutside});
700 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
701 wrapperElement.append({text: core});
704 if(prefixInside.length > 0) {
705 wrapperElement.append({text: prefixInside});
707 for(var i = idx1 + 1; i < idx2; i++) {
708 wrapperElement.append(contentsInside[i]);
710 if(suffixInside.length > 0) {
711 wrapperElement.append({text: suffixInside});
714 if(suffixOutside.length > 0) {
715 wrapperElement.after({text: suffixOutside});
717 return wrapperElement;
720 trigger: function() {
721 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
722 Backbone.Events.trigger.apply(this, arguments);
725 getNodeInsertion: function(node) {
727 if(node instanceof DocumentNode) {
728 insertion.ofNode = node;
729 insertion.insertsNew = !this.containsNode(node);
731 insertion.ofNode = this.createDocumentNode(node);
732 insertion.insertsNew = true;
737 replaceRoot: function(node) {
738 var insertion = this.getNodeInsertion(node);
740 defineDocumentProperties(this, insertion.ofNode._$);
741 insertion.ofNode.triggerChangeEvent('nodeAdded');
742 return insertion.ofNode;
745 transform: function(transformation, args) {
746 console.log('transform');
747 var Transformation, toret;
748 if(typeof transformation === 'string') {
749 Transformation = this.transformations.get(transformation);
751 transformation = new Transformation(this, this, args);
755 toret = transformation.run();
756 this.undoStack.push(transformation);
757 console.log('clearing redo stack');
761 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
765 var transformation = this.undoStack.pop();
767 transformation.undo();
768 this.redoStack.push(transformation);
772 var transformation = this.redoStack.pop();
774 transformation.run();
775 this.undoStack.push(transformation);
779 getNodeByPath: function(path) {
780 var toret = this.root;
781 path.forEach(function(idx) {
782 toret = toret.contents()[idx];
788 var defineDocumentProperties = function(doc, $document) {
789 Object.defineProperty(doc, 'root', {get: function() {
790 return doc.createDocumentNode($document[0]);
791 }, configurable: true});
792 Object.defineProperty(doc, 'dom', {get: function() {
794 }, configurable: true});
797 Document.prototype.transformations.register(transformations.createContextTransformation({
798 name: 'smartxml.wrapNodes',
799 // init: function() {
802 // getChangeRoot: function() {
803 // return this.context;
805 impl: function(args) {
806 this.wrapNodes(args);
813 documentFromXML: function(xml) {
814 return new Document(xml);
817 elementNodeFromXML: function(xml) {
818 return this.documentFromXML(xml).root;
822 DocumentNode: DocumentNode,
823 ElementNode: ElementNode