6 ], function($, _, Backbone, events) {
11 var TEXT_NODE = Node.TEXT_NODE;
14 var INSERTION = function(implementation) {
15 var toret = function(node) {
16 var insertion = this.getNodeInsertion(node),
18 if(!(this.document.containsNode(this))) {
19 nodeParent = insertion.ofNode.parent();
21 implementation.call(this, insertion.ofNode.nativeNode);
22 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent);
23 return insertion.ofNode;
28 // var TRANSFORMATION = function(name, implementation) {
29 // //implementation._isTransformation = true;
31 // createDumbTransformation(name, implementation, )
33 // return implementation;
36 var DocumentNode = function(nativeNode, document) {
38 throw new Error('undefined document for a node');
40 this.document = document;
41 this._setNativeNode(nativeNode);
45 $.extend(DocumentNode.prototype, {
46 _setNativeNode: function(nativeNode) {
47 this.nativeNode = nativeNode;
48 this._$ = $(nativeNode);
52 var clone = this._$.clone(true, true);
53 // clone.find('*').addBack().each(function() {
55 // if(n.data('canvasElement')) {
56 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
57 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
60 return this.document.createDocumentNode(clone[0]);
63 getPath: function(ancestor) {
64 var nodePath = [this].concat(this.parents()),
66 ancestor = ancestor || this.document.root;
68 nodePath.some(function(node, i) {
69 if(node.sameNode(ancestor)) {
75 if(idx !== 'undefined') {
76 nodePath = nodePath.slice(0, idx);
78 toret = nodePath.map(function(node) {return node.getIndex(); });
84 return this.document.root.sameNode(this);
88 var parent = this.parent();
90 this.triggerChangeEvent('nodeDetached', {parent: parent});
94 replaceWith: function(node) {
97 return this.document.replaceRoot(node);
99 toret = this.after(node);
104 sameNode: function(otherNode) {
105 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
109 var parentNode = this.nativeNode.parentNode;
110 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
111 return this.document.createDocumentNode(parentNode);
116 parents: function() {
117 var parent = this.parent(),
118 parents = parent ? parent.parents() : [];
120 parents.unshift(parent);
126 var myIdx = this.getIndex();
127 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
134 var myIdx = this.getIndex(),
135 parentContents = this.parent().contents();
136 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
139 isSurroundedByTextElements: function() {
140 var prev = this.prev(),
142 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
145 after: INSERTION(function(nativeNode) {
146 return this._$.after(nativeNode);
149 before: INSERTION(function(nativeNode) {
150 return this._$.before(nativeNode);
153 wrapWith: function(node) {
154 var insertion = this.getNodeInsertion(node);
156 this.before(insertion.ofNode);
158 insertion.ofNode.append(this);
159 return insertion.ofNode;
163 * Removes parent of a node if node has no siblings.
169 var parent = this.parent(),
171 if(parent.contents().length === 1) {
172 grandParent = parent.parent();
173 parent.unwrapContent();
178 triggerChangeEvent: function(type, metaData, origParent) {
179 var node = (metaData && metaData.node) ? metaData.node : this,
180 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
181 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
182 this.document.trigger('change', event);
184 if((type === 'nodeAdded' || type === 'nodeMoved') && !(this.document.containsNode(this))) {
185 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
186 this.document.trigger('change', event);
190 getNodeInsertion: function(node) {
191 return this.document.getNodeInsertion(node);
194 getIndex: function() {
198 return this.parent().indexOf(this);
202 var ElementNode = function(nativeNode, document) {
203 DocumentNode.call(this, nativeNode, document);
205 ElementNode.prototype = Object.create(DocumentNode.prototype);
207 $.extend(ElementNode.prototype, {
208 nodeType: Node.ELEMENT_NODE,
212 if(this.parent() && this.isSurroundedByTextElements()) {
214 this.prev().appendText(next.getText());
217 return DocumentNode.prototype.detach.call(this);
220 setData: function(key, value) {
221 if(value !== undefined) {
222 this._$.data(key, value);
224 this._$.removeData(_.keys(this._$.data()));
229 getData: function(key) {
231 return this._$.data(key);
233 return this._$.data();
236 getTagName: function() {
237 return this.nativeNode.tagName.toLowerCase();
240 contents: function() {
242 document = this.document;
243 this._$.contents().each(function() {
244 toret.push(document.createDocumentNode(this));
249 indexOf: function(node) {
250 return this._$.contents().index(node._$);
253 setTag: function(tagName) {
254 var node = this.document.createDocumentNode({tagName: tagName}),
255 oldTagName = this.getTagName(),
256 myContents = this._$.contents();
258 this.getAttrs().forEach(function(attribute) {
259 node.setAttr(attribute.name, attribute.value, true);
261 node.setData(this.getData());
263 if(this.sameNode(this.document.root)) {
264 defineDocumentProperties(this.document, node._$);
266 this._$.replaceWith(node._$);
267 this._setNativeNode(node._$[0]);
268 this._$.append(myContents);
269 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
272 getAttr: function(name) {
273 return this._$.attr(name);
276 setAttr: function(name, value, silent) {
277 var oldVal = this.getAttr(name);
278 this._$.attr(name, value);
280 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
284 getAttrs: function() {
286 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
287 toret.push(this.nativeNode.attributes[i]);
292 append: INSERTION(function(nativeNode) {
293 this._$.append(nativeNode);
296 prepend: INSERTION(function(nativeNode) {
297 this._$.prepend(nativeNode);
300 insertAtIndex: function(nativeNode, index) {
301 var contents = this.contents();
302 if(index < contents.length) {
303 return contents[index].before(nativeNode);
304 } else if(index === contents.length) {
305 return this.append(nativeNode);
309 unwrapContent: function() {
310 var parent = this.parent();
315 var myContents = this.contents(),
316 myIdx = parent.indexOf(this);
319 if(myContents.length === 0) {
320 return this.detach();
323 var prev = this.prev(),
325 moveLeftRange, moveRightRange, leftMerged;
327 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
328 prev.appendText(myContents[0].getText());
329 myContents[0].detach();
330 moveLeftRange = true;
336 if(!(leftMerged && myContents.length === 1)) {
337 var lastContents = _.last(myContents);
338 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
339 next.prependText(lastContents.getText());
340 lastContents.detach();
341 moveRightRange = true;
345 var childrenLength = this.contents().length;
346 this.contents().forEach(function(child) {
353 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
354 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
358 wrapText: function(params) {
359 return this.document._wrapText(_.extend({inside: this}, params));
363 var wrapper = $('<div>');
364 wrapper.append(this._getXMLDOMToDump());
365 return wrapper.html();
368 _getXMLDOMToDump: function() {
373 var TextNode = function(nativeNode, document) {
374 DocumentNode.call(this, nativeNode, document);
376 TextNode.prototype = Object.create(DocumentNode.prototype);
378 $.extend(TextNode.prototype, {
379 nodeType: Node.TEXT_NODE,
381 getText: function() {
382 return this.nativeNode.data;
385 setText: function(text) {
386 console.log('smartxml: ' + text);
387 this.nativeNode.data = text;
388 this.triggerTextChangeEvent();
391 appendText: function(text) {
392 this.nativeNode.data = this.nativeNode.data + text;
393 this.triggerTextChangeEvent();
396 prependText: function(text) {
397 this.nativeNode.data = text + this.nativeNode.data;
398 this.triggerTextChangeEvent();
401 wrapWith: function(desc) {
402 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
403 return this.document._wrapText({
404 inside: this.parent(),
405 textNodeIdx: this.parent().indexOf(this),
406 offsetStart: Math.min(desc.start, desc.end),
407 offsetEnd: Math.max(desc.start, desc.end),
408 _with: {tagName: desc.tagName, attrs: desc.attrs}
411 return DocumentNode.prototype.wrapWith.call(this, desc);
415 split: function(params) {
416 var parentElement = this.parent(),
418 succeedingChildren = [],
419 prefix = this.getText().substr(0, params.offset),
420 suffix = this.getText().substr(params.offset);
422 parentElement.contents().forEach(function(child) {
424 succeedingChildren.push(child);
426 if(child.sameNode(this)) {
431 if(prefix.length > 0) {
432 this.setText(prefix);
439 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
440 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
441 parentElement.after(newElement);
443 if(suffix.length > 0) {
444 newElement.append({text: suffix});
446 succeedingChildren.forEach(function(child) {
447 newElement.append(child);
450 return {first: parentElement, second: newElement};
453 triggerTextChangeEvent: function() {
454 var event = new events.ChangeEvent('nodeTextChange', {node: this});
455 this.document.trigger('change', event);
460 var parseXML = function(xml) {
461 return $($.trim(xml))[0];
464 var Document = function(xml) {
470 $.extend(Document.prototype, Backbone.Events, {
471 ElementNodeFactory: ElementNode,
472 TextNodeFactory: TextNode,
474 createDocumentNode: function(from) {
475 if(!(from instanceof Node)) {
476 if(from.text !== undefined) {
477 /* globals document */
478 from = document.createTextNode(from.text);
480 var node = $('<' + from.tagName + '>');
482 _.keys(from.attrs || {}).forEach(function(key) {
483 node.attr(key, from.attrs[key]);
490 if(from.nodeType === Node.TEXT_NODE) {
491 Factory = this.TextNodeFactory;
492 } else if(from.nodeType === Node.ELEMENT_NODE) {
493 Factory = this.ElementNodeFactory;
495 return new Factory(from, this);
498 loadXML: function(xml, options) {
499 options = options || {};
500 defineDocumentProperties(this, $(parseXML(xml)));
501 if(!options.silent) {
502 this.trigger('contentSet');
507 return this.root.toXML();
510 containsNode: function(node) {
511 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
514 wrapNodes: function(params) {
515 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
516 throw new Error('Wrapping non-sibling nodes not supported.');
519 var parent = params.node1.parent(),
520 parentContents = parent.contents(),
521 wrapper = this.createDocumentNode({
522 tagName: params._with.tagName,
523 attrs: params._with.attrs}),
524 idx1 = parent.indexOf(params.node1),
525 idx2 = parent.indexOf(params.node2);
533 var insertingMethod, insertingTarget;
535 insertingMethod = 'prepend';
536 insertingTarget = parent;
538 insertingMethod = 'after';
539 insertingTarget = parentContents[idx1-1];
542 for(var i = idx1; i <= idx2; i++) {
543 wrapper.append(parentContents[i].detach());
546 insertingTarget[insertingMethod](wrapper);
550 getSiblingParents: function(params) {
551 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
552 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
553 noSiblingParents = null;
555 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
556 return noSiblingParents;
560 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
561 if(parents1[i].sameNode(parents2[i])) {
566 return {node1: parents1[i], node2: parents2[i]};
569 _wrapText: function(params) {
570 params = _.extend({textNodeIdx: 0}, params);
571 if(typeof params.textNodeIdx === 'number') {
572 params.textNodeIdx = [params.textNodeIdx];
575 var contentsInside = params.inside.contents(),
576 idx1 = Math.min.apply(Math, params.textNodeIdx),
577 idx2 = Math.max.apply(Math, params.textNodeIdx),
578 textNode1 = contentsInside[idx1],
579 textNode2 = contentsInside[idx2],
580 sameNode = textNode1.sameNode(textNode2),
581 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
582 prefixInside = textNode1.getText().substr(params.offsetStart),
583 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
584 suffixOutside = textNode2.getText().substr(params.offsetEnd)
587 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
588 throw new Error('Wrapping text in non-sibling text nodes not supported.');
591 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
592 textNode1.after(wrapperElement);
595 if(prefixOutside.length > 0) {
596 wrapperElement.before({text:prefixOutside});
599 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
600 wrapperElement.append({text: core});
603 if(prefixInside.length > 0) {
604 wrapperElement.append({text: prefixInside});
606 for(var i = idx1 + 1; i < idx2; i++) {
607 wrapperElement.append(contentsInside[i]);
609 if(suffixInside.length > 0) {
610 wrapperElement.append({text: suffixInside});
613 if(suffixOutside.length > 0) {
614 wrapperElement.after({text: suffixOutside});
616 return wrapperElement;
619 trigger: function() {
620 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
621 Backbone.Events.trigger.apply(this, arguments);
624 getNodeInsertion: function(node) {
626 if(node instanceof DocumentNode) {
627 insertion.ofNode = node;
628 insertion.insertsNew = !this.containsNode(node);
630 insertion.ofNode = this.createDocumentNode(node);
631 insertion.insertsNew = true;
636 replaceRoot: function(node) {
637 var insertion = this.getNodeInsertion(node);
639 defineDocumentProperties(this, insertion.ofNode._$);
640 insertion.ofNode.triggerChangeEvent('nodeAdded');
641 return insertion.ofNode;
644 transform: function(transformationName, args) {
645 console.log('transform');
646 var Transformation = transformations[transformationName],
649 transformation = new Transformation(args);
650 transformation.run();
651 this.undoStack.push(transformation);
652 console.log('clearing redo stack');
655 throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
659 var transformation = this.undoStack.pop();
661 transformation.undo();
662 this.redoStack.push(transformation);
666 var transformation = this.redoStack.pop();
668 transformation.run();
669 this.undoStack.push(transformation);
673 getNodeByPath: function(path) {
674 var toret = this.root;
675 path.forEach(function(idx) {
676 toret = toret.contents()[idx];
682 var defineDocumentProperties = function(doc, $document) {
683 Object.defineProperty(doc, 'root', {get: function() {
684 return doc.createDocumentNode($document[0]);
685 }, configurable: true});
686 Object.defineProperty(doc, 'dom', {get: function() {
688 }, configurable: true});
692 // var registerTransformationsFromObject = function(object) {
693 // _.values(object).filter(function(val) {
694 // return typeof val === 'function' && val._isTransformation;
696 // .forEach(function(val) {
697 // registerTransformation(val._transformationName, val, object);
700 // registerTransformationsFromObject(ElementNode.prototype);
701 // registerTransformationsFromObject(TextNode.prototype);
702 // registerTransformationsFromObject(Document.prototype);
704 // var Transformation = function() {
706 // $.extend(Transformation.prototype, {
711 // var createDumbTransformation = function(impl, contextObject) {
712 // var DumbTransformation = function(args) {
713 // this.args = this.args;
715 // DumbTransformation.prototype = Object.create(Transformation.prototype);
716 // $.extend(DumbTransformation.prototype, {
718 // impl.apply(contextObject, this.args);
722 // return DumbTransformation;
727 var transformations = {};
728 // var registerTransformation = function(name, impl, contextObject) {
729 // if(typeof impl === 'function') {
730 // transformations[name] = createDumbTransformation(impl, contextObject);
734 // registerTransformation('detachx', DocumentNode.prototype.detach, )
737 // 1. detach via totalny fallback
738 var DetachNodeTransformation = function(args) {
739 this.node = args.node;
740 this.document = this.node.document;
742 $.extend(DetachNodeTransformation.prototype, {
744 this.oldRoot = this.node.document.root.clone();
745 this.path = this.node.getPath();
746 this.node.detach(); // @TS
750 this.document.root.replaceWith(this.oldRoot); // this.getDocument?
751 this.node = this.document.getNodeByPath(this.path);
754 transformations['detach'] = DetachNodeTransformation;
756 //2. detach via wskazanie changeroot
758 var Detach2NodeTransformation = function(args) {
759 this.nodePath = args.node.getPath();
760 this.document = args.node.document;
762 $.extend(Detach2NodeTransformation.prototype, {
764 var node = this.document.getNodeByPath(this.nodePath),
765 root = node.parent() ? node.parent() : this.document.root;
767 this.rootPath = root.getPath();
768 this.oldRoot = (root).clone();
772 this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
775 //transformations['detach2'] = Detach2NodeTransformation;
777 //2a. generyczna transformacja
779 var createTransformation = function(desc) {
781 var NodeTransformation = function(args) {
782 this.nodePath = args.node.getPath();
783 this.document = args.node.document;
786 $.extend(NodeTransformation.prototype, {
788 var node = this.document.getNodeByPath(this.nodePath),
792 root = desc.getRoot(node);
794 root = this.document.root;
797 this.rootPath = root.getPath();
798 this.oldRoot = (root).clone();
799 desc.impl.call(node, this.args);
802 this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
806 return NodeTransformation;
809 transformations['detach2'] = createTransformation({
810 // impl: function() {
811 // //this.setAttr('class', 'cite'); //
813 impl: ElementNode.prototype.detach,
814 getRoot: function(node) {
815 return node.parent();
820 transformations['setText'] = createTransformation({
821 impl: function(args) {
822 this.setText(args.text)
824 getRoot: function(node) {
830 //3. detach z pełnym własnym redo
832 var Detach3NodeTransformation = function(args) {
833 this.node = args.node;
834 this.document = this.node.document;
836 $.extend(Detach3NodeTransformation.prototype, {
838 //this.index = this.node.getIndex();
839 //this.parent = this.node.parent();
841 this.path = this.node.getPath();
842 if(this.node.isSurroundedByTextElements()) {
843 this.prevText = this.node.prev().getText();
844 this.nextText = this.node.next().getText();
847 this.prevText = this.nextText = null;
854 var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
855 idx = _.last(this.path);
856 var inserted = parent.insertAtIndex(this.node, idx);
858 if(inserted.next()) {
859 inserted.before({text: this.prevText});
860 inserted.next().setText(this.nextText);
862 inserted.prev().setText(this.prevText);
863 inserted.after({text: this.nextText});
868 transformations['detach3'] = Detach3NodeTransformation;
871 documentFromXML: function(xml) {
872 return new Document(xml);
875 elementNodeFromXML: function(xml) {
876 return this.documentFromXML(xml).root;
880 DocumentNode: DocumentNode,
881 ElementNode: ElementNode