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 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
399 name: 'smartxml.setAttr2',
400 impl: function(args) {
401 this.prevAttr = this.getAttr(args.name);
402 this.setAttr(args.name, args.value);
404 undo: function(args) {
405 this.setAttr(args.name, this.prevAttr);
409 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
410 name: 'smartxml.wrapWith',
411 getChangeRoot: function() {
412 return this.context.parent();
414 impl: function(args) {
415 return this.wrapWith(args);
419 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
420 name: 'smartxml.wrapText',
421 getChangeRoot: function() {
424 impl: function(args) {
425 return this.wrapText(args);
429 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
430 name: 'smartxml.detach',
431 getChangeRoot: function() {
432 return this.context.parent();
434 impl: function(args) {
435 return this.detach();
441 var TextNode = function(nativeNode, document) {
442 DocumentNode.call(this, nativeNode, document);
444 TextNode.prototype = Object.create(DocumentNode.prototype);
446 $.extend(TextNode.prototype, {
447 nodeType: Node.TEXT_NODE,
449 getText: function() {
450 return this.nativeNode.data;
453 setText: function(text) {
454 console.log('smartxml: ' + text);
455 this.nativeNode.data = text;
456 this.triggerTextChangeEvent();
459 appendText: function(text) {
460 this.nativeNode.data = this.nativeNode.data + text;
461 this.triggerTextChangeEvent();
464 prependText: function(text) {
465 this.nativeNode.data = text + this.nativeNode.data;
466 this.triggerTextChangeEvent();
469 wrapWith: function(desc) {
470 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
471 return this.document._wrapText({
472 inside: this.parent(),
473 textNodeIdx: this.parent().indexOf(this),
474 offsetStart: Math.min(desc.start, desc.end),
475 offsetEnd: Math.max(desc.start, desc.end),
476 _with: {tagName: desc.tagName, attrs: desc.attrs}
479 return DocumentNode.prototype.wrapWith.call(this, desc);
483 split: function(params) {
484 var parentElement = this.parent(),
486 succeedingChildren = [],
487 prefix = this.getText().substr(0, params.offset),
488 suffix = this.getText().substr(params.offset);
490 parentElement.contents().forEach(function(child) {
492 succeedingChildren.push(child);
494 if(child.sameNode(this)) {
499 if(prefix.length > 0) {
500 this.setText(prefix);
507 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
508 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
509 parentElement.after(newElement);
511 if(suffix.length > 0) {
512 newElement.append({text: suffix});
514 succeedingChildren.forEach(function(child) {
515 newElement.append(child);
518 return {first: parentElement, second: newElement};
521 triggerTextChangeEvent: function() {
522 var event = new events.ChangeEvent('nodeTextChange', {node: this});
523 this.document.trigger('change', event);
528 TextNode.prototype.transformations.register(transformations.createContextTransformation({
529 name: 'rng.breakContent',
530 // impl: function(args) {
531 // var node = this.context,
532 // newNodes, emptyNode, emptyText;
533 // newNodes = node.transform('smartxml.split', {offset: args.offset});
534 // [newNodes.first, newNodes.second].some(function(newNode) {
535 // if(!(newNode.contents().length)) {
536 // newNode.transform('smartxml.append', {text: ''});
537 // return true; // break
540 // return _.extend(newNodes, {emptyText: emptyText});
542 impl: function(args) {
544 newNodes, emptyNode, emptyText;
545 newNodes = node.split({offset: args.offset});
546 [newNodes.first, newNodes.second].some(function(newNode) {
547 if(!(newNode.contents().length)) {
548 newNode.append({text: ''});
549 return true; // break
552 return _.extend(newNodes, {emptyText: emptyText});
554 getChangeRoot: function() {
555 return this.context.parent().parent();
557 isAllowed: function(args) {
558 var parent = this.parent();
559 return !!(parent && parent.parent());
564 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
565 name: 'smartxml.setText',
566 impl: function(args) {
567 this.setText(args.text);
569 getChangeRoot: function() {
575 var parseXML = function(xml) {
576 return $($.trim(xml))[0];
579 var Document = function(xml) {
583 this._transformationLevel = 0;
586 $.extend(Document.prototype, Backbone.Events, {
587 ElementNodeFactory: ElementNode,
588 TextNodeFactory: TextNode,
589 transformations: new transformations.TransformationStorage(),
591 createDocumentNode: function(from) {
592 if(!(from instanceof Node)) {
593 if(from.text !== undefined) {
594 /* globals document */
595 from = document.createTextNode(from.text);
597 var node = $('<' + from.tagName + '>');
599 _.keys(from.attrs || {}).forEach(function(key) {
600 node.attr(key, from.attrs[key]);
607 if(from.nodeType === Node.TEXT_NODE) {
608 Factory = this.TextNodeFactory;
609 } else if(from.nodeType === Node.ELEMENT_NODE) {
610 Factory = this.ElementNodeFactory;
612 return new Factory(from, this);
615 loadXML: function(xml, options) {
616 options = options || {};
617 defineDocumentProperties(this, $(parseXML(xml)));
618 if(!options.silent) {
619 this.trigger('contentSet');
624 return this.root.toXML();
627 containsNode: function(node) {
628 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
631 wrapNodes: function(params) {
632 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
633 throw new Error('Wrapping non-sibling nodes not supported.');
636 var parent = params.node1.parent(),
637 parentContents = parent.contents(),
638 wrapper = this.createDocumentNode({
639 tagName: params._with.tagName,
640 attrs: params._with.attrs}),
641 idx1 = parent.indexOf(params.node1),
642 idx2 = parent.indexOf(params.node2);
650 var insertingMethod, insertingTarget;
652 insertingMethod = 'prepend';
653 insertingTarget = parent;
655 insertingMethod = 'after';
656 insertingTarget = parentContents[idx1-1];
659 for(var i = idx1; i <= idx2; i++) {
660 wrapper.append(parentContents[i].detach());
663 insertingTarget[insertingMethod](wrapper);
667 getSiblingParents: function(params) {
668 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
669 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
670 noSiblingParents = null;
672 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
673 return noSiblingParents;
677 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
678 if(parents1[i].sameNode(parents2[i])) {
683 return {node1: parents1[i], node2: parents2[i]};
686 _wrapText: function(params) {
687 params = _.extend({textNodeIdx: 0}, params);
688 if(typeof params.textNodeIdx === 'number') {
689 params.textNodeIdx = [params.textNodeIdx];
692 var contentsInside = params.inside.contents(),
693 idx1 = Math.min.apply(Math, params.textNodeIdx),
694 idx2 = Math.max.apply(Math, params.textNodeIdx),
695 textNode1 = contentsInside[idx1],
696 textNode2 = contentsInside[idx2],
697 sameNode = textNode1.sameNode(textNode2),
698 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
699 prefixInside = textNode1.getText().substr(params.offsetStart),
700 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
701 suffixOutside = textNode2.getText().substr(params.offsetEnd)
704 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
705 throw new Error('Wrapping text in non-sibling text nodes not supported.');
708 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
709 textNode1.after(wrapperElement);
712 if(prefixOutside.length > 0) {
713 wrapperElement.before({text:prefixOutside});
716 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
717 wrapperElement.append({text: core});
720 if(prefixInside.length > 0) {
721 wrapperElement.append({text: prefixInside});
723 for(var i = idx1 + 1; i < idx2; i++) {
724 wrapperElement.append(contentsInside[i]);
726 if(suffixInside.length > 0) {
727 wrapperElement.append({text: suffixInside});
730 if(suffixOutside.length > 0) {
731 wrapperElement.after({text: suffixOutside});
733 return wrapperElement;
736 trigger: function() {
737 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
738 Backbone.Events.trigger.apply(this, arguments);
741 getNodeInsertion: function(node) {
743 if(node instanceof DocumentNode) {
744 insertion.ofNode = node;
745 insertion.insertsNew = !this.containsNode(node);
747 insertion.ofNode = this.createDocumentNode(node);
748 insertion.insertsNew = true;
753 replaceRoot: function(node) {
754 var insertion = this.getNodeInsertion(node);
756 defineDocumentProperties(this, insertion.ofNode._$);
757 insertion.ofNode.triggerChangeEvent('nodeAdded');
758 return insertion.ofNode;
761 transform: function(transformation, args) {
762 console.log('transform');
763 var Transformation, toret;
764 if(typeof transformation === 'string') {
765 Transformation = this.transformations.get(transformation);
767 transformation = new Transformation(this, this, args);
771 this._transformationLevel++;
772 toret = transformation.run();
773 if(this._transformationLevel === 1) {
774 this.undoStack.push(transformation);
776 this._transformationLevel--;
777 console.log('clearing redo stack');
781 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
785 var transformation = this.undoStack.pop();
787 transformation.undo();
788 this.redoStack.push(transformation);
792 var transformation = this.redoStack.pop();
794 transformation.run();
795 this.undoStack.push(transformation);
799 getNodeByPath: function(path) {
800 var toret = this.root;
801 path.forEach(function(idx) {
802 toret = toret.contents()[idx];
808 var defineDocumentProperties = function(doc, $document) {
809 Object.defineProperty(doc, 'root', {get: function() {
810 return doc.createDocumentNode($document[0]);
811 }, configurable: true});
812 Object.defineProperty(doc, 'dom', {get: function() {
814 }, configurable: true});
817 Document.prototype.transformations.register(transformations.createContextTransformation({
818 name: 'smartxml.wrapNodes',
819 // init: function() {
822 // getChangeRoot: function() {
823 // return this.context;
825 impl: function(args) {
826 this.wrapNodes(args);
833 documentFromXML: function(xml) {
834 return new Document(xml);
837 elementNodeFromXML: function(xml) {
838 return this.documentFromXML(xml).root;
842 DocumentNode: DocumentNode,
843 ElementNode: ElementNode