<commit_before>/* liteUploader v2.1.2 | https://github.com/burt202/lite-uploader | Aaron Burtnyk (http://www.burtdev.net) */

$.fn.liteUploader = function (options) {
    var defaults = {
        script: null,
        rules: {
            allowedFileTypes: null,
            maxSize: null
        },
        params: {},
        changeHandler: true,
        clickElement: null
    };

    return this.each(function () {
        $.data(this, 'liteUploader', new LiteUploader(this, $.extend(defaults, options)));
    });
};

function LiteUploader (element, options) {
    this.el = $(element);
    this.options = options;
    this.params = options.params;
    this.xhr = this._buildXhrObject();

    this._init();
}

LiteUploader.prototype = {
    _init: function () {
        if (this.options.changeHandler) {
            this.el.change(function () {
                this._start();
            }.bind(this));
        }

        if (this.options.clickElement) {
            this.options.clickElement.click(function () {
                this._start();
            }.bind(this));
        }
    },

    _buildXhrObject: function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', this._onProgress.bind(this), false);
        return xhr;
    },

    _onProgress: function (evt) {
        if (evt.lengthComputable) {
            this.el.trigger('lu:progress', Math.floor((evt.loaded / evt.total) * 100));
        }
    },

    _start: function () {
        var files = this.el.get(0).files;
        var errors = this._getInputErrors(files);
        if (!errors) errors = this._getFileErrors(files);

        if (errors) {
            this.el.trigger('lu:errors', errors);
            this._resetInput();
        } else {
            this.el.trigger('lu:before', [files]);
            this._performUpload(this._collateFormData(files));
        }
    },

    _resetInput: function () {
        this.el.val('');
    },

    _getInputErrors: function (files) {
        var errors = [];
        var inputErrors = [];

        if (!this.el.attr('name')) {
            errors.push({
                type: 'fileInputNameRequired'
            });
        }

        if (!this.options.script) {
            errors.push({
                type: 'scriptOptionRequired'
            });
        }

        if (files.length === 0) {
            errors.push({
                type: 'noFilesSelected'
            });
        }

        inputErrors.push ({
            name: 'liteUploader_input',
            errors: errors
        });

        return (errors.length > 0) ? [inputErrors] : null;
    },

    _getFileErrors: function (files) {
        var errorsCount = 0;
        var fileErrors = [];

        $.each(files, function (i) {
            var errorsFound = this._findErrorsForFile(files[i]);

            fileErrors.push({
                name: files[i].name,
                errors: errorsFound
            });

            errorsCount += errorsFound.length;
        }.bind(this));

        return (errorsCount > 0) ? [fileErrors] : null;
    },

    _findErrorsForFile: function (file) {
        var errorsArray = [];

        $.each(this.options.rules, function (key, value) {
            if (key === 'allowedFileTypes' && value && $.inArray(file.type, value.split(',')) === -1) {
                errorsArray.push({
                    type: 'type',
                    rule: value,
                    given: file.type
                });
            }

            if (key === 'maxSize' && value && file.size > value) {
                errorsArray.push({
                    type: 'size',
                    rule: value,
                    given: file.size
                });
            }
        });

        return errorsArray;
    },

    _getFormDataObject: function () {
        return new FormData();
    },

    _collateFormData: function (files) {
        var formData = this._getFormDataObject();

        if (this.el.attr('id')) formData.append('liteUploader_id', this.el.attr('id'));

        $.each(this.params, function (key, value) {
            formData.append(key, value);
        });

        $.each(files, function (i) {
            formData.append(this.el.attr('name'), files[i]);
        }.bind(this));

        return formData;
    },

    _performUpload: function (formData) {
        $.ajax({
            xhr: function () {
                return this.xhr;
            }.bind(this),
            url: this.options.script,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false
        })
        .done(function (response) {
            this.el.trigger('lu:success', response);
        }.bind(this))
        .fail(function (jqXHR) {
            this.el.trigger('lu:fail', jqXHR);
        }.bind(this))
        .always(function () {
            this._resetInput();
        }.bind(this));
    },

    /* Public Methods */

    addParam: function (key, value) {
        this.params[key] = value;
    },

    cancelUpload: function () {
        this.xhr.abort();
        this.el.trigger('lu:cancelled');
        this._resetInput();
    }
};
<commit_msg>refactors xhr call so its more testable<commit_after>/* liteUploader v2.1.2 | https://github.com/burt202/lite-uploader | Aaron Burtnyk (http://www.burtdev.net) */

$.fn.liteUploader = function (options) {
    var defaults = {
        script: null,
        rules: {
            allowedFileTypes: null,
            maxSize: null
        },
        params: {},
        changeHandler: true,
        clickElement: null
    };

    return this.each(function () {
        $.data(this, 'liteUploader', new LiteUploader(this, $.extend(defaults, options)));
    });
};

function LiteUploader (element, options) {
    this.el = $(element);
    this.options = options;
    this.params = options.params;
    this.xhr = this._buildXhrObject();

    this._init();
}

LiteUploader.prototype = {
    _init: function () {
        if (this.options.changeHandler) {
            this.el.change(function () {
                this._start();
            }.bind(this));
        }

        if (this.options.clickElement) {
            this.options.clickElement.click(function () {
                this._start();
            }.bind(this));
        }
    },

    _start: function () {
        var files = this.el.get(0).files;
        var errors = this._getInputErrors(files);
        if (!errors) errors = this._getFileErrors(files);

        if (errors) {
            this.el.trigger('lu:errors', errors);
            this._resetInput();
        } else {
            this.el.trigger('lu:before', [files]);
            this._performUpload(this._collateFormData(files));
        }
    },

    _resetInput: function () {
        this.el.val('');
    },

    _getInputErrors: function (files) {
        var errors = [];
        var inputErrors = [];

        if (!this.el.attr('name')) {
            errors.push({
                type: 'fileInputNameRequired'
            });
        }

        if (!this.options.script) {
            errors.push({
                type: 'scriptOptionRequired'
            });
        }

        if (files.length === 0) {
            errors.push({
                type: 'noFilesSelected'
            });
        }

        inputErrors.push ({
            name: 'liteUploader_input',
            errors: errors
        });

        return (errors.length > 0) ? [inputErrors] : null;
    },

    _getFileErrors: function (files) {
        var errorsCount = 0;
        var fileErrors = [];

        $.each(files, function (i) {
            var errorsFound = this._findErrorsForFile(files[i]);

            fileErrors.push({
                name: files[i].name,
                errors: errorsFound
            });

            errorsCount += errorsFound.length;
        }.bind(this));

        return (errorsCount > 0) ? [fileErrors] : null;
    },

    _findErrorsForFile: function (file) {
        var errorsArray = [];

        $.each(this.options.rules, function (key, value) {
            if (key === 'allowedFileTypes' && value && $.inArray(file.type, value.split(',')) === -1) {
                errorsArray.push({
                    type: 'type',
                    rule: value,
                    given: file.type
                });
            }

            if (key === 'maxSize' && value && file.size > value) {
                errorsArray.push({
                    type: 'size',
                    rule: value,
                    given: file.size
                });
            }
        });

        return errorsArray;
    },

    _getFormDataObject: function () {
        return new FormData();
    },

    _collateFormData: function (files) {
        var formData = this._getFormDataObject();
        if (this.el.attr('id')) formData.append('liteUploader_id', this.el.attr('id'));

        $.each(this.params, function (key, value) {
            formData.append(key, value);
        });

        $.each(files, function (i) {
            formData.append(this.el.attr('name'), files[i]);
        }.bind(this));

        return formData;
    },

    _buildXhrObject: function () {
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', this._onXHRProgress.bind(this), false);
        return xhr;
    },

    _getXHRObject: function () {
        return this.xhr;
    },

    _performUpload: function (formData) {
        $.ajax({
            xhr: this._getXHRObject.bind(this),
            url: this.options.script,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false
        })
        .done(this._onXHRSuccess.bind(this))
        .fail(this._onXHRFailure.bind(this))
        .always(this._onXHRAlways.bind(this));
    },

    _onXHRProgress: function (e) {
        if (e.lengthComputable) this.el.trigger('lu:progress', Math.floor((e.loaded / e.total) * 100));
    },

    _onXHRSuccess: function (response) {
        this.el.trigger('lu:success', response);
    },

    _onXHRFailure: function (jqXHR) {
        this.el.trigger('lu:fail', jqXHR);
    },

    _onXHRAlways: function () {
        this._resetInput();
    },

    /* Public Methods */

    addParam: function (key, value) {
        this.params[key] = value;
    },

    cancelUpload: function () {
        this.xhr.abort();
        this.el.trigger('lu:cancelled');
        this._resetInput();
    }
};
<|endoftext|>


