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

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

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

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

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

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {
      'polyfills': './src/polyfills.browser.ts',
      'twbs':      'bootstrap-loader',
      'main':      AOT ? './src/main.browser.aot.ts' :
        './src/main.browser.ts'
    },

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

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

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

    },

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

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

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

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['raw-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['sass-loader', 'raw-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * Bootstrap 4 loader
         */
        {
          test: /bootstrap\/dist\/js\/umd\//,
          use: 'imports-loader?jQuery=jquery'
        },

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

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        },

      ],

    },

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

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

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

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

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

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

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

      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery",
        Tether: "tether",
        "window.Tether": "tether",
        Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
        Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
        Button: "exports-loader?Button!bootstrap/js/dist/button",
        Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
        Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
        Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
        Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
        Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
        Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
        Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
        Util: "exports-loader?Util!bootstrap/js/dist/util"
      }),

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

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

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

  };
}
<commit_msg>try fixe<commit_after>/**
 * @author: @AngularClass
 */

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

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

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

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

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {
      'polyfills': './src/polyfills.browser.ts',
      'twbs':      'bootstrap-loader',
      'main':      AOT ? './src/main.browser.aot.ts' :
        './src/main.browser.ts'
    },

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

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

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

    },

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

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

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

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['raw-loader','style-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['sass-loader', 'raw-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * Bootstrap 4 loader
         */
        {
          test: /bootstrap\/dist\/js\/umd\//,
          use: 'imports-loader?jQuery=jquery'
        },

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

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        },

      ],

    },

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

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

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

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

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

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

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

      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery",
        Tether: "tether",
        "window.Tether": "tether",
        Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
        Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
        Button: "exports-loader?Button!bootstrap/js/dist/button",
        Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
        Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
        Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
        Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
        Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
        Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
        Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
        Util: "exports-loader?Util!bootstrap/js/dist/util"
      }),

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

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

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

  };
}
<|endoftext|>


<commit_before>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var NpmInstallPlugin = require('npm-install-webpack-plugin');
var autoprefixer = require('autoprefixer');
var helpers = require('./helpers');
var CopyPlugin = require('copy-webpack-plugin');

var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = {
    entry: {
        'polyfills': './scripts/polyfills.ts',
        'vendor': './scripts/vendor.ts',
        'app': './scripts/main.ts'
    },

    resolve: {
        extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
    },

    module: {
        loaders: [{
                test: /\.ts$/,
                loaders: ['ts', 'angular2-template-loader']
            }, {
                test: /\.html$/,
                loader: 'html'
            }, {
                test: /\.(png|jpe?g|gif|svg|ttf|eot|ico)$/,
                loader: 'file?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src'),
                loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
            }, {
                test: /\.css$/,
                include: helpers.root('src'),
                loader: 'raw!postcss'
            },
            // support for .scss files
            // use 'null' loader in test mode (https://github.com/webpack/null-loader)
            // all css in src/style will be bundled in an external css file
            {
                test: /\.scss$/,
                exclude: helpers.root('src'),
                loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
            },
            //all css required in src/app files will be merged in js files
            {
                test: /\.scss$/,
                exclude: helpers.root('styles'),
                loader: 'raw!postcss!sass'
            }
        ],
        preloaders: [{
            test: /\.js/,
            loader: 'source-map-loader'
        }]
    },

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

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

        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),

        new CopyPlugin([{
            from: "bower_components/vss-web-extension-sdk/lib/VSS.SDK.min.js",
            to:""
        }])
    ],

    /**
     * PostCSS
     * Reference: https://github.com/postcss/autoprefixer-core
     * Add vendor prefixes to your css
     */
    postcss: [
        autoprefixer({
            browsers: ['last 2 version']
        })
    ],

    /**
     * Sass
     * Reference: https://github.com/jtangelder/sass-loader
     * Transforms .scss files to .css
     */
    sassLoader: {
        //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
    }
};

<commit_msg>adding tfs namespaces as externals<commit_after>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var NpmInstallPlugin = require('npm-install-webpack-plugin');
var autoprefixer = require('autoprefixer');
var helpers = require('./helpers');
var CopyPlugin = require('copy-webpack-plugin');

var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

module.exports = {
    entry: {
        'polyfills': './scripts/polyfills.ts',
        'vendor': './scripts/vendor.ts',
        'app': './scripts/main.ts'
    },

    externals: [
        /^VSS\/.*/, /^TFS\/.*/, /^q$/
    ],

    resolve: {
        extensions: ['', '.ts', '.js', '.json', '.css', '.scss', '.html']
    },

    module: {
        loaders: [{
                test: /\.ts$/,
                loaders: ['ts', 'angular2-template-loader']
            }, {
                test: /\.html$/,
                loader: 'html'
            }, {
                test: /\.(png|jpe?g|gif|svg|ttf|eot|ico)$/,
                loader: 'file?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
            },
            // support for .scss files
            // use 'null' loader in test mode (https://github.com/webpack/null-loader)
            // all css in src/style will be bundled in an external css file
            {
                test: /\.scss$/,
                loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
            }
        ],
        preloaders: [{
            test: /\.js/,
            loader: 'source-map-loader'
        }]
    },

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

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

        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(".bower.json", ["main"])
        ),

        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),

        new CopyPlugin([{
            from: "bower_components/vss-web-extension-sdk/lib/VSS.SDK.min.js",
            to:""
        }])
    ],

    /**
     * PostCSS
     * Reference: https://github.com/postcss/autoprefixer-core
     * Add vendor prefixes to your css
     */
    postcss: [
        autoprefixer({
            browsers: ['last 2 version']
        })
    ],

    /**
     * Sass
     * Reference: https://github.com/jtangelder/sass-loader
     * Transforms .scss files to .css
     */
    sassLoader: {
        //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
    }
};

<|endoftext|>


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

var CleanPlugin = require('clean-webpack-plugin');
var HtmlPlugin = require('html-webpack-plugin');

__dirname = path.resolve(__dirname, '..');

module.exports = {
  devtool: 'source-map',
  __dirname: __dirname,
  entry: {
    candela: ['./src/candela/index.js'],
    demo: './app/demo/index.js',
    resize: './app/resize/index.js'
  },
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    path: 'build',
    filename: '[name]/[name].js'
  },
  resolve: {
    alias: {
      vega: path.resolve(__dirname, 'node_modules/vega/index.js'),
      d3: path.resolve(__dirname, 'node_modules/d3/d3.min.js')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      vg: 'vega'
    }),

    new CleanPlugin([
      './build'
    ]),

    new HtmlPlugin({
      title: 'Candela Demo',
      filename: 'demo/index.html',
      chunks: ['demo']
    }),

    new HtmlPlugin({
      title: 'Resize Test',
      filename: 'resize/index.html',
      chunks: ['resize']
    })
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'semistandard',
        include: [
          path.resolve(__dirname, 'src/candela'),
          path.resolve(__dirname, 'app')
        ],
        exclude: path.resolve(__dirname, 'src', 'external')
      }
    ],
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        include: [
          __dirname + '/src',
          __dirname + '/app'
        ]
      },
      {
        test: function (path) {
          return path.endsWith('/src/external/pc.js');
        },
        loader: 'legacy'
      },
      {
        test: /\.styl$/,
        loaders: ['style', 'css', 'stylus']
      },
      {
        test: /\.jade$/,
        loaders: ['jade']
      },
      {
        test: /\.json$/,
        loader: 'json'
      }
    ]
  }
};
<commit_msg>Change clean rule to empty the build directory, not remove it<commit_after>var webpack = require('webpack');
var path = require('path');

var CleanPlugin = require('clean-webpack-plugin');
var HtmlPlugin = require('html-webpack-plugin');

