<commit_before>jQuery.ajaxSetup({
    cache : false
});

jQuery(document).ready(function() {
    fixRequiredAttributeForSafari();
    setupFeedbackPanel();

    //setupApostropheKey();
    changeFormTabOrder();

    enableLemmaAutoComplete();
    enablePosAutoComplete();
});

// see http://caniuse.com/#feat=form-validation
function fixRequiredAttributeForSafari() {
    if (navigator.userAgent.indexOf("Safari") != -1
            && navigator.userAgent.indexOf("Chrome") == -1) {
        jQuery("form").submit(function(event) {
            var requiredFields = jQuery(this).find("[required]");

            requiredFields.each(function() {
                if (jQuery(this).val() == "") {
                    alert("Bitte alle erforderlichen Felder ausfüllen.");
                    jQuery(this).focus();
                    event.preventDefault();

                    return false;
                }
            });

            return true;
        });
    }
}

function setupFeedbackPanel(id) {
    var listItems;

    if (typeof id !== "undefined") {
        listItems = jQuery(id + " li");
    } else {
        listItems = jQuery(".feedbackPanel li");
    }

    listItems.each(function(index) {
        var listElementClass = jQuery(this).attr("class");

        jQuery(this).removeClass(listElementClass).addClass(
                "alert alert-" + listElementClass);
    });
}

function setupApostropheKey() {
    jQuery(":input:text, textarea")
            .keydown(
                    function(event) {
                        var character = "’", formElement = jQuery(this), selectionStart, selectionEnd;

                        if (event.shiftKey && event.which === 163) {
                            event.preventDefault();

                            selectionStart = formElement[0].selectionStart;
                            selectionEnd = formElement[0].selectionEnd;

                            insertCharacter(formElement, character,
                                    selectionStart, selectionEnd);
                        }
                    });
}

function insertCharacter(formElement, character, selectionStart, selectionEnd) {
    var value = formElement.val();

    if (selectionStart <= selectionEnd) {
        formElement.val(value.substring(0, selectionStart) + character
                + value.substring(selectionEnd));
        formElement[0]
                .setSelectionRange(selectionStart + 1, selectionStart + 1);
    } else {
        formElement.val(value.substring(0, selectionEnd) + character
                + value.substring(selectionStart));
        formElement[0].setSelectionRange(selectionEnd + 1, selectionEnd + 1);
    }
}

function changeFormTabOrder() {
    jQuery(".basePage form").on(
            "keypress",
            function(event) {
                var tabulatorPressed = (event.keyCode === 9) ? true : false;
                var shiftPressed = event.shiftKey;

                if (tabulatorPressed && jQuery(event.target).is(":input")) {
                    var formDescendants = jQuery(event.target).closest("form")
                            .find("*");
                    var formInputs = formDescendants.filter(":input:visible")
                            .not(":disabled").not(":button").not(":submit");
                    var firstInput = formInputs.first();
                    var lastInput = formInputs.last();

                    if (firstInput.is(event.target) && shiftPressed) {
                        lastInput.focus();
                        event.preventDefault();
                    } else if (lastInput.is(event.target) && !(shiftPressed)) {
                        firstInput.focus();
                        event.preventDefault();
                    }
                }
            });
}

function enableLemmaAutoComplete() {
    if (typeof lemmaSelector !== "undefined") {
        jQuery(lemmaSelector).autocomplete({
            autoFocus : true,
            delay : 0,
            source : lemmaCallbackUrl
        });
    }
}

function enablePosAutoComplete() {
    if (typeof posSelector !== "undefined") {
        jQuery(posSelector).autocomplete({
            autoFocus : true,
            delay : 0,
            source : posCallbackUrl
        });
    }
}
<commit_msg>Focus input fields with autofocus attribute when they scroll into the viewport.<commit_after>jQuery.ajaxSetup({
    cache : false
});

jQuery(document).ready(function() {
    fixRequiredAttributeForSafari();
    setupFeedbackPanel();

    //setupApostropheKey();
    changeFormTabOrder();

    enableLemmaAutoComplete();
    enablePosAutoComplete();
});

jQuery.fn.isInViewport = function (offset) {
    var elementTop, elementBottom, viewportTop, viewportBottom;

    if (typeof offset === "undefined") {
        offset = 0;
    }

    elementTop = jQuery(this).offset().top;
    elementBottom = elementTop + jQuery(this).outerHeight();
    viewportTop = jQuery(window).scrollTop();
    viewportBottom = viewportTop + jQuery(window).height();

    return elementBottom - offset > viewportTop && elementTop + offset < viewportBottom;
};

// focus autofocus inputs when they become visible
jQuery(window).on("resize scroll", function () {
    if (jQuery("input[autofocus]").first().isInViewport()) {
        jQuery("input[autofocus]").first().focus();
    }
});

// see http://caniuse.com/#feat=form-validation
function fixRequiredAttributeForSafari() {
    if (navigator.userAgent.indexOf("Safari") != -1
            && navigator.userAgent.indexOf("Chrome") == -1) {
        jQuery("form").submit(function(event) {
            var requiredFields = jQuery(this).find("[required]");

            requiredFields.each(function() {
                if (jQuery(this).val() == "") {
                    alert("Bitte alle erforderlichen Felder ausfüllen.");
                    jQuery(this).focus();
                    event.preventDefault();

                    return false;
                }
            });

            return true;
        });
    }
}

function setupFeedbackPanel(id) {
    var listItems;

    if (typeof id !== "undefined") {
        listItems = jQuery(id + " li");
    } else {
        listItems = jQuery(".feedbackPanel li");
    }

    listItems.each(function(index) {
        var listElementClass = jQuery(this).attr("class");

        jQuery(this).removeClass(listElementClass).addClass(
                "alert alert-" + listElementClass);
    });
}

function setupApostropheKey() {
    jQuery(":input:text, textarea")
            .keydown(
                    function(event) {
                        var character = "’", formElement = jQuery(this), selectionStart, selectionEnd;

                        if (event.shiftKey && event.which === 163) {
                            event.preventDefault();

                            selectionStart = formElement[0].selectionStart;
                            selectionEnd = formElement[0].selectionEnd;

                            insertCharacter(formElement, character,
                                    selectionStart, selectionEnd);
                        }
                    });
}

function insertCharacter(formElement, character, selectionStart, selectionEnd) {
    var value = formElement.val();

    if (selectionStart <= selectionEnd) {
        formElement.val(value.substring(0, selectionStart) + character
                + value.substring(selectionEnd));
        formElement[0]
                .setSelectionRange(selectionStart + 1, selectionStart + 1);
    } else {
        formElement.val(value.substring(0, selectionEnd) + character
                + value.substring(selectionStart));
        formElement[0].setSelectionRange(selectionEnd + 1, selectionEnd + 1);
    }
}

