<commit_before>define(['dojo/_base/Deferred', 'dojo/topic', 'dojo/request/xhr',
  'dojo/promise/all', 'dojo/store/Memory', 'dojo/store/Observable', 'dojo/when'
], function (
  Deferred, Topic, xhr,
  All, MemoryStore, Observable, when
) {

  var self = this;
  var TIME_OUT = 5000; // in ms

  // state model of filters applied to jobs
  self.filters = {
    app: 'all',
    status: null
  };

  // state of status (used to detect changes)
  var StatusSummary = { init: null };

  var _DataStore = new MemoryStore({
    idProperty: 'id',
    data: []
  });

  /**
   * updates the job list (see JobsGrid.js)
   */
  function updateJobsList(cb) {
    Topic.publish('/Jobs', { status: 'loading' });

    var prom = window.App.api.service('AppService.enumerate_tasks', [0, 30000]);
    return prom.then(function (res) {
      // filter out jobs marked as deleted (includes killed jobs)
      var jobs = res[0].filter(function (job) { return job.status !== 'deleted'; });

      _DataStore.setData(jobs);

      if (self.filters.app || self.filters.status) {
        Topic.publish('/Jobs', { status: 'filtered', jobs: _DataStore.data });
        Topic.publish('/JobFilter', self.filters);
        return;
      }

      Topic.publish('/Jobs', { status: 'updated', jobs: _DataStore.data });

      if (cb) cb();
    });
  }

  /**
   * sets status locally, publishes status for jobs ticker, and returns True if any changes
   */
  function getStatus() {
    var prom = window.App.api.service('AppService.query_task_summary', []);
    return prom.then(function (res) {
      var status = res[0];

      var queued = (status.queued || 0) + (status.pending || 0) + (status.init || 0);
      var inProgress = status['in-progress'] || 0;
      var completed = status.completed || 0;
      var failed = status.failed || 0;

      // check for any changes in status
      var change = false;
      if (queued !== StatusSummary.queued ||
          inProgress !== StatusSummary.inProgress ||
          completed !== StatusSummary.completed ||
          failed !== StatusSummary.failed) {
        change = true;
      }

      StatusSummary = {
        queued: queued,
        inProgress: inProgress,
        completed: completed,
        failed: failed
      };

      // publish job status for jobs ticker
      Topic.publish('/JobStatus', StatusSummary);

      return change; // bool
    });
  }

  function PollJobs() {
    // leaving this here since instantiation order is unpredictable
    if (!(window.App && window.App.api && window.App.api.service)) {
      setTimeout(PollJobs, 1000);
      return;
    }

    // check for status change.  if change, update jobs list
    var prom = getStatus();
    prom.then(function (statusChange) {
      if (statusChange) {
        updateJobsList().then(function () {
          setTimeout(PollJobs, TIME_OUT);
        });
        return;
      }

      setTimeout(PollJobs, TIME_OUT);
    });
  }

  // kick off the polling
  setTimeout(PollJobs, 1000);

  /**
   * listen for job filtering to store filter state locally
   */
  Topic.subscribe('/JobFilter', function (filter) {
    Object.assign(self.filters, filter);
  });

  return {
    queryTaskDetail: function (id, stdout, stderr) {
      return Deferred.when(window.App.api.service('AppService.query_task_details', [id]), function (detail) {
        detail = detail[0];
        var defs = [];
        if (detail.stderr_url && stderr) {
          defs.push(Deferred.when(xhr.get(detail.stderr_url, {
            headers: {
              Authorization: 'Oauth ' + window.App.authorizationToken,
              'X-Requested-With': false
            }
          }), function (txt) {
            detail.stderr = txt;

          }));
        }
        if (detail.stdout_url && stdout) {
          defs.push(Deferred.when(xhr.get(detail.stdout_url, {
            headers: {
              Authorization: 'Oauth ' + window.App.authorizationToken,
              'X-Requested-With': false
            }
          }), function (txt) {
            detail.stdout = txt;

          }));
        }
        if (defs.length < 1) {
          return detail;
        }
        return Deferred.when(All(defs), function () {
          return detail;
        });

      });
    },

    getStore: function () {
      return _DataStore;
    },

    killJob: function (id) {

      Topic.publish('/Notification', {
        message: 'Terminating job '+id+'...',
        type: 'default',
        duration: 50000
      });

      window.App.api.service('AppService.kill_task', [id]).then(function (res) {
        updateJobsList(function () {
          Topic.publish('/Notification', {
            message: 'Job terminated.',
            type: 'message'
          });
        });
      });

    }
  };
});
<commit_msg>move callback<commit_after>define(['dojo/_base/Deferred', 'dojo/topic', 'dojo/request/xhr',
  'dojo/promise/all', 'dojo/store/Memory', 'dojo/store/Observable', 'dojo/when'
], function (
  Deferred, Topic, xhr,
  All, MemoryStore, Observable, when
) {

  var self = this;
  var TIME_OUT = 5000; // in ms

  // state model of filters applied to jobs
  self.filters = {
    app: 'all',
    status: null
  };

  // state of status (used to detect changes)
  var StatusSummary = { init: null };

  var _DataStore = new MemoryStore({
    idProperty: 'id',
    data: []
  });

  /**
   * updates the job list (see JobsGrid.js)
   */
  function updateJobsList(cb) {
    Topic.publish('/Jobs', { status: 'loading' });

    var prom = window.App.api.service('AppService.enumerate_tasks', [0, 30000]);
    return prom.then(function (res) {
      // filter out jobs marked as deleted (includes killed jobs)
      var jobs = res[0].filter(function (job) { return job.status !== 'deleted'; });

      _DataStore.setData(jobs);

      // perform any callback action before filtering
      if (cb) cb();

      if (self.filters.app || self.filters.status) {
        Topic.publish('/Jobs', { status: 'filtered', jobs: _DataStore.data });
        Topic.publish('/JobFilter', self.filters);
        return;
      }

      Topic.publish('/Jobs', { status: 'updated', jobs: _DataStore.data });
    });
  }

  /**
   * sets status locally, publishes status for jobs ticker, and returns True if any changes
   */
  function getStatus() {
    var prom = window.App.api.service('AppService.query_task_summary', []);
    return prom.then(function (res) {
      var status = res[0];

      var queued = (status.queued || 0) + (status.pending || 0) + (status.init || 0);
      var inProgress = status['in-progress'] || 0;
      var completed = status.completed || 0;
      var failed = status.failed || 0;

      // check for any changes in status
      var change = false;
      if (queued !== StatusSummary.queued ||
          inProgress !== StatusSummary.inProgress ||
          completed !== StatusSummary.completed ||
          failed !== StatusSummary.failed) {
        change = true;
      }

      StatusSummary = {
        queued: queued,
        inProgress: inProgress,
        completed: completed,
        failed: failed
      };

      // publish job status for jobs ticker
      Topic.publish('/JobStatus', StatusSummary);

      return change; // bool
    });
  }

  function PollJobs() {
    // leaving this here since instantiation order is unpredictable
    if (!(window.App && window.App.api && window.App.api.service)) {
      setTimeout(PollJobs, 1000);
      return;
    }

    // check for status change.  if change, update jobs list
    var prom = getStatus();
    prom.then(function (statusChange) {
      if (statusChange) {
        updateJobsList().then(function () {
          setTimeout(PollJobs, TIME_OUT);
        });
        return;
      }

      setTimeout(PollJobs, TIME_OUT);
    });
  }

  // kick off the polling
  setTimeout(PollJobs, 1000);

  /**
   * listen for job filtering to store filter state locally
   */
  Topic.subscribe('/JobFilter', function (filter) {
    Object.assign(self.filters, filter);
  });

  return {
    queryTaskDetail: function (id, stdout, stderr) {
      return Deferred.when(window.App.api.service('AppService.query_task_details', [id]), function (detail) {
        detail = detail[0];
        var defs = [];
        if (detail.stderr_url && stderr) {
          defs.push(Deferred.when(xhr.get(detail.stderr_url, {
            headers: {
              Authorization: 'Oauth ' + window.App.authorizationToken,
              'X-Requested-With': false
            }
          }), function (txt) {
            detail.stderr = txt;

          }));
        }
        if (detail.stdout_url && stdout) {
          defs.push(Deferred.when(xhr.get(detail.stdout_url, {
            headers: {
              Authorization: 'Oauth ' + window.App.authorizationToken,
              'X-Requested-With': false
            }
          }), function (txt) {
            detail.stdout = txt;

          }));
        }
        if (defs.length < 1) {
          return detail;
        }
        return Deferred.when(All(defs), function () {
          return detail;
        });

      });
    },

    getStore: function () {
      return _DataStore;
    },

    killJob: function (id) {

      Topic.publish('/Notification', {
        message: 'Terminating job '+id+'...',
        type: 'default',
        duration: 50000
      });

      window.App.api.service('AppService.kill_task', [id]).then(function (res) {
        updateJobsList(function () {
          Topic.publish('/Notification', {
            message: 'Job terminated.',
            type: 'message'
          });
        });
      });

    }
  };
});
<|endoftext|>