__dirname = path.resolve(__dirname, '..');

module.exports = {
  devtool: 'source-map',
  __dirname: __dirname,
  entry: {
    candela: ['./src/candela/index.js'],
    demo: './app/demo/index.js',
    resize: './app/resize/index.js'
  },
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    path: 'build',
    filename: '[name]/[name].js'
  },
  resolve: {
    alias: {
      vega: path.resolve(__dirname, 'node_modules/vega/index.js'),
      d3: path.resolve(__dirname, 'node_modules/d3/d3.min.js')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      vg: 'vega'
    }),

    new CleanPlugin([
      './build/*'
    ]),

    new HtmlPlugin({
      title: 'Candela Demo',
      filename: 'demo/index.html',
      chunks: ['demo']
    }),

    new HtmlPlugin({
      title: 'Resize Test',
      filename: 'resize/index.html',
      chunks: ['resize']
    })
  ],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'semistandard',
        include: [
          path.resolve(__dirname, 'src/candela'),
          path.resolve(__dirname, 'app')
        ],
        exclude: path.resolve(__dirname, 'src', 'external')
      }
    ],
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        include: [
          __dirname + '/src',
          __dirname + '/app'
        ]
      },
      {
        test: function (path) {
          return path.endsWith('/src/external/pc.js');
        },
        loader: 'legacy'
      },
      {
        test: /\.styl$/,
        loaders: ['style', 'css', 'stylus']
      },
      {
        test: /\.jade$/,
        loaders: ['jade']
      },
      {
        test: /\.json$/,
        loader: 'json'
      }
    ]
  }
};
<|endoftext|>


<commit_before>/*
function updateOnResize() {
  var desc = demoplayer.videojs.videoWidth() +
             "x" +
             demoplayer.videojs.videoHeight();
  var current = document.getElementsByClassName("active button");
  for (var i = 0; i < current.length; i++) {
    if(current[i].id != "auto")
      current[i].setAttribute("class","button");
  }
  var newactive = document.getElementsByName(desc);
  for (var j = 0; j < newactive.length; j++)
    newactive[j].setAttribute("class","active button");
}

function requestResolution() {
  document.getElementById("auto").setAttribute("class","button");
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (this.id == i);
  }
}

function requestAuto() {
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = true;
  }
  document.getElementById("auto").setAttribute("class","active button");
}

function addButton(bid,qlevel,desc,css) {
      var btn = document.createElement("BUTTON");
      adaptive.appendChild(btn);
      btn.addEventListener("click", requestResolution);
      btn.innerHTML = desc;
      btn.setAttribute("id",bid);
      btn.setAttribute("class",css);
      btn.setAttribute("name",desc);
}

function changeOfResolution() {
  for (var i = 0; i < qualityLevels.length; i++) {
    var btn = document.getElementById(i);
    var qlevel = qualityLevels[i];
    var desc = qlevel.width + "x" + qlevel.height;
    var css = "button";
    if (i == qualityLevels.selectedIndex)
        css = "requested button";
    if(btn) {
      if(btn.getAttribute("class") != "active button")
        btn.setAttribute("class",css);
    }
    else
      addButton(i,qlevel,desc,css);
  }
}

function removeProfileButtons() {
  var loop = document.getElementsByClassName("button").length - 1;
  for (var i = 0; i < loop; i++) {
    var btn = document.getElementById(i)
    if(btn)
      adaptive.removeChild(btn);
  }
}

function setProfile() {
  removeProfileButtons();
  var profile;
  var profiles = document.getElementsByName("profile");
  for(var i = 0; i < profiles.length; i++){
    if(profiles[i].checked){
        profile = profiles[i].value;
    }
  }
  demoplayer.source("hd_trim2", { sourceTypes: ['hls'], transformation: {streaming_profile: profile } });
}
*/
var cld = cloudinary.Cloudinary.new({ cloud_name: 'hadar' });
/*
var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);
*/
var demoplayer = cld.videoPlayer('demo-adaptive-player');
 /*
var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });
*/
demoplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

function updateOnEvent(eventStr) {
  var list = document.getElementById('events-list');
  var entry = document.createElement('li');
  entry.appendChild(document.createTextNode(eventStr));
  list.appendChild(entry);
  list.scrollTop = list.scrollHeight;
/*  var text = document.createTextNode(eventStr);
  var textDiv = document.createElement('div');
  textDiv.appendChild(text);
  eventsDiv.appendChild(textDiv);
  eventsDiv.scrollTop = eventsDiv.scrollHeight;*/
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var eventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek', 'sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

eventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr);
      })
    });

 eventplayer.source('hls_30s_test',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

 var plistplayer = cld.videoPlayer('demo-playlist-player');

 plistplayer.source('game2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

var recplayer = cld.videoPlayer('demo-recommendation-player',{ autoShowRecommendations: true });

var source1 = { publicId: 'Homepage_2', info: { title: 'Kid Play', subtitle: 'A preview' } };
var source2 = { publicId: 'game2', info: { title: 'Game', subtitle: 'A game ad' } };
var source3 = { publicId: 'hd_trim2', info: { title: 'Race', subtitle: 'Volve Ocean Race' } };
var source4 = { publicId: 'hls_30s_test', info: { title: 'NBA', subtitle: 'A game' } };
var source5 = { publicId: 'oceans', info: { title: 'Oceans', subtitle: 'A movie about oceans' } };
source1.recommendations = [source2, source3, source4, source5];
source2.recommendations = [source3];
source3.recommendations = [source4];
source4.recommendations = [source5];
source5.recommendations = [source2, source3, source4, source1];
recplayer.source(source1);

<commit_msg>Update draft.js<commit_after>/*
function updateOnResize() {
  var desc = demoplayer.videojs.videoWidth() +
             "x" +
             demoplayer.videojs.videoHeight();
  var current = document.getElementsByClassName("active button");
  for (var i = 0; i < current.length; i++) {
    if(current[i].id != "auto")
      current[i].setAttribute("class","button");
  }
  var newactive = document.getElementsByName(desc);
  for (var j = 0; j < newactive.length; j++)
    newactive[j].setAttribute("class","active button");
}

function requestResolution() {
  document.getElementById("auto").setAttribute("class","button");
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (this.id == i);
  }
}

function requestAuto() {
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = true;
  }
  document.getElementById("auto").setAttribute("class","active button");
}

function addButton(bid,qlevel,desc,css) {
      var btn = document.createElement("BUTTON");
      adaptive.appendChild(btn);
      btn.addEventListener("click", requestResolution);
      btn.innerHTML = desc;
      btn.setAttribute("id",bid);
      btn.setAttribute("class",css);
      btn.setAttribute("name",desc);
}

function changeOfResolution() {
  for (var i = 0; i < qualityLevels.length; i++) {
    var btn = document.getElementById(i);
    var qlevel = qualityLevels[i];
    var desc = qlevel.width + "x" + qlevel.height;
    var css = "button";
    if (i == qualityLevels.selectedIndex)
        css = "requested button";
    if(btn) {
      if(btn.getAttribute("class") != "active button")
        btn.setAttribute("class",css);
    }
    else
      addButton(i,qlevel,desc,css);
  }
}

function removeProfileButtons() {
  var loop = document.getElementsByClassName("button").length - 1;
  for (var i = 0; i < loop; i++) {
    var btn = document.getElementById(i)
    if(btn)
      adaptive.removeChild(btn);
  }
}

function setProfile() {
  removeProfileButtons();
  var profile;
  var profiles = document.getElementsByName("profile");
  for(var i = 0; i < profiles.length; i++){
    if(profiles[i].checked){
        profile = profiles[i].value;
    }
  }
  demoplayer.source("hd_trim2", { sourceTypes: ['hls'], transformation: {streaming_profile: profile } });
}
*/
var cld = cloudinary.Cloudinary.new({ cloud_name: 'hadar' });
/*
var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);
*/
var demoplayer = cld.videoPlayer('demo-adaptive-player');
 /*
var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });
*/
demoplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

function updateOnEvent(eventStr) {
  var list = document.getElementById('events-list');
  var entry = document.createElement('li');
  if (eventStr.includes("timeplayed"))
      entry.className = "orange";
  entry.appendChild(document.createTextNode(eventStr));
  list.appendChild(entry);
  list.scrollTop = list.scrollHeight;
/*  var text = document.createTextNode(eventStr);
  var textDiv = document.createElement('div');
  textDiv.appendChild(text);
  eventsDiv.appendChild(textDiv);
  eventsDiv.scrollTop = eventsDiv.scrollHeight;*/
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var eventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek', 'sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

eventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr);
      })
    });

 eventplayer.source('hls_30s_test',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

 var plistplayer = cld.videoPlayer('demo-playlist-player');

 plistplayer.source('game2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

var recplayer = cld.videoPlayer('demo-recommendation-player',{ autoShowRecommendations: true });

var source1 = { publicId: 'Homepage_2', info: { title: 'Kid Play', subtitle: 'A preview' } };
var source2 = { publicId: 'game2', info: { title: 'Game', subtitle: 'A game ad' } };
var source3 = { publicId: 'hd_trim2', info: { title: 'Race', subtitle: 'Volve Ocean Race' } };
var source4 = { publicId: 'hls_30s_test', info: { title: 'NBA', subtitle: 'A game' } };
var source5 = { publicId: 'oceans', info: { title: 'Oceans', subtitle: 'A movie about oceans' } };
source1.recommendations = [source2, source3, source4, source5];
source2.recommendations = [source3];
source3.recommendations = [source4];
source4.recommendations = [source5];
source5.recommendations = [source2, source3, source4, source1];
recplayer.source(source1);

<|endoftext|>


<commit_before>function updateOnResize() {
  var desc = demoplayer.videojs.videoWidth() +
             "x" +
             demoplayer.videojs.videoHeight();
  var current = document.getElementsByClassName("active button");
  for (var i = 0; i < current.length; i++) {
    if(current[i].id != "auto")
      current[i].setAttribute("class","button");
  }
  var newactive = document.getElementsByName(desc);
  for (var j = 0; j < newactive.length; j++)
    newactive[j].setAttribute("class","active button");
}

function requestResolution() {
  document.getElementById("auto").setAttribute("class","button");
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (this.id == i);
  }
}

function requestAuto() {
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = true;
  }
  document.getElementById("auto").setAttribute("class","active button");
}

