<commit_before>/**
    Featherbone is a JavaScript based persistence framework for building object
    relational database applications

    Copyright (C) 2015  John Rogelstad
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

(function (exports) {

  var conn,
    pg = require("pg"),
    controller = require("./controller"),
    readPgConfig = require("./pgconfig"),
    registered = {
      GET: {},
      POST: {},
      PUT: {},
      PATCH: {},
      DELETE: {}
    },
    that = {};

  /**
    Request.

    Example payload:
        {
           "name": "Contact",
           "method": "POST",
           "data": {
             "id": "1f8c8akkptfe",
             "created": "2015-04-26T12:57:57.896Z",
             "createdBy": "admin",
             "updated": "2015-04-26T12:57:57.896Z",
             "updatedBy": "admin",
             "fullName": "John Doe",
             "birthDate": "1970-01-01T00:00:00.000Z",
             "isMarried": true,
             "dependentes": 2
           }
        }

    @param {Object} Payload
    @param {String} [payload.name] Name of model or function
    @param {String} [payload.method] Method to perform: "GET", "POST",
      "PUT", "PATCH" or "DELETE"
    @param {String} [payload.id] Identifier for "GET", "PATCH" ond "DELETE"
    @param {String} [payload.data] Data for "POST" and "PATCH" or functions
    @param {Object} [payload.client] Database client. If undefined one will
      be intialized by default and wrapped in a transaction if necessary.
    @param {String} [payload.callback] Callback
    @param {Boolean} Bypass authorization checks. Default = false.
    @return receiver
  */
  that.request = function (obj, isSuperUser) {
    isSuperUser = isSuperUser === undefined ? false : isSuperUser;

    var client, done, transaction, connect,
      doRequest, afterTransaction, afterRequest,
      callback = obj.callback;

    connect = function () {
      pg.connect(conn, function (err, c, d) {
        client = c;
        done = d;

        // handle an error from the connection
        if (err) {
          controller.setCurrentUser(undefined);
          console.error("Could not connect to server", err);
          obj.callback(err);
          return;
        }

        doRequest();
      });
    };

    doRequest = function (err) {
      if (err) {
        afterRequest(err);
        return;
      }

      client.currentUser = obj.user;

      // If registered function, execute it
      if (typeof registered[obj.method][obj.name] === "function") {
        obj.data.client = client;
        transaction = registered[obj.method][obj.name];
        obj = obj.data;

      // Otherwise handle as model
      } else {
        obj.client = client;

        switch (obj.method) {
        case "GET":
          obj.callback = afterRequest;
          controller.doSelect(obj, false, isSuperUser);
          return;
        case "POST":
          transaction = controller.doInsert;
          break;
        case "PATCH":
          transaction = controller.doUpdate;
          break;
        case "DELETE":
          transaction = controller.doDelete;
          break;
        default:
          obj.callback("method \"" + obj.method + "\" unknown");
        }
      }

      // Wrap transactions
      if (transaction && !obj.client) {
        obj.callback = afterTransaction;
        obj.client.query("BEGIN;", function (err, resp) {
          if (err) {
            obj.callback(err);
            return;
          }

          transaction(obj, false, isSuperUser);
        });
        return;
      }

      // Passed client must handle its own transaction wrapping
      obj.callback = afterRequest;
      transaction(obj, false, isSuperUser);
    };

    afterTransaction = function (err, resp) {
      if (err) {
        obj.client.query("ROLLBACK;", function (e, resp) {
          afterRequest(err);
        });

        return;
      }

      obj.client.query("COMMIT;", function (err) {
        if (err) {
          afterRequest(err);
          return;
        }

        afterRequest(null, resp);
      });
    };

    afterRequest = function (err, resp) {
      // Passed client will handle it's own connection
      if (!obj.client) { done(); }

      // Format errors into objects that can be handled by server
      if (err) {
        console.error(err);
        if (typeof err === "object") {
          err = {message: err.message, statusCode: err.statusCode || 500};
        } else {
          err = {message: err, statusCode: 500};
        }
        err.isError = true;
        callback(err);
        return;
      }

      // Otherwise return response
      callback(null, resp);
    };

    if (obj.client) {
      client = obj.client;
      doRequest();
      return;
    }

    if (conn) {
      connect();
      return;
    }

    // Read configuration if necessary
    readPgConfig(function (config) {
      conn = "postgres://" +
        config.user + ":" +
        config.password + "@" +
        config.server + "/" +
        config.database;
      connect();
    });

    return this;
  };

  /**
    Register a function that can be called by a method type. Use
    this to expose function calls via `request`. As a rule, all
    functions must accept an object as an argument whose properties
    can be used to calculate the result. The object should be passed
    as `data` on the request.

    The object should include a callback to forward a response on
    completion. The callback should accept an error as the first
    argument and a response as the second.

    The request will automatically append an active client to the object
    to use for executing queries.

      var fn, callback, datasource = require(./datasource);

      // Create a function that queries something
      fn = function (obj) {
        var sql = "SELECT foo FROM bar WHERE id=$1;",
          params = [obj.id];

        obj.client.query(sql, params, function (err, resp) {
          if (err) {
            obj.callback(err);
            return;
          }

          obj.callback(null, resp.rows);
        })
      }

      // Register the function
      datasource.registerFunction("GET", "myQuery", fn);

      // Define a callback to use when calling our function
      callback = function (err, resp) {
        if (err) {
          console.error(err);
          return;
        }

        console.log("Query rows->", resp);
      }

      // Execute a request that calls our function and sends a response
      // via the callback
      datasource.request({
        method: "GET",
        name: "myQuery",
        callback: callback,
        data: {
          id: "HTJ28n"
        }
      });

    @param {String} Function name
    @param {String} Method. "GET", "POST", "PUT", "PATCH", or "DELETE"
    @param {Function} Function
    @return receiver
  */
  that.registerFunction = function (method, name, func) {
    registered[method][name] = func;
    return this;
  };

  /**
    @return {Object} Object listing register functions
  */
  that.registeredFunctions = function () {
    var keys = Object.keys(registered),
      result = {};

    keys.forEach(function (key) {
      result[key] = Object.keys(registered[key]);
    });

    return result;
  };

  // Set properties on exports
  Object.keys(that).forEach(function (key) {
    exports[key] = that[key];
  });

  // Register certain functions
  that.registerFunction("GET", "getAuthorization", controller.getAuthorization);
  that.registerFunction("GET", "isAuthorized", controller.isAuthorized);
  that.registerFunction("GET", "isSuperUser", controller.isSuperUser);
  that.registerFunction("GET", "getSettings", controller.getSettings);
  that.registerFunction("GET", "getModel", controller.getModel);
  that.registerFunction("PUT", "saveAuthorization",
    controller.saveAuthorization);
  that.registerFunction("PUT", "saveModel", controller.saveModel);
  that.registerFunction("PUT", "saveSettings", controller.saveSettings);
  that.registerFunction("PUT", "setSuperUser", controller.setSuperUser);
  that.registerFunction("DELETE", "deleteModel", controller.deleteModel);

}(exports));