<commit_before>"use strict";

var preprocess = require("./preprocess.js"),
    ast = require("./ast.js");

function pushCloneOf(idx, item) {
    /*jshint validthis:true*/ //
    this.push(gpf.clone(item));
}

/**
 * Process a specific source
 *
 * @param {Object} parsed Dictionary of sources
 * @param {String} source Source name
 * @param {Object} version Version to apply
 * @param {Object} placeholder result AST placeholder
 * @param {ASTreducer} reducer
 */
function process (parsed, source, version, placeholder, reducer) {
    var body;
    try {
        body = parsed[source].body;
    } catch(e) {
        console.error("Error while processing source: " + source
        + "\r\n" + e.message);
    }
    if (version.reduce) {
        reducer.reduce(body);
        try {
            parsed[source + ".compact.js"] = ast.rewrite(parsed[source], versions.debug.rewriteOptions);
        } catch (e) {
            console.error("Failed to generate compact source for " + source + ": " + e.message);
        }
    }
    if (body instanceof Array) {
        gpf.each.apply(placeholder, [body, pushCloneOf]);
    } else {
        placeholder.push(gpf.clone(body));
    }
}

/**
 * Build the requested version
 *
 * @param {Object} sources Dictionary of sources
 * @param {Object} parameters Version parameters
 * @param {Object} temporary Dictionary of intermediate results
 * @returns {String}
 */
module.exports = function (sources, parameters, temporary) {
    var parsed,
        placeholder,
        idx,
        source,
        reducer = null;
    // First, parse everything
    temporary["UMD.js"] = preprocess(sources.UMD, parameters);
    temporary.UMD = ast.transform(temporary["UMD.js"], parameters);
    if (parameters.reduce) {
        ast.reduce(temporary.UMD.body);
        try {
            temporary["UMD.compact.js"] = ast.rewrite(temporary.UMD, parameters.rewriteOptions);
        } catch (e) {
            console.error("Failed to generate compact source for UMD: " + e.message);
        }
    }
    parsed.result = gpf.clone(temporary.UMD);
    parsed["boot.js"] = preProcess(sources.boot, version);
    parsed.boot = toAST(parsed, "boot.js", version);
    for (idx = 0; idx < sources._list.length; ++idx) {
        source = sources._list[idx];
        parsed[source + ".js"] = preProcess(sources[source], version);
        parsed[source] = toAST(parsed, source + ".js", version);
    }
    placeholder = parsed.result.body[0].expression["arguments"][1].body.body;
    placeholder.pop(); // remove __gpf__
    // Add all sources
    for (idx = -1; idx < sources._list.length; ++idx) {
        if (-1 === idx) {
            source = "boot";
        } else {
            source = sources._list[idx];
        }
        process(parsed, source, version, placeholder, reducer);
    }
    // And generate the result
    parsed["result.js"] = escodegen.generate(parsed.result, version.rewriteOptions);
    return parsed["result.js"];
};
<commit_msg>Refactoring<commit_after>"use strict";

var fs = require("fs"),
    preprocess = require("./preprocess.js"),
    ast = require("./ast.js");

function clone (obj) {
    return JSON.parse(JSON.stringify(obj));
}

function Builder(sources, parameters) {
    this._sources = sources;
    this._parameters = parameters;
}

Builder.prototype = {

    // Sources dictionary (name => String)
    _sources: {},

    // Parameters of the build
    _parameters: {},

    // AST objects (name => Object)
    _asts: {},

    // AST result placeholder
    _placeholder: {},

    // save temporary files
    _save: function (fileName, data) {
        if (this._parameters.saveTemporaryfiles) {
            fs.writeFileSync(this._parameters.temporaryPath+ "/" + fileName, data);
        }
    },

    // preprocess source file, convert to AST and reduce it if necessary
    _toAst: function (name) {
        var source,
            astObject;
        try {
            preprocess(this._sources[name], this._parameters.define);
        } catch (e) {
            e.sourceName = name;
            e.step = "preprocess";
            throw e;
        }
        this._save(name + ".js", source);
        try {
            astObject = ast.transform(source);
        } catch (e) {
            e.sourceName = name;
            e.step = "ast.transform";
            throw e;
        }
        this._save(name + ".ast.json", JSON.stringify(astObject));
        if (this.parameters.reduce) {
            try {
                astObject = ast.reduce(astObject);
            } catch (e) {
                e.sourceName = name;
                e.step = "ast.reduce";
                throw e;
            }
            this._save(name + ".ast.reduced.json", JSON.stringify(astObject));
            this._save(name + ".ast.reduced.js", ast.rewrite(astObject, this._parameters.debugRewriteOptions));
        }
        this._asts[name] = astObject;
        return astObject;
    },

    // _toAst and append to _placeholder
    _addAst: function (name) {
        var astObject = this._toAst(name),
            astBody = clone(astObject.body),
            placeholder = this._placeholder;
        if (astBody instanceof Array) {
            astBody.forEach(placeholder.push, placeholder);
        } else {
            placeholder.push(astBody);
        }
    },

    build: function () {
        var resultAst,
            name;
        // Generate UMD AST
        resultAst = clone(this._toAst("UMD"));
        // Grab the final placeholder
        this._placeholder = resultAst.body[0].expression["arguments"][1].body.body;
        this._placeholder.pop(); // remove __gpf__
        // Generate all ASTs and aggregate to the final result
        this._addAst("boot");
        for (name in this._sources) {
            if (this._sources.hasOwnProperty(name)) {
                this._addAst(name);
            }
        }
        // Generate the final result
        return ast.rewrite(resultAst, this._parameters.rewriteOptions);
    }

};