function addButton(bid,qlevel,desc,css) {
      var btn = document.createElement("BUTTON");
      adaptive.appendChild(btn);
      btn.addEventListener("click", requestResolution);
      btn.innerHTML = desc;
      btn.setAttribute("id",bid);
      btn.setAttribute("class",css);
      btn.setAttribute("name",desc);
}

function changeOfResolution() {
  for (var i = 0; i < qualityLevels.length; i++) {
    var btn = document.getElementById(i);
    var qlevel = qualityLevels[i];
    var desc = qlevel.width + "x" + qlevel.height;
    var css = "button";
    if (i == qualityLevels.selectedIndex)
        css = "requested button";
    if(btn) {
      if(btn.getAttribute("class") != "active button")
        btn.setAttribute("class",css);
    }
    else
      addButton(i,qlevel,desc,css);
  }
}

function removeProfileButtons() {
  var loop = document.getElementsByClassName("button").length - 1;
  for (var i = 0; i < loop; i++) {
    var btn = document.getElementById(i)
    if(btn)
      adaptive.removeChild(btn);
  }
}

function setProfile() {
  removeProfileButtons();
  var profile;
  var profiles = document.getElementsByName("profile");
  for(var i = 0; i < profiles.length; i++){
    if(profiles[i].checked){
        profile = profiles[i].value;
    }
  }
  demoplayer.source("hd_trim2", { sourceTypes: ['hls'], transformation: {streaming_profile: profile } });
}

var cld = cloudinary.Cloudinary.new({ cloud_name: 'hadar' });

var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);

var demoplayer = cld.videoPlayer('demo-adaptive-player');

var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });

demoplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

function updateOnEvent(eventStr) {
  var eventsDiv = document.querySelector('#vid-events');
  var text = document.createTextNode(eventStr);
  var textDiv = document.createElement('div');
  textDiv.appendChild(text);
  eventsDiv.appendChild(textDiv);
  eventsDiv.scrollTop = eventsDiv.scrollHeight;
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var eventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek', 'sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

eventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr);
      })
    });

 eventplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

 function playMe() {
  var val = parseInt(this.value);
  plistplayer.playlist().playAtIndex(val);
}

function updateOnSrc() {
  var plist = plistplayer.playlist();
  var playing = plist.currentIndex();
  var loop = plist.length();
  for(var i=0; i<loop; i++) {
    var label = "list"+i;
    var btn = document.getElementById(label);
    if(i == playing)
      btn.setAttribute("class", "thumbnail playing");
    else
      btn.setAttribute("class", "thumbnail ");
  }
  console.log("updateOnSrc", playing, loop);
}

var plistplayer = cld.videoPlayer('demo-playlist-player');
plistplayer.on('sourcechanged', updateOnSrc);
plistplayer.playlist(
  [{ publicId: 'game2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'hls_30s_test', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'hd_trim2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'Homepage_2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }}],
   { autoAdvance: 0, repeat: true });

 plistplayer.source('game2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });
<commit_msg>Update video.js<commit_after>function updateOnResize() {
  var desc = demoplayer.videojs.videoWidth() +
             "x" +
             demoplayer.videojs.videoHeight();
  var current = document.getElementsByClassName("active button");
  for (var i = 0; i < current.length; i++) {
    if(current[i].id != "auto")
      current[i].setAttribute("class","button");
  }
  var newactive = document.getElementsByName(desc);
  for (var j = 0; j < newactive.length; j++)
    newactive[j].setAttribute("class","active button");
}

function requestResolution() {
  document.getElementById("auto").setAttribute("class","button");
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (this.id == i);
  }
}

function requestAuto() {
  for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = true;
  }
  document.getElementById("auto").setAttribute("class","active button");
}

function addButton(bid,qlevel,desc,css) {
      var btn = document.createElement("BUTTON");
      adaptive.appendChild(btn);
      btn.addEventListener("click", requestResolution);
      btn.innerHTML = desc;
      btn.setAttribute("id",bid);
      btn.setAttribute("class",css);
      btn.setAttribute("name",desc);
}

function changeOfResolution() {
  for (var i = 0; i < qualityLevels.length; i++) {
    var btn = document.getElementById(i);
    var qlevel = qualityLevels[i];
    var desc = qlevel.width + "x" + qlevel.height;
    var css = "button";
    if (i == qualityLevels.selectedIndex)
        css = "requested button";
    if(btn) {
      if(btn.getAttribute("class") != "active button")
        btn.setAttribute("class",css);
    }
    else
      addButton(i,qlevel,desc,css);
  }
}

function removeProfileButtons() {
  var loop = document.getElementsByClassName("button").length - 1;
  for (var i = 0; i < loop; i++) {
    var btn = document.getElementById(i)
    if(btn)
      adaptive.removeChild(btn);
  }
}

function setProfile() {
  removeProfileButtons();
  var profile;
  var profiles = document.getElementsByName("profile");
  for(var i = 0; i < profiles.length; i++){
    if(profiles[i].checked){
        profile = profiles[i].value;
    }
  }
  demoplayer.source("hd_trim2", { sourceTypes: ['hls'], transformation: {streaming_profile: profile } });
}

var cld = cloudinary.Cloudinary.new({ cloud_name: 'hadar' });

var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);