<commit_before>function spaceSelect(selElem, size) {
  selElem.classList.add('two-col-sel');

  var childOptions = selElem.querySelectorAll('option');

  for(var i = 0; i < childOptions.length; i++) {
    var parts = childOptions[i].innerText.split('|'),
		spacesToAdd = (size || 60) - parts[0].trim().length - parts[1].trim().length,
        repeatSpace = function(num) {
        	return Array(num + 1).join('\u00a0');
        };

    // Set the text of the option to contain the padding spaces
    childOptions[i].innerText = parts[0] + repeatSpace(spacesToAdd) + parts[1] + repeatSpace(2);
  }
}
<commit_msg>Add check if unable to split | character in two-col-sel<commit_after>function spaceSelect(selElem, size) {
  selElem.classList.add('two-col-sel');

  var childOptions = selElem.querySelectorAll('option');

  for(var i = 0; i < childOptions.length; i++) {
    var parts = childOptions[i].innerText.split('|');

    if(parts.length == 2) {
        var spacesToAdd = (size || 60) - parts[0].trim().length - parts[1].trim().length,
            repeatSpace = function(num) {
            	return Array(num + 1).join('\u00a0');
            };

        // Set the text of the option to contain the padding spaces
        childOptions[i].innerText = parts[0] + repeatSpace(spacesToAdd) + parts[1] + repeatSpace(2);
    }
    else {
        // Otherwise we keep the childOptions innerText the same
    }
  }
}
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    // These names MUST match the folder name within app/src so that the JS bundle doesn't end up in
    // a different directory from the files copied by file-loader
    home: path.join(__dirname, 'app/src/home'),
    404: path.join(__dirname, 'app/src/404'),
    products: path.join(__dirname, 'app/src/products'),
  },

  module: {
    loaders: [
      // SASS files
      {
        test: /\.sass$/,
        loader: ExtractTextWebpackPlugin.extract(['css-loader', 'postcss-loader', 'sass-loader']),
      },
      // CSS files
      {
        test: /\.css$/,
        loader: ExtractTextWebpackPlugin.extract(['css-loader', 'postcss-loader']),
      },
      // JavaScript files
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: { presets: ['es2015'] },
      },
      // Pug files
      {
        test: /\.pug$/,
        loaders: [
          'file-loader?name=[path][name].html&context=app/src',
          'pug-html-loader?exports=false',
        ],
      },
      // HTML files
      {
        test: /\.html$/,
        loaders: [
          'file-loader?name=[path][name].html&context=app/src',
          'extract-loader',
          'html-loader',
        ],
      },
      // Files that require no compilation or processing
      {
        test: /\.(ttf|woff|woff2|eot|png|svg)/,
        loader: 'url-loader',
        query: { limit: 10000, name: '[path][name].[ext]', context: 'app/src' },
      },
    ],
  },

  output: {
    path: path.join(__dirname, 'app/build'),
    publicPath: '/',
    filename: '[name]/index.js',
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }),
    new CopyWebpackPlugin([{ from: 'app/favicons' }]),
    new ExtractTextWebpackPlugin('[name]/style.css'),
  ],

  // --------------------------------------------------------------------------

  devServer: {
    contentBase: path.join(__dirname, 'app/build'),
  },
};
<commit_msg>Only minify on production server<commit_after>const path = require('path');
const webpack = require('webpack');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    // These names MUST match the folder name within app/src so that the JS bundle doesn't end up in
    // a different directory from the files copied by file-loader
    home: path.join(__dirname, 'app/src/home'),
    404: path.join(__dirname, 'app/src/404'),
    products: path.join(__dirname, 'app/src/products'),
  },

  module: {
    loaders: [
      // SASS files
      {
        test: /\.sass$/,
        loader: ExtractTextWebpackPlugin.extract(['css-loader', 'postcss-loader', 'sass-loader']),
      },
      // CSS files
      {
        test: /\.css$/,
        loader: ExtractTextWebpackPlugin.extract(['css-loader', 'postcss-loader']),
      },
      // JavaScript files
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: { presets: ['es2015'] },
      },
      // Pug files
      {
        test: /\.pug$/,
        loaders: [
          'file-loader?name=[path][name].html&context=app/src',
          'pug-html-loader?exports=false',
        ],
      },
      // HTML files
      {
        test: /\.html$/,
        loaders: [
          'file-loader?name=[path][name].html&context=app/src',
          'extract-loader',
          'html-loader',
        ],
      },
      // Files that require no compilation or processing
      {
        test: /\.(ttf|woff|woff2|eot|png|svg)/,
        loader: 'url-loader',
        query: { limit: 10000, name: '[path][name].[ext]', context: 'app/src' },
      },
    ],
  },

  output: {
    path: path.join(__dirname, 'app/build'),
    publicPath: '/',
    filename: '[name]/index.js',
  },

  plugins: [
    new CopyWebpackPlugin([{ from: 'app/favicons' }]),
    new ExtractTextWebpackPlugin('[name]/style.css'),
  ],

  // --------------------------------------------------------------------------

  devServer: {
    contentBase: path.join(__dirname, 'app/build'),
  },
};

// Custom settings for production
// detected when building in a path that begins with '/var/www'
if (__dirname.startsWith('/var/www')) {
  console.log('Production detected');
  module.exports.plugins = module.exports.plugins.concat([
    // Minify JS
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        warnings: false,
      },
    }),
    // Let all loaders know they can minimize output
    new webpack.LoaderOptionsPlugin({
      minimize: true,
    }),
  ]);
}

<|endoftext|>


<commit_before>const get = require('lodash.get')
const toPairs = require('lodash.topairs')

const FIELD_REGEXP = /^<(.*?)>/i

const KNOWN_ERRORS = toPairs({
  email_check: '<email> Please format your email like `a@b.c`.',
  pass_check: '<password> I saw an unfamiliar error.',
  user_email_key: "<email> I've seen this email address before.",
  user_pkey: ' I saw an unfamiliar error.',
  user_name_key: "<name> I've seen this name before.",
  create_user: ' I am unable to send you an email to create your account.',
  user_user_id_fkey: ' I saw an unfamiliar error.',
  '355CAC69': '<password> I need at least 8 characters for passwords.',
  '51EA51A9': "<password> Your password didn't match.",
  '3883C744': "<email> I didn't find an account with that email.",
  '4F811CFE': "<name> I couldn't find a matching account.",
  '58483A61': " I couldn't update your email.",
  EBC6E992: " I couldn't update your password.",
  EE05C989: 'No card found.',
  '1306BF1C': 'You may only respond to a scored card.',
  '681942FD': 'You must submit an available response `id`.',
  '5E310F2E': '<name> Subject name in use.',
  '76177573': 'A reply must belong to the same topic.',
  '8DF72C56': 'A vote may only reply to a proposal.',
  E47E0411: 'A user cannot vote on their own proposal.',
  '47C88D24': 'No user found.',
  CF018471: 'No previous version found.',
  B7615F09: 'No previous version found.',
}).map(([key, message]) => ({
  key,
  field: get(message.match(FIELD_REGEXP), 1, undefined),
  message: message.replace(FIELD_REGEXP, ''),
}))

const DEFAULT_FIELD = 'all'

module.exports = function getGqlErrors(e) {
  if (process.env.NODE_ENV !== 'production') console.error(e) // eslint-disable-line
  return get(e, 'response.errors', [])
    .map(({ message }) =>
      get(KNOWN_ERRORS.filter(({ key }) => message.indexOf(key) > -1), 0, {
        message,
      })
    )
    .reduce((sum, { message, field }) => {
      const xfield = field || DEFAULT_FIELD
      sum[xfield] = sum[xfield] || [] // eslint-disable-line
      sum[xfield].push(message) // eslint-disable-line
      return sum
    }, {})
}
<commit_msg>Update gql-errors.js<commit_after>const get = require('lodash.get')
const toPairs = require('lodash.topairs')

const FIELD_REGEXP = /^<(.*?)>\s?/i

const KNOWN_ERRORS = toPairs({
  email_check: '<email> Please format your email like `a@b.c`.',
  pass_check: '<password> I saw an unfamiliar error.',
  user_email_key: "<email> I've seen this email address before.",
  user_pkey: 'I saw an unfamiliar error.',
  user_name_key: "<name> I've seen this name before.",
  create_user: 'I am unable to send you an email to create your account.',
  user_user_id_fkey: 'I saw an unfamiliar error.',
  '355CAC69': '<password> I need at least 8 characters for passwords.',
  '51EA51A9': "<password> Your password didn't match.",
  '3883C744': "<email> I didn't find an account with that email.",
  '4F811CFE': "<name> I couldn't find a matching account.",
  '58483A61': "I couldn't update your email.",
  EBC6E992: "I couldn't update your password.",
  EE05C989: 'No card found.',
  '1306BF1C': 'You may only respond to a scored card.',
  '681942FD': 'You must submit an available response `id`.',
  '5E310F2E': '<name> Subject name in use.',
  '76177573': 'A reply must belong to the same topic.',
  '8DF72C56': 'A vote may only reply to a proposal.',
  E47E0411: 'A user cannot vote on their own proposal.',
  '47C88D24': 'No user found.',
  CF018471: 'No previous version found.',
  B7615F09: 'No previous version found.',
}).map(([key, message]) => ({
  key,
  field: get(message.match(FIELD_REGEXP), 1, undefined),
  message: message.replace(FIELD_REGEXP, ''),
}))

const DEFAULT_FIELD = 'all'

module.exports = function getGqlErrors(e) {
  if (process.env.NODE_ENV !== 'production') console.error(e) // eslint-disable-line
  return get(e, 'response.errors', [])
    .map(({ message }) =>
      get(KNOWN_ERRORS.filter(({ key }) => message.includes(key)), 0, {
        message,
      })
    )
    .reduce((sum, { message, field }) => {
      const xfield = field || DEFAULT_FIELD
      sum[xfield] = sum[xfield] || [] // eslint-disable-line
      sum[xfield].push(message) // eslint-disable-line
      return sum
    }, {})
}
<|endoftext|>


<commit_before>/*
 * QueryLoader v2 - A simple script to create a preloader for images
 *
 * For instructions read the original post:
 * http://www.gayadesign.com/diy/queryloader2-preload-your-images-with-ease/
 *
 * Copyright (c) 2011 - Gaya Kessler
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Version:  2.1
 * Last update: 11-1-2011
 *
 */