<commit_msg>Make sure client is released to the pool.<commit_after>/**
    Featherbone is a JavaScript based persistence framework for building object
    relational database applications

    Copyright (C) 2015  John Rogelstad
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

(function (exports) {

  var conn,
    pg = require("pg"),
    controller = require("./controller"),
    readPgConfig = require("./pgconfig"),
    registered = {
      GET: {},
      POST: {},
      PUT: {},
      PATCH: {},
      DELETE: {}
    },
    that = {};

  /**
    Request.

    Example payload:
        {
           "name": "Contact",
           "method": "POST",
           "data": {
             "id": "1f8c8akkptfe",
             "created": "2015-04-26T12:57:57.896Z",
             "createdBy": "admin",
             "updated": "2015-04-26T12:57:57.896Z",
             "updatedBy": "admin",
             "fullName": "John Doe",
             "birthDate": "1970-01-01T00:00:00.000Z",
             "isMarried": true,
             "dependentes": 2
           }
        }

    @param {Object} Payload
    @param {String} [payload.name] Name of model or function
    @param {String} [payload.method] Method to perform: "GET", "POST",
      "PUT", "PATCH" or "DELETE"
    @param {String} [payload.id] Identifier for "GET", "PATCH" ond "DELETE"
    @param {String} [payload.data] Data for "POST" and "PATCH" or functions
    @param {Object} [payload.client] Database client. If undefined one will
      be intialized by default and wrapped in a transaction if necessary.
    @param {String} [payload.callback] Callback
    @param {Boolean} Bypass authorization checks. Default = false.
    @return receiver
  */
  that.request = function (obj, isSuperUser) {
    isSuperUser = isSuperUser === undefined ? false : isSuperUser;

    var client, done, transaction, connect,
      doRequest, afterTransaction, afterRequest,
      callback = obj.callback,
      externalClient = false;

    connect = function () {
      pg.connect(conn, function (err, c, d) {
        client = c;
        done = d;

        // handle an error from the connection
        if (err) {
          controller.setCurrentUser(undefined);
          console.error("Could not connect to server", err);
          obj.callback(err);
          return;
        }

        doRequest();
      });
    };

    doRequest = function (err) {
      if (err) {
        afterRequest(err);
        return;
      }

      client.currentUser = obj.user;

      // If registered function, execute it
      if (typeof registered[obj.method][obj.name] === "function") {
        obj.data.client = client;
        transaction = registered[obj.method][obj.name];
        obj = obj.data;

      // Otherwise handle as model
      } else {
        obj.client = client;

        switch (obj.method) {
        case "GET":
          obj.callback = afterRequest;
          controller.doSelect(obj, false, isSuperUser);
          return;
        case "POST":
          transaction = controller.doInsert;
          break;
        case "PATCH":
          transaction = controller.doUpdate;
          break;
        case "DELETE":
          transaction = controller.doDelete;
          break;
        default:
          obj.callback("method \"" + obj.method + "\" unknown");
        }
      }

      // Wrap transactions
      if (transaction && !obj.client) {
        obj.callback = afterTransaction;
        obj.client.query("BEGIN;", function (err, resp) {
          if (err) {
            obj.callback(err);
            return;
          }

          transaction(obj, false, isSuperUser);
        });
        return;
      }

      // Passed client must handle its own transaction wrapping
      obj.callback = afterRequest;
      transaction(obj, false, isSuperUser);
    };

    afterTransaction = function (err, resp) {
      if (err) {
        obj.client.query("ROLLBACK;", function (e, resp) {
          afterRequest(err);
        });

        return;
      }

      obj.client.query("COMMIT;", function (err) {
        if (err) {
          afterRequest(err);
          return;
        }

        afterRequest(null, resp);
      });
    };

    afterRequest = function (err, resp) {
      // Passed client will handle it's own connection
      if (!externalClient) { done(); }

      // Format errors into objects that can be handled by server
      if (err) {
        console.error(err);
        if (typeof err === "object") {
          err = {message: err.message, statusCode: err.statusCode || 500};
        } else {
          err = {message: err, statusCode: 500};
        }
        err.isError = true;
        callback(err);
        return;
      }

      // Otherwise return response
      callback(null, resp);
    };

    if (obj.client) {
      externalClient = true;
      client = obj.client;
      doRequest();
      return;
    }

    if (conn) {
      connect();
      return;
    }

    // Read configuration if necessary
    readPgConfig(function (config) {
      conn = "postgres://" +
        config.user + ":" +
        config.password + "@" +
        config.server + "/" +
        config.database;
      connect();
    });

    return this;
  };

  /**
    Register a function that can be called by a method type. Use
    this to expose function calls via `request`. As a rule, all
    functions must accept an object as an argument whose properties
    can be used to calculate the result. The object should be passed
    as `data` on the request.

    The object should include a callback to forward a response on
    completion. The callback should accept an error as the first
    argument and a response as the second.

    The request will automatically append an active client to the object
    to use for executing queries.

      var fn, callback, datasource = require(./datasource);

      // Create a function that queries something
      fn = function (obj) {
        var sql = "SELECT foo FROM bar WHERE id=$1;",
          params = [obj.id];

        obj.client.query(sql, params, function (err, resp) {
          if (err) {
            obj.callback(err);
            return;
          }

          obj.callback(null, resp.rows);
        })
      }

      // Register the function
      datasource.registerFunction("GET", "myQuery", fn);

      // Define a callback to use when calling our function
      callback = function (err, resp) {
        if (err) {
          console.error(err);
          return;
        }

        console.log("Query rows->", resp);
      }

      // Execute a request that calls our function and sends a response
      // via the callback
      datasource.request({
        method: "GET",
        name: "myQuery",
        callback: callback,
        data: {
          id: "HTJ28n"
        }
      });

    @param {String} Function name
    @param {String} Method. "GET", "POST", "PUT", "PATCH", or "DELETE"
    @param {Function} Function
    @return receiver
  */
  that.registerFunction = function (method, name, func) {
    registered[method][name] = func;
    return this;
  };

  /**
    @return {Object} Object listing register functions
  */
  that.registeredFunctions = function () {
    var keys = Object.keys(registered),
      result = {};

    keys.forEach(function (key) {
      result[key] = Object.keys(registered[key]);
    });

    return result;
  };

  // Set properties on exports
  Object.keys(that).forEach(function (key) {
    exports[key] = that[key];
  });

  // Register certain functions
  that.registerFunction("GET", "getAuthorization", controller.getAuthorization);
  that.registerFunction("GET", "isAuthorized", controller.isAuthorized);
  that.registerFunction("GET", "isSuperUser", controller.isSuperUser);
  that.registerFunction("GET", "getSettings", controller.getSettings);
  that.registerFunction("GET", "getModel", controller.getModel);
  that.registerFunction("PUT", "saveAuthorization",
    controller.saveAuthorization);
  that.registerFunction("PUT", "saveModel", controller.saveModel);
  that.registerFunction("PUT", "saveSettings", controller.saveSettings);
  that.registerFunction("PUT", "setSuperUser", controller.setSuperUser);
  that.registerFunction("DELETE", "deleteModel", controller.deleteModel);

}(exports));

<|endoftext|>


<commit_before>Ext.namespace('Vpc.Abstract.List');

Vpc.Abstract.List.MultiFileUploadPanel = Ext.extend(Ext.Panel,
{
    afterRender: function() {
        Vpc.Abstract.List.MultiFileUploadPanel.superclass.afterRender.call(this);

        var container = this.body.createChild();

        if (!Vps.Utils.Upload.supportsHtml5Upload()) {
            this.swfu = new Vps.Utils.SwfUpload({
                fileSizeLimit: this.list.multiFileUpload.fileSizeLimit,
                allowOnlyImages: this.list.multiFileUpload.allowOnlyImages,
                buttonPlaceholderId: container.id,
                postParams: {
                    maxResolution: this.list.multiFileUpload.maxResolution
                },
                buttonText: trlVps('Upload Files'),
                selectMultiple: true
            });
            this.swfu.on('fileQueued', function(file) {
                if (!this.files) this.files = [];
                this.files.push(file.id);

                if (this.running) {
                    return;
                }

                this.uploadedIds = [];
                this.running = true;
                this.progress = Ext.MessageBox.show({
                    title : trlVps('Upload'),
                    msg : trlVps('Uploading files'),
                    buttons: false,
                    progress:true,
                    closable:false,
                    minWidth: 250,
                    buttons: Ext.MessageBox.CANCEL,
                    scope: this,
                    fn: function(button) {
                        for(var i=0;i<this.files.length;i++) {
                            if (this.swfu.getFile(i)) this.swfu.cancelUpload(this.swfu.getFile(i).id);
                        }
                        this.files = [];
                        this.running = false;
                    }
                });
                this.swfu.startUpload(file.id);
            }, this);
            this.swfu.on('uploadProgress', function(file, done, total) {
                var total = 0;
                var sumDone = 0;
                for(var i=0;i<this.files.length;i++) {
                    total += this.swfu.getFile(i).size;
                    if (this.swfu.getFile(i).id == file.id) {
                        sumDone += done;
                    } else if (this.swfu.getFile(i).filestatus != SWFUpload.FILE_STATUS.QUEUED) {
                        sumDone += this.swfu.getFile(i).size;
                    }
                }
                this.progress.updateProgress(sumDone/total);
            }, this);
            this.swfu.on('uploadSuccess', function(file, r) {
                this.uploadedIds.push(r.value.uploadId);

                for(var i=0;i<this.files.length;i++) {
                    if (this.swfu.getFile(i).filestatus == SWFUpload.FILE_STATUS.QUEUED) {
                        //neeext
                        this.swfu.startUpload(this.swfu.getFile(i).id);
                        return;
                    }
                }
                this.running = false;
                this.files = [];
                this.progress.hide();

                var params = Ext.apply(this.list.getBaseParams(), { uploadIds: this.uploadedIds.join(',')});
                Ext.Ajax.request({
                    url: this.list.controllerUrl+'/json-multi-upload',
                    params: params,
                    success: function() {
                        this.list.grid.reload();
                    },
                    scope: this
                })
            }, this);
            this.swfu.on('uploadError', function(file, errorCode, errorMessage) {
                this.progress.hide();
            }, this);
        } else {
            container.setStyle('position', 'relative');
            this.uploadButton = new Ext.Button({
                text: trlVps('Upload Files'),
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/add.png',
                renderTo: container
            });

            var fileInputContainer = container.createChild({
                style: 'width: 120px; height: 20px; top: 0; position: absolute; overflow: hidden;'
            });

            var fileInput = fileInputContainer.createChild({
                tag: 'input',
                type: 'file',
                multiple: 'multiple',
                style: 'opacity: 0; cursor: pointer; '
            });
            fileInput.on('change', function(ev, dom) {
                if (dom.files) {
                    this.html5UploadFiles(dom.files);
                    dom.value = ''; //leeren, damit gleiche datei nochmal gewählt werden kann
                }
            }, this);

            this.list.westPanel.el.on('dragenter', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
            }, this);
            this.list.westPanel.el.on('dragover', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
            }, this);
            this.list.westPanel.el.on('drop', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
                if (e.browserEvent.dataTransfer) {
                    this.html5UploadFiles(e.browserEvent.dataTransfer.files);
                }
            }, this);
        }
    },
    html5UploadFiles: function(files)
    {
        if (!files.length) return;

        this.progress = Ext.MessageBox.show({
            title : trlVps('Upload'),
            msg : trlVps('Uploading files'),
            buttons: false,
            progress:true,
            closable:false,
            minWidth: 250,
            buttons: Ext.MessageBox.CANCEL,
            scope: this,
            fn: function(button) {
                this.fileQueue = [];
                this.currentXhr.abort();
            }
        });

        this.processedFiles = [];
        this.fileQueue = [];
        this.uploadedIds = [];
        for(var i=0;i<files.length;++i) {
            this.fileQueue.push(files[i]);
        }
        this.html5UploadFile();
    },

    updateProgress: function(e)
    {
        var total = 0;
        if (e && e.total) total += e.total;
        var loaded = 0;
        if (e && e.loaded) loaded += e.loaded;
        this.processedFiles.forEach(function(f) {
            total += f.size;
            loaded += f.size;
        }, this);
        this.fileQueue.forEach(function(f) {
            total += f.size;
        }, this);
        this.progress.updateProgress(loaded / total);
    },

    html5UploadFile: function()
    {
        var file = this.fileQueue.pop();
        this.currentXhr = Vps.Utils.Upload.uploadFile({
            maxResolution: this.maxResolution,
            file: file,
            success: function(r, options) {
                this.processedFiles.push(options.file);
                this.uploadedIds.push(r.value.uploadId);
                if (this.fileQueue.length) {
                    this.updateProgress();
                    this.html5UploadFile(); //neext
                } else {
                    var params = Ext.apply(this.list.getBaseParams(), { uploadIds: this.uploadedIds.join(',')});
                    Ext.Ajax.request({
                        url: this.list.controllerUrl+'/json-multi-upload',
                        params: params,
                        success: function() {
                            this.progress.hide();
                            this.list.grid.reload();
                        },
                        scope: this
                    });
                }
            },
            failure: function() {
                this.progress.hide();
            },
            progress: function(e) {
                this.updateProgress(e);
            },
            scope: this
        });
    },
    onDestroy: function() {
        this.swfu.destroy();
    }
});
Vpc.Abstract.List.Panel = Ext.extend(Vps.Binding.ProxyPanel,
{
    border: false,
    initComponent: function()
    {
        this.childPanel = Ext.ComponentMgr.create(Ext.applyIf(this.childConfig, {
            region: 'center'
        }));

        this.grid = new Vps.Auto.GridPanel({
            controllerUrl: this.controllerUrl,
            split: true,
            region: 'center',
            baseParams: this.baseParams, //Kompatibilität zu ComponentPanel
            autoLoad: this.autoLoad,
            bindings: [{
                item        : this.childPanel,
                componentIdSuffix: '-{0}'
            }],
            onAdd: this.onAdd
        });
        this.proxyItem = this.grid;

        this.grid.on('datachange', function() {
            this.childPanel.reload();
        }, this);

        var westItems = [this.grid];

        if (this.multiFileUpload) {
            this.multiFileUploadPanel = new Vpc.Abstract.List.MultiFileUploadPanel({
                border: false,
                region: 'south',
                height: 50,
                bodyStyle: 'padding-top: 15px; padding-left:80px;',
                list: this
            });
            westItems.push(this.multiFileUploadPanel);
        }

        this.westPanel = new Ext.Panel({
            layout: 'border',
            region: 'west',
            width: 300,
            border: false,
            items: westItems
        });

        this.layout = 'border';
        this.items = [this.westPanel, this.childPanel];
        Vpc.Abstract.List.Panel.superclass.initComponent.call(this);
    },

    load: function()
    {
        this.grid.load();
        this.grid.selectId(false);

        this.childPanel.setBaseParams({});
        var f = this.childPanel.getForm();
        if (f) {
            f.clearValues();
            f.clearInvalid();
        }
        this.childPanel.disable();
    },

    onAdd : function()
    {
        Ext.Ajax.request({
            mask: true,
            url: this.controllerUrl + '/json-insert',
            params: this.getBaseParams(),
            success: function(response, options, r) {
                this.getSelectionModel().clearSelections();
                this.reload({
                    callback: function(o, r, s) {
                        this.getSelectionModel().selectLastRow();
                    },
                    scope: this
                });
            },
            scope: this
        });
    }
});
Ext.reg('vpc.list', Vpc.Abstract.List.Panel);
<commit_msg>Vpc_List: title fuer child ausblenden, der macht da keinen sinn<commit_after>Ext.namespace('Vpc.Abstract.List');