/**
 * Build the requested version
 *
 * @param {Object} sources Dictionary of sources
 * @param {Object} parameters Version parameters
 * @param {Object} temporary Dictionary of intermediate results
 * @returns {String}
 */
module.exports = function (sources, parameters) {
    var builder = new Builder(sources, parameters);
    return builder.build();
};
<|endoftext|>


<commit_before>(function() {
    /*!
     * Саджест
     * @namespace jquery.ui.suggest
     * @extends {jquery.ui.autocomplete} http://api.jqueryui.com/autocomplete/
     * @description
     *      Саджест это блок сотоящий из инпута и выпадающего списка.
     *      При вводе какого-либо значения в инпут это значение матчится на список
     *      слов из источника данных, и подходящие элементы из исходного списка
     *      показываются в выпадающем списке, в котором пользователь может выбрать
     *      нужный ему элемент.
     *      После выбора элемента значение инпута меняется на значение выбранного элемента
     *
     *      Поддерживаемые события:
     *        nb-type – всплывает при вводе значения в инпут
     *        nb-select – всплывает при выборе значения из саджеста
     *        nb-keypress-enter – всплывает при нажатии на энетер и отсутвии саджеста
     */

    /*!
     * Опции инициализации саджеста
     * @description
     *     Эти опции могут быть определены в yate шаблонах при описании наноблока.
     *     Опции можно менять в рантайме через событие setOption
     *
     * @example
     *     var sug = nb.find('#mysuggest');
     *     sug.setOption({ 'source','http://mydomain.com/user/search'});
     *
     * @type {Object}
     */
    var optionsSuggest = {
        /*!
         * Истоник данных
         * @description См. http://api.jqueryui.com/autocomplete/#option-source
         *
         * @type {(String|Array|Function)}
         */
        source: null,

        /*!
         * Количество элеметов, при котором в выпадающем списке появляется скролл
         *
         * @type {Number}
         */
        countMax: 10,

        /*!
         * Тип саджеста
         * @description
         *     Указывает из какого шаблона брать верстку для элемента выпадающего списка.
         *     См. файл suggest.yate: match /[.type].item nb-suggest
         *
         * @type {String}
         */
        type: 'default',

        /*!
         * Включение или отключение выделения жирным начертанием результатов
         * матчинга в выпадающем списке.
         *
         * @type {Boolean}
         */
        highlight: false,

        /*!
         * Размер блока.
         * @description Применятся на размер элементов в выпадающем списке.
         *
         * @type {String}
         */
        size: 's',

        /*!
         * Количесвто введенных символов, после которого начинать поиск слов
         */
        minLength: 2
    };

    $.widget("ui.suggest", $.ui.autocomplete, {
        options: optionsSuggest,

        _resizeMenu: function() {
            this.menu.element.width($(this.options.position.of).outerWidth());
        },

        _renderMenu: function(ul, items) {
            var that = this;
            var html = '';

            $.each(items, function(index, item) {
                html += that._renderItem(item);
            });

            $(html).appendTo(ul);

            ul.children('li').each(function(index) {
                $(this).data("ui-autocomplete-item", items[index]);
            });
        },

        _renderItem: function(item) {
            var clone = $.extend({}, item);

            if (this.options.highlight) {
                if (typeof highlightings[this.options.type] == 'function') {
                    highlightings[this.options.type](clone, this._value());
                } else if (typeof this.options.highlight == 'function') {
                    this.options.highlight(clone, this._value());
                }
            }

            clone.labelContent = clone.label;
            delete clone.label;

            var renderData = {
                item: clone,
                type: this.options.type,
                size: this.options.size
            };

            if ($.isFunction(this.options.renderItem)) {
                return this.options.renderItem(renderData);
            } else {
                return '
' + clone.labelContent + '
';
            }
        },

        _suggest: function(items) {
            this._super(items);

            if (this.options.countMax && !this._heightMax) {
                this._heightMax = this.menu.element.children().eq(0).height() * this.options.countMax;
                this.menu.element.css({
                    'max-height': this._heightMax,
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden'
                });
            }
        },

        _value: function(value) {
            if (value) {
                this._trigger('_setvalue', null, value);
                return;
            }

            return this._super.apply(this, arguments);
        },

        search: function(value, event) {
            this._trigger('_search');

            return this._super(value, event);
        }
    });

    var highlightings = {
        'default': function(item, term) {
            var matcher = new RegExp('(' + $.ui.autocomplete.escapeRegex(term) + ')', "i");
            item.label = item.label.replace(matcher, '$1');
        },

        'username': function(item, term) {
            var matcher = new RegExp('(' + $.ui.autocomplete.escapeRegex(term) + ')', "ig");

            item.usernameHighlighted = item.username.replace(matcher, '$1');

            if (typeof item.email == 'string') {
                item.emailHighlighted = item.email.replace(matcher, '$1');
            }
        }
    };

    /*
     * ### jQuery UI Depends:
     * - jquery.ui.autocomplete.js
     * - jquery.ui.button.js
     * - jquery.ui.core.js
     * - jquery.ui.widget.js
     * - jquery.ui.position.js
     * - jquery.ui.menu.js
     */

    /*!
     * @class nb.block.Suggest
     * @augments nb.block.Base
     */
    nb.define('suggest', {

        /**
         * Init select
         * @fires 'nb-suggest_inited'
         */
        oninit: function() {
            var that = this;
            var nodeTagName = this.$node[0].tagName.toLowerCase();

            if (nodeTagName === 'input' || nodeTagName === 'textarea') {
                this.$control = this.$node;
            } else {
                this.$control = this.$node.find('input');
                this.input = nb.block(this.$node.find('.nb-input').get(0));
            }

            var source = this.$node.data('source');

            this.$control.on('keydown.nb-suggest', function(e) {
                var keyCode = $.ui.keyCode;

                if ($.inArray(e.keyCode, [keyCode.ENTER, keyCode.NUMPAD_ENTER]) !== -1) {
                    if (!this.$jUI.data().uiSuggest.menu.active) {
                        this.trigger('nb-keypress-enter', this, this.getValue());
                    }
                }
            }.bind(this));

            this.$jUI = this.$control.suggest({
                source: source,
                position: {
                    of: this.$node.get(0)
                },
                countMax: this.$node.data('countMax'),
                appendTo: this.$node.data('append-to'),
                type: this.$node.data('type'),
                size: this.$node.data('size'),
                highlight: this.$node.data('highlight'),
                minLength: this.$node.data('minLength'),
                renderItem: function(data) {
                    return yr.run(that.getYateModuleName(), data, 'nb-suggest');
                }
            });

            this.$suggest = this.$jUI.data().uiSuggest.menu.element;

            this.$suggest.addClass(this.$node.data('class-suggest'));

            this.$jUI.on('suggest_search.nb-suggest', function() {
                this.trigger('nb-type', this, this.getValue());
            }.bind(this));

            this.$jUI.on('suggest_setvalue.nb-suggest', this.onSetValueToInput.bind(this));

            this.$jUI.on('suggestselect.nb-suggest', this.onSelectValue.bind(this));

            this.trigger('nb-inited', this);
        },

        /**
         * Callback of a `suggestselect` event
         * @param {$.Event} e
         * @param {Object} item data of selected item
         * @private
         */
        onSelectValue: function(e, item) {
            this.$selected = item.item;

            this.trigger('nb-select', this, item.item);
        },

        /**
         * Callback of a `suggest_setvalue` event
         * @param {$.Event} e
         * @param {string} value
         * @private
         */
        onSetValueToInput: function(e, value) {
            if (this.input) {
                this.input.setValue(value);
            } else {
                this.$control.val(value);
            }
        },

        /**
         * Get selected item from suggest
         * @return {Object}
         */
        getSelected: function() {
            return this.$selected;
        },

        /**
         * Sets option to the jUI widget
         * http://api.jqueryui.com/autocomplete/#method-option
         * @param  {Object} option `{ name: value }` имя и значение опции
         * @fires 'nb-option-set'
         * @returns {Object} nb.block
         */
        setOption: function(option) {
            this.$jUI.suggest('option', option);
            this.trigger('nb-option-set', this);
            return this;
        },

        /**
         * Gets option of the jUI widget
         * http://api.jqueryui.com/autocomplete/#method-option
         * @param {String} option
         * @returns {String} option value
         */
        getOption: function(option) {
            return this.$jUI.suggest('option', option);
        },

        /*
         * Set new items for suggest
         * @params {Array} source New source
         * @fires 'nb-source-changed'
         * @returns {Object} nb.block
         */
        setSource: function(source) {
            this.setOption({'source': source});
            this.trigger('nb-source-set', this);
            return this;
        },

        /*
         * Get items from suggest
         * @returns {Array} source
         */
        getSource: function() {
            return this.getOption('source');
        },

        /**
         * Скрывает список предложений
         * @fires 'nb-closed'
         * @returns {Object} nb.block
         */
        close: function() {
            this.$jUI.suggest('close');
            this.trigger('nb-closed', this);
            return this;
        },

        /**
         * Disables the suggest
         * @fires 'nb-disabled'
         * @returns {Object} nb.block
         */
        disable: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.disable();
                } else {
                    this.$control.prop('disabled', true);
                }
                this.$node.addClass('_nb-is-disabled');
                this.$jUI.suggest('disable');
                this.trigger('nb-disabled', this);
            }
            return this;
        },

        /**
         * Enables the suggest
         * @fires 'nb-enabled'
         * @returns {Object} nb.block
         */
        enable: function() {
            if (!this.isEnabled()) {
                if (this.input) {
                    this.input.enable();
                } else {
                    this.$control.prop('disabled', false);
                }
                this.$node.removeClass('_nb-is-disabled');
                this.$jUI.suggest('enable');
                this.trigger('nb-enabled', this);
            }
            return this;
        },

        /**
         * Return state of the suggest
         * @returns {Boolean}
         */
        isEnabled: function() {
            return !this.$node.hasClass('_nb-is-disabled');
        },

        /**
         * Focus the suggest
         * @fires 'nb-focused'
         * @returns {Object} nb.block
         */
        focus: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.focus();
                } else {
                    this.$control.focus();
                }
            }
            this.trigger('nb-focused', this);
            return this;
        },

        /**
         * Get name of the suggest
         * @returns {String|Object} name
         */
        getName: function() {
            return this.$control.prop('name');
        },

        /**
         * Set name of the suggest
         * @param {string} name
         * @fires 'nb-name-set'
         * @returns {Object} nb.block
         */
        setName: function(name) {
            this.$control.prop('name', name);
            this.trigger('nb-name-set', this);
            return this;
        },

        /**
         * Blur the suggest
         * @fires 'nb-blured'
         * @returns {Object} nb.block
         */
        blur: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.blur();
                } else {
                    this.$control.blur();
                }
            }
            this.trigger('nb-blured', this);
            return this;
        },

        /**
         * Get current value of the suggest
         * @returns {String | Number}
         */
        getValue: function() {
            return this.$control.val();
        },

        /**
         * Get current value of the suggest
         * @param {String} value
         * @fires 'nb-value-set'
         * @returns {Object} nb.block
         */
        setValue: function(value) {
            if (this.isEnabled()) {
                this.$control.val(value);
                this.trigger('nb-value-set', this);
            }
            return this;
        },

        /**
         * Search value in the source array and open suggest popup
         * @param  {string|number} value
         * @returns {Object} nb.block
         */
        search: function(value) {
            this.$jUI.suggest("search", value);
            return this;
        },

        /**
         * Destroy the suggest
         * @fires 'nb-destroyed'
         */
        destroy: function() {
            if (this.$control && this.$jUI) {
                var jUIData = this.$jUI.data();
                this.$control.off('.nb-suggest');
                this.$jUI.off('.nb-suggest');
                if (jUIData && jUIData.uiSuggest) {
                    this.$jUI.suggest('destroy');
                    this.$control.remove();
                }

                this.$control.remove();
                this.$jUI.remove();
            }
            this.trigger('nb-destroyed', this);
            this.nbdestroy();
        }

    }, 'base');

})();
<commit_msg>Removed unneeded removals (could remove things that are shouldnt be removed)<commit_after>(function() {
    /*!
     * Саджест
     * @namespace jquery.ui.suggest
     * @extends {jquery.ui.autocomplete} http://api.jqueryui.com/autocomplete/
     * @description
     *      Саджест это блок сотоящий из инпута и выпадающего списка.
     *      При вводе какого-либо значения в инпут это значение матчится на список
     *      слов из источника данных, и подходящие элементы из исходного списка
     *      показываются в выпадающем списке, в котором пользователь может выбрать
     *      нужный ему элемент.
     *      После выбора элемента значение инпута меняется на значение выбранного элемента
     *
     *      Поддерживаемые события:
     *        nb-type – всплывает при вводе значения в инпут
     *        nb-select – всплывает при выборе значения из саджеста
     *        nb-keypress-enter – всплывает при нажатии на энетер и отсутвии саджеста
     */

    /*!
     * Опции инициализации саджеста
     * @description
     *     Эти опции могут быть определены в yate шаблонах при описании наноблока.
     *     Опции можно менять в рантайме через событие setOption
     *
     * @example
     *     var sug = nb.find('#mysuggest');
     *     sug.setOption({ 'source','http://mydomain.com/user/search'});
     *
     * @type {Object}
     */
    var optionsSuggest = {
        /*!
         * Истоник данных
         * @description См. http://api.jqueryui.com/autocomplete/#option-source
         *
         * @type {(String|Array|Function)}
         */
        source: null,

        /*!
         * Количество элеметов, при котором в выпадающем списке появляется скролл
         *
         * @type {Number}
         */
        countMax: 10,

        /*!
         * Тип саджеста
         * @description
         *     Указывает из какого шаблона брать верстку для элемента выпадающего списка.
         *     См. файл suggest.yate: match /[.type].item nb-suggest
         *
         * @type {String}
         */
        type: 'default',

        /*!
         * Включение или отключение выделения жирным начертанием результатов
         * матчинга в выпадающем списке.
         *
         * @type {Boolean}
         */
        highlight: false,

        /*!
         * Размер блока.
         * @description Применятся на размер элементов в выпадающем списке.
         *
         * @type {String}
         */
        size: 's',

        /*!
         * Количесвто введенных символов, после которого начинать поиск слов
         */
        minLength: 2
    };

    $.widget("ui.suggest", $.ui.autocomplete, {
        options: optionsSuggest,

        _resizeMenu: function() {
            this.menu.element.width($(this.options.position.of).outerWidth());
        },

        _renderMenu: function(ul, items) {
            var that = this;
            var html = '';

            $.each(items, function(index, item) {
                html += that._renderItem(item);
            });

            $(html).appendTo(ul);

            ul.children('li').each(function(index) {
                $(this).data("ui-autocomplete-item", items[index]);
            });
        },

        _renderItem: function(item) {
            var clone = $.extend({}, item);

            if (this.options.highlight) {
                if (typeof highlightings[this.options.type] == 'function') {
                    highlightings[this.options.type](clone, this._value());
                } else if (typeof this.options.highlight == 'function') {
                    this.options.highlight(clone, this._value());
                }
            }

            clone.labelContent = clone.label;
            delete clone.label;

            var renderData = {
                item: clone,
                type: this.options.type,
                size: this.options.size
            };

            if ($.isFunction(this.options.renderItem)) {
                return this.options.renderItem(renderData);
            } else {
                return '
' + clone.labelContent + '
';
            }
        },

        _suggest: function(items) {
            this._super(items);

            if (this.options.countMax && !this._heightMax) {
                this._heightMax = this.menu.element.children().eq(0).height() * this.options.countMax;
                this.menu.element.css({
                    'max-height': this._heightMax,
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden'
                });
            }
        },

        _value: function(value) {
            if (value) {
                this._trigger('_setvalue', null, value);
                return;
            }

            return this._super.apply(this, arguments);
        },

        search: function(value, event) {
            this._trigger('_search');

            return this._super(value, event);
        }
    });

    var highlightings = {
        'default': function(item, term) {
            var matcher = new RegExp('(' + $.ui.autocomplete.escapeRegex(term) + ')', "i");
            item.label = item.label.replace(matcher, '$1');
        },

        'username': function(item, term) {
            var matcher = new RegExp('(' + $.ui.autocomplete.escapeRegex(term) + ')', "ig");

            item.usernameHighlighted = item.username.replace(matcher, '$1');

            if (typeof item.email == 'string') {
                item.emailHighlighted = item.email.replace(matcher, '$1');
            }
        }
    };

    /*
     * ### jQuery UI Depends:
     * - jquery.ui.autocomplete.js
     * - jquery.ui.button.js
     * - jquery.ui.core.js
     * - jquery.ui.widget.js
     * - jquery.ui.position.js
     * - jquery.ui.menu.js
     */

    /*!
     * @class nb.block.Suggest
     * @augments nb.block.Base
     */
    nb.define('suggest', {

        /**
         * Init select
         * @fires 'nb-suggest_inited'
         */
        oninit: function() {
            var that = this;
            var nodeTagName = this.$node[0].tagName.toLowerCase();

            if (nodeTagName === 'input' || nodeTagName === 'textarea') {
                this.$control = this.$node;
            } else {
                this.$control = this.$node.find('input');
                this.input = nb.block(this.$node.find('.nb-input').get(0));
            }

            var source = this.$node.data('source');

            this.$control.on('keydown.nb-suggest', function(e) {
                var keyCode = $.ui.keyCode;

                if ($.inArray(e.keyCode, [keyCode.ENTER, keyCode.NUMPAD_ENTER]) !== -1) {
                    if (!this.$jUI.data().uiSuggest.menu.active) {
                        this.trigger('nb-keypress-enter', this, this.getValue());
                    }
                }
            }.bind(this));

            this.$jUI = this.$control.suggest({
                source: source,
                position: {
                    of: this.$node.get(0)
                },
                countMax: this.$node.data('countMax'),
                appendTo: this.$node.data('append-to'),
                type: this.$node.data('type'),
                size: this.$node.data('size'),
                highlight: this.$node.data('highlight'),
                minLength: this.$node.data('minLength'),
                renderItem: function(data) {
                    return yr.run(that.getYateModuleName(), data, 'nb-suggest');
                }
            });

            this.$suggest = this.$jUI.data().uiSuggest.menu.element;

            this.$suggest.addClass(this.$node.data('class-suggest'));

            this.$jUI.on('suggest_search.nb-suggest', function() {
                this.trigger('nb-type', this, this.getValue());
            }.bind(this));

            this.$jUI.on('suggest_setvalue.nb-suggest', this.onSetValueToInput.bind(this));

            this.$jUI.on('suggestselect.nb-suggest', this.onSelectValue.bind(this));

            this.trigger('nb-inited', this);
        },

        /**
         * Callback of a `suggestselect` event
         * @param {$.Event} e
         * @param {Object} item data of selected item
         * @private
         */
        onSelectValue: function(e, item) {
            this.$selected = item.item;

            this.trigger('nb-select', this, item.item);
        },

        /**
         * Callback of a `suggest_setvalue` event
         * @param {$.Event} e
         * @param {string} value
         * @private
         */
        onSetValueToInput: function(e, value) {
            if (this.input) {
                this.input.setValue(value);
            } else {
                this.$control.val(value);
            }
        },

        /**
         * Get selected item from suggest
         * @return {Object}
         */
        getSelected: function() {
            return this.$selected;
        },

        /**
         * Sets option to the jUI widget
         * http://api.jqueryui.com/autocomplete/#method-option
         * @param  {Object} option `{ name: value }` имя и значение опции
         * @fires 'nb-option-set'
         * @returns {Object} nb.block
         */
        setOption: function(option) {
            this.$jUI.suggest('option', option);
            this.trigger('nb-option-set', this);
            return this;
        },

        /**
         * Gets option of the jUI widget
         * http://api.jqueryui.com/autocomplete/#method-option
         * @param {String} option
         * @returns {String} option value
         */
        getOption: function(option) {
            return this.$jUI.suggest('option', option);
        },

        /*
         * Set new items for suggest
         * @params {Array} source New source
         * @fires 'nb-source-changed'
         * @returns {Object} nb.block
         */
        setSource: function(source) {
            this.setOption({'source': source});
            this.trigger('nb-source-set', this);
            return this;
        },

        /*
         * Get items from suggest
         * @returns {Array} source
         */
        getSource: function() {
            return this.getOption('source');
        },

        /**
         * Скрывает список предложений
         * @fires 'nb-closed'
         * @returns {Object} nb.block
         */
        close: function() {
            this.$jUI.suggest('close');
            this.trigger('nb-closed', this);
            return this;
        },

        /**
         * Disables the suggest
         * @fires 'nb-disabled'
         * @returns {Object} nb.block
         */
        disable: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.disable();
                } else {
                    this.$control.prop('disabled', true);
                }
                this.$node.addClass('_nb-is-disabled');
                this.$jUI.suggest('disable');
                this.trigger('nb-disabled', this);
            }
            return this;
        },

        /**
         * Enables the suggest
         * @fires 'nb-enabled'
         * @returns {Object} nb.block
         */
        enable: function() {
            if (!this.isEnabled()) {
                if (this.input) {
                    this.input.enable();
                } else {
                    this.$control.prop('disabled', false);
                }
                this.$node.removeClass('_nb-is-disabled');
                this.$jUI.suggest('enable');
                this.trigger('nb-enabled', this);
            }
            return this;
        },

        /**
         * Return state of the suggest
         * @returns {Boolean}
         */
        isEnabled: function() {
            return !this.$node.hasClass('_nb-is-disabled');
        },

        /**
         * Focus the suggest
         * @fires 'nb-focused'
         * @returns {Object} nb.block
         */
        focus: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.focus();
                } else {
                    this.$control.focus();
                }
            }
            this.trigger('nb-focused', this);
            return this;
        },

        /**
         * Get name of the suggest
         * @returns {String|Object} name
         */
        getName: function() {
            return this.$control.prop('name');
        },

        /**
         * Set name of the suggest
         * @param {string} name
         * @fires 'nb-name-set'
         * @returns {Object} nb.block
         */
        setName: function(name) {
            this.$control.prop('name', name);
            this.trigger('nb-name-set', this);
            return this;
        },

        /**
         * Blur the suggest
         * @fires 'nb-blured'
         * @returns {Object} nb.block
         */
        blur: function() {
            if (this.isEnabled()) {
                if (this.input) {
                    this.input.blur();
                } else {
                    this.$control.blur();
                }
            }
            this.trigger('nb-blured', this);
            return this;
        },

        /**
         * Get current value of the suggest
         * @returns {String | Number}
         */
        getValue: function() {
            return this.$control.val();
        },

        /**
         * Get current value of the suggest
         * @param {String} value
         * @fires 'nb-value-set'
         * @returns {Object} nb.block
         */
        setValue: function(value) {
            if (this.isEnabled()) {
                this.$control.val(value);
                this.trigger('nb-value-set', this);
            }
            return this;
        },

        /**
         * Search value in the source array and open suggest popup
         * @param  {string|number} value
         * @returns {Object} nb.block
         */
        search: function(value) {
            this.$jUI.suggest("search", value);
            return this;
        },

        /**
         * Destroy the suggest
         * @fires 'nb-destroyed'
         */
        destroy: function() {
            if (this.$control && this.$jUI) {
                var jUIData = this.$jUI.data();
                this.$control.off('.nb-suggest');
                this.$jUI.off('.nb-suggest');
                if (jUIData && jUIData.uiSuggest) {
                    this.$jUI.suggest('destroy');
                }
            }
            this.trigger('nb-destroyed', this);
            this.nbdestroy();
        }

    }, 'base');

})();
<|endoftext|>


