Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
evergreen / app / assets / javascripts / admin_actions.js
Size: Mime:
//= require bootstrap
//= require handlebars

var AdminActions = function() {
  this.init();
};

AdminActions.prototype = {
  el: 'fieldset.actions',
  errors: '.errors',
  actions_template: '#tmpl-contextual_actions',
  errors_template: '#tmpl-errors',
  buttonDefaults: {
    name: 'commit',
    value: 'Submit',
    type: 'submit'
  },

  init: function() {
    if (!$(this.actions_template).length) { return; }

    this.$actions = $(this.el);
    this.renderToolbar();

    return this;
  },

  renderToolbar: function(record, actions, notice) {
    var html       = '';
    record         = record || {};
    template       = this.compileTemplate(this.actions_template);
    record.actions = this.buildActions(actions);
    record.notice  = notice;
    html           = $.trim(template(record));

    if (this.$actions.length) {
      this.$actions.replaceWith(html);
    } else {
      $(html).prependTo('form');
    }

    $(this.errors).remove();
    this.removeNotice(4000);

    if (record.id) {
      this.updateFormAction(record);
      this.addMethodField();
    }

    this.$actions = $(this.el);
    this.affix();
  },

  renderErrors: function(errors) {
    var html = '';
    errors   = errors || [];

    $(this.errors).remove();

    template = this.compileTemplate(this.errors_template);
    html = $.trim(template({ errors: errors }));

    $(html).insertAfter(this.el);
  },

  removeNotice: function(timeout) {
    var that = this;

    setTimeout(function() {
      $(that.el).find('.notice').fadeOut('fast', function() {
        $(this).remove();
      });
    }, timeout);
  },

  buildActions: function(actions) {
    var collection = [],
        that = this;

    actions = actions || [];

    $.each(actions, function(i) {
      var attrs = $.extend({}, that.buttonDefaults, actions[i]);
      var $action = $("<input>", attrs)[0].outerHTML;

      collection.push($action);
    });

    return collection;
  },

  updateFormAction: function(record) {
    form_action = $('form')[0].action;

    if (!(/[\d]+$/).test(form_action)) {
      $('form')[0].action += "/" + record.id;
    }
  },

  addMethodField: function(record) {
    var $method = $('form').find('input[name=_method]');

    if (!$method.length) {
      $('form').prepend('<input name="_method" type="hidden" value="put">');
    }
  },

  compileTemplate: function(template) {
    var source = $(template).html();
    return Handlebars.compile(source);
  },

  affix: function() {
    var that = this;
    that.$actions.find('.affix-container').affix({
      offset: 151
    });
    that.$actions.height(that.$actions.height() || 27);
  }
};