(function($) {
    var qLimages = new Array;
    var qLdone = 0;

    var qLimageContainer = "";
    var qLoverlay = "";
    var qLbar = "";
    var qLpercentage = "";

    var qLoptions = {
        onComplete: function () {},
        backgroundColor: "#000",
        barColor: "#fff",
        barHeight: 1,
        percentage: false,
        deepSearch: true,
        completeAnimation: "fade",
        onLoadComplete: function () {
            if (qLoptions.completeAnimation == "grow") {
                $(qLbar).stop().css("width", "100%").animate({
                    top: "0%",
                    height: "100%"
                }, 500, function () {
                    $(qLoverlay).fadeOut(500, function () {
                        $(this).remove();
                        qLoptions.onComplete();
                    })
                });
            } else {
                $(qLoverlay).fadeOut(500, function () {
                    $(qLoverlay).remove();
                    qLoptions.onComplete();
                });
            }
        }
    }

    var afterEach = function () {
        createPreloadContainer();
        createOverlayLoader();
    }

    var createPreloadContainer = function() {
        qLimageContainer = $("

").appendTo("body").css({
            display: "none",
            width: 0,
            height: 0,
            overflow: "hidden"
        });
        for (var i = 0; qLimages.length > i; i++) {
            var image = $("").attr("src", qLimages[i]).bind("load", function () {
                completeImageLoading();
            });
        }
    }

    var completeImageLoading = function () {
        qLdone++;

        var percentage = (qLdone / qLimages.length) * 100;
        $(qLbar).stop().animate({
            width: percentage + "%"
        }, 200);

        if (qLoptions.percentage == true) {
            $(qLpercentage).text(Math.ceil(percentage) + "%");
        }

        if (qLdone == qLimages.length) {
            destroyQueryLoader();
        }
    }

    var destroyQueryLoader = function () {
        $(qLimageContainer).remove();
        qLoptions.onLoadComplete();
    }

    var createOverlayLoader = function () {
        qLoverlay = $("

").css({
            width: "100%",
            height: "100%",
            backgroundColor: qLoptions.backgroundColor,
            backgroundPosition: "fixed",
            position: "fixed",
            zIndex: 666999,
            top: 0,
            left: 0
        }).appendTo("body");
        qLbar = $("

").css({
            height: qLoptions.barHeight + "px",
            marginTop: "-" + (qLoptions.barHeight / 2) + "px",
            backgroundColor: qLoptions.barColor,
            width: "0%",
            position: "absolute",
            top: "50%"
        }).appendTo(qLoverlay);
        if (qLoptions.percentage == true) {
            qLpercentage = $("

").text("0%").css({
                height: "40px",
                width: "100px",
                position: "absolute",
                fontSize: "3em",
                top: "50%",
                left: "50%",
                marginTop: "-" + (59 + qLoptions.barHeight) + "px",
                textAlign: "center",
                marginLeft: "-50px",
                color: qLoptions.barColor
            }).appendTo(qLoverlay);
        }
    }

    var findImageInElement = function (element) {
        var url = "";

        if ($(element).css("background-image") != "none") {
            var url = $(element).css("background-image");
        } else if (typeof($(element).attr("src")) != "undefined" && element.nodeName.toLowerCase() == "img") {
            var url = $(element).attr("src");
        }

        url = url.replace(/url\(\"/g, "");
        url = url.replace(/url\(/g, "");
        url = url.replace(/\"\)/g, "");
        url = url.replace(/\)/g, "");

        var urls = url.split(", ");

        for (var i = 0; i < urls.length; i++) {
            if (urls[i].length > 0) {
                var extra = "";
                if ($.browser.msie && $.browser.version < 9) {
                    extra = "?" + Math.floor(Math.random() * 3000);
                }
                qLimages.push(urls[i] + extra);
            }
        }
    }

    $.fn.queryLoader2 = function(options) {
        if(options) {
            $.extend(qLoptions, options );
        }

        this.each(function() {
            findImageInElement(this);
            if (qLoptions.deepSearch == true) {
                $(this).find("*:not(script)").each(function() {
                    findImageInElement(this);
                });
            }
        });

        afterEach();

        return this;
    };

})(jQuery);<commit_msg>Fixed the CSS3 gradient problem.<commit_after>/*
 * QueryLoader v2 - A simple script to create a preloader for images
 *
 * For instructions read the original post:
 * http://www.gayadesign.com/diy/queryloader2-preload-your-images-with-ease/
 *
 * Copyright (c) 2011 - Gaya Kessler
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Version:  2.1
 * Last update: 11-1-2011
 *
 */
(function($) {
    var qLimages = new Array;
    var qLdone = 0;

    var qLimageContainer = "";
    var qLoverlay = "";
    var qLbar = "";
    var qLpercentage = "";
    var qLimageCounter = 0;

    var qLoptions = {
        onComplete: function () {},
        backgroundColor: "#000",
        barColor: "#fff",
        barHeight: 1,
        percentage: false,
        deepSearch: true,
        completeAnimation: "fade",
        onLoadComplete: function () {
            if (qLoptions.completeAnimation == "grow") {
                $(qLbar).stop().css("width", "100%").animate({
                    top: "0%",
                    height: "100%"
                }, 500, function () {
                    $(qLoverlay).fadeOut(500, function () {
                        $(this).remove();
                        qLoptions.onComplete();
                    })
                });
            } else {
                $(qLoverlay).fadeOut(500, function () {
                    $(qLoverlay).remove();
                    qLoptions.onComplete();
                });
            }
        }
    }

    var afterEach = function () {
        createPreloadContainer();
        createOverlayLoader();
    }

    var createPreloadContainer = function() {
        qLimageContainer = $("

").appendTo("body").css({
            display: "none",
            width: 0,
            height: 0,
            overflow: "hidden"
        });
        for (var i = 0; qLimages.length > i; i++) {
            $.ajax({
                url: qLimages[i],
                type: 'HEAD',
                success: function(data) {
                    qLimageCounter++;
                    addImageForPreload(this['url']);
                }
            });
        }
    }

    var addImageForPreload = function(url) {
        var image = $("").attr("src", url).bind("load", function () {
            completeImageLoading();
        }).appendTo(qLimageContainer);
    }

    var completeImageLoading = function () {
        qLdone++;

        var percentage = (qLdone / qLimageCounter) * 100;
        $(qLbar).stop().animate({
            width: percentage + "%"
        }, 200);

        if (qLoptions.percentage == true) {
            $(qLpercentage).text(Math.ceil(percentage) + "%");
        }

        if (qLdone == qLimageCounter) {
            destroyQueryLoader();
        }
    }

    var destroyQueryLoader = function () {
        $(qLimageContainer).remove();
        qLoptions.onLoadComplete();
    }

    var createOverlayLoader = function () {
        qLoverlay = $("

").css({
            width: "100%",
            height: "100%",
            backgroundColor: qLoptions.backgroundColor,
            backgroundPosition: "fixed",
            position: "fixed",
            zIndex: 666999,
            top: 0,
            left: 0
        }).appendTo("body");
        qLbar = $("

").css({
            height: qLoptions.barHeight + "px",
            marginTop: "-" + (qLoptions.barHeight / 2) + "px",
            backgroundColor: qLoptions.barColor,
            width: "0%",
            position: "absolute",
            top: "50%"
        }).appendTo(qLoverlay);
        if (qLoptions.percentage == true) {
            qLpercentage = $("

").text("0%").css({
                height: "40px",
                width: "100px",
                position: "absolute",
                fontSize: "3em",
                top: "50%",
                left: "50%",
                marginTop: "-" + (59 + qLoptions.barHeight) + "px",
                textAlign: "center",
                marginLeft: "-50px",
                color: qLoptions.barColor
            }).appendTo(qLoverlay);
        }
    }

    var findImageInElement = function (element) {
        var url = "";

        if ($(element).css("background-image") != "none") {
            var url = $(element).css("background-image");
        } else if (typeof($(element).attr("src")) != "undefined" && element.nodeName.toLowerCase() == "img") {
            var url = $(element).attr("src");
        }

        if (url.indexOf("gradient") == -1) {
            url = url.replace(/url\(\"/g, "");
            url = url.replace(/url\(/g, "");
            url = url.replace(/\"\)/g, "");
            url = url.replace(/\)/g, "");

            var urls = url.split(", ");

            for (var i = 0; i < urls.length; i++) {
                if (urls[i].length > 0) {
                    var extra = "";
                    if ($.browser.msie && $.browser.version < 9) {
                        extra = "?" + Math.floor(Math.random() * 3000);
                    }
                    qLimages.push(urls[i] + extra);
                }
            }
        }
    }

    $.fn.queryLoader2 = function(options) {
        if(options) {
            $.extend(qLoptions, options );
        }

        this.each(function() {
            findImageInElement(this);
            if (qLoptions.deepSearch == true) {
                $(this).find("*:not(script)").each(function() {
                    findImageInElement(this);
                });
            }
        });

        afterEach();

        return this;
    };

})(jQuery);<|endoftext|>


<commit_before>const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const path = require('path');
const pkg = require('./package.json');
const validate = require('webpack-validator');
const webpack = require('webpack');

const PATHS = {
  app: path.join(__dirname, 'app/scripts/main.js'),
  style: path.join(__dirname, 'app', 'styles'),
  build: path.join(__dirname, 'dist')
}

const devServerOpts = function(options) {
  return {
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      stats: 'errors-only',
      host: options.host,
      port: options.port
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin({
        multiStep: true
      })
    ]
  };
}

const extractBundle = function(options) {
  const entry = {};
  entry[options.name] = options.entries;

  return {
    entry: entry,
    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        names: [options.name, 'manifest']
      })
    ]
  };
}

const setupCSS = function() {
  return {
    module: {
      loaders: [{
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass'],
      }, {
        test: /\.css$/,
        loaders: ['style', 'css'],
      }]
    }
  }
}

const extractCSS = function() {
  return {
    module: {
      loaders: [{
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(['css', 'sass'])
      }, {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(['css'])
      }]
    },
    plugins: [
      new ExtractTextPlugin('[name].[chunkhash].css')
    ]
  };
}

const common = {
  entry: {
    app: PATHS.app,
    style: path.join(PATHS.style, 'main.scss')
  },
  output: {
    path: PATHS.build,
    filename: '[name].js'
  },
  module: {
    loaders: [
      // font related loaders
      {
        // Matches both node_modules/font-awesome/fonts and src/fonts
        test: /fonts\/.*\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file',
        query: {
          name: 'fonts/[name].[ext]',
          limit: 10000,
          mimetype: 'application/font-woff'
        }
      },
      {
        // Matches both node_modules/font-awesome/fonts and src/fonts
        test: /fonts\/.*\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file',
        query: {
          name: 'fonts/[name].[ext]'
        }
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          mimetype: 'image/svg+xml',
          name: 'images/[path][name].[ext]'
        }
      },
      {
        test: /\.swf$/,
        loader: 'file'
      },
      {
        test: /\.(jpe?g|gif|png|svg)$/,
        loader: 'file',
        query: {
          name: 'images/[md5:hash].[ext]'
        }
      },
      // copy favicons to root
      {
        test: /favicon-\d+.png$|favicon.ico$/,
        loader: 'file?name=[name].[ext]'
      },
      // copy htaccess to root
      {
        test: /.htaccess$/,
        loader: 'file'
      },
      // copy php files to root
      {
        test: /\.php$/,
        loader: 'file'
      },
      {
        test: /\.xml$/,
        loader: 'file'
      },
      {
        test: /\.hbs$/,
        loader: 'handlebars-loader'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel"
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.ejs',
      inject: false
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    })
  ],
  resolve: {
    alias: {
      bootstrap: 'bootstrap-sass/assets/javascripts/bootstrap',
      localforage: 'localforage/dist/localforage.nopromises.js',
    }
  },
  sassLoader: {
    includePaths: [path.resolve(__dirname, "./node_modules")]
  }
};

