<commit_before>module.exports = function (grunt) {
  'use strict';

  var helpers = require('./.grunt/helpers')(grunt);
  var clone = grunt.util._.clone;

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-mocha');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-hull-dox');
  grunt.loadNpmTasks('grunt-hull-widgets');
  grunt.loadNpmTasks('grunt-s3');
  grunt.loadNpmTasks('grunt-git-describe');
  grunt.loadNpmTasks('grunt-coverjs');
  grunt.loadNpmTasks('grunt-plato');
  grunt.loadNpmTasks('grunt-wrap');

  var clientConfig = grunt.file.readJSON('.grunt/client.json');
  var remoteConfig = grunt.file.readJSON('.grunt/remote.json');
  var apiConfig = grunt.file.readJSON('.grunt/api.json');

  var port = 3001;

  // ==========================================================================
  // Project configuration
  // ==========================================================================

  // Lookup of the available libs and injects them for the build
  // in the requirejs conf
  var clientLibs = helpers.getBuiltFilenames('src/client/**/*.coffee');
  var remoteLibs = helpers.getBuiltFilenames('src/remote/**/*.coffee');

  // Lookup of the Aura Extensions and injects them in the requirejs build
  var auraExtensions = grunt.file.glob
    .sync('aura-extensions/**/*.js')
    .map(function (extension) {
      return extension.replace('.js', '');
    });

  //Augment the require.js configuation with some computed elements
  var apiRJSConfig = (function () {
    var _c = apiConfig.requireJS;
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();
  var clientRJSConfig = (function () {
    var _c = clientConfig.requireJS;
    _c.include = _c.include.concat(auraExtensions).concat(clientLibs);
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();

  var remoteRJSConfig = (function () {
    var _c = remoteConfig.requireJS;
    _c.include = _c.include.concat(remoteLibs);
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();

  var gruntConfig = {
    clean: {
      client: {
        src: 'lib/client/**/*'
      },
      remote: {
        src: 'lib/remote/**/*'
      },
      reset: {
        src: ['build', 'lib', 'tmp', 'dist', 'components', 'node_modules']
      }
    },
    dox: {
      files: {
        baseDir: 'aura_components',
        src: 'aura_components/**/main.js',
        dest: 'dist/<%= PKG_VERSION %>/docs'
      }
    },
    coffee: {
      compile: {
        options: {
          header: true
        }
      },
      remote: {
        files: grunt.file.expandMapping(remoteConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      },
      client: {
        files: grunt.file.expandMapping(clientConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      },
      api: {
        files: grunt.file.expandMapping(apiConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      }
    },
    connect: {
      server: {
        options: {
          port: port
        }
      }
    },
    requirejs: {
      "client-no-backbone": {
        options: (function (c) {
          c.paths.underscore = 'empty:';
          c.paths.backbone = 'empty:';
          c.out = c.out.replace('hull.js', 'hull.no-backbone.js');
          c.wrap.start = c.wrap.start + ";root._ = window._;";
          c.wrap.start = c.wrap.start + ";root.Backbone = window.Backbone;";
          return c;
        })(clone(clientRJSConfig, true))
      },
      "client-no-underscore": {
        options: (function (c) {
          c.paths.underscore = 'empty:';
          c.out = c.out.replace('hull.js', 'hull.no-underscore.js');
          c.wrap.start = c.wrap.start + ";root._ = window._;";
          return c;
        })(clone(clientRJSConfig, true))
      },
      api: {
        options: clone(apiRJSConfig, true)
      },
      client: {
        options: clone(clientRJSConfig, true)
      },
      remote: {
        options: clone(remoteRJSConfig, true)
      },
      upload: {
        options: {
          namespace: 'Hull',
          paths: {
            jquery: "empty:",
            "jquery.ui.widget" : 'bower_components/jquery-file-upload/js/vendor/jquery.ui.widget',
            "jquery.fileupload" : 'bower_components/jquery-file-upload/js/jquery.fileupload'
          },
          include: [
            'jquery.fileupload'
          ],
          out: 'tmp/aura_components/upload/deps/jquery.fileupload.js'
        }
      },
      // registration: {
      //   options: {
      //     namespace: 'Hull',
      //     paths: { h5f: 'aura_components/registration/h5f' },
      //     shim: { h5f: { exports: 'H5F' } },
      //     include: ['h5f'],
      //     out: 'tmp/aura_components/registration/deps.js'
      //   }
      // },
      dox: {
        options: {
          namespace: 'Hull',
          paths: { prism: 'aura_components/dox/dox/prism' },
          shim: { prism: { exports: 'Prism' } },
          include: ['prism'],
          out: 'tmp/aura_components/dox/dox/deps.js'
        }
      }
    },
    mocha: {
      hull: {
        src: ["spec/index.html"]
      }
    },
    watch: {
      widgets: {
        files: ['aura_components/**/*'],
        tasks: ['hull_widgets']
      },
      remote: {
        files: remoteConfig.srcFiles,
        tasks: ['dist:remote', 'do_test']
      },
      api: {
        files: apiConfig.srcFiles,
        tasks: ['dist:api', 'do_test']
      },
      client: {
        files: [clientConfig.srcFiles, "aura-extensions/**/*.js"],
        tasks: ['dist:client', 'do_test']
      },
      spec: {
        files: ['spec/**/*.js'],
        tasks: ['mocha']
      },
      extensions: {
        files: ['aura-extensions/**/*.js'],
        tasks: ['dist:client', 'do_test']
      }
    },
    version: {
      template: "define(function () { return '<%= PKG_VERSION %>';});",
      dest: 'lib/utils/version.js'
    },
    hull_widgets: {
      hull: {
        src: 'aura_components',
        before: [],
        dest: 'dist/<%= PKG_VERSION%>',
        optimize: !grunt.option('dev')
      }
    },
    describe: {
      out: 'dist/<%= PKG_VERSION%>/REVISION'
    },
    wrap: {
      Handlebars: {
        src: 'node_modules/grunt-contrib-handlebars/node_modules/handlebars/dist/handlebars.js',
        dest: 'lib/shims',
        wrapper: [
          '(function () {', ';define("handlebars", function () {return Handlebars;});})()'
        ]
      },
      easyXDM: {
        src: 'bower_components/easyXDM/easyXDM.js',
        dest: 'lib/shims',
        wrapper: [
          '', ';var _available = window.easyXDM;define("easyXDM", function () {return window.easyXDM.noConflict();});if(!_available){delete window.easyXDM;};'
        ]
      }
    },
    cover: {
      compile: {
        files: {
          'build/instrumented/*.js' : ['lib/**/*.js']
        },
        options: {
          basePath: 'lib'
        }
      }
    },
    plato: {
      develop: {
        files: {
          'build/report': ['lib/**/*.js']
        }
      }
    },
    dist: {
      "remote": ['version', 'clean:remote', 'coffee:remote', 'wrap', 'version', 'requirejs:remote'],
      "client": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client'],
      "api": ['version', 'clean:client', 'coffee:api', 'wrap', 'version', 'requirejs:api'],
      "client-no-underscore": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client-no-underscore'],
      "client-no-backbone": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client-no-backbone'],
      "widgets": ["hull_widgets"],
      "docs": ['dox'],
      "describe": ['describe']
    }
  };

  helpers.appendAWSConfig(gruntConfig);
  grunt.initConfig(gruntConfig);

  grunt.registerTask('do_test', ['cover', 'plato', 'mocha']);
  grunt.registerTask('test', ['dist:api', 'dist:client', 'dist:remote', 'do_test']);
  grunt.registerTask('reset', ['clean:reset']);

  //These tasks are the only ones needed to be used
  grunt.registerTask('default', 'server');
  grunt.registerTask('server', ['connect', 'test', 'dist:widgets', 'watch']);
  grunt.registerTask('deploy', ['dist', 's3:prod']);

  require('./.grunt/customTasks')(grunt);

};
<commit_msg>Fixes component watch task target<commit_after>module.exports = function (grunt) {
  'use strict';

  var helpers = require('./.grunt/helpers')(grunt);
  var clone = grunt.util._.clone;

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-mocha');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-hull-dox');
  grunt.loadNpmTasks('grunt-hull-widgets');
  grunt.loadNpmTasks('grunt-s3');
  grunt.loadNpmTasks('grunt-git-describe');
  grunt.loadNpmTasks('grunt-coverjs');
  grunt.loadNpmTasks('grunt-plato');
  grunt.loadNpmTasks('grunt-wrap');

  var clientConfig = grunt.file.readJSON('.grunt/client.json');
  var remoteConfig = grunt.file.readJSON('.grunt/remote.json');
  var apiConfig = grunt.file.readJSON('.grunt/api.json');

  var port = 3001;

  // ==========================================================================
  // Project configuration
  // ==========================================================================

  // Lookup of the available libs and injects them for the build
  // in the requirejs conf
  var clientLibs = helpers.getBuiltFilenames('src/client/**/*.coffee');
  var remoteLibs = helpers.getBuiltFilenames('src/remote/**/*.coffee');

  // Lookup of the Aura Extensions and injects them in the requirejs build
  var auraExtensions = grunt.file.glob
    .sync('aura-extensions/**/*.js')
    .map(function (extension) {
      return extension.replace('.js', '');
    });

  //Augment the require.js configuation with some computed elements
  var apiRJSConfig = (function () {
    var _c = apiConfig.requireJS;
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();
  var clientRJSConfig = (function () {
    var _c = clientConfig.requireJS;
    _c.include = _c.include.concat(auraExtensions).concat(clientLibs);
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();

  var remoteRJSConfig = (function () {
    var _c = remoteConfig.requireJS;
    _c.include = _c.include.concat(remoteLibs);
    _c.optimize = grunt.option('dev') ? "none" : "uglify";
    return _c;
  })();

  var gruntConfig = {
    clean: {
      client: {
        src: 'lib/client/**/*'
      },
      remote: {
        src: 'lib/remote/**/*'
      },
      reset: {
        src: ['build', 'lib', 'tmp', 'dist', 'components', 'node_modules']
      }
    },
    dox: {
      files: {
        baseDir: 'aura_components',
        src: 'aura_components/**/main.js',
        dest: 'dist/<%= PKG_VERSION %>/docs'
      }
    },
    coffee: {
      compile: {
        options: {
          header: true
        }
      },
      remote: {
        files: grunt.file.expandMapping(remoteConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      },
      client: {
        files: grunt.file.expandMapping(clientConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      },
      api: {
        files: grunt.file.expandMapping(apiConfig.srcFiles, 'lib/', {
          rename: function (destBase, destPath) {
            return destBase + destPath.replace(/\.coffee$/, '.js').replace(/^src\//, "");
          }
        })
      }
    },
    connect: {
      server: {
        options: {
          port: port
        }
      }
    },
    requirejs: {
      "client-no-backbone": {
        options: (function (c) {
          c.paths.underscore = 'empty:';
          c.paths.backbone = 'empty:';
          c.out = c.out.replace('hull.js', 'hull.no-backbone.js');
          c.wrap.start = c.wrap.start + ";root._ = window._;";
          c.wrap.start = c.wrap.start + ";root.Backbone = window.Backbone;";
          return c;
        })(clone(clientRJSConfig, true))
      },
      "client-no-underscore": {
        options: (function (c) {
          c.paths.underscore = 'empty:';
          c.out = c.out.replace('hull.js', 'hull.no-underscore.js');
          c.wrap.start = c.wrap.start + ";root._ = window._;";
          return c;
        })(clone(clientRJSConfig, true))
      },
      api: {
        options: clone(apiRJSConfig, true)
      },
      client: {
        options: clone(clientRJSConfig, true)
      },
      remote: {
        options: clone(remoteRJSConfig, true)
      },
      upload: {
        options: {
          namespace: 'Hull',
          paths: {
            jquery: "empty:",
            "jquery.ui.widget" : 'bower_components/jquery-file-upload/js/vendor/jquery.ui.widget',
            "jquery.fileupload" : 'bower_components/jquery-file-upload/js/jquery.fileupload'
          },
          include: [
            'jquery.fileupload'
          ],
          out: 'tmp/aura_components/upload/deps/jquery.fileupload.js'
        }
      },
      // registration: {
      //   options: {
      //     namespace: 'Hull',
      //     paths: { h5f: 'aura_components/registration/h5f' },
      //     shim: { h5f: { exports: 'H5F' } },
      //     include: ['h5f'],
      //     out: 'tmp/aura_components/registration/deps.js'
      //   }
      // },
      dox: {
        options: {
          namespace: 'Hull',
          paths: { prism: 'aura_components/dox/dox/prism' },
          shim: { prism: { exports: 'Prism' } },
          include: ['prism'],
          out: 'tmp/aura_components/dox/dox/deps.js'
        }
      }
    },
    mocha: {
      hull: {
        src: ["spec/index.html"]
      }
    },
    watch: {
      widgets: {
        files: ['aura_components/**/*'],
        tasks: ['dist:widgets']
      },
      remote: {
        files: remoteConfig.srcFiles,
        tasks: ['dist:remote', 'do_test']
      },
      api: {
        files: apiConfig.srcFiles,
        tasks: ['dist:api', 'do_test']
      },
      client: {
        files: [clientConfig.srcFiles, "aura-extensions/**/*.js"],
        tasks: ['dist:client', 'do_test']
      },
      spec: {
        files: ['spec/**/*.js'],
        tasks: ['mocha']
      },
      extensions: {
        files: ['aura-extensions/**/*.js'],
        tasks: ['dist:client', 'do_test']
      }
    },
    version: {
      template: "define(function () { return '<%= PKG_VERSION %>';});",
      dest: 'lib/utils/version.js'
    },
    hull_widgets: {
      hull: {
        src: 'aura_components',
        before: [],
        dest: 'dist/<%= PKG_VERSION%>',
        optimize: !grunt.option('dev')
      }
    },
    describe: {
      out: 'dist/<%= PKG_VERSION%>/REVISION'
    },
    wrap: {
      Handlebars: {
        src: 'node_modules/grunt-contrib-handlebars/node_modules/handlebars/dist/handlebars.js',
        dest: 'lib/shims',
        wrapper: [
          '(function () {', ';define("handlebars", function () {return Handlebars;});})()'
        ]
      },
      easyXDM: {
        src: 'bower_components/easyXDM/easyXDM.js',
        dest: 'lib/shims',
        wrapper: [
          '', ';var _available = window.easyXDM;define("easyXDM", function () {return window.easyXDM.noConflict();});if(!_available){delete window.easyXDM;};'
        ]
      }
    },
    cover: {
      compile: {
        files: {
          'build/instrumented/*.js' : ['lib/**/*.js']
        },
        options: {
          basePath: 'lib'
        }
      }
    },
    plato: {
      develop: {
        files: {
          'build/report': ['lib/**/*.js']
        }
      }
    },
    dist: {
      "remote": ['version', 'clean:remote', 'coffee:remote', 'wrap', 'version', 'requirejs:remote'],
      "client": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client'],
      "api": ['version', 'clean:client', 'coffee:api', 'wrap', 'version', 'requirejs:api'],
      "client-no-underscore": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client-no-underscore'],
      "client-no-backbone": ['version', 'clean:client', 'coffee:client', 'wrap', 'version', 'requirejs:client-no-backbone'],
      "widgets": ["version", "hull_widgets"],
      "docs": ['dox'],
      "describe": ['describe']
    }
  };

  helpers.appendAWSConfig(gruntConfig);
  grunt.initConfig(gruntConfig);

  grunt.registerTask('do_test', ['cover', 'plato', 'mocha']);
  grunt.registerTask('test', ['dist:api', 'dist:client', 'dist:remote', 'do_test']);
  grunt.registerTask('reset', ['clean:reset']);

  //These tasks are the only ones needed to be used
  grunt.registerTask('default', 'server');
  grunt.registerTask('server', ['connect', 'test', 'dist:widgets', 'watch']);
  grunt.registerTask('deploy', ['dist', 's3:prod']);

  require('./.grunt/customTasks')(grunt);

};
<|endoftext|>


<commit_before>var TransferComponentFormView = Backbone.View.extend({
  initialize: function(options) {
    this.form_layout_template = _.template(options.form_layout_template);
    this.modal_template = options.modal_template;
    this.sourceDirectories = options.sourceDirectories;
  },

  showSelector: function(sourceDir) {

   // display action selector in modal window
    $(this.modal_template).modal({show: true});

    // make it destroy rather than hide modal
    $('#transfer-component-select-close, #transfer-component-select-cancel')
      .click(function() {
        $('#transfer-component-select-modal').remove();
      });

    // add directory selector
    createDirectoryPicker(
      sourceDir,
      'transfer-component-select-modal',
      'path_container'
    );
  },

  addedPaths: function() {
    var paths = [];
    $('.transfer_path').each(function() {
      paths.push($(this).text());
    });
    return paths;
  },

  startTransfer: function(transfer) {
    var path
      , copied = 0;

    $('.transfer-component-activity-indicator').show();
    // get path to temp directory in which to copy individual transfer
    // components
    $.ajax({
      url: '/filesystem/get_temp_directory/',
      type: 'GET',
      cache: false,
      success: function(results) {

        var tempDir = results.tempDir;

        // copy each transfer component to the temp directory
        for (var index in transfer.sourcePaths) {
          path = transfer.sourcePaths[index];
          $.ajax({
            url: '/filesystem/copy_transfer_component/',
            type: 'POST',
            async: false,
            cache: false,
            data: {
              name:        transfer.name,
              path:        path,
              destination: tempDir
            },
            success: function(results) {
              copied++;
            }
          });
        }
        // move from temp directory to appropriate watchdir
        var url = '/filesystem/ransfer/';
        $.ajax({
          url: url,
          type: 'POST',
          async: false,
          cache: false,
          data: {
            filepath: tempDir + '/' + transfer.name,
            type:     transfer.type
          },
          success: function(results) {
            $('#path_container').html('');
            $('.transfer-component-activity-indicator').hide();
          }
        });
        // report progress
      }
    });
  },

  render: function() {
    var $pathAreaEl = $('

')
       , $pathContainerEl = $('

');

    this.pathContainerEl = $pathContainerEl;

    // add button to add paths via a pop-up selector
    var $buttonContainer = $('

')
      , $addButton = $('Browse')
      , $sourceDirSelect = $('<select id="path_source_select"></select>')
      , $startTransferButton = $('Start transfer')
      , self = this;

    $buttonContainer
      .append($sourceDirSelect)
      .append($addButton)
      .append($startTransferButton);

    $pathAreaEl.append($buttonContainer);

    // add path container to parent container
    $pathAreaEl.append($pathContainerEl);

    // populate select with source directory values
    $.each(this.sourceDirectories, function(id, path) {
      $sourceDirSelect
        .append($("<option></option>")
        .attr("value", id)
        .text(path));
    });

    // populate view's DOM element with template output
    var context = {
      transfer_paths: $pathAreaEl.html()
    };
    $(this.el).html(this.form_layout_template(context));

    // make add button clickable
    $('#path_add_button').click(function() {
      // add modal containing directory selector
      // selecting makes modal disappear, adds directory, and re-renders
      self.showSelector($('#path_source_select').children(':selected').text());
    });

    // make start transfer button clickable
    $('#start_transfer_button').click(function() {
      var transferName = $('#transfer-name').val();

      if (!transferName)
      {
        alert('Please enter a transfer name');
      } else {
        if (!self.addedPaths().length) {
          alert('Please click "Browse" to add one or more paths from the source directory.');
        } else {
          var transferData = {
            'name':            transferName,
            'type':            $('#transfer-type').val(),
            'accessionNumber': $('#transfer-accession-number').val(),
            'sourcePaths':     self.addedPaths()
          };
          self.startTransfer(transferData);
        }
      }
    });
  }
});
<commit_msg>Made it so tranfer name is blanked in start transfer form after transfer completes.<commit_after>var TransferComponentFormView = Backbone.View.extend({
  initialize: function(options) {
    this.form_layout_template = _.template(options.form_layout_template);
    this.modal_template = options.modal_template;
    this.sourceDirectories = options.sourceDirectories;
  },

  showSelector: function(sourceDir) {

   // display action selector in modal window
    $(this.modal_template).modal({show: true});

    // make it destroy rather than hide modal
    $('#transfer-component-select-close, #transfer-component-select-cancel')
      .click(function() {
        $('#transfer-component-select-modal').remove();
      });

    // add directory selector
    createDirectoryPicker(
      sourceDir,
      'transfer-component-select-modal',
      'path_container'
    );
  },

  addedPaths: function() {
    var paths = [];
    $('.transfer_path').each(function() {
      paths.push($(this).text());
    });
    return paths;
  },

  startTransfer: function(transfer) {
    var path
      , copied = 0;

    $('.transfer-component-activity-indicator').show();
    // get path to temp directory in which to copy individual transfer
    // components
    $.ajax({
      url: '/filesystem/get_temp_directory/',
      type: 'GET',
      cache: false,
      success: function(results) {

        var tempDir = results.tempDir;

        // copy each transfer component to the temp directory
        for (var index in transfer.sourcePaths) {
          path = transfer.sourcePaths[index];
          $.ajax({
            url: '/filesystem/copy_transfer_component/',
            type: 'POST',
            async: false,
            cache: false,
            data: {
              name:        transfer.name,
              path:        path,
              destination: tempDir
            },
            success: function(results) {
              copied++;
            }
          });
        }
        // move from temp directory to appropriate watchdir
        var url = '/filesystem/ransfer/';
        $.ajax({
          url: url,
          type: 'POST',
          async: false,
          cache: false,
          data: {
            filepath: tempDir + '/' + transfer.name,
            type:     transfer.type
          },
          success: function(results) {
            $('#transfer-name').val('');
            $('#path_container').html('');
            $('.transfer-component-activity-indicator').hide();
          }
        });
        // report progress
      }
    });
  },

  render: function() {
    var $pathAreaEl = $('

')
       , $pathContainerEl = $('

');

    this.pathContainerEl = $pathContainerEl;

    // add button to add paths via a pop-up selector
    var $buttonContainer = $('

')
      , $addButton = $('Browse')
      , $sourceDirSelect = $('<select id="path_source_select"></select>')
      , $startTransferButton = $('Start transfer')
      , self = this;

    $buttonContainer
      .append($sourceDirSelect)
      .append($addButton)
      .append($startTransferButton);

    $pathAreaEl.append($buttonContainer);

    // add path container to parent container
    $pathAreaEl.append($pathContainerEl);

    // populate select with source directory values
    $.each(this.sourceDirectories, function(id, path) {
      $sourceDirSelect
        .append($("<option></option>")
        .attr("value", id)
        .text(path));
    });

    // populate view's DOM element with template output
    var context = {
      transfer_paths: $pathAreaEl.html()
    };
    $(this.el).html(this.form_layout_template(context));

    // make add button clickable
    $('#path_add_button').click(function() {
      // add modal containing directory selector
      // selecting makes modal disappear, adds directory, and re-renders
      self.showSelector($('#path_source_select').children(':selected').text());
    });

    // make start transfer button clickable
    $('#start_transfer_button').click(function() {
      var transferName = $('#transfer-name').val();

      if (!transferName)
      {
        alert('Please enter a transfer name');
      } else {
        if (!self.addedPaths().length) {
          alert('Please click "Browse" to add one or more paths from the source directory.');
        } else {
          var transferData = {
            'name':            transferName,
            'type':            $('#transfer-type').val(),
            'accessionNumber': $('#transfer-accession-number').val(),
            'sourcePaths':     self.addedPaths()
          };
          self.startTransfer(transferData);
        }
      }
    });
  }
});
<|endoftext|>


<commit_before>(function () {

    'use strict';

    module.exports = function (grunt) {

        var watchedFiles = [
            'sass/**/*',
            'fonts/**/*',
            'img/**/*',
            'js/**/*',
            '*.html',
            '*.json',
            '*.js',
            '!dist'
        ];

        /**
         * Grunt Tasks and Configurations
         */
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            copy: {
                build: {
                    expand: true,
                    src: [
                        'img/**',
                        'demo/**',
                        'fonts/**',
                        'js/**/*',
                        'video/**/*',
                        'uploads/**/*'
                    ],
                    dest: 'dist'
                },
                all: {
                    expand: true,
                    src: [
                        '*.html',
                        'img/**',
                        'demo/**',
                        'fonts/**',
                        'js/**'
                    ],
                    dest: 'dist'
                },
                test: {
                    expand: true,
                    src: [
                        'test/*',
                        'js/rjsTest.js',
                        'js/rjsConfig.js',
                        'test.html'
                    ],
                    dest: 'dist'
                },
                /**
                 * Copies original source from src/js to build/js/src/js for source map debugging.
                 */
                src: {
                    files: [
                        {
                            expand: true,
                            src: '*.js',
                            dest: 'dist/js/src/js'
                        }
                    ]
                },
                other: {
                    files: [
                        {
                            expand: true,
                            src: [
                                'img/**',
                                'cache.manifest',
                                'favicon.ico'
                            ],
                            dest: 'dist/'
                        }
                    ]
                },
                js: {
                    files: [
                        {
                            expand: true,
                            src: '**',
                            dest: 'dist/js'
                        }
                    ]
                }
            },
            sass: {
                build: {
                    options: {
                        style: 'expanded'
                    },
                    files: {
                        'dist/css/main.css': 'sass/main.scss'
                    }
                }
            },
            htmlmin: {
                build: {
                    options: {
                        removeComments: true,
                        collapseWhitespace: true
                    },
                    files: {
                        'dist/index.html': 'index.html'
                    }
                }
            },
            bootlint: {
                options: {
                    showallerrors: true,
                    stoponerror: false,
                    stoponwarning: false,
                    relaxerror: []
                },
                files: getTestFiles()
            },
            shell: {
                snapshots: {
                    command: makeCommands().join('&&')
                }
            },
            bump: {
                options: {
                    updateConfigs: ['pkg'],
                    commit: true,
                    commitMessage: 'Release v%VERSION%',
                    tagName: 'v%VERSION%',
                    tagMessage: 'Version %VERSION%',
                    push: true,
                    pushTo: 'origin',
                    gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
                    globalReplace: false,
                    prereleaseName: false,
                    metadata: '',
                    regExp: false
                }
            },
            clean: {
                dist: {
                    src: [
                        'dist/**'
                    ]
                }
            },
            watch: {
                options: {
                    atBegin: true
                },
                build: {
                    files: watchedFiles,
                    tasks: [
                        'default'
                    ]
                }
            }
        });

        grunt.loadNpmTasks('grunt-contrib-clean');
        grunt.loadNpmTasks('grunt-contrib-copy');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-htmlmin');
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.loadNpmTasks('grunt-contrib-sass');
        grunt.loadNpmTasks('grunt-shell');
        grunt.loadNpmTasks('grunt-bootlint');
        grunt.loadNpmTasks('grunt-bump');

        /**
         * Alias tasks
         */

        grunt.registerTask('default', ['build']);

        grunt.registerTask('build', [
            'clean',
            'htmlmin:build',
            'copy:build'
        ]);

        grunt.registerTask('markup', ['shell:snapshots','bootlint']);

    };

}());
<commit_msg>Replace missing functions, etc.<commit_after>(function () {

    'use strict';

    module.exports = function (grunt) {

        var watchedFiles = [
            'sass/**/*',
            'fonts/**/*',
            'img/**/*',
            'js/**/*',
            '*.html',
            '*.json',
            '*.js',
            '!dist'
        ];

        var baseUrl = 'http://localhost:8000/';
        var testPath = baseUrl + 'test.html';
        var routesArr = ['about', 'contact', 'work'];

        function getTestFiles() {
            return routesArr.map(function(route) {
                return 'dist/test/html/' + route + '.html';
            });
        }

        function makeCommands() {
            return routesArr.map(function(route) {
                return 'phantomjs load_ajax.js http://localhost:5000/index.html#' + route + ' dist/test/html/' + route + '.html';
            });
        }

        /**
         * Grunt Tasks and Configurations
         */
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            copy: {
                build: {
                    expand: true,
                    src: [
                        'img/**',
                        'demo/**',
                        'fonts/**',
                        'js/**/*',
                        'video/**/*',
                        'uploads/**/*'
                    ],
                    dest: 'dist'
                },
                all: {
                    expand: true,
                    src: [
                        '*.html',
                        'img/**',
                        'demo/**',
                        'fonts/**',
                        'js/**'
                    ],
                    dest: 'dist'
                },
                test: {
                    expand: true,
                    src: [
                        'test/*',
                        'js/rjsTest.js',
                        'js/rjsConfig.js',
                        'test.html'
                    ],
                    dest: 'dist'
                },
                /**
                 * Copies original source from src/js to build/js/src/js for source map debugging.
                 */
                src: {
                    files: [
                        {
                            expand: true,
                            src: '*.js',
                            dest: 'dist/js/src/js'
                        }
                    ]
                },
                other: {
                    files: [
                        {
                            expand: true,
                            src: [
                                'img/**',
                                'cache.manifest',
                                'favicon.ico'
                            ],
                            dest: 'dist/'
                        }
                    ]
                },
                js: {
                    files: [
                        {
                            expand: true,
                            src: '**',
                            dest: 'dist/js'
                        }
                    ]
                }
            },
            sass: {
                build: {
                    options: {
                        style: 'expanded'
                    },
                    files: {
                        'dist/css/main.css': 'sass/main.scss'
                    }
                }
            },
            htmlmin: {
                build: {
                    options: {
                        removeComments: true,
                        collapseWhitespace: true
                    },
                    files: {
                        'dist/index.html': 'index.html'
                    }
                }
            },
            bootlint: {
                options: {
                    showallerrors: true,
                    stoponerror: false,
                    stoponwarning: false,
                    relaxerror: []
                },
                files: getTestFiles()
            },
            shell: {
                snapshots: {
                    command: makeCommands().join('&&')
                }
            },
            bump: {
                options: {
                    updateConfigs: ['pkg'],
                    commit: true,
                    commitMessage: 'Release v%VERSION%',
                    tagName: 'v%VERSION%',
                    tagMessage: 'Version %VERSION%',
                    push: true,
                    pushTo: 'origin',
                    gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d',
                    globalReplace: false,
                    prereleaseName: false,
                    metadata: '',
                    regExp: false
                }
            },
            clean: {
                dist: {
                    src: [
                        'dist/**'
                    ]
                }
            },
            watch: {
                options: {
                    atBegin: true
                },
                build: {
                    files: watchedFiles,
                    tasks: [
                        'default'
                    ]
                }
            }
        });

        grunt.loadNpmTasks('grunt-contrib-clean');
        grunt.loadNpmTasks('grunt-contrib-copy');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-htmlmin');
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.loadNpmTasks('grunt-contrib-sass');
        grunt.loadNpmTasks('grunt-shell');
        grunt.loadNpmTasks('grunt-bootlint');
        grunt.loadNpmTasks('grunt-bump');

        /**
         * Alias tasks
         */

        grunt.registerTask('default', ['build']);

        grunt.registerTask('build', [
            'clean',
            'htmlmin:build',
            'copy:build'
        ]);

        grunt.registerTask('markup', ['shell:snapshots','bootlint']);

    };

}());
<|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.

chromespec = {};
chromespec.fgWnd = null;
chromespec.fgDoc = null;
chromespec.bgWnd = window;
chromespec.bgDoc = document;
chromespec.subPages = [];
chromespec.jasmineScripts = {};

// A flag for jasmine_helper.js.
window.runningInBg = true;

(function() {
  var jasmineLoaded = false;
  var bufferedLogs = [];

  function log(text) {
    var logElem = chromespec.fgDoc && chromespec.fgDoc.querySelector('#logs');
    if (logElem) {
      // Empty out buffered logs.
      if (bufferedLogs) {
        var logs = bufferedLogs;
        bufferedLogs = null;
        for (var i = 0; i < logs.length; ++i) {
          log(logs[i]);
        }
      }
      var newPre = chromespec.fgDoc.createElement('pre');
      newPre.textContent = text;
      logElem.appendChild(newPre);
    } else {
      bufferedLogs.push(text);
    }
    console.log(text);
  }

  function clearLogs() {
    var logElem = chromespec.fgDoc.querySelector('#logs');
    logElem.innerHTML = '';
  }

  function createButton(name, func) {
    var newButton = chromespec.fgDoc.createElement('div');
    newButton.textContent = name;
    newButton.className = 'btn';
    newButton.onclick = func;
    newButton.tabIndex = 1;
    return newButton;
  }

  function injectScript(doc, src, callback) {
    log('injecting script into ' + (doc == chromespec.fgDoc ? 'fg' : 'bg') + ': ' + src);
    var n = doc.createElement('script');
    n.onload = callback;
    n.src = src;
    var head = doc.querySelector('head');
    head.appendChild(n);
  }

  // Loads scripts in sequence.
  function injectScripts(doc, srcs, callback) {
    srcs = srcs.concat();
    function helper() {
      var src = srcs.shift();
      if (src) {
        injectScript(doc, src, helper);
      } else {
        callback && callback();
      }
    }
    helper();
  }

  function registerJasmineTest(testName) {
    chromespec.jasmineScripts[testName] = {
      name: testName,
      jsFile: 'test.' + testName + '.js',
      bgInstance: null,
      fgInstance: null
    };
  }

  function initJasmine(callback) {
    function afterJasmineLoaded() {
      // Make sure both pages use the same jasmine context.
      if (chromespec.fgWnd) {
        chromespec.fgWnd.jasmine = window.jasmine;
      }
      callback();
    }
    if (!jasmineLoaded) {
      jasmineLoaded = true;
      var scripts = [
          'third_party/jasmine-1.3.1/jasmine.js',
          'third_party/jasmine-1.3.1/jasmine-html.js',
          'jasmine_helper.js'
          ];
      injectScripts(document, scripts, afterJasmineLoaded);
    } else {
      afterJasmineLoaded();
    }
  }

  function registerSubPage(name, func) {
    chromespec.subPages.push({
      name: name,
      initFunc: func
    });
  }

  function registerJasmineTestInstance(runningInBg, name, func) {
    chromespec.jasmineScripts[name][runningInBg ? 'bgInstance' : 'fgInstance'] = func;
  }

  function injectStyle(src) {
    var n = chromespec.fgDoc.createElement('link');
    n.setAttribute('rel', 'stylesheet');
    n.setAttribute('href', src);
    chromespec.fgDoc.querySelector('head').appendChild(n);
  }

  function createUiWindow(onLoadCallback) {
    chrome.app.window.create('wnd.html', {
      width: 320,
      height: 380,
      id: 'ui'
    }, function(w) {
      log('UI window init start.');
      var wnd = w.contentWindow;
      chromespec.fgWnd = wnd;
      chromespec.fgDoc = wnd.document;
      wnd.onload = onUiWindowLoad;
      wnd.jasmine = window.jasmine;
      wnd.chromespec = chromespec;
      if (typeof onLoadCallback == 'function') {
        onLoadCallback(w);
      }
    });
  }

  function onUiWindowLoad() {
    injectStyle('third_party/jasmine-1.3.1/jasmine.css');
    injectStyle('spec_styles.css');
    // Inject jasmine.js again so that it will register it's global helper functions (e.g. it, describe).
    var scripts = [
        'third_party/jasmine-1.2.0/jasmine.js',
        'jasmine_helper.js'
    ];
    injectScripts(chromespec.fgDoc, scripts, onScriptsLoaded);
  }

  function ensureCordovaInitializes() {
    var timerId = window.setTimeout(function() {
      log('Cordova failed to initialize.');
    }, 500);
    chromespec.fgDoc.addEventListener('deviceready', function() {
      window.clearTimeout(timerId);
      log('Cordova initialized. platform: ' + chromespec.fgWnd.device.platform);
    }, false);
  }

  function onScriptsLoaded() {
    var homeButton = chromespec.createButton('Home', changePage.bind(null, 0));
    homeButton.classList.add('home-btn');
    chromespec.fgDoc.body.appendChild(homeButton);
    chromespec.fgDoc.body.insertAdjacentHTML('beforeend', '

' +
        '

' +
        '
Logsclear

');

    chromespec.fgDoc.querySelector('.clear-logs').onclick = clearLogs;

    chrome.storage.local.get('chromespec-page', function(values) {
      changePage(values && values['chromespec-page'] || 0);
    });
    ensureCordovaInitializes();
  }

  function changePage(pageIndex) {
    chrome.storage.local.set({'chromespec-page': pageIndex});
    clearLogs();
    var page = chromespec.subPages[pageIndex];
    var doc = chromespec.fgDoc;
    var pageContainerEl = doc.getElementById('page-container');
    doc.getElementById('page-title').textContent = page.name;
    pageContainerEl.innerHTML = '';
    page.initFunc(pageContainerEl);
  }

  function startUpLogic() {
    log('onLaunched called.');
    if (!window.noAutoCreateWindow) {
      createUiWindow();
    }
  }

  log('App started. ID = ' + chrome.runtime.id);
  chrome.app.runtime.onLaunched.addListener(startUpLogic);

  chromespec.changePage = changePage;
  chromespec.createButton = createButton;
  chromespec.createUiWindow = createUiWindow;
  chromespec.log = log;
  chromespec.initJasmine = initJasmine;
  chromespec.injectScript = injectScript;
  chromespec.injectScripts = injectScripts;
  chromespec.injectStyle = injectStyle;
  chromespec.registerJasmineTest = registerJasmineTest;
  chromespec.registerJasmineTestInstance = registerJasmineTestInstance;
  chromespec.registerSubPage = registerSubPage;
})();
<commit_msg>Added a dropdown function.<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.

chromespec = {};
chromespec.fgWnd = null;
chromespec.fgDoc = null;
chromespec.bgWnd = window;
chromespec.bgDoc = document;
chromespec.subPages = [];
chromespec.jasmineScripts = {};

// A flag for jasmine_helper.js.
window.runningInBg = true;

(function() {
  var jasmineLoaded = false;
  var bufferedLogs = [];

  function log(text) {
    var logElem = chromespec.fgDoc && chromespec.fgDoc.querySelector('#logs');
    if (logElem) {
      // Empty out buffered logs.
      if (bufferedLogs) {
        var logs = bufferedLogs;
        bufferedLogs = null;
        for (var i = 0; i < logs.length; ++i) {
          log(logs[i]);
        }
      }
      var newPre = chromespec.fgDoc.createElement('pre');
      newPre.textContent = text;
      logElem.appendChild(newPre);
    } else {
      bufferedLogs.push(text);
    }
    console.log(text);
  }

  function clearLogs() {
    var logElem = chromespec.fgDoc.querySelector('#logs');
    logElem.innerHTML = '';
  }

  function createButton(name, func) {
    var newButton = chromespec.fgDoc.createElement('div');
    newButton.textContent = name;
    newButton.className = 'btn';
    newButton.onclick = func;
    newButton.tabIndex = 1;
    return newButton;
  }

  function createDropdown(name, values) {
    var container = chromespec.fgDoc.createElement('div');

    // Create the title label.
    container.appendChild(document.createTextNode(name + ': '));

    // Create the dropdown.
    var dropdown = chromespec.fgDoc.createElement('select');
    dropdown.id = name + '-dropdown';
    for (var value in values) {
      var option = chromespec.fgDoc.createElement('option');
      option.value = values[value];
      option.textContent = value;
      dropdown.appendChild(option);
    }
    container.appendChild(dropdown);

    return container;
  }

  function injectScript(doc, src, callback) {
    log('injecting script into ' + (doc == chromespec.fgDoc ? 'fg' : 'bg') + ': ' + src);
    var n = doc.createElement('script');
    n.onload = callback;
    n.src = src;
    var head = doc.querySelector('head');
    head.appendChild(n);
  }

  // Loads scripts in sequence.
  function injectScripts(doc, srcs, callback) {
    srcs = srcs.concat();
    function helper() {
      var src = srcs.shift();
      if (src) {
        injectScript(doc, src, helper);
      } else {
        callback && callback();
      }
    }
    helper();
  }

  function registerJasmineTest(testName) {
    chromespec.jasmineScripts[testName] = {
      name: testName,
      jsFile: 'test.' + testName + '.js',
      bgInstance: null,
      fgInstance: null
    };
  }

  function initJasmine(callback) {
    function afterJasmineLoaded() {
      // Make sure both pages use the same jasmine context.
      if (chromespec.fgWnd) {
        chromespec.fgWnd.jasmine = window.jasmine;
      }
      callback();
    }
    if (!jasmineLoaded) {
      jasmineLoaded = true;
      var scripts = [
          'third_party/jasmine-1.3.1/jasmine.js',
          'third_party/jasmine-1.3.1/jasmine-html.js',
          'jasmine_helper.js'
          ];
      injectScripts(document, scripts, afterJasmineLoaded);
    } else {
      afterJasmineLoaded();
    }
  }

  function registerSubPage(name, func) {
    chromespec.subPages.push({
      name: name,
      initFunc: func
    });
  }

  function registerJasmineTestInstance(runningInBg, name, func) {
    chromespec.jasmineScripts[name][runningInBg ? 'bgInstance' : 'fgInstance'] = func;
  }

  function injectStyle(src) {
    var n = chromespec.fgDoc.createElement('link');
    n.setAttribute('rel', 'stylesheet');
    n.setAttribute('href', src);
    chromespec.fgDoc.querySelector('head').appendChild(n);
  }

  function createUiWindow(onLoadCallback) {
    chrome.app.window.create('wnd.html', {
      width: 320,
      height: 380,
      id: 'ui'
    }, function(w) {
      log('UI window init start.');
      var wnd = w.contentWindow;
      chromespec.fgWnd = wnd;
      chromespec.fgDoc = wnd.document;
      wnd.onload = onUiWindowLoad;
      wnd.jasmine = window.jasmine;
      wnd.chromespec = chromespec;
      if (typeof onLoadCallback == 'function') {
        onLoadCallback(w);
      }
    });
  }

  function onUiWindowLoad() {
    injectStyle('third_party/jasmine-1.3.1/jasmine.css');
    injectStyle('spec_styles.css');
    // Inject jasmine.js again so that it will register it's global helper functions (e.g. it, describe).
    var scripts = [
        'third_party/jasmine-1.2.0/jasmine.js',
        'jasmine_helper.js'
    ];
    injectScripts(chromespec.fgDoc, scripts, onScriptsLoaded);
  }

  function ensureCordovaInitializes() {
    var timerId = window.setTimeout(function() {
      log('Cordova failed to initialize.');
    }, 500);
    chromespec.fgDoc.addEventListener('deviceready', function() {
      window.clearTimeout(timerId);
      log('Cordova initialized. platform: ' + chromespec.fgWnd.device.platform);
    }, false);
  }

  function onScriptsLoaded() {
    var homeButton = chromespec.createButton('Home', changePage.bind(null, 0));
    homeButton.classList.add('home-btn');
    chromespec.fgDoc.body.appendChild(homeButton);
    chromespec.fgDoc.body.insertAdjacentHTML('beforeend', '

' +
        '

' +
        '
Logsclear

');

    chromespec.fgDoc.querySelector('.clear-logs').onclick = clearLogs;

    chrome.storage.local.get('chromespec-page', function(values) {
      changePage(values && values['chromespec-page'] || 0);
    });
    ensureCordovaInitializes();
  }

  function changePage(pageIndex) {
    chrome.storage.local.set({'chromespec-page': pageIndex});
    clearLogs();
    var page = chromespec.subPages[pageIndex];
    var doc = chromespec.fgDoc;
    var pageContainerEl = doc.getElementById('page-container');
    doc.getElementById('page-title').textContent = page.name;
    pageContainerEl.innerHTML = '';
    page.initFunc(pageContainerEl);
  }

  function startUpLogic() {
    log('onLaunched called.');
    if (!window.noAutoCreateWindow) {
      createUiWindow();
    }
  }

  log('App started. ID = ' + chrome.runtime.id);
  chrome.app.runtime.onLaunched.addListener(startUpLogic);

  chromespec.changePage = changePage;
  chromespec.createButton = createButton;
  chromespec.createDropdown = createDropdown;
  chromespec.createUiWindow = createUiWindow;
  chromespec.log = log;
  chromespec.initJasmine = initJasmine;
  chromespec.injectScript = injectScript;
  chromespec.injectScripts = injectScripts;
  chromespec.injectStyle = injectStyle;
  chromespec.registerJasmineTest = registerJasmineTest;
  chromespec.registerJasmineTestInstance = registerJasmineTestInstance;
  chromespec.registerSubPage = registerSubPage;
})();

<|endoftext|>


<commit_before>'use strict';

let _       = require('lodash');
let path    = require('path');
let cdn     = require('./cdn');
let node    = require('./node');
let browser = require('./browser');

function newBuildDirectory(dir, subdir) {
  let build = path.join(dir.build, subdir);

  return { build: build };
}

module.exports = function(commander, dir) {
  let data = {};

  _.each(['cdn', 'node', 'browser'], function(target) {
    let newDirectory = newBuildDirectory(dir, target),
        directory    = _.defaults(newDirectory, dir),
        options      = _.defaults({ target: target }, commander);

    data[target] = {
      directory: directory,
      commander: options
    };
  });

  return [].concat(
    cdn(data.cdn.commander, data.cdn.directory),
    node(data.node.commander, data.node.directory),
    browser(data.browser.commander, data.browser.directory)
  );
};
<commit_msg>Use const when it makes sense in `all` target<commit_after>'use strict';

let _       = require('lodash');
let path    = require('path');
let cdn     = require('./cdn');
let node    = require('./node');
let browser = require('./browser');

function newBuildDirectory(dir, subdir) {
  const build = path.join(dir.build, subdir);

  return { build: build };
}

module.exports = function(commander, dir) {
  let data = {};

  _.each(['cdn', 'node', 'browser'], function(target) {
    const newDirectory = newBuildDirectory(dir, target),
          directory    = _.defaults(newDirectory, dir),
          options      = _.defaults({ target: target }, commander);

    data[target] = {
      directory: directory,
      commander: options
    };
  });

  return [].concat(
    cdn(data.cdn.commander, data.cdn.directory),
    node(data.node.commander, data.node.directory),
    browser(data.browser.commander, data.browser.directory)
  );
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  'use strict';

  var config = require('load-grunt-config')(grunt, {
    pattern: ['grunt-template-*', '!grunt-template-jasmine-requirejs']
  });

  grunt.loadTasks('grunt/tasks');

  config.pkg = grunt.file.readJSON('package.json');

  grunt.registerTask('norelease:patch', ['versioner:bumpOnly:default:patch']);

  grunt.registerTask('release:patch', ['versioner:bumpOnly:default:patch', 'versioner:commitOnly:default']);
  grunt.registerTask('release:minor', ['versioner:bumpOnly:default:minor', 'versioner:commitOnly:default']);
  grunt.registerTask('release:major', ['versioner:bumpOnly:default:major', 'versioner:commitOnly:default']);
  grunt.registerTask('latest-build:git', ['versioner:bumpOnly:default:git']);

  grunt.registerTask('release:npm', ['versioner:bumpOnly:git']);

  grunt.initConfig(config);
};
<commit_msg>should build git for git task not npm<commit_after>module.exports = function(grunt) {
  'use strict';

  var config = require('load-grunt-config')(grunt, {
    pattern: ['grunt-template-*', '!grunt-template-jasmine-requirejs']
  });

  grunt.loadTasks('grunt/tasks');

  config.pkg = grunt.file.readJSON('package.json');

  grunt.registerTask('norelease:patch', ['versioner:bumpOnly:default:patch']);

  grunt.registerTask('release:patch', ['versioner:bumpOnly:default:patch', 'versioner:commitOnly:default']);
  grunt.registerTask('release:minor', ['versioner:bumpOnly:default:minor', 'versioner:commitOnly:default']);
  grunt.registerTask('release:major', ['versioner:bumpOnly:default:major', 'versioner:commitOnly:default']);
  grunt.registerTask('latest-build:git', ['versioner:bumpOnly:git']);

  grunt.registerTask('release:npm', ['versioner:npmOnly:default']);

  grunt.initConfig(config);
};
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function(grunt) {
  var coreJsFiles = [
    // Core:
    'src/sigma.core.js',

    // Utils:
    'src/conrad.js',
    'src/utils/sigma.utils.js',
    'src/utils/sigma.polyfills.js',

    // Main classes:
    'src/sigma.settings.js',
    'src/classes/sigma.classes.dispatcher.js',
    'src/classes/sigma.classes.configurable.js',
    'src/classes/sigma.classes.graph.js',
    'src/classes/sigma.classes.camera.js',
    'src/classes/sigma.classes.quad.js',
    'src/classes/sigma.classes.edgequad.js',

    // Captors:
    'src/captors/sigma.captors.mouse.js',
    'src/captors/sigma.captors.touch.js',

    // Renderers:
    'src/renderers/sigma.renderers.canvas.js',
    'src/renderers/sigma.renderers.webgl.js',
    'src/renderers/sigma.renderers.svg.js',
    'src/renderers/sigma.renderers.def.js',

    // Sub functions per engine:
    'src/renderers/webgl/sigma.webgl.nodes.def.js',
    'src/renderers/webgl/sigma.webgl.nodes.fast.js',
    'src/renderers/webgl/sigma.webgl.edges.def.js',
    'src/renderers/webgl/sigma.webgl.edges.fast.js',
    'src/renderers/webgl/sigma.webgl.edges.arrow.js',
    'src/renderers/canvas/sigma.canvas.labels.def.js',
    'src/renderers/canvas/sigma.canvas.hovers.def.js',
    'src/renderers/canvas/sigma.canvas.nodes.def.js',
    'src/renderers/canvas/sigma.canvas.edges.def.js',
    'src/renderers/canvas/sigma.canvas.edges.curve.js',
    'src/renderers/canvas/sigma.canvas.edges.arrow.js',
    'src/renderers/canvas/sigma.canvas.edges.curvedArrow.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.def.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.curve.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.arrow.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js',
    'src/renderers/canvas/sigma.canvas.extremities.def.js',
    'src/renderers/svg/sigma.svg.utils.js',
    'src/renderers/svg/sigma.svg.nodes.def.js',
    'src/renderers/svg/sigma.svg.edges.def.js',
    'src/renderers/svg/sigma.svg.edges.curve.js',
    'src/renderers/svg/sigma.svg.labels.def.js',
    'src/renderers/svg/sigma.svg.hovers.def.js',

    // Middlewares:
    'src/middlewares/sigma.middlewares.rescale.js',
    'src/middlewares/sigma.middlewares.copy.js',

    // Miscellaneous:
    'src/misc/sigma.misc.animation.js',
    'src/misc/sigma.misc.bindEvents.js',
    'src/misc/sigma.misc.bindDOMEvents.js',
    'src/misc/sigma.misc.drawHovers.js'
  ];

  var npmJsFiles = coreJsFiles.slice(0);
  npmJsFiles.splice(2, 0, 'src/sigma.export.js');

  var plugins = [
    'exporters.svg',
    'layout.forceAtlas2',
    'parsers.cypher',
    'parsers.gexf',
    'parsers.json',
    'pathfinding.astar',
    'plugins.animate',
    'plugins.dragNodes',
    'plugins.filter',
    'plugins.neighborhoods',
    'plugins.relativeSize',
    'renderers.customEdgeShapes',
    'renderers.customShapes',
    'renderers.edgeLabels',
    'renderers.parallelEdges',
    'renderers.snapshot',
    'statistics.HITS'
  ];

  var pluginFiles = [],
      subGrunts = {};

  plugins.forEach(function(p) {
    var dir = 'plugins/sigma.' + p + '/';

    if (fs.existsSync(dir + 'Gruntfile.js'))
      subGrunts[p] = {
        gruntfile: dir + 'Gruntfile.js'
      };
    else
      pluginFiles.push(dir + '**/*.js');
  });

  // Project configuration:
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    grunt: subGrunts,
    closureLint: {
      app: {
        closureLinterPath: '/usr/local/bin',
        command: 'gjslint',
        src: coreJsFiles,
        options: {
          stdout: true,
          strict: true,
          opt: '--disable 6,13'
        }
      }
    },
    jshint: {
      all: coreJsFiles,
      options: {
        '-W055': true,
        '-W040': true,
        '-W064': true
      }
    },
    qunit: {
      all: {
        options: {
          urls: [
            './test/unit.html'
          ]
        }
      }
    },
    uglify: {
      prod: {
        files: {
          'build/sigma.min.js': coreJsFiles
        },
        options: {
          banner: '/* sigma.js - <%= pkg.description %> - Version: <%= pkg.version %> - Author: Alexis Jacomy, Sciences-Po Médialab - License: MIT */\n'
        }
      },
      plugins: {
        files: pluginFiles.reduce(function(res, path) {
          var dest = 'build/' + path.replace(/\/\*\*\/\*\.js$/, '.min.js');
          res[dest] = path;
          return res;
        }, {})
      }
    },
    concat: {
      options: {
        separator: '\n'
      },
      dist: {
        src: coreJsFiles,
        dest: 'build/sigma.js'
      },
      require: {
        src: npmJsFiles,
        dest: 'build/sigma.require.js'
      }
    },
    sed: {
      version: {
        recursive: true,
        path: 'examples/',
        pattern: /<!-- START SIGMA IMPORTS -->[\s\S]*<!-- END SIGMA IMPORTS -->/g,
        replacement: ['<!-- START SIGMA IMPORTS -->'].concat(coreJsFiles.map(function(path) {
          return '<script src="../' + path + '"></script>';
        }).concat('<!-- END SIGMA IMPORTS -->')).join('\n')
      }
    },
    zip: {
      release: {
        dest: 'build/release-v<%= pkg.version %>.zip',
        src: [
          'README.md',
          'build/sigma.min.js',
          'build/plugins/*.min.js'
        ],
        router: function(filepath) {
          return filepath.replace(/build\//, '');
        }
      }
    }
  });

  require('load-grunt-tasks')(grunt);

  // By default, will check lint, hint, test and minify:
  grunt.registerTask('default', ['closureLint', 'jshint', 'qunit', 'sed', 'grunt', 'uglify']);
  grunt.registerTask('release', ['closureLint', 'jshint', 'qunit', 'sed', 'grunt', 'uglify', 'zip']);
  grunt.registerTask('npmPrePublish', ['uglify:plugins', 'grunt', 'concat:require']);
  grunt.registerTask('build', ['uglify', 'grunt', 'concat:require']);
  grunt.registerTask('test', ['qunit']);

  // For travis-ci.org, only launch tests:
  grunt.registerTask('travis', ['qunit']);
};
<commit_msg>Renaming the neo4j plugin in Gruntfile.js<commit_after>var fs = require('fs');

module.exports = function(grunt) {
  var coreJsFiles = [
    // Core:
    'src/sigma.core.js',

    // Utils:
    'src/conrad.js',
    'src/utils/sigma.utils.js',
    'src/utils/sigma.polyfills.js',

    // Main classes:
    'src/sigma.settings.js',
    'src/classes/sigma.classes.dispatcher.js',
    'src/classes/sigma.classes.configurable.js',
    'src/classes/sigma.classes.graph.js',
    'src/classes/sigma.classes.camera.js',
    'src/classes/sigma.classes.quad.js',
    'src/classes/sigma.classes.edgequad.js',

    // Captors:
    'src/captors/sigma.captors.mouse.js',
    'src/captors/sigma.captors.touch.js',

    // Renderers:
    'src/renderers/sigma.renderers.canvas.js',
    'src/renderers/sigma.renderers.webgl.js',
    'src/renderers/sigma.renderers.svg.js',
    'src/renderers/sigma.renderers.def.js',

    // Sub functions per engine:
    'src/renderers/webgl/sigma.webgl.nodes.def.js',
    'src/renderers/webgl/sigma.webgl.nodes.fast.js',
    'src/renderers/webgl/sigma.webgl.edges.def.js',
    'src/renderers/webgl/sigma.webgl.edges.fast.js',
    'src/renderers/webgl/sigma.webgl.edges.arrow.js',
    'src/renderers/canvas/sigma.canvas.labels.def.js',
    'src/renderers/canvas/sigma.canvas.hovers.def.js',
    'src/renderers/canvas/sigma.canvas.nodes.def.js',
    'src/renderers/canvas/sigma.canvas.edges.def.js',
    'src/renderers/canvas/sigma.canvas.edges.curve.js',
    'src/renderers/canvas/sigma.canvas.edges.arrow.js',
    'src/renderers/canvas/sigma.canvas.edges.curvedArrow.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.def.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.curve.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.arrow.js',
    'src/renderers/canvas/sigma.canvas.edgehovers.curvedArrow.js',
    'src/renderers/canvas/sigma.canvas.extremities.def.js',
    'src/renderers/svg/sigma.svg.utils.js',
    'src/renderers/svg/sigma.svg.nodes.def.js',
    'src/renderers/svg/sigma.svg.edges.def.js',
    'src/renderers/svg/sigma.svg.edges.curve.js',
    'src/renderers/svg/sigma.svg.labels.def.js',
    'src/renderers/svg/sigma.svg.hovers.def.js',

    // Middlewares:
    'src/middlewares/sigma.middlewares.rescale.js',
    'src/middlewares/sigma.middlewares.copy.js',

    // Miscellaneous:
    'src/misc/sigma.misc.animation.js',
    'src/misc/sigma.misc.bindEvents.js',
    'src/misc/sigma.misc.bindDOMEvents.js',
    'src/misc/sigma.misc.drawHovers.js'
  ];

  var npmJsFiles = coreJsFiles.slice(0);
  npmJsFiles.splice(2, 0, 'src/sigma.export.js');

  var plugins = [
    'exporters.svg',
    'layout.forceAtlas2',
    'neo4j.cypher',
    'parsers.gexf',
    'parsers.json',
    'pathfinding.astar',
    'plugins.animate',
    'plugins.dragNodes',
    'plugins.filter',
    'plugins.neighborhoods',
    'plugins.relativeSize',
    'renderers.customEdgeShapes',
    'renderers.customShapes',
    'renderers.edgeLabels',
    'renderers.parallelEdges',
    'renderers.snapshot',
    'statistics.HITS'
  ];

  var pluginFiles = [],
      subGrunts = {};

  plugins.forEach(function(p) {
    var dir = 'plugins/sigma.' + p + '/';

    if (fs.existsSync(dir + 'Gruntfile.js'))
      subGrunts[p] = {
        gruntfile: dir + 'Gruntfile.js'
      };
    else
      pluginFiles.push(dir + '**/*.js');
  });

  // Project configuration:
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    grunt: subGrunts,
    closureLint: {
      app: {
        closureLinterPath: '/usr/local/bin',
        command: 'gjslint',
        src: coreJsFiles,
        options: {
          stdout: true,
          strict: true,
          opt: '--disable 6,13'
        }
      }
    },
    jshint: {
      all: coreJsFiles,
      options: {
        '-W055': true,
        '-W040': true,
        '-W064': true
      }
    },
    qunit: {
      all: {
        options: {
          urls: [
            './test/unit.html'
          ]
        }
      }
    },
    uglify: {
      prod: {
        files: {
          'build/sigma.min.js': coreJsFiles
        },
        options: {
          banner: '/* sigma.js - <%= pkg.description %> - Version: <%= pkg.version %> - Author: Alexis Jacomy, Sciences-Po Médialab - License: MIT */\n'
        }
      },
      plugins: {
        files: pluginFiles.reduce(function(res, path) {
          var dest = 'build/' + path.replace(/\/\*\*\/\*\.js$/, '.min.js');
          res[dest] = path;
          return res;
        }, {})
      }
    },
    concat: {
      options: {
        separator: '\n'
      },
      dist: {
        src: coreJsFiles,
        dest: 'build/sigma.js'
      },
      require: {
        src: npmJsFiles,
        dest: 'build/sigma.require.js'
      }
    },
    sed: {
      version: {
        recursive: true,
        path: 'examples/',
        pattern: /<!-- START SIGMA IMPORTS -->[\s\S]*<!-- END SIGMA IMPORTS -->/g,
        replacement: ['<!-- START SIGMA IMPORTS -->'].concat(coreJsFiles.map(function(path) {
          return '<script src="../' + path + '"></script>';
        }).concat('<!-- END SIGMA IMPORTS -->')).join('\n')
      }
    },
    zip: {
      release: {
        dest: 'build/release-v<%= pkg.version %>.zip',
        src: [
          'README.md',
          'build/sigma.min.js',
          'build/plugins/*.min.js'
        ],
        router: function(filepath) {
          return filepath.replace(/build\//, '');
        }
      }
    }
  });

  require('load-grunt-tasks')(grunt);

  // By default, will check lint, hint, test and minify:
  grunt.registerTask('default', ['closureLint', 'jshint', 'qunit', 'sed', 'grunt', 'uglify']);
  grunt.registerTask('release', ['closureLint', 'jshint', 'qunit', 'sed', 'grunt', 'uglify', 'zip']);
  grunt.registerTask('npmPrePublish', ['uglify:plugins', 'grunt', 'concat:require']);
  grunt.registerTask('build', ['uglify', 'grunt', 'concat:require']);
  grunt.registerTask('test', ['qunit']);

  // For travis-ci.org, only launch tests:
  grunt.registerTask('travis', ['qunit']);
};
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (openerp) {
var QWeb = openerp.web.qweb,
      _t = openerp.web._t,
     _lt = openerp.web._lt;
openerp.web.views.add('diagram', 'openerp.web.DiagramView');
openerp.web.DiagramView = openerp.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        this._super();
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;

        this.$element.html(QWeb.render("DiagramView", this));

        this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$element.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params,
            function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        console.log(result);
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;

        var id_to_node = {};

        var style = {   "edge"          : "#A0A0A0",
                        "edge_label"    : "#555",
                        "text"          : "#333",
                        "outline"       : "#333",
                        "selected"      : "#0097BE",
                        "gray"          : "#DCDCDC",
                        "white"         : "#FFF",
                        "node_size_x"   : 100,
                        "node_size_y"   : 70,
                        "edge_spacing"  : 100,
                        "edge_label_font_size" : 10              };

        $('#dia-canvas').empty();    // remove previous diagram

        var r  = new Raphael(document.getElementById("dia-canvas"), '100%','100%');

        var graph  = new CuteGraph(r,style);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(     graph,
                                      node.x + 50,  //FIXME the +50 should be in the layout algorithm
                                      node.y + 50,
                                      CuteGraph.wordwrap(node.name, 16),
                                      node.shape === 'rectangle' ? 'rect' : 'circle',
                                      node.color === 'white' ? style.white : style.gray    );
            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(          graph,
                                            CuteGraph.wordwrap(edge.signal, 32),
                                            id_to_node[edge.s_id],
                                            id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };

        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector( cuteedge.get_start().id,
                                cuteedge.get_end().id,
                                cuteedge);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new openerp.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_first(function() {
            _.each(form_fields, function(fld) {
                    if (!(fld in form_controller.fields)) { return; }
                    var field = form_controller.fields[fld];
                    field.$input.prop('disabled', true);
                    field.$drop_down.unbind();
                    field.$menu_btn.unbind();
                });
            });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new openerp.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on_record_loaded.add_last(function() {
                _.each(form_fields, function(fld) {
                    if (!(fld in form_controller.fields)) { return; }
                    var field = form_controller.fields[fld];
                    field.set_value(self.id);
                    field.dirty = true;
                });
            });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new openerp.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$element.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_last(function () {
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
        });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_diagram_loaded);
        this.do_update_pager();
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return this._super();
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[REM] leftover logging<commit_after>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (openerp) {
var QWeb = openerp.web.qweb,
      _t = openerp.web._t,
     _lt = openerp.web._lt;
openerp.web.views.add('diagram', 'openerp.web.DiagramView');
openerp.web.DiagramView = openerp.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        this._super();
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;

        this.$element.html(QWeb.render("DiagramView", this));

        this.$element.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.on_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$element.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params,
            function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
        }
    },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;

        var id_to_node = {};

        var style = {   "edge"          : "#A0A0A0",
                        "edge_label"    : "#555",
                        "text"          : "#333",
                        "outline"       : "#333",
                        "selected"      : "#0097BE",
                        "gray"          : "#DCDCDC",
                        "white"         : "#FFF",
                        "node_size_x"   : 100,
                        "node_size_y"   : 70,
                        "edge_spacing"  : 100,
                        "edge_label_font_size" : 10              };

        $('#dia-canvas').empty();    // remove previous diagram

        var r  = new Raphael(document.getElementById("dia-canvas"), '100%','100%');

        var graph  = new CuteGraph(r,style);

        _.each(res_nodes, function(node) {
            var n = new CuteNode(     graph,
                                      node.x + 50,  //FIXME the +50 should be in the layout algorithm
                                      node.y + 50,
                                      CuteGraph.wordwrap(node.name, 16),
                                      node.shape === 'rectangle' ? 'rect' : 'circle',
                                      node.color === 'white' ? style.white : style.gray    );
            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(          graph,
                                            CuteGraph.wordwrap(edge.signal, 32),
                                            id_to_node[edge.s_id],
                                            id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };

        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector( cuteedge.get_start().id,
                                cuteedge.get_end().id,
                                cuteedge);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new openerp.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );

        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_first(function() {
            _.each(form_fields, function(fld) {
                    if (!(fld in form_controller.fields)) { return; }
                    var field = form_controller.fields[fld];
                    field.$input.prop('disabled', true);
                    field.$drop_down.unbind();
                    field.$menu_btn.unbind();
                });
            });
    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new openerp.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on_record_loaded.add_last(function() {
                _.each(form_fields, function(fld) {
                    if (!(fld in form_controller.fields)) { return; }
                    var field = form_controller.fields[fld];
                    field.set_value(self.id);
                    field.dirty = true;
                });
            });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new openerp.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on_write.add(function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new openerp.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );

        pop.on_select_elements.add_last(function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$element.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

        form_controller.on_record_loaded.add_last(function () {
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
        });
    },

    on_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_diagram_loaded);
        this.do_update_pager();
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$element.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return this._super();
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>/*
 * grunt-require-gettext
 * https://github.com/open-xchange-frontend/grunt-require-gettext
 *
 * Copyright (c) 2014 Julian Bäume
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        watch: {
            options: {
                interrupt: true,
                spawn: true
            },
            all: {
                files: ['spec/**/*.*', 'tasks/*.js', 'Gruntfile.js'],
                tasks: ['jshint', 'create_pot', 'compile_po', 'mochaTest']
            }
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                'tasks/*.js'
            ],
            specs: {
                options: {
                    jshintrc: 'spec/.jshintrc'
                },
                src: ['spec/**/*_spec.js']
            }
        },

        // Before generating any new files, remove any previously-created files.
        clean: {
            tests: ['tmp']
        },

        // Configuration to be run (and then tested).
        create_pot: {
            simple: {
                options: {
                    headers: {
                        'PO-Revision-Date': 'DATE',
                        'Last-Translator': 'NAME <EMAIL>',
                        'Language-Team': 'NAME <EMAIL>',
                        'MIME-Version': '1.0',
                        'Content-Type': 'text/plain; charset=UTF-8',
                        'Content-Transfer-Encoding': '8bit',
                        'Plural-Forms': 'nplurals=INTEGER; plural=EXPRESSION;'
                    }
                },
                files: {
                    'tmp/i18n/simple.pot': [
                        'spec/fixtures/simpleModule.js',
                        'spec/fixtures/fuzzyModule.js'
                    ]
                }
            },
            no_headers: {
                files: {
                    'tmp/i18n/simple_no_headers.pot': ['spec/fixtures/simpleModule.js']
                }
            }
        },

        compile_po: {
            simple: {
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/'
                }]
            },
            fuzzy: {
                options: {
                    template: 'spec/fixtures/templates/custom.tpl',
                    includeFuzzy: true
                },
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/includeFuzzy/'
                }]
            },
            custom_template: {
                options: {
                    template: 'spec/fixtures/templates/custom.tpl'
                },
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/custom/'
                }]
            }
        },

        // Unit tests.
        mochaTest: {
            tests: {
                src: 'spec/**/*_spec.js',
                options: {
                    reporter: 'spec'
                }
            }
        }

    });

    // Actually load this plugin's task(s).
    grunt.loadTasks('tasks');

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-mocha-test');

    // Whenever the "test" task is run, first clean the "tmp" dir, then run this
    // plugin's task(s), then test the result.
    grunt.registerTask('test', ['clean', 'create_pot', 'compile_po', 'mochaTest']);

    // By default, lint and run all tests.
    grunt.registerTask('default', ['jshint', 'test']);

};
<commit_msg>grunt: run clean task if any file changed<commit_after>/*
 * grunt-require-gettext
 * https://github.com/open-xchange-frontend/grunt-require-gettext
 *
 * Copyright (c) 2014 Julian Bäume
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    // Project configuration.
    grunt.initConfig({
        watch: {
            options: {
                interrupt: true,
                spawn: true
            },
            all: {
                files: ['spec/**/*.*', 'tasks/*.js', 'Gruntfile.js'],
                tasks: ['clean', 'jshint', 'create_pot', 'compile_po', 'mochaTest']
            }
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                'tasks/*.js'
            ],
            specs: {
                options: {
                    jshintrc: 'spec/.jshintrc'
                },
                src: ['spec/**/*_spec.js']
            }
        },

        // Before generating any new files, remove any previously-created files.
        clean: {
            tests: ['tmp']
        },

        // Configuration to be run (and then tested).
        create_pot: {
            simple: {
                options: {
                    headers: {
                        'PO-Revision-Date': 'DATE',
                        'Last-Translator': 'NAME <EMAIL>',
                        'Language-Team': 'NAME <EMAIL>',
                        'MIME-Version': '1.0',
                        'Content-Type': 'text/plain; charset=UTF-8',
                        'Content-Transfer-Encoding': '8bit',
                        'Plural-Forms': 'nplurals=INTEGER; plural=EXPRESSION;'
                    }
                },
                files: {
                    'tmp/i18n/simple.pot': [
                        'spec/fixtures/simpleModule.js',
                        'spec/fixtures/fuzzyModule.js'
                    ]
                }
            },
            no_headers: {
                files: {
                    'tmp/i18n/simple_no_headers.pot': ['spec/fixtures/simpleModule.js']
                }
            }
        },

        compile_po: {
            simple: {
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/'
                }]
            },
            fuzzy: {
                options: {
                    template: 'spec/fixtures/templates/custom.tpl',
                    includeFuzzy: true
                },
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/includeFuzzy/'
                }]
            },
            custom_template: {
                options: {
                    template: 'spec/fixtures/templates/custom.tpl'
                },
                files: [{
                    src: ['spec/fixtures/**/*.po'],
                    dest: 'tmp/build/i18n/custom/'
                }]
            }
        },

        // Unit tests.
        mochaTest: {
            tests: {
                src: 'spec/**/*_spec.js',
                options: {
                    reporter: 'spec'
                }
            }
        }

    });

    // Actually load this plugin's task(s).
    grunt.loadTasks('tasks');

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-mocha-test');

    // Whenever the "test" task is run, first clean the "tmp" dir, then run this
    // plugin's task(s), then test the result.
    grunt.registerTask('test', ['clean', 'create_pot', 'compile_po', 'mochaTest']);

    // By default, lint and run all tests.
    grunt.registerTask('default', ['jshint', 'test']);

};
<|endoftext|>