var demoplayer = cld.videoPlayer('demo-adaptive-player');

var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });

demoplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

function updateOnEvent(eventStr) {
  var eventsDiv = document.querySelector('#vid-events');
  var text = document.createTextNode(eventStr);
  var textDiv = document.createElement('div');
  textDiv.appendChild(text);
  eventsDiv.appendChild(textDiv);
  eventsDiv.scrollTop = eventsDiv.scrollHeight;
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var eventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek', 'sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

eventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr);
      })
    });

 eventplayer.source('hd_trim2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });

 function playMe(btn) {
  var val = parseInt(btn.value);
  plistplayer.playlist().playAtIndex(val);
}

function updateOnSrc() {
  var plist = plistplayer.playlist();
  var playing = plist.currentIndex();
  var loop = plist.length();
  for(var i=0; i<loop; i++) {
    var label = "list"+i;
    var btn = document.getElementById(label);
    if(i == playing)
      btn.setAttribute("class", "thumbnail playing");
    else
      btn.setAttribute("class", "thumbnail ");
  }
  console.log("updateOnSrc", playing, loop);
}

var plistplayer = cld.videoPlayer('demo-playlist-player');
plistplayer.on('sourcechanged', updateOnSrc);
plistplayer.playlist(
  [{ publicId: 'game2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'hls_30s_test', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'hd_trim2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }},
   { publicId: 'Homepage_2', sourceTypes: ['dash'], transformation: {streaming_profile: 'hd' }}],
   { autoAdvance: 0, repeat: true });

 plistplayer.source('game2',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'hd' } });
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = function jacksMergeProcessor(log) {
	return {
		$runAfter: ['computePathsProcessor'],
		$runBefore: ['renderDocsProcessor'],
		$process: function (docs) {

			// var jsDocs = docs.filter(function(doc) {
			// 	if (doc.docType === 'js'){
			// 		return true;
			// 	}
			// });

			// jsDocs.forEach(function(jsdoc, idx, arr) {
			// 	// todo:
			// 	// 1. 	a. update path
			// 	// 		b. create a new doctype for method
			// 	// 		c. ignore the doc, add directly to the angular stuff as dependencies
			// 	// 2. remove the element if it is added to a parent
			// 	jsdoc.codeNode.type === 'FunctionDeclaration'
			// });
			// 1. do some stuff with docs
			// 2. update path
			// 3. add reference link to parent service or directive
			// find the memberof tag
			// check type from doc.codeNode.type: e.g. FunctionDeclaration

			ngServiceDocs = _.filter(docs, { docType: 'ngService'});

			ngDirectiveDocs = _.filter(docs, {docType: 'ngDirective'});

			ngControllerDocs = _.filter(docs, {docType: 'ngController'});

			jsDocs = _.filter(docs, {docType: 'js'});

			jsDocs = _.filter(docs, function(doc) {
				var tags = doc.tags.tags;
				return _.find(tags, function(tag) {
					if(tag.tagName === 'memberof') {
						return true;
					}
					return false;
				});
			});

			jsDocsWithMemberOf = _(docs).filter({docType: 'js'})
										.filter(function(doc) {
											var tags = doc.tags.tags;
											return _.find(tags, function(tag) {
												if(tag.tagName === 'memberof') {
													return true;
												}
												return false;
											});
										})
										.value();

			docs.forEach( function(doc, idx, docs) {
				if (doc.docType === 'js') {
					// todo:
					// 1. 	a. update path
					// 		b. create a new doctype for method
					// 		c. ignore the doc, add directly to the angular stuff as dependencies
					// 2. remove the element if it is added to a parent

					var tags = doc.tags.tags;
					var memberofTag = _.find(tags, function(tag) {
						if(tag.tagName === 'memberof'){
							return true;
						}
					});

					if (typeof memberofTag !== 'undefined'){
						var parentName = memberofTag.description;

						log.debug("memberof: " + parentName);
						// find the associated doc e.g. service or directive
						var parentIdx = _.findIndex(docs, function(a) {
							return a.name === parentName;
						});

						log.debug("doc id:"+ doc.id + ", parentIdx:" + parentIdx + ", memberof:" + parentName);

						if(parentIdx > -1){

							var parentDoc = docs[parentIdx];

							if (! parentDoc.hasOwnProperty('methods')) {
								// add methods
								parentDoc.methods = [];
							}

							parentDoc.methods.push({
								"name": doc.id,
								"description": doc.description
							});
						}
					}

					// update doc type
					doc.docType = "gcMethod";

				}
			});

			return docs;
		}
	};
};<commit_msg>ref(processor): update output path and path for gcMethods<commit_after>var _ = require('lodash');

module.exports = function jacksMergeProcessor(log) {
	return {
		$runAfter: ['computePathsProcessor'],
		$runBefore: ['renderDocsProcessor'],
		$process: function (docs) {

			// var jsDocs = docs.filter(function(doc) {
			// 	if (doc.docType === 'js'){
			// 		return true;
			// 	}
			// });

			// jsDocs.forEach(function(jsdoc, idx, arr) {
			// 	// todo:
			// 	// 1. 	a. update path
			// 	// 		b. create a new doctype for method
			// 	// 		c. ignore the doc, add directly to the angular stuff as dependencies
			// 	// 2. remove the element if it is added to a parent
			// 	jsdoc.codeNode.type === 'FunctionDeclaration'
			// });
			// 1. do some stuff with docs
			// 2. update path
			// 3. add reference link to parent service or directive
			// find the memberof tag
			// check type from doc.codeNode.type: e.g. FunctionDeclaration

			// ngServiceDocs = _.filter(docs, { docType: 'ngService'});

			// ngDirectiveDocs = _.filter(docs, {docType: 'ngDirective'});

			// ngControllerDocs = _.filter(docs, {docType: 'ngController'});

			ngDocs = _(docs).reject({docType: 'ngModule'})
							.reject({docTYpe: 'componentGroup'})
							.value();

			jsDocsWithMemberOf = _(docs).filter({docType: 'js'})
										.filter(function(doc) {
											var tags = doc.tags.tags;
											return _.find(tags, function(tag) {
												if(tag.tagName === 'memberof') {
													return true;
												}
												return false;
											});
										})
										.value();

			jsDocsWithMemberOf.forEach( function(doc, idx) {
				var tags = doc.tags.tags;
				var memberofTag = _.find(tags, function(tag) {
					if(tag.tagName === 'memberof'){
						return true;
					}
				});

				if (typeof memberofTag !== 'undefined'){
					var parentName = memberofTag.description;

					log.debug("memberof: " + parentName);
					// find the associated doc e.g. service or directive
					var parentIdx = _.findIndex(ngDocs, function(a) {
						return a.name === parentName;
					});

					log.debug("doc id:"+ doc.id + ", parentIdx:" + parentIdx + ", memberof:" + parentName);

					if(parentIdx > -1){

						var parentDoc = ngDocs[parentIdx];

						if (! parentDoc.hasOwnProperty('methods')) {
							// add methods
							parentDoc.methods = [];
						}

						parentDoc.methods.push({
							"name": doc.id,
							"description": doc.description
						});

						// if(_.isString(parentDoc.path)){
							doc.path = parentDoc.path;
							doc.outputPath = doc.path + doc.outputPath;
						// }
					}
				}

				// update doc type
				doc.docType = "gcMethod";

			});

			return docs;
		}
	};
};<|endoftext|>