var config;

// Detect how npm is run and branch based on that
switch(process.env.npm_lifecycle_event) {
  case 'build':
    config = merge(
      common,
      {
        devtool: 'source-map'
      },
      extractCSS(),
      {
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      }
    );
    break;
  default:
    config = merge(
      common,
      {
        devtool: 'eval-source-map'
      },
      setupCSS(),
      devServerOpts({
        host: process.env.HOST,
        port: process.env.PORT
      })
    );
}

// module.exports = validate(config);
module.exports = config;
<commit_msg>Fix windows font load error and ignore localforage error message<commit_after>const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const path = require('path');
const pkg = require('./package.json');
const validate = require('webpack-validator');
const webpack = require('webpack');

const PATHS = {
  app: path.join(__dirname, 'app/scripts/main.js'),
  style: path.join(__dirname, 'app', 'styles'),
  build: path.join(__dirname, 'dist')
}

const devServerOpts = function(options) {
  return {
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      stats: 'errors-only',
      host: options.host,
      port: options.port
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin({
        multiStep: true
      })
    ]
  };
}

const extractBundle = function(options) {
  const entry = {};
  entry[options.name] = options.entries;

  return {
    entry: entry,
    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        names: [options.name, 'manifest']
      })
    ]
  };
}

const setupCSS = function() {
  return {
    module: {
      loaders: [{
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass'],
      }, {
        test: /\.css$/,
        loaders: ['style', 'css'],
      }]
    }
  }
}

const extractCSS = function() {
  return {
    module: {
      loaders: [{
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(['css', 'sass'])
      }, {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(['css'])
      }]
    },
    plugins: [
      new ExtractTextPlugin('[name].[chunkhash].css')
    ]
  };
}

const common = {
  entry: {
    app: PATHS.app,
    style: path.join(PATHS.style, 'main.scss')
  },
  output: {
    path: PATHS.build,
    filename: '[name].js'
  },
  module: {
    noParse: /[\/\\]node_modules[\/\\]localforage[\/\\]dist[\/\\].*$/,
    loaders: [
      // font related loaders
      {
        // Matches both node_modules/font-awesome/fonts and src/fonts
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file',
        query: {
          name: 'fonts/[name].[ext]',
          limit: 10000,
          mimetype: 'application/font-woff'
        }
      },
      {
        // Matches both node_modules/font-awesome/fonts and src/fonts
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file',
        query: {
          name: 'fonts/[name].[ext]'
        }
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          mimetype: 'image/svg+xml',
          name: 'images/[path][name].[ext]'
        }
      },
      {
        test: /\.swf$/,
        loader: 'file'
      },
      {
        test: /\.(jpe?g|gif|png|svg)$/,
        loader: 'file',
        query: {
          name: 'images/[md5:hash].[ext]'
        }
      },
      // copy favicons to root
      {
        test: /favicon-\d+.png$|favicon.ico$/,
        loader: 'file?name=[name].[ext]'
      },
      // copy htaccess to root
      {
        test: /.htaccess$/,
        loader: 'file'
      },
      // copy php files to root
      {
        test: /\.php$/,
        loader: 'file'
      },
      {
        test: /\.xml$/,
        loader: 'file'
      },
      {
        test: /\.hbs$/,
        loader: 'handlebars-loader'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel"
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.ejs',
      inject: false
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    })
  ],
  resolve: {
    alias: {
      bootstrap: 'bootstrap-sass/assets/javascripts/bootstrap',
      localforage: 'localforage/dist/localforage.nopromises.js',
    }
  },
  sassLoader: {
    includePaths: [path.resolve(__dirname, "./node_modules")]
  }
};

var config;

// Detect how npm is run and branch based on that
switch(process.env.npm_lifecycle_event) {
  case 'build':
    config = merge(
      common,
      {
        devtool: 'source-map'
      },
      extractCSS(),
      {
        plugins: [
          new webpack.optimize.UglifyJsPlugin({
            compress: {
              warnings: false
            }
          })
        ]
      }
    );
    break;
  default:
    config = merge(
      common,
      {
        devtool: 'eval-source-map'
      },
      setupCSS(),
      devServerOpts({
        host: process.env.HOST,
        port: process.env.PORT
      })
    );
}

// module.exports = validate(config);
module.exports = config;
<|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 * Single location of all accessibility strings used in joist.  These
 * strings are not meant to be translatable yet.  Rosetta needs some work to
 * provide translators with context for these strings, and we want to receive
 * some community feedback before these strings are submitted for translation.
 *
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  var joist = require( 'JOIST/joist' );

  var JoistA11yStrings = {

    // dialogs
    hotKeysAndHelpString: 'Keyboard Shortcuts',
    closeString: 'Close',

    // navigation bar
    simResourcesAndToolsString: 'Sim Resources and Tools',

    // PhET menu ('menu' label added by aria role)
    phetString: 'PhET'
  };

  if ( phet.chipper.queryParameters.stringTest === 'xss' ) {
    for ( var key in JoistA11yStrings ) {
      JoistA11yStrings[ key ] += '';
    }
  }

  // verify that object is immutable, without the runtime penalty in production code
  if ( assert ) { Object.freeze( JoistA11yStrings ); }

  joist.register( 'JoistA11yStrings', JoistA11yStrings );

  return JoistA11yStrings;
} );<commit_msg>add 'Menu' to PhET menu label, see phetsims/john-travoltage#215<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 * Single location of all accessibility strings used in joist.  These
 * strings are not meant to be translatable yet.  Rosetta needs some work to
 * provide translators with context for these strings, and we want to receive
 * some community feedback before these strings are submitted for translation.
 *
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  var joist = require( 'JOIST/joist' );

  var JoistA11yStrings = {

    // dialogs
    hotKeysAndHelpString: 'Keyboard Shortcuts',
    closeString: 'Close',

    // navigation bar
    simResourcesAndToolsString: 'Sim Resources and Tools',

    // PhET menu
    phetString: 'PhET Menu'
  };

  if ( phet.chipper.queryParameters.stringTest === 'xss' ) {
    for ( var key in JoistA11yStrings ) {
      JoistA11yStrings[ key ] += '';
    }
  }

  // verify that object is immutable, without the runtime penalty in production code
  if ( assert ) { Object.freeze( JoistA11yStrings ); }

  joist.register( 'JoistA11yStrings', JoistA11yStrings );

  return JoistA11yStrings;
} );<|endoftext|>


<commit_before>
function speech_init() {
  prop.speech = {};
  prop.speech.synthesis = window.speechSynthesis;
  prop.speech.enabled = false;

  if('atc-speech-enabled' in localStorage && localStorage['atc-speech-enabled'] == 'true') {
    prop.speech.enabled = true;
    $(".speech-toggle").addClass("active");
  }
}

function speech_say(textToSay) {
  if(prop.speech.synthesis != null && prop.speech.enabled) {
    // Split numbers into individual digits e.g. Speedbird 666 -> Speedbird 6 6 6
    textToSay = textToSay.replace(/[0-9]{,4}/g, "$& ").replace(/\s0/g, " zero");
    prop.speech.synthesis.speak(new SpeechSynthesisUtterance(textToSay));
  }
}

function speech_toggle() {
  prop.speech.enabled = !prop.speech.enabled;

  if(prop.speech.enabled) {
    $(".speech-toggle").addClass("active");
  } else {
    $(".speech-toggle").removeClass("active");
    prop.speech.synthesis.cancel();
  }

  localStorage['atc-speech-enabled'] = prop.speech.enabled;

}
<commit_msg>add back number splitting<commit_after>
function speech_init() {
  prop.speech = {};
  prop.speech.synthesis = window.speechSynthesis;
  prop.speech.enabled = false;

  if('atc-speech-enabled' in localStorage && localStorage['atc-speech-enabled'] == 'true') {
    prop.speech.enabled = true;
    $(".speech-toggle").addClass("active");
  }
}

function speech_say(textToSay) {
  if(prop.speech.synthesis != null && prop.speech.enabled) {
    // Split numbers into individual digits e.g. Speedbird 666 -> Speedbird 6 6 6
    textToSay = textToSay.replace(/[0-9]/g, "$& ").replace(/\s0/g, " zero");
    prop.speech.synthesis.speak(new SpeechSynthesisUtterance(textToSay));
  }
}

function speech_toggle() {
  prop.speech.enabled = !prop.speech.enabled;

  if(prop.speech.enabled) {
    $(".speech-toggle").addClass("active");
  } else {
    $(".speech-toggle").removeClass("active");
    prop.speech.synthesis.cancel();
  }

  localStorage['atc-speech-enabled'] = prop.speech.enabled;

}
<|endoftext|>


<commit_before>'use strict';

let Backbone = require('Backbone');

var Todo = Backbone.Model.extend({

	defaults: function() {
		return {
			title: "Empty todo",
			done: false
		}
	},

});<commit_msg>add exports<commit_after>'use strict';

let Backbone = require('Backbone');

var Todo = Backbone.Model.extend({

	defaults: function() {
		return {
			title: "Empty todo",
			done: false
		};
	},

});

module.exports = Todo;<|endoftext|>


<commit_before>const path = require('path');
const webpackStream = require('webpack-stream');
const webpack = webpackStream.webpack;
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
// const ComponentDirectoryPlugin = require("component-directory-webpack-plugin");
const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

function _path(p) {
  return path.join(__dirname, p);
}