Vpc.Abstract.List.MultiFileUploadPanel = Ext.extend(Ext.Panel,
{
    afterRender: function() {
        Vpc.Abstract.List.MultiFileUploadPanel.superclass.afterRender.call(this);

        var container = this.body.createChild();

        if (!Vps.Utils.Upload.supportsHtml5Upload()) {
            this.swfu = new Vps.Utils.SwfUpload({
                fileSizeLimit: this.list.multiFileUpload.fileSizeLimit,
                allowOnlyImages: this.list.multiFileUpload.allowOnlyImages,
                buttonPlaceholderId: container.id,
                postParams: {
                    maxResolution: this.list.multiFileUpload.maxResolution
                },
                buttonText: trlVps('Upload Files'),
                selectMultiple: true
            });
            this.swfu.on('fileQueued', function(file) {
                if (!this.files) this.files = [];
                this.files.push(file.id);

                if (this.running) {
                    return;
                }

                this.uploadedIds = [];
                this.running = true;
                this.progress = Ext.MessageBox.show({
                    title : trlVps('Upload'),
                    msg : trlVps('Uploading files'),
                    buttons: false,
                    progress:true,
                    closable:false,
                    minWidth: 250,
                    buttons: Ext.MessageBox.CANCEL,
                    scope: this,
                    fn: function(button) {
                        for(var i=0;i<this.files.length;i++) {
                            if (this.swfu.getFile(i)) this.swfu.cancelUpload(this.swfu.getFile(i).id);
                        }
                        this.files = [];
                        this.running = false;
                    }
                });
                this.swfu.startUpload(file.id);
            }, this);
            this.swfu.on('uploadProgress', function(file, done, total) {
                var total = 0;
                var sumDone = 0;
                for(var i=0;i<this.files.length;i++) {
                    total += this.swfu.getFile(i).size;
                    if (this.swfu.getFile(i).id == file.id) {
                        sumDone += done;
                    } else if (this.swfu.getFile(i).filestatus != SWFUpload.FILE_STATUS.QUEUED) {
                        sumDone += this.swfu.getFile(i).size;
                    }
                }
                this.progress.updateProgress(sumDone/total);
            }, this);
            this.swfu.on('uploadSuccess', function(file, r) {
                this.uploadedIds.push(r.value.uploadId);

                for(var i=0;i<this.files.length;i++) {
                    if (this.swfu.getFile(i).filestatus == SWFUpload.FILE_STATUS.QUEUED) {
                        //neeext
                        this.swfu.startUpload(this.swfu.getFile(i).id);
                        return;
                    }
                }
                this.running = false;
                this.files = [];
                this.progress.hide();

                var params = Ext.apply(this.list.getBaseParams(), { uploadIds: this.uploadedIds.join(',')});
                Ext.Ajax.request({
                    url: this.list.controllerUrl+'/json-multi-upload',
                    params: params,
                    success: function() {
                        this.list.grid.reload();
                    },
                    scope: this
                })
            }, this);
            this.swfu.on('uploadError', function(file, errorCode, errorMessage) {
                this.progress.hide();
            }, this);
        } else {
            container.setStyle('position', 'relative');
            this.uploadButton = new Ext.Button({
                text: trlVps('Upload Files'),
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/add.png',
                renderTo: container
            });

            var fileInputContainer = container.createChild({
                style: 'width: 120px; height: 20px; top: 0; position: absolute; overflow: hidden;'
            });

            var fileInput = fileInputContainer.createChild({
                tag: 'input',
                type: 'file',
                multiple: 'multiple',
                style: 'opacity: 0; cursor: pointer; '
            });
            fileInput.on('change', function(ev, dom) {
                if (dom.files) {
                    this.html5UploadFiles(dom.files);
                    dom.value = ''; //leeren, damit gleiche datei nochmal gewählt werden kann
                }
            }, this);

            this.list.westPanel.el.on('dragenter', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
            }, this);
            this.list.westPanel.el.on('dragover', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
            }, this);
            this.list.westPanel.el.on('drop', function(e) {
                e.browserEvent.stopPropagation();
                e.browserEvent.preventDefault();
                if (e.browserEvent.dataTransfer) {
                    this.html5UploadFiles(e.browserEvent.dataTransfer.files);
                }
            }, this);
        }
    },
    html5UploadFiles: function(files)
    {
        if (!files.length) return;

        this.progress = Ext.MessageBox.show({
            title : trlVps('Upload'),
            msg : trlVps('Uploading files'),
            buttons: false,
            progress:true,
            closable:false,
            minWidth: 250,
            buttons: Ext.MessageBox.CANCEL,
            scope: this,
            fn: function(button) {
                this.fileQueue = [];
                this.currentXhr.abort();
            }
        });

        this.processedFiles = [];
        this.fileQueue = [];
        this.uploadedIds = [];
        for(var i=0;i<files.length;++i) {
            this.fileQueue.push(files[i]);
        }
        this.html5UploadFile();
    },

    updateProgress: function(e)
    {
        var total = 0;
        if (e && e.total) total += e.total;
        var loaded = 0;
        if (e && e.loaded) loaded += e.loaded;
        this.processedFiles.forEach(function(f) {
            total += f.size;
            loaded += f.size;
        }, this);
        this.fileQueue.forEach(function(f) {
            total += f.size;
        }, this);
        this.progress.updateProgress(loaded / total);
    },

    html5UploadFile: function()
    {
        var file = this.fileQueue.pop();
        this.currentXhr = Vps.Utils.Upload.uploadFile({
            maxResolution: this.maxResolution,
            file: file,
            success: function(r, options) {
                this.processedFiles.push(options.file);
                this.uploadedIds.push(r.value.uploadId);
                if (this.fileQueue.length) {
                    this.updateProgress();
                    this.html5UploadFile(); //neext
                } else {
                    var params = Ext.apply(this.list.getBaseParams(), { uploadIds: this.uploadedIds.join(',')});
                    Ext.Ajax.request({
                        url: this.list.controllerUrl+'/json-multi-upload',
                        params: params,
                        success: function() {
                            this.progress.hide();
                            this.list.grid.reload();
                        },
                        scope: this
                    });
                }
            },
            failure: function() {
                this.progress.hide();
            },
            progress: function(e) {
                this.updateProgress(e);
            },
            scope: this
        });
    },
    onDestroy: function() {
        this.swfu.destroy();
    }
});
Vpc.Abstract.List.Panel = Ext.extend(Vps.Binding.ProxyPanel,
{
    border: false,
    initComponent: function()
    {
        if (this.childConfig.title) delete this.childConfig.title;
        this.childPanel = Ext.ComponentMgr.create(Ext.applyIf(this.childConfig, {
            region: 'center'
        }));

        this.grid = new Vps.Auto.GridPanel({
            controllerUrl: this.controllerUrl,
            split: true,
            region: 'center',
            baseParams: this.baseParams, //Kompatibilität zu ComponentPanel
            autoLoad: this.autoLoad,
            bindings: [{
                item        : this.childPanel,
                componentIdSuffix: '-{0}'
            }],
            onAdd: this.onAdd
        });
        this.proxyItem = this.grid;

        this.grid.on('datachange', function() {
            this.childPanel.reload();
        }, this);

        var westItems = [this.grid];

        if (this.multiFileUpload) {
            this.multiFileUploadPanel = new Vpc.Abstract.List.MultiFileUploadPanel({
                border: false,
                region: 'south',
                height: 50,
                bodyStyle: 'padding-top: 15px; padding-left:80px;',
                list: this
            });
            westItems.push(this.multiFileUploadPanel);
        }

        this.westPanel = new Ext.Panel({
            layout: 'border',
            region: 'west',
            width: 300,
            border: false,
            items: westItems
        });

        this.layout = 'border';
        this.items = [this.westPanel, this.childPanel];
        Vpc.Abstract.List.Panel.superclass.initComponent.call(this);
    },

    load: function()
    {
        this.grid.load();
        this.grid.selectId(false);

        this.childPanel.setBaseParams({});
        var f = this.childPanel.getForm();
        if (f) {
            f.clearValues();
            f.clearInvalid();
        }
        this.childPanel.disable();
    },

    onAdd : function()
    {
        Ext.Ajax.request({
            mask: true,
            url: this.controllerUrl + '/json-insert',
            params: this.getBaseParams(),
            success: function(response, options, r) {
                this.getSelectionModel().clearSelections();
                this.reload({
                    callback: function(o, r, s) {
                        this.getSelectionModel().selectLastRow();
                    },
                    scope: this
                });
            },
            scope: this
        });
    }
});
Ext.reg('vpc.list', Vpc.Abstract.List.Panel);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var savingsPolicy = require('../policies/savings.server.policy'),
    savings = require('../controllers/savings.server.controller');