<commit_before>angular
    .module('eArkPlatform.ordermanagement')
    .factory('ordermanagementService', ordermanagementService);

function ordermanagementService($http, $filter) {
    var service = {
        getOrders: getOrders,
        getOrder: getOrder,
        getArchivists: getArchivists,
        updateOrder: updateOrder,
        processOrder: processOrder
    };

    return service;

    function getOrders() {
        return $http.get('/api/getOrders').then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting orders');
            }
        );
    };

    function getOrder(orderId) {
        return $http.get('/api/getOrderData?orderId=' + orderId).then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting order');
            }
        );
    };

    function updateOrder(queryObj) {
        console.log($filter('json')(queryObj));
        return $http.put('/api/updateOrder', $filter('json')(queryObj)).then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error updating order');
            }
        );
    };

    function getArchivists() {
        return $http.get('/api/getArchivists').then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting archivists');
            }
        );
    };

    //TODO: resolve this interface call
    function processOrder(order) {
        return $http.post('/earkweb/submitOrder', order).then(
            function (response) {
                console.log('Successfully posted the order for processing');
                return response.data;
            }, function (response) {
                console.log('There was an error posting the order for processing');
                return false;
            }
        );
    }

}<commit_msg>Fixed resource URL for the submit order request<commit_after>angular
    .module('eArkPlatform.ordermanagement')
    .factory('ordermanagementService', ordermanagementService);

function ordermanagementService($http, $filter) {
    var service = {
        getOrders: getOrders,
        getOrder: getOrder,
        getArchivists: getArchivists,
        updateOrder: updateOrder,
        processOrder: processOrder
    };

    return service;

    function getOrders() {
        return $http.get('/api/getOrders').then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting orders');
            }
        );
    };

    function getOrder(orderId) {
        return $http.get('/api/getOrderData?orderId=' + orderId).then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting order');
            }
        );
    };

    function updateOrder(queryObj) {
        console.log($filter('json')(queryObj));
        return $http.put('/api/updateOrder', $filter('json')(queryObj)).then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error updating order');
            }
        );
    };

    function getArchivists() {
        return $http.get('/api/getArchivists').then(
            function (response) {
                return response.data;
            }, function (response) {
                console.log('Error getting archivists');
            }
        );
    };

    //TODO: resolve this interface call
    function processOrder(order) {
        return $http.post('/api/earkweb/submitOrder', order).then(
            function (response) {
                console.log('Successfully posted the order for processing');
                return response.data;
            }, function (response) {
                console.log('There was an error posting the order for processing');
                return false;
            }
        );
    }

}
<|endoftext|>


<commit_before>import React from "react";
import { Row, Col } from "helpers/reactstrap";
import useMeasure from "helpers/hooks/useMeasure";
import useSoundEffect from "helpers/hooks/useSoundEffect";

function calcBorderColor(i, power, powerLevels) {
  const color = i >= power ? "transparent" : "#0b0";
  if (powerLevels.indexOf(i + 1) > -1)
    return `${color} yellow ${color} ${color}`;
  return color;
}
const PowerLine = ({
  power,
  onChange,
  onChanging,
  maxPower,
  topPower,
  boxWidthRatio = 1,
  powerLevels,
  label,
  style,
  labelClass
}) => {
  const [storedPower, setStoredPower] = React.useState(power || 0);
  const powerRef = React.useRef();
  const [measureRef, { left, width }] = useMeasure();
  const playEffect = useSoundEffect();
  React.useEffect(() => {
    if (power) {
      setStoredPower(power);
    }
  }, [power]);
  const mouseDown = e => {
    playEffect("buttonClick");
    mouseMove(e);
    document.addEventListener("mousemove", mouseMove);
    document.addEventListener("mouseup", mouseUp);
    document.addEventListener("touchmove", mouseMove);
    document.addEventListener("touchend", mouseUp);
  };
  const mouseUp = () => {
    document.removeEventListener("mousemove", mouseMove);
    document.removeEventListener("mouseup", mouseUp);
    document.removeEventListener("touchmove", mouseMove);
    document.removeEventListener("touchend", mouseUp);
    onChange && onChange(powerRef.current);
  };
  const mouseMove = e => {
    const mouseX = e.pageX || e.touches[0].pageX;
    const boxWidth = width / (maxPower - boxWidthRatio) - 4;
    let newPower = Math.floor((mouseX - left) / boxWidth) - 1;
    if (newPower > topPower) return;
    if (newPower < 0) newPower = 0;
    setStoredPower(newPower);
    powerRef.current = newPower;
    onChanging && onChanging(newPower);
  };
  return (
    <Row className="power-bar-dragger" style={{ ...style }}>
      <Col sm={4} className={labelClass}>
        {label}
      </Col>

          {powerLevels.map(n => {
            return (
              <div
                className="power-level"
                key={`powerLine-${n}`}
                style={{ left: `${(n + 1) * 14 - 7}px` }}
              />
            );
          })}

        {Array(maxPower)
          .fill(0)
          .map((n, i) => {
            return (

= storedPower ? "transparent" : null,

                  borderColor: calcBorderColor(i, storedPower, powerLevels)
                }}
                className={`power-box`}
                onMouseDown={mouseDown}
                onTouchStart={mouseDown}
                key={`powerLevel-${i}`}
              />
            );
          })}

    </Row>
  );
};

PowerLine.defaultProps = {
  maxPower: 40,
  powerLevels: []
};

export default PowerLine;
<commit_msg>fix(Power Distribution): Setting power levels to 0 in core show properly on the station. Closes #2477<commit_after>import React from "react";
import { Row, Col } from "helpers/reactstrap";
import useMeasure from "helpers/hooks/useMeasure";
import useSoundEffect from "helpers/hooks/useSoundEffect";

function calcBorderColor(i, power, powerLevels) {
  const color = i >= power ? "transparent" : "#0b0";
  if (powerLevels.indexOf(i + 1) > -1)
    return `${color} yellow ${color} ${color}`;
  return color;
}
const PowerLine = ({
  power,
  onChange,
  onChanging,
  maxPower,
  topPower,
  boxWidthRatio = 1,
  powerLevels,
  label,
  style,
  labelClass
}) => {
  const [storedPower, setStoredPower] = React.useState(power || 0);
  const powerRef = React.useRef();
  const [measureRef, { left, width }] = useMeasure();
  const playEffect = useSoundEffect();
  React.useEffect(() => {
    if (power || power === 0) {
      setStoredPower(power);
    }
  }, [power]);
  const mouseDown = e => {
    playEffect("buttonClick");
    mouseMove(e);
    document.addEventListener("mousemove", mouseMove);
    document.addEventListener("mouseup", mouseUp);
    document.addEventListener("touchmove", mouseMove);
    document.addEventListener("touchend", mouseUp);
  };
  const mouseUp = () => {
    document.removeEventListener("mousemove", mouseMove);
    document.removeEventListener("mouseup", mouseUp);
    document.removeEventListener("touchmove", mouseMove);
    document.removeEventListener("touchend", mouseUp);
    onChange && onChange(powerRef.current);
  };
  const mouseMove = e => {
    const mouseX = e.pageX || e.touches[0].pageX;
    const boxWidth = width / (maxPower - boxWidthRatio) - 4;
    let newPower = Math.floor((mouseX - left) / boxWidth) - 1;
    if (newPower > topPower) return;
    if (newPower < 0) newPower = 0;
    setStoredPower(newPower);
    powerRef.current = newPower;
    onChanging && onChanging(newPower);
  };
  return (
    <Row className="power-bar-dragger" style={{ ...style }}>
      <Col sm={4} className={labelClass}>
        {label}
      </Col>

          {powerLevels.map(n => {
            return (
              <div
                className="power-level"
                key={`powerLine-${n}`}
                style={{ left: `${(n + 1) * 14 - 7}px` }}
              />
            );
          })}

        {Array(maxPower)
          .fill(0)
          .map((n, i) => {
            return (

= storedPower ? "transparent" : null,

                  borderColor: calcBorderColor(i, storedPower, powerLevels)
                }}
                className={`power-box`}
                onMouseDown={mouseDown}
                onTouchStart={mouseDown}
                key={`powerLevel-${i}`}
              />
            );
          })}

    </Row>
  );
};