function changeFormTabOrder() {
    jQuery(".basePage form").on(
            "keypress",
            function(event) {
                var tabulatorPressed = (event.keyCode === 9) ? true : false;
                var shiftPressed = event.shiftKey;

                if (tabulatorPressed && jQuery(event.target).is(":input")) {
                    var formDescendants = jQuery(event.target).closest("form")
                            .find("*");
                    var formInputs = formDescendants.filter(":input:visible")
                            .not(":disabled").not(":button").not(":submit");
                    var firstInput = formInputs.first();
                    var lastInput = formInputs.last();

                    if (firstInput.is(event.target) && shiftPressed) {
                        lastInput.focus();
                        event.preventDefault();
                    } else if (lastInput.is(event.target) && !(shiftPressed)) {
                        firstInput.focus();
                        event.preventDefault();
                    }
                }
            });
}

function enableLemmaAutoComplete() {
    if (typeof lemmaSelector !== "undefined") {
        jQuery(lemmaSelector).autocomplete({
            autoFocus : true,
            delay : 0,
            source : lemmaCallbackUrl
        });
    }
}

function enablePosAutoComplete() {
    if (typeof posSelector !== "undefined") {
        jQuery(posSelector).autocomplete({
            autoFocus : true,
            delay : 0,
            source : posCallbackUrl
        });
    }
}
<|endoftext|>


<commit_before>var debug = require('debug')('kaching');

/**
 * Export actions prototype for strategies operating within an HTTP context.
 */
var actions = module.exports = {};

/**
 * Redirect to `url` with optional `status`, defaulting to 302.
 *
 * Strategies should call this function to redirect the user (via their user
 * agent) to a third-party website for authentication.
 *
 * @param {String} url
 * @param {Number} status
 * @api public
 */
actions.redirect = function(url, status) {
  var res = this.res;
  if (typeof res.redirect == 'function') {
    // If possible use redirect method on the response
    // Assume Express API, optional status param comes first
    if (status) {
      res.redirect(status, url);
    } else {
      res.redirect(url);
    }
  } else {
    // Otherwise fall back to native methods
    res.statusCode = status || 302;
    res.setHeader('Location', url);
    res.setHeader('Content-Length', '0');
    res.end();
  }
};

/**
 * Pass without making a success or fail decision.
 *
 * Under most circumstances, Strategies should not need to call this function.
 * It exists primarily to allow previous authentication state to be restored,
 * for example from an HTTP session.
 *
 * @api public
 */
actions.pass = function() {
  if (this.next) {
    this.next();
  }
};

/**
 * Internal error while performing authentication.
 *
 * Strategies should call this function when an internal error occurs during the
 * process of performing authentication; for example, if the user directory is
 * not available.
 *
 * @param {Error} err
 * @api public
 */
actions.error = function(err) {
  if (this.next) {
    this.next(err);
  } else {
    debug(JSON.stringify(err));
    throw err;
  }
};
<commit_msg>Update actions' description.<commit_after>var debug = require('debug')('kaching');

/**
 * Export actions prototype for strategies operating within an HTTP context.
 */
var actions = module.exports = {};

/**
 * Redirect to `url` with optional `status`, defaulting to 302.
 *
 * Strategies should call this function to redirect the user (via their user
 * agent) to a third-party website to continue the process.
 *
 * @param {String} url
 * @param {Number} status
 * @api public
 */
actions.redirect = function(url, status) {
  var res = this.res;
  if (typeof res.redirect == 'function') {
    // If possible use redirect method on the response
    // Assume Express API, optional status param comes first
    if (status) {
      res.redirect(status, url);
    } else {
      res.redirect(url);
    }
  } else {
    // Otherwise fall back to native methods
    res.statusCode = status || 302;
    res.setHeader('Location', url);
    res.setHeader('Content-Length', '0');
    res.end();
  }
};

/**
 * Pass to next request handler.
 *
 * Strategies should call this function when all the jobs has been completed,
 * and want to give control to the following up request handler. Mostly used
 * in middlewares.
 *
 * @api public
 */
actions.pass = function() {
  if (this.next) {
    this.next();
  }
};

/**
 * Internal error.
 *
 * Strategies should call this function when an internal error occurs during the
 * process. For example, paypal return 400 bad request.
 *
 * @param {Error} err
 * @api public
 */
actions.error = function(err) {
  if (this.next) {
    this.next(err);
  } else {
    debug(JSON.stringify(err));
    throw err;
  }
};
<|endoftext|>


<commit_before>/**
 * Created by yfyuan on 2016/10/28.
 */
'use strict';
cBoard.service('chartService', function ($q, dataService, chartPieService, chartLineService, chartFunnelService,
                                         chartSankeyService, chartTableService, chartKpiService, chartRadarService,
                                         chartMapService, chartScatterService, chartGaugeService, chartWordCloudService,
                                         chartTreeMapService ) {

        this.render = function (containerDom, widget, optionFilter, scope, reload, persist) {
            var deferred = $q.defer();
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                try {
                    var option = chart.parseOption(data);
                    if (optionFilter) {
                        optionFilter(option);
                    }
                    if (data.drill) {
                        data.drill.drillDown = function (id, value, render) {
                            dataService.getDrillPath(widget.datasetId, id).then(function (path) {
                                var i = 0;
                                _.each(path, function (e, _i) {
                                    if (e.id == id) {
                                        i = _i;
                                    }
                                });
                                var node = path[++i];
                                _.find(widget.config.keys, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.keys, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.keys.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                _.find(widget.config.groups, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.groups, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.groups.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                    var option = chart.parseOption(data);
                                    if (optionFilter) {
                                        optionFilter(option);
                                    }
                                    render(option, data.drill.config);
                                });
                            });
                        };
                        data.drill.drillUp = function (id, render) {
                            _.find(widget.config.keys, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.keys[_i - 1].values = [];
                                    widget.config.keys.splice(_i, 1);
                                    return true;
                                }
                            });
                            _.find(widget.config.groups, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.groups[_i - 1].values = [];
                                    widget.config.groups.splice(_i, 1);
                                    return true;
                                }
                            });
                            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                var option = chart.parseOption(data);
                                if (optionFilter) {
                                    optionFilter(option);
                                }
                                render(option, data.drill.config);
                            });
                        };
                    }
                } finally {
                    deferred.resolve(chart.render(containerDom, option, scope, persist, data.drill));
                }
            }, reload);
            return deferred.promise;
        };

        this.realTimeRender = function (realTimeTicket, widget, optionFilter, scope) {
            if (!realTimeTicket) {
                return;
            }
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                var option = chart.parseOption(data);
                if (optionFilter) {
                    optionFilter(option);
                }
                realTimeTicket(option, data.drill.config);
            });
        };

        var getChartServices = function (chartConfig) {
            var chart;
            switch (chartConfig.chart_type) {
                case 'line':
                    chart = chartLineService;
                    break;
                case 'pie':
                    chart = chartPieService;
                    break;
                case 'kpi':
                    chart = chartKpiService;
                    break;
                case 'table':
                    chart = chartTableService;
                    break;
                case 'funnel':
                    chart = chartFunnelService;
                    break;
                case 'sankey':
                    chart = chartSankeyService;
                    break;
                case 'radar':
                    chart = chartRadarService;
                    break;
                case 'map':
                    chart = chartMapService;
                    break;
                case 'scatter':
                    chart = chartScatterService;
                    break;
                case 'gauge':
                    chart = chartGaugeService;
                    break;
                case 'wordCloud':
                    chart = chartWordCloudService;
                    break;
                case 'treeMap':
                chart = chartTreeMapService;
                break;
            }
            return chart;
        };

    }
);<commit_msg>update<commit_after>/**
 * Created by yfyuan on 2016/10/28.
 */