<commit_before>var TableView = Backbone.View.extend({
  initialize: function(cards) {
    this.collection = cards;
    this.$el.className = "table-cards"
    this.listenTo(this.collection, "change", this.render);
  },

  render: function(){
    this.$el.empty();
    this.addAll();
  },

  addOne: function(card){
    var view = new CardView(card);
    view.render();
    this.$el.append(view.$el)
  },

  addAll: function(){
    this.collection.forEach(function(card) {
      this.addOne(card);
    }, this);
    return this;
  }
})<commit_msg>fix class into attributes<commit_after>var TableView = Backbone.View.extend({
  initialize: function(cards) {
    this.collection = cards;
    this.listenTo(this.collection, "change", this.render);
  },

  attributes: {
    class: "table-cards"
  },

  render: function(){
    this.$el.empty();
    this.addAll();
  },

  addOne: function(card){
    var view = new CardView(card);
    view.render();
    this.$el.append(view.$el)
  },

  addAll: function(){
    this.collection.forEach(function(card) {
      this.addOne(card);
    }, this);
    return this;
  }
})<|endoftext|>


<commit_before>//
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');

// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');

//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
    .withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
    .inDir('target/classes/io/jenkins/blueocean')
    .less('src/main/less/blueocean.less')
    .generateNoImportsBundle();