module.exports = function (app) {

    app.route('/api/savings/picture')
        .post(savings.changeProductPictureSaving);

    // Savings collection routes
    app.route('/api/savings').all(savingsPolicy.isAllowed)
        .get(savings.list)
        .post(savings.create);

    // Single saving routes
    app.route('/api/savings/:savingId')
        .all(savingsPolicy.isAllowed)
        .get(savings.read)
        .put(savings.update)
        .delete(savings.delete);

    // // Single saving routes
    // app.route('/api/savings/app/upvote/:savingId/:email')
    //     .put(savings.appUpvoteSaving)
    //     .get(savings.read);

    // Single saving routes
    app.route('/api/savings/app/downvote/:savingId/:email')
        .put(savings.appDownvoteSaving)
        .get(savings.read);

    app.route('/savings/savingCount').all()
        .get(savings.countSavings);

    app.route('/savings/savingCountToday').all()
        .get(savings.countSavingsToday);

    //app.route('/savings/usersSavingsPostedTotal').all()
    //    .get(savings.usersSavingsPostedTotal);

    app.route('/api/savings/of/:userid')
        .get(savings.listOf);

    app.route('/api/savings/of/:username')
        .get(savings.listOf);

    app.route('/savings/usersSavingsPostedTotal/:userIdString')
        .get(savings.usersSavingsPostedTotal);

    app.route('/savings/usersUpvotesTotal/:userIdString')
        .get(savings.usersUpvotesTotal);

    app.route('/savings/removeVotesDaily')
        .get(savings.removeVotesDaily);

    // Finish by binding the saving middleware
    app.param('savingId', savings.savingByID);
    app.param('userid', savings.listOf);
    app.param('userIdString', savings.usersSavingsPostedTotal);
    app.param('userIdString', savings.usersUpvotesTotal);
    app.param('email', savings.appUpvoteSaving);
    app.param('email1', savings.appDownvoteSaving);

};
<commit_msg>Routes.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var savingsPolicy = require('../policies/savings.server.policy'),
    savings = require('../controllers/savings.server.controller');

module.exports = function (app) {

    app.route('/api/savings/picture')
        .post(savings.changeProductPictureSaving);

    // Savings collection routes
    app.route('/api/savings').all(savingsPolicy.isAllowed)
        .get(savings.list)
        .post(savings.create);

    // Single saving routes
    app.route('/api/savings/:savingId')
        .all(savingsPolicy.isAllowed)
        .get(savings.read)
        .put(savings.update)
        .delete(savings.delete);

    // Single saving routes
    app.route('/api/savings/app/upvote/:savingId/:email')
        .put(savings.appUpvoteSaving)
        .get(savings.read);

    // Single saving routes
    app.route('/api/savings/app/downvote/:savingId/:email1')
        .put(savings.appDownvoteSaving)
        .get(savings.read);

    app.route('/savings/savingCount').all()
        .get(savings.countSavings);

    app.route('/savings/savingCountToday').all()
        .get(savings.countSavingsToday);

    //app.route('/savings/usersSavingsPostedTotal').all()
    //    .get(savings.usersSavingsPostedTotal);

    app.route('/api/savings/of/:userid')
        .get(savings.listOf);

    app.route('/api/savings/of/:username')
        .get(savings.listOf);

    app.route('/savings/usersSavingsPostedTotal/:userIdString')
        .get(savings.usersSavingsPostedTotal);

    app.route('/savings/usersUpvotesTotal/:userIdString')
        .get(savings.usersUpvotesTotal);

    app.route('/savings/removeVotesDaily')
        .get(savings.removeVotesDaily);

    // Finish by binding the saving middleware
    app.param('savingId', savings.savingByID);
    app.param('userid', savings.listOf);
    app.param('userIdString', savings.usersSavingsPostedTotal);
    app.param('userIdString', savings.usersUpvotesTotal);
    app.param('email', savings.appUpvoteSaving);
    app.param('email1', savings.appDownvoteSaving);

};
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracks.timeline_viewport_track');

base.require('tracks.timeline_track');
base.require('tracks.timeline_canvas_based_track');
base.require('ui');