'use strict';
cBoard.service('chartService', function ($q, dataService, chartPieService, chartLineService, chartFunnelService,
                                         chartSankeyService, chartTableService, chartKpiService, chartRadarService,
                                         chartMapService, chartScatterService, chartGaugeService, chartWordCloudService,
                                         chartTreeMapService ) {

        this.render = function (containerDom, widget, optionFilter, scope, reload, persist) {
            var deferred = $q.defer();
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                try {
                    var option = chart.parseOption(data);
                    if (optionFilter) {
                        optionFilter(option);
                    }
                    if (data.drill) {
                        data.drill.drillDown = function (id, value, render) {
                            dataService.getDrillPath(widget.datasetId, id).then(function (path) {
                                var i = 0;
                                _.each(path, function (e, _i) {
                                    if (e.id == id) {
                                        i = _i;
                                    }
                                });
                                var node = path[++i];
                                _.find(widget.config.keys, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.keys, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.keys.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                _.find(widget.config.groups, function (e, _i) {
                                    if (e.id == id) {
                                        e.type = '=';
                                        e.values = [value];
                                        if (!_.find(widget.config.groups, function (e) {
                                                return e.id == node.id;
                                            })) {
                                            widget.config.groups.splice(_i + 1, 0, node);
                                        }
                                        return true;
                                    }
                                });
                                dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                    var option = chart.parseOption(data);
                                    if (optionFilter) {
                                        optionFilter(option);
                                    }
                                    render(option, data.drill.config);
                                });
                            });
                        };
                        data.drill.drillUp = function (id, render) {
                            _.find(widget.config.keys, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.keys[_i - 1].values = [];
                                    widget.config.keys.splice(_i, 1);
                                    return true;
                                }
                            });
                            _.find(widget.config.groups, function (e, _i) {
                                if (e.id == id) {
                                    widget.config.groups[_i - 1].values = [];
                                    widget.config.groups.splice(_i, 1);
                                    return true;
                                }
                            });
                            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                                var option = chart.parseOption(data);
                                if (optionFilter) {
                                    optionFilter(option);
                                }
                                render(option, data.drill.config);
                            });
                        };
                    }
                } finally {
                    deferred.resolve(chart.render(containerDom, option, scope, persist, data.drill));
                }
            }, reload);
            return deferred.promise;
        };

        this.realTimeRender = function (realTimeTicket, widget, optionFilter, scope) {
            if (!realTimeTicket) {
                return;
            }
            var chart = getChartServices(widget.config);
            dataService.getDataSeries(widget.datasource, widget.query, widget.datasetId, widget.config, function (data) {
                var option = chart.parseOption(data);
                if (optionFilter) {
                    optionFilter(option);
                }
                realTimeTicket(option, data.drill.config);
            });
        };

        var getChartServices = function (chartConfig) {
            var chart;
            switch (chartConfig.chart_type) {
                case 'line':
                    chart = chartLineService;
                    break;
                case 'pie':
                    chart = chartPieService;
                    break;
                case 'kpi':
                    chart = chartKpiService;
                    break;
                case 'table':
                    chart = chartTableService;
                    break;
                case 'funnel':
                    chart = chartFunnelService;
                    break;
                case 'sankey':
                    chart = chartSankeyService;
                    break;
                case 'radar':
                    chart = chartRadarService;
                    break;
                case 'map':
                    chart = chartMapService;
                    break;
                case 'scatter':
                    chart = chartScatterService;
                    break;
                case 'gauge':
                    chart = chartGaugeService;
                    break;
                case 'wordCloud':
                    chart = chartWordCloudService;
                    break;
                case 'treeMap':
                    chart = chartTreeMapService;
                    break;
            }
            return chart;
        };

    }
);<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
var CopyWebpackPlugin = (CopyWebpackPlugin = require('copy-webpack-plugin'), CopyWebpackPlugin.default || CopyWebpackPlugin);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/*
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/'
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * Cache generated modules and chunks to improve performance for multiple incremental builds.
   * This is enabled by default in watch mode.
   * You can pass false to disable it.
   *
   * See: http://webpack.github.io/docs/configuration.html#cache
   */
   //cache: false,

  /*
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts'

  },

  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules'],

    alias: {
      // legacy imports pre-rc releases
      'angular2': helpers.root('node_modules/@angularclass/angular2-beta-to-rc-alias/dist/beta-17')
    },

  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
       // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular'),
        ]
      }

    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

      /*
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      /*
       * Raw loader support for *.css files
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      }

    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /*
     * Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurenceOrderPlugin(true),

    /*
     * Plugin: CommonsChunkPlugin
     * Description: Shares common code between the pages.
     * It identifies common modules and put them into a commons chunk.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
     * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
     */
    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'static'
    }]),

    /*
     * Plugin: HtmlWebpackPlugin
     * Description: Simplifies creation of HTML files to serve your webpack bundles.
     * This is especially useful for webpack bundles that include a hash in the filename
     * which changes every compilation.
     *
     * See: https://github.com/ampedandwired/html-webpack-plugin
     */
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    })

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<commit_msg>Changing assets folder to static to copy over dev resources<commit_after>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
var CopyWebpackPlugin = (CopyWebpackPlugin = require('copy-webpack-plugin'), CopyWebpackPlugin.default || CopyWebpackPlugin);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/*
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/'
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * Cache generated modules and chunks to improve performance for multiple incremental builds.
   * This is enabled by default in watch mode.
   * You can pass false to disable it.
   *
   * See: http://webpack.github.io/docs/configuration.html#cache
   */
   //cache: false,

  /*
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts'

  },

  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules'],

    alias: {
      // legacy imports pre-rc releases
      'angular2': helpers.root('node_modules/@angularclass/angular2-beta-to-rc-alias/dist/beta-17')
    },

  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
       // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular'),
        ]
      }

    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
     * This means they are not resolved relative to the configuration file.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

      /*
       * Json loader support for *.json files.
       *
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      /*
       * Raw loader support for *.css files
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      }

    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /*
     * Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurenceOrderPlugin(true),

    /*
     * Plugin: CommonsChunkPlugin
     * Description: Shares common code between the pages.
     * It identifies common modules and put them into a commons chunk.
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
     * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
     */
    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: 'src/static',
      to: 'static'
    }]),

    /*
     * Plugin: HtmlWebpackPlugin
     * Description: Simplifies creation of HTML files to serve your webpack bundles.
     * This is especially useful for webpack bundles that include a hash in the filename
     * which changes every compilation.
     *
     * See: https://github.com/ampedandwired/html-webpack-plugin
     */
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    })

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<|endoftext|>