PowerLine.defaultProps = {
  maxPower: 40,
  powerLevels: []
};

export default PowerLine;
<|endoftext|>


<commit_before>import React, { useEffect, useRef } from "react";
import { connect } from "react-redux";
import styled from "styled-components";

import { axisTop } from "d3-axis";
import { scaleLinear } from "d3-scale";
import { select } from "d3-selection";
import { getMaxSequenceLength } from "../../selectors";

const draw = (element, maxLength, sequenceLength) => {
    element.innerHTML = "";

    const width = element.offsetWidth;

    // Set-up a y-axis that will appear at the top of the chart.
    const x = scaleLinear()
        .range([0, width - 30])
        .domain([0, maxLength]);

    // Construct the SVG canvas.
    const svg = select(element).append("svg").attr("width", width).attr("height", 26);

    // Create a mother group that will hold all chart elements.
    const group = svg.append("g").attr("transform", "translate(15,0)");

    group.append("rect").attr("x", 0).attr("y", 18).attr("width", x(sequenceLength)).attr("height", 8);

    group.append("g").attr("class", "x axis").attr("transform", "translate(0,16)").call(axisTop(x));
};

const StyledNuVsSequence = styled.div`
    height: 32px;
    margin: 10px 0;
`;

const NuVsSequence = ({ maxSequenceLength, sequence, width }) => {
    const chartEl = useRef(null);

    useEffect(() => draw(chartEl.current, maxSequenceLength, sequence.length), [sequence, width]);

    return (


<commit_before>var helpers = clientApp.helpers || {};

$.fn.gallery_new = function(result, index)  {
  if (result.visible) {
    var visible = eval(result.visible);
    if (!visible) return;
  }

  var contentKeys = Object.keys(result.contents);

  if (result.label) $(this).appendLabel(result.label);
  var gallerySelector = "gallery_" + index;
  $(this).append("

");
  $("." + gallerySelector).addClass("gallery-container");

  var leftItems = "gallery-left-items-" + index;
  var rightItems = "gallery-right-items-" + index;
  renderGalleryBlobList(index, contentKeys, gallerySelector, result, leftItems, 'left');

  var blobsContainerSelector = "gallery-blobs-container-" + index;
  $("." + gallerySelector).append("

");
  $("." + blobsContainerSelector).addClass("blobs-wrapper");

  // $("." + gallerySelector).append("

");
  renderGalleryBlobList(index, contentKeys, gallerySelector, result, rightItems, 'right');
  $("." + rightItems).addClass("gallery-item-list-right di-none");

  var imgContainerLeft = "gallery-blob-container-left-" + index;
  var imgContainerRight = "gallery-blob-container-right-" + index;
  $("." + blobsContainerSelector).append("

");
  $("." + blobsContainerSelector).append("

");
  $("#" + imgContainerLeft).addClass("gallery-blob-container");
  $("#" + imgContainerRight).addClass("gallery-blob-container di-none");

  var img = result.contents[contentKeys[0]].img;
  var contentType = typeof(img);
  var idx = 0;
  var src = [];
  if (contentType === "string") { // single image
    $("#" + imgContainerLeft).append('');
    $("#" + imgContainerRight).append('');
    $("#" + imgContainerLeft + " > img").addClass('gallery-' +index+ '-blob-left di-inline');
    $("#" + imgContainerRight + " > img").addClass('gallery-' +index+ '-blob-right di-inline');
    src.push((img.indexOf("'") == -1 ? img : eval(img)));
  } else { // array of images
    for (var i = 0; i < img.length; i++) {
      $("#" + imgContainerLeft).append('');
      $("#" + imgContainerRight).append('');
      src.push(img[i].indexOf("'") == -1 ? img[i] : eval(img[i]));
    }
    $("#" + imgContainerLeft + " > img").addClass('gallery-' +index+ '-blob-left');
    $("#" + imgContainerRight + " > img").addClass('gallery-' +index+ '-blob-right');
  }

  $("." + gallerySelector).setGalleryMinHeight(work_url, src);
  $(this).append("

");
  $("#gallery-" + index + "-zoom-container").appendZoom(index, leftItems);
  if ($("#gallery-"+index+"-blobList-left").children().length > 1) $("." + leftItems).appendCompare(index, rightItems, imgContainerRight);
  checkOptions(result.type, index);
}

function checkRepeat(line, repeatKey, repeatParam) {
  if (repeatKey === "params") {
    var repeatValues = JSON.stringify(params);
    var repeat = repeatValues[repeatParam];
  } else if (repeatKey === "info") {
    var repeat = info[repeatParam];
  } else {
    repeat = eval(line.repeat);
  }
  return repeat;
}

function renderGalleryBlobList(index, contentKeys, gallerySelector, result, itemSelector, side) {
  $("." + gallerySelector).append("

");
  $("." + itemSelector).addClass("gallery-item-list");
  var contents = result.contents;
  var firstSrc = result.contents[contentKeys[0]].img;
  var firstVisibleBlob = true;
  if (typeof(firstSrc) == "string") {
    firstSrc = [firstSrc];
  }
  for (let i = 0; i < contentKeys.length; i++) {
    if (eval(contents[contentKeys[i]].visible)) {
      var content = result.contents[contentKeys[i]].img;
      if (typeof(content) == "string") {
        content = [content];
        firstSrc = content;
      }
      var srcStorage = [];
      for (let k = 0; k < firstSrc.length; k++) {
        var idx = k;
        srcStorage[k] = work_url + (firstSrc[k].indexOf("'") == -1 ? firstSrc[k] : eval(firstSrc[k]));
      }
      if (firstVisibleBlob) {
        helpers.addToStorage("gallery-" + index + "-" + side, srcStorage);
        firstVisibleBlob = false;
      }
      var line = contents[contentKeys[i]];
      var spanContainer = "

";
      $("." + itemSelector).append(spanContainer);
      if (line.repeat) {
        line.repeat = line.repeat.toString();
        var repeatSplit = line.repeat.split(".");
        var repeat = checkRepeat(line, repeatSplit[0], repeatSplit[1]);
        for (var idx = 0; idx < repeat; idx++) {
          var text = getEvalText(contentKeys[i]);
          $("#gallery-"+index+"-blobList-"+side).append("" + eval(text) + "");
          var evalContents = [];
          for (var j = 0; j < content.length; j++) {
            evalContents[j] = work_url + (content[j].indexOf("'") == -1 ? content[j] : eval(content[j]));
          }
          $("#gallery-" +index+ "-item-" +side+ "-" + i +idx).addHoverFeature(index, side, work_url, evalContents, idx);
        }
      } else {
        var text = getEvalText(contentKeys[i]);
        $("#gallery-"+index+"-blobList-"+side).append("" + eval(text) + "");
        var evalContents = [];
        for (var j = 0; j < content.length; j++) {
          evalContents[j] = work_url + (content[j].indexOf("'") == -1 ? content[j] : eval(content[j]));
        }
        $("#gallery-" +index+ "-item-" +side+ "-" +i).addHoverFeature(index, side, work_url, evalContents, 0);
      }
    }
  }
  $(this).addMouseOut(index, side);
  $("." +itemSelector+ " span:first-child").addClass("gallery-item-selected");
}

$.fn.addMouseOut = function (galleryIndex, side) {
  var selector = '#gallery-blob-container-' + side + '-' + galleryIndex;
  $("#gallery-" + galleryIndex + "-blobList-" + side).mouseout(function (event) {
    e = event.toElement || event.relatedTarget;
    if (e != null && (e.parentNode == this || e == this)) {
      return;
    }
    var selectedSrc = helpers.getFromStorage("gallery-" + galleryIndex + "-" + side);
    $(selector).empty();
    for (var i = 0; i < selectedSrc.length; i++) {
      var elem = '';
      $(elem).appendTo(selector);
      $(elem).on('load', function () {
        $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
      });
      $(selector + " > img").addClass('gallery-' + galleryIndex + '-blob-' + side);
    }
    $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
  });
}

function getEvalText(str) {
  if (str.indexOf('+') != -1) {
    return str;
  } else {
    return "\'"+str+"\'";
  }
}

$.fn.addHoverFeature = function(galleryIndex, side, work_url, src, idx) {
  var imgSelector = '.gallery-' +galleryIndex+ '-blob-' + side;
  var selector = '#gallery-blob-container-' +side+ '-' + galleryIndex;
  $(this).mouseover(function() {
    $(selector).empty();
    for (var i = 0; i < src.length; i++) {
      var elem = '';
      $(elem).appendTo(selector);
      $(elem).on('load', function () {
        $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
      });
      $(selector + " > img").addClass('gallery-' +galleryIndex+ '-blob-'+side);
    }
    $("#gallery-" +galleryIndex+ "-zoom > input").adjustSize(galleryIndex);
  });
  $(this).on('click', function() {
    var listSelector = ".gallery-" +side+ "-items-" + galleryIndex;
    $("#gallery-" + galleryIndex + "-blobList-" + side + " > .gallery-item-selected").toggleClass("gallery-item-selected");
    $(this).toggleClass("gallery-item-selected");
    var selectedSrc = [];
    $(imgSelector).each(function(i){
      selectedSrc.push($(imgSelector)[i].src);
    });
    helpers.addToStorage("gallery-" +galleryIndex + "-" + side, selectedSrc);
  });
}

$.fn.appendZoom = function(index, leftItems) {
  var zoom = $("#zoom-container").clone();
  zoom.find('input').val('1.0');
  zoom.find('span').html('1x');
  var newZoomID= "gallery-" +index+ "-zoom";
  zoom.attr("id", newZoomID).appendTo($(this));
  zoom.removeClass("di-none");
  $("#" + newZoomID + " > .zoom-info > #editor-image-size").remove();
  $("#" + newZoomID + " > input").on('input', function() {
    var zoomLevel = $(this).val();
    let selector = ".gallery_" + index + " img";
    helpers.checkInterpolation(zoomLevel, selector);
    $(".gallery_" + index).css({ height: (parseInt($(".gallery_" + index).css('min-height')) || parseInt($(".gallery_" + index).css('height'))) * zoomLevel + "px" });
    $(this).adjustSize(index);
    $("#" + newZoomID + " > .zoom-info > #editor-zoom-value").html(zoomLevel + "x");
  });
  scrollSync(index);
}

$.fn.adjustSize = function(index) {
  var zoomLevel = $(this).val();
  $("#gallery-blob-container-left-"+index + ", #gallery-blob-container-right-"+index).children('img').each(function(i){
    $(this).height($(this)[0].naturalHeight * zoomLevel);
    $(this).width($(this)[0].naturalWidth * zoomLevel);
  });
}

function scrollSync(index) {
  var isSyncingLeftScroll = false;
  var isSyncingRightScroll = false;
  var leftDiv = document.getElementById('gallery-blob-container-left-' + index);
  var rightDiv = document.getElementById('gallery-blob-container-right-' + index);
  $('#gallery-blob-container-left-' + index).attachDragger();
  $('#gallery-blob-container-right-' + index).attachDragger();

  leftDiv.onscroll = function() {
    if (!isSyncingLeftScroll) {
      isSyncingRightScroll = true;
      rightDiv.scrollTop = this.scrollTop;
      rightDiv.scrollLeft = this.scrollLeft;
    }
    isSyncingLeftScroll = false;
  }
  rightDiv.onscroll = function() {
    if (!isSyncingRightScroll) {
      isSyncingLeftScroll = true;
      leftDiv.scrollTop = this.scrollTop;
      leftDiv.scrollLeft = this.scrollLeft;
    }
    isSyncingRightScroll = false;
  }
}<commit_msg>[ClientApp2/gallery_new] Fixed check interpolation after mouseover and mouseout<commit_after>var helpers = clientApp.helpers || {};

$.fn.gallery_new = function(result, index)  {
  if (result.visible) {
    var visible = eval(result.visible);
    if (!visible) return;
  }

  var contentKeys = Object.keys(result.contents);

  if (result.label) $(this).appendLabel(result.label);
  var gallerySelector = "gallery_" + index;
  $(this).append("

");
  $("." + gallerySelector).addClass("gallery-container");

  var leftItems = "gallery-left-items-" + index;
  var rightItems = "gallery-right-items-" + index;
  renderGalleryBlobList(index, contentKeys, gallerySelector, result, leftItems, 'left');

  var blobsContainerSelector = "gallery-blobs-container-" + index;
  $("." + gallerySelector).append("

");
  $("." + blobsContainerSelector).addClass("blobs-wrapper");

  // $("." + gallerySelector).append("

");
  renderGalleryBlobList(index, contentKeys, gallerySelector, result, rightItems, 'right');
  $("." + rightItems).addClass("gallery-item-list-right di-none");

  var imgContainerLeft = "gallery-blob-container-left-" + index;
  var imgContainerRight = "gallery-blob-container-right-" + index;
  $("." + blobsContainerSelector).append("

");
  $("." + blobsContainerSelector).append("

");
  $("#" + imgContainerLeft).addClass("gallery-blob-container");
  $("#" + imgContainerRight).addClass("gallery-blob-container di-none");

  var img = result.contents[contentKeys[0]].img;
  var contentType = typeof(img);
  var idx = 0;
  var src = [];
  if (contentType === "string") { // single image
    $("#" + imgContainerLeft).append('');
    $("#" + imgContainerRight).append('');
    $("#" + imgContainerLeft + " > img").addClass('gallery-' +index+ '-blob-left di-inline');
    $("#" + imgContainerRight + " > img").addClass('gallery-' +index+ '-blob-right di-inline');
    src.push((img.indexOf("'") == -1 ? img : eval(img)));
  } else { // array of images
    for (var i = 0; i < img.length; i++) {
      $("#" + imgContainerLeft).append('');
      $("#" + imgContainerRight).append('');
      src.push(img[i].indexOf("'") == -1 ? img[i] : eval(img[i]));
    }
    $("#" + imgContainerLeft + " > img").addClass('gallery-' +index+ '-blob-left');
    $("#" + imgContainerRight + " > img").addClass('gallery-' +index+ '-blob-right');
  }

  $("." + gallerySelector).setGalleryMinHeight(work_url, src);
  $(this).append("

");
  $("#gallery-" + index + "-zoom-container").appendZoom(index, leftItems);
  if ($("#gallery-"+index+"-blobList-left").children().length > 1) $("." + leftItems).appendCompare(index, rightItems, imgContainerRight);
  checkOptions(result.type, index);
}

function checkRepeat(line, repeatKey, repeatParam) {
  if (repeatKey === "params") {
    var repeatValues = JSON.stringify(params);
    var repeat = repeatValues[repeatParam];
  } else if (repeatKey === "info") {
    var repeat = info[repeatParam];
  } else {
    repeat = eval(line.repeat);
  }
  return repeat;
}

function renderGalleryBlobList(index, contentKeys, gallerySelector, result, itemSelector, side) {
  $("." + gallerySelector).append("

");
  $("." + itemSelector).addClass("gallery-item-list");
  var contents = result.contents;
  var firstSrc = result.contents[contentKeys[0]].img;
  var firstVisibleBlob = true;
  if (typeof(firstSrc) == "string") {
    firstSrc = [firstSrc];
  }
  for (let i = 0; i < contentKeys.length; i++) {
    if (eval(contents[contentKeys[i]].visible)) {
      var content = result.contents[contentKeys[i]].img;
      if (typeof(content) == "string") {
        content = [content];
        firstSrc = content;
      }
      var srcStorage = [];
      for (let k = 0; k < firstSrc.length; k++) {
        var idx = k;
        srcStorage[k] = work_url + (firstSrc[k].indexOf("'") == -1 ? firstSrc[k] : eval(firstSrc[k]));
      }
      if (firstVisibleBlob) {
        helpers.addToStorage("gallery-" + index + "-" + side, srcStorage);
        firstVisibleBlob = false;
      }
      var line = contents[contentKeys[i]];
      var spanContainer = "

";
      $("." + itemSelector).append(spanContainer);
      if (line.repeat) {
        line.repeat = line.repeat.toString();
        var repeatSplit = line.repeat.split(".");
        var repeat = checkRepeat(line, repeatSplit[0], repeatSplit[1]);
        for (var idx = 0; idx < repeat; idx++) {
          var text = getEvalText(contentKeys[i]);
          $("#gallery-"+index+"-blobList-"+side).append("" + eval(text) + "");
          var evalContents = [];
          for (var j = 0; j < content.length; j++) {
            evalContents[j] = work_url + (content[j].indexOf("'") == -1 ? content[j] : eval(content[j]));
          }
          $("#gallery-" +index+ "-item-" +side+ "-" + i +idx).addHoverFeature(index, side, work_url, evalContents, idx);
        }
      } else {
        var text = getEvalText(contentKeys[i]);
        $("#gallery-"+index+"-blobList-"+side).append("" + eval(text) + "");
        var evalContents = [];
        for (var j = 0; j < content.length; j++) {
          evalContents[j] = work_url + (content[j].indexOf("'") == -1 ? content[j] : eval(content[j]));
        }
        $("#gallery-" +index+ "-item-" +side+ "-" +i).addHoverFeature(index, side, work_url, evalContents, 0);
      }
    }
  }
  $(this).addMouseOut(index, side);
  $("." +itemSelector+ " span:first-child").addClass("gallery-item-selected");
}

$.fn.addMouseOut = function (galleryIndex, side) {
  var selector = '#gallery-blob-container-' + side + '-' + galleryIndex;
  $("#gallery-" + galleryIndex + "-blobList-" + side).mouseout(function (event) {
    e = event.toElement || event.relatedTarget;
    if (e != null && (e.parentNode == this || e == this)) {
      return;
    }
    var selectedSrc = helpers.getFromStorage("gallery-" + galleryIndex + "-" + side);
    $(selector).empty();
    for (var i = 0; i < selectedSrc.length; i++) {
      var elem = '';
      $(elem).appendTo(selector);
      $(elem).on('load', function () {
        $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
      });
      $(selector + " > img").addClass('gallery-' + galleryIndex + '-blob-' + side);
    }
    var zoomValue = $("#gallery-" + galleryIndex + "-zoom > #editor-zoom").val();
    helpers.checkInterpolation(zoomValue, ".gallery_" + galleryIndex + " img");
    $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
  });
}

function getEvalText(str) {
  if (str.indexOf('+') != -1) {
    return str;
  } else {
    return "\'"+str+"\'";
  }
}

$.fn.addHoverFeature = function(galleryIndex, side, work_url, src, idx) {
  var imgSelector = '.gallery-' +galleryIndex+ '-blob-' + side;
  var selector = '#gallery-blob-container-' +side+ '-' + galleryIndex;
  $(this).mouseover(function() {
    $(selector).empty();
    for (var i = 0; i < src.length; i++) {
      var elem = '';
      $(elem).appendTo(selector);
      $(elem).on('load', function () {
        $("#gallery-" + galleryIndex + "-zoom > input").adjustSize(galleryIndex);
      });
      $(selector + " > img").addClass('gallery-' +galleryIndex+ '-blob-'+side);
    }
    var zoomValue = $("#gallery-" + galleryIndex + "-zoom > #editor-zoom").val();
    helpers.checkInterpolation(zoomValue, ".gallery_" + galleryIndex + " img");
    $("#gallery-" +galleryIndex+ "-zoom > input").adjustSize(galleryIndex);
  });
  $(this).on('click', function() {
    var listSelector = ".gallery-" +side+ "-items-" + galleryIndex;
    $("#gallery-" + galleryIndex + "-blobList-" + side + " > .gallery-item-selected").toggleClass("gallery-item-selected");
    $(this).toggleClass("gallery-item-selected");
    var selectedSrc = [];
    $(imgSelector).each(function(i){
      selectedSrc.push($(imgSelector)[i].src);
    });
    helpers.addToStorage("gallery-" +galleryIndex + "-" + side, selectedSrc);
  });
}

$.fn.appendZoom = function(index, leftItems) {
  var zoom = $("#zoom-container").clone();
  zoom.find('input').val('1.0');
  zoom.find('span').html('1x');
  var newZoomID= "gallery-" +index+ "-zoom";
  zoom.attr("id", newZoomID).appendTo($(this));
  zoom.removeClass("di-none");
  $("#" + newZoomID + " > .zoom-info > #editor-image-size").remove();
  $("#" + newZoomID + " > input").on('input', function() {
    var zoomLevel = $(this).val();
    let selector = ".gallery_" + index + " img";
    helpers.checkInterpolation(zoomLevel, selector);
    $(".gallery_" + index).css({ height: (parseInt($(".gallery_" + index).css('min-height')) || parseInt($(".gallery_" + index).css('height'))) * zoomLevel + "px" });
    $(this).adjustSize(index);
    $("#" + newZoomID + " > .zoom-info > #editor-zoom-value").html(zoomLevel + "x");
  });
  scrollSync(index);
}

$.fn.adjustSize = function(index) {
  var zoomLevel = $(this).val();
  $("#gallery-blob-container-left-"+index + ", #gallery-blob-container-right-"+index).children('img').each(function(i){
    $(this).height($(this)[0].naturalHeight * zoomLevel);
    $(this).width($(this)[0].naturalWidth * zoomLevel);
  });
}

function scrollSync(index) {
  var isSyncingLeftScroll = false;
  var isSyncingRightScroll = false;
  var leftDiv = document.getElementById('gallery-blob-container-left-' + index);
  var rightDiv = document.getElementById('gallery-blob-container-right-' + index);
  $('#gallery-blob-container-left-' + index).attachDragger();
  $('#gallery-blob-container-right-' + index).attachDragger();

  leftDiv.onscroll = function() {
    if (!isSyncingLeftScroll) {
      isSyncingRightScroll = true;
      rightDiv.scrollTop = this.scrollTop;
      rightDiv.scrollLeft = this.scrollLeft;
    }
    isSyncingLeftScroll = false;
  }
  rightDiv.onscroll = function() {
    if (!isSyncingRightScroll) {
      isSyncingLeftScroll = true;
      leftDiv.scrollTop = this.scrollTop;
      leftDiv.scrollLeft = this.scrollLeft;
    }
    isSyncingRightScroll = false;
  }
}<|endoftext|>