base.exportTo('tracks', function() {

  /**
   * A track that displays the viewport size and scale.
   * @constructor
   * @extends {CanvasBasedTrack}
   */

  var TimelineViewportTrack = base.ui.define(tracks.TimelineCanvasBasedTrack);

  var logOf10 = Math.log(10);
  function log10(x) {
    return Math.log(x) / logOf10;
  }

  TimelineViewportTrack.prototype = {

    __proto__: tracks.TimelineCanvasBasedTrack.prototype,

    decorate: function() {
      this.classList.add('timeline-viewport-track');
      this.strings_secs_ = [];
      this.strings_msecs_ = [];
      this.addEventListener('mousedown', this.onMouseDown);
    },

    onMouseDown: function(e) {
      if (e.button != 0)
        return;
      this.placeAndBeginDraggingMarker(e.clientX);
    },

    placeAndBeginDraggingMarker: function(clientX) {
      var viewX = clientX - this.canvasContainer_.offsetLeft;
      var worldX = this.viewport_.xViewToWorld(viewX);
      var marker = this.viewport_.findMarkerNear(worldX, 6);
      var createdMarker = false;
      var movedMarker = false;
      if (!marker) {
        marker = this.viewport_.addMarker(worldX);
        createdMarker = true;
      }
      marker.selected = true;

      var that = this;
      var onMouseMove = function(e) {
        var viewX = e.clientX - that.canvasContainer_.offsetLeft;
        var worldX = that.viewport_.xViewToWorld(viewX);
        marker.positionWorld = worldX;
        movedMarker = true;
      };

      var onMouseUp = function(e) {
        marker.selected = false;
        if (!movedMarker && !createdMarker)
          that.viewport_.removeMarker(marker);
        document.removeEventListener('mouseup', onMouseUp);
        document.removeEventListener('mousemove', onMouseMove);
      };

      document.addEventListener('mouseup', onMouseUp);
      document.addEventListener('mousemove', onMouseMove);
    },

    drawLine_: function(ctx, x1, y1, x2, y2, color) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.closePath();
      ctx.strokeStyle = color;
      ctx.stroke();
    },

    drawArrow_: function(ctx, x1, y1, x2, y2, arrowWidth, color) {

      this.drawLine_(ctx, x1, y1, x2, y2, color);

      var dx = x2 - x1;
      var dy = y2 - y1;
      var len = Math.sqrt(dx * dx + dy * dy);
      var perc = (len - 10) / len;
      var bx = x1 + perc * dx;
      var by = y1 + perc * dy;
      var ux = dx / len;
      var uy = dy / len;
      var ax = uy * arrowWidth;
      var ay = -ux * arrowWidth;

      ctx.beginPath();
      ctx.fillStyle = color;
      ctx.moveTo(bx + ax, by + ay);
      ctx.lineTo(x2, y2);
      ctx.lineTo(bx - ax, by - ay);
      ctx.lineTo(bx + ax, by + ay);
      ctx.closePath();
      ctx.fill();
    },

    redraw: function() {
      var ctx = this.ctx_;
      var canvasW = this.canvas_.width;
      var canvasH = this.canvas_.height;

      ctx.clearRect(0, 0, canvasW, canvasH);

      // Culling parametrs.
      var vp = this.viewport_;
      var pixWidth = vp.xViewVectorToWorld(1);
      var viewLWorld = vp.xViewToWorld(0);
      var viewRWorld = vp.xViewToWorld(canvasW);

      var measurements = this.classList.contains('timeline-viewport' +
          '-track-with-distance-measurements');

      var rulerHeight = measurements ? canvasH / 2 : canvasH;

      for (var i = 0; i < vp.markers.length; ++i) {
        vp.markers[i].drawTriangle_(ctx, viewLWorld, viewRWorld,
                                    canvasH, rulerHeight, vp);
      }

      var idealMajorMarkDistancePix = 150;
      var idealMajorMarkDistanceWorld =
          vp.xViewVectorToWorld(idealMajorMarkDistancePix);

      var majorMarkDistanceWorld;
      var unit;
      var unitDivisor;
      var tickLabels;

      // The conservative guess is the nearest enclosing 0.1, 1, 10, 100, etc.
      var conservativeGuess =
          Math.pow(10, Math.ceil(log10(idealMajorMarkDistanceWorld)));

      // Once we have a conservative guess, consider things that evenly add up
      // to the conservative guess, e.g. 0.5, 0.2, 0.1 Pick the one that still
      // exceeds the ideal mark distance.
      var divisors = [10, 5, 2, 1];
      for (var i = 0; i < divisors.length; ++i) {
        var tightenedGuess = conservativeGuess / divisors[i];
        if (vp.xWorldVectorToView(tightenedGuess) < idealMajorMarkDistancePix)
          continue;
        majorMarkDistanceWorld = conservativeGuess / divisors[i - 1];
        break;
      }
      var tickLabels = undefined;
      if (majorMarkDistanceWorld < 100) {
        unit = 'ms';
        unitDivisor = 1;
        tickLabels = this.strings_msecs_;
      } else {
        unit = 's';
        unitDivisor = 1000;
        tickLabels = this.strings_secs_;
      }

      var numTicksPerMajor = 5;
      var minorMarkDistanceWorld = majorMarkDistanceWorld / numTicksPerMajor;
      var minorMarkDistancePx = vp.xWorldVectorToView(minorMarkDistanceWorld);

      var firstMajorMark =
          Math.floor(viewLWorld / majorMarkDistanceWorld) *
              majorMarkDistanceWorld;

      var minorTickH = Math.floor(canvasH * 0.25);

      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.strokeStyle = 'rgb(0, 0, 0)';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';

      var pixelRatio = window.devicePixelRatio || 1;
      ctx.font = (9 * pixelRatio) + 'px sans-serif';

      // Each iteration of this loop draws one major mark
      // and numTicksPerMajor minor ticks.
      //
      // Rendering can't be done in world space because canvas transforms
      // affect line width. So, do the conversions manually.
      for (var curX = firstMajorMark;
           curX < viewRWorld;
           curX += majorMarkDistanceWorld) {

        var curXView = Math.floor(vp.xWorldToView(curX));

        var unitValue = curX / unitDivisor;
        var roundedUnitValue = Math.floor(unitValue * 100000) / 100000;

        if (!tickLabels[roundedUnitValue])
          tickLabels[roundedUnitValue] = roundedUnitValue + ' ' + unit;
        ctx.fillText(tickLabels[roundedUnitValue],
                     curXView + 2 * pixelRatio, 0);
        ctx.beginPath();

        // Major mark
        ctx.moveTo(curXView, 0);
        ctx.lineTo(curXView, rulerHeight);

        // Minor marks
        for (var i = 1; i < numTicksPerMajor; ++i) {
          var xView = Math.floor(curXView + minorMarkDistancePx * i);
          ctx.moveTo(xView, rulerHeight - minorTickH);
          ctx.lineTo(xView, rulerHeight);
        }

        ctx.stroke();
      }

      // Give distance between directly adjacent markers.
      if (measurements) {

        // Divide canvas horizontally between ruler and measurements.
        ctx.moveTo(0, rulerHeight);
        ctx.lineTo(canvasW, rulerHeight);
        ctx.stroke();

        // Obtain a sorted array of markers
        var sortedMarkers = vp.markers.slice();
        sortedMarkers.sort(function(a, b) {
          return a.positionWorld_ - b.positionWorld_;
        });

        // Distance Variables.
        var displayDistance;
        var unitDivisor;
        var displayTextColor = 'rgb(0,0,0)';
        var measurementsPosY = rulerHeight + 2;

        // Arrow Variables.
        var arrowSpacing = 10;
        var arrowColor = 'rgb(128,121,121)';
        var arrowPosY = measurementsPosY + 4;
        var arrowWidthView = 3;
        var spaceForArrowsView = 2 * (arrowWidthView + arrowSpacing);

        for (i = 0; i < sortedMarkers.length - 1; i++) {
          var rightMarker = sortedMarkers[i + 1];
          var leftMarker = sortedMarkers[i];
          var distanceBetweenMarkers =
              rightMarker.positionWorld - leftMarker.positionWorld;
          var distanceBetweenMarkersView =
              vp.xWorldVectorToView(distanceBetweenMarkers);

          var positionInMiddleOfMarkers = leftMarker.positionWorld +
                                              distanceBetweenMarkers / 2;
          var positionInMiddleOfMarkersView =
              vp.xWorldToView(positionInMiddleOfMarkers);

          // Determine units.
          if (distanceBetweenMarkers < 100) {
            unit = 'ms';
            unitDivisor = 1;
          } else {
            unit = 's';
            unitDivisor = 1000;
          }
          // Calculate display value to print.
          displayDistance = distanceBetweenMarkers / unitDivisor;
          var roundedDisplayDistance =
              Math.abs((Math.floor(displayDistance * 1000) / 1000));
          var textToDraw = roundedDisplayDistance + ' ' + unit;
          var textWidthView = ctx.measureText(textToDraw).width;
          var textWidthWorld = vp.xViewVectorToWorld(textWidthView);
          var spaceForArrowsAndTextView = textWidthView +
                                          spaceForArrowsView + arrowSpacing;

          // Set text positions.
          var textLeft = leftMarker.positionWorld +
              (distanceBetweenMarkers / 2) - (textWidthWorld / 2);
          var textRight = textLeft + textWidthWorld;
          var textPosY = measurementsPosY;
          var textLeftView = vp.xWorldToView(textLeft);
          var textRightView = vp.xWorldToView(textRight);
          var leftMarkerView = vp.xWorldToView(leftMarker.positionWorld);
          var rightMarkerView = vp.xWorldToView(rightMarker.positionWorld);
          var textDrawn = false;

          if (spaceForArrowsAndTextView <= distanceBetweenMarkersView) {
            // Print the display distance text.
            ctx.fillStyle = displayTextColor;
            ctx.fillText(textToDraw, textLeftView, textPosY);
            textDrawn = true;
          }

          if (spaceForArrowsView <= distanceBetweenMarkersView) {
            var leftArrowStart;
            var rightArrowStart;
            if (textDrawn) {
              leftArrowStart = textLeftView - arrowSpacing;
              rightArrowStart = textRightView + arrowSpacing;
            } else {
              leftArrowStart = positionInMiddleOfMarkersView;
              rightArrowStart = positionInMiddleOfMarkersView;
            }
            // Draw left arrow.
            this.drawArrow_(ctx, leftArrowStart, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            // Draw right arrow.
            this.drawArrow_(ctx, rightArrowStart, arrowPosY,
                rightMarkerView, arrowPosY, arrowWidthView, arrowColor);
          }
        }
      }
    },

    /**
     * Adds items intersecting a point to a selection.
     * @param {number} vX X location to search at, in viewspace.
     * @param {number} vY Y location to search at, in viewspace.
     * @param {TimelineSelection} selection Selection to which to add hits.
     * @return {boolean} true if a slice was found, otherwise false.
     */
    addIntersectingItemsToSelection: function(vX, vY, selection) {
      // Does nothing. There's nothing interesting to pick on the viewport
      // track.
    },

    /**
     * Adds items intersecting the given range to a selection.
     * @param {number} loVX Lower X bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVX Upper X bound of the interval to search, in
     *     viewspace.
     * @param {number} loVY Lower Y bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVY Upper Y bound of the interval to search, in
     *     viewspace.
     * @param {TimelineSelection} selection Selection to which to add hits.
     */
    addIntersectingItemsInRangeToSelection: function(
        loVX, hiVX, loY, hiY, selection) {
      // Does nothing. There's nothing interesting to pick on the viewport
      // track.
    },

    addAllObjectsMatchingFilterToSelection: function(filter, selection) {
    }
  };

  return {
    TimelineViewportTrack: TimelineViewportTrack
  };
});
<commit_msg>Fix viewport for highdpi<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracks.timeline_viewport_track');

base.require('tracks.timeline_track');
base.require('tracks.timeline_canvas_based_track');
base.require('ui');