<commit_before>'use strict';

const webpack           = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const conf              = require('./conf');

module.exports = {
    entry: {
        'app'   : './src/bootstrap.ts',
        'vendor': './src/vendor.ts'
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test   : /\.ts$/,
                loaders: [
                    {
                        loader : 'awesome-typescript-loader',
                        options: {configFileName: conf.dir.fromRoot('tsconfig.json')}
                    },
                    'angular2-template-loader'
                ]
            }, {
                test   : /\.s[ac]ss$/,
                use    : [
                    {loader: 'to-string-loader'}, // creates JS strings
                    {loader: 'css-loader', options: {sourceMap: true}}, // translates CSS into CommonJS Modules
                    {loader: 'sass-loader', options: {sourceMap: true}} // compiles Sass to CSS
                ],
                exclude: [conf.dir.fromRoot('src/scss')],
                include: [conf.dir.fromRoot('src/app')]
            }, {
                test   : /\.s[ac]ss$/,
                use    : [
                    {loader: 'style-loader'}, // creates style nodes
                    {loader: 'css-loader', options: {sourceMap: true}}, // translates CSS into CommonJS Modules
                    {loader: 'sass-loader', options: {sourceMap: true}} // compiles Sass to CSS
                ],
                exclude: [conf.dir.fromRoot('src/app')],
                include: [conf.dir.fromRoot('src/scss')]
            }, {
                test  : /\.html$/,
                loader: 'html-loader'
            }, {
                test  : /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            }, {
                test   : /\.css$/,
                exclude: conf.dir.fromRoot('app/app'),
                loader : ExtractTextPlugin.extract({fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap'})
            }, {
                test   : /\.css$/,
                include: conf.dir.fromRoot('app/app'),
                loader : 'raw-loader'
            }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/, // The (\\|\/) piece accounts for path separators in *nix and Windows
            conf.dir.fromRoot('src'), // location of your app
            {} // a map of your routes
        ),

        new webpack.optimize.CommonsChunkPlugin({
            name: ['app']
        }),

        new HtmlWebpackPlugin({
            template: 'public/index.html'
        }),

        new CopyWebpackPlugin([{
            from: 'public/assets',
            to  : 'assets'
        }])
    ]
};
<commit_msg>chore(sass): used webpacks ExtractTextPlugin to not remove css content required from src/scss from the js bundle, and place it in a css file<commit_after>'use strict';

const webpack           = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const conf              = require('./conf');

module.exports = {
    entry: {
        'app': './src/bootstrap.ts'
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test   : /\.ts$/,
                loaders: [
                    {
                        loader : 'awesome-typescript-loader',
                        options: {configFileName: conf.dir.fromRoot('tsconfig.json')}
                    },
                    'angular2-template-loader'
                ]
            }, {
                test   : /\.s[ac]ss$/,
                use    : [
                    {loader: 'to-string-loader'}, // creates JS strings
                    {loader: 'css-loader', options: {sourceMap: true}}, // translates CSS into CommonJS Modules
                    {loader: 'sass-loader', options: {sourceMap: true}} // compiles Sass to CSS
                ],
                exclude: [conf.dir.fromRoot('src/scss')],
                include: [conf.dir.fromRoot('src/app')]
            }, {
                test   : /\.s[ac]ss$/,
                loader : ExtractTextPlugin.extract([
                    {loader: 'css-loader', options: {sourceMap: true}}, // translates CSS into CommonJS Modules
                    {loader: 'sass-loader', options: {sourceMap: true}} // compiles Sass to CSS
                ]),
                exclude: [conf.dir.fromRoot('src/app')],
                include: [conf.dir.fromRoot('src/scss')]
            }, {
                test  : /\.html$/,
                loader: 'html-loader'
            }, {
                test  : /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            }, {
                test   : /\.css$/,
                exclude: conf.dir.fromRoot('app/app'),
                loader : ExtractTextPlugin.extract({fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap'})
            }, {
                test   : /\.css$/,
                include: conf.dir.fromRoot('app/app'),
                loader : 'raw-loader'
            }
        ]
    },

    plugins: [
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            /angular(\\|\/)core(\\|\/)@angular/, // The (\\|\/) piece accounts for path separators in *nix and Windows
            conf.dir.fromRoot('src'), // location of your app
            {} // a map of your routes
        ),

        new webpack.optimize.CommonsChunkPlugin({
            name: ['app']
        }),

        new HtmlWebpackPlugin({
            template: 'public/index.html'
        }),

        new CopyWebpackPlugin([{
            from: 'public/assets',
            to  : 'assets'
        }])
    ]
};
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');

/**
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular 2 pro starter With Webpack by @luchillo',
  name: 'Ng2Pro',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'vendor':    './src/vendor.browser.ts',
      'main':      './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          use: [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader',
            'angular-router-loader'
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },
        /**
         * Scss loader support for *.scss files.
         *
         * See: https://github.com/jtangelder/sass-loader
         */
        {
          test: /\.scss$/,
          use: [
            // ExtractTextPlugin.extract("style", "css?sourceMap"),
            'to-string-loader',
            'css-loader',
            'resolve-url-loader',
            {
              loader: "sass-loader",
              query: {
                includePaths: [
                  helpers.root('src'),
                  helpers.root('node_modules'),
                ],
              },
            },
          ]
        },

        /*
         * To string and css loader support for *.css files
         * Returns file content as string
         *
         * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
         * See: https://github.com/angular/angular/issues/11580
         * See: https://github.com/gajus/to-string-loader
         * See: https://github.com/webpack/css-loader
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader']
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /**
         * Url loader support for png|jpg|gif
         *
         * See: https://www.npmjs.com/package/url-loader
         */
        {
          test: /\.(png|jpg|gif)$/,
          use: "url?limit=50000&name=[path][name].[ext]"
        },

        /**
         * Font loader support for fonts necesary for FontAwesome
         * Fonts handled by next 2 loaders are ttf|eot|otf|svg|woff|woff2
         *
         * See: https://www.npmjs.com/package/url-loader
         */
        {
          test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/,
          use: "url-loader?limit=10000&name=fonts/[name].[ext]"
        },
        {
          test: /\.(ttf|eot|otf|svg)(\?v=\d+\.\d+\.\d+)?$/,
          use: "file-loader?name=fonts/[name].[ext]"
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new OfflinePlugin(),

      /**
       * Plugin: WebpackBuildNotifierPlugin
       * Description: Desk notifications in upper right corner of screen
       *
       * See: https://www.npmjs.com/package/webpack-build-notifier
       */
      new WebpackBuildNotifierPlugin({
        title: 'TAO WEB'
        // logo: 'public/dist/img/favicon.ico'
      }),

      new ProgressBarPlugin()
    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}

