1 define(function(require) {
5 var _ = require('libs/underscore'),
8 var getTransDesc = function(desc) {
9 if(typeof desc === 'function') {
13 throw new Error('Got transformation description without implementation.');
18 toret.createGenericTransformation = function(desc, name) {
19 desc = getTransDesc(desc);
21 var GenericTransformation = function(document, args) {
22 this.args = args || [];
24 var transformation = this;
25 // _.keys(this.args).forEach(function(key) {
26 // if(transformation.args[key].nodeType) { //@@ change to instanceof check, fix circular dependency
27 // var value = transformation.args[key],
28 // path = value.getPath();
29 // Object.defineProperty(transformation.args, key, {
31 // if(transformation.hasRun) {
32 // //console.log('returning via path');
33 // return transformation.document.getNodeByPath(path);
35 // //console.log('returning original arg');
44 // potem spr na dotychczasowych undo/redo tests;
46 var patchObject = function(obj, depth) {
47 depth = _.isNumber(depth) ? depth : 1;
51 _.keys(obj).forEach(function(key) {
55 transformation.wrapNodeProperty(obj, key);
56 } else if(_.isObject(value)) {
57 patchObject(value, depth+1);
63 this.args.forEach(function(arg, idx, args) {
65 if(arg.nodeType) { // ~
66 transformation.wrapNodeProperty(args, idx);
67 } else if(_.isObject(arg)) {
73 this.document = document;
79 _.extend(GenericTransformation.prototype, {
81 run: function(options) {
83 if(!desc.undo && options.beUndoable) {
84 changeRoot = this.getChangeRoot();
87 'Transformation {name} returned invalid change root value'
88 .replace('{name}', name)
91 this.changeRootPath = changeRoot.getPath();
92 this.snapshot = changeRoot.clone();
94 var argsToPass = desc.undo ? [this].concat(this.args) : this.args;
95 var toret = desc.impl.apply(this.context, argsToPass);
101 desc.undo.call(this.context, this);
103 this.document.getNodeByPath(this.changeRootPath).replaceWith(this.snapshot);
106 getChangeRoot: desc.getChangeRoot || function() {
107 return this.document.root;
109 wrapNodeProperty: function(object, propName, value) {
110 var transformation = this,
113 value = value || object[propName];
114 if(value && value.nodeType) {
115 path = value.getPath();
116 Object.defineProperty(object, propName, {
118 if(transformation.hasRun && path) {
119 return transformation.document.getNodeByPath(path);
129 return GenericTransformation;
132 toret.createContextTransformation = function(desc, name) {
133 var GenericTransformation = toret.createGenericTransformation(desc, name);
135 var ContextTransformation = function(document, object, args) {
136 GenericTransformation.call(this, document, args);
138 if(document === object) {
139 this.context = document;
141 this.wrapNodeProperty(this, 'context', object);
144 ContextTransformation.prototype = Object.create(GenericTransformation.prototype);
145 return ContextTransformation;