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, {
47 transform: function(name, args) {
48 var Transformation = contextTransformations[name],
51 transformation = new Transformation(this.document, this, args);
53 return this.document.transform(transformation);
56 _setNativeNode: function(nativeNode) {
57 this.nativeNode = nativeNode;
58 this._$ = $(nativeNode);
62 var clone = this._$.clone(true, true);
63 // clone.find('*').addBack().each(function() {
65 // if(n.data('canvasElement')) {
66 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
67 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
70 return this.document.createDocumentNode(clone[0]);
73 getPath: function(ancestor) {
74 var nodePath = [this].concat(this.parents()),
76 ancestor = ancestor || this.document.root;
78 nodePath.some(function(node, i) {
79 if(node.sameNode(ancestor)) {
85 if(idx !== 'undefined') {
86 nodePath = nodePath.slice(0, idx);
88 toret = nodePath.map(function(node) {return node.getIndex(); });
94 return this.document.root.sameNode(this);
98 var parent = this.parent();
100 this.triggerChangeEvent('nodeDetached', {parent: parent});
104 replaceWith: function(node) {
107 return this.document.replaceRoot(node);
109 toret = this.after(node);
114 sameNode: function(otherNode) {
115 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
119 var parentNode = this.nativeNode.parentNode;
120 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
121 return this.document.createDocumentNode(parentNode);
126 parents: function() {
127 var parent = this.parent(),
128 parents = parent ? parent.parents() : [];
130 parents.unshift(parent);
136 var myIdx = this.getIndex();
137 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
144 var myIdx = this.getIndex(),
145 parentContents = this.parent().contents();
146 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
149 isSurroundedByTextElements: function() {
150 var prev = this.prev(),
152 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
155 after: INSERTION(function(nativeNode) {
156 return this._$.after(nativeNode);
159 before: INSERTION(function(nativeNode) {
160 return this._$.before(nativeNode);
163 wrapWith: function(node) {
164 var insertion = this.getNodeInsertion(node);
166 this.before(insertion.ofNode);
168 insertion.ofNode.append(this);
169 return insertion.ofNode;
173 * Removes parent of a node if node has no siblings.
179 var parent = this.parent(),
181 if(parent.contents().length === 1) {
182 grandParent = parent.parent();
183 parent.unwrapContent();
188 triggerChangeEvent: function(type, metaData, origParent) {
189 var node = (metaData && metaData.node) ? metaData.node : this,
190 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
191 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
192 this.document.trigger('change', event);
194 if((type === 'nodeAdded' || type === 'nodeMoved') && !(this.document.containsNode(this))) {
195 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
196 this.document.trigger('change', event);
200 getNodeInsertion: function(node) {
201 return this.document.getNodeInsertion(node);
204 getIndex: function() {
208 return this.parent().indexOf(this);
212 var ElementNode = function(nativeNode, document) {
213 DocumentNode.call(this, nativeNode, document);
215 ElementNode.prototype = Object.create(DocumentNode.prototype);
217 $.extend(ElementNode.prototype, {
218 nodeType: Node.ELEMENT_NODE,
222 if(this.parent() && this.isSurroundedByTextElements()) {
224 this.prev().appendText(next.getText());
227 return DocumentNode.prototype.detach.call(this);
230 setData: function(key, value) {
231 if(value !== undefined) {
232 this._$.data(key, value);
234 this._$.removeData(_.keys(this._$.data()));
239 getData: function(key) {
241 return this._$.data(key);
243 return this._$.data();
246 getTagName: function() {
247 return this.nativeNode.tagName.toLowerCase();
250 contents: function() {
252 document = this.document;
253 this._$.contents().each(function() {
254 toret.push(document.createDocumentNode(this));
259 indexOf: function(node) {
260 return this._$.contents().index(node._$);
263 setTag: function(tagName) {
264 var node = this.document.createDocumentNode({tagName: tagName}),
265 oldTagName = this.getTagName(),
266 myContents = this._$.contents();
268 this.getAttrs().forEach(function(attribute) {
269 node.setAttr(attribute.name, attribute.value, true);
271 node.setData(this.getData());
273 if(this.sameNode(this.document.root)) {
274 defineDocumentProperties(this.document, node._$);
276 this._$.replaceWith(node._$);
277 this._setNativeNode(node._$[0]);
278 this._$.append(myContents);
279 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
282 getAttr: function(name) {
283 return this._$.attr(name);
286 setAttr: function(name, value, silent) {
287 var oldVal = this.getAttr(name);
288 this._$.attr(name, value);
290 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
294 getAttrs: function() {
296 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
297 toret.push(this.nativeNode.attributes[i]);
302 append: INSERTION(function(nativeNode) {
303 this._$.append(nativeNode);
306 prepend: INSERTION(function(nativeNode) {
307 this._$.prepend(nativeNode);
310 insertAtIndex: function(nativeNode, index) {
311 var contents = this.contents();
312 if(index < contents.length) {
313 return contents[index].before(nativeNode);
314 } else if(index === contents.length) {
315 return this.append(nativeNode);
319 unwrapContent: function() {
320 var parent = this.parent();
325 var myContents = this.contents(),
326 myIdx = parent.indexOf(this);
329 if(myContents.length === 0) {
330 return this.detach();
333 var prev = this.prev(),
335 moveLeftRange, moveRightRange, leftMerged;
337 if(prev && (prev.nodeType === TEXT_NODE) && (myContents[0].nodeType === TEXT_NODE)) {
338 prev.appendText(myContents[0].getText());
339 myContents[0].detach();
340 moveLeftRange = true;
346 if(!(leftMerged && myContents.length === 1)) {
347 var lastContents = _.last(myContents);
348 if(next && (next.nodeType === TEXT_NODE) && (lastContents.nodeType === TEXT_NODE)) {
349 next.prependText(lastContents.getText());
350 lastContents.detach();
351 moveRightRange = true;
355 var childrenLength = this.contents().length;
356 this.contents().forEach(function(child) {
363 element1: parent.contents()[myIdx + (moveLeftRange ? -1 : 0)],
364 element2: parent.contents()[myIdx + childrenLength-1 + (moveRightRange ? 1 : 0)]
368 wrapText: function(params) {
369 return this.document._wrapText(_.extend({inside: this}, params));
373 var wrapper = $('<div>');
374 wrapper.append(this._getXMLDOMToDump());
375 return wrapper.html();
378 _getXMLDOMToDump: function() {
383 var TextNode = function(nativeNode, document) {
384 DocumentNode.call(this, nativeNode, document);
386 TextNode.prototype = Object.create(DocumentNode.prototype);
388 $.extend(TextNode.prototype, {
389 nodeType: Node.TEXT_NODE,
391 getText: function() {
392 return this.nativeNode.data;
395 setText: function(text) {
396 console.log('smartxml: ' + text);
397 this.nativeNode.data = text;
398 this.triggerTextChangeEvent();
401 appendText: function(text) {
402 this.nativeNode.data = this.nativeNode.data + text;
403 this.triggerTextChangeEvent();
406 prependText: function(text) {
407 this.nativeNode.data = text + this.nativeNode.data;
408 this.triggerTextChangeEvent();
411 wrapWith: function(desc) {
412 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
413 return this.document._wrapText({
414 inside: this.parent(),
415 textNodeIdx: this.parent().indexOf(this),
416 offsetStart: Math.min(desc.start, desc.end),
417 offsetEnd: Math.max(desc.start, desc.end),
418 _with: {tagName: desc.tagName, attrs: desc.attrs}
421 return DocumentNode.prototype.wrapWith.call(this, desc);
425 split: function(params) {
426 var parentElement = this.parent(),
428 succeedingChildren = [],
429 prefix = this.getText().substr(0, params.offset),
430 suffix = this.getText().substr(params.offset);
432 parentElement.contents().forEach(function(child) {
434 succeedingChildren.push(child);
436 if(child.sameNode(this)) {
441 if(prefix.length > 0) {
442 this.setText(prefix);
449 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
450 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
451 parentElement.after(newElement);
453 if(suffix.length > 0) {
454 newElement.append({text: suffix});
456 succeedingChildren.forEach(function(child) {
457 newElement.append(child);
460 return {first: parentElement, second: newElement};
463 triggerTextChangeEvent: function() {
464 var event = new events.ChangeEvent('nodeTextChange', {node: this});
465 this.document.trigger('change', event);
470 var parseXML = function(xml) {
471 return $($.trim(xml))[0];
474 var Document = function(xml) {
480 $.extend(Document.prototype, Backbone.Events, {
481 ElementNodeFactory: ElementNode,
482 TextNodeFactory: TextNode,
484 createDocumentNode: function(from) {
485 if(!(from instanceof Node)) {
486 if(from.text !== undefined) {
487 /* globals document */
488 from = document.createTextNode(from.text);
490 var node = $('<' + from.tagName + '>');
492 _.keys(from.attrs || {}).forEach(function(key) {
493 node.attr(key, from.attrs[key]);
500 if(from.nodeType === Node.TEXT_NODE) {
501 Factory = this.TextNodeFactory;
502 } else if(from.nodeType === Node.ELEMENT_NODE) {
503 Factory = this.ElementNodeFactory;
505 return new Factory(from, this);
508 loadXML: function(xml, options) {
509 options = options || {};
510 defineDocumentProperties(this, $(parseXML(xml)));
511 if(!options.silent) {
512 this.trigger('contentSet');
517 return this.root.toXML();
520 containsNode: function(node) {
521 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
524 wrapNodes: function(params) {
525 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
526 throw new Error('Wrapping non-sibling nodes not supported.');
529 var parent = params.node1.parent(),
530 parentContents = parent.contents(),
531 wrapper = this.createDocumentNode({
532 tagName: params._with.tagName,
533 attrs: params._with.attrs}),
534 idx1 = parent.indexOf(params.node1),
535 idx2 = parent.indexOf(params.node2);
543 var insertingMethod, insertingTarget;
545 insertingMethod = 'prepend';
546 insertingTarget = parent;
548 insertingMethod = 'after';
549 insertingTarget = parentContents[idx1-1];
552 for(var i = idx1; i <= idx2; i++) {
553 wrapper.append(parentContents[i].detach());
556 insertingTarget[insertingMethod](wrapper);
560 getSiblingParents: function(params) {
561 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
562 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
563 noSiblingParents = null;
565 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
566 return noSiblingParents;
570 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
571 if(parents1[i].sameNode(parents2[i])) {
576 return {node1: parents1[i], node2: parents2[i]};
579 _wrapText: function(params) {
580 params = _.extend({textNodeIdx: 0}, params);
581 if(typeof params.textNodeIdx === 'number') {
582 params.textNodeIdx = [params.textNodeIdx];
585 var contentsInside = params.inside.contents(),
586 idx1 = Math.min.apply(Math, params.textNodeIdx),
587 idx2 = Math.max.apply(Math, params.textNodeIdx),
588 textNode1 = contentsInside[idx1],
589 textNode2 = contentsInside[idx2],
590 sameNode = textNode1.sameNode(textNode2),
591 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
592 prefixInside = textNode1.getText().substr(params.offsetStart),
593 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
594 suffixOutside = textNode2.getText().substr(params.offsetEnd)
597 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
598 throw new Error('Wrapping text in non-sibling text nodes not supported.');
601 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
602 textNode1.after(wrapperElement);
605 if(prefixOutside.length > 0) {
606 wrapperElement.before({text:prefixOutside});
609 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
610 wrapperElement.append({text: core});
613 if(prefixInside.length > 0) {
614 wrapperElement.append({text: prefixInside});
616 for(var i = idx1 + 1; i < idx2; i++) {
617 wrapperElement.append(contentsInside[i]);
619 if(suffixInside.length > 0) {
620 wrapperElement.append({text: suffixInside});
623 if(suffixOutside.length > 0) {
624 wrapperElement.after({text: suffixOutside});
626 return wrapperElement;
629 trigger: function() {
630 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
631 Backbone.Events.trigger.apply(this, arguments);
634 getNodeInsertion: function(node) {
636 if(node instanceof DocumentNode) {
637 insertion.ofNode = node;
638 insertion.insertsNew = !this.containsNode(node);
640 insertion.ofNode = this.createDocumentNode(node);
641 insertion.insertsNew = true;
646 replaceRoot: function(node) {
647 var insertion = this.getNodeInsertion(node);
649 defineDocumentProperties(this, insertion.ofNode._$);
650 insertion.ofNode.triggerChangeEvent('nodeAdded');
651 return insertion.ofNode;
654 transform: function(transformationName, args) {
655 console.log('transform');
656 var Transformation, transformation, toret;
657 if(typeof transformationName === 'string') {
658 Transformation = transformations[transformationName];
660 transformation = new Transformation(args);
663 transformation = transformationName;
666 toret = transformation.run();
667 this.undoStack.push(transformation);
668 console.log('clearing redo stack');
672 throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
676 var transformation = this.undoStack.pop();
678 transformation.undo();
679 this.redoStack.push(transformation);
683 var transformation = this.redoStack.pop();
685 transformation.run();
686 this.undoStack.push(transformation);
690 getNodeByPath: function(path) {
691 var toret = this.root;
692 path.forEach(function(idx) {
693 toret = toret.contents()[idx];
699 var defineDocumentProperties = function(doc, $document) {
700 Object.defineProperty(doc, 'root', {get: function() {
701 return doc.createDocumentNode($document[0]);
702 }, configurable: true});
703 Object.defineProperty(doc, 'dom', {get: function() {
705 }, configurable: true});
709 // var registerTransformationsFromObject = function(object) {
710 // _.values(object).filter(function(val) {
711 // return typeof val === 'function' && val._isTransformation;
713 // .forEach(function(val) {
714 // registerTransformation(val._transformationName, val, object);
717 // registerTransformationsFromObject(ElementNode.prototype);
718 // registerTransformationsFromObject(TextNode.prototype);
719 // registerTransformationsFromObject(Document.prototype);
721 // var Transformation = function() {
723 // $.extend(Transformation.prototype, {
728 // var createDumbTransformation = function(impl, contextObject) {
729 // var DumbTransformation = function(args) {
730 // this.args = this.args;
732 // DumbTransformation.prototype = Object.create(Transformation.prototype);
733 // $.extend(DumbTransformation.prototype, {
735 // impl.apply(contextObject, this.args);
739 // return DumbTransformation;
744 var transformations = {};
745 // var registerTransformation = function(name, impl, contextObject) {
746 // if(typeof impl === 'function') {
747 // transformations[name] = createDumbTransformation(impl, contextObject);
751 // registerTransformation('detachx', DocumentNode.prototype.detach, )
754 // 1. detach via totalny fallback
755 var DetachNodeTransformation = function(args) {
756 this.node = args.node;
757 this.document = this.node.document;
759 $.extend(DetachNodeTransformation.prototype, {
761 this.oldRoot = this.node.document.root.clone();
762 this.path = this.node.getPath();
763 this.node.detach(); // @TS
767 this.document.root.replaceWith(this.oldRoot); // this.getDocument?
768 this.node = this.document.getNodeByPath(this.path);
771 transformations['detach'] = DetachNodeTransformation;
773 //2. detach via wskazanie changeroot
775 var Detach2NodeTransformation = function(args) {
776 this.nodePath = args.node.getPath();
777 this.document = args.node.document;
779 $.extend(Detach2NodeTransformation.prototype, {
781 var node = this.document.getNodeByPath(this.nodePath),
782 root = node.parent() ? node.parent() : this.document.root;
784 this.rootPath = root.getPath();
785 this.oldRoot = (root).clone();
789 this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
792 //transformations['detach2'] = Detach2NodeTransformation;
794 //2a. generyczna transformacja
796 var createTransformation = function(desc) {
798 var NodeTransformation = function(args) {
799 this.nodePath = args.node.getPath();
800 this.document = args.node.document;
803 $.extend(NodeTransformation.prototype, {
805 var node = this.document.getNodeByPath(this.nodePath),
809 root = desc.getRoot(node);
811 root = this.document.root;
814 this.rootPath = root.getPath();
815 this.oldRoot = (root).clone();
816 desc.impl.call(node, this.args);
819 this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
823 return NodeTransformation;
827 var Transformation = function(args) {
830 $.extend(Transformation.prototype, {
832 throw new Error('not implemented');
835 throw new Error('not implemented');
839 var createGenericTransformation = function(desc) {
840 var GenericTransformation = function(document, args) {
841 //document.getNodeByPath(contextPath).call(this, args);
843 this.document = document;
845 $.extend(GenericTransformation.prototype, {
847 var changeRoot = desc.getChangeRoot ? desc.getChangeRoot.call(this) : this.document.root;
848 this.snapshot = changeRoot.clone();
849 this.changeRootPath = changeRoot.getPath();
850 return desc.impl.call(this.context, this.args); // a argumenty do metody?
853 this.document.getNodeByPath(this.changeRootPath).replaceWith(this.snapshot);
857 return GenericTransformation;
860 // var T = createGenericTransformation({impl: function() {}});
861 // var t = T(doc, {a:1,b:2,c3:3});
864 var createContextTransformation = function(desc) {
865 // mozna sie pozbyc przez przeniesienie object/context na koniec argumentow konstruktora generic transformation
866 var GenericTransformation = createGenericTransformation(desc);
868 var ContextTransformation = function(document, object, args) {
869 var contextPath = object.getPath();
871 GenericTransformation.call(this, document, args);
873 Object.defineProperty(this, 'context', {
875 return document.getNodeByPath(contextPath);
879 ContextTransformation.prototype = Object.create(GenericTransformation.prototype);
880 return ContextTransformation;
882 // var T = createContextTransformation({impl: function() {}});
883 // var t = T(doc, node, {a:1,b:2,c3:3});
886 var contextTransformations = {};
887 contextTransformations['setText'] = createContextTransformation({
888 impl: function(args) {
889 this.setText(args.text);
891 getChangeRoot: function() {
896 contextTransformations['setAttr'] = createContextTransformation({
897 impl: function(args) {
898 this.setAttr(args.name, args.value);
900 getChangeRoot: function() {
905 contextTransformations['split'] = createContextTransformation({
906 impl: function(args) {
907 return this.split({offset: args.offset});
909 // getChangeRoot: function() {
910 // return this.context.parent().parent();
914 // var TRANSFORMATION2 = function(f, getChangeRoot, undo) {
915 // var context = this,
918 // var transformation = createContextTransformation({
920 // getChangeRoot: getChangeRoot,
924 // var toret = function() {
926 // f.apply(context, createArgs ? createArgs(arguments) : arguments)
931 transformations['detach2'] = createTransformation({
932 // impl: function() {
933 // //this.setAttr('class', 'cite'); //
935 impl: ElementNode.prototype.detach,
936 getRoot: function(node) {
937 return node.parent();
942 transformations['setText-old'] = createTransformation({
943 impl: function(args) {
944 this.setText(args.text)
946 getRoot: function(node) {
952 transformations['setClass-old'] = createTransformation({
953 impl: function(args) {
954 this.setClass(args.klass);
956 getRoot: function(node) {
961 //3. detach z pełnym własnym redo
963 var Detach3NodeTransformation = function(args) {
964 this.node = args.node;
965 this.document = this.node.document;
967 $.extend(Detach3NodeTransformation.prototype, {
969 //this.index = this.node.getIndex();
970 //this.parent = this.node.parent();
972 this.path = this.node.getPath();
973 if(this.node.isSurroundedByTextElements()) {
974 this.prevText = this.node.prev().getText();
975 this.nextText = this.node.next().getText();
978 this.prevText = this.nextText = null;
985 var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
986 idx = _.last(this.path);
987 var inserted = parent.insertAtIndex(this.node, idx);
989 if(inserted.next()) {
990 inserted.before({text: this.prevText});
991 inserted.next().setText(this.nextText);
993 inserted.prev().setText(this.prevText);
994 inserted.after({text: this.nextText});
999 transformations['detach3'] = Detach3NodeTransformation;
1002 var registerTransformationsFromObject = function(object) {
1003 _.pairs(object).filter(function(pair) {
1004 var property = pair[1];
1005 return typeof property === 'function' && property._isTransformation;
1007 .forEach(function(pair) {
1010 object.registerTransformation(name, createContextTransformation(method));
1013 registerTransformationsFromObject(ElementNode.prototype);
1014 registerTransformationsFromObject(TextNode.prototype);
1015 registerTransformationsFromObject(Document.prototype);
1018 documentFromXML: function(xml) {
1019 return new Document(xml);
1022 elementNodeFromXML: function(xml) {
1023 return this.documentFromXML(xml).root;
1027 DocumentNode: DocumentNode,
1028 ElementNode: ElementNode