<commit_msg>Change query for options<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');

/**
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular 2 pro starter With Webpack by @luchillo',
  name: 'Ng2Pro',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'vendor':    './src/vendor.browser.ts',
      'main':      './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          use: [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader',
            'angular-router-loader'
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },
        /**
         * Scss loader support for *.scss files.
         *
         * See: https://github.com/jtangelder/sass-loader
         * See issue: https://github.com/webpack/webpack/issues/3060#issuecomment-249382018
         */
        {
          test: /\.scss$/,
          use: [
            // ExtractTextPlugin.extract("style", "css?sourceMap"),
            'to-string-loader',
            'css-loader',
            'resolve-url-loader',
            {
              loader: "sass-loader",
              options: {
                includePaths: [
                  helpers.root('src'),
                  helpers.root('node_modules'),
                ],
              },
            },
          ]
        },

        /*
         * To string and css loader support for *.css files
         * Returns file content as string
         *
         * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
         * See: https://github.com/angular/angular/issues/11580
         * See: https://github.com/gajus/to-string-loader
         * See: https://github.com/webpack/css-loader
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader']
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /**
         * Url loader support for png|jpg|gif
         *
         * See: https://www.npmjs.com/package/url-loader
         */
        {
          test: /\.(png|jpg|gif)$/,
          use: "url?limit=50000&name=[path][name].[ext]"
        },

        /**
         * Font loader support for fonts necesary for FontAwesome
         * Fonts handled by next 2 loaders are ttf|eot|otf|svg|woff|woff2
         *
         * See: https://www.npmjs.com/package/url-loader
         */
        {
          test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/,
          use: "url-loader?limit=10000&name=fonts/[name].[ext]"
        },
        {
          test: /\.(ttf|eot|otf|svg)(\?v=\d+\.\d+\.\d+)?$/,
          use: "file-loader?name=fonts/[name].[ext]"
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new OfflinePlugin(),

      /**
       * Plugin: WebpackBuildNotifierPlugin
       * Description: Desk notifications in upper right corner of screen
       *
       * See: https://www.npmjs.com/package/webpack-build-notifier
       */
      new WebpackBuildNotifierPlugin({
        title: 'TAO WEB'
        // logo: 'public/dist/img/favicon.ico'
      }),

      new ProgressBarPlugin()
    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}

<|endoftext|>


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

// Webpack and third party plugins.
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AutoPrefixerPlugin = require('autoprefixer-core');
var ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');

// Environment detection.
var node_env = process.env.NODE_ENV || 'development';

/*
 Configuration settings
 ------------------------------------------------------------------------------
 */

// Where is your project located relative to this config?
var context = path.join(__dirname, '..');

// Where are your source assets located?
var rootAssetPath = './catwatch/assets';
var contextRoot = path.join(context, rootAssetPath);

// Where will the files get built to?
var buildOutputPath = './build/public';

// How should certain asset types be configured?
var assets = {
    fonts: {
        path: 'fonts',
        filename: '[path][name].[hash].[ext]'
    },
    images: {
        path: 'images',
        filename: '[path][name].[hash].[ext]'
    },
    scripts: {
        path: 'scripts',
        filename: '[name].[chunkhash].js',
        chunkFilename: '[id].[chunkhash].js'
    },
    styles: {
        path: 'styles',
        filename: '[name].[chunkhash].css'
    }
};

// Which top level JS and CSS files should get output?
var chunks = {
    app_js: [
        path.join(contextRoot, assets.scripts.path, 'entry.js')
    ],
    app_css: [
        path.join(contextRoot, assets.styles.path, 'default.scss')
    ],
    vendor_js: ['bootstrap-sass', 'moment', 'rome'],
    vendor_css: [
         // Bootstrap configuration settings:
        // https://gist.github.com/anonymous/ef4593b01915d647ed88
        // http://getbootstrap.com/customize/?id=ef4593b01915d647ed88
        path.join(contextRoot, assets.styles.path,
        'vendor', 'bootstrap.3.3.5.min.css'),
        path.join(contextRoot, assets.styles.path,
        'vendor', 'font-awesome.4.3.0.css'),
        path.join(contextRoot, assets.styles.path,
        'vendor', 'rome.2.1.17.css')
    ]
};

// Avoid parsing this code to speed up rebuilds.
var noParse = [
    path.join(contextRoot, assets.styles.path, 'vendor')
];

// Where will assets get served in development mode? This depends on running
// the webpack dev server.
var publicPath = process.env.PUBLIC_PATH || 'http://localhost:2992/assets/';

/*
 Do not edit past this line unless you are tinkering with webpack.
 ------------------------------------------------------------------------------
 */

// Plugins that will load in all environments.
var plugins = [
    // http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
    new webpack.NoErrorsPlugin(),

    // http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    new webpack.optimize.CommonsChunkPlugin('vendor_js', 'vendor_js.js'),

    // https://github.com/webpack/extract-text-webpack-plugin
    new ExtractTextPlugin(assets.styles.filename),

    // https://github.com/nickjj/manifest-revision-webpack-plugin
    new ManifestRevisionPlugin(path.join('build', 'manifest.json'), {
        rootAssetPath: rootAssetPath,
        ignorePaths: ['/fonts', '/styles', '/scripts']
    })
];

// Development environment only plugins.
if (node_env !== 'development') {
    var developmentPlugins = [
        // http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
        new webpack.optimize.UglifyJsPlugin({compressor: {warnings: false}}),

        // http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
        new webpack.optimize.DedupePlugin()
    ];

    plugins.push(developmentPlugins[0])
}