let webpackConfig = {
    // click on the name of the option to get to the detailed documentation
    // click on the items with arrows to show more examples / advanced options

    entry: path.resolve(__dirname, "src/app.js"), // string | object | array
    // Here the application starts executing
    // and webpack starts bundling

    output: {
      // options related to how webpack emits results

      path: path.resolve(__dirname, "tmp/assets/scripts"), // string
      // the target directory for all output files
      // must be an absolute path (use the Node.js path module)

      filename: "app.js", // string
      // the filename template for entry chunks

      // publicPath: path.resolve(__dirname, "."), // string
      // the url to the output directory resolved relative to the HTML page

      library: "App", // string,
      // the name of the exported library (Global object)

      // libraryTarget: "umd", // universal module definition
      // the type of the exported library

      /* Advanced output configuration (click to show) */
    },
    module: {
        rules : [
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  presets: [
                      ['env', {
                          "modules": false,
                          "useBuiltIns": true,
                          "debug": true
                        }
                      ]
                  ],
                    plugins: ['transform-remove-strict-mode', 'transform-object-assign', 'transform-object-rest-spread'],

                }
              },
            ]
          }
        ]
      },

    resolve: {
      // options for resolving module requests
      // (does not apply to resolving to loaders)

      modules: [
        "node_modules",
        path.resolve(__dirname, "src/components"),
        path.resolve(__dirname, "node_modules"),
        path.resolve(__dirname, "assets/styles/vendors")
      ],
      // directories where to look for modules

      extensions: ['.js', '.jsx', '.scss'],
      // extensions that are used

      alias: {
        // a list of module name aliases
        vendors: path.resolve(__dirname, 'src/vendors/'),
        components: path.resolve(__dirname, 'src/components/'),
        utils: path.resolve(__dirname, 'src/components/utils/'),
        npm: path.resolve(__dirname, 'node_modules/'),

        // Switch dependency lib accordingly (this one uses jquery)
        'inputmask.dependencyLib': _path('node_modules/jquery.inputmask/dist/inputmask/inputmask.dependencyLib'),
        // Core library (order of these aliases shouldn't matter FYI)
        'inputmask' : _path('node_modules/jquery.inputmask/dist/inputmask/inputmask'),
        // Allows use of jquery input mask via jquery chaining api/$('selector').inputmask(...)
        'jquery.inputmask': _path('node_modules/jquery.inputmask/dist/inputmask/jquery.inputmask'),
        // Add extensions following the pattern below remember to import them as necessary in your .js files
        'inputmask.numeric.extensions': _path('node_modules/jquery.inputmask/dist/inputmask/inputmask.numeric.extensions'),

        'viewport-units-buggyfill': _path('node_modules/viewport-units-buggyfill/viewport-units-buggyfill'),
        'viewport-units-buggyfill.hacks': _path('node_modules/viewport-units-buggyfill/viewport-units-buggyfill.hacks'),

        // "module": "new-module",
        // // alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"
        //
        // "only-module$": "new-module",
        // // alias "only-module" -> "new-module", but not "module/path/file" -> "new-module/path/file"
        //
        // "module": path.resolve(__dirname, "app/third/module.js"),
        // alias "module" -> "./app/third/module.js" and "module/file" results in error
        // modules aliases are imported relative to the current context
      },

      // /* alternative alias syntax (click to show) */
      // alias: [
      //   {
      //     name: "module",
      //     // the old request
      //
      //     alias: "new-module",
      //     // the new request
      //
      //     onlyModule: true
      //     // if true only "module" is aliased
      //     // if false "module/inner/path" is also aliased
      //   }
      // ],

      // /* Advanced resolve configuration (click to show) */
      //
      // symlinks: true,
      // // follow symlinks to new location
      //
      // descriptionFiles: ["package.json"],
      // // files that are read for package description
      //
      // mainFields: ["main"],
      // // properties that are read from description file
      // // when a folder is requested
      //
      // aliasFields: ["browser"],
      // // properites that are read from description file
      // // to alias requests in this package
      //
      // enforceExtension: false,
      // // if true request must not include an extensions
      // // if false request may already include an extension
      //
      // moduleExtensions: ["-module"],
      // enforceModuleExtension: false,
      // // like extensions/enforceExtension but for module names instead of files
      //
      // unsafeCache: true,
      // unsafeCache: {},
      // // enables caching for resolved requests
      // // this is unsafe as folder structure may change
      // // but preformance improvement is really big
      //
      // cachePredicate: (path, request) => true,
      // // predicate function which selects requests for caching
      //
      // plugins: [
      //   // ...
      // ]
      // additional plugins applied to the resolver
    },

  /*  performance: {
      hints: "warning", // enum
      maxAssetSize: 200000, // int (in bytes),
      maxEntrypointSize: 400000, // int (in bytes)
      assetFilter: function(assetFilename) {
        // Function predicate that provides asset filenames
        return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
      }
    },*/

    devtool: "source-map", // enum
    watch: isDevelopment,
  	// watchOptions: {
  	// 	aggregateTimeout: 100
  	// },
    // enhance debugging by adding meta info for the browser devtools
    // source-map most detailed at the expense of build speed.

    // context: __dirname, // string (absolute path!)
    // the home directory for webpack
    // the entry and module.rules.loader option
    //   is resolved relative to this directory

    // target: "web", // enum
    // the environment in which the bundle should run
    // changes chunk loading behavior and available modules

    // externals: ["react", /^@angular\//],
    externals: [
      'TweenLite',
      'window',
    {
      jquery: "jQuery"
    }
    ],
    // Don't follow/bundle these modules, but request them at runtime from the environment

    plugins: [
       new webpack.NoErrorsPlugin(),
       new webpack.ProvidePlugin({
          $: "jquery",
          "jQuery": "jquery",
          "_": "lodash",
          "domready": "domready"
      }),
      new UglifyJSPlugin({
        compress: !isDevelopment,
        // mangle: {
        //   // Skip mangling these
        //  except: ['$super', '$', 'exports', 'require']
        // },
        mangle: false,
        beautify: isDevelopment,
        sourceMap: isDevelopment,

      })
      //  new webpack.ResolverPlugin(new ComponentDirectoryPlugin(true)) // resolve require('components/demo') as components/demo/demo.js || index.js
    ],
    // list of additional plugins
  };

module.exports = webpackConfig;
<commit_msg>webpack билд сборка настройки оптимизированы<commit_after>const path = require('path');
const webpackStream = require('webpack-stream');
const webpack = webpackStream.webpack;
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
// const ComponentDirectoryPlugin = require("component-directory-webpack-plugin");
const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

function _path(p) {
  return path.join(__dirname, p);
}

const curEnv = isDevelopment ? 'development' : 'production';
const config = {
  development: {
    plugins: {
      UglifyJSPlugin: {
        compress: false,
        // mangle: {
        //   // Skip mangling these
        //  except: ['$super', '$', 'exports', 'require']
        // },
        mangle: false,
        beautify: true,
        sourceMap: false,
      }
    }
  },
  production: {
    plugins: {
      UglifyJSPlugin: {
        beautify: false,
         mangle: {
           screw_ie8: true,
           keep_fnames: true
         },
         compress: {
           screw_ie8: true
         },
         comments: false,
         sourceMap: false,
      }
    }
  }
}

let webpackConfig = {
    // click on the name of the option to get to the detailed documentation
    // click on the items with arrows to show more examples / advanced options

    entry: path.resolve(__dirname, "src/app.js"), // string | object | array
    // Here the application starts executing
    // and webpack starts bundling

    output: {
      // options related to how webpack emits results

      path: path.resolve(__dirname, "tmp/assets/scripts"), // string
      // the target directory for all output files
      // must be an absolute path (use the Node.js path module)

      filename: "app.js", // string
      // the filename template for entry chunks

      // publicPath: path.resolve(__dirname, "."), // string
      // the url to the output directory resolved relative to the HTML page

      library: "App", // string,
      // the name of the exported library (Global object)

      // libraryTarget: "umd", // universal module definition
      // the type of the exported library

      /* Advanced output configuration (click to show) */
    },
    module: {
        rules : [
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  presets: [
                      ['env', {
                          "modules": false,
                          "useBuiltIns": true,
                          "debug": true
                        }
                      ]
                  ],
                    plugins: ['transform-remove-strict-mode', 'transform-object-assign', 'transform-object-rest-spread'],

                }
              },
            ]
          }
        ]
      },

    resolve: {
      // options for resolving module requests
      // (does not apply to resolving to loaders)

      modules: [
        "node_modules",
        path.resolve(__dirname, "src/components"),
        path.resolve(__dirname, "node_modules"),
        path.resolve(__dirname, "assets/styles/vendors")
      ],
      // directories where to look for modules

      extensions: ['.js', '.jsx', '.scss'],
      // extensions that are used

      alias: {
        // a list of module name aliases
        vendors: path.resolve(__dirname, 'src/vendors/'),
        components: path.resolve(__dirname, 'src/components/'),
        utils: path.resolve(__dirname, 'src/components/utils/'),
        npm: path.resolve(__dirname, 'node_modules/'),

        // Switch dependency lib accordingly (this one uses jquery)
        'inputmask.dependencyLib': _path('node_modules/jquery.inputmask/dist/inputmask/inputmask.dependencyLib'),
        // Core library (order of these aliases shouldn't matter FYI)
        'inputmask' : _path('node_modules/jquery.inputmask/dist/inputmask/inputmask'),
        // Allows use of jquery input mask via jquery chaining api/$('selector').inputmask(...)
        'jquery.inputmask': _path('node_modules/jquery.inputmask/dist/inputmask/jquery.inputmask'),
        // Add extensions following the pattern below remember to import them as necessary in your .js files
        'inputmask.numeric.extensions': _path('node_modules/jquery.inputmask/dist/inputmask/inputmask.numeric.extensions'),

        'viewport-units-buggyfill': _path('node_modules/viewport-units-buggyfill/viewport-units-buggyfill'),
        'viewport-units-buggyfill.hacks': _path('node_modules/viewport-units-buggyfill/viewport-units-buggyfill.hacks'),

        // "module": "new-module",
        // // alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"
        //
        // "only-module$": "new-module",
        // // alias "only-module" -> "new-module", but not "module/path/file" -> "new-module/path/file"
        //
        // "module": path.resolve(__dirname, "app/third/module.js"),
        // alias "module" -> "./app/third/module.js" and "module/file" results in error
        // modules aliases are imported relative to the current context
      },

      // /* alternative alias syntax (click to show) */
      // alias: [
      //   {
      //     name: "module",
      //     // the old request
      //
      //     alias: "new-module",
      //     // the new request
      //
      //     onlyModule: true
      //     // if true only "module" is aliased
      //     // if false "module/inner/path" is also aliased
      //   }
      // ],

      // /* Advanced resolve configuration (click to show) */
      //
      // symlinks: true,
      // // follow symlinks to new location
      //
      // descriptionFiles: ["package.json"],
      // // files that are read for package description
      //
      // mainFields: ["main"],
      // // properties that are read from description file
      // // when a folder is requested
      //
      // aliasFields: ["browser"],
      // // properites that are read from description file
      // // to alias requests in this package
      //
      // enforceExtension: false,
      // // if true request must not include an extensions
      // // if false request may already include an extension
      //
      // moduleExtensions: ["-module"],
      // enforceModuleExtension: false,
      // // like extensions/enforceExtension but for module names instead of files
      //
      // unsafeCache: true,
      // unsafeCache: {},
      // // enables caching for resolved requests
      // // this is unsafe as folder structure may change
      // // but preformance improvement is really big
      //
      // cachePredicate: (path, request) => true,
      // // predicate function which selects requests for caching
      //
      // plugins: [
      //   // ...
      // ]
      // additional plugins applied to the resolver
    },

  /*  performance: {
      hints: "warning", // enum
      maxAssetSize: 200000, // int (in bytes),
      maxEntrypointSize: 400000, // int (in bytes)
      assetFilter: function(assetFilename) {
        // Function predicate that provides asset filenames
        return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
      }
    },*/

    devtool: "source-map", // enum
    watch: isDevelopment,
  	// watchOptions: {
  	// 	aggregateTimeout: 100
  	// },
    // enhance debugging by adding meta info for the browser devtools
    // source-map most detailed at the expense of build speed.

    // context: __dirname, // string (absolute path!)
    // the home directory for webpack
    // the entry and module.rules.loader option
    //   is resolved relative to this directory

    // target: "web", // enum
    // the environment in which the bundle should run
    // changes chunk loading behavior and available modules

    // externals: ["react", /^@angular\//],
    externals: [
      'TweenLite',
      'window',
    {
      jquery: "jQuery"
    }
    ],
    // Don't follow/bundle these modules, but request them at runtime from the environment

    plugins: [
       new webpack.NoErrorsPlugin(),
       new webpack.ProvidePlugin({
          $: "jquery",
          "jQuery": "jquery",
          "_": "lodash",
          "domready": "domready"
      }),
      new UglifyJSPlugin(
        config[curEnv].plugins.UglifyJSPlugin
      )
      //  new webpack.ResolverPlugin(new ComponentDirectoryPlugin(true)) // resolve require('components/demo') as components/demo/demo.js || index.js
    ],
    // list of additional plugins
  };

