1 define(function(require) {
5 var _ = require('libs/underscore'),
9 var getTransDesc = function(desc) {
10 if(typeof desc === 'function') {
14 throw new Error('Got transformation description without implementation.');
19 toret.createGenericTransformation = function(desc, name) {
20 desc = getTransDesc(desc);
22 var GenericTransformation = function(document, args) {
23 this.args = args || [];
24 var transformation = this;
26 var patchObject = function(obj, depth) {
27 depth = _.isNumber(depth) ? depth : 1;
31 _.keys(obj).forEach(function(key) {
35 transformation.wrapNodeProperty(obj, key);
36 } else if(_.isObject(value)) {
37 patchObject(value, depth+1);
43 this.args.forEach(function(arg, idx, args) {
45 if(arg.nodeType) { // ~
46 transformation.wrapNodeProperty(args, idx);
47 } else if(_.isObject(arg)) {
53 this.document = document;
59 _.extend(GenericTransformation.prototype, {
61 run: function(options) {
63 if(!desc.undo && options.beUndoable) {
64 changeRoot = this.getChangeRoot();
67 'Transformation {name} returned invalid change root value'
68 .replace('{name}', name)
71 this.changeRootPath = changeRoot.getPath();
72 this.snapshot = changeRoot.clone();
74 var argsToPass = desc.undo ? [this].concat(this.args) : this.args;
75 var toret = desc.impl.apply(this.context, argsToPass);
81 desc.undo.call(this.context, this);
84 this.document.getNodeByPath(this.changeRootPath).replaceWith(this.snapshot);
87 getChangeRoot: desc.getChangeRoot || function() {
88 return this.document.root;
90 wrapNodeProperty: function(object, propName, value) {
91 var transformation = this,
95 value = value || object[propName];
96 if(value && value.nodeType) {
97 path = value.getPath();
98 Object.defineProperty(object, propName, {
100 if((lastRunNumber !== transformation.runCount) && path) {
101 value = transformation.document.getNodeByPath(path);
102 lastRunNumber = transformation.runCount;
111 return GenericTransformation;
114 toret.createContextTransformation = function(desc, name) {
115 var GenericTransformation = toret.createGenericTransformation(desc, name);
117 var ContextTransformation = function(document, object, args) {
118 GenericTransformation.call(this, document, args);
120 if(document === object) {
121 this.context = document;
123 this.wrapNodeProperty(this, 'context', object);
126 ContextTransformation.prototype = Object.create(GenericTransformation.prototype);
127 return ContextTransformation;