module.exports = {
    context: path.join(__dirname, '../'),
    entry: chunks,
    output: {
        path: buildOutputPath,
        publicPath: publicPath,
        filename: assets.scripts.filename,
        chunkFilename: assets.scripts.chunkFilename
    },
    resolve: {
        // Allow requiring files without supplying the extension.
        extensions: ['', '.js', '.scss']
    },
    module: {
        noParse: noParse,
        loaders: [
            {
                test: /\.js$/i, loader: 'babel-loader?stage=0',
                exclude: /node_modules/
            },
            {
                test: /\.s?css$/i,
                loader: ExtractTextPlugin.extract('style-loader',
                    'css-loader!postcss-loader!sass-loader?includePaths[]=' + path.join(contextRoot, assets.styles.path))
            },
            {
                test: /\.(jpe?g|png|gif|svg([\?]?.*))$/i,
                loaders: [
                    'file?context=' + rootAssetPath + '&name=' + assets.images.filename,
                    'image?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            },
            {
                test: /\.(woff([\?]?.*)|woff2([\?]?.*))$/i,
                loader: 'url-loader?limit=100000'
            },
            {
                test: /\.(ttf([\?]?.*)|eot([\?]?.*))$/i,
                loader: 'file-loader?context=' + rootAssetPath + '&name=' + assets.fonts.filename
            }
        ]
    },
    plugins: plugins,
    postcss: [AutoPrefixerPlugin()]
};
<commit_msg>Fix styling in the webpack config<commit_after>var fs = require('fs');
var path = require('path');

// Webpack and third party plugins.
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var AutoPrefixerPlugin = require('autoprefixer-core');
var ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');

// Environment detection.
var node_env = process.env.NODE_ENV || 'development';

/*
 Configuration settings
 ------------------------------------------------------------------------------
 */

// Where is your project located relative to this config?
var context = path.join(__dirname, '..');

// Where are your source assets located?
var rootAssetPath = './catwatch/assets';
var contextRoot = path.join(context, rootAssetPath);

// Where will the files get built to?
var buildOutputPath = './build/public';

// How should certain asset types be configured?
var assets = {
    fonts: {
        path: 'fonts',
        filename: '[path][name].[hash].[ext]'
    },
    images: {
        path: 'images',
        filename: '[path][name].[hash].[ext]'
    },
    scripts: {
        path: 'scripts',
        filename: '[name].[chunkhash].js',
        chunkFilename: '[id].[chunkhash].js'
    },
    styles: {
        path: 'styles',
        filename: '[name].[chunkhash].css'
    }
};

// Which top level JS and CSS files should get output?
var chunks = {
    app_js: [
        path.join(contextRoot, assets.scripts.path, 'entry.js')
    ],
    app_css: [
        path.join(contextRoot, assets.styles.path, 'default.scss')
    ],
    vendor_js: ['bootstrap-sass', 'moment', 'rome'],
    vendor_css: [
        // Bootstrap configuration settings:
        // https://gist.github.com/anonymous/ef4593b01915d647ed88
        // http://getbootstrap.com/customize/?id=ef4593b01915d647ed88
        path.join(contextRoot, assets.styles.path,
            'vendor', 'bootstrap.3.3.5.min.css'),
        path.join(contextRoot, assets.styles.path,
            'vendor', 'font-awesome.4.3.0.css'),
        path.join(contextRoot, assets.styles.path,
            'vendor', 'rome.2.1.17.css')
    ]
};

// Avoid parsing this code to speed up rebuilds.
var noParse = [
    path.join(contextRoot, assets.styles.path, 'vendor')
];

// Where will assets get served in development mode? This depends on running
// the webpack dev server.
var publicPath = process.env.PUBLIC_PATH || 'http://localhost:2992/assets/';

/*
 Do not edit past this line unless you are tinkering with webpack.
 ------------------------------------------------------------------------------
 */

// Plugins that will load in all environments.
var plugins = [
    // http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
    new webpack.NoErrorsPlugin(),

    // http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    new webpack.optimize.CommonsChunkPlugin('vendor_js', 'vendor_js.js'),

    // https://github.com/webpack/extract-text-webpack-plugin
    new ExtractTextPlugin(assets.styles.filename),

    // https://github.com/nickjj/manifest-revision-webpack-plugin
    new ManifestRevisionPlugin(path.join('build', 'manifest.json'), {
        rootAssetPath: rootAssetPath,
        ignorePaths: ['/fonts', '/styles', '/scripts']
    })
];

// Development environment only plugins.
if (node_env !== 'development') {
    var developmentPlugins = [
        // http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
        new webpack.optimize.UglifyJsPlugin({compressor: {warnings: false}}),

        // http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
        new webpack.optimize.DedupePlugin()
    ];

    plugins.push(developmentPlugins[0])
}

module.exports = {
    context: path.join(__dirname, '../'),
    entry: chunks,
    output: {
        path: buildOutputPath,
        publicPath: publicPath,
        filename: assets.scripts.filename,
        chunkFilename: assets.scripts.chunkFilename
    },
    resolve: {
        // Allow requiring files without supplying the extension.
        extensions: ['', '.js', '.scss']
    },
    module: {
        noParse: noParse,
        loaders: [
            {
                test: /\.js$/i, loader: 'babel-loader?stage=0',
                exclude: /node_modules/
            },
            {
                test: /\.s?css$/i,
                loader: ExtractTextPlugin.extract('style-loader',
                    'css-loader!postcss-loader!sass-loader?includePaths[]=' + path.join(contextRoot, assets.styles.path))
            },
            {
                test: /\.(jpe?g|png|gif|svg([\?]?.*))$/i,
                loaders: [
                    'file?context=' + rootAssetPath + '&name=' + assets.images.filename,
                    'image?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            },
            {
                test: /\.(woff([\?]?.*)|woff2([\?]?.*))$/i,
                loader: 'url-loader?limit=100000'
            },
            {
                test: /\.(ttf([\?]?.*)|eot([\?]?.*))$/i,
                loader: 'file-loader?context=' + rootAssetPath + '&name=' + assets.fonts.filename
            }
        ]
    },
    plugins: plugins,
    postcss: [AutoPrefixerPlugin()]
};
<|endoftext|>


<commit_before>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import React, {Component, PropTypes} from 'react';
import {MySearchApi} from '../../api/search';
import {parseMetadata} from '../../services/metadata-parser';
import HomeHeader from './HomeHeader';
import EntityCard from '../EntityCard';
import Store from 'services/store/store.js';
import T from 'i18n-react';
const shortid = require('shortid');
const classNames = require('classnames');
require('./Home.less');

const defaultFilter = ['app', 'dataset', 'stream'];

class Home extends Component {
  constructor(props) {
    super(props);
    this.filterOptions = [
      {
        displayName: T.translate('commons.entity.application.plural'),
        id: 'app'
      },
      {
        displayName: T.translate('commons.entity.artifact.plural'),
        id: 'artifact'
      },
      {
        displayName: T.translate('commons.entity.dataset.plural'),
        id: 'dataset'
      },
      {
        displayName: T.translate('commons.entity.stream.plural'),
        id: 'stream'
      }
    ];
    this.sortOptions = [
      {
        displayName: T.translate('features.Home.Header.sortOptions.nameAsc.displayName'),
        sort: T.translate('features.Home.Header.sortOptions.nameAsc.sortField'),
        order: T.translate('features.Home.Header.sortOptions.nameAsc.sortOrder'),
        fullSort: T.translate('features.Home.Header.sortOptions.nameAsc.fullSort')
      },
      {
        displayName: T.translate('features.Home.Header.sortOptions.nameDesc.displayName'),
        sort: T.translate('features.Home.Header.sortOptions.nameDesc.sortField'),
        order: T.translate('features.Home.Header.sortOptions.nameDesc.sortOrder'),
        fullSort: T.translate('features.Home.Header.sortOptions.nameDesc.fullSort')
      }
    ];
    this.state = {
      filter: defaultFilter,
      sortObj: this.sortOptions[0],
      query: '',
      entities: [],
      selectedEntity: null,
      loading: true
    };
    this.updateQueryString = this.updateQueryString.bind(this);
    this.getQueryObject = this.getQueryObject.bind(this);
  }
  componentWillReceiveProps(nextProps) {
    this.search(this.state.query, this.state.filter, this.state.sortObj, nextProps.params.namespace);
  }

  //Update Store and State to correspond to query parameters before component renders
  componentWillMount() {
    Store.dispatch({
      type: 'SELECT_NAMESPACE',
      payload: {
        selectedNamespace: this.props.params.namespace
      }
    });

    let queryObject = this.getQueryObject();
    this.setState({
      filter: queryObject.filter,
      sortObj: queryObject.sort,
      query: queryObject.query
    });
  }

  //Retrieve entities for rendering
  componentDidMount(){
    this.search();
  }

  //Construct and return query object from query parameters
  getQueryObject() {
    let filters = '';
    let sortBy = '';
    let orderBy = '';
    let searchTerm = '';
    let sortOption = '';
    let query = this.props.location.query;

    //Get filters, order, sort, search from query
    if(query){
      orderBy = typeof query.order === 'string' ? query.order : '';
      sortBy = typeof query.sort === 'string' ? query.sort : '';
      searchTerm = typeof query.q === 'string' ? query.q : '';
      if(typeof query.filter === 'string'){
        filters = [query.filter];
      } else if(Array.isArray(query.filter)){
        filters = query.filter;
      }
    }

    //Ensure sort combination is valid
    sortOption = this.sortOptions.filter((option) => {
      return ( sortBy === option.sort && orderBy === option.order);
    });

    //If query parameters are valid return those else return the current state's parameters
    return ({
      'query' : searchTerm ? searchTerm : this.state.query,
      'sort' : sortOption.length === 0 ? this.state.sortObj : sortOption[0],
      'filter' : filters ? filters : this.state.filter
    });
  }

  search(
    query = this.state.query,
    filter = this.state.filter,
    sortObj = this.state.sortObj,
    namespace = this.props.params.namespace
  ) {
    //No entity types requested - set state and return
    if (filter.length === 0) {
      this.setState({query, filter, sortObj, entities: [], selectedEntity: null, loading: false});
      return;
    }

    this.setState({loading: true});

    let params = {
      namespace: namespace,
      query: `${query}*`,
      target: filter,
      sort: sortObj.fullSort
    };

    MySearchApi.search(params)
      .map((res) => {
        return res.results
          .map(parseMetadata)
          .map((entity) => {
            entity.uniqueId = shortid.generate();
            return entity;
          })
          .filter((entity) => entity.id.charAt(0) !== '_');
      })
      .subscribe((res) => {
        this.setState({query, filter, sortObj, entities: res, selectedEntity: null, loading: false});
      });
  }

  handleFilterClick(option) {
    let filters = [...this.state.filter];
    if (this.state.filter.includes(option.id)) {
      let index = filters.indexOf(option.id);
      filters.splice(index, 1);
    } else {
      filters.push(option.id);
    }

    this.setState({
      filter : filters
    });

    this.search(this.state.query, filters, this.state.sortObj);
  }

  handleSortClick(option) {
    this.setState({
      sortObj : option
    });
    this.search(this.state.query, this.state.filter, option);
  }

  handleSearch(query) {
    this.search(query, this.state.filter, this.state.sortObj);
  }

  handleEntityClick(uniqueId) {
    this.setState({selectedEntity: uniqueId});
  }

  //Set query string using application state
  updateQueryString(){
    let queryString = '';
    let sort = '';
    let filter = '';
    let query = '';
    let queryParams = [];

    //Sort Params
    if(this.state.sortObj.sort){
      sort = 'sort=' + this.state.sortObj.sort + '&order=' + this.state.sortObj.order;
    }

    //Filter Params
    if(this.state.filter.length === 1){
      filter = 'filter=' + this.state.filter[0];
    } else if (this.state.filter.length > 1){
      filter = 'filter=' + this.state.filter.join('&filter=');
    }

    //Search Param
    if(this.state.query.length > 0){
      query = 'q=' + this.state.query;
    }

    //Combine Query Parameters
    queryParams = [query, sort, filter].filter((element) => {
      return element.length > 0;
    });
    queryString = queryParams.join('&');

    if(queryString.length > 0){
      queryString = '?' + queryString;
    }

    let obj = {
      title: 'CDAP',
      url: location.pathname + queryString
    };

    history.pushState(obj, obj.title, obj.url);
  }

  render() {
    this.updateQueryString();

    const empty = (

        {T.translate('features.Home.emptyMessage')}

    );

    const loading = (

    );

    let entitiesToBeRendered;
    if(this.state.loading){
      entitiesToBeRendered = loading;
    } else if(this.state.entities.length === 0) {
      entitiesToBeRendered = empty;
    } else {
      entitiesToBeRendered = this.state.entities.map(
        (entity) => {
          return (

              <EntityCard
                entity={entity}
                onUpdate={this.search.bind(this)}
              />

          );
        }
      );
    }

    return (

        <HomeHeader
          filterOptions={this.filterOptions}
          onFilterClick={this.handleFilterClick.bind(this)}
          activeFilter={this.state.filter}
          sortOptions={this.sortOptions}
          activeSort={this.state.sortObj}
          onSortClick={this.handleSortClick.bind(this)}
          onSearch={this.handleSearch.bind(this)}
          searchText={this.state.query}
        />

          {entitiesToBeRendered}

    );
  }
}

Home.propTypes = {
  params: PropTypes.shape({
    namespace : PropTypes.string
  }),
  location: PropTypes.object,
  history: PropTypes.object
};

export default Home;
<commit_msg>default filters are applied when invalid params are supplied<commit_after>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import React, {Component, PropTypes} from 'react';
import {MySearchApi} from '../../api/search';
import {parseMetadata} from '../../services/metadata-parser';
import HomeHeader from './HomeHeader';
import EntityCard from '../EntityCard';
import Store from 'services/store/store.js';
import T from 'i18n-react';
const shortid = require('shortid');
const classNames = require('classnames');
require('./Home.less');

const defaultFilter = ['app', 'dataset', 'stream'];

class Home extends Component {
  constructor(props) {
    super(props);
    this.filterOptions = [
      {
        displayName: T.translate('commons.entity.application.plural'),
        id: 'app'
      },
      {
        displayName: T.translate('commons.entity.artifact.plural'),
        id: 'artifact'
      },
      {
        displayName: T.translate('commons.entity.dataset.plural'),
        id: 'dataset'
      },
      {
        displayName: T.translate('commons.entity.stream.plural'),
        id: 'stream'
      }
    ];

    //Accepted filter ids to be compared against incoming query parameters
    this.acceptedFilterIds = this.filterOptions.map( (item) => {
      return item.id;
    });

    this.sortOptions = [
      {
        displayName: T.translate('features.Home.Header.sortOptions.nameAsc.displayName'),
        sort: T.translate('features.Home.Header.sortOptions.nameAsc.sortField'),
        order: T.translate('features.Home.Header.sortOptions.nameAsc.sortOrder'),
        fullSort: T.translate('features.Home.Header.sortOptions.nameAsc.fullSort')
      },
      {
        displayName: T.translate('features.Home.Header.sortOptions.nameDesc.displayName'),
        sort: T.translate('features.Home.Header.sortOptions.nameDesc.sortField'),
        order: T.translate('features.Home.Header.sortOptions.nameDesc.sortOrder'),
        fullSort: T.translate('features.Home.Header.sortOptions.nameDesc.fullSort')
      }
    ];

    this.state = {
      filter: defaultFilter,
      sortObj: this.sortOptions[0],
      query: '',
      entities: [],
      selectedEntity: null,
      loading: true
    };
    this.updateQueryString = this.updateQueryString.bind(this);
    this.getQueryObject = this.getQueryObject.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    this.search(this.state.query, this.state.filter, this.state.sortObj, nextProps.params.namespace);
  }

  //Update Store and State to correspond to query parameters before component renders
  componentWillMount() {
    Store.dispatch({
      type: 'SELECT_NAMESPACE',
      payload: {
        selectedNamespace: this.props.params.namespace
      }
    });

    let queryObject = this.getQueryObject();

    this.setState({
      filter: queryObject.filter,
      sortObj: queryObject.sort,
      query: queryObject.query
    });
  }

  //Retrieve entities for rendering
  componentDidMount(){
    this.search();
  }

  //Construct and return query object from query parameters
  getQueryObject() {
    let sortBy = '';
    let orderBy = '';
    let searchTerm = '';
    let sortOption = '';
    let query = this.props.location.query;
    let filters = '';
    let verifiedFilters = null;
    let invalidFilter = false;

    //Get filters, order, sort, search from query
    if(query){
      orderBy = typeof query.order === 'string' ? query.order : '';
      sortBy = typeof query.sort === 'string' ? query.sort : '';
      searchTerm = typeof query.q === 'string' ? query.q : '';
      if(typeof query.filter === 'string'){
        filters = [query.filter];
      } else if(Array.isArray(query.filter)){
        filters = query.filter;
      }
    }

    //Ensure sort parameters are valid
    sortOption = this.sortOptions.filter((option) => {
      return ( sortBy === option.sort && orderBy === option.order);
    });

    //Ensure filter parameters are valid
    if(filters.length > 0){
      verifiedFilters = filters.filter( (filterOption) => {
        if(this.acceptedFilterIds.indexOf(filterOption) !== -1){
          return true;
        } else {
          invalidFilter = true;
          return false;
        }
      });
    }

    //Ensure all defaults are applied if an invalid parameter is passed
    if(invalidFilter){
      defaultFilter.forEach(( option ) => {
        if(verifiedFilters.indexOf(option) === -1){
          verifiedFilters.push(option);
        }
      });
    }

    //Return valid query parameters or return current state values if query params are invalid
    return ({
      'query' : searchTerm ? searchTerm : this.state.query,
      'sort' : sortOption.length === 0 ? this.state.sortObj : sortOption[0],
      'filter' : verifiedFilters ? verifiedFilters : this.state.filter
    });
  }

  search(
    query = this.state.query,
    filter = this.state.filter,
    sortObj = this.state.sortObj,
    namespace = this.props.params.namespace
  ) {
    //No entity types requested - set state and return
    if (filter.length === 0) {
      this.setState({query, filter, sortObj, entities: [], selectedEntity: null, loading: false});
      return;
    }

    this.setState({loading: true});

    let params = {
      namespace: namespace,
      query: `${query}*`,
      target: filter,
      sort: sortObj.fullSort
    };

    MySearchApi.search(params)
      .map((res) => {
        return res.results
          .map(parseMetadata)
          .map((entity) => {
            entity.uniqueId = shortid.generate();
            return entity;
          })
          .filter((entity) => entity.id.charAt(0) !== '_');
      })
      .subscribe((res) => {
        this.setState({query, filter, sortObj, entities: res, selectedEntity: null, loading: false});
      });
  }

  handleFilterClick(option) {
    let filters = [...this.state.filter];
    if (this.state.filter.includes(option.id)) {
      let index = filters.indexOf(option.id);
      filters.splice(index, 1);
    } else {
      filters.push(option.id);
    }

    this.setState({
      filter : filters
    });

    this.search(this.state.query, filters, this.state.sortObj);
  }

  handleSortClick(option) {
    this.setState({
      sortObj : option
    });
    this.search(this.state.query, this.state.filter, option);
  }

  handleSearch(query) {
    this.search(query, this.state.filter, this.state.sortObj);
  }

  handleEntityClick(uniqueId) {
    this.setState({selectedEntity: uniqueId});
  }

  //Set query string using current application state
  updateQueryString(){
    let queryString = '';
    let sort = '';
    let filter = '';
    let query = '';
    let queryParams = [];

    //Generate sort params
    if(this.state.sortObj.sort){
      sort = 'sort=' + this.state.sortObj.sort + '&order=' + this.state.sortObj.order;
    }

    //Generate filter params
    if(this.state.filter.length === 1){
      filter = 'filter=' + this.state.filter[0];
    } else if (this.state.filter.length > 1){
      filter = 'filter=' + this.state.filter.join('&filter=');
    }

    //Generate search param
    if(this.state.query.length > 0){
      query = 'q=' + this.state.query;
    }

    //Combine query parameters into query string
    queryParams = [query, sort, filter].filter((element) => {
      return element.length > 0;
    });
    queryString = queryParams.join('&');

    if(queryString.length > 0){
      queryString = '?' + queryString;
    }

    let obj = {
      title: 'CDAP',
      url: location.pathname + queryString
    };

    //Modify URL to match application state
    history.pushState(obj, obj.title, obj.url);
  }

  render() {
    this.updateQueryString();

    const empty = (

        {T.translate('features.Home.emptyMessage')}

    );

    const loading = (

    );

    let entitiesToBeRendered;
    if(this.state.loading){
      entitiesToBeRendered = loading;
    } else if(this.state.entities.length === 0) {
      entitiesToBeRendered = empty;
    } else {
      entitiesToBeRendered = this.state.entities.map(
        (entity) => {
          return (

              <EntityCard
                entity={entity}
                onUpdate={this.search.bind(this)}
              />

          );
        }
      );
    }

    return (

        <HomeHeader
          filterOptions={this.filterOptions}
          onFilterClick={this.handleFilterClick.bind(this)}
          activeFilter={this.state.filter}
          sortOptions={this.sortOptions}
          activeSort={this.state.sortObj}
          onSortClick={this.handleSortClick.bind(this)}
          onSearch={this.handleSearch.bind(this)}
          searchText={this.state.query}
        />

          {entitiesToBeRendered}

    );
  }
}

Home.propTypes = {
  params: PropTypes.shape({
    namespace : PropTypes.string
  }),
  location: PropTypes.object,
  history: PropTypes.object
};

export default Home;
<|endoftext|>