module.exports = webpackConfig;
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone',
	'text!./app/views/templates/search-form.html',
	'text!./app/views/templates/search-empty.html',
	'text!./app/views/templates/search-listing.html',
	'models'], function($, _, Backbone, searchFormTemplate, emptySearchTemplate, searchListingTemplate, Models) {
	var Views = {};

    function urlencode (str) {
      // http://kevin.vanzonneveld.net
      // +   original by: Philip Peterson
      // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +      input by: AJ
      // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   improved by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +      input by: travc
      // +      input by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   improved by: Lars Fischer
      // +      input by: Ratheous
      // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Joris
      // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
      // %          note 1: This reflects PHP 5.3/6.0+ behavior
      // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
      // %        note 2: pages served as UTF-8
      // *     example 1: urlencode('Kevin van Zonneveld!');
      // *     returns 1: 'Kevin+van+Zonneveld%21'
      // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
      // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
      // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
      // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
      str = (str + '').toString();

      // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
      // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
      return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
      replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
    }

	Views.SearchView = Backbone.View.extend({
		template: _.template(searchListingTemplate),

		events: {
			"click button#btn-pledge": "pledgeClick"
		},

		pledgeClick: function() {

		},

		initialize: function() {
			this.listenTo(this.model, "change", this.render);
			this.id = "search-" + this.model.attributes.id;
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
			return this;
		}
	});

	Views.SearchListing = Backbone.View.extend({
		initialize: function() {
			this.listenTo(this.collection, 'add', this.collectionAdded);
			this.listenTo(this.collection, 'change', this.collectionChanged);
			this.listenTo(this.collection, 'remove', this.collectionRemoved);

			this.childViews = [];

			this._addAllModels();
		},

		render: function() {
			var fragment = document.createDocumentFragment();

			if (this.childViews.length > 0) {
				_(this.childViews).each(function(currentView) {
					fragment.appendChild(currentView.render().el);
				});
			} else {
				$(emptySearchTemplate).appendTo(fragment);
			}

			this.$('.item-listing').html(fragment);
			return this;
		},

		collectionAdded: function(item) {
			this._addViewForModel(item);
			this.render();
		},

		collectionRemoved: function(item) {
			this.childViews = this.childViews.filter(function(view) {
				return view.model.id !== item.id;
			});
			this.render();
		},

		collectionChanged: function() {
			this.childViews = [];
			this._addAllModels();
		},

		_addViewForModel: function(item) {
			this.childViews.push(new Views.SearchView({
				model: item
			}));
		},

		_addAllModels: function() {
			this.collection.each(function(item) {
				_addViewForModel(item);
			});
			this.render();
		}
	});

	Views.SearchForm = Backbone.View.extend({
		template: _.template(searchFormTemplate),

		events: {
			"click a#btn-search": "searchClick",
            "keypress input[type=text]": "keypress"
		},

        keypress: function(e) {
            switch (e.keyCode) {
                case 13:
                this.searchClick();
            }
        },

		searchClick: function() {
			var search = $('#txt-search').val();
			this.searchCollection.url = '/service/products/search/' + urlencode(search);
			this.searchCollection.fetch({
			    success: function(results) {
        			$('#lbl-search').text(search);
        			$('#search-results').show();
			    }
			});
			this.searchListingView.render();
		},

		initialize: function() {
			this.render();
			this.searchCollection = new Models.SearchResults();
			this.searchListingView = new Views.SearchListing({
				collection: this.searchCollection,
				el: '#search-results',
				id: 'search-results'
			});
		},

		render: function() {
			this.$el.html(this.template());
			return this;
		}
	});

	return Views;
});<commit_msg>testing double urlencode for search<commit_after>define(['jquery', 'underscore', 'backbone',
	'text!./app/views/templates/search-form.html',
	'text!./app/views/templates/search-empty.html',
	'text!./app/views/templates/search-listing.html',
	'models'], function($, _, Backbone, searchFormTemplate, emptySearchTemplate, searchListingTemplate, Models) {
	var Views = {};

    function urlencode (str) {
      // http://kevin.vanzonneveld.net
      // +   original by: Philip Peterson
      // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +      input by: AJ
      // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   improved by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +      input by: travc
      // +      input by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
      // +   improved by: Lars Fischer
      // +      input by: Ratheous
      // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
      // +   bugfixed by: Joris
      // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
      // %          note 1: This reflects PHP 5.3/6.0+ behavior
      // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
      // %        note 2: pages served as UTF-8
      // *     example 1: urlencode('Kevin van Zonneveld!');
      // *     returns 1: 'Kevin+van+Zonneveld%21'
      // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
      // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
      // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
      // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
      str = (str + '').toString();

      // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
      // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
      return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
      replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
    }

	Views.SearchView = Backbone.View.extend({
		template: _.template(searchListingTemplate),

		events: {
			"click button#btn-pledge": "pledgeClick"
		},

		pledgeClick: function() {

		},

		initialize: function() {
			this.listenTo(this.model, "change", this.render);
			this.id = "search-" + this.model.attributes.id;
		},

		render: function() {
			this.$el.html(this.template(this.model.attributes));
			return this;
		}
	});

	Views.SearchListing = Backbone.View.extend({
		initialize: function() {
			this.listenTo(this.collection, 'add', this.collectionAdded);
			this.listenTo(this.collection, 'change', this.collectionChanged);
			this.listenTo(this.collection, 'remove', this.collectionRemoved);

			this.childViews = [];

			this._addAllModels();
		},

		render: function() {
			var fragment = document.createDocumentFragment();

			if (this.childViews.length > 0) {
				_(this.childViews).each(function(currentView) {
					fragment.appendChild(currentView.render().el);
				});
			} else {
				$(emptySearchTemplate).appendTo(fragment);
			}

			this.$('.item-listing').html(fragment);
			return this;
		},

		collectionAdded: function(item) {
			this._addViewForModel(item);
			this.render();
		},

		collectionRemoved: function(item) {
			this.childViews = this.childViews.filter(function(view) {
				return view.model.id !== item.id;
			});
			this.render();
		},

		collectionChanged: function() {
			this.childViews = [];
			this._addAllModels();
		},

		_addViewForModel: function(item) {
			this.childViews.push(new Views.SearchView({
				model: item
			}));
		},

		_addAllModels: function() {
			this.collection.each(function(item) {
				_addViewForModel(item);
			});
			this.render();
		}
	});

	Views.SearchForm = Backbone.View.extend({
		template: _.template(searchFormTemplate),

		events: {
			"click a#btn-search": "searchClick",
            "keypress input[type=text]": "keypress"
		},

        keypress: function(e) {
            switch (e.keyCode) {
                case 13:
                this.searchClick();
            }
        },

		searchClick: function() {
			var search = $('#txt-search').val();
			this.searchCollection.url = '/service/products/search/' + urlencode(urlencode(search));
			this.searchCollection.fetch({
			    success: function(results) {
        			$('#lbl-search').text(search);
        			$('#search-results').show();
			    }
			});
			this.searchListingView.render();
		},

		initialize: function() {
			this.render();
			this.searchCollection = new Models.SearchResults();
			this.searchListingView = new Views.SearchListing({
				collection: this.searchCollection,
				el: '#search-results',
				id: 'search-results'
			});
		},

		render: function() {
			this.$el.html(this.template());
			return this;
		}
	});

	return Views;
});<|endoftext|>


<commit_before>/**
 * Created by YU on 2015/8/4.
 */

var webpack = require('webpack');

