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;
584 this.transformations = new transformations.TransformationStorage();
588 $.extend(Document.prototype, Backbone.Events, {
589 ElementNodeFactory: ElementNode,
590 TextNodeFactory: TextNode,
591 transformations: new transformations.TransformationStorage(),
593 createDocumentNode: function(from) {
594 if(!(from instanceof Node)) {
595 if(from.text !== undefined) {
596 /* globals document */
597 from = document.createTextNode(from.text);
599 var node = $('<' + from.tagName + '>');
601 _.keys(from.attrs || {}).forEach(function(key) {
602 node.attr(key, from.attrs[key]);
609 if(from.nodeType === Node.TEXT_NODE) {
610 Factory = this.TextNodeFactory;
611 } else if(from.nodeType === Node.ELEMENT_NODE) {
612 Factory = this.ElementNodeFactory;
614 return new Factory(from, this);
617 loadXML: function(xml, options) {
618 options = options || {};
619 defineDocumentProperties(this, $(parseXML(xml)));
620 if(!options.silent) {
621 this.trigger('contentSet');
626 return this.root.toXML();
629 containsNode: function(node) {
630 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
633 wrapNodes: function(params) {
634 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
635 throw new Error('Wrapping non-sibling nodes not supported.');
638 var parent = params.node1.parent(),
639 parentContents = parent.contents(),
640 wrapper = this.createDocumentNode({
641 tagName: params._with.tagName,
642 attrs: params._with.attrs}),
643 idx1 = parent.indexOf(params.node1),
644 idx2 = parent.indexOf(params.node2);
652 var insertingMethod, insertingTarget;
654 insertingMethod = 'prepend';
655 insertingTarget = parent;
657 insertingMethod = 'after';
658 insertingTarget = parentContents[idx1-1];
661 for(var i = idx1; i <= idx2; i++) {
662 wrapper.append(parentContents[i].detach());
665 insertingTarget[insertingMethod](wrapper);
669 getSiblingParents: function(params) {
670 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
671 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
672 noSiblingParents = null;
674 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
675 return noSiblingParents;
679 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
680 if(parents1[i].sameNode(parents2[i])) {
685 return {node1: parents1[i], node2: parents2[i]};
688 _wrapText: function(params) {
689 params = _.extend({textNodeIdx: 0}, params);
690 if(typeof params.textNodeIdx === 'number') {
691 params.textNodeIdx = [params.textNodeIdx];
694 var contentsInside = params.inside.contents(),
695 idx1 = Math.min.apply(Math, params.textNodeIdx),
696 idx2 = Math.max.apply(Math, params.textNodeIdx),
697 textNode1 = contentsInside[idx1],
698 textNode2 = contentsInside[idx2],
699 sameNode = textNode1.sameNode(textNode2),
700 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
701 prefixInside = textNode1.getText().substr(params.offsetStart),
702 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
703 suffixOutside = textNode2.getText().substr(params.offsetEnd)
706 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
707 throw new Error('Wrapping text in non-sibling text nodes not supported.');
710 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
711 textNode1.after(wrapperElement);
714 if(prefixOutside.length > 0) {
715 wrapperElement.before({text:prefixOutside});
718 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
719 wrapperElement.append({text: core});
722 if(prefixInside.length > 0) {
723 wrapperElement.append({text: prefixInside});
725 for(var i = idx1 + 1; i < idx2; i++) {
726 wrapperElement.append(contentsInside[i]);
728 if(suffixInside.length > 0) {
729 wrapperElement.append({text: suffixInside});
732 if(suffixOutside.length > 0) {
733 wrapperElement.after({text: suffixOutside});
735 return wrapperElement;
738 trigger: function() {
739 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
740 Backbone.Events.trigger.apply(this, arguments);
743 getNodeInsertion: function(node) {
745 if(node instanceof DocumentNode) {
746 insertion.ofNode = node;
747 insertion.insertsNew = !this.containsNode(node);
749 insertion.ofNode = this.createDocumentNode(node);
750 insertion.insertsNew = true;
755 replaceRoot: function(node) {
756 var insertion = this.getNodeInsertion(node);
758 defineDocumentProperties(this, insertion.ofNode._$);
759 insertion.ofNode.triggerChangeEvent('nodeAdded');
760 return insertion.ofNode;
763 transform: function(transformation, args) {
764 console.log('transform');
765 var Transformation, toret;
766 if(typeof transformation === 'string') {
767 Transformation = this.transformations.get(transformation);
769 transformation = new Transformation(this, this, args);
773 this._transformationLevel++;
774 toret = transformation.run();
775 if(this._transformationLevel === 1) {
776 this.undoStack.push(transformation);
778 this._transformationLevel--;
779 console.log('clearing redo stack');
783 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
787 var transformation = this.undoStack.pop();
789 transformation.undo();
790 this.redoStack.push(transformation);
794 var transformation = this.redoStack.pop();
796 transformation.run();
797 this.undoStack.push(transformation);
801 getNodeByPath: function(path) {
802 var toret = this.root;
803 path.forEach(function(idx) {
804 toret = toret.contents()[idx];
810 var defineDocumentProperties = function(doc, $document) {
811 Object.defineProperty(doc, 'root', {get: function() {
812 return doc.createDocumentNode($document[0]);
813 }, configurable: true});
814 Object.defineProperty(doc, 'dom', {get: function() {
816 }, configurable: true});
819 Document.prototype.transformations.register(transformations.createContextTransformation({
820 name: 'smartxml.wrapNodes',
821 // init: function() {
824 // getChangeRoot: function() {
825 // return this.context;
827 impl: function(args) {
828 this.wrapNodes(args);
835 documentFromXML: function(xml) {
836 return new Document(xml);
839 elementNodeFromXML: function(xml) {
840 return this.documentFromXML(xml).root;
844 DocumentNode: DocumentNode,
845 ElementNode: ElementNode,