base.exportTo('tracks', function() {

  /**
   * A track that displays the viewport size and scale.
   * @constructor
   * @extends {CanvasBasedTrack}
   */

  var TimelineViewportTrack = base.ui.define(tracks.TimelineCanvasBasedTrack);

  var logOf10 = Math.log(10);
  function log10(x) {
    return Math.log(x) / logOf10;
  }

  TimelineViewportTrack.prototype = {

    __proto__: tracks.TimelineCanvasBasedTrack.prototype,

    decorate: function() {
      this.classList.add('timeline-viewport-track');
      this.strings_secs_ = [];
      this.strings_msecs_ = [];
      this.addEventListener('mousedown', this.onMouseDown);
    },

    onMouseDown: function(e) {
      if (e.button != 0)
        return;
      this.placeAndBeginDraggingMarker(e.clientX);
    },

    placeAndBeginDraggingMarker: function(clientX) {
      var pixelRatio = window.devicePixelRatio || 1;
      var viewX = (clientX - this.canvasContainer_.offsetLeft) * pixelRatio;
      var worldX = this.viewport_.xViewToWorld(viewX);
      var marker = this.viewport_.findMarkerNear(worldX, 6);
      var createdMarker = false;
      var movedMarker = false;
      if (!marker) {
        marker = this.viewport_.addMarker(worldX);
        createdMarker = true;
      }
      marker.selected = true;

      var that = this;
      var onMouseMove = function(e) {
        var viewX = (e.clientX - that.canvasContainer_.offsetLeft) * pixelRatio;
        var worldX = that.viewport_.xViewToWorld(viewX);
        marker.positionWorld = worldX;
        movedMarker = true;
      };

      var onMouseUp = function(e) {
        marker.selected = false;
        if (!movedMarker && !createdMarker)
          that.viewport_.removeMarker(marker);
        document.removeEventListener('mouseup', onMouseUp);
        document.removeEventListener('mousemove', onMouseMove);
      };

      document.addEventListener('mouseup', onMouseUp);
      document.addEventListener('mousemove', onMouseMove);
    },

    drawLine_: function(ctx, x1, y1, x2, y2, color) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.closePath();
      ctx.strokeStyle = color;
      ctx.stroke();
    },

    drawArrow_: function(ctx, x1, y1, x2, y2, arrowWidth, color) {

      this.drawLine_(ctx, x1, y1, x2, y2, color);

      var dx = x2 - x1;
      var dy = y2 - y1;
      var len = Math.sqrt(dx * dx + dy * dy);
      var perc = (len - 10) / len;
      var bx = x1 + perc * dx;
      var by = y1 + perc * dy;
      var ux = dx / len;
      var uy = dy / len;
      var ax = uy * arrowWidth;
      var ay = -ux * arrowWidth;

      ctx.beginPath();
      ctx.fillStyle = color;
      ctx.moveTo(bx + ax, by + ay);
      ctx.lineTo(x2, y2);
      ctx.lineTo(bx - ax, by - ay);
      ctx.lineTo(bx + ax, by + ay);
      ctx.closePath();
      ctx.fill();
    },

    redraw: function() {
      var ctx = this.ctx_;
      var canvasW = this.canvas_.width;
      var canvasH = this.canvas_.height;

      ctx.clearRect(0, 0, canvasW, canvasH);

      // Culling parametrs.
      var vp = this.viewport_;
      var pixWidth = vp.xViewVectorToWorld(1);
      var viewLWorld = vp.xViewToWorld(0);
      var viewRWorld = vp.xViewToWorld(canvasW);

      var measurements = this.classList.contains('timeline-viewport' +
          '-track-with-distance-measurements');

      var rulerHeight = measurements ? canvasH / 2 : canvasH;

      for (var i = 0; i < vp.markers.length; ++i) {
        vp.markers[i].drawTriangle_(ctx, viewLWorld, viewRWorld,
                                    canvasH, rulerHeight, vp);
      }

      var pixelRatio = window.devicePixelRatio || 1;
      var idealMajorMarkDistancePix = 150 * pixelRatio;
      var idealMajorMarkDistanceWorld =
          vp.xViewVectorToWorld(idealMajorMarkDistancePix);

      var majorMarkDistanceWorld;
      var unit;
      var unitDivisor;
      var tickLabels;

      // The conservative guess is the nearest enclosing 0.1, 1, 10, 100, etc.
      var conservativeGuess =
          Math.pow(10, Math.ceil(log10(idealMajorMarkDistanceWorld)));

      // Once we have a conservative guess, consider things that evenly add up
      // to the conservative guess, e.g. 0.5, 0.2, 0.1 Pick the one that still
      // exceeds the ideal mark distance.
      var divisors = [10, 5, 2, 1];
      for (var i = 0; i < divisors.length; ++i) {
        var tightenedGuess = conservativeGuess / divisors[i];
        if (vp.xWorldVectorToView(tightenedGuess) < idealMajorMarkDistancePix)
          continue;
        majorMarkDistanceWorld = conservativeGuess / divisors[i - 1];
        break;
      }
      var tickLabels = undefined;
      if (majorMarkDistanceWorld < 100) {
        unit = 'ms';
        unitDivisor = 1;
        tickLabels = this.strings_msecs_;
      } else {
        unit = 's';
        unitDivisor = 1000;
        tickLabels = this.strings_secs_;
      }

      var numTicksPerMajor = 5;
      var minorMarkDistanceWorld = majorMarkDistanceWorld / numTicksPerMajor;
      var minorMarkDistancePx = vp.xWorldVectorToView(minorMarkDistanceWorld);

      var firstMajorMark =
          Math.floor(viewLWorld / majorMarkDistanceWorld) *
              majorMarkDistanceWorld;

      var minorTickH = Math.floor(canvasH * 0.25);

      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.strokeStyle = 'rgb(0, 0, 0)';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';

      var pixelRatio = window.devicePixelRatio || 1;
      ctx.font = (9 * pixelRatio) + 'px sans-serif';

      // Each iteration of this loop draws one major mark
      // and numTicksPerMajor minor ticks.
      //
      // Rendering can't be done in world space because canvas transforms
      // affect line width. So, do the conversions manually.
      for (var curX = firstMajorMark;
           curX < viewRWorld;
           curX += majorMarkDistanceWorld) {

        var curXView = Math.floor(vp.xWorldToView(curX));

        var unitValue = curX / unitDivisor;
        var roundedUnitValue = Math.floor(unitValue * 100000) / 100000;

        if (!tickLabels[roundedUnitValue])
          tickLabels[roundedUnitValue] = roundedUnitValue + ' ' + unit;
        ctx.fillText(tickLabels[roundedUnitValue],
                     curXView + 2 * pixelRatio, 0);
        ctx.beginPath();

        // Major mark
        ctx.moveTo(curXView, 0);
        ctx.lineTo(curXView, rulerHeight);

        // Minor marks
        for (var i = 1; i < numTicksPerMajor; ++i) {
          var xView = Math.floor(curXView + minorMarkDistancePx * i);
          ctx.moveTo(xView, rulerHeight - minorTickH);
          ctx.lineTo(xView, rulerHeight);
        }

        ctx.stroke();
      }

      // Give distance between directly adjacent markers.
      if (measurements) {

        // Divide canvas horizontally between ruler and measurements.
        ctx.moveTo(0, rulerHeight);
        ctx.lineTo(canvasW, rulerHeight);
        ctx.stroke();

        // Obtain a sorted array of markers
        var sortedMarkers = vp.markers.slice();
        sortedMarkers.sort(function(a, b) {
          return a.positionWorld_ - b.positionWorld_;
        });

        // Distance Variables.
        var displayDistance;
        var unitDivisor;
        var displayTextColor = 'rgb(0,0,0)';
        var measurementsPosY = rulerHeight + 2;

        // Arrow Variables.
        var arrowSpacing = 10;
        var arrowColor = 'rgb(128,121,121)';
        var arrowPosY = measurementsPosY + 4;
        var arrowWidthView = 3;
        var spaceForArrowsView = 2 * (arrowWidthView + arrowSpacing);

        for (i = 0; i < sortedMarkers.length - 1; i++) {
          var rightMarker = sortedMarkers[i + 1];
          var leftMarker = sortedMarkers[i];
          var distanceBetweenMarkers =
              rightMarker.positionWorld - leftMarker.positionWorld;
          var distanceBetweenMarkersView =
              vp.xWorldVectorToView(distanceBetweenMarkers);

          var positionInMiddleOfMarkers = leftMarker.positionWorld +
                                              distanceBetweenMarkers / 2;
          var positionInMiddleOfMarkersView =
              vp.xWorldToView(positionInMiddleOfMarkers);

          // Determine units.
          if (distanceBetweenMarkers < 100) {
            unit = 'ms';
            unitDivisor = 1;
          } else {
            unit = 's';
            unitDivisor = 1000;
          }
          // Calculate display value to print.
          displayDistance = distanceBetweenMarkers / unitDivisor;
          var roundedDisplayDistance =
              Math.abs((Math.floor(displayDistance * 1000) / 1000));
          var textToDraw = roundedDisplayDistance + ' ' + unit;
          var textWidthView = ctx.measureText(textToDraw).width;
          var textWidthWorld = vp.xViewVectorToWorld(textWidthView);
          var spaceForArrowsAndTextView = textWidthView +
                                          spaceForArrowsView + arrowSpacing;

          // Set text positions.
          var textLeft = leftMarker.positionWorld +
              (distanceBetweenMarkers / 2) - (textWidthWorld / 2);
          var textRight = textLeft + textWidthWorld;
          var textPosY = measurementsPosY;
          var textLeftView = vp.xWorldToView(textLeft);
          var textRightView = vp.xWorldToView(textRight);
          var leftMarkerView = vp.xWorldToView(leftMarker.positionWorld);
          var rightMarkerView = vp.xWorldToView(rightMarker.positionWorld);
          var textDrawn = false;

          if (spaceForArrowsAndTextView <= distanceBetweenMarkersView) {
            // Print the display distance text.
            ctx.fillStyle = displayTextColor;
            ctx.fillText(textToDraw, textLeftView, textPosY);
            textDrawn = true;
          }

          if (spaceForArrowsView <= distanceBetweenMarkersView) {
            var leftArrowStart;
            var rightArrowStart;
            if (textDrawn) {
              leftArrowStart = textLeftView - arrowSpacing;
              rightArrowStart = textRightView + arrowSpacing;
            } else {
              leftArrowStart = positionInMiddleOfMarkersView;
              rightArrowStart = positionInMiddleOfMarkersView;
            }
            // Draw left arrow.
            this.drawArrow_(ctx, leftArrowStart, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            // Draw right arrow.
            this.drawArrow_(ctx, rightArrowStart, arrowPosY,
                rightMarkerView, arrowPosY, arrowWidthView, arrowColor);
          }
        }
      }
    },

    /**
     * Adds items intersecting a point to a selection.
     * @param {number} vX X location to search at, in viewspace.
     * @param {number} vY Y location to search at, in viewspace.
     * @param {TimelineSelection} selection Selection to which to add hits.
     * @return {boolean} true if a slice was found, otherwise false.
     */
    addIntersectingItemsToSelection: function(vX, vY, selection) {
      // Does nothing. There's nothing interesting to pick on the viewport
      // track.
    },

    /**
     * Adds items intersecting the given range to a selection.
     * @param {number} loVX Lower X bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVX Upper X bound of the interval to search, in
     *     viewspace.
     * @param {number} loVY Lower Y bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVY Upper Y bound of the interval to search, in
     *     viewspace.
     * @param {TimelineSelection} selection Selection to which to add hits.
     */
    addIntersectingItemsInRangeToSelection: function(
        loVX, hiVX, loY, hiY, selection) {
      // Does nothing. There's nothing interesting to pick on the viewport
      // track.
    },

    addAllObjectsMatchingFilterToSelection: function(filter, selection) {
    }
  };

  return {
    TimelineViewportTrack: TimelineViewportTrack
  };
});
<|endoftext|>