module.exports = {
    watch: true,
    output:{
        path:__dirname + '/bundle/js/',
        publicPath:'/demo-with-webpack/assets/bundle/js/',//配置chunkFile加载地址的,这里要写服务器路径
        filename:'[name].js',
        chunkFilename:'[name].chunk.js'
    },
    cache:true,
    module:{
        loaders:[
            {test:/\.less$/,loader:"style!css!less"},//less加载
            {test:/\.json$/,loader:'json'}//加载json对象
        ]
    },
    resolve:{
        root:[__dirname + '/js/',__dirname + '/dep/'],
        extensions:['.js','.less',''],
        modulesDirectories:['node_modules'],
        alias:{
            'printer':'jquery.PrintArea.js',
            'echarts$':'echarts/echarts.js',
            'echarts':'echarts/src',
            'zrender$':'zrender/src/zrender.js',
            'zrender':'zrender/src'
        }
    },
    plugins:[
        //new webpack.optimize.CommonsChunkPlugin('vendor','vendor.js',Infinity)
        new webpack.optimize.CommonsChunkPlugin({
            name:'vendor',
            filename:'vendor.js',
            minChunks:/*4*/Infinity//Infinity 代表不进行合并，主要是开发的时候能用上，线上版本的时候 最好写成一个数字比如3，当出现3次的时候将打包进入vendor中
        })
    ],
    externals:{
        'jquery':'$'
    }
};<commit_msg>add  message<commit_after>/**
 * Created by YU on 2015/8/4.
 */

var webpack = require('webpack');

module.exports = {
    watch: true,
    output:{
        path:__dirname + '/bundle/js/',
        publicPath:'/demo-with-webpack/assets/bundle/js/',//配置chunkFile加载地址的,这里要写服务器路径,可以写cdn的地址
        filename:'[name].js',
        chunkFilename:'[name].chunk.js'
    },
    cache:true,
    module:{
        loaders:[
            {test:/\.less$/,loader:"style!css!less"},//less加载
            {test:/\.json$/,loader:'json'}//加载json对象
        ]
    },
    resolve:{
        root:[__dirname + '/js/',__dirname + '/dep/'],
        extensions:['.js','.less',''],
        modulesDirectories:['node_modules'],
        alias:{
            'printer':'jquery.PrintArea.js',
            'echarts$':'echarts/echarts.js',
            'echarts':'echarts/src',
            'zrender$':'zrender/src/zrender.js',
            'zrender':'zrender/src'
        }
    },
    plugins:[
        //new webpack.optimize.CommonsChunkPlugin('vendor','vendor.js',Infinity)
        new webpack.optimize.CommonsChunkPlugin({
            name:'vendor',
            filename:'vendor.js',
            minChunks:/*4*/Infinity//Infinity 代表不进行合并，主要是开发的时候能用上，线上版本的时候 最好写成一个数字比如3，当出现3次的时候将打包进入vendor中
        })
    ],
    externals:{
        'jquery':'$'
    }
};<|endoftext|>


<commit_before>Router.map(function () {
	this.route('find', {
		path: '/find/:query?',
		template: 'find',
		waitOn: function () {
			var region = Session.get('region')
			var filter = {}
			if (this.params.hasUpcomingEvent) filter.hasUpcomingEvent = true
			return Meteor.subscribe('coursesFind', region, this.params.query, filter);
		},
		data: function() {
			return {
				hasUpcomingEvent: this.params.hasUpcomingEvent,
				query: this.params.query,
				results: Courses.find()
			}
		},
		onAfterAction: function() {
			document.title = webpagename + 'Find ' + this.params.query
		}
	})
})

var submitForm = function(event) {
	options = {}
	if ($("#hasUpcomingEvent")[0].checked) {
		options.query = "hasUpcomingEvent";
	}

	Router.go('find', { query: $('#find').val().replace("/", " ")}, options )
	event.preventDefault();
	event.stopPropagation();
	return false;
}

Template.find.events({
	'submit': submitForm,
	'change': submitForm
});

Template.find.helpers({
	'hasUpcomingEventsChecked': function() {
		if (this.hasUpcomingEvent) return "checked";
	}
})<commit_msg>fix search<commit_after>Router.map(function () {
	this.route('find', {
		path: '/find/:search?',
		template: 'find',
		waitOn: function () {
			var region = Session.get('region')
			var filter = {}
			if (this.params.hasUpcomingEvent) filter.hasUpcomingEvent = true;
			return Meteor.subscribe('coursesFind', region, this.params.search, filter);
		},
		data: function() {
			return {
				hasUpcomingEvent: this.params.hasUpcomingEvent,
				query: this.params.search,
				results: Courses.find()
			}
		},
		onAfterAction: function() {
			document.title = webpagename + 'Find ' + this.params.search
		}
	})
})

var submitForm = function(event) {
	options = {}
	if ($("#hasUpcomingEvent")[0].checked) {
		options.query = "hasUpcomingEvent";
	}

	Router.go('find', { query: $('#find').val().replace("/", " ")}, options )
	event.preventDefault();
	event.stopPropagation();
	return false;
}

Template.find.events({
	'submit': submitForm,
	'change': submitForm
});

Template.find.helpers({
	'hasUpcomingEventsChecked': function() {
		if (this.hasUpcomingEvent) return "checked";
	}
})<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { LicenseWebpackPlugin } = require('license-webpack-plugin')
const project = require('./project.config')

const __DEV__ = project.env === 'development'
const __TEST__ = project.env === 'test'
const __PROD__ = project.env === 'production'

const config = {
  mode: __PROD__ ? 'production' : 'development',
  entry: {
    main: [
      './src/main.js'
    ],
  },
  output: {
    path: path.join(project.basePath, 'dist'),
    filename: __DEV__ ? '[name].js' : '[name].[hash].js',
    publicPath: project.publicPath,
  },
  resolve: {
    modules: [
      path.join(project.basePath, 'src'),
      'node_modules',
    ],
    alias: {
      'shared': path.join(project.basePath, 'shared'),
    }
  },
  module: { rules: [] },
  plugins: [
    new webpack.DefinePlugin(Object.assign({
      'process.env': { NODE_ENV: JSON.stringify(project.env) },
      __DEV__,
      __TEST__,
      __PROD__,
    }, project.globals)),
    new CaseSensitivePathsPlugin(),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
}

if (__PROD__) {
  // copy static assets in /assets to /dist
  config.plugins.push(new CopyWebpackPlugin([{
    from: path.join(project.basePath, 'assets'),
    to: path.join(project.basePath, 'dist'),
  }], { /* options */ }))

  // @TODO: using style-loader in development until
  // MiniCssExtractPlugin supports HMR
  config.plugins.push(new MiniCssExtractPlugin({
    filename: __DEV__ ? '[name].css' : '[name].[hash].css',
    chunkFilename: __DEV__ ? '[id].css' : '[id].[hash].css',
  }))

  config.plugins.push(new LicenseWebpackPlugin({
    addBanner: true,
    outputFilename: 'license_en.txt',
    perChunkOutput: false,
    renderLicenses: (modules) => {
      let txt = ''

      modules.forEach(m => {
        if (!m.licenseText) return

        txt += '\n' + '*'.repeat(80) + '\n\n'
        txt += m.packageJson.name + '\n'
        txt += m.licenseText.replace(/(\S)\n(\S)/gm, '$1 $2')
      })

      return fs.readFileSync('./LICENSE', 'utf8') + txt
    },
  }))
}

// HTML Template
config.plugins.push(new HtmlWebpackPlugin({
  template: './src/index.html',
  inject: true,
}))

// Loaders
// ------------------------------------

// JavaScript
config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    options: {
      cacheDirectory: __DEV__,
      plugins: [
        '@babel/plugin-transform-runtime',
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-object-rest-spread',
        ['react-css-modules', {
          webpackHotModuleReloading: __DEV__,
          'generateScopedName' : '[name]__[local]___[hash:base64:5]',
        }]
      ],
      presets: [
        '@babel/preset-env',
        '@babel/preset-react',
      ]
    },
  }],
})

// Global Style
config.module.rules.push({
  test : /(global)\.css$/,
  use  : [{
    loader : __PROD__ ? MiniCssExtractPlugin.loader : 'style-loader',
  }, {
    loader  : 'css-loader',
    options : {
      modules   : false,
      sourceMap : false,
    }
  }],
})

// CSS Modules
config.module.rules.push({
  test : /\.css$/,
  exclude : /(global)\.css$/,
  use  : [{
    loader : __PROD__ ? MiniCssExtractPlugin.loader : 'style-loader',
  }, {
    loader  : 'css-loader',
    options : {
      modules   : true,
      localIdentName: '[name]__[local]___[hash:base64:5]',
    }
  }],
})

// Files
config.module.rules.push(
  {
    test    : /\.woff(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'application/font-woff'
    }
  },
  {
    test    : /\.woff2(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'application/font-woff2'
    }
  },
  {
    test    : /\.svg(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'image/svg+xml'
    }
  },
  {
    test    : /\.(png|jpg|gif)$/,
    loader  : 'url-loader',
    options : {
      limit : '8192'
    }
  }
)

module.exports = config
<commit_msg>License as displayed in the Windows installer wraps at 71<commit_after>const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { LicenseWebpackPlugin } = require('license-webpack-plugin')
const project = require('./project.config')

const __DEV__ = project.env === 'development'
const __TEST__ = project.env === 'test'
const __PROD__ = project.env === 'production'

const config = {
  mode: __PROD__ ? 'production' : 'development',
  entry: {
    main: [
      './src/main.js'
    ],
  },
  output: {
    path: path.join(project.basePath, 'dist'),
    filename: __DEV__ ? '[name].js' : '[name].[hash].js',
    publicPath: project.publicPath,
  },
  resolve: {
    modules: [
      path.join(project.basePath, 'src'),
      'node_modules',
    ],
    alias: {
      'shared': path.join(project.basePath, 'shared'),
    }
  },
  module: { rules: [] },
  plugins: [
    new webpack.DefinePlugin(Object.assign({
      'process.env': { NODE_ENV: JSON.stringify(project.env) },
      __DEV__,
      __TEST__,
      __PROD__,
    }, project.globals)),
    new CaseSensitivePathsPlugin(),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
}

if (__PROD__) {
  // copy static assets in /assets to /dist
  config.plugins.push(new CopyWebpackPlugin([{
    from: path.join(project.basePath, 'assets'),
    to: path.join(project.basePath, 'dist'),
  }], { /* options */ }))

  // @TODO: using style-loader in development until
  // MiniCssExtractPlugin supports HMR
  config.plugins.push(new MiniCssExtractPlugin({
    filename: __DEV__ ? '[name].css' : '[name].[hash].css',
    chunkFilename: __DEV__ ? '[id].css' : '[id].[hash].css',
  }))

  config.plugins.push(new LicenseWebpackPlugin({
    addBanner: true,
    outputFilename: 'license_en.txt',
    perChunkOutput: false,
    renderLicenses: (modules) => {
      let txt = ''

      modules.forEach(m => {
        if (!m.licenseText) return

        txt += '\n' + '*'.repeat(71) + '\n\n'
        txt += m.packageJson.name + '\n'
        txt += m.licenseText.replace(/(\S)\n(\S)/gm, '$1 $2')
      })

      return fs.readFileSync('./LICENSE', 'utf8') + txt
    },
  }))
}

// HTML Template
config.plugins.push(new HtmlWebpackPlugin({
  template: './src/index.html',
  inject: true,
}))

// Loaders
// ------------------------------------

// JavaScript
config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    options: {
      cacheDirectory: __DEV__,
      plugins: [
        '@babel/plugin-transform-runtime',
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-object-rest-spread',
        ['react-css-modules', {
          webpackHotModuleReloading: __DEV__,
          'generateScopedName' : '[name]__[local]___[hash:base64:5]',
        }]
      ],
      presets: [
        '@babel/preset-env',
        '@babel/preset-react',
      ]
    },
  }],
})

