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 this.nativeNode.data = text;
387 this.triggerTextChangeEvent();
390 appendText: function(text) {
391 this.nativeNode.data = this.nativeNode.data + text;
392 this.triggerTextChangeEvent();
395 prependText: function(text) {
396 this.nativeNode.data = text + this.nativeNode.data;
397 this.triggerTextChangeEvent();
400 wrapWith: function(desc) {
401 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
402 return this.document._wrapText({
403 inside: this.parent(),
404 textNodeIdx: this.parent().indexOf(this),
405 offsetStart: Math.min(desc.start, desc.end),
406 offsetEnd: Math.max(desc.start, desc.end),
407 _with: {tagName: desc.tagName, attrs: desc.attrs}
410 return DocumentNode.prototype.wrapWith.call(this, desc);
414 split: function(params) {
415 var parentElement = this.parent(),
417 succeedingChildren = [],
418 prefix = this.getText().substr(0, params.offset),
419 suffix = this.getText().substr(params.offset);
421 parentElement.contents().forEach(function(child) {
423 succeedingChildren.push(child);
425 if(child.sameNode(this)) {
430 if(prefix.length > 0) {
431 this.setText(prefix);
438 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
439 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
440 parentElement.after(newElement);
442 if(suffix.length > 0) {
443 newElement.append({text: suffix});
445 succeedingChildren.forEach(function(child) {
446 newElement.append(child);
449 return {first: parentElement, second: newElement};
452 triggerTextChangeEvent: function() {
453 var event = new events.ChangeEvent('nodeTextChange', {node: this});
454 this.document.trigger('change', event);
459 var parseXML = function(xml) {
460 return $($.trim(xml))[0];
463 var Document = function(xml) {
469 $.extend(Document.prototype, Backbone.Events, {
470 ElementNodeFactory: ElementNode,
471 TextNodeFactory: TextNode,
473 createDocumentNode: function(from) {
474 if(!(from instanceof Node)) {
475 if(from.text !== undefined) {
476 /* globals document */
477 from = document.createTextNode(from.text);
479 var node = $('<' + from.tagName + '>');
481 _.keys(from.attrs || {}).forEach(function(key) {
482 node.attr(key, from.attrs[key]);
489 if(from.nodeType === Node.TEXT_NODE) {
490 Factory = this.TextNodeFactory;
491 } else if(from.nodeType === Node.ELEMENT_NODE) {
492 Factory = this.ElementNodeFactory;
494 return new Factory(from, this);
497 loadXML: function(xml, options) {
498 options = options || {};
499 defineDocumentProperties(this, $(parseXML(xml)));
500 if(!options.silent) {
501 this.trigger('contentSet');
506 return this.root.toXML();
509 containsNode: function(node) {
510 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
513 wrapNodes: function(params) {
514 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
515 throw new Error('Wrapping non-sibling nodes not supported.');
518 var parent = params.node1.parent(),
519 parentContents = parent.contents(),
520 wrapper = this.createDocumentNode({
521 tagName: params._with.tagName,
522 attrs: params._with.attrs}),
523 idx1 = parent.indexOf(params.node1),
524 idx2 = parent.indexOf(params.node2);
532 var insertingMethod, insertingTarget;
534 insertingMethod = 'prepend';
535 insertingTarget = parent;
537 insertingMethod = 'after';
538 insertingTarget = parentContents[idx1-1];
541 for(var i = idx1; i <= idx2; i++) {
542 wrapper.append(parentContents[i].detach());
545 insertingTarget[insertingMethod](wrapper);
549 getSiblingParents: function(params) {
550 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
551 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
552 noSiblingParents = null;
554 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
555 return noSiblingParents;
559 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
560 if(parents1[i].sameNode(parents2[i])) {
565 return {node1: parents1[i], node2: parents2[i]};
568 _wrapText: function(params) {
569 params = _.extend({textNodeIdx: 0}, params);
570 if(typeof params.textNodeIdx === 'number') {
571 params.textNodeIdx = [params.textNodeIdx];
574 var contentsInside = params.inside.contents(),
575 idx1 = Math.min.apply(Math, params.textNodeIdx),
576 idx2 = Math.max.apply(Math, params.textNodeIdx),
577 textNode1 = contentsInside[idx1],
578 textNode2 = contentsInside[idx2],
579 sameNode = textNode1.sameNode(textNode2),
580 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
581 prefixInside = textNode1.getText().substr(params.offsetStart),
582 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
583 suffixOutside = textNode2.getText().substr(params.offsetEnd)
586 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
587 throw new Error('Wrapping text in non-sibling text nodes not supported.');
590 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
591 textNode1.after(wrapperElement);
594 if(prefixOutside.length > 0) {
595 wrapperElement.before({text:prefixOutside});
598 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
599 wrapperElement.append({text: core});
602 if(prefixInside.length > 0) {
603 wrapperElement.append({text: prefixInside});
605 for(var i = idx1 + 1; i < idx2; i++) {
606 wrapperElement.append(contentsInside[i]);
608 if(suffixInside.length > 0) {
609 wrapperElement.append({text: suffixInside});
612 if(suffixOutside.length > 0) {
613 wrapperElement.after({text: suffixOutside});
615 return wrapperElement;
618 trigger: function() {
619 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
620 Backbone.Events.trigger.apply(this, arguments);
623 getNodeInsertion: function(node) {
625 if(node instanceof DocumentNode) {
626 insertion.ofNode = node;
627 insertion.insertsNew = !this.containsNode(node);
629 insertion.ofNode = this.createDocumentNode(node);
630 insertion.insertsNew = true;
635 replaceRoot: function(node) {
636 var insertion = this.getNodeInsertion(node);
638 defineDocumentProperties(this, insertion.ofNode._$);
639 insertion.ofNode.triggerChangeEvent('nodeAdded');
640 return insertion.ofNode;
643 transform: function(transformationName, args) {
644 var Transformation = transformations[transformationName],
647 transformation = new Transformation(args);
648 transformation.run();
649 this.undoStack.push(transformation);
652 throw new Error('Transformation ' + transformationName + ' doesn\'t exist!');
656 var transformation = this.undoStack.pop();
658 transformation.undo();
659 this.redoStack.push(transformation);
663 var transformation = this.redoStack.pop();
665 transformation.run();
666 this.undoStack.push(transformation);
670 getNodeByPath: function(path) {
671 var toret = this.root;
672 path.forEach(function(idx) {
673 toret = toret.contents()[idx];
679 var defineDocumentProperties = function(doc, $document) {
680 Object.defineProperty(doc, 'root', {get: function() {
681 return doc.createDocumentNode($document[0]);
682 }, configurable: true});
683 Object.defineProperty(doc, 'dom', {get: function() {
685 }, configurable: true});
689 // var registerTransformationsFromObject = function(object) {
690 // _.values(object).filter(function(val) {
691 // return typeof val === 'function' && val._isTransformation;
693 // .forEach(function(val) {
694 // registerTransformation(val._transformationName, val, object);
697 // registerTransformationsFromObject(ElementNode.prototype);
698 // registerTransformationsFromObject(TextNode.prototype);
699 // registerTransformationsFromObject(Document.prototype);
701 // var Transformation = function() {
703 // $.extend(Transformation.prototype, {
708 // var createDumbTransformation = function(impl, contextObject) {
709 // var DumbTransformation = function(args) {
710 // this.args = this.args;
712 // DumbTransformation.prototype = Object.create(Transformation.prototype);
713 // $.extend(DumbTransformation.prototype, {
715 // impl.apply(contextObject, this.args);
719 // return DumbTransformation;
724 var transformations = {};
725 // var registerTransformation = function(name, impl, contextObject) {
726 // if(typeof impl === 'function') {
727 // transformations[name] = createDumbTransformation(impl, contextObject);
731 // registerTransformation('detachx', DocumentNode.prototype.detach, )
734 // 1. detach via totalny fallback
735 var DetachNodeTransformation = function(args) {
736 this.node = args.node;
737 this.document = this.node.document;
739 $.extend(DetachNodeTransformation.prototype, {
741 this.oldRoot = this.node.document.root.clone();
742 this.path = this.node.getPath();
743 this.node.detach(); // @TS
747 this.document.root.replaceWith(this.oldRoot); // this.getDocument?
748 this.node = this.document.getNodeByPath(this.path);
751 transformations['detach'] = DetachNodeTransformation;
753 //2. detach via wskazanie changeroot
755 var Detach2NodeTransformation = function(args) {
756 this.nodePath = args.node.getPath();
757 this.document = args.node.document;
759 $.extend(Detach2NodeTransformation.prototype, {
761 var node = this.document.getNodeByPath(this.nodePath),
762 root = node.parent() ? node.parent() : this.document.root;
764 this.rootPath = root.getPath();
765 this.oldRoot = (root).clone();
769 this.document.getNodeByPath(this.rootPath).replaceWith(this.oldRoot);
772 transformations['detach2'] = Detach2NodeTransformation;
774 //3. detach z pełnym własnym redo
776 var Detach3NodeTransformation = function(args) {
777 this.node = args.node;
778 this.document = this.node.document;
780 $.extend(Detach3NodeTransformation.prototype, {
782 //this.index = this.node.getIndex();
783 //this.parent = this.node.parent();
785 this.path = this.node.getPath();
786 if(this.node.isSurroundedByTextElements()) {
787 this.prevText = this.node.prev().getText();
788 this.nextText = this.node.next().getText();
791 this.prevText = this.nextText = null;
798 var parent = this.document.getNodeByPath(this.path.slice(0,-1)),
799 idx = _.last(this.path);
800 var inserted = parent.insertAtIndex(this.node, idx);
802 if(inserted.next()) {
803 inserted.before({text: this.prevText});
804 inserted.next().setText(this.nextText);
806 inserted.prev().setText(this.prevText);
807 inserted.after({text: this.nextText});
812 transformations['detach3'] = Detach3NodeTransformation;
815 documentFromXML: function(xml) {
816 return new Document(xml);
819 elementNodeFromXML: function(xml) {
820 return this.documentFromXML(xml).root;
824 DocumentNode: DocumentNode,
825 ElementNode: ElementNode