<commit_before>'use strict';

var raven      = require('raven'),
    newWinston = new require('winston').Logger()

var LumberJack = function (sentry, winston, options) {

    this.sentry = new raven.Client(sentry, {logger: 'LumberJack'});

    if(winston === undefined) {
        this.winston = newWinston;
    }else{
        this.winston = winston;
    }

    this.options = options;

    if(this.options.logFile !== undefined) {
        this.winston.add(newWinston.transports.File, {filename: this.options.logFile});
    }

    if(this.options.prefix !== undefined) {
        this.winston.remove(newWinston.transports.Console);
        this.winston.add(newWinston.transports.Console, {
            json : false,
            timestamp : this.options.timestamp,
            label: this.options.prefix
        });
    }
};

LumberJack.prototype.info = function (message, extra) {
  this.log('info', message, extra);
};

LumberJack.prototype.debug = function (message, extra) {
  this.log('debug', message, extra);
};

LumberJack.prototype.warn = function (message, extra) {
  this.log('warn', message, extra);
};

LumberJack.prototype.error = function (message, extra) {
  this.log('error', message, extra);
};

LumberJack.prototype.getWinston = function() {
    return this.winston;
};

LumberJack.prototype.getSentry = function() {
    return this.sentry;
};

LumberJack.prototype.log = function(logLevel, message, extra) {
  if(typeof message !== 'string')
      return new Error('LumberJack: Failed to use non-string object for log message.');

  var color           = 'grey',
      winstonLogLevel = logLevel;

  if(this.options.colors === true) {
    switch (logLevel) {
        case 'info':
            color = 'green';
        break;

        case 'log':
            color = 'green';
        break;

        case 'debug':
            color = 'cyan';
        break;

        case 'warn':
            color = 'yellow';
        break;

        case 'error':
            color = 'red';
        break;

        default:
            color = 'grey';
        break;
    }
  }

  if(logLevel === 'debug')
      winstonLogLevel = 'info';

  if(this.winston !== undefined)
        this.winston.log(winstonLogLevel, message[color]);
  if(this.sentry !== undefined)
        if(logLevel === 'error')
            this.sentry.captureError(new Error(message), {level: logLevel, extra: extra});
        else
            this.sentry.captureMessage(message, {level: logLevel, extra: extra});
};

module.exports = LumberJack;<commit_msg>Fixed winston issues<commit_after>'use strict';

var raven      = require('raven'),
    winston    = require('winston');

var LumberJack = function (sentry, suppliedWinston, options) {

    this.sentry = new raven.Client(sentry, {logger: 'LumberJack'});

    if(suppliedWinston === undefined) {
        this.winston = new (winston.Logger);
    }else{
        this.winston = suppliedWinston;
    }

    this.options = options;

    if(this.options.logFile !== undefined) {
        this.winston.add(winston.transports.File, {filename: this.options.logFile});
    }

    if(this.options.prefix !== undefined) {
        this.winston.add(winston.transports.Console, {
            json : false,
            timestamp : this.options.timestamp,
            label: this.options.prefix
        });
    }
};

LumberJack.prototype.info = function (message, extra) {
  this.log('info', message, extra);
};

LumberJack.prototype.debug = function (message, extra) {
  this.log('debug', message, extra);
};

LumberJack.prototype.warn = function (message, extra) {
  this.log('warn', message, extra);
};

LumberJack.prototype.error = function (message, extra) {
  this.log('error', message, extra);
};

LumberJack.prototype.getWinston = function() {
    return this.winston;
};

LumberJack.prototype.getSentry = function() {
    return this.sentry;
};

LumberJack.prototype.log = function(logLevel, message, extra) {
  if(typeof message !== 'string')
      return new Error('LumberJack: Failed to use non-string object for log message.');

  var color           = 'grey',
      winstonLogLevel = logLevel;

  if(this.options.colors === true) {
    switch (logLevel) {
        case 'info':
            color = 'green';
        break;

        case 'log':
            color = 'green';
        break;

        case 'debug':
            color = 'cyan';
        break;

        case 'warn':
            color = 'yellow';
        break;

        case 'error':
            color = 'red';
        break;

        default:
            color = 'grey';
        break;
    }
  }

  if(logLevel === 'debug')
      winstonLogLevel = 'info';

  if(this.winston !== undefined)
        this.winston.log(winstonLogLevel, message[color]);
  if(this.sentry !== undefined)
        if(logLevel === 'error')
            this.sentry.captureError(new Error(message), {level: logLevel, extra: extra});
        else
            this.sentry.captureMessage(message, {level: logLevel, extra: extra});
};

