6 'smartxml/transformations',
8 ], function($, _, Backbone, events, transformations, coreTransformations) {
14 var DocumentNode = function(nativeNode, document) {
16 throw new Error('undefined document for a node');
18 this.document = document;
19 this._setNativeNode(nativeNode);
23 $.extend(DocumentNode.prototype, {
25 transform: function(Transformation, args) {
26 var transformation = new Transformation(this.document, this, args);
27 return this.document.transform(transformation);
30 _setNativeNode: function(nativeNode) {
31 this.nativeNode = nativeNode;
32 this._$ = $(nativeNode);
36 var clone = this._$.clone(true, true);
37 // clone.find('*').addBack().each(function() {
39 // if(n.data('canvasElement')) {
40 // n.data('canvasElement', $.extend(true, {}, n.data('canvasElement')));
41 // n.data('canvasElement').$element = n.data('canvasElement').$element.clone(true, true);
44 return this.document.createDocumentNode(clone[0]);
47 getPath: function(ancestor) {
48 if(!(this.document.containsNode(this))) {
52 var nodePath = [this].concat(this.parents()),
54 ancestor = ancestor || this.document.root;
56 nodePath.some(function(node, i) {
57 if(node.sameNode(ancestor)) {
63 if(idx !== 'undefined') {
64 nodePath = nodePath.slice(0, idx);
66 toret = nodePath.map(function(node) {return node.getIndex(); });
72 return this.document.root.sameNode(this);
75 sameNode: function(otherNode) {
76 return !!(otherNode) && this.nativeNode === otherNode.nativeNode;
80 var parentNode = this.nativeNode.parentNode;
81 if(parentNode && parentNode.nodeType === Node.ELEMENT_NODE) {
82 return this.document.createDocumentNode(parentNode);
88 var parent = this.parent(),
89 parents = parent ? parent.parents() : [];
91 parents.unshift(parent);
97 var myIdx = this.getIndex();
98 return myIdx > 0 ? this.parent().contents()[myIdx-1] : null;
105 var myIdx = this.getIndex(),
106 parentContents = this.parent().contents();
107 return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null;
110 isSurroundedByTextElements: function() {
111 var prev = this.prev(),
113 return prev && (prev.nodeType === Node.TEXT_NODE) && next && (next.nodeType === Node.TEXT_NODE);
116 triggerChangeEvent: function(type, metaData, origParent, nodeWasContained) {
117 var node = (metaData && metaData.node) ? metaData.node : this,
118 event = new events.ChangeEvent(type, $.extend({node: node}, metaData || {}));
119 if(type === 'nodeDetached' || this.document.containsNode(event.meta.node)) {
120 this.document.trigger('change', event);
122 if((type === 'nodeAdded' || type === 'nodeMoved') && !this.document.containsNode(this) && nodeWasContained) {
123 event = new events.ChangeEvent('nodeDetached', {node: node, parent: origParent});
124 this.document.trigger('change', event);
128 getNodeInsertion: function(node) {
129 return this.document.getNodeInsertion(node);
132 getIndex: function() {
136 return this.parent().indexOf(this);
141 var ElementNode = function(nativeNode, document) {
142 DocumentNode.call(this, nativeNode, document);
144 ElementNode.prototype = Object.create(DocumentNode.prototype);
146 $.extend(ElementNode.prototype, {
147 nodeType: Node.ELEMENT_NODE,
149 setData: function(key, value) {
150 if(value !== undefined) {
151 this._$.data(key, value);
153 this._$.removeData(_.keys(this._$.data()));
158 getData: function(key) {
160 return this._$.data(key);
162 return this._$.data();
165 getTagName: function() {
166 return this.nativeNode.tagName.toLowerCase();
169 contents: function(selector) {
171 document = this.document;
173 this._$.children(selector).each(function() {
174 toret.push(document.createDocumentNode(this));
177 this._$.contents().each(function() {
178 toret.push(document.createDocumentNode(this));
184 indexOf: function(node) {
185 return this._$.contents().index(node._$);
188 getAttr: function(name) {
189 return this._$.attr(name);
192 getAttrs: function() {
194 for(var i = 0; i < this.nativeNode.attributes.length; i++) {
195 toret.push(this.nativeNode.attributes[i]);
201 var wrapper = $('<div>');
202 wrapper.append(this._getXMLDOMToDump());
203 return wrapper.html();
206 _getXMLDOMToDump: function() {
212 var TextNode = function(nativeNode, document) {
213 DocumentNode.call(this, nativeNode, document);
215 TextNode.prototype = Object.create(DocumentNode.prototype);
217 $.extend(TextNode.prototype, {
218 nodeType: Node.TEXT_NODE,
220 getText: function() {
221 return this.nativeNode.data;
224 triggerTextChangeEvent: function() {
225 var event = new events.ChangeEvent('nodeTextChange', {node: this});
226 this.document.trigger('change', event);
231 var parseXML = function(xml) {
232 return $($.trim(xml))[0];
235 var registerTransformation = function(desc, name, target) {
236 var Transformation = transformations.createContextTransformation(desc, name);
237 //+ to sie powinna nazywac registerTransformationFromDesc or sth
238 //+ ew. spr czy nie override (tylko jesli powyzej sa prototypy to trudno do nich dojsc)
239 target[name] = function() {
241 args = Array.prototype.slice.call(arguments, 0);
242 return instance.transform(Transformation, args);
246 var registerMethod = function(methodName, method, target) {
247 if(target[methodName]) {
248 throw new Error('Cannot extend {target} with method name {methodName}. Name already exists.'
249 .replace('{target}', target)
250 .replace('{methodName}', methodName)
253 target[methodName] = method;
257 var Document = function(xml) {
261 this._transformationLevel = 0;
263 this._nodeMethods = {};
264 this._textNodeMethods = {};
265 this._elementNodeMethods = {};
266 this._nodeTransformations = {};
267 this._textNodeTransformations = {};
268 this._elementNodeTransformations = {};
270 this.registerExtension(coreTransformations);
273 $.extend(Document.prototype, Backbone.Events, {
274 ElementNodeFactory: ElementNode,
275 TextNodeFactory: TextNode,
277 createDocumentNode: function(from) {
278 if(!(from instanceof Node)) {
279 if(from.text !== undefined) {
280 /* globals document */
281 from = document.createTextNode(from.text);
283 var node = $('<' + from.tagName + '>');
285 _.keys(from.attrs || {}).forEach(function(key) {
286 node.attr(key, from.attrs[key]);
292 var Factory, typeMethods, typeTransformations;
293 if(from.nodeType === Node.TEXT_NODE) {
294 Factory = this.TextNodeFactory;
295 typeMethods = this._textNodeMethods;
296 typeTransformations = this._textNodeTransformations;
297 } else if(from.nodeType === Node.ELEMENT_NODE) {
298 Factory = this.ElementNodeFactory;
299 typeMethods = this._elementNodeMethods;
300 typeTransformations = this._elementNodeTransformations;
302 var toret = new Factory(from, this);
303 _.extend(toret, this._nodeMethods);
304 _.extend(toret, typeMethods);
306 _.extend(toret, this._nodeTransformations);
307 _.extend(toret, typeTransformations);
309 toret.__super__ = _.extend({}, this._nodeMethods, this._nodeTransformations);
310 _.keys(toret.__super__).forEach(function(key) {
311 toret.__super__[key] = _.bind(toret.__super__[key], toret);
317 loadXML: function(xml, options) {
318 options = options || {};
319 this._defineDocumentProperties($(parseXML(xml)));
320 if(!options.silent) {
321 this.trigger('contentSet');
326 return this.root.toXML();
329 containsNode: function(node) {
330 return this.root && (node.nativeNode === this.root.nativeNode || node._$.parents().index(this.root._$) !== -1);
333 getSiblingParents: function(params) {
334 var parents1 = [params.node1].concat(params.node1.parents()).reverse(),
335 parents2 = [params.node2].concat(params.node2.parents()).reverse(),
336 noSiblingParents = null;
338 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0]))) {
339 return noSiblingParents;
343 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
344 if(parents1[i].sameNode(parents2[i])) {
349 return {node1: parents1[i], node2: parents2[i]};
352 trigger: function() {
353 //console.log('trigger: ' + arguments[0] + (arguments[1] ? ', ' + arguments[1].type : ''));
354 Backbone.Events.trigger.apply(this, arguments);
357 getNodeInsertion: function(node) {
359 if(node instanceof DocumentNode) {
360 insertion.ofNode = node;
361 insertion.insertsNew = !this.containsNode(node);
363 insertion.ofNode = this.createDocumentNode(node);
364 insertion.insertsNew = true;
369 registerMethod: function(methodName, method, dstName) {
373 documentNode: doc._nodeMethods,
374 textNode: doc._textNodeMethods,
375 elementNode: doc._elementNodeMethods
377 registerMethod(methodName, method, destination);
380 registerTransformation: function(desc, name, dstName) {
384 documentNode: doc._nodeTransformations,
385 textNode: doc._textNodeTransformations,
386 elementNode: doc._elementNodeTransformations
388 registerTransformation(desc, name, destination);
391 registerExtension: function(extension) {
394 existingPropertyNames = _.values(this);
396 ['document', 'documentNode', 'elementNode', 'textNode'].forEach(function(dstName) {
397 var dstExtension = extension[dstName];
399 if(dstExtension.methods) {
400 _.pairs(dstExtension.methods).forEach(function(pair) {
401 var methodName = pair[0],
404 doc.registerMethod(methodName, method, dstName);
409 if(dstExtension.transformations) {
410 _.pairs(dstExtension.transformations).forEach(function(pair) {
413 doc.registerTransformation(desc, name, dstName);
420 transform: function(Transformation, args) {
421 //console.log('transform');
422 var toret, transformation;
424 // ref: odrebnie przygotowanie transformacji, odrebnie jej wykonanie (to pierwsze to analog transform z node)
426 if(typeof Transformation === 'function') {
427 transformation = new Transformation(this, this, args);
429 transformation = Transformation;
432 this._transformationLevel++;
433 toret = transformation.run();
434 if(this._transformationLevel === 1 && !this._undoInProgress) {
435 this.undoStack.push(transformation);
437 this._transformationLevel--;
438 //console.log('clearing redo stack');
442 throw new Error('Transformation ' + transformation + ' doesn\'t exist!');
446 var transformation = this.undoStack.pop();
448 this._undoInProgress = true;
449 transformation.undo();
450 this._undoInProgress = false;
451 this.redoStack.push(transformation);
455 var transformation = this.redoStack.pop();
457 this._transformationLevel++;
458 transformation.run();
459 this._transformationLevel--;
460 this.undoStack.push(transformation);
464 getNodeByPath: function(path) {
465 var toret = this.root;
466 path.forEach(function(idx) {
467 toret = toret.contents()[idx];
472 _defineDocumentProperties: function($document) {
474 Object.defineProperty(doc, 'root', {get: function() {
475 return doc.createDocumentNode($document[0]);
476 }, configurable: true});
477 Object.defineProperty(doc, 'dom', {get: function() {
479 }, configurable: true});
485 documentFromXML: function(xml) {
486 var doc = new Document(xml);
490 elementNodeFromXML: function(xml) {
491 return this.documentFromXML(xml).root;
495 DocumentNode: DocumentNode,
496 ElementNode: ElementNode,