<commit_msg>Watch for changes in the JDL package (rebundle)<commit_after>//
// See https://github.com/jenkinsci/js-builder
//
var builder = require('@jenkins-cd/js-builder');

// Disable js-builder based linting for now.
// Will get fixed with https://github.com/cloudbees/blueocean/pull/55
builder.lint('none');

// Explicitly setting the src paths in order to allow the rebundle task to
// watch for changes in the JDL (js, css, icons etc).
// See https://github.com/jenkinsci/js-builder#setting-src-and-test-spec-paths
builder.src(['src/main/js', 'src/main/less', 'node_modules/@jenkins-cd/design-language']);

//
// Create the main "App" bundle.
// generateNoImportsBundle makes it easier to test with zombie.
//
builder.bundle('src/main/js/blueocean.js')
    .withExternalModuleMapping('jquery-detached', 'jquery-detached:jquery2')
    .inDir('target/classes/io/jenkins/blueocean')
    .less('src/main/less/blueocean.less')
    .generateNoImportsBundle();

<|endoftext|>


<commit_before>"use strict";
var EventDispatcher = require('../events/event-dispatcher'),
    loader = require('../loader/loader'),
    environments = require('../environments/environments'),
    inject = require('../inject/inject'),
    path = require('path'),
    fs = require('fs'),
    _ = require('lodash');

