6 'smartxml/transformations',
8 ], function($, _, Backbone, events, transformations, coreTransformations) {
13 var TEXT_NODE = Node.TEXT_NODE;
17 var DocumentNode = function(nativeNode, document) {
19 throw new Error('undefined document for a node');
21 this.document = document;
22 this._setNativeNode(nativeNode);
26 $.extend(DocumentNode.prototype, {
28 transform: function(Transformation, args) {
29 var transformation = new Transformation(this.document, this, args);
30 return this.document.transform(transformation);
33 _setNativeNode: function(nativeNode) {
34 this.nativeNode = nativeNode;
35 this._$ = $(nativeNode);
39 var clone = this._$.clone(true, true);
40 // clone.find('*').addBack().each(function() {
42 // if(n.data('canvasElement')) {
43 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
44 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
47 return this.document.createDocumentNode(clone[0]);
50 getPath: function(ancestor) {
51 if(!(this.document.containsNode(this))) {
55 var nodePath = [this].concat(this.parents()),
57 ancestor = ancestor || this.document.root;
59 nodePath.some(function(node, i) {
60 if(node.sameNode(ancestor)) {
66 if(idx !== 'undefined') {
67 nodePath = nodePath.slice(0, idx);
69 toret = nodePath.map(function(node) {return node.getIndex(); });
75 return this.document.root.sameNode(this);
78 sameNode: function(otherNode) {
79 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
83 var parentNode = this.nativeNode.parentNode;
84 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
85 return this.document.createDocumentNode(parentNode);
91 var parent = this.parent(),
92 parents = parent ? parent.parents() : [];
94 parents.unshift(parent);
100 var myIdx = this.getIndex();
101 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
108 var myIdx = this.getIndex(),
109 parentContents = this.parent().contents();
110 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
113 isSurroundedByTextElements: function() {
114 var prev = this.prev(),
116 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
119 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
120 var node = (metaData && metaData.node) ? metaData.node : this,
121 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
122 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
123 this.document.trigger('change', event);
125 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
126 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
127 this.document.trigger('change', event);
131 getNodeInsertion: function(node) {
132 return this.document.getNodeInsertion(node);
135 getIndex: function() {
139 return this.parent().indexOf(this);
144 var ElementNode = function(nativeNode, document) {
145 DocumentNode.call(this, nativeNode, document);
147 ElementNode.prototype = Object.create(DocumentNode.prototype);
149 $.extend(ElementNode.prototype, {
150 nodeType: Node.ELEMENT_NODE,
152 setData: function(key, value) {
153 if(value !== undefined) {
154 this._$.data(key, value);
156 this._$.removeData(_.keys(this._$.data()));
161 getData: function(key) {
163 return this._$.data(key);
165 return this._$.data();
168 getTagName: function() {
169 return this.nativeNode.tagName.toLowerCase();
172 contents: function(selector) {
174 document = this.document;
176 this._$.children(selector).each(function() {
177 toret.push(document.createDocumentNode(this));
180 this._$.contents().each(function() {
181 toret.push(document.createDocumentNode(this));
187 indexOf: function(node) {
188 return this._$.contents().index(node._$);
191 getAttr: function(name) {
192 return this._$.attr(name);
195 getAttrs: function() {
197 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
198 toret.push(this.nativeNode.attributes[i]);
204 var wrapper = $('<div>');
205 wrapper.append(this._getXMLDOMToDump());
206 return wrapper.html();
209 _getXMLDOMToDump: function() {
215 var TextNode = function(nativeNode, document) {
216 DocumentNode.call(this, nativeNode, document);
218 TextNode.prototype = Object.create(DocumentNode.prototype);
220 $.extend(TextNode.prototype, {
221 nodeType: Node.TEXT_NODE,
223 getText: function() {
224 return this.nativeNode.data;
227 triggerTextChangeEvent: function() {
228 var event = new events.ChangeEvent('nodeTextChange', {node: this});
229 this.document.trigger('change', event);
234 var parseXML = function(xml) {
235 return $($.trim(xml))[0];
238 var registerTransformation = function(desc, name, target) {
239 var Transformation = transformations.createContextTransformation(desc, name);
240 //+ to sie powinna nazywac registerTransformationFromDesc or sth
241 //+ ew. spr czy nie override (tylko jesli powyzej sa prototypy to trudno do nich dojsc)
242 target[name] = function() {
244 args = Array.prototype.slice.call(arguments, 0);
245 return instance.transform(Transformation, args);
249 var registerMethod = function(methodName, method, target) {
250 if(target[methodName]) {
251 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
252 .replace('{target}', target)
253 .replace('{methodName}', methodName)
256 target[methodName] = method;
260 var Document = function(xml) {
264 this._transformationLevel = 0;
266 this._nodeMethods = {};
267 this._textNodeMethods = {};
268 this._elementNodeMethods = {};
269 this._nodeTransformations = {};
270 this._textNodeTransformations = {};
271 this._elementNodeTransformations = {};
274 $.extend(Document.prototype, Backbone.Events, {
275 ElementNodeFactory: ElementNode,
276 TextNodeFactory: TextNode,
278 createDocumentNode: function(from) {
279 if(!(from instanceof Node)) {
280 if(from.text !== undefined) {
281 /* globals document */
282 from = document.createTextNode(from.text);
284 var node = $('<' + from.tagName + '>');
286 _.keys(from.attrs || {}).forEach(function(key) {
287 node.attr(key, from.attrs[key]);
293 var Factory, typeMethods, typeTransformations;
294 if(from.nodeType === Node.TEXT_NODE) {
295 Factory = this.TextNodeFactory;
296 typeMethods = this._textNodeMethods;
297 typeTransformations = this._textNodeTransformations;
298 } else if(from.nodeType === Node.ELEMENT_NODE) {
299 Factory = this.ElementNodeFactory;
300 typeMethods = this._elementNodeMethods;
301 typeTransformations = this._elementNodeTransformations;
303 var toret = new Factory(from, this);
304 _.extend(toret, this._nodeMethods);
305 _.extend(toret, typeMethods);
307 _.extend(toret, this._nodeTransformations);
308 _.extend(toret, typeTransformations);
310 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
311 _.keys(toret.__super__).forEach(function(key) {
312 toret.__super__[key] = _.bind(toret.__super__[key], toret);
318 loadXML: function(xml, options) {
319 options = options || {};
320 this._defineDocumentProperties($(parseXML(xml)));
321 if(!options.silent) {
322 this.trigger('contentSet');
327 return this.root.toXML();
330 containsNode: function(node) {
331 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
334 getSiblingParents: function(params) {
335 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
336 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
337 noSiblingParents = null;
339 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
340 return noSiblingParents;
344 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
345 if(parents1[i].sameNode(parents2[i])) {
350 return {node1: parents1[i], node2: parents2[i]};
353 trigger: function() {
354 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
355 Backbone.Events.trigger.apply(this, arguments);
358 getNodeInsertion: function(node) {
360 if(node instanceof DocumentNode) {
361 insertion.ofNode = node;
362 insertion.insertsNew = !this.containsNode(node);
364 insertion.ofNode = this.createDocumentNode(node);
365 insertion.insertsNew = true;
370 registerMethod: function(methodName, method, dstName) {
374 documentNode: doc._nodeMethods,
375 textNode: doc._textNodeMethods,
376 elementNode: doc._elementNodeMethods
378 registerMethod(methodName, method, destination);
381 registerTransformation: function(desc, name, dstName) {
385 documentNode: doc._nodeTransformations,
386 textNode: doc._textNodeTransformations,
387 elementNode: doc._elementNodeTransformations
389 registerTransformation(desc, name, destination);
392 registerExtension: function(extension) {
395 existingPropertyNames = _.values(this);
397 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
398 var dstExtension = extension[dstName];
400 if(dstExtension.methods) {
401 _.pairs(dstExtension.methods).forEach(function(pair) {
402 var methodName = pair[0],
405 doc.registerMethod(methodName, method, dstName);
410 if(dstExtension.transformations) {
411 _.pairs(dstExtension.transformations).forEach(function(pair) {
414 doc.registerTransformation(desc, name, dstName);
421 transform: function(Transformation, args) {
422 //console.log('transform');
423 var toret, transformation;
425 // ref: odrebnie przygotowanie transformacji, odrebnie jej wykonanie (to pierwsze to analog transform z node)
427 if(typeof Transformation === 'function') {
428 transformation = new Transformation(this, this, args);
430 transformation = Transformation;
433 this._transformationLevel++;
434 toret = transformation.run();
435 if(this._transformationLevel === 1) {
436 this.undoStack.push(transformation);
438 this._transformationLevel--;
439 //console.log('clearing redo stack');
443 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
447 var transformation = this.undoStack.pop();
449 transformation.undo();
450 this.redoStack.push(transformation);
454 var transformation = this.redoStack.pop();
456 transformation.run();
457 this.undoStack.push(transformation);
461 getNodeByPath: function(path) {
462 var toret = this.root;
463 path.forEach(function(idx) {
464 toret = toret.contents()[idx];
469 _defineDocumentProperties: function($document) {
471 Object.defineProperty(doc, 'root', {get: function() {
472 return doc.createDocumentNode($document[0]);
473 }, configurable: true});
474 Object.defineProperty(doc, 'dom', {get: function() {
476 }, configurable: true});
482 documentFromXML: function(xml) {
483 var doc = new Document(xml);
484 doc.registerExtension(coreTransformations);
488 elementNodeFromXML: function(xml) {
489 return this.documentFromXML(xml).root;
493 DocumentNode: DocumentNode,
494 ElementNode: ElementNode,