<commit_before>import _ from 'lodash'
import flatten from 'flat'

const DOT_SAFE = '__dotSafe__'
const dotSafeWrap = unsafePath => ({[DOT_SAFE]: unsafePath})
const dotSafeUnwrap = safePath => safePath[DOT_SAFE]

export const dotSafe = dotSafeWrap

export const toPathList = (path, safe = false) => {
    if (_.isArray(path)) {
        return _.chain(path)
            .map(pathElement => toPathList(pathElement, safe))
            .filter(_.identity)
            .flatten()
            .value()
    }
    if (_.isObject(path)) {
        const unwrapped = dotSafeUnwrap(path)
        return _.isUndefined(unwrapped)
            ? path
            : toPathList([unwrapped], true)
    }
    if (_.isString(path)) {
        return safe ? [path] : path.split('.')
    }
    if (_.isNumber(path)) {
        return [path.toString()]
    }
    if (_.isUndefined(path)) {
        return null
    }
    if (_.isNull(path)) {
        return null
    }
    throw Error(`Unsupported path element type: '${path}'`)
}

export const resolve = (object, path, createTemplates = false) =>
    toPathList(path)
        .reduce((value, pathElement, _index, pathElements) => {
            if (_.isString(pathElement)) {
                if (_.isArray(value)) {
                    // match array item by index
                    const index = parseInt(pathElement)
                    if (isNaN(index)) {
                        throw Error(`Cannot match array item with non-numeric index: path: ${path}, element: ${pathElement}`)
                    }
                    return value[index]
                }
                if (_.isObjectLike(value)) {
                    // match object property
                    if (value[pathElement] !== undefined) {
                        return value[pathElement]
                    }
                }
            }
            if (_.isPlainObject(pathElement) && _.isArray(value)) {
                const item = _.find(value,
                    item => _.isEqual(_.pick(item, Object.keys(flatten(pathElement))), pathElement)
                )
                if (item) {
                    return item
                }
                if (createTemplates) {
                    return pathElement
                }
            }
            pathElements.splice(1) // break out of reduce
            return undefined
        }, object)

export const selectFrom = (object, path) => resolve(object, path)

export const mutate = (state, path) => new Mutator(state, path)

export class Mutator {
    constructor(state, path) {
        this.state = {
            root: state
        }
        this.path = toPathList(['root', path])
    }

    getKey(pathState, pathElement) {
        if (_.isPlainObject(pathElement)) {
            return _.findIndex(pathState, item => _.isEqual(_.pick(item, Object.keys(flatten(pathElement))), pathElement))
        }
        return pathElement
    }

    getNext(next, index) {
        const isPositiveInt = str => {
            var n = Math.floor(Number(str))
            return n !== Infinity && String(n) === str && n >= 0
        }
        if (next === undefined) {
            const nextPathElement = this.path[index + 1]
            const isArray = v => (_.isString(v) && isPositiveInt(v)) || _.isPlainObject(v)
            return isArray(nextPathElement) ? [] : {}
        } else {
            return _.clone(next || {})
        }
    }

    mutate(func) {
        const parentPath = _.initial(this.path)
        const pathElement = _.last(this.path)
        const stateElements = _.chain(parentPath)
            .transform(
                (stateElements, pathElement, index, pathElements) => {
                    const stateElement = _.last(stateElements)
                    const key = this.getKey(stateElement, pathElement)
                    if (key === -1) {
                        const next = _.clone(pathElement)
                        if (stateElement) {
                            // add to array
                            stateElement.push(next)
                        } else {
                            // create array
                            const previousElement = _.nth(stateElements, -2)
                            previousElement[pathElements[index - 1]] = [next]
                        }
                        stateElements.push(next)
                    } else {
                        const next = this.getNext(stateElement[key], index)
                        stateElement[key] = next
                        stateElements.push(next)
                    }
                }, [this.state])
            .tail() // drop the synthetic root
            .value()
        const state = _.first(stateElements)
        const pathState = _.last(stateElements)
        const key = this.getKey(pathState, pathElement)
        const pathKey = key === -1
            ? pathState.length
            : key
        func(pathState, pathKey)
        return state
    }

    set(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.cloneDeep(value)
        })
    }

    sort(key) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.orderBy(pathState[pathKey], key)
        })
    }

    unique() {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.uniq(pathState[pathKey])
        })
    }

    assign(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.assign({}, pathState[pathKey], _.cloneDeep(value))
        })
    }

    merge(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.merge({}, pathState[pathKey], _.cloneDeep(value))
        })
    }

    push(value) {
        return this.mutate((pathState, pathKey) => {
            if (!pathState[pathKey]) {
                pathState[pathKey] = []
            }
            pathState[pathKey] = [...pathState[pathKey], _.cloneDeep(value)]
        })
    }

    pushUnique(value, key) {
        return this.mutate((pathState, pathKey) => {
            const finder = key
                ? item => resolve(item, key, true) === resolve(value, key, true)
                : item => item === value
            const array = pathState[pathKey]
            if (!array || !_.find(array, finder)) {
                if (!array) {
                    pathState[pathKey] = []
                }
                pathState[pathKey] = [...pathState[pathKey], _.cloneDeep(value)]
            }
        })
    }

    del() {
        return this.mutate((pathState, pathKey) => {
            if (_.isPlainObject(pathState)) {
                delete pathState[pathKey]
            } else if (_.isArray(pathState)) {
                pathState.splice(pathKey, 1)
            } else {
                console.error('Unsupported type to delete from', {pathState, pathKey})
                throw Error('Unsupported type to delete from')
            }
        })
    }
}
<commit_msg>Allowed deletion of array elements by value.<commit_after>import _ from 'lodash'
import flatten from 'flat'

const DOT_SAFE = '__dotSafe__'
const dotSafeWrap = unsafePath => ({[DOT_SAFE]: unsafePath})
const dotSafeUnwrap = safePath => safePath[DOT_SAFE]

export const dotSafe = dotSafeWrap

export const toPathList = (path, safe = false) => {
    if (_.isArray(path)) {
        return _.chain(path)
            .map(pathElement => toPathList(pathElement, safe))
            .filter(_.identity)
            .flatten()
            .value()
    }
    if (_.isObject(path)) {
        const unwrapped = dotSafeUnwrap(path)
        return _.isUndefined(unwrapped)
            ? path
            : toPathList([unwrapped], true)
    }
    if (_.isString(path)) {
        return safe ? [path] : path.split('.')
    }
    if (_.isNumber(path)) {
        return [path.toString()]
    }
    if (_.isUndefined(path)) {
        return null
    }
    if (_.isNull(path)) {
        return null
    }
    throw Error(`Unsupported path element type: '${path}'`)
}

export const resolve = (object, path, createTemplates = false) =>
    toPathList(path)
        .reduce((value, pathElement, _index, pathElements) => {
            if (_.isString(pathElement)) {
                if (_.isArray(value)) {
                    // match array item by index
                    const index = parseInt(pathElement)
                    if (isNaN(index)) {
                        throw Error(`Cannot match array item with non-numeric index: path: ${path}, element: ${pathElement}`)
                    }
                    return value[index]
                }
                if (_.isObjectLike(value)) {
                    // match object property
                    if (value[pathElement] !== undefined) {
                        return value[pathElement]
                    }
                }
            }
            if (_.isPlainObject(pathElement) && _.isArray(value)) {
                const item = _.find(value,
                    item => _.isEqual(_.pick(item, Object.keys(flatten(pathElement))), pathElement)
                )
                if (item) {
                    return item
                }
                if (createTemplates) {
                    return pathElement
                }
            }
            pathElements.splice(1) // break out of reduce
            return undefined
        }, object)

export const selectFrom = (object, path) => resolve(object, path)

export const mutate = (state, path) => new Mutator(state, path)

export class Mutator {
    constructor(state, path) {
        this.state = {
            root: state
        }
        this.path = toPathList(['root', path])
    }

