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),
18 nodeWasContained = this.document.containsNode(insertion.ofNode),
20 if(!(this.document.containsNode(this))) {
21 nodeParent = insertion.ofNode.parent();
23 implementation.call(this, insertion.ofNode.nativeNode);
24 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent, nodeWasContained);
25 return insertion.ofNode;
30 var DocumentNode = function(nativeNode, document) {
32 throw new Error('undefined document for a node');
34 this.document = document;
35 this._setNativeNode(nativeNode);
39 $.extend(DocumentNode.prototype, {
41 transformations: new transformations.TransformationStorage(),
43 transform: function(name, args) {
44 var Transformation = this.transformations.get(name),
47 transformation = new Transformation(this.document, this, args);
49 return this.document.transform(transformation);
52 _setNativeNode: function(nativeNode) {
53 this.nativeNode = nativeNode;
54 this._$ = $(nativeNode);
58 var clone = this._$.clone(true, true);
59 // clone.find('*').addBack().each(function() {
61 // if(n.data('canvasElement')) {
62 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
63 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
66 return this.document.createDocumentNode(clone[0]);
69 getPath: function(ancestor) {
70 var nodePath = [this].concat(this.parents()),
72 ancestor = ancestor || this.document.root;
74 nodePath.some(function(node, i) {
75 if(node.sameNode(ancestor)) {
81 if(idx !== 'undefined') {
82 nodePath = nodePath.slice(0, idx);
84 toret = nodePath.map(function(node) {return node.getIndex(); });
90 return this.document.root.sameNode(this);
94 var parent = this.parent();
96 this.triggerChangeEvent('nodeDetached', {parent: parent});
100 replaceWith: function(node) {
103 return this.document.replaceRoot(node);
105 toret = this.after(node);
110 sameNode: function(otherNode) {
111 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
115 var parentNode = this.nativeNode.parentNode;
116 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
117 return this.document.createDocumentNode(parentNode);
122 parents: function() {
123 var parent = this.parent(),
124 parents = parent ? parent.parents() : [];
126 parents.unshift(parent);
132 var myIdx = this.getIndex();
133 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
140 var myIdx = this.getIndex(),
141 parentContents = this.parent().contents();
142 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
145 isSurroundedByTextElements: function() {
146 var prev = this.prev(),
148 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
151 after: INSERTION(function(nativeNode) {
152 return this._$.after(nativeNode);
155 before: INSERTION(function(nativeNode) {
156 return this._$.before(nativeNode);
159 wrapWith: function(node) {
160 var insertion = this.getNodeInsertion(node);
162 this.before(insertion.ofNode);
164 insertion.ofNode.append(this);
165 return insertion.ofNode;
169 * Removes parent of a node if node has no siblings.
175 var parent = this.parent(),
177 if(parent.contents().length === 1) {
178 grandParent = parent.parent();
179 parent.unwrapContent();
184 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
185 var node = (metaData && metaData.node) ? metaData.node : this,
186 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
187 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
188 this.document.trigger('change', event);
190 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
191 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
192 this.document.trigger('change', event);
196 getNodeInsertion: function(node) {
197 return this.document.getNodeInsertion(node);
200 getIndex: function() {
204 return this.parent().indexOf(this);
208 var ElementNode = function(nativeNode, document) {
209 DocumentNode.call(this, nativeNode, document);
211 ElementNode.prototype = Object.create(DocumentNode.prototype);
213 $.extend(ElementNode.prototype, {
214 nodeType: Node.ELEMENT_NODE,
218 if(this.parent() && this.isSurroundedByTextElements()) {
220 this.prev().appendText(next.getText());
223 return DocumentNode.prototype.detach.call(this);
226 setData: function(key, value) {
227 if(value !== undefined) {
228 this._$.data(key, value);
230 this._$.removeData(_.keys(this._$.data()));
235 getData: function(key) {
237 return this._$.data(key);
239 return this._$.data();
242 getTagName: function() {
243 return this.nativeNode.tagName.toLowerCase();
246 contents: function(selector) {
248 document = this.document;
250 this._$.children(selector).each(function() {
251 toret.push(document.createDocumentNode(this));
254 this._$.contents().each(function() {
255 toret.push(document.createDocumentNode(this));
261 indexOf: function(node) {
262 return this._$.contents().index(node._$);
265 setTag: function(tagName) {
266 var node = this.document.createDocumentNode({tagName: tagName}),
267 oldTagName = this.getTagName(),
268 myContents = this._$.contents();
270 this.getAttrs().forEach(function(attribute) {
271 node.setAttr(attribute.name, attribute.value, true);
273 node.setData(this.getData());
275 if(this.sameNode(this.document.root)) {
276 defineDocumentProperties(this.document, node._$);
278 this._$.replaceWith(node._$);
279 this._setNativeNode(node._$[0]);
280 this._$.append(myContents);
281 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
284 getAttr: function(name) {
285 return this._$.attr(name);
288 setAttr: function(name, value, silent) {
289 var oldVal = this.getAttr(name);
290 this._$.attr(name, value);
292 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
296 getAttrs: function() {
298 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
299 toret.push(this.nativeNode.attributes[i]);
304 append: INSERTION(function(nativeNode) {
305 this._$.append(nativeNode);
308 prepend: INSERTION(function(nativeNode) {
309 this._$.prepend(nativeNode);
312 insertAtIndex: function(nativeNode, index) {
313 var contents = this.contents();
314 if(index < contents.length) {
315 return contents[index].before(nativeNode);
316 } else if(index === contents.length) {
317 return this.append(nativeNode);
321 unwrapContent: function() {
322 var parent = this.parent();
327 var myContents = this.contents(),
328 myIdx = parent.indexOf(this);
331 if(myContents.length === 0) {
332 return this.detach();
335 var prev = this.prev(),
337 moveLeftRange, moveRightRange, leftMerged;
339 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
340 prev.appendText(myContents[0].getText());
341 myContents[0].detach();
342 moveLeftRange = true;
348 if(!(leftMerged && myContents.length === 1)) {
349 var lastContents = _.last(myContents);
350 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
351 next.prependText(lastContents.getText());
352 lastContents.detach();
353 moveRightRange = true;
357 var childrenLength = this.contents().length;
358 this.contents().forEach(function(child) {
365 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
366 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
370 wrapText: function(params) {
371 return this.document._wrapText(_.extend({inside: this}, params));
375 var wrapper = $('<div>');
376 wrapper.append(this._getXMLDOMToDump());
377 return wrapper.html();
380 _getXMLDOMToDump: function() {
387 // todo - split+append
389 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
390 name: 'smartxml.setAttr',
391 impl: function(args) {
392 this.setAttr(args.name, args.value);
394 getChangeRoot: function() {
399 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
400 name: 'smartxml.setAttr2',
401 impl: function(args) {
402 this.prevAttr = this.getAttr(args.name);
403 this.setAttr(args.name, args.value);
405 undo: function(args) {
406 this.setAttr(args.name, this.prevAttr);
410 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
411 name: 'smartxml.wrapWith',
412 getChangeRoot: function() {
413 return this.context.parent();
415 impl: function(args) {
416 return this.wrapWith(args);
420 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
421 name: 'smartxml.wrapText',
422 getChangeRoot: function() {
425 impl: function(args) {
426 return this.wrapText(args);
430 DocumentNode.prototype.transformations.register(transformations.createContextTransformation({
431 name: 'smartxml.detach',
432 getChangeRoot: function() {
433 return this.context.parent();
435 impl: function(args) {
436 return this.detach();
442 var TextNode = function(nativeNode, document) {
443 DocumentNode.call(this, nativeNode, document);
445 TextNode.prototype = Object.create(DocumentNode.prototype);
447 $.extend(TextNode.prototype, {
448 nodeType: Node.TEXT_NODE,
450 getText: function() {
451 return this.nativeNode.data;
454 setText: function(text) {
455 //console.log('smartxml: ' + text);
456 this.nativeNode.data = text;
457 this.triggerTextChangeEvent();
460 appendText: function(text) {
461 this.nativeNode.data = this.nativeNode.data + text;
462 this.triggerTextChangeEvent();
465 prependText: function(text) {
466 this.nativeNode.data = text + this.nativeNode.data;
467 this.triggerTextChangeEvent();
470 wrapWith: function(desc) {
471 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
472 return this.document._wrapText({
473 inside: this.parent(),
474 textNodeIdx: this.parent().indexOf(this),
475 offsetStart: Math.min(desc.start, desc.end),
476 offsetEnd: Math.max(desc.start, desc.end),
477 _with: {tagName: desc.tagName, attrs: desc.attrs}
480 return DocumentNode.prototype.wrapWith.call(this, desc);
484 split: function(params) {
485 var parentElement = this.parent(),
487 succeedingChildren = [],
488 prefix = this.getText().substr(0, params.offset),
489 suffix = this.getText().substr(params.offset);
491 parentElement.contents().forEach(function(child) {
493 succeedingChildren.push(child);
495 if(child.sameNode(this)) {
500 if(prefix.length > 0) {
501 this.setText(prefix);
508 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
509 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
510 parentElement.after(newElement);
512 if(suffix.length > 0) {
513 newElement.append({text: suffix});
515 succeedingChildren.forEach(function(child) {
516 newElement.append(child);
519 return {first: parentElement, second: newElement};
522 triggerTextChangeEvent: function() {
523 var event = new events.ChangeEvent('nodeTextChange', {node: this});
524 this.document.trigger('change', event);
529 TextNode.prototype.transformations.register(transformations.createContextTransformation({
530 name: 'rng.breakContent',
531 // impl: function(args) {
532 // var node = this.context,
533 // newNodes, emptyNode, emptyText;
534 // newNodes = node.transform('smartxml.split', {offset: args.offset});
535 // [newNodes.first, newNodes.second].some(function(newNode) {
536 // if(!(newNode.contents().length)) {
537 // newNode.transform('smartxml.append', {text: ''});
538 // return true; // break
541 // return _.extend(newNodes, {emptyText: emptyText});
543 impl: function(args) {
545 newNodes, emptyNode, emptyText;
546 newNodes = node.split({offset: args.offset});
547 [newNodes.first, newNodes.second].some(function(newNode) {
548 if(!(newNode.contents().length)) {
549 newNode.append({text: ''});
550 return true; // break
553 return _.extend(newNodes, {emptyText: emptyText});
555 getChangeRoot: function() {
556 return this.context.parent().parent();
558 isAllowed: function(args) {
559 var parent = this.parent();
560 return !!(parent && parent.parent());
565 ElementNode.prototype.transformations.register(transformations.createContextTransformation({
566 name: 'smartxml.setText',
567 impl: function(args) {
568 this.setText(args.text);
570 getChangeRoot: function() {
576 var parseXML = function(xml) {
577 return $($.trim(xml))[0];
580 var Document = function(xml) {
584 this._transformationLevel = 0;
585 this.transformations = new transformations.TransformationStorage();
589 $.extend(Document.prototype, Backbone.Events, {
590 ElementNodeFactory: ElementNode,
591 TextNodeFactory: TextNode,
592 transformations: new transformations.TransformationStorage(),
594 createDocumentNode: function(from) {
595 if(!(from instanceof Node)) {
596 if(from.text !== undefined) {
597 /* globals document */
598 from = document.createTextNode(from.text);
600 var node = $('<' + from.tagName + '>');
602 _.keys(from.attrs || {}).forEach(function(key) {
603 node.attr(key, from.attrs[key]);
610 if(from.nodeType === Node.TEXT_NODE) {
611 Factory = this.TextNodeFactory;
612 } else if(from.nodeType === Node.ELEMENT_NODE) {
613 Factory = this.ElementNodeFactory;
615 return new Factory(from, this);
618 loadXML: function(xml, options) {
619 options = options || {};
620 defineDocumentProperties(this, $(parseXML(xml)));
621 if(!options.silent) {
622 this.trigger('contentSet');
627 return this.root.toXML();
630 containsNode: function(node) {
631 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
634 wrapNodes: function(params) {
635 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
636 throw new Error('Wrapping non-sibling nodes not supported.');
639 var parent = params.node1.parent(),
640 parentContents = parent.contents(),
641 wrapper = this.createDocumentNode({
642 tagName: params._with.tagName,
643 attrs: params._with.attrs}),
644 idx1 = parent.indexOf(params.node1),
645 idx2 = parent.indexOf(params.node2);
653 var insertingMethod, insertingTarget;
655 insertingMethod = 'prepend';
656 insertingTarget = parent;
658 insertingMethod = 'after';
659 insertingTarget = parentContents[idx1-1];
662 for(var i = idx1; i <= idx2; i++) {
663 wrapper.append(parentContents[i].detach());
666 insertingTarget[insertingMethod](wrapper);
670 getSiblingParents: function(params) {
671 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
672 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
673 noSiblingParents = null;
675 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
676 return noSiblingParents;
680 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
681 if(parents1[i].sameNode(parents2[i])) {
686 return {node1: parents1[i], node2: parents2[i]};
689 _wrapText: function(params) {
690 params = _.extend({textNodeIdx: 0}, params);
691 if(typeof params.textNodeIdx === 'number') {
692 params.textNodeIdx = [params.textNodeIdx];
695 var contentsInside = params.inside.contents(),
696 idx1 = Math.min.apply(Math, params.textNodeIdx),
697 idx2 = Math.max.apply(Math, params.textNodeIdx),
698 textNode1 = contentsInside[idx1],
699 textNode2 = contentsInside[idx2],
700 sameNode = textNode1.sameNode(textNode2),
701 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
702 prefixInside = textNode1.getText().substr(params.offsetStart),
703 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
704 suffixOutside = textNode2.getText().substr(params.offsetEnd)
707 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
708 throw new Error('Wrapping text in non-sibling text nodes not supported.');
711 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
712 textNode1.after(wrapperElement);
715 if(prefixOutside.length > 0) {
716 wrapperElement.before({text:prefixOutside});
719 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
720 wrapperElement.append({text: core});
723 if(prefixInside.length > 0) {
724 wrapperElement.append({text: prefixInside});
726 for(var i = idx1 + 1; i < idx2; i++) {
727 wrapperElement.append(contentsInside[i]);
729 if(suffixInside.length > 0) {
730 wrapperElement.append({text: suffixInside});
733 if(suffixOutside.length > 0) {
734 wrapperElement.after({text: suffixOutside});
736 return wrapperElement;
739 trigger: function() {
740 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
741 Backbone.Events.trigger.apply(this, arguments);
744 getNodeInsertion: function(node) {
746 if(node instanceof DocumentNode) {
747 insertion.ofNode = node;
748 insertion.insertsNew = !this.containsNode(node);
750 insertion.ofNode = this.createDocumentNode(node);
751 insertion.insertsNew = true;
756 replaceRoot: function(node) {
757 var insertion = this.getNodeInsertion(node);
759 defineDocumentProperties(this, insertion.ofNode._$);
760 insertion.ofNode.triggerChangeEvent('nodeAdded');
761 return insertion.ofNode;
764 transform: function(transformation, args) {
765 //console.log('transform');
766 var Transformation, toret;
767 if(typeof transformation === 'string') {
768 Transformation = this.transformations.get(transformation);
770 transformation = new Transformation(this, this, args);
774 this._transformationLevel++;
775 toret = transformation.run();
776 if(this._transformationLevel === 1) {
777 this.undoStack.push(transformation);
779 this._transformationLevel--;
780 //console.log('clearing redo stack');
784 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
788 var transformation = this.undoStack.pop();
790 transformation.undo();
791 this.redoStack.push(transformation);
795 var transformation = this.redoStack.pop();
797 transformation.run();
798 this.undoStack.push(transformation);
802 getNodeByPath: function(path) {
803 var toret = this.root;
804 path.forEach(function(idx) {
805 toret = toret.contents()[idx];
811 var defineDocumentProperties = function(doc, $document) {
812 Object.defineProperty(doc, 'root', {get: function() {
813 return doc.createDocumentNode($document[0]);
814 }, configurable: true});
815 Object.defineProperty(doc, 'dom', {get: function() {
817 }, configurable: true});
820 Document.prototype.transformations.register(transformations.createContextTransformation({
821 name: 'smartxml.wrapNodes',
822 // init: function() {
825 // getChangeRoot: function() {
826 // return this.context;
828 impl: function(args) {
829 this.wrapNodes(args);
836 documentFromXML: function(xml) {
837 return new Document(xml);
840 elementNodeFromXML: function(xml) {
841 return this.documentFromXML(xml).root;
845 DocumentNode: DocumentNode,
846 ElementNode: ElementNode,