module.exports = LumberJack;<|endoftext|>


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

    /** @namespace oui5lib.configuration */
    const configuration = oui5lib.namespace("configuration");

    /**
     * Get the componentId from the configuration.
     */
    function getComponentId() {
        return getConfigData().componentId;
    }

    /**
     * Get Component.
     * @memberof oui5lib.configuration
     * @returns The Component by the configured ID. Returns undefined if such a Components does not exist. Returns null if the componentId parameter has not been specified in the configuration.
     */
    function getComponent() {
        const componentId = getComponentId();
        if (typeof componentId === "string") {
            return sap.ui.getCore().getComponent(componentId);
        }
        return null;
    }

    /**
     * Get the availableLanguages property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {Array} The available languages. Returns undefined if not set.
     */
    function getAvailableLanguages() {
        return getConfigData().availableLanguages;
    }

    /**
     * Get the logLevel property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The logLevel. Returns WARN if not set.
     */
    function getLogLevel() {
        const config = getConfigData();
        if (config === null || typeof config.logLevel === "undefined") {
            return "WARN";
        }
        return config.logLevel;
    }

    /**
     * Get the defaultLanguage property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The default language. Returns undefined if not set.
     */
    function getDefaultLanguage() {
        return getConfigData().defaultLanguage;
    }

    /**
     * Get the current language.
     * @memberof oui5lib.configuration
     * @returns {string} The current language. Returns the defaultLanguage if not set.
     */
    function getCurrentLanguage() {
        const config = getConfigData();
        if (typeof config.currentLanguage === "undefined") {
            return config.defaultLanguage;
        }
        return config.currentLanguage;
    }

    /**
     * Set the current language.
     * @memberof oui5lib.configuration
     * @param {string} sLanguage
     */
    function setCurrentLanguage(sLanguage) {
        const config = getConfigData();

        const availableLanguages = config.availableLanguages;
        if (availableLanguages.indexOf(sLanguage) === -1) {
            sLanguage = config.defaultLanguage;
        }

        setLanguageModel(sLanguage);

        const ui5Configuration = sap.ui.getCore().getConfiguration();
        ui5Configuration.setLanguage(sLanguage);
        config.currentLanguage = sLanguage;
    }

    /**
     * Set the language model to the component under the name 'i18n'. Will load oui5lib properties and enhance it with 'i18n/i18n.properties'.
     * @memberof oui5lib.configuration
     * @param {string} sLanguage
     */
    function setLanguageModel(sLanguage) {
        // set i18n model
        const i18nModel = new sap.ui.model.resource.ResourceModel({
            bundleUrl: "oui5lib/i18n/i18n.properties",
            bundleLocale: sLanguage
        });
        i18nModel.enhance({
            bundleUrl: "i18n/i18n.properties",
            bundleLocale: sLanguage
        });
        const component = getComponent();
        if (typeof component.setModel === "function") {
            component.setModel(i18nModel, "i18n");
        }
    }

    /**
     * Get the mappingDirectory property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The mapping folder. Returns undefined if not set.
     */
    function getMappingDir() {
        return getConfigData().mappingDirectory;
    }

    function getEnvironment() {
        const config = getConfigData();
        if (config.environment === undefined) {
            return "production";
        }
        return config.environment;
    }

    function getUserProfileUrl() {
        const userProfileUrl = getConfigData("userProfileUrl");
        if (userProfileUrl === "undefined") {
            return null;
        }
        return userProfileUrl;
    }

    const _defaultDateTimePatterns = {
        dateTime: "YYYY-MM-dd HH:mm:ss",
        date: "YYYY-MM-dd",
        time: "HH:mm:ss"
    };

    function getDateTimeValuePattern(type) {
        if (_defaultDateTimePatterns.hasOwnProperty(type)) {
            const config = getConfigData();
            if (typeof config.defaultFormats === "object" &&
                typeof config.defaultFormats[type] === "string") {
                return  config.defaultFormats[type];
            }
            return _defaultDateTimePatterns[type];
        }
        return undefined;
    }

    /**
     * @param {string} type Possible values: "dateTime", "date", "time".
     * @param {string} style Possible values: "short", "medium", "long", "full".
     */
    function getDateTimeDisplayPattern(type, style) {
        const ui5Locale = new sap.ui.core.Locale(getCurrentLanguage());
        const ui5LocaleData = new sap.ui.core.LocaleData(ui5Locale);
        switch (type) {
        case "dateTime": {
            let pattern = ui5LocaleData.getDateTimePattern(style);
            pattern = pattern.replace(/'/g, "");
            pattern = pattern.replace("{1}", ui5LocaleData.getDatePattern(style));
            pattern = pattern.replace("{0}", ui5LocaleData.getTimePattern(style));
            return pattern;
        }
        case "date":
            return ui5LocaleData.getDatePattern(style);
        case "time":
            return ui5LocaleData.getTimePattern(style);
        default:
            return undefined;
        }
    }

    /**
     * Get the regular expression string from the configuration.
     * @memberof oui5lib.configuration
     * @param {string} type
     * @returns {RegExp}
     */
    function getValidationRegex(type) {
        const config = getConfigData();
        if (typeof config.validation === "undefined") {
            return null;
        }

        if (typeof config.validation[type + "Regex"] === "string") {
            return new RegExp(config.validation[type + "Regex"]);
        }
        return null;
    }

    const _dateRegex = /^\d{4}-\d{2}-\d{2}$/,
          _timeRegex = /^\d{2}:\d{2}:\d{2}$/,
          _phoneRegex = /^0{2}[1-9][\d]*$/,
          _emailRegex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

    function getDateRegex() {
        const customRegex = getValidationRegex("date");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _dateRegex;
    }

    function getTimeRegex() {
        const customRegex = getValidationRegex("time");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _timeRegex;
    }

    function getPhoneRegex() {
        const customRegex = getValidationRegex("phone");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _phoneRegex;
    }

    function getEmailRegex() {
        const customRegex = getValidationRegex("email");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _emailRegex;
    }

    /**
     * Get config data. Loads configuration file, if necessary.
     * @memberof oui5lib.configuration
     * @returns {object} The config data
     */
    function getConfigData() {
        if (typeof oui5lib.config === "undefined") {
            throw new Error("oui5lib needs configuration");
        }
        return oui5lib.config;
    }

    configuration.getAvailableLanguages = getAvailableLanguages;
    configuration.getDefaultLanguage = getDefaultLanguage;
    configuration.getCurrentLanguage = getCurrentLanguage;
    configuration.setCurrentLanguage = setCurrentLanguage;

    configuration.getLogLevel = getLogLevel;
    configuration.getMappingDir = getMappingDir;
    configuration.getEnvironment = getEnvironment;

    configuration.getDateRegex = getDateRegex;
    configuration.getTimeRegex = getTimeRegex;
    configuration.getPhoneRegex = getPhoneRegex;
    configuration.getEmailRegex = getEmailRegex;

    configuration.getDateTimeValuePattern = getDateTimeValuePattern;
    configuration.getDateTimeDisplayPattern = getDateTimeDisplayPattern;

    configuration.getComponent = getComponent;
    configuration.getUserProfileUrl = getUserProfileUrl;
}());
<commit_msg>date pattern fixed<commit_after>(function() {
    "use strict";

    /** @namespace oui5lib.configuration */
    const configuration = oui5lib.namespace("configuration");

    /**
     * Get the componentId from the configuration.
     */
    function getComponentId() {
        return getConfigData().componentId;
    }

    /**
     * Get Component.
     * @memberof oui5lib.configuration
     * @returns The Component by the configured ID. Returns undefined if such a Components does not exist. Returns null if the componentId parameter has not been specified in the configuration.
     */
    function getComponent() {
        const componentId = getComponentId();
        if (typeof componentId === "string") {
            return sap.ui.getCore().getComponent(componentId);
        }
        return null;
    }

    /**
     * Get the availableLanguages property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {Array} The available languages. Returns undefined if not set.
     */
    function getAvailableLanguages() {
        return getConfigData().availableLanguages;
    }

    /**
     * Get the logLevel property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The logLevel. Returns WARN if not set.
     */
    function getLogLevel() {
        const config = getConfigData();
        if (config === null || typeof config.logLevel === "undefined") {
            return "WARN";
        }
        return config.logLevel;
    }

    /**
     * Get the defaultLanguage property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The default language. Returns undefined if not set.
     */
    function getDefaultLanguage() {
        return getConfigData().defaultLanguage;
    }

    /**
     * Get the current language.
     * @memberof oui5lib.configuration
     * @returns {string} The current language. Returns the defaultLanguage if not set.
     */
    function getCurrentLanguage() {
        const config = getConfigData();
        if (typeof config.currentLanguage === "undefined") {
            return config.defaultLanguage;
        }
        return config.currentLanguage;
    }

    /**
     * Set the current language.
     * @memberof oui5lib.configuration
     * @param {string} sLanguage
     */
    function setCurrentLanguage(sLanguage) {
        const config = getConfigData();

        const availableLanguages = config.availableLanguages;
        if (availableLanguages.indexOf(sLanguage) === -1) {
            sLanguage = config.defaultLanguage;
        }

        setLanguageModel(sLanguage);

        const ui5Configuration = sap.ui.getCore().getConfiguration();
        ui5Configuration.setLanguage(sLanguage);
        config.currentLanguage = sLanguage;
    }

    /**
     * Set the language model to the component under the name 'i18n'. Will load oui5lib properties and enhance it with 'i18n/i18n.properties'.
     * @memberof oui5lib.configuration
     * @param {string} sLanguage
     */
    function setLanguageModel(sLanguage) {
        // set i18n model
        const i18nModel = new sap.ui.model.resource.ResourceModel({
            bundleUrl: "oui5lib/i18n/i18n.properties",
            bundleLocale: sLanguage
        });
        i18nModel.enhance({
            bundleUrl: "i18n/i18n.properties",
            bundleLocale: sLanguage
        });
        const component = getComponent();
        if (typeof component.setModel === "function") {
            component.setModel(i18nModel, "i18n");
        }
    }

    /**
     * Get the mappingDirectory property from the configuration.
     * @memberof oui5lib.configuration
     * @returns {string} The mapping folder. Returns undefined if not set.
     */
    function getMappingDir() {
        return getConfigData().mappingDirectory;
    }

    function getEnvironment() {
        const config = getConfigData();
        if (config.environment === undefined) {
            return "production";
        }
        return config.environment;
    }

    function getUserProfileUrl() {
        const userProfileUrl = getConfigData("userProfileUrl");
        if (userProfileUrl === "undefined") {
            return null;
        }
        return userProfileUrl;
    }

    const _defaultDateTimePatterns = {
        dateTime: "yyyy-MM-dd HH:mm:ss",
        date: "yyyy-MM-dd",
        time: "HH:mm:ss"
    };

    function getDateTimeValuePattern(type) {
        if (_defaultDateTimePatterns.hasOwnProperty(type)) {
            const config = getConfigData();
            if (typeof config.defaultFormats === "object" &&
                typeof config.defaultFormats[type] === "string") {
                return  config.defaultFormats[type];
            }
            return _defaultDateTimePatterns[type];
        }
        return undefined;
    }

    /**
     * @param {string} type Possible values: "dateTime", "date", "time".
     * @param {string} style Possible values: "short", "medium", "long", "full".
     */
    function getDateTimeDisplayPattern(type, style) {
        const ui5Locale = new sap.ui.core.Locale(getCurrentLanguage());
        const ui5LocaleData = new sap.ui.core.LocaleData(ui5Locale);
        switch (type) {
        case "dateTime": {
            let pattern = ui5LocaleData.getDateTimePattern(style);
            pattern = pattern.replace(/'/g, "");
            pattern = pattern.replace("{1}", ui5LocaleData.getDatePattern(style));
            pattern = pattern.replace("{0}", ui5LocaleData.getTimePattern(style));
            return pattern;
        }
        case "date":
            return ui5LocaleData.getDatePattern(style);
        case "time":
            return ui5LocaleData.getTimePattern(style);
        default:
            return undefined;
        }
    }

    /**
     * Get the regular expression string from the configuration.
     * @memberof oui5lib.configuration
     * @param {string} type
     * @returns {RegExp}
     */
    function getValidationRegex(type) {
        const config = getConfigData();
        if (typeof config.validation === "undefined") {
            return null;
        }

        if (typeof config.validation[type + "Regex"] === "string") {
            return new RegExp(config.validation[type + "Regex"]);
        }
        return null;
    }

    const _dateRegex = /^\d{4}-\d{2}-\d{2}$/,
          _timeRegex = /^\d{2}:\d{2}:\d{2}$/,
          _phoneRegex = /^0{2}[1-9][\d]*$/,
          _emailRegex = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

    function getDateRegex() {
        const customRegex = getValidationRegex("date");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _dateRegex;
    }

    function getTimeRegex() {
        const customRegex = getValidationRegex("time");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _timeRegex;
    }

    function getPhoneRegex() {
        const customRegex = getValidationRegex("phone");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _phoneRegex;
    }

    function getEmailRegex() {
        const customRegex = getValidationRegex("email");
        if (customRegex !== null &&
            customRegex instanceof RegExp) {
            return customRegex;
        }
        return _emailRegex;
    }

    /**
     * Get config data. Loads configuration file, if necessary.
     * @memberof oui5lib.configuration
     * @returns {object} The config data
     */
    function getConfigData() {
        if (typeof oui5lib.config === "undefined") {
            throw new Error("oui5lib needs configuration");
        }
        return oui5lib.config;
    }

    configuration.getAvailableLanguages = getAvailableLanguages;
    configuration.getDefaultLanguage = getDefaultLanguage;
    configuration.getCurrentLanguage = getCurrentLanguage;
    configuration.setCurrentLanguage = setCurrentLanguage;

    configuration.getLogLevel = getLogLevel;
    configuration.getMappingDir = getMappingDir;
    configuration.getEnvironment = getEnvironment;

    configuration.getDateRegex = getDateRegex;
    configuration.getTimeRegex = getTimeRegex;
    configuration.getPhoneRegex = getPhoneRegex;
    configuration.getEmailRegex = getEmailRegex;

    configuration.getDateTimeValuePattern = getDateTimeValuePattern;
    configuration.getDateTimeDisplayPattern = getDateTimeDisplayPattern;

    configuration.getComponent = getComponent;
    configuration.getUserProfileUrl = getUserProfileUrl;
}());
<|endoftext|>


<commit_before>import gulp from 'gulp'
import zip from 'gulp-zip'

const TASK_NAME = 'package'

function packageTask () {
  gulp.autoRegister(TASK_NAME, config => {
    return gulp.src(config.src)
      .pipe(zip(config.options.filename))
      .pipe(gulp.dest(config.dest))
  })
}

gulp.task(TASK_NAME, packageTask)

export default packageTask
<commit_msg>log npm package<commit_after>import gulp from 'gulp'
import zip from 'gulp-zip'

const TASK_NAME = 'package'

function packageTask () {
  let counter = 1
  gulp.autoRegister(TASK_NAME, config => {
    console.log('Iteration: ', counter)
    console.log('=============================\n')
    console.log('config.src: ', config.src)
    console.log('=============================\n')
    console.log('config.options.filename: ', config.options.filename)
    console.log('=============================\n')
    console.log('config.dest: ', config.dest)
    console.log('=============================')
    return gulp.src(config.src)
      .pipe(zip(config.options.filename))
      .pipe(gulp.dest(config.dest))
  })
}
console.log('Running TASK_NAME:', TASK_NAME)
console.log('\n')
console.log('packageTask', packageTask)
console.log('\n')
console.log('=============================')
gulp.task(TASK_NAME, packageTask)

export default packageTask
<|endoftext|>


<commit_before>/*
Mag.JS AddOns v0.10.2
(c) Michael Glazer
https://github.com/magnumjs/mag.js
*/
mag.addons = {};
// helper function for non proxy supported browser i.e. NOT firefox
// state.fom = mag.addons.binds(state)
mag.addons.binds = function(data, attachTo, callback) {
  var oldVal,handler = function(e) {

    var val = e.target.type == 'checkbox' ? e.target.checked : e.target.value
    if (val === oldVal) return

    oldVal = val;

    var name = e.target.name
    if (data[name] && data[name].type == 'fun' && typeof data[name] == 'function') {
        data[name](val)
    } else if(name) {
      //necessary ?
      if(data[name] && typeof data[name]._text !=='undefined')
        data[name]._text=val
      else
        data[name]=val
    }

    if(typeof Object.observe !== 'undefined'){
      Object.observe(data, function(changes) {
        // update target with changes
        changes.forEach(function(change) {
          if (change.type == 'update' || change.type == 'add') {
              // update the related dom
            if (e.target.name == change.name && e.target.value!==change.object[change.name])
                e.target.value = change.object[change.name]
          }
        })
      })
    }
    if (callback && typeof callback == 'function') callback()
  }
  var addThis = {}

  var events = ['_onchange', '_oninput']
  for (var k in events) addThis[events[k]] = handler

  addThis['_config'] = function(node, isNew) {
    for (var j in data) {
        if (j) {
          if(document.querySelector('[name="' + j + '"]')){
            document.querySelector('[name="' + j + '"]').value=data[j]
            //Why is this necesary?
            //if(isNew){document.querySelector('[name="' + j + '"]').click()}
        }
      }
    }
  }

  if (attachTo) mag.addons.merge(addThis, attachTo)

  return addThis
}

// simple bind to keyup event
// mag.addons.change(state, state.form={})
// state.form = mag.addons.change(state)
mag.addons.change=function(data, addTo){
  var src = {
    _onkeyup : function(e){
      data[e.target.name](e.target.value)
    }
  }
  if(addTo){
    return mag.addons.merge(src, addTo)
  }
  return src
}

// BINDS
// this is the context which should be the 'state'
//  mag.addons.bindEvent.call(state, 'input', 'keyup', props.model.name)

mag.addons.bindEvent = function(field, event, model) {
  var src = {}
  src._value = model()
  src['_on' + event] = mag.withProp('value', model)

  mag.addons.merge(src, this[field] = {});
}

// bind methods from a model to a controller instance
//  mag.addons.bindToModel(this, Todo)
mag.addons.bindToModel = function(context, model) {
  for (var meth in model) {
    context[meth] = model[meth].bind(context)
  }
}

//UTILITY
mag.addons.copy =function (o) {
   var out, v, key;
   out = Array.isArray(o) ? [] : {};
   for (key in o) {
       v = o[key];
       out[key] = (typeof v === "object") ? mag.addons.copy(v) : v;
   }
   return out;
}

mag.addons.merge = function(source, destination) {
    for (var k in source) destination[k] = source[k]
}

// return object of getter values
mag.addons.getProp = function(data) {
    var newData = {}
    Object.keys(data).forEach(function(k) {
        if (data[k].type == 'fun' && typeof data[k] == 'function') newData[k] = data[k]()
    })
    return newData
}

// show hide

// remove class hide to given context/this
// show(this) inside controller
mag.addons.show = function(condition) {
  if (typeof condition === 'boolean') {
    return {
      _config: function(n) {
        if (!condition) n.style.display = 'none';
        else n.style.display = 'block';
      }
    };
  } else if(typeof condition === 'object') {
    condition.didload = function(e, n) {
      n.classList.remove('hide')
      // both or just if no class hide ..
      //node.style.display = 'none'
    }
  } else if (arguments.length == 0){
    return function(e, n) {
      // next didupdate event
      n.style.display = 'block'
    }
  }
}

mag.addons.hide = function(condition) {
  if (typeof condition === 'boolean') {
    return {
      _config: function(n) {
          if (condition) n.style.display = 'none';
      }
    }
  } else if(arguments.length == 0){
    return function(e, n) {
      // next didupdate event
      n.style.display = 'none'
    }
  }
}

// life cycle event helpers

mag.addons.onNextUpdate = function(context, callback) {
  context.didupdate = function(event, node) {
    return callback.call(context, event, node)
  }
}

// promises
mag.deferred = Deferred = function() {
  return function Deferred(resolve, reject) {
    Deferred.resolve = resolve
    Deferred.reject = reject
  }
}

mag.addons.when = function(arrayOfPromises, callback) {
    Promise.all(arrayOfPromises).then(callback)
}

mag.addons.requestWithFeedback = function(args) {
  var key = JSON.stringify(args)
  if (!mag.addons.requestWithFeedback.cache[key]) {

    var loaders = document.querySelectorAll(".loader")

    //show icons
    for (var i = 0, loader; loader = loaders[i]; i++) loader.style.display = "block"

    var expire = function(data) {
      delete mag.addons.requestWithFeedback.cache[key]

      if (Object.keys(mag.addons.requestWithFeedback.cache).length == 0) {
          //hide icons
          for (var i = 0, loader; loader = loaders[i]; i++) loader.style.display = "none"
      }
      return data
    }
    mag.addons.requestWithFeedback.cache[key] = mag.request(args).then(expire, function(error) {
      expire(error)
      throw error
    })
  }
  return mag.addons.requestWithFeedback.cache[key]
}
mag.addons.requestWithFeedback.cache = {}

// hookins

mag.hookin('attributes', 'key', function(data) {
    // remove system key from being added to attributes in html
  //  data.value = null
})

mag.hookin('attributes', 'className', function(data) {
  var newClass = data.value
  data.value = data.node.classList + ''
  if (!data.node.classList.contains(newClass)) {
    data.value = data.node.classList.length > 0 ? data.node.classList + ' ' + newClass : newClass
  }
    data.key = 'class'
})
<commit_msg>Update mag.addons.js<commit_after>/*
Mag.JS AddOns v0.10.2
(c) Michael Glazer
https://github.com/magnumjs/mag.js
*/
mag.addons = {};
// helper function for non proxy supported browser i.e. NOT firefox
// state.fom = mag.addons.binds(state)
mag.addons.binds = function(data, attachTo, callback) {
  var oldVal,handler = function(e) {

    var val = e.target.type == 'checkbox' ? e.target.checked : e.target.value
    if (val === oldVal) return

    oldVal = val;

    var name = e.target.name
    if (data[name] && data[name].type == 'fun' && typeof data[name] == 'function') {
        data[name](val)
    } else if(name) {
      //necessary ?
      if(data[name] && typeof data[name]._text !=='undefined')
        data[name]._text=val
      else
        data[name]=val
    }

    if(typeof Object.observe !== 'undefined'){
      Object.observe(data, function(changes) {
        // update target with changes
        changes.forEach(function(change) {
          if (change.type == 'update' || change.type == 'add') {
              // update the related dom
            if (e.target.name == change.name && e.target.value!==change.object[change.name])
                e.target.value = change.object[change.name]
          }
        })
      })
    }
    if (callback && typeof callback == 'function') callback()
  }
  var addThis = {}

  var events = ['_onclick','_onchange', '_oninput']
  for (var k in events) addThis[events[k]] = handler

  addThis['_config'] = function(node, isNew) {
    for (var j in data) {
      if(j && isNew && document.querySelector('[name="' + j + '"]')){
            //Why is this necesary?
        document.querySelector('[name="' + j + '"]').click()
      }
    }
  }

  if (attachTo) mag.addons.merge(addThis, attachTo)

  return addThis
}

// simple bind to keyup event
// mag.addons.change(state, state.form={})
// state.form = mag.addons.change(state)
mag.addons.change=function(data, addTo){
  var src = {
    _onkeyup : function(e){
      data[e.target.name](e.target.value)
    }
  }
  if(addTo){
    return mag.addons.merge(src, addTo)
  }
  return src
}

// BINDS
// this is the context which should be the 'state'
//  mag.addons.bindEvent.call(state, 'input', 'keyup', props.model.name)

mag.addons.bindEvent = function(field, event, model) {
  var src = {}
  src._value = model()
  src['_on' + event] = mag.withProp('value', model)

  mag.addons.merge(src, this[field] = {});
}

// bind methods from a model to a controller instance
//  mag.addons.bindToModel(this, Todo)
mag.addons.bindToModel = function(context, model) {
  for (var meth in model) {
    context[meth] = model[meth].bind(context)
  }
}

//UTILITY
mag.addons.copy =function (o) {
   var out, v, key;
   out = Array.isArray(o) ? [] : {};
   for (key in o) {
       v = o[key];
       out[key] = (typeof v === "object") ? mag.addons.copy(v) : v;
   }
   return out;
}

mag.addons.merge = function(source, destination) {
    for (var k in source) destination[k] = source[k]
}

// return object of getter values
mag.addons.getProp = function(data) {
    var newData = {}
    Object.keys(data).forEach(function(k) {
        if (data[k].type == 'fun' && typeof data[k] == 'function') newData[k] = data[k]()
    })
    return newData
}

// show hide

// remove class hide to given context/this
// show(this) inside controller
mag.addons.show = function(condition) {
  if (typeof condition === 'boolean') {
    return {
      _config: function(n) {
        if (!condition) n.style.display = 'none';
        else n.style.display = 'block';
      }
    };
  } else if(typeof condition === 'object') {
    condition.didload = function(e, n) {
      n.classList.remove('hide')
      // both or just if no class hide ..
      //node.style.display = 'none'
    }
  } else if (arguments.length == 0){
    return function(e, n) {
      // next didupdate event
      n.style.display = 'block'
    }
  }
}

mag.addons.hide = function(condition) {
  if (typeof condition === 'boolean') {
    return {
      _config: function(n) {
          if (condition) n.style.display = 'none';
      }
    }
  } else if(arguments.length == 0){
    return function(e, n) {
      // next didupdate event
      n.style.display = 'none'
    }
  }
}

// life cycle event helpers

mag.addons.onNextUpdate = function(context, callback) {
  context.didupdate = function(event, node) {
    return callback.call(context, event, node)
  }
}

// promises
mag.deferred = Deferred = function() {
  return function Deferred(resolve, reject) {
    Deferred.resolve = resolve
    Deferred.reject = reject
  }
}

mag.addons.when = function(arrayOfPromises, callback) {
    Promise.all(arrayOfPromises).then(callback)
}

mag.addons.requestWithFeedback = function(args) {
  var key = JSON.stringify(args)
  if (!mag.addons.requestWithFeedback.cache[key]) {

    var loaders = document.querySelectorAll(".loader")

    //show icons
    for (var i = 0, loader; loader = loaders[i]; i++) loader.style.display = "block"

    var expire = function(data) {
      delete mag.addons.requestWithFeedback.cache[key]

      if (Object.keys(mag.addons.requestWithFeedback.cache).length == 0) {
          //hide icons
          for (var i = 0, loader; loader = loaders[i]; i++) loader.style.display = "none"
      }
      return data
    }
    mag.addons.requestWithFeedback.cache[key] = mag.request(args).then(expire, function(error) {
      expire(error)
      throw error
    })
  }
  return mag.addons.requestWithFeedback.cache[key]
}
mag.addons.requestWithFeedback.cache = {}

// hookins

mag.hookin('attributes', 'key', function(data) {
    // remove system key from being added to attributes in html
  //  data.value = null
})

mag.hookin('attributes', 'className', function(data) {
  var newClass = data.value
  data.value = data.node.classList + ''
  if (!data.node.classList.contains(newClass)) {
    data.value = data.node.classList.length > 0 ? data.node.classList + ' ' + newClass : newClass
  }
    data.key = 'class'
})
<|endoftext|>


<commit_before>/*global KeyboardEvent*/

const HTML_ELEMENT = global.document.documentElement;
const ATTR_CREATE_NEW = 'data-new-instance';
const ATTR_CLOSE = 'data-close-modal';
const CLS_CONTAINER_CURRENT = 'front';
const ATTR_NAME = 'data-modal';
const CLS_OPEN = 'open';
const CURRENT_CLASS = 'current';
const PART_OF_STACK_CLASS = 'part-of-stack';
const CLS_MODAL_OPEN = 'modal-open';
import Settings from 'util/Settings';
import $ from 'jquery';
import Event from 'util/Event';
import Util from 'util/Util';

const EVENT_MODAL_CLOSED = 'flexcss.modal.closed';
const EVENT_MODAL_BEFORE_CLOSED = 'flexcss.modal.beforeClose';

/**
 * A Modal Implementation
 */
export default
class Modal {
    constructor(DelegateContainer, options) {
        var doc = global.document, container = DelegateContainer instanceof HTMLElement ?
            DelegateContainer : doc.getElementById(DelegateContainer);

        // Instance vars:
        if (!container) {
            throw 'Could not found container element by given ID/Element: ' + DelegateContainer;
        }

        this.currentOpen = null;

        this.loading = false;

        this.container = container;

        /**
         * Default Options
         */
        this.options = {
            classNames: 'modal',
            closeOnEscape: true,
            closeOnBackgroundClick: true,
            destroyOnFinish: false
        };

        Object.assign(this.options, options);

        // Container where events are delegated
        this.eventContainer = null;

        this.dataMainPageContainer = global.document.body;

        this.currentScrollTop = 0;

        this.modalContainer = null;

        // Destroy full modal instance when no dialogs are bind to?
        // Otherwise container is recycled
        this.destroyOnFinish = this.options.destroyOnFinish;
    }

    /**
     * Removes this modal from global stack
     * Will handle fixing main html element too
     * @private
     * @param n
     */
    _removeModalFromStack(n) {
        var t = Modal._modalInstances.indexOf(n);
        if (t > -1) {
            Modal._modalInstances.splice(t, 1);
            if (0 === FlexCss._modalInstances.length) {
                HTML_ELEMENT.classList.remove(CLS_MODAL_OPEN);
                Settings.get().scrollbarUpdateNodes.forEach(function (n) {
                    // restore scrollPosition:
                    if (this.dataMainPageContainer) {
                        this.dataMainPageContainer.style.position = "static";
                        this.dataMainPageContainer.style.top = "0px";
                        $(window, document.body).scrollTop(this.currentScrollTop);
                    }
                    n.style.paddingRight = '';
                });

            }
        }
    }

    /**
     * Modal container that contains all `stacked` modals for this instance
     * @returns {HTMLElement}
     */
    getModalContainer() {
        return this.modalContainer;
    }

    /**
     * Closes the current open modal of this stack
     * @params [e], optional event
     * @returns {*}
     */
    close(e) {
        var self = this;

        // close only on keyboard if instance should
        if (!self.options.closeOnEscape && e instanceof KeyboardEvent) {
            return false;
        }

        // close only on background if instance should
        if (!self.options.closeOnBackgroundClick && e &&
            e.type === FlexCss.CONST_FLEX_EVENT_TAB && !e.target.hasAttribute(ATTR_CLOSE)) {
            return false;
        }

        // if an instance is currently loading, prevent from closing
        if (self.loading) {
            return false;
        }

        if (e) {
            e.preventDefault();
        }

        if (self.currentOpen) {
            // dispatch beforeClose event, if prevented prevent modal from closing
            var ev = Event.dispatchAndFire(self.currentOpen, EVENT_MODAL_BEFORE_CLOSED);
            if (ev.isDefaultPrevented()) {
                return false;
            }

            self.currentOpen.removeAttribute('style');

            // if there is an previous modal
            if (self.currentOpen.prevModal) {
                // switch to the next modal
                return self.switchModals(self.currentOpen.prevModal,
                    self.currentOpen.prevModal.prevModal || null);
            }

            // finally trigger closed event
            Event.dispatchAndFire(self.currentOpen, EVENT_MODAL_CLOSED);

        }
        self._removeModalFromStack(self.currentOpen);

        // Full stack closed:
        self.currentOpen = null;
        if (self.modalContainer) {
            // setup next open
            var lastContainer = Modal._modalInstances[Modal._modalInstances.length - 1],
                classList = self.modalContainer.classList;
            classList.remove(CLS_CONTAINER_CURRENT);
            classList.remove(CLS_OPEN);
            // Remove all current classes from child-nodes
            for (var i = 0; i < self.modalContainer.childNodes.length; i++) {
                var node = self.modalContainer.childNodes[i], cl = node.classList;
                // remove applied styles
                node.removeAttribute('style');
                cl.remove(CURRENT_CLASS);
                cl.remove(PART_OF_STACK_CLASS);
            }
            if (lastContainer) {
                lastContainer.parentNode.classList.add(CLS_CONTAINER_CURRENT);
            }
        }

        if (self.options.destroyOnFinish) {
            self.destroy();
        }
        return self;
    }

    /**
     * Brings the given modal to front
     * @param co
     * @param last
     */
    switchModals(co, last) {
        co.prevModal = last;
        Modal._modalInstances.push(co);

        if (last) {
            last.classList.add('part-of-stack');
        }
        // set new currentOpen
        this.currentOpen = co;

        // bring current container to the front
        var instances = Modal._modalInstances;

        for (var m = 0; m < instances.length; m++) {
            instances[m].parentNode.classList.remove(CLS_CONTAINER_CURRENT);
        }
        this.modalContainer.classList.add(CLS_CONTAINER_CURRENT);

        // remove animations if animations has been completed, fixes various bugs:
        // - fixes nested scrolling element issue in iOS Browsers / Mobile-Safari
        Util.PrefixedAnimateEvent(co, 'AnimationEnd', function (e, self) {
            e.target.style.animation = 'none';
            e.target.style.webkitAnimation = 'none';
            co.removeEventListener(e.type, self, true);
        });

        for (var i = 0; i < this.modalContainer.childNodes.length; i++) {
            var n = this.modalContainer.childNodes[i], isCurrent = n.classList.contains(CURRENT_CLASS);
            if (n === co) {
                co.classList.add(CURRENT_CLASS);
                co.classList.remove(PART_OF_STACK_CLASS);
            } else {
                n.classList.remove(CURRENT_CLASS);
                if (isCurrent) {
                    this._removeModalFromStack(n);
                    Event.dispatchAndFire(n, EVENT_MODAL_CLOSED);
                }
            }
        }
    }

    handleScrollbar() {
        var self = this;
        if (0 === Modal._modalInstances.length) {
            HTML_ELEMENT.classList.add(CLS_MODAL_OPEN);
            // save current scrollTop:
            var scrollTop = window.pageYOffset,
                c = self.dataMainPageContainer;
            self.currentScrollTop = scrollTop;
            if (c) {
                c.style.top = scrollTop * -1 + 'px';
                c.style.position = 'fixed';
            }
            Settings.get().scrollbarUpdateNodes.forEach(function (n) {
                n.style.paddingRight = parseInt(window.getComputedStyle(n).paddingRight) +
                Settings.CONST_SCROLLBAR_WIDTH + 'px';
            });
        }
    }

    /**
     * Creates this instance
     * @param e
     * @returns {*} (Future, undefined if in unstable state)
     */
    createWidget(e) {
        if (this.loading) {
            return;
        }

        // check if another modal has registered events on this dom path:
        if (e && e.target) {
            var foundInstance = Util.parentsUntil(e.target, function (node) {
                return node.flexModalInstance;
            });

            // if another instance has been found, abort
            if (foundInstance !== this.container) {
                return;
            }
        }
        var targetContent, future, widget, target, hasTarget = true,
            isHtmlElement = e instanceof HTMLElement, isWidget = e instanceof FlexCss.Widget;
        if (isHtmlElement || isWidget) {
            if (isHtmlElement) {
                targetContent = e;
                widget = e.hfWidgetInstance;
            } else {
                widget = e;
                targetContent = widget.widget;
            }
        } else {
            target = e.target;
            hasTarget = target.hasAttribute(ATTR_NAME);
            targetContent = target.getAttribute(ATTR_NAME);
            widget = target.hfWidgetInstance;

            if (target.hasAttribute(ATTR_CREATE_NEW) && !e.newInstance) {
                var newInstance = new FlexCss.Modal(this.container)
                    .setDestroyOnFinish(true);
                e.newInstance = true;
                newInstance.fromEvent(e).then(function () {
                    newInstance.registerEvents(newInstance.getModalContainer());
                });
                return;
            }

            if (hasTarget) {
                e.stopImmediatePropagation();
                e.preventDefault();
            }
        }
        if (!hasTarget) {
            return;
        }

        var modalContainerClasses = this.modalContainer ? this.modalContainer.classList : [];

        if (!this.modalContainer) {
            this.modalContainer = doc.createElement('div');
            this.modalContainer.className = 'modal-container ' + CLS_OPEN;
            var closeModalFunction = function (e) {
                if (loading || FlexCss.MODAL_JUST_OPENED) {
                    return;
                }
                if (FlexCss.isPartOfNode(e.target, currentOpen)) {
                    if (!e.target.hasAttribute(ATTR_CLOSE)) {
                        return;
                    }
                }
                self.close(e);
            };

            FlexCss.SETTINGS.clickEvents.forEach(function (e) {
                this.modalContainer.addEventListener(e, closeModalFunction, true);
            });

            modalContainerClasses = this.modalContainer.classList;
            container.appendChild(this.modalContainer);

        } else {
            modalContainerClasses.add(CLS_OPEN);
        }

        var loader, toggleLoader = function (show) {
            if (show) {
                loader = doc.createElement('div');
                loader.className = 'loader-container';
                var loaderLoader = doc.createElement('div');
                loaderLoader.className = 'loader';
                loader.appendChild(loaderLoader);
                modalContainer.appendChild(this.loader);
            } else {
                loader.parentNode.removeChild(this.loader);
            }
        };

        this.handleScrollbar();

        modalContainerClasses.add(CLS_CONTAINER_CURRENT);
        modalContainerClasses.add('loading');
        this.loading = true;
        toggleLoader(true);
        if (widget instanceof FlexCss.Widget && widget.getAsync()) {
            future = widget.runAsync().then(function (r) {
                if (r instanceof HTMLElement || r instanceof DocumentFragment) {
                    widget.setWidget(r);
                    return r;
                } else {
                    // Create container Element:
                    var element = doc.createElement('div');
                    element.className = self.options.classNames;
                    element.innerHTML = r;
                    element.id = Util.guid();
                    // Setup modal as widget to widget instance:
                    widget.setWidget(element);
                    return element;
                }
            });
        } else {
            var el = targetContent instanceof HTMLElement ||
            targetContent instanceof DocumentFragment ? targetContent : doc.getElementById(targetContent);
            if (el) {
                // If Widget is bound to content container, use this as our widget
                if (el.hfWidgetInstance) {
                    widget = el.hfWidgetInstance;
                }
                future = new Promise((resolve) => {
                    resolve(el);
                });
            } else {
                throw 'Could not found given modal element with ID: ' + targetContent;
            }
        }

        var self = this;

        return future.then(function (el) {
            el.hfWidgetInstance = widget;
            el.hfContainerInstance = self;

            modalContainer.appendChild(el);
            modalContainerClasses.remove('loading');
            self.loading = false;
            toggleLoader(false);

            self.open(el, true);

            return el;
        });
    }

;

}

// Static variable that keeps track of all open modals
Modal._modalInstances = [];

// Global keydown listener for modal
global.addEventListener('keydown', function (e) {
    if (27 === e.keyCode) {
        var lastModal = Modal._modalInstances[Modal._modalInstances.length - 1];
        if (lastModal) {
            lastModal.hfContainerInstance.close(e);
        }
    }
});

Modal.MODAL_JUST_OPENED = false;<commit_msg>moved import statements<commit_after>/*global KeyboardEvent*/

import Settings from 'util/Settings';
import $ from 'jquery';
import Event from 'util/Event';
import Util from 'util/Util';

const HTML_ELEMENT = global.document.documentElement;
const ATTR_CREATE_NEW = 'data-new-instance';
const ATTR_CLOSE = 'data-close-modal';
const CLS_CONTAINER_CURRENT = 'front';
const ATTR_NAME = 'data-modal';
const CLS_OPEN = 'open';
const CURRENT_CLASS = 'current';
const PART_OF_STACK_CLASS = 'part-of-stack';
const CLS_MODAL_OPEN = 'modal-open';

const EVENT_MODAL_CLOSED = 'flexcss.modal.closed';
const EVENT_MODAL_BEFORE_CLOSED = 'flexcss.modal.beforeClose';

/**
 * A Modal Implementation
 */
export default
class Modal {
    constructor(DelegateContainer, options) {
        var doc = global.document, container = DelegateContainer instanceof HTMLElement ?
            DelegateContainer : doc.getElementById(DelegateContainer);

        // Instance vars:
        if (!container) {
            throw 'Could not found container element by given ID/Element: ' + DelegateContainer;
        }

        this.currentOpen = null;

        this.loading = false;

        this.container = container;

        /**
         * Default Options
         */
        this.options = {
            classNames: 'modal',
            closeOnEscape: true,
            closeOnBackgroundClick: true,
            destroyOnFinish: false
        };

        Object.assign(this.options, options);

        // Container where events are delegated
        this.eventContainer = null;

        this.dataMainPageContainer = global.document.body;

        this.currentScrollTop = 0;

        this.modalContainer = null;

        // Destroy full modal instance when no dialogs are bind to?
        // Otherwise container is recycled
        this.destroyOnFinish = this.options.destroyOnFinish;
    }

    /**
     * Removes this modal from global stack
     * Will handle fixing main html element too
     * @private
     * @param n
     */
    _removeModalFromStack(n) {
        var t = Modal._modalInstances.indexOf(n);
        if (t > -1) {
            Modal._modalInstances.splice(t, 1);
            if (0 === FlexCss._modalInstances.length) {
                HTML_ELEMENT.classList.remove(CLS_MODAL_OPEN);
                Settings.get().scrollbarUpdateNodes.forEach(function (n) {
                    // restore scrollPosition:
                    if (this.dataMainPageContainer) {
                        this.dataMainPageContainer.style.position = "static";
                        this.dataMainPageContainer.style.top = "0px";
                        $(window, document.body).scrollTop(this.currentScrollTop);
                    }
                    n.style.paddingRight = '';
                });

            }
        }
    }

    /**
     * Modal container that contains all `stacked` modals for this instance
     * @returns {HTMLElement}
     */
    getModalContainer() {
        return this.modalContainer;
    }

    /**
     * Closes the current open modal of this stack
     * @params [e], optional event
     * @returns {*}
     */
    close(e) {
        var self = this;

        // close only on keyboard if instance should
        if (!self.options.closeOnEscape && e instanceof KeyboardEvent) {
            return false;
        }

        // close only on background if instance should
        if (!self.options.closeOnBackgroundClick && e &&
            e.type === FlexCss.CONST_FLEX_EVENT_TAB && !e.target.hasAttribute(ATTR_CLOSE)) {
            return false;
        }

        // if an instance is currently loading, prevent from closing
        if (self.loading) {
            return false;
        }

        if (e) {
            e.preventDefault();
        }

        if (self.currentOpen) {
            // dispatch beforeClose event, if prevented prevent modal from closing
            var ev = Event.dispatchAndFire(self.currentOpen, EVENT_MODAL_BEFORE_CLOSED);
            if (ev.isDefaultPrevented()) {
                return false;
            }

            self.currentOpen.removeAttribute('style');

            // if there is an previous modal
            if (self.currentOpen.prevModal) {
                // switch to the next modal
                return self.switchModals(self.currentOpen.prevModal,
                    self.currentOpen.prevModal.prevModal || null);
            }

            // finally trigger closed event
            Event.dispatchAndFire(self.currentOpen, EVENT_MODAL_CLOSED);

        }
        self._removeModalFromStack(self.currentOpen);

        // Full stack closed:
        self.currentOpen = null;
        if (self.modalContainer) {
            // setup next open
            var lastContainer = Modal._modalInstances[Modal._modalInstances.length - 1],
                classList = self.modalContainer.classList;
            classList.remove(CLS_CONTAINER_CURRENT);
            classList.remove(CLS_OPEN);
            // Remove all current classes from child-nodes
            for (var i = 0; i < self.modalContainer.childNodes.length; i++) {
                var node = self.modalContainer.childNodes[i], cl = node.classList;
                // remove applied styles
                node.removeAttribute('style');
                cl.remove(CURRENT_CLASS);
                cl.remove(PART_OF_STACK_CLASS);
            }
            if (lastContainer) {
                lastContainer.parentNode.classList.add(CLS_CONTAINER_CURRENT);
            }
        }

        if (self.options.destroyOnFinish) {
            self.destroy();
        }
        return self;
    }

    /**
     * Brings the given modal to front
     * @param co
     * @param last
     */
    switchModals(co, last) {
        co.prevModal = last;
        Modal._modalInstances.push(co);

        if (last) {
            last.classList.add('part-of-stack');
        }
        // set new currentOpen
        this.currentOpen = co;

        // bring current container to the front
        var instances = Modal._modalInstances;

        for (var m = 0; m < instances.length; m++) {
            instances[m].parentNode.classList.remove(CLS_CONTAINER_CURRENT);
        }
        this.modalContainer.classList.add(CLS_CONTAINER_CURRENT);

        // remove animations if animations has been completed, fixes various bugs:
        // - fixes nested scrolling element issue in iOS Browsers / Mobile-Safari
        Util.PrefixedAnimateEvent(co, 'AnimationEnd', function (e, self) {
            e.target.style.animation = 'none';
            e.target.style.webkitAnimation = 'none';
            co.removeEventListener(e.type, self, true);
        });

        for (var i = 0; i < this.modalContainer.childNodes.length; i++) {
            var n = this.modalContainer.childNodes[i], isCurrent = n.classList.contains(CURRENT_CLASS);
            if (n === co) {
                co.classList.add(CURRENT_CLASS);
                co.classList.remove(PART_OF_STACK_CLASS);
            } else {
                n.classList.remove(CURRENT_CLASS);
                if (isCurrent) {
                    this._removeModalFromStack(n);
                    Event.dispatchAndFire(n, EVENT_MODAL_CLOSED);
                }
            }
        }
    }

    handleScrollbar() {
        var self = this;
        if (0 === Modal._modalInstances.length) {
            HTML_ELEMENT.classList.add(CLS_MODAL_OPEN);
            // save current scrollTop:
            var scrollTop = window.pageYOffset,
                c = self.dataMainPageContainer;
            self.currentScrollTop = scrollTop;
            if (c) {
                c.style.top = scrollTop * -1 + 'px';
                c.style.position = 'fixed';
            }
            Settings.get().scrollbarUpdateNodes.forEach(function (n) {
                n.style.paddingRight = parseInt(window.getComputedStyle(n).paddingRight) +
                Settings.CONST_SCROLLBAR_WIDTH + 'px';
            });
        }
    }

    /**
     * Creates this instance
     * @param e
     * @returns {*} (Future, undefined if in unstable state)
     */
    createWidget(e) {
        if (this.loading) {
            return;
        }

        // check if another modal has registered events on this dom path:
        if (e && e.target) {
            var foundInstance = Util.parentsUntil(e.target, function (node) {
                return node.flexModalInstance;
            });

            // if another instance has been found, abort
            if (foundInstance !== this.container) {
                return;
            }
        }
        var targetContent, future, widget, target, hasTarget = true,
            isHtmlElement = e instanceof HTMLElement, isWidget = e instanceof FlexCss.Widget;
        if (isHtmlElement || isWidget) {
            if (isHtmlElement) {
                targetContent = e;
                widget = e.hfWidgetInstance;
            } else {
                widget = e;
                targetContent = widget.widget;
            }
        } else {
            target = e.target;
            hasTarget = target.hasAttribute(ATTR_NAME);
            targetContent = target.getAttribute(ATTR_NAME);
            widget = target.hfWidgetInstance;

            if (target.hasAttribute(ATTR_CREATE_NEW) && !e.newInstance) {
                var newInstance = new FlexCss.Modal(this.container)
                    .setDestroyOnFinish(true);
                e.newInstance = true;
                newInstance.fromEvent(e).then(function () {
                    newInstance.registerEvents(newInstance.getModalContainer());
                });
                return;
            }

            if (hasTarget) {
                e.stopImmediatePropagation();
                e.preventDefault();
            }
        }
        if (!hasTarget) {
            return;
        }

        var modalContainerClasses = this.modalContainer ? this.modalContainer.classList : [];

        if (!this.modalContainer) {
            this.modalContainer = doc.createElement('div');
            this.modalContainer.className = 'modal-container ' + CLS_OPEN;
            var closeModalFunction = function (e) {
                if (loading || FlexCss.MODAL_JUST_OPENED) {
                    return;
                }
                if (FlexCss.isPartOfNode(e.target, currentOpen)) {
                    if (!e.target.hasAttribute(ATTR_CLOSE)) {
                        return;
                    }
                }
                self.close(e);
            };

            FlexCss.SETTINGS.clickEvents.forEach(function (e) {
                this.modalContainer.addEventListener(e, closeModalFunction, true);
            });

            modalContainerClasses = this.modalContainer.classList;
            container.appendChild(this.modalContainer);

        } else {
            modalContainerClasses.add(CLS_OPEN);
        }

        var loader, toggleLoader = function (show) {
            if (show) {
                loader = doc.createElement('div');
                loader.className = 'loader-container';
                var loaderLoader = doc.createElement('div');
                loaderLoader.className = 'loader';
                loader.appendChild(loaderLoader);
                modalContainer.appendChild(this.loader);
            } else {
                loader.parentNode.removeChild(this.loader);
            }
        };

        this.handleScrollbar();

        modalContainerClasses.add(CLS_CONTAINER_CURRENT);
        modalContainerClasses.add('loading');
        this.loading = true;
        toggleLoader(true);
        if (widget instanceof FlexCss.Widget && widget.getAsync()) {
            future = widget.runAsync().then(function (r) {
                if (r instanceof HTMLElement || r instanceof DocumentFragment) {
                    widget.setWidget(r);
                    return r;
                } else {
                    // Create container Element:
                    var element = doc.createElement('div');
                    element.className = self.options.classNames;
                    element.innerHTML = r;
                    element.id = Util.guid();
                    // Setup modal as widget to widget instance:
                    widget.setWidget(element);
                    return element;
                }
            });
        } else {
            var el = targetContent instanceof HTMLElement ||
            targetContent instanceof DocumentFragment ? targetContent : doc.getElementById(targetContent);
            if (el) {
                // If Widget is bound to content container, use this as our widget
                if (el.hfWidgetInstance) {
                    widget = el.hfWidgetInstance;
                }
                future = new Promise((resolve) => {
                    resolve(el);
                });
            } else {
                throw 'Could not found given modal element with ID: ' + targetContent;
            }
        }

        var self = this;

        return future.then(function (el) {
            el.hfWidgetInstance = widget;
            el.hfContainerInstance = self;

            modalContainer.appendChild(el);
            modalContainerClasses.remove('loading');
            self.loading = false;
            toggleLoader(false);

            self.open(el, true);

            return el;
        });
    }

;

}

// Static variable that keeps track of all open modals
Modal._modalInstances = [];

// Global keydown listener for modal
global.addEventListener('keydown', function (e) {
    if (27 === e.keyCode) {
        var lastModal = Modal._modalInstances[Modal._modalInstances.length - 1];
        if (lastModal) {
            lastModal.hfContainerInstance.close(e);
        }
    }
});

Modal.MODAL_JUST_OPENED = false;<|endoftext|>


<commit_before>import { Menu, dialog, app, ipcMain as ipc } from 'electron';
import { resolve } from 'path';

import Rx from 'rxjs/Rx';

import {
  launch,
  launchNewNotebook,
} from './launch';

import { defaultMenu, loadFullMenu } from './menu';

const log = require('electron-log');

const kernelspecs = require('kernelspecs');

const version = require('../../package.json').version;

log.info('args', process.argv);

const sliceAt = process.argv[0].match('nteract') ? 1 : 2;

const argv = require('yargs')
  .version(version)
  .parse(process.argv.slice(sliceAt));

const notebooks = argv._
  .filter(Boolean)
  .filter(x => /^(?!-)/.test(x)) // Ignore strangeness on OS X first launch
                                 // see #805
  .filter(x => x !== '.'); // Ignore the `electron .`
                           // TODO: Consider opening something for directories

app.on('window-all-closed', () => {
  // On OS X, we want to keep the app and menu bar active
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

ipc.on('new-kernel', (event, newKernel) => {
  launchNewNotebook(newKernel);
});

ipc.on('open-notebook', (event, filename) => {
  launch(resolve(filename));
});

const appReady$ = Rx.Observable.fromEvent(app, 'ready');

const openFile$ = Rx.Observable.fromEvent(
  app,
  'open-file', (event, path) => ({ event, path })
);

function openFileFromEvent({ event, path }) {
  event.preventDefault();
  launch(resolve(path));
}

const kernelSpecsPromise = kernelspecs.findAll();

// Since we can't launch until app is ready
// and OS X will send the open-file events early,
// buffer those that come early.
openFile$
  .buffer(appReady$) // Form an array of open-file events from before app-ready
  .first() // Should only be the first
  .subscribe(buffer => {
    // Now we can choose whether to open the default notebook
    // based on if arguments went through argv or through open-file events
    if (notebooks.length <= 0 && buffer.length <= 0) {
      log.info('launching an empty notebook by default');
      kernelSpecsPromise.then(specs => {
        const defaultKernel = 'python3';
        let kernel = defaultKernel;

        if ('python3' in specs) {
          kernel = 'python3';
        } else if ('python2' in specs) {
          kernel = 'python2';
        } else {
          const specList = Object.keys(specs);
          specList.sort();
          kernel = specList[0];
        }

        launchNewNotebook(kernel);
      }
      );
    } else {
      notebooks
        .forEach(f => {
          try {
            launch(resolve(f));
          } catch (e) {
            log.error(e);
            console.error(e);
          }
        });
    }
    buffer.forEach(openFileFromEvent);
  });

// All open file events after app is ready
openFile$
  .skipUntil(appReady$)
  .subscribe(openFileFromEvent);

appReady$
  .subscribe(() => {
    kernelSpecsPromise.then(kernelSpecs => {
      if (Object.keys(kernelSpecs).length !== 0) {
        // Get the default menu first
        Menu.setApplicationMenu(defaultMenu);
        // Let the kernels/languages come in after
        loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
      } else {
        dialog.showMessageBox({
          type: 'warning',
          title: 'No Kernels Installed',
          buttons: [],
          message: 'No kernels are installed on your system.',
          detail: 'No kernels are installed on your system so you will not be ' +
            'able to execute code cells in any language. You can read about ' +
            'installing kernels at ' +
            'https://ipython.readthedocs.io/en/latest/install/kernel_install.html',
        }, (index) => {
          if (index === 0) {
            app.quit();
          }
        });
      }
    }).catch(err => {
      dialog.showMessageBox({
        type: 'error',
        title: 'No Kernels Installed',
        buttons: [],
        message: 'No kernels are installed on your system.',
        detail: 'No kernels are installed on your system so you will not be ' +
          'able to execute code cells in any language. You can read about ' +
          'installing kernels at ' +
          'https://ipython.readthedocs.io/en/latest/install/kernel_install.html' +
          `\nFull error: ${err.message}`,
      }, (index) => {
        if (index === 0) {
          app.quit();
        }
      });
    });
  });
<commit_msg>fix(launch): filter out ProcessSerialNumber for OS X<commit_after>import { Menu, dialog, app, ipcMain as ipc } from 'electron';
import { resolve } from 'path';

import Rx from 'rxjs/Rx';

import {
  launch,
  launchNewNotebook,
} from './launch';

import { defaultMenu, loadFullMenu } from './menu';

const log = require('electron-log');

const kernelspecs = require('kernelspecs');

const version = require('../../package.json').version;

log.info('args', process.argv);

const sliceAt = process.argv[0].match('nteract') ? 1 : 2;

const argv = require('yargs')
  .version(version)
  .parse(process.argv.slice(sliceAt));

const notebooks = argv._
  .filter(Boolean)
  .filter(x => /^(?!-psn)/.test(x)) // Ignore strangeness on OS X first launch
                                 // see #805
  .filter(x => x !== '.'); // Ignore the `electron .`
                           // TODO: Consider opening something for directories

app.on('window-all-closed', () => {
  // On OS X, we want to keep the app and menu bar active
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

ipc.on('new-kernel', (event, newKernel) => {
  launchNewNotebook(newKernel);
});

ipc.on('open-notebook', (event, filename) => {
  launch(resolve(filename));
});

const appReady$ = Rx.Observable.fromEvent(app, 'ready');

const openFile$ = Rx.Observable.fromEvent(
  app,
  'open-file', (event, path) => ({ event, path })
);

function openFileFromEvent({ event, path }) {
  event.preventDefault();
  launch(resolve(path));
}

const kernelSpecsPromise = kernelspecs.findAll();

// Since we can't launch until app is ready
// and OS X will send the open-file events early,
// buffer those that come early.
openFile$
  .buffer(appReady$) // Form an array of open-file events from before app-ready
  .first() // Should only be the first
  .subscribe(buffer => {
    // Now we can choose whether to open the default notebook
    // based on if arguments went through argv or through open-file events
    if (notebooks.length <= 0 && buffer.length <= 0) {
      log.info('launching an empty notebook by default');
      kernelSpecsPromise.then(specs => {
        const defaultKernel = 'python3';
        let kernel = defaultKernel;

        if ('python3' in specs) {
          kernel = 'python3';
        } else if ('python2' in specs) {
          kernel = 'python2';
        } else {
          const specList = Object.keys(specs);
          specList.sort();
          kernel = specList[0];
        }

        launchNewNotebook(kernel);
      }
      );
    } else {
      notebooks
        .forEach(f => {
          try {
            launch(resolve(f));
          } catch (e) {
            log.error(e);
            console.error(e);
          }
        });
    }
    buffer.forEach(openFileFromEvent);
  });

// All open file events after app is ready
openFile$
  .skipUntil(appReady$)
  .subscribe(openFileFromEvent);

appReady$
  .subscribe(() => {
    kernelSpecsPromise.then(kernelSpecs => {
      if (Object.keys(kernelSpecs).length !== 0) {
        // Get the default menu first
        Menu.setApplicationMenu(defaultMenu);
        // Let the kernels/languages come in after
        loadFullMenu().then(menu => Menu.setApplicationMenu(menu));
      } else {
        dialog.showMessageBox({
          type: 'warning',
          title: 'No Kernels Installed',
          buttons: [],
          message: 'No kernels are installed on your system.',
          detail: 'No kernels are installed on your system so you will not be ' +
            'able to execute code cells in any language. You can read about ' +
            'installing kernels at ' +
            'https://ipython.readthedocs.io/en/latest/install/kernel_install.html',
        }, (index) => {
          if (index === 0) {
            app.quit();
          }
        });
      }
    }).catch(err => {
      dialog.showMessageBox({
        type: 'error',
        title: 'No Kernels Installed',
        buttons: [],
        message: 'No kernels are installed on your system.',
        detail: 'No kernels are installed on your system so you will not be ' +
          'able to execute code cells in any language. You can read about ' +
          'installing kernels at ' +
          'https://ipython.readthedocs.io/en/latest/install/kernel_install.html' +
          `\nFull error: ${err.message}`,
      }, (index) => {
        if (index === 0) {
          app.quit();
        }
      });
    });
  });
<|endoftext|>


<commit_before>/* eslint-env es6 */

import _ from 'lodash'
import path from 'path'
import webpack from 'webpack'
import autoprefixer from 'autoprefixer'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import ProgressBar from 'progress'
import S3Plugin from 'webpack-s3-plugin'
import CompressionPlugin from 'compression-webpack-plugin'
import {vendor} from './vendors.json'
import {name} from './package.json'

const {
  CommonsChunkPlugin,
  DedupePlugin,
  OccurenceOrderPlugin,
  LimitChunkCountPlugin,
  MinChunkSizePlugin,
  UglifyJsPlugin
} = webpack.optimize

const {DefinePlugin, ProgressPlugin} = webpack,
      CONTEXT = path.resolve(__dirname),
      createPath = (nPath) => path.resolve(CONTEXT, nPath),
      DEV_SERVER_PORT = 4000,
      APP_ROOT = createPath('src'),
      PUBLIC_PATH = createPath('public'),
      createAppPath = (nPath) => path.resolve(APP_ROOT, nPath),
      {NODE_ENV, AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, AWS_BUCKET, CDN_URL} = process.env,
      BUILD_PATH = createPath('build')

const progressBar = new ProgressBar('[:bar] :percent (:current/:total)', {
  complete: '-',
  incomplete: ' ',
  total: 100
})

var devtool

const TS_INGORES = [
  2403,
  2300,
  2374,
  2375,
  1005
]

const ENV = {
  __DEV__: NODE_ENV === 'development',
  __PROD__: NODE_ENV === 'production',
  __TEST__: NODE_ENV === 'test',
  __STAGING__: NODE_ENV === 'staging'
}

const IS_BUILD = ENV.__STAGING__ || ENV.__PROD__,
      DEFAULT_CDN = CDN_URL || `https://s3-us-west-2.amazonaws.com/${AWS_BUCKET}`,
      SASS_LOADER = `${IS_BUILD ? 'postcss!' : ''}sass?sourceMap`

Object.assign(ENV, {__IS_BUILD__: IS_BUILD})

var preLoaders = {
  tslint: {
    test: /\.ts/,
    loader: 'tslint',
    exclude: [createPath('node_modules')],
    include: [APP_ROOT]
  }
}

var loaders = {
  javascript: {
    test: /\.ts/,
    loader: `babel!ts?${TS_INGORES.map(num => `ignoreDiagnostics[]=${num}`).join('&')}`,
    exclude: [createPath('node_modules')],
    include: [APP_ROOT]
  },

  html: {
    test: /\.jade/,
    loader: 'jade',
    include: [APP_ROOT]
  },

  globalCss: {
    test: /\.s?css/,
    loader: `style!css?sourceMap!${SASS_LOADER}`,
    include: [createAppPath('style')]
  },

  // For to-string removes the ability to cache css so we use raw in development
  componentCss: {
    test: /\.s?css/,
    loader: `${IS_BUILD ? 'to-string' : 'raw'}!${SASS_LOADER}`,
    exclude: [createAppPath('style')]
  },

  json: {
    test: /\.json/,
    loader: 'json'
  },

  file: {
    test: /\.(png|gif|jpg|jpeg)$/,
    loader: `file${IS_BUILD ? '?name=[hash].[ext]' : ''}!image-webpack?bypassOnDebug`,
    include: [createPath('public/img')]
  },

  svg: {
    test: /\.svg/,
    loader: 'image-webpack?bypassOnDebug!svg-inline',
    include: [createPath('public/svg')]
  }
}

if (ENV.__PROD__)
  devtool = false
else if (ENV.__DEV__)
  devtool = '#source-map'
else if (ENV.__STAGING__ || ENV.__TEST__)
  devtool = '#inline-source-map'

var config = {
  context: CONTEXT,
  devtool,
  debug: !ENV.__PROD__ && !ENV.__STAGING__,

  entry: {
    vendor,
    app: './src/boot.ts'
  },

  output: {
    path: BUILD_PATH,
    publicPath: IS_BUILD ? DEFAULT_CDN : '',
    filename: IS_BUILD ? '[name]-[chunkhash].js' : '[name].js',
    sourceMapFilename: '[name].map',
    chunkFilename: IS_BUILD ? '[id].chunk-[chunkhash].js': '[id].chunk.js'
  },

  resolve: {
    extensions: ['', '.ts', '.js', '.json'],
    root: [APP_ROOT, PUBLIC_PATH],
    alias: {
      vendor: createPath('vendor')
    }
  },

  module: {
    noParse: [/.+zone\.js\/dist\/.+/, /.+angular2\/bundles\/.+/],
    preLoaders: Object.values(preLoaders),
    loaders: Object.values(loaders)
  },

  plugins: [
    new DefinePlugin(ENV),
    new ProgressPlugin(percentage => progressBar.update(percentage)),
    new HtmlWebpackPlugin({
      inject: false,
      title: name,
      minify: IS_BUILD ? {caseSensitive: true} : false,
      template: createAppPath('index.jade'),
      favicon: path.resolve(__dirname, 'favicon.ico'),
    })
  ],

  tslint: {
    emitErrors: false,
    failOnHint: false
  },

  postcss() {
    return [autoprefixer]
  },

  devServer: {
    stats: 'minimal',
    port: DEV_SERVER_PORT,
    // Sample Proxy Config
    //proxy: [{
      //path: '/api/*',
      //target: 'http://localhost:4000'
    //}],

    historyApiFallback: {
      // If you have multiple entrypoints add them here
      rewrites: [{
        from: /.*/,
        to: '/index.html'
      }]
    },

    watchOptions: {
      aggregateTimeout: 300
    }
  }
}

if (!ENV.__TEST__)
  config.plugins.push(
    new CommonsChunkPlugin({
      name: 'vendor',
      async: true,
      filename: IS_BUILD ? 'vendor-[chunkhash].js' : 'vendor.js',
      minChunks: Infinity
    }),
  )

if (ENV.__DEV__) {
  var WebpackNotifierPlugin = require('webpack-notifier')

  config.plugins.push(new WebpackNotifierPlugin({
    title: name,
    contentImage: createPath('./favicon.ico')
  }))
} else if (IS_BUILD) {
  loaders.globalCss.loader = ExtractTextPlugin.extract('style', loaders.globalCss.loader.replace('style', ''))

  config.plugins.push(
    new OccurenceOrderPlugin(),
    new DedupePlugin(),
    new ExtractTextPlugin('[name]-[chunkhash].css'),
    new LimitChunkCountPlugin({maxChunks: 15}),
    new MinChunkSizePlugin({minChunkSize: 10000}),
    new UglifyJsPlugin({mangle: false}),
    new CommonsChunkPlugin({
      name: 'common',
      filename: IS_BUILD ? 'common-[chunkhash].js' : 'common.js',
      minChunks: 2,
      chunks: ['app', 'vendor']
    })
  )
} else if (ENV.__TEST__) {
  config.resolve.cache = false
  config.stats = {
    colors: true,
    reasons: true
  }

  config.node = _.extend(config.node, {
    global: 'window',
    progress: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  })

  config.module.noParse = [
    /zone\.js\/dist\/zone-microtask\.js/,
    /zone\.js\/dist\/long-stack-trace-zone\.js/,
    /zone\.js\/dist\/jasmine-patch\.js/
  ]
}

if (ENV.__PROD__)
  config.plugins.push(
    new CompressionPlugin({
      asset: '[path]',
      algorithm: 'gzip',
      minRatio: 0.8
    }),

    new S3Plugin({
      exclude: /.*\.html$/,
      s3Options: {
        accessKeyId: AWS_ACCESS_KEY,
        secretAccessKey: AWS_SECRET_KEY,
        region: AWS_REGION
      },
      s3UploadOptions: {
        Bucket: AWS_BUCKET,
        CacheControl: 'max-age=315360000, no-transform, public',
        ContentEncoding: 'gzip'
      },
      cdnizerOptions: {
        defaultCDNBase: DEFAULT_CDN
      }
    }),

    new S3Plugin({
      directory: BUILD_PATH,
      basePath: 'public/',
      exclude: /\.svg$/,
      include: loaders.file.test,
      s3Options: {
        accessKeyId: AWS_ACCESS_KEY,
        secretAccessKey: AWS_SECRET_KEY,
        region: AWS_REGION

      },
      s3UploadOptions: {
        Bucket: AWS_BUCKET,
        CacheControl: 'max-age=315360000, no-transform, public'
      }
    })
  )
else
  vendor.push('zone.js/dist/long-stack-trace-zone')

module.exports = config
<commit_msg>remove comma<commit_after>/* eslint-env es6 */

import _ from 'lodash'
import path from 'path'
import webpack from 'webpack'
import autoprefixer from 'autoprefixer'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import ProgressBar from 'progress'
import S3Plugin from 'webpack-s3-plugin'
import CompressionPlugin from 'compression-webpack-plugin'
import {vendor} from './vendors.json'
import {name} from './package.json'

const {
  CommonsChunkPlugin,
  DedupePlugin,
  OccurenceOrderPlugin,
  LimitChunkCountPlugin,
  MinChunkSizePlugin,
  UglifyJsPlugin
} = webpack.optimize

const {DefinePlugin, ProgressPlugin} = webpack,
      CONTEXT = path.resolve(__dirname),
      createPath = (nPath) => path.resolve(CONTEXT, nPath),
      DEV_SERVER_PORT = 4000,
      APP_ROOT = createPath('src'),
      PUBLIC_PATH = createPath('public'),
      createAppPath = (nPath) => path.resolve(APP_ROOT, nPath),
      {NODE_ENV, AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, AWS_BUCKET, CDN_URL} = process.env,
      BUILD_PATH = createPath('build')

const progressBar = new ProgressBar('[:bar] :percent (:current/:total)', {
  complete: '-',
  incomplete: ' ',
  total: 100
})

var devtool

const TS_INGORES = [
  2403,
  2300,
  2374,
  2375,
  1005
]

const ENV = {
  __DEV__: NODE_ENV === 'development',
  __PROD__: NODE_ENV === 'production',
  __TEST__: NODE_ENV === 'test',
  __STAGING__: NODE_ENV === 'staging'
}

const IS_BUILD = ENV.__STAGING__ || ENV.__PROD__,
      DEFAULT_CDN = CDN_URL || `https://s3-us-west-2.amazonaws.com/${AWS_BUCKET}`,
      SASS_LOADER = `${IS_BUILD ? 'postcss!' : ''}sass?sourceMap`

Object.assign(ENV, {__IS_BUILD__: IS_BUILD})

var preLoaders = {
  tslint: {
    test: /\.ts/,
    loader: 'tslint',
    exclude: [createPath('node_modules')],
    include: [APP_ROOT]
  }
}

var loaders = {
  javascript: {
    test: /\.ts/,
    loader: `babel!ts?${TS_INGORES.map(num => `ignoreDiagnostics[]=${num}`).join('&')}`,
    exclude: [createPath('node_modules')],
    include: [APP_ROOT]
  },

  html: {
    test: /\.jade/,
    loader: 'jade',
    include: [APP_ROOT]
  },

  globalCss: {
    test: /\.s?css/,
    loader: `style!css?sourceMap!${SASS_LOADER}`,
    include: [createAppPath('style')]
  },

  // For to-string removes the ability to cache css so we use raw in development
  componentCss: {
    test: /\.s?css/,
    loader: `${IS_BUILD ? 'to-string' : 'raw'}!${SASS_LOADER}`,
    exclude: [createAppPath('style')]
  },

  json: {
    test: /\.json/,
    loader: 'json'
  },

  file: {
    test: /\.(png|gif|jpg|jpeg)$/,
    loader: `file${IS_BUILD ? '?name=[hash].[ext]' : ''}!image-webpack?bypassOnDebug`,
    include: [createPath('public/img')]
  },

  svg: {
    test: /\.svg/,
    loader: 'image-webpack?bypassOnDebug!svg-inline',
    include: [createPath('public/svg')]
  }
}

if (ENV.__PROD__)
  devtool = false
else if (ENV.__DEV__)
  devtool = '#source-map'
else if (ENV.__STAGING__ || ENV.__TEST__)
  devtool = '#inline-source-map'

var config = {
  context: CONTEXT,
  devtool,
  debug: !ENV.__PROD__ && !ENV.__STAGING__,

  entry: {
    vendor,
    app: './src/boot.ts'
  },

  output: {
    path: BUILD_PATH,
    publicPath: IS_BUILD ? DEFAULT_CDN : '',
    filename: IS_BUILD ? '[name]-[chunkhash].js' : '[name].js',
    sourceMapFilename: '[name].map',
    chunkFilename: IS_BUILD ? '[id].chunk-[chunkhash].js': '[id].chunk.js'
  },

  resolve: {
    extensions: ['', '.ts', '.js', '.json'],
    root: [APP_ROOT, PUBLIC_PATH],
    alias: {
      vendor: createPath('vendor')
    }
  },

  module: {
    noParse: [/.+zone\.js\/dist\/.+/, /.+angular2\/bundles\/.+/],
    preLoaders: Object.values(preLoaders),
    loaders: Object.values(loaders)
  },

  plugins: [
    new DefinePlugin(ENV),
    new ProgressPlugin(percentage => progressBar.update(percentage)),
    new HtmlWebpackPlugin({
      inject: false,
      title: name,
      minify: IS_BUILD ? {caseSensitive: true} : false,
      template: createAppPath('index.jade'),
      favicon: path.resolve(__dirname, 'favicon.ico'),
    })
  ],

  tslint: {
    emitErrors: false,
    failOnHint: false
  },

  postcss() {
    return [autoprefixer]
  },

  devServer: {
    stats: 'minimal',
    port: DEV_SERVER_PORT,
    // Sample Proxy Config
    //proxy: [{
      //path: '/api/*',
      //target: 'http://localhost:4000'
    //}],

    historyApiFallback: {
      // If you have multiple entrypoints add them here
      rewrites: [{
        from: /.*/,
        to: '/index.html'
      }]
    },

    watchOptions: {
      aggregateTimeout: 300
    }
  }
}

if (!ENV.__TEST__)
  config.plugins.push(
    new CommonsChunkPlugin({
      name: 'vendor',
      async: true,
      filename: IS_BUILD ? 'vendor-[chunkhash].js' : 'vendor.js',
      minChunks: Infinity
    })
  )

if (ENV.__DEV__) {
  var WebpackNotifierPlugin = require('webpack-notifier')

  config.plugins.push(new WebpackNotifierPlugin({
    title: name,
    contentImage: createPath('./favicon.ico')
  }))
} else if (IS_BUILD) {
  loaders.globalCss.loader = ExtractTextPlugin.extract('style', loaders.globalCss.loader.replace('style', ''))

  config.plugins.push(
    new OccurenceOrderPlugin(),
    new DedupePlugin(),
    new ExtractTextPlugin('[name]-[chunkhash].css'),
    new LimitChunkCountPlugin({maxChunks: 15}),
    new MinChunkSizePlugin({minChunkSize: 10000}),
    new UglifyJsPlugin({mangle: false}),
    new CommonsChunkPlugin({
      name: 'common',
      filename: IS_BUILD ? 'common-[chunkhash].js' : 'common.js',
      minChunks: 2,
      chunks: ['app', 'vendor']
    })
  )
} else if (ENV.__TEST__) {
  config.resolve.cache = false
  config.stats = {
    colors: true,
    reasons: true
  }

  config.node = _.extend(config.node, {
    global: 'window',
    progress: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  })

  config.module.noParse = [
    /zone\.js\/dist\/zone-microtask\.js/,
    /zone\.js\/dist\/long-stack-trace-zone\.js/,
    /zone\.js\/dist\/jasmine-patch\.js/
  ]
}

if (ENV.__PROD__)
  config.plugins.push(
    new CompressionPlugin({
      asset: '[path]',
      algorithm: 'gzip',
      minRatio: 0.8
    }),

    new S3Plugin({
      exclude: /.*\.html$/,
      s3Options: {
        accessKeyId: AWS_ACCESS_KEY,
        secretAccessKey: AWS_SECRET_KEY,
        region: AWS_REGION
      },
      s3UploadOptions: {
        Bucket: AWS_BUCKET,
        CacheControl: 'max-age=315360000, no-transform, public',
        ContentEncoding: 'gzip'
      },
      cdnizerOptions: {
        defaultCDNBase: DEFAULT_CDN
      }
    }),

    new S3Plugin({
      directory: BUILD_PATH,
      basePath: 'public/',
      exclude: /\.svg$/,
      include: loaders.file.test,
      s3Options: {
        accessKeyId: AWS_ACCESS_KEY,
        secretAccessKey: AWS_SECRET_KEY,
        region: AWS_REGION

      },
      s3UploadOptions: {
        Bucket: AWS_BUCKET,
        CacheControl: 'max-age=315360000, no-transform, public'
      }
    })
  )
else
  vendor.push('zone.js/dist/long-stack-trace-zone')

module.exports = config
<|endoftext|>


<commit_before>'use strict';

let fs = require('fs');
let path = require('path');
let yargs = require('yargs');
let webpack = require('webpack');
let autoprefixer = require('autoprefixer');
let ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');

const entry = require('./webpack.entry.json');
const packageJson = require('../package.json');

const alias = (() => {
    const aliasPath = path.join(__dirname, '../src/entry');
    let alias = {};
    fs.readdirSync(aliasPath).forEach(( filename ) => {
        let file = path.join(aliasPath, filename);
        if (fs.statSync(file).isFile() && path.extname(file) == '.js') {
            alias[path.basename(filename, '.js')] = file;
        }
    });
    return alias;
})();
const imageSize = 10240;
const constant = {};

let config = {
    devtool : '#source-map',
    entry,
    output : {
        filename : '[name].js',
        publicPath : '',
    },
    extensions : ['.vue', '.js', '.json', '.scss'],
    resolve : {
        alias,
    },
    module : {
        loaders : [
            {
                test : /\.vue$/,
                loader : 'vue',
            },
            {
                test : /\.(png|jpg|gif|svg)$/,
                loader : `url?limit=${ imageSize }&name=../img/[name].[ext]?[hash]`,
            },
            {
                test : /\.css$/,
                loader : ExtractTextWebpackPlugin.extract('style', 'css!postcss'),
            },
            {
                test : /\.scss$/,
                loader : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            },
            {
                test : /\.js$/,
                exclude : path.join(__dirname, '../node_modules/'),
                loader : 'babel',
                query : {
                    presets : ['es2015', 'stage-0'],
                    // plugins : ['transform-remove-strict-mode'],
                    // plugins: ['transform-runtime'],
                },
            },
        ],
    },
    plugins : [
        new ExtractTextWebpackPlugin('[name].css'),
        new webpack.DefinePlugin((() => {
            Object.keys(constant).forEach(( key ) => {
                constant[key] = JSON.stringify(constant[key]);
            });
            return {
                'process.env' : constant,
            };
        })()),
    ],
    vue : {
        loaders : {
            sass : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            scss : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
        },
    },
    postcss () {
        return [autoprefixer({ browsers : ['last 2 versions'] })];
    },
    devServer : {
        proxy : {
            '/dist' : {
                target : `http://localhost:${ yargs.argv.port + 1 }/`,
                changeOrigin : true,
                pathRewrite : {
                    '^/dist' : ''
                },
            },
        },
    },
};

module.exports = config;
<commit_msg>update demo<commit_after>'use strict';

let fs = require('fs');
let path = require('path');
let webpack = require('webpack');
let autoprefixer = require('autoprefixer');
let ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');

const entry = require('./webpack.entry.json');
const packageJson = require('../package.json');

const alias = {
    'micro-app' : path.join(__dirname, '../src/entry/micro-app.js'),
};
const imageSize = 10240;
const constant = {
    NAME : packageJson.name,
    VERSION : packageJson.version,
};

let config = {
    devtool : '#source-map',
    entry,
    output : {
        filename : '[name].js',
        publicPath : '',
    },
    extensions : ['.vue', '.js', '.coffee', '.json', '.scss'],
    resolve : {
        alias,
    },
    module : {
        loaders : [
            {
                test : /\.vue$/,
                loader : 'vue',
            },
            {
                test : /\.html$/,
                loader : 'raw',
            },
            {
                test : /\.(png|jpg|gif|svg)$/,
                loader : `url?limit=${ imageSize }&name=../img/[name].[ext]?[hash]`,
            },
            {
                test : /\.css$/,
                loader : ExtractTextWebpackPlugin.extract('style', 'css!postcss'),
            },
            {
                test : /\.scss$/,
                loader : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            },
            {
                test : /\.js$/,
                exclude : path.join(__dirname, '../node_modules/'),
                loader : 'babel',
                query : {
                    presets : ['es2015', 'stage-0'],
                    // plugins : ['transform-remove-strict-mode'],
                    // plugins: ['transform-runtime'],
                },
            },
            {
                test : /\.coffee/,
                loader : 'coffee',
            },
            {
                test : /\.(coffee\.md|litcoffee)$/,
                loader : 'coffee?literate',
            },
        ],
    },
    plugins : [
        new ExtractTextWebpackPlugin('[name].css'),
        new webpack.DefinePlugin((() => {
            Object.keys(constant).forEach(( key ) => {
                constant[key] = JSON.stringify(constant[key]);
            });
            return {
                'process.env' : constant,
            };
        })()),
    ],
    vue : {
        loaders : {
            sass : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            scss : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
        },
    },
    postcss () {
        return [autoprefixer({ browsers : ['last 2 versions'] })];
    },
    devServer : {
        proxy : {
            '/' : {
                bypass ( req, res ) {
                    if (/^\/micro-app\.js($|\?)/.test(req.url)) {
                        let file = path.join(__dirname, '../dist/micro-app.js');
                        if (fs.existsSync(file)) {
                            res.writeHead(200, { 'Content-Type' : 'application/x-javascript' });
                            res.end(fs.readFileSync(file, 'utf8'));
                        } else {
                            return req.url;
                        }
                    } else {
                        return req.url;
                    }
                },
            },
        },
    },
};

module.exports = config;
<|endoftext|>