    getKey(pathState, pathElement) {
        if (_.isPlainObject(pathElement)) {
            return _.findIndex(pathState, item => _.isEqual(_.pick(item, Object.keys(flatten(pathElement))), pathElement))
        }
        return pathElement
    }

    getNext(next, index) {
        const isPositiveInt = str => {
            var n = Math.floor(Number(str))
            return n !== Infinity && String(n) === str && n >= 0
        }
        if (next === undefined) {
            const nextPathElement = this.path[index + 1]
            const isArray = v => (_.isString(v) && isPositiveInt(v)) || _.isPlainObject(v)
            return isArray(nextPathElement) ? [] : {}
        } else {
            return _.clone(next || {})
        }
    }

    mutate(func) {
        const parentPath = _.initial(this.path)
        const pathElement = _.last(this.path)
        const stateElements = _.chain(parentPath)
            .transform(
                (stateElements, pathElement, index, pathElements) => {
                    const stateElement = _.last(stateElements)
                    const key = this.getKey(stateElement, pathElement)
                    if (key === -1) {
                        const next = _.clone(pathElement)
                        if (stateElement) {
                            // add to array
                            stateElement.push(next)
                        } else {
                            // create array
                            const previousElement = _.nth(stateElements, -2)
                            previousElement[pathElements[index - 1]] = [next]
                        }
                        stateElements.push(next)
                    } else {
                        const next = this.getNext(stateElement[key], index)
                        stateElement[key] = next
                        stateElements.push(next)
                    }
                }, [this.state])
            .tail() // drop the synthetic root
            .value()
        const state = _.first(stateElements)
        const pathState = _.last(stateElements)
        const key = this.getKey(pathState, pathElement)
        const pathKey = key === -1
            ? pathState.length
            : key
        func(pathState, pathKey)
        return state
    }

    set(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.cloneDeep(value)
        })
    }

    sort(key) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.orderBy(pathState[pathKey], key)
        })
    }

    unique() {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.uniq(pathState[pathKey])
        })
    }

    assign(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.assign({}, pathState[pathKey], _.cloneDeep(value))
        })
    }

    merge(value) {
        return this.mutate((pathState, pathKey) => {
            pathState[pathKey] = _.merge({}, pathState[pathKey], _.cloneDeep(value))
        })
    }

    push(value) {
        return this.mutate((pathState, pathKey) => {
            if (!pathState[pathKey]) {
                pathState[pathKey] = []
            }
            pathState[pathKey] = [...pathState[pathKey], _.cloneDeep(value)]
        })
    }

    pushUnique(value, key) {
        return this.mutate((pathState, pathKey) => {
            const finder = key
                ? item => resolve(item, key, true) === resolve(value, key, true)
                : item => item === value
            const array = pathState[pathKey]
            if (!array || !_.find(array, finder)) {
                if (!array) {
                    pathState[pathKey] = []
                }
                pathState[pathKey] = [...pathState[pathKey], _.cloneDeep(value)]
            }
        })
    }

    del() {
        return this.mutate((pathState, pathKey) => {
            if (_.isPlainObject(pathState)) {
                delete pathState[pathKey]
            } else if (_.isArray(pathState)) {
                if (_.isNumber(pathKey)) {
                    pathState.splice(pathKey, 1)
                } else {
                    const index = pathState.indexOf(pathKey)
                    index >= 0 && pathState.splice(index, 1)
                }
            } else {
                console.error('Unsupported type to delete from', {pathState, pathKey})
                throw Error('Unsupported type to delete from')
            }
        })
    }
}
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('blackholeApp')
        .config(stateConfig);

    stateConfig.$inject = ['$stateProvider'];

    function stateConfig($stateProvider) {
        $stateProvider
        .state('gen-ledger', {
            parent: 'entity',
            url: '/gen-ledger?page&sort&search',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'blackholeApp.genLedger.home.title'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-entries.html',
                    controller: 'GenLedgerController',
                    controllerAs: 'vm'
                }
            },
            params: {
                page: {
                    value: '1',
                    squash: true
                },
                sort: {
                    value: 'id,asc',
                    squash: true
                },
                search: null
            },
            resolve: {
                pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) {
                    return {
                        page: PaginationUtil.parsePage($stateParams.page),
                        sort: $stateParams.sort,
                        predicate: PaginationUtil.parsePredicate($stateParams.sort),
                        ascending: PaginationUtil.parseAscending($stateParams.sort),
                        search: $stateParams.search
                    };
                }],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('genLedger');
                    $translatePartialLoader.addPart('global');
                    return $translate.refresh();
                }]
            }
        })
        .state('gen-ledger-detail', {
            parent: 'entity',
            url: '/gen-ledger/{id}',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'blackholeApp.genLedger.detail.title'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-detail.html',
                    controller: 'GenLedgerDetailController',
                    controllerAs: 'vm'
                }
            },
            resolve: {
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('genLedger');
                    return $translate.refresh();
                }],
                entity: ['$stateParams', 'GenLedger', function($stateParams, GenLedger) {
                    return GenLedger.get({id : $stateParams.id}).$promise;
                }],
                previousState: ["$state", function ($state) {
                    var currentStateData = {
                        name: $state.current.name || 'gen-ledger',
                        params: $state.params,
                        url: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        })
        .state('gen-ledger-detail.edit', {
            parent: 'gen-ledger-detail',
            url: '/detail/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('^', {}, { reload: false });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('gen-ledger.new', {
            parent: 'gen-ledger',
            url: '/new',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: function () {
                            return {
                                entrydate: null,
                                transaction: null,
                                reconcile: null,
                                postingref: null,
                                debit: null,
                                credit: null,
                                debitbalance: null,
                                creditbalance: null,
                                notes: null,
                                cno: null,
                                accountname: null,
                                id: null
                            };
                        }
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('gen-ledger');
                });
            }]
        })
        .state('gen-ledger.edit', {
            parent: 'gen-ledger',
            url: '/{id}/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('gen-ledger.delete', {
            parent: 'gen-ledger',
            url: '/{id}/delete',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-delete-dialog.html',
                    controller: 'GenLedgerDeleteController',
                    controllerAs: 'vm',
                    size: 'md',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('^');
                });
            }]
        });
    }

})();
<commit_msg>fixed case for accountname<commit_after>(function() {
    'use strict';

    angular
        .module('blackholeApp')
        .config(stateConfig);

    stateConfig.$inject = ['$stateProvider'];

    function stateConfig($stateProvider) {
        $stateProvider
        .state('gen-ledger', {
            parent: 'entity',
            url: '/gen-ledger?page&sort&search',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'blackholeApp.genLedger.home.title'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-entries.html',
                    controller: 'GenLedgerController',
                    controllerAs: 'vm'
                }
            },
            params: {
                page: {
                    value: '1',
                    squash: true
                },
                sort: {
                    value: 'id,asc',
                    squash: true
                },
                search: null
            },
            resolve: {
                pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) {
                    return {
                        page: PaginationUtil.parsePage($stateParams.page),
                        sort: $stateParams.sort,
                        predicate: PaginationUtil.parsePredicate($stateParams.sort),
                        ascending: PaginationUtil.parseAscending($stateParams.sort),
                        search: $stateParams.search
                    };
                }],
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('genLedger');
                    $translatePartialLoader.addPart('global');
                    return $translate.refresh();
                }]
            }
        })
        .state('gen-ledger-detail', {
            parent: 'entity',
            url: '/gen-ledger/{id}',
            data: {
                authorities: ['ROLE_USER'],
                pageTitle: 'blackholeApp.genLedger.detail.title'
            },
            views: {
                'content@': {
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-detail.html',
                    controller: 'GenLedgerDetailController',
                    controllerAs: 'vm'
                }
            },
            resolve: {
                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
                    $translatePartialLoader.addPart('genLedger');
                    return $translate.refresh();
                }],
                entity: ['$stateParams', 'GenLedger', function($stateParams, GenLedger) {
                    return GenLedger.get({id : $stateParams.id}).$promise;
                }],
                previousState: ["$state", function ($state) {
                    var currentStateData = {
                        name: $state.current.name || 'gen-ledger',
                        params: $state.params,
                        url: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        })
        .state('gen-ledger-detail.edit', {
            parent: 'gen-ledger-detail',
            url: '/detail/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('^', {}, { reload: false });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('gen-ledger.new', {
            parent: 'gen-ledger',
            url: '/new',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: function () {
                            return {
                                entrydate: null,
                                transaction: null,
                                reconcile: null,
                                postingref: null,
                                debit: null,
                                credit: null,
                                debitbalance: null,
                                creditbalance: null,
                                notes: null,
                                cno: null,
                                accountName: null,
                                id: null
                            };
                        }
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('gen-ledger');
                });
            }]
        })
        .state('gen-ledger.edit', {
            parent: 'gen-ledger',
            url: '/{id}/edit',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-dialog.html',
                    controller: 'GenLedgerDialogController',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    size: 'lg',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('^');
                });
            }]
        })
        .state('gen-ledger.delete', {
            parent: 'gen-ledger',
            url: '/{id}/delete',
            data: {
                authorities: ['ROLE_USER']
            },
            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {
                $uibModal.open({
                    templateUrl: 'app/entities/gen-ledger/gen-ledger-delete-dialog.html',
                    controller: 'GenLedgerDeleteController',
                    controllerAs: 'vm',
                    size: 'md',
                    resolve: {
                        entity: ['GenLedger', function(GenLedger) {
                            return GenLedger.get({id : $stateParams.id}).$promise;
                        }]
                    }
                }).result.then(function() {
                    $state.go('gen-ledger', null, { reload: true });
                }, function() {
                    $state.go('^');
                });
            }]
        });
    }

})();
<|endoftext|>