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() {
247 document = this.document;
248 this._$.contents().each(function() {
249 toret.push(document.createDocumentNode(this));
254 indexOf: function(node) {
255 return this._$.contents().index(node._$);
258 setTag: function(tagName) {
259 var node = this.document.createDocumentNode({tagName: tagName}),
260 oldTagName = this.getTagName(),
261 myContents = this._$.contents();
263 this.getAttrs().forEach(function(attribute) {
264 node.setAttr(attribute.name, attribute.value, true);
266 node.setData(this.getData());
268 if(this.sameNode(this.document.root)) {
269 defineDocumentProperties(this.document, node._$);
271 this._$.replaceWith(node._$);
272 this._setNativeNode(node._$[0]);
273 this._$.append(myContents);
274 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
277 getAttr: function(name) {
278 return this._$.attr(name);
281 setAttr: function(name, value, silent) {
282 var oldVal = this.getAttr(name);
283 this._$.attr(name, value);
285 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
289 getAttrs: function() {
291 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
292 toret.push(this.nativeNode.attributes[i]);
297 append: INSERTION(function(nativeNode) {
298 this._$.append(nativeNode);
301 prepend: INSERTION(function(nativeNode) {
302 this._$.prepend(nativeNode);
305 insertAtIndex: function(nativeNode, index) {
306 var contents = this.contents();
307 if(index < contents.length) {
308 return contents[index].before(nativeNode);
309 } else if(index === contents.length) {
310 return this.append(nativeNode);
314 unwrapContent: function() {
315 var parent = this.parent();
320 var myContents = this.contents(),
321 myIdx = parent.indexOf(this);
324 if(myContents.length === 0) {
325 return this.detach();
328 var prev = this.prev(),
330 moveLeftRange, moveRightRange, leftMerged;
332 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
333 prev.appendText(myContents[0].getText());
334 myContents[0].detach();
335 moveLeftRange = true;
341 if(!(leftMerged && myContents.length === 1)) {
342 var lastContents = _.last(myContents);
343 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
344 next.prependText(lastContents.getText());
345 lastContents.detach();
346 moveRightRange = true;
350 var childrenLength = this.contents().length;
351 this.contents().forEach(function(child) {
358 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
359 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
363 wrapText: function(params) {
364 return this.document._wrapText(_.extend({inside: this}, params));
368 var wrapper = $('<div>');
369 wrapper.append(this._getXMLDOMToDump());
370 return wrapper.html();
373 _getXMLDOMToDump: function() {
380 // todo - split+append
382 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
383 name: 'smartxml.setAttr',
384 impl: function(args) {
385 this.setAttr(args.name, args.value);
387 getChangeRoot: function() {
392 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
393 name: 'smartxml.wrapWith',
394 getChangeRoot: function() {
395 return this.context.parent();
397 impl: function(args) {
398 return this.wrapWith(args);
402 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
403 name: 'smartxml.wrapText',
404 getChangeRoot: function() {
407 impl: function(args) {
408 return this.wrapText(args);
412 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
413 name: 'smartxml.detach',
414 getChangeRoot: function() {
415 return this.context.parent();
417 impl: function(args) {
418 return this.detach();
424 var TextNode = function(nativeNode, document) {
425 DocumentNode.call(this, nativeNode, document);
427 TextNode.prototype = Object.create(DocumentNode.prototype);
429 $.extend(TextNode.prototype, {
430 nodeType: Node.TEXT_NODE,
432 getText: function() {
433 return this.nativeNode.data;
436 setText: function(text) {
437 console.log('smartxml: ' + text);
438 this.nativeNode.data = text;
439 this.triggerTextChangeEvent();
442 appendText: function(text) {
443 this.nativeNode.data = this.nativeNode.data + text;
444 this.triggerTextChangeEvent();
447 prependText: function(text) {
448 this.nativeNode.data = text + this.nativeNode.data;
449 this.triggerTextChangeEvent();
452 wrapWith: function(desc) {
453 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
454 return this.document._wrapText({
455 inside: this.parent(),
456 textNodeIdx: this.parent().indexOf(this),
457 offsetStart: Math.min(desc.start, desc.end),
458 offsetEnd: Math.max(desc.start, desc.end),
459 _with: {tagName: desc.tagName, attrs: desc.attrs}
462 return DocumentNode.prototype.wrapWith.call(this, desc);
466 split: function(params) {
467 var parentElement = this.parent(),
469 succeedingChildren = [],
470 prefix = this.getText().substr(0, params.offset),
471 suffix = this.getText().substr(params.offset);
473 parentElement.contents().forEach(function(child) {
475 succeedingChildren.push(child);
477 if(child.sameNode(this)) {
482 if(prefix.length > 0) {
483 this.setText(prefix);
490 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
491 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
492 parentElement.after(newElement);
494 if(suffix.length > 0) {
495 newElement.append({text: suffix});
497 succeedingChildren.forEach(function(child) {
498 newElement.append(child);
501 return {first: parentElement, second: newElement};
504 triggerTextChangeEvent: function() {
505 var event = new events.ChangeEvent('nodeTextChange', {node: this});
506 this.document.trigger('change', event);
511 TextNode.prototype.transformations.register(transformations.createContextTransformation({
512 name: 'rng.breakContent',
513 // impl: function(args) {
514 // var node = this.context,
515 // newNodes, emptyNode, emptyText;
516 // newNodes = node.transform('smartxml.split', {offset: args.offset});
517 // [newNodes.first, newNodes.second].some(function(newNode) {
518 // if(!(newNode.contents().length)) {
519 // newNode.transform('smartxml.append', {text: ''});
520 // return true; // break
523 // return _.extend(newNodes, {emptyText: emptyText});
525 impl: function(args) {
527 newNodes, emptyNode, emptyText;
528 newNodes = node.split({offset: args.offset});
529 [newNodes.first, newNodes.second].some(function(newNode) {
530 if(!(newNode.contents().length)) {
531 newNode.append({text: ''});
532 return true; // break
535 return _.extend(newNodes, {emptyText: emptyText});
537 getChangeRoot: function() {
538 return this.context.parent().parent();
543 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
544 name: 'smartxml.setText',
545 impl: function(args) {
546 this.setText(args.text);
548 getChangeRoot: function() {
554 var parseXML = function(xml) {
555 return $($.trim(xml))[0];
558 var Document = function(xml) {
564 $.extend(Document.prototype, Backbone.Events, {
565 ElementNodeFactory: ElementNode,
566 TextNodeFactory: TextNode,
567 transformations: new transformations.TransformationStorage(),
569 createDocumentNode: function(from) {
570 if(!(from instanceof Node)) {
571 if(from.text !== undefined) {
572 /* globals document */
573 from = document.createTextNode(from.text);
575 var node = $('<' + from.tagName + '>');
577 _.keys(from.attrs || {}).forEach(function(key) {
578 node.attr(key, from.attrs[key]);
585 if(from.nodeType === Node.TEXT_NODE) {
586 Factory = this.TextNodeFactory;
587 } else if(from.nodeType === Node.ELEMENT_NODE) {
588 Factory = this.ElementNodeFactory;
590 return new Factory(from, this);
593 loadXML: function(xml, options) {
594 options = options || {};
595 defineDocumentProperties(this, $(parseXML(xml)));
596 if(!options.silent) {
597 this.trigger('contentSet');
602 return this.root.toXML();
605 containsNode: function(node) {
606 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
609 wrapNodes: function(params) {
610 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
611 throw new Error('Wrapping non-sibling nodes not supported.');
614 var parent = params.node1.parent(),
615 parentContents = parent.contents(),
616 wrapper = this.createDocumentNode({
617 tagName: params._with.tagName,
618 attrs: params._with.attrs}),
619 idx1 = parent.indexOf(params.node1),
620 idx2 = parent.indexOf(params.node2);
628 var insertingMethod, insertingTarget;
630 insertingMethod = 'prepend';
631 insertingTarget = parent;
633 insertingMethod = 'after';
634 insertingTarget = parentContents[idx1-1];
637 for(var i = idx1; i <= idx2; i++) {
638 wrapper.append(parentContents[i].detach());
641 insertingTarget[insertingMethod](wrapper);
645 getSiblingParents: function(params) {
646 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
647 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
648 noSiblingParents = null;
650 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
651 return noSiblingParents;
655 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
656 if(parents1[i].sameNode(parents2[i])) {
661 return {node1: parents1[i], node2: parents2[i]};
664 _wrapText: function(params) {
665 params = _.extend({textNodeIdx: 0}, params);
666 if(typeof params.textNodeIdx === 'number') {
667 params.textNodeIdx = [params.textNodeIdx];
670 var contentsInside = params.inside.contents(),
671 idx1 = Math.min.apply(Math, params.textNodeIdx),
672 idx2 = Math.max.apply(Math, params.textNodeIdx),
673 textNode1 = contentsInside[idx1],
674 textNode2 = contentsInside[idx2],
675 sameNode = textNode1.sameNode(textNode2),
676 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
677 prefixInside = textNode1.getText().substr(params.offsetStart),
678 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
679 suffixOutside = textNode2.getText().substr(params.offsetEnd)
682 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
683 throw new Error('Wrapping text in non-sibling text nodes not supported.');
686 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
687 textNode1.after(wrapperElement);
690 if(prefixOutside.length > 0) {
691 wrapperElement.before({text:prefixOutside});
694 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
695 wrapperElement.append({text: core});
698 if(prefixInside.length > 0) {
699 wrapperElement.append({text: prefixInside});
701 for(var i = idx1 + 1; i < idx2; i++) {
702 wrapperElement.append(contentsInside[i]);
704 if(suffixInside.length > 0) {
705 wrapperElement.append({text: suffixInside});
708 if(suffixOutside.length > 0) {
709 wrapperElement.after({text: suffixOutside});
711 return wrapperElement;
714 trigger: function() {
715 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
716 Backbone.Events.trigger.apply(this, arguments);
719 getNodeInsertion: function(node) {
721 if(node instanceof DocumentNode) {
722 insertion.ofNode = node;
723 insertion.insertsNew = !this.containsNode(node);
725 insertion.ofNode = this.createDocumentNode(node);
726 insertion.insertsNew = true;
731 replaceRoot: function(node) {
732 var insertion = this.getNodeInsertion(node);
734 defineDocumentProperties(this, insertion.ofNode._$);
735 insertion.ofNode.triggerChangeEvent('nodeAdded');
736 return insertion.ofNode;
739 transform: function(transformation, args) {
740 console.log('transform');
741 var Transformation, toret;
742 if(typeof transformation === 'string') {
743 Transformation = this.transformations.get(transformation);
745 transformation = new Transformation(this, this, args);
749 toret = transformation.run();
750 this.undoStack.push(transformation);
751 console.log('clearing redo stack');
755 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
759 var transformation = this.undoStack.pop();
761 transformation.undo();
762 this.redoStack.push(transformation);
766 var transformation = this.redoStack.pop();
768 transformation.run();
769 this.undoStack.push(transformation);
773 getNodeByPath: function(path) {
774 var toret = this.root;
775 path.forEach(function(idx) {
776 toret = toret.contents()[idx];
782 var defineDocumentProperties = function(doc, $document) {
783 Object.defineProperty(doc, 'root', {get: function() {
784 return doc.createDocumentNode($document[0]);
785 }, configurable: true});
786 Object.defineProperty(doc, 'dom', {get: function() {
788 }, configurable: true});
791 Document.prototype.transformations.register(transformations.createContextTransformation({
792 name: 'smartxml.wrapNodes',
793 // init: function() {
796 // getChangeRoot: function() {
797 // return this.context;
799 impl: function(args) {
800 this.wrapNodes(args);
807 documentFromXML: function(xml) {
808 return new Document(xml);
811 elementNodeFromXML: function(xml) {
812 return this.documentFromXML(xml).root;
816 DocumentNode: DocumentNode,
817 ElementNode: ElementNode