var Launcher = EventDispatcher.define({

    constructor: function () {
        this.cachedRequire = [];

    },

    launch: function (config) {

        this.loadOptions(config)

        this.loadEnvironments();

        this.loadFiles();

        this.loadInjector();

        this.fireEvent('appolo-launched');
    },

    loadOptions:function(config){

        var defaults = {
            paths:['config', 'server'],
            root : process.cwd(),
            environment : (process.env.NODE_ENV || 'development'),
            bootStrapClassId :'appolo-bootstrap',
            version: require(path.join(process.cwd(),'package.json')).version
        }

        this._options = _.extend(defaults ,config || {});

        return this._options;
    },

    loadFiles:function(){
        var loadPaths = _.union(this._options.paths, environments.paths);

        //load env files
        loader(this._options.root,loadPaths,function(filePath){
            require(filePath);
            this.cachedRequire.push(filePath);
        }.bind(this));
    },

    loadEnvironments: function () {
        var allPath = path.join(this._options.root, 'config/environments/all'),
            environmentPath = path.join(this._options.root, 'config/environments/', this._options.environment + '.js'),
            all = require(allPath),
            environment = require(environmentPath);

        this.cachedRequire.push(allPath);
        this.cachedRequire.push(environmentPath);

        //add current env config to appolo env
        _.extend(environments, all, environment || {});

        //save evn name
        environments.type = this._options.environment;

        //add root
        environments.rootDir = this._options.root;

        inject.addObject('environment', environments);
        inject.addObject('env', environments);
    },

    loadInjector: function () {
        var definitions = {},
            injectPath = path.join(this._options.root, 'config/inject');

        if (fs.existsSync(injectPath)) {

            loader(this._options.root,path.join('config', 'inject'),function(filePath){
                _.extend(definitions, require(filePath));
                this.cachedRequire.push(filePath);
            }.bind(this));
        }

        //load inject
        inject.initialize({
            definitions: definitions,
            root: this._options.root
        });

        this.loadBootStrap();

    },

    loadBootStrap:function(){
        var bootstrapDef = inject.getDefinition(this._options.bootStrapClassId);

        if(bootstrapDef){
            var bootstrap = inject.getObject(this._options.bootStrapClassId);

            bootstrap.initialize();
        }

    },

    reset:function(){
        _.forEach(this.cachedRequire,function(filePath){
            delete require.cache[filePath];
        });
        this.cachedRequire.length = 0;
        this._options = null;
        _.forEach(environments,function(value,key){
            delete environments[key];
        });

        inject.reset();

        process.removeAllListeners();
    }
});

module.exports = new Launcher();<commit_msg>new appolo<commit_after>"use strict";
var EventDispatcher = require('../events/event-dispatcher'),
    loader = require('../loader/loader'),
    environments = require('../environments/environments'),
    inject = require('../inject/inject'),
    path = require('path'),
    fs = require('fs'),
    _ = require('lodash');