// Global Style
config.module.rules.push({
  test : /(global)\.css$/,
  use  : [{
    loader : __PROD__ ? MiniCssExtractPlugin.loader : 'style-loader',
  }, {
    loader  : 'css-loader',
    options : {
      modules   : false,
      sourceMap : false,
    }
  }],
})

// CSS Modules
config.module.rules.push({
  test : /\.css$/,
  exclude : /(global)\.css$/,
  use  : [{
    loader : __PROD__ ? MiniCssExtractPlugin.loader : 'style-loader',
  }, {
    loader  : 'css-loader',
    options : {
      modules   : true,
      localIdentName: '[name]__[local]___[hash:base64:5]',
    }
  }],
})

// Files
config.module.rules.push(
  {
    test    : /\.woff(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'application/font-woff'
    }
  },
  {
    test    : /\.woff2(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'application/font-woff2'
    }
  },
  {
    test    : /\.svg(\?.*)?$/,
    loader  : 'url-loader',
    options : {
      prefix   : 'fonts/',
      name     : 'fonts/[name].[ext]',
      limit    : '10000',
      mimetype : 'image/svg+xml'
    }
  },
  {
    test    : /\.(png|jpg|gif)$/,
    loader  : 'url-loader',
    options : {
      limit : '8192'
    }
  }
)

module.exports = config
<|endoftext|>


<commit_before>// ==UserScript==
// @name         nbr_sidebar.js
// @author       katalin_2003
// @version      1.7
// @downloadURL  https://raw.githubusercontent.com/katalin2003/tampermonkey-TG/master/scripts/nbr_sidebar.js
// @description  show hide side menu on http://forum.notebookreview.com
// @include      http://forum.notebookreview.com/*
// @include      http://forum.tabletpcreview.com/*
// @include      http://forum.brighthand.com/*
// @grant        none
// ==/UserScript==

// Let's make it easier to add global styles
function addStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// change font family
// Yeah, I know this is evil but still better than serif text.
addStyle('* { font-family: sans-serif !important; }');

// reduce the min-height of messages to gain some vertical space in the case of small messages.
// or you can get the size of .messageUserInfo and use that value as the min-height for messages, though the former might not always have a fixed height for all users.
addStyle('.messageContent { min-height: 2em !important; }');

// add the missing right border..OCD much :)
addStyle('ol#forums { border-right: 1px solid #7B7B7B !important; }');
addStyle('div.sectionMain { border-right: 1px solid #7B7B7B !important; }');

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

// Toggle visibility function
function toggle(obj) {
    //  var el = document.getElementById(obj);
    var el = document.getElementsByClassName(obj)[0],
        mainContent = document.getElementsByClassName('mainContent')[0],
        elWidth,
        mainContentWidth;
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
        sideTgl.innerHTML = '<<';
        mainContent.style.width = '100%';

        elWidth = el.offsetWidth;
        mainContentWidth = mainContent.offsetWidth;
        console.log('katalin_2003: sidebar hidden');
        console.log('katalin_2003: mainContent width is: ' + mainContentWidth + 'px');
    }
    else {
        el.style.display = '';
        sideTgl.innerHTML = '>>';

        elWidth = el.offsetWidth;
        mainContentWidth = mainContent.offsetWidth;
        mainContent.style.width = (mainContentWidth - elWidth-10) +'px';

        console.log('katalin_2003: sidebar visible');
        console.log('katalin_2003: mainContent width is: ' + (mainContentWidth-elWidth-10) + 'px');
    }
}

var sideTgl = document.createElement('div');
sideTgl.setAttribute('id', "sidebarToggle");
sideTgl.style.cssFloat = 'right';
//sideTgl.style.color = '#000000';

sideTgl.innerHTML = ">>";
//var div = document.getElementsByClassName("blockLinksList")[0];
var div = document.getElementsByClassName("breadBoxTop")[0];
insertAfter(div, sideTgl);

addStyle('div#sidebarToggle { border: 1px solid #7B7B7B; }');
addStyle('div#sidebarToggle { border-radius: 2px; }');
addStyle('div#sidebarToggle { padding: 1px 10px; }');
addStyle('div#sidebarToggle { margin-top: 3px; }');
//addStyle('div#sidebarToggle { margin-right: 20px; }');
addStyle('div#sidebarToggle:hover { cursor: pointer; }');
addStyle('div#sidebarToggle:hover { background-color: #F0F0F0; }');

var sidebarToggle = document.getElementById('sidebarToggle');
sidebarToggle.setAttribute('title' , 'Toggle sidebar visibility');

// Hide the sidebar by default
(function() {
    toggle('sidebar');
    console.log('hidden');
    return false;
})();

// Toggle sidebar's visibility on click
sidebarToggle.onclick = function () {
    toggle('sidebar');
    return false;
};

// remove "Latest" string in front of thread titles
addStyle('span.lastThreadTitle > span { display:none; }');
// increase the width of the element containig the latest thread in a sub forum
addStyle('.node .nodeLastPost { width: 30%; }');
// push the nodeControl icons (RSS etc..) to the left to compensate
addStyle('.node .nodeControls { right: 32%; }');
// make quote blocks fit nicely in the message block
addStyle('.bbCodeBlock { margin: 1em 0 1em 0; }');
<commit_msg>Added updateURL<commit_after>// ==UserScript==
// @name         nbr_sidebar.js
// @author       katalin_2003
// @version      1.7
// @downloadURL  https://raw.githubusercontent.com/katalin2003/tampermonkey-TG/master/scripts/nbr_sidebar.js
// @updateURL    https://raw.githubusercontent.com/katalin2003/tampermonkey-TG/master/scripts/nbr_sidebar.js
// @description  show hide side menu on http://forum.notebookreview.com
// @include      http://forum.notebookreview.com/*
// @include      http://forum.tabletpcreview.com/*
// @include      http://forum.brighthand.com/*
// @grant        none
// ==/UserScript==

// Let's make it easier to add global styles
function addStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// change font family
// Yeah, I know this is evil but still better than serif text.
addStyle('* { font-family: sans-serif !important; }');

// reduce the min-height of messages to gain some vertical space in the case of small messages.
// or you can get the size of .messageUserInfo and use that value as the min-height for messages, though the former might not always have a fixed height for all users.
addStyle('.messageContent { min-height: 2em !important; }');

// add the missing right border..OCD much :)
addStyle('ol#forums { border-right: 1px solid #7B7B7B !important; }');
addStyle('div.sectionMain { border-right: 1px solid #7B7B7B !important; }');

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

// Toggle visibility function
function toggle(obj) {
    //  var el = document.getElementById(obj);
    var el = document.getElementsByClassName(obj)[0],
        mainContent = document.getElementsByClassName('mainContent')[0],
        elWidth,
        mainContentWidth;
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
        sideTgl.innerHTML = '<<';
        mainContent.style.width = '100%';

        elWidth = el.offsetWidth;
        mainContentWidth = mainContent.offsetWidth;
        console.log('katalin_2003: sidebar hidden');
        console.log('katalin_2003: mainContent width is: ' + mainContentWidth + 'px');
    }
    else {
        el.style.display = '';
        sideTgl.innerHTML = '>>';

        elWidth = el.offsetWidth;
        mainContentWidth = mainContent.offsetWidth;
        mainContent.style.width = (mainContentWidth - elWidth-10) +'px';

        console.log('katalin_2003: sidebar visible');
        console.log('katalin_2003: mainContent width is: ' + (mainContentWidth-elWidth-10) + 'px');
    }
}

var sideTgl = document.createElement('div');
sideTgl.setAttribute('id', "sidebarToggle");
sideTgl.style.cssFloat = 'right';
//sideTgl.style.color = '#000000';

sideTgl.innerHTML = ">>";
//var div = document.getElementsByClassName("blockLinksList")[0];
var div = document.getElementsByClassName("breadBoxTop")[0];
insertAfter(div, sideTgl);

addStyle('div#sidebarToggle { border: 1px solid #7B7B7B; }');
addStyle('div#sidebarToggle { border-radius: 2px; }');
addStyle('div#sidebarToggle { padding: 1px 10px; }');
addStyle('div#sidebarToggle { margin-top: 3px; }');
//addStyle('div#sidebarToggle { margin-right: 20px; }');
addStyle('div#sidebarToggle:hover { cursor: pointer; }');
addStyle('div#sidebarToggle:hover { background-color: #F0F0F0; }');

var sidebarToggle = document.getElementById('sidebarToggle');
sidebarToggle.setAttribute('title' , 'Toggle sidebar visibility');

// Hide the sidebar by default
(function() {
    toggle('sidebar');
    console.log('hidden');
    return false;
})();

// Toggle sidebar's visibility on click
sidebarToggle.onclick = function () {
    toggle('sidebar');
    return false;
};

// remove "Latest" string in front of thread titles
addStyle('span.lastThreadTitle > span { display:none; }');
// increase the width of the element containig the latest thread in a sub forum
addStyle('.node .nodeLastPost { width: 30%; }');
// push the nodeControl icons (RSS etc..) to the left to compensate
addStyle('.node .nodeControls { right: 32%; }');
// make quote blocks fit nicely in the message block
addStyle('.bbCodeBlock { margin: 1em 0 1em 0; }');
<|endoftext|>