var Launcher = EventDispatcher.define({

    constructor: function () {
        this.cachedRequire = [];

    },

    launch: function (config) {

        this.loadOptions(config)

        this.loadEnvironments();

        this.loadFiles();

        this.loadInjector();

        this.fireEvent('appolo-launched');
    },

    loadOptions:function(config){

        var defaults = {
            paths:['config', 'server'],
            root : process.cwd(),
            environment : (process.env.NODE_ENV || 'development'),
            bootStrapClassId :'appolo-bootstrap'

        }

        this._options = _.extend(defaults ,config || {});

        return this._options;
    },

    loadFiles:function(){
        var loadPaths = _.union(this._options.paths, environments.paths);

        //load env files
        loader(this._options.root,loadPaths,function(filePath){
            require(filePath);
            this.cachedRequire.push(filePath);
        }.bind(this));
    },

    loadEnvironments: function () {
        var allPath = path.join(this._options.root, 'config/environments/all'),
            environmentPath = path.join(this._options.root, 'config/environments/', this._options.environment + '.js'),
            all = require(allPath),
            environment = require(environmentPath);

        this.cachedRequire.push(allPath);
        this.cachedRequire.push(environmentPath);

        //add current env config to appolo env
        _.extend(environments, all, environment || {});

        //save evn name
        environments.type = this._options.environment;

        var package = require(path.join(process.cwd(),'package.json'));

        environments.version = package ?package.version : ""

        //add root
        environments.rootDir = this._options.root;

        inject.addObject('environment', environments);
        inject.addObject('env', environments);
    },

    loadInjector: function () {
        var definitions = {},
            injectPath = path.join(this._options.root, 'config/inject');

        if (fs.existsSync(injectPath)) {

            loader(this._options.root,path.join('config', 'inject'),function(filePath){
                _.extend(definitions, require(filePath));
                this.cachedRequire.push(filePath);
            }.bind(this));
        }

        //load inject
        inject.initialize({
            definitions: definitions,
            root: this._options.root
        });

        this.loadBootStrap();

    },

    loadBootStrap:function(){
        var bootstrapDef = inject.getDefinition(this._options.bootStrapClassId);

        if(bootstrapDef){
            var bootstrap = inject.getObject(this._options.bootStrapClassId);

            bootstrap.initialize();
        }

    },

    reset:function(){
        _.forEach(this.cachedRequire,function(filePath){
            delete require.cache[filePath];
        });
        this.cachedRequire.length = 0;
        this._options = null;
        _.forEach(environments,function(value,key){
            delete environments[key];
        });

        inject.reset();

        process.removeAllListeners();
    }
});

module.exports = new Launcher();<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableWithoutFeedback, Animated } from 'react-native';
import { OPEN_ANIM_DURATION, CLOSE_ANIM_DURATION } from './constants';

class Backdrop extends Component {

  constructor(...args) {
    super(...args);
    this.fadeAnim = new Animated.Value(0.001);
  }

  open() {
    return new Promise(resolve => {
      Animated.timing(this.fadeAnim, {
        duration: OPEN_ANIM_DURATION,
        toValue: 1,
        useNativeDriver: true,
      }).start(resolve);
    });
  }

  close() {
    return new Promise(resolve => {
      Animated.timing(this.fadeAnim, {
        duration: CLOSE_ANIM_DURATION,
        toValue: 0,
        useNativeDriver: true,
      }).start(resolve);
    });
  }

  render() {
    const { onPress, style } = this.props;
    return (
      <TouchableWithoutFeedback onPress={onPress}>
        <Animated.View style={[styles.fullscreen, { opacity: this.fadeAnim }]}>
          <View style={[styles.fullscreen, style]} />
        </Animated.View>
      </TouchableWithoutFeedback>
    );
  }

}

Backdrop.propTypes = {
  onPress: PropTypes.func.isRequired,
};

const styles = StyleSheet.create({
  fullscreen: {
    opacity: 0,
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});

export default Backdrop;
<commit_msg>Fix web warning about useNativeDriver<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet, TouchableWithoutFeedback, Animated, Platform } from 'react-native';
import { OPEN_ANIM_DURATION, CLOSE_ANIM_DURATION } from './constants';

class Backdrop extends Component {

  constructor(...args) {
    super(...args);
    this.fadeAnim = new Animated.Value(0.001);
  }

  open() {
    return new Promise(resolve => {
      Animated.timing(this.fadeAnim, {
        duration: OPEN_ANIM_DURATION,
        toValue: 1,
        useNativeDriver: (Platform.OS !== "web"),
      }).start(resolve);
    });
  }

  close() {
    return new Promise(resolve => {
      Animated.timing(this.fadeAnim, {
        duration: CLOSE_ANIM_DURATION,
        toValue: 0,
        useNativeDriver: (Platform.OS !== "web"),
      }).start(resolve);
    });
  }

  render() {
    const { onPress, style } = this.props;
    return (
      <TouchableWithoutFeedback onPress={onPress}>
        <Animated.View style={[styles.fullscreen, { opacity: this.fadeAnim }]}>
          <View style={[styles.fullscreen, style]} />
        </Animated.View>
      </TouchableWithoutFeedback>
    );
  }

}

Backdrop.propTypes = {
  onPress: PropTypes.func.isRequired,
};

const styles = StyleSheet.create({
  fullscreen: {
    opacity: 0,
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});

export default Backdrop;
<|endoftext|>


<commit_before>require(__dirname + '/../../app/js/entry');
require('angular-mocks');

describe('Resume Controller', function() {
  var $httpBackend;
  var $ControllerConstructor;
  var $scope;

  beforeEach(angular.mock.module('resumeApp'));

  beforeEach(angular.mock.inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    $ControllerConstructor = $controller;
  }));

  it('should be able to create a controller', function() {
    var controller = $ControllerConstructor('ResumeController', {$scope:$scope});
    expect(typeof $scope).toBe('object');
    expect(typeof controller).toBe ('object');
    expect(Array.isArray($scope.resume)).toBe(true);
  });

  describe('REST request functions', function() {
    beforeEach(angular.mock.inject(function(_$httpBackend_, $rootScope) {
      $httpBackend = _$httpBackend_;
      $scope = $rootScope.$new();
      $ControllerConstructor('ResumeController', {$scope: $scope});
    }));

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it('should make a get request when getAll() is called', function() {
      $httpBackend.expectGET('/api/resume').respond(200, [{_id: 1, firstName: 'Goldilocks', lastName: '3Bears'}]);
      $scope.getAll();
      $httpBackend.flush();
      expect($scope.resume[0].firstName).toBe('Goldilocks');
      expect($scope.resume[0].lastName).toBe('3Bears');
    });

    it('should be able to create a new resume', function() {
      //might need full schema when posting
      $httpBackend.expectPOST('/api/resume', {firstName: 'Teddy', lastName: 'Bear'}).respond(200, {firstName: 'Theodore', lastName: 'Roosevelt'});
      expect($scope.resume.length).toBe(0);
      expect($scope.newResume).toEqual($scope.defaults);
      $scope.newResume.firstName = 'Panda';
      $scope.create($scope.newResume);
      $httpBackend.flush();
      expect($scope.resume[0].firstName).toBe('Theodore');
      expect($scope.newResume).toEqual($scope.defaults);
    });

    it('should be able to update a resume', function() {
      var resume = { firstName: 'Grizz', lastName: 'Bear',_id: 1, editing: true};
      $httpBackend.expectPUT('/api/resume/1', resume).respond(200);
      $scope.updateResume(resume);
      $httpBackend.flush();
      expect(resume.editing).toBe(false);
    });

    it('should be able to delete a resume', function() {
      var resume = { firstName: 'Polar', lastName: 'Bear',_id: 1, editing: true};
      $scope.resume = [resume];
      $httpBackend.expectDELETE('/api/resume/1', resume).respond(200);
      expect($scope.resume.length).toBe(0);
      expect($scope.resume.indexOf(resume)).toBe(-1);
    });

  });
})

<commit_msg>got dummy controller test to pass<commit_after>require(__dirname + '/../../app/js/entry');
require('angular-mocks');

describe('Resume Controller', function() {
  var $httpBackend;
  var $ControllerConstructor;
  var $scope;

  beforeEach(angular.mock.module('resumeApp'));

  beforeEach(angular.mock.inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    $ControllerConstructor = $controller;
  }));

  it('should be able to create a controller', function() {
    var controller = $ControllerConstructor('ResumeController', {$scope:$scope});
    expect(typeof $scope).toBe('object');
    expect(typeof controller).toBe ('object');
    expect(Array.isArray($scope.resumes)).toBe(true);
  });

  describe('REST request functions', function() {
    beforeEach(angular.mock.inject(function(_$httpBackend_, $rootScope) {
      $httpBackend = _$httpBackend_;
      $scope = $rootScope.$new();
      $ControllerConstructor('ResumeController', {$scope: $scope});
    }));

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it('should make a get request when getAll() is called', function() {
      $httpBackend.expectGET('/api/resumes').respond(200, [{_id: 1, firstName: 'Goldilocks', lastName: '3Bears'}]);
      $scope.getAll();
      $httpBackend.flush();
      expect($scope.resume[0].firstName).toBe('Goldilocks');
      expect($scope.resume[0].lastName).toBe('3Bears');
    });

    it('should be able to create a new resume', function() {
      //might need full schema when posting
      $httpBackend.expectPOST('/api/resumes', {firstName: 'Teddy', lastName: 'Bear'}).respond(200, {firstName: 'Theodore', lastName: 'Roosevelt'});
      expect($scope.resume.length).toBe(0);
      expect($scope.newResume).toEqual($scope.defaults);
      $scope.newResume.firstName = 'Panda';
      $scope.create($scope.newResume);
      $httpBackend.flush();
      expect($scope.resume[0].firstName).toBe('Theodore');
      expect($scope.newResume).toEqual($scope.defaults);
    });

    it('should be able to update a resume', function() {
      var resume = { firstName: 'Grizz', lastName: 'Bear',_id: 1, editing: true};
      $httpBackend.expectPUT('/api/resumes/1', resume).respond(200);
      $scope.updateResume(resume);
      $httpBackend.flush();
      expect(resume.editing).toBe(false);
    });

    it('should be able to delete a resume', function() {
      var resume = { firstName: 'Polar', lastName: 'Bear',_id: 1, editing: true};
      $scope.resume = [resume];
      $httpBackend.expectDELETE('/api/resumes/1', resume).respond(200);
      expect($scope.resume.length).toBe(0);
      expect($scope.resume.indexOf(resume)).toBe(-1);
    });

  });
})

<|endoftext|>


<commit_before>enyo.kind({
        name: "Ares.ErrorPopup",
        kind: "onyx.Popup",
        modal: true,
        centered: true,
        floating: true,
        published: {
        	errorMsg: "unknown error",
		details: ""
        },
        components: [
                {tag: "h3", content: "Oh, no!?"},
                {name: "msg"},
                {tag: "br"},
                {name: "okButton", kind: "onyx.Button", classes: "onyx-affirmative", content: "Ok", ontap: "hideErrorPopup"},
                {name: "detailsBtn", kind: "onyx.Button", content: "Details...", ontap: "toggleDetails", showing: false},
                {tag: "br"},
		{name: "detailsDrw", kind: "onyx.Drawer", open: false, showing:false, components: [
			{name: "detailsTxt", kind: "onyx.TextArea", disabled: true, fit:true, classes:"ajax-sample-source"}
		]}
        ],
        create: function() {
                this.inherited(arguments);
        },
        errorMsgChanged: function (oldVal) {
        	this.$.msg.setContent(this.errorMsg);
        },
	detailsChanged: function(oldVal) {
		if (this.details) {
			this.$.detailsBtn.show();
			this.$.detailsDrw.show();
			this.$.detailsDrw.setOpen(false);
			this.$.detailsTxt.setValue(this.details);
		} else {
			this.$.detailsBtn.hide();
			this.$.detailsDrw.hide();
			this.$.detailsTxt.setValue("");
		}
	},
	toggleDetails: function() {
		this.$.detailsDrw.setOpen(!this.$.detailsDrw.open);
	},
        hideErrorPopup: function(inSender, inEvent) {
		this.setErrorMsg();
		this.setDetails();
                this.hide();
        },
        raise: function(msg) {
			this.setErrorMsg(msg);
			this.show();
		}
});
<commit_msg>ENYO-1224: Fix Ares.ErrorPopup<commit_after>enyo.kind({
        name: "Ares.ErrorPopup",
        kind: "onyx.Popup",
        modal: true,
        centered: true,
        floating: true,
        published: {
		errorMsg: "unknown error",
		details: ""
        },
        components: [
                {tag: "h3", content: "Oh, no!?"},
                {name: "msg"},
                {tag: "br"},
                {name: "okButton", kind: "onyx.Button", classes: "onyx-affirmative", content: "Ok", ontap: "hideErrorPopup"},
                {name: "detailsBtn", kind: "onyx.Button", content: "Details...", ontap: "toggleDetails", showing: false},
                {tag: "br"},
		{name: "detailsDrw", kind: "onyx.Drawer", open: false, showing:false, components: [
			{name: "detailsTxt", kind: "onyx.TextArea", disabled: true, fit:true, classes:"ajax-sample-source"}
		]}
        ],
        create: function() {
                this.inherited(arguments);
        },
        errorMsgChanged: function (oldVal) {
		this.$.msg.setContent(this.errorMsg);
        },
	detailsChanged: function(oldVal) {
		if (this.details) {
			this.$.detailsBtn.show();
			this.$.detailsDrw.show();
			this.$.detailsDrw.setOpen(false);
			this.$.detailsTxt.setValue(this.details);
		} else {
			this.$.detailsBtn.hide();
			this.$.detailsDrw.hide();
			this.$.detailsTxt.setValue("");
		}
	},
	toggleDetails: function() {
		this.$.detailsDrw.setOpen(!this.$.detailsDrw.open);
	},
        hideErrorPopup: function(inSender, inEvent) {
		this.setErrorMsg();
		this.setDetails();
                this.hide();
        },
        raise: function(msg, details) {
		this.setErrorMsg(msg);
		this.setDetails(details);
		this.show();
	}
});
<|endoftext|>


<commit_before>//= require admin/spree_core
<commit_msg>Specify jquery dependencies inside admin/all.js template<commit_after>//= require jquery
//= require jquery_ujs
//= require admin/spree_core
//= require_tree .

<|endoftext|>