<commit_before>/* eslint strict: "off" */
/* eslint import/no-dynamic-require: "off" */

'use strict';

const os = require('os');
const path = require('path');
const webpack = require('webpack');
const combineLoaders = require('webpack-combine-loaders');
const git = require('git-rev-sync');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Visualizer = require('webpack-visualizer-plugin');
const HappyPack = require('happypack');

const packageInfo = require(path.resolve('package.json'));
const version = packageInfo.version;
const isCommon = packageInfo.name === 'omni-common-ui';
const srcFolder = isCommon ? 'src' : 'app';
const contextFolder = isCommon ? 'sample' : 'app';
const nodeEnv = process.env.NODE_ENV || 'development';
const isDev = nodeEnv === 'development';
const isProd = ! isDev && nodeEnv !== 'test';

const commitHash = git.long();
const tag = git.tag();
const excluded = /node_modules(\/|\\)((?!(omni-common-ui)).)/;

HappyPack.SERIALIZABLE_OPTIONS = HappyPack.SERIALIZABLE_OPTIONS.concat(['postcss']);
const happyPackThreadPool = new HappyPack.ThreadPool({ size: os.cpus().length });

const BABEL_CACHE_ENABLED = true;

const jsxLoader = combineLoaders([
  {
    loader: 'babel',
    query: {
      presets: ['react', 'es2015', 'stage-2'],
      cacheDirectory: BABEL_CACHE_ENABLED,
    },
  },
]);

const postcssLoader = combineLoaders([
  { loader: 'style' },
  {
    loader: 'css',
    query: {
      root: '.',
      modules: true,
      importLoaders: 1,
      localIdentName: isProd ? undefined : '[local]___[hash:base64:5]',
    },
  },
  { loader: 'postcss' },
]);

module.exports = {
  context: path.resolve(contextFolder),
  devtool: getSourceMapType(),
  entry: {
    app: 'app.jsx',
    vendor: ['babel-polyfill', 'omni-common-ui'],
  },
  output: {
    path: path.resolve('dist'),
    filename: '[name].[hash].js',
  },
  module: {
    loaders: [
      {
        test: /\.(html|hbs)$/,
        loader: 'handlebars',
        query: { inlineRequires: 'assets/favicons' },
      },
      {
        test: /\.jsx?$/,
        exclude: excluded,
        loader: isDev ? 'happypack/loader?id=jsx' : jsxLoader,
      },
      {
        test: /\.css$/,
        loader: 'style!css?root=.',
      },
      {
        test: /\.postcss$/,
        loader: isDev ? 'happypack/loader?id=postcss' : postcssLoader,
      },
      {
        test: /fonts(\/|\\).+\.(woff2?|ttf|eot|otf|svg)$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]',
      },
      {
        test: /assets\/favicons\/.+$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]',
      },
      {
        test: /\.inline\.svg$/,
        loader: 'svg-inline?removeTags',
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        exclude: /\.inline\.svg$/,
        loaders: [
          'url?limit=10000&hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false',
        ],
      },
      {
        test: /\.json$/,
        exclude: /assets\/favicons/,
        loader: 'json',
      },
    ],
  },
  plugins: (nodeEnv !== 'test' ?
      [new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.[hash].js')] :
      []).concat([
        new webpack.optimize.OccurenceOrderPlugin(),
        new CopyWebpackPlugin([
          { from: path.join(__dirname, 'lib/assets/favicons/browserconfig.xml'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/android-chrome-192x192.png'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/android-chrome-512x512.png'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/mstile-150x150.png'), to: path.resolve('dist') },
        ]),
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': `'${isProd ? 'production' : nodeEnv}'`,
          PRODUCTION: isProd,
          VERSION: `'${version}'`,
          COMMIT: `'${commitHash}'`,
          SENTRY_ENV: `'${nodeEnv}'`,
        }),
      ]).concat(! isProd ?
        [
          new webpack.ProvidePlugin({
            __CONFIG__: path.resolve(`config/${process.env.CONFIG || nodeEnv}.json`),
          }),
        ] :
        [])
      .concat(isDev ?
        [
          new HappyPack({
            id: 'jsx',
            cache: ! BABEL_CACHE_ENABLED,
            threadPool: happyPackThreadPool,
            loaders: [jsxLoader],
            cacheContext: {
              env: process.env.NODE_ENV,
            },
          }),
          new HappyPack({
            id: 'postcss',
            threadPool: happyPackThreadPool,
            loaders: [postcssLoader],
            cacheContext: {
              env: process.env.NODE_ENV,
            },
          }),
        ] :
        [])
      .concat([
        new HtmlWebpackPlugin({
          template: path.join(__dirname, 'lib/index.html'),
          inject: 'body',
          version,
          tag,
          commit: commitHash,
          title: process.env.TITLE,
          isProd,
        }),
        new Visualizer({ filename: '../package-stats.html' }),
      ])
      .concat(addOptionalPlugins()),
  devServer: {
    contentBase: srcFolder,
    noInfo: false,
    stats: { colors: true },
    historyApiFallback: true,
  },
  resolve: Object.assign(
    {
      root: [
        path.resolve(contextFolder),
        path.resolve(srcFolder),
        process.cwd(),
      ],
      extensions: ['', '.js', '.jsx', '.json'],
    },
    {
      alias: Object.assign(
        isCommon ?
            { 'omni-common-ui$': 'src/index.js' } :
            {}
        , {
          react: path.resolve('node_modules', 'react'),
          'react-ga': path.resolve('node_modules', 'react-ga'),
          'react-radial-progress': path.resolve('node_modules', 'react-radial-progress-sans-animation'),
          'react-addons-perf': path.resolve('node_modules', 'react-addons-perf'),
          'react-dom': path.resolve('node_modules', 'react-dom'),
        }
      ),
    }
  ),
  externals: {
    cheerio: 'window',
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true,
    'react/addons': true,
  },
};

function getSourceMapType() {
  if (isProd) {
    return 'source-map';
  }

  return 'inline-source-map';
}

function addOptionalPlugins() {
  /* eslint global-require: "off" */
  const plugins = [];

  if (isProd) {
    plugins.concat([
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
        sourceMap: true,
      }),
    ]);
  }

  return [];
}
<commit_msg>Added favicon.ico to the build<commit_after>/* eslint strict: "off" */
/* eslint import/no-dynamic-require: "off" */

'use strict';

const os = require('os');
const path = require('path');
const webpack = require('webpack');
const combineLoaders = require('webpack-combine-loaders');
const git = require('git-rev-sync');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Visualizer = require('webpack-visualizer-plugin');
const HappyPack = require('happypack');

const packageInfo = require(path.resolve('package.json'));
const version = packageInfo.version;
const isCommon = packageInfo.name === 'omni-common-ui';
const srcFolder = isCommon ? 'src' : 'app';
const contextFolder = isCommon ? 'sample' : 'app';
const nodeEnv = process.env.NODE_ENV || 'development';
const isDev = nodeEnv === 'development';
const isProd = ! isDev && nodeEnv !== 'test';

const commitHash = git.long();
const tag = git.tag();
const excluded = /node_modules(\/|\\)((?!(omni-common-ui)).)/;

HappyPack.SERIALIZABLE_OPTIONS = HappyPack.SERIALIZABLE_OPTIONS.concat(['postcss']);
const happyPackThreadPool = new HappyPack.ThreadPool({ size: os.cpus().length });

const BABEL_CACHE_ENABLED = true;

const jsxLoader = combineLoaders([
  {
    loader: 'babel',
    query: {
      presets: ['react', 'es2015', 'stage-2'],
      cacheDirectory: BABEL_CACHE_ENABLED,
    },
  },
]);

const postcssLoader = combineLoaders([
  { loader: 'style' },
  {
    loader: 'css',
    query: {
      root: '.',
      modules: true,
      importLoaders: 1,
      localIdentName: isProd ? undefined : '[local]___[hash:base64:5]',
    },
  },
  { loader: 'postcss' },
]);

module.exports = {
  context: path.resolve(contextFolder),
  devtool: getSourceMapType(),
  entry: {
    app: 'app.jsx',
    vendor: ['babel-polyfill', 'omni-common-ui'],
  },
  output: {
    path: path.resolve('dist'),
    filename: '[name].[hash].js',
  },
  module: {
    loaders: [
      {
        test: /\.(html|hbs)$/,
        loader: 'handlebars',
        query: { inlineRequires: 'assets/favicons' },
      },
      {
        test: /\.jsx?$/,
        exclude: excluded,
        loader: isDev ? 'happypack/loader?id=jsx' : jsxLoader,
      },
      {
        test: /\.css$/,
        loader: 'style!css?root=.',
      },
      {
        test: /\.postcss$/,
        loader: isDev ? 'happypack/loader?id=postcss' : postcssLoader,
      },
      {
        test: /fonts(\/|\\).+\.(woff2?|ttf|eot|otf|svg)$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]',
      },
      {
        test: /assets\/favicons\/.+$/,
        loader: 'file?hash=sha512&digest=hex&name=[hash].[ext]',
      },
      {
        test: /\.inline\.svg$/,
        loader: 'svg-inline?removeTags',
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        exclude: /\.inline\.svg$/,
        loaders: [
          'url?limit=10000&hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false',
        ],
      },
      {
        test: /\.json$/,
        exclude: /assets\/favicons/,
        loader: 'json',
      },
    ],
  },
  plugins: (nodeEnv !== 'test' ?
      [new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.[hash].js')] :
      []).concat([
        new webpack.optimize.OccurenceOrderPlugin(),
        new CopyWebpackPlugin([
          { from: path.join(__dirname, 'lib/assets/favicons/browserconfig.xml'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/android-chrome-192x192.png'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/android-chrome-512x512.png'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/mstile-150x150.png'), to: path.resolve('dist') },
          { from: path.join(__dirname, 'lib/assets/favicons/favicon.ico'), to: path.resolve('dist') },
        ]),
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': `'${isProd ? 'production' : nodeEnv}'`,
          PRODUCTION: isProd,
          VERSION: `'${version}'`,
          COMMIT: `'${commitHash}'`,
          SENTRY_ENV: `'${nodeEnv}'`,
        }),
      ]).concat(! isProd ?
        [
          new webpack.ProvidePlugin({
            __CONFIG__: path.resolve(`config/${process.env.CONFIG || nodeEnv}.json`),
          }),
        ] :
        [])
      .concat(isDev ?
        [
          new HappyPack({
            id: 'jsx',
            cache: ! BABEL_CACHE_ENABLED,
            threadPool: happyPackThreadPool,
            loaders: [jsxLoader],
            cacheContext: {
              env: process.env.NODE_ENV,
            },
          }),
          new HappyPack({
            id: 'postcss',
            threadPool: happyPackThreadPool,
            loaders: [postcssLoader],
            cacheContext: {
              env: process.env.NODE_ENV,
            },
          }),
        ] :
        [])
      .concat([
        new HtmlWebpackPlugin({
          template: path.join(__dirname, 'lib/index.html'),
          inject: 'body',
          version,
          tag,
          commit: commitHash,
          title: process.env.TITLE,
          isProd,
        }),
        new Visualizer({ filename: '../package-stats.html' }),
      ])
      .concat(addOptionalPlugins()),
  devServer: {
    contentBase: srcFolder,
    noInfo: false,
    stats: { colors: true },
    historyApiFallback: true,
  },
  resolve: Object.assign(
    {
      root: [
        path.resolve(contextFolder),
        path.resolve(srcFolder),
        process.cwd(),
      ],
      extensions: ['', '.js', '.jsx', '.json'],
    },
    {
      alias: Object.assign(
        isCommon ?
            { 'omni-common-ui$': 'src/index.js' } :
            {}
        , {
          react: path.resolve('node_modules', 'react'),
          'react-ga': path.resolve('node_modules', 'react-ga'),
          'react-radial-progress': path.resolve('node_modules', 'react-radial-progress-sans-animation'),
          'react-addons-perf': path.resolve('node_modules', 'react-addons-perf'),
          'react-dom': path.resolve('node_modules', 'react-dom'),
        }
      ),
    }
  ),
  externals: {
    cheerio: 'window',
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true,
    'react/addons': true,
  },
};

function getSourceMapType() {
  if (isProd) {
    return 'source-map';
  }

  return 'inline-source-map';
}

function addOptionalPlugins() {
  /* eslint global-require: "off" */
  const plugins = [];

  if (isProd) {
    plugins.concat([
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
        sourceMap: true,
      }),
    ]);
  }

  return [];
}
<|endoftext|>


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

  var React = require('react/addons'),
    Router = require('react-router'),
    stores = require('stores'),
    AtmosphereUser = require('./AtmosphereUser.react');
  var timer,
    timerDelay = 100;

  return React.createClass({
    displayName: "AtmosphereUserMaster",
    mixins: [Router.State],
    getInitialState: function() {
        return {
            query: "",
            allModels: null,
        };
    },

    componentDidMount: function () {
      stores.UserStore.addChangeListener(this.updateState);
    },

    componentWillUnmount: function() {
      stores.UserStore.removeChangeListener(this.updateState);
    },

    //Borrowed shamelessly from ImageListView
    handleSearch: function (input) {
      if (timer) clearTimeout(timer);

      timer = setTimeout(function () {
        this.setState({query: this.state.query});
      }.bind(this), timerDelay);
    },

    onSearchChange: function (e) {
      var input = e.target.value;
      this.setState({query: input});
      this.handleSearch(input);
    },

    renderTable: function () {
      var users;
     var query_params = {};
      if(this.state.query !== null && this.state.query !== "") {
          query_params.username = this.state.query
      }
      if(query_params) {
          users = stores.UserStore.fetchWhere(query_params);
      } else {
          users = stores.UserStore.getAll();
      }

      if (!users) return

;

      var atmosphereUserRows = users.map(function (user) {
        return (
          <AtmosphereUser key={user.id} user={user}/>
        )
      });

      if (!atmosphereUserRows[0]) {
        return  (

No Users were returned from the API

                );
      }
      return (

User

E-Mail

Staff

Superuser

Enabled/Disabled

              {atmosphereUserRows}

        );
    },
    render: function () {
      return (

            <input
            type='text'
            className='form-control search-input'
            placeholder='Search for a specific user by username'
            onChange={this.onSearchChange}
            value={this.state.query}
            ref="textField"
            />

Atmosphere Users

          {this.renderTable()}

      );
    }

  });

});
<commit_msg>Implement input with delay and refactor<commit_after>define(function (require) {
  "use strict";

  var React = require('react/addons'),
    Router = require('react-router'),
    stores = require('stores'),
    ComponentHandleInputWithDelay = require('components/mixins/ComponentHandleInputWithDelay'),
    AtmosphereUser = require('./AtmosphereUser.react');

  return React.createClass({
    displayName: "AtmosphereUserMaster",
    mixins: [Router.State, ComponentHandleInputWithDelay],

    getInitialState: function() {
        return {
            query: "",
            users: null,
        };
    },

    USERS_PAGE_SIZE: 20,

    componentDidMount: function () {
      stores.UserStore.addChangeListener(this.updateState);

      // Prime the data
      this.updateState();
    },

    componentWillUnmount: function() {
      stores.UserStore.removeChangeListener(this.updateState);
    },

     updateState: function() {
         let query = this.state.query;
         let users;
         if (query) {
             users = stores.UserStore.fetchWhere({
                 username:query,
                 page_size: this.USERS_PAGE_SIZE
             });
         } else {
             users = stores.UserStore.fetchWhere({
                 page_size: this.USERS_PAGE_SIZE
             });
         }
         this.setState({ users });
     },

     onSearchChange: function (e) {
         var input = e.target.value.trim();
         this.setState({query: input}, () => {
             // The callback will be called at least after 500 ms, if the
             // function is called again, its internal timer will be reset
             this.callIfNotInterruptedAfter(500 /*ms*/, this.updateState);
         });
     },

    renderTable: function () {
        let users = this.state.users;

        if (!users) {
            return

;
        }

        let rows = users.map(
            (user) => <AtmosphereUser key={user.id} user={user}/>
        );

        if (rows.length == 0) {
            return  (

No Users were returned from the API

            );
        }

        return (

User

E-Mail

Staff

Superuser

Enabled/Disabled

                    {rows}

        );
    },
    render: function () {
      return (

            <input
            type='text'
            className='form-control search-input'
            placeholder='Search for a specific user by username'
            onChange={this.onSearchChange}
            value={this.state.query}
            ref="textField"
            />

Atmosphere Users

          {this.renderTable()}

      );
    }

  });

});
<|endoftext|>


<commit_before>const webpack = require('webpack')
const HtmlWebpackPLugin = require('html-webpack-plugin')
const OfflinePlugin = require('offline-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const autoprefixer = require('autoprefixer')

const debug = process.env.NODE_ENV !== 'production'

module.exports = {
  context: `${__dirname}/src`,
  devtool: debug ? 'cheap-module-eval-source-map' : 'source-map',
  entry: {
    app: [
      'babel-polyfill',
      'react-hot-loader/patch',
      './client.js',
    ],
  },
  output: {
    path: `${__dirname}/public`,
    filename: debug ? '[name].js' : '[name].[chunkhash].js',
    publicPath: '/',
  },
  performance: {
    hints: false,
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              minimize: true,
              importLoaders: 2,
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]',
            },
          },
          'sass-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer(),
              ],
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        loader: {
          loader: 'svg-sprite-loader',
          options: {
            name: '[name]',
          },
        },
      },
    ],
  },
  plugins: debug ? [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new FriendlyErrorsPlugin(),
    new HtmlWebpackPLugin({
      template: './index.html',
    }),
  ] : [
    new webpack.EnvironmentPlugin('NODE_ENV'),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPLugin({
      template: './index.html',
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => module.context && module.context.indexOf('node_modules') !== -1,
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      mangle: true,
      sourcemap: true,
    }),
    new CopyWebpackPlugin([
      { from: 'manifest.json' },
    ]),
    new OfflinePlugin({
      version: '[hash]',
      AppCache: false,
      ServiceWorker: {
        events: true,
      },
    }),
  ],
  devServer: {
    contentBase: `${__dirname}/src`,
    historyApiFallback: true,
    hot: true,
    quiet: true,
  },
}
<commit_msg>Use default localIdentName in prod<commit_after>const webpack = require('webpack')
const HtmlWebpackPLugin = require('html-webpack-plugin')
const OfflinePlugin = require('offline-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const autoprefixer = require('autoprefixer')

const debug = process.env.NODE_ENV !== 'production'

module.exports = {
  context: `${__dirname}/src`,
  devtool: debug ? 'cheap-module-eval-source-map' : 'source-map',
  entry: {
    app: [
      'babel-polyfill',
      'react-hot-loader/patch',
      './client.js',
    ],
  },
  output: {
    path: `${__dirname}/public`,
    filename: debug ? '[name].js' : '[name].[chunkhash].js',
    publicPath: '/',
  },
  performance: {
    hints: false,
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              minimize: true,
              importLoaders: 2,
              modules: true,
              localIdentName: debug ? '[name]__[local]--[hash:base64:5]' : null,
            },
          },
          'sass-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer(),
              ],
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        loader: {
          loader: 'svg-sprite-loader',
          options: {
            name: '[name]',
          },
        },
      },
    ],
  },
  plugins: debug ? [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new FriendlyErrorsPlugin(),
    new HtmlWebpackPLugin({
      template: './index.html',
    }),
  ] : [
    new webpack.EnvironmentPlugin('NODE_ENV'),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPLugin({
      template: './index.html',
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => module.context && module.context.indexOf('node_modules') !== -1,
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      mangle: true,
      sourcemap: true,
    }),
    new CopyWebpackPlugin([
      { from: 'manifest.json' },
    ]),
    new OfflinePlugin({
      version: '[hash]',
      AppCache: false,
      ServiceWorker: {
        events: true,
      },
    }),
  ],
  devServer: {
    contentBase: `${__dirname}/src`,
    historyApiFallback: true,
    hot: true,
    quiet: true,
  },
}
<|endoftext|>


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

module.exports = {
  entry: './webapp/assets/js/home.js',
  output: {
    filename: 'home.bundle.js',
    path: path.resolve(__dirname, 'webapp/static/js/')
  }
};

<commit_msg>Aplica StandardJS<commit_after>var path = require('path')

module.exports = {
  entry: './webapp/assets/js/home.js',
  output: {
    filename: 'home.bundle.js',
    path: path.resolve(__dirname, 'webapp/static/js/')
  }
}
<|endoftext|>


<commit_before>/*
===============================================================================================

		Unify Project

		Homepage: unify-project.org
		License: MIT + Apache (V2)
		Copyright: 2011, TELEKOM AG

===============================================================================================
*/

/**
 * EXPERIMENTAL
 */

(function() {

	if (jasy.Env.getValue("engine") == "webkit") {
		var styleNode = document.createElement('style');
		styleNode.type = 'text/css';
		//TODO write keyframe rule with correct prefix depending on browser engine
		var rules = document.createTextNode(
				'@-webkit-keyframes KAI_rotateZ{' +//use a unique name to avoid overriding other keyframe definitions
					'from{' +
						'-webkit-transform:rotate3d(0,0,1,0deg)}' +
					'to{' +
						'-webkit-transform:rotate3d(0,0,1,360deg)' +
					'}' +
				'}');
		styleNode.appendChild(rules);
		document.head.appendChild(styleNode);
	}

	core.Class("unify.ui.basic.KeyframeAnimatedImage", {
		include : [unify.ui.basic.Image],

		construct : function(source) {
			this.__source = source;
			unify.ui.basic.Image.call(this);

			this.addListener("changeVisibility", this.__onChangeVisibility, this);
		},

		properties:{
			/** Duration of rotation */
			animateRotateDuration:{
				init:1500,
				type:"Integer"
			}
		},

		members : {
			_createElement: function(){
				//use a backgroundimage div because android (at least on motorola xoom with 3.1) has problems rotating images around their center
				var elem= document.createElement('div');
				var style = {
					backgroundColor:"transparent",
					backgroundPosition:"center center",
					backgroundRepeat:"no-repeat",
					transformOriginX:"50%",
					transformOriginY:"50%"
				};

				if (this.__source) {
					style.backgroundImage = "url("+jasy.Asset.toUri(this.__source)+")";
				}

				lowland.bom.Style.set(elem, style);

				return elem;
			},
			_applySource : function(value) {
				this.setStyle({backgroundImage:"url("+jasy.Asset.toUri(value)+")"});
			},
			/**
			 * Event handler for visibility changes
			 *
			 * @param e {Event} Change event
			 */
			__onChangeVisibility : function(e) {
				if (e.getData() == "visible") {
					this.__startRotate();
				} else {
					this.__stopRotate();
				}
			},

			/**
			 * starts rotation by adding the required css styles
			 */
			__startRotate : function(){
				if (jasy.Env.getValue("engine") == "webkit") {
					this.setStyle({
							animationName: "KAI_rotateZ",
							animationDuration: this.getAnimateRotateDuration()+"ms",
							animationIterationCount: "infinite",
							animationTimingFunction: "linear"
					});
				}
			},

			/**
			 * stops rotation by removing the required css styles
			 */
			__stopRotate : function(){
				if (jasy.Env.getValue("engine") == "webkit") {
					this.setStyle({
						animationName: "",
						animationDuration: "",
						animationIterationCount: "",
						animationTimingFunction: ""
					});
				}
			}
		}
	});

})();<commit_msg>Fix use of getData vs. getValue<commit_after>/*
===============================================================================================

		Unify Project

		Homepage: unify-project.org
		License: MIT + Apache (V2)
		Copyright: 2011, TELEKOM AG

===============================================================================================
*/

/**
 * EXPERIMENTAL
 */

(function() {

	if (jasy.Env.getValue("engine") == "webkit") {
		var styleNode = document.createElement('style');
		styleNode.type = 'text/css';
		//TODO write keyframe rule with correct prefix depending on browser engine
		var rules = document.createTextNode(
				'@-webkit-keyframes KAI_rotateZ{' +//use a unique name to avoid overriding other keyframe definitions
					'from{' +
						'-webkit-transform:rotate3d(0,0,1,0deg)}' +
					'to{' +
						'-webkit-transform:rotate3d(0,0,1,360deg)' +
					'}' +
				'}');
		styleNode.appendChild(rules);
		document.head.appendChild(styleNode);
	}

	core.Class("unify.ui.basic.KeyframeAnimatedImage", {
		include : [unify.ui.basic.Image],

		construct : function(source) {
			this.__source = source;
			unify.ui.basic.Image.call(this);

			this.addListener("changeVisibility", this.__onChangeVisibility, this);
		},

		properties:{
			/** Duration of rotation */
			animateRotateDuration:{
				init:1500,
				type:"Integer"
			}
		},

		members : {
			_createElement: function(){
				//use a backgroundimage div because android (at least on motorola xoom with 3.1) has problems rotating images around their center
				var elem= document.createElement('div');
				var style = {
					backgroundColor:"transparent",
					backgroundPosition:"center center",
					backgroundRepeat:"no-repeat",
					transformOriginX:"50%",
					transformOriginY:"50%"
				};

				if (this.__source) {
					style.backgroundImage = "url("+jasy.Asset.toUri(this.__source)+")";
				}

				lowland.bom.Style.set(elem, style);

				return elem;
			},
			_applySource : function(value) {
				this.setStyle({backgroundImage:"url("+jasy.Asset.toUri(value)+")"});
			},
			/**
			 * Event handler for visibility changes
			 *
			 * @param e {Event} Change event
			 */
			__onChangeVisibility : function(e) {
				if (e.getValue() == "visible") {
					this.__startRotate();
				} else {
					this.__stopRotate();
				}
			},

			/**
			 * starts rotation by adding the required css styles
			 */
			__startRotate : function(){
				if (jasy.Env.getValue("engine") == "webkit") {
					this.setStyle({
							animationName: "KAI_rotateZ",
							animationDuration: this.getAnimateRotateDuration()+"ms",
							animationIterationCount: "infinite",
							animationTimingFunction: "linear"
					});
				}
			},

			/**
			 * stops rotation by removing the required css styles
			 */
			__stopRotate : function(){
				if (jasy.Env.getValue("engine") == "webkit") {
					this.setStyle({
						animationName: "",
						animationDuration: "",
						animationIterationCount: "",
						animationTimingFunction: ""
					});
				}
			}
		}
	});

})();
<|endoftext|>


<commit_before>module.exports = (webpackConfig) => {
  // FilenameHash
  webpackConfig.output.chunkFilename = '[name].[hash].js' // http://webpack.github.io/docs/configuration.html#output-chunkfilename

  // ClassnameHash
  const cssLoaderOption = {
    importLoaders: 1,
    modules: true,
    localIdentName: '[hash:base64:5]',
  }
  const cssLoaders = webpackConfig.module.loaders[3].loader.split('!')
  cssLoaders[1] = `css?${JSON.stringify(cssLoaderOption)}`
  webpackConfig.module.loaders[3].loader = cssLoaders.join('!')

  // PreLoaders
  webpackConfig.module.preLoaders = [{
    test: /\.js$/,
    enforce: 'pre',
    loader: 'eslint',
  }]

  return webpackConfig
}
<commit_msg>fix production className to hash<commit_after>module.exports = (webpackConfig) => {
  // FilenameHash
  webpackConfig.output.chunkFilename = '[name].[hash].js' // http://webpack.github.io/docs/configuration.html#output-chunkfilename

  // ClassnameHash
  const cssLoaderOption = {
    importLoaders: 1,
    modules: true,
    localIdentName: '[hash:base64:5]',
  }
  const cssLoaders = webpackConfig.module.loaders[3].loader.split('!')
  cssLoaders.map(item => {
    if (item.startsWith('css')) {
      return `css?${JSON.stringify(cssLoaderOption)}`
    }
    return item
  })
  webpackConfig.module.loaders[3].loader = cssLoaders.join('!')

  // PreLoaders
  webpackConfig.module.preLoaders = [{
    test: /\.js$/,
    enforce: 'pre',
    loader: 'eslint',
  }]

  return webpackConfig
}
<|endoftext|>


<commit_before>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

/* eslint-disable global-require */

const path = require('path');
const webpack = require('webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const pkg = require('./package.json');

const isDebug = global.DEBUG === false ? false : !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose') || process.argv.includes('-v');
const useHMR = !!global.HMR; // Hot Module Replacement (HMR)
const babelConfig = Object.assign({}, pkg.babel, {
  babelrc: false,
  cacheDirectory: useHMR,
});

// Webpack configuration (main.js => public/dist/main.{hash}.js)
// http://webpack.github.io/docs/configuration.html
const config = {

  // The base directory for resolving the entry option
  context: __dirname,

  // The entry point for the bundle
  entry: [
    /* Material Design Lite (https://getmdl.io) */
    '!!style!css!react-mdl/extra/material.min.css',
    'react-mdl/extra/material.min.js',
    /* The main entry point of your JavaScript application */
    './main.js',
  ],

  // Options affecting the output of the compilation
  output: {
    path: path.resolve(__dirname, './public/dist'),
    publicPath: '/dist/',
    filename: isDebug ? '[name].js?[hash]' : '[name].[hash].js',
    chunkFilename: isDebug ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
    sourcePrefix: '  ',
  },

  // Switch loaders to debug or release mode
  debug: isDebug,

  // Developer tool to enhance debugging, source maps
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'source-map' : false,

  // What information should be printed to the console
  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  // The list of plugins for Webpack compiler
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      __DEV__: isDebug,
    }),
    // Emit a JSON file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, './public/dist'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
  ],

  // Options affecting the normal modules
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, './components'),
          path.resolve(__dirname, './core'),
          path.resolve(__dirname, './pages'),
          path.resolve(__dirname, './main.js'),
        ],
        loader: `babel-loader?${JSON.stringify(babelConfig)}`,
      },
      {
        test: /\.css/,
        loaders: [
          'style-loader',
          `css-loader?${JSON.stringify({
            sourceMap: isDebug,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
            // CSS Nano http://cssnano.co/options/
            minimize: !isDebug,
          })}`,
          'postcss-loader',
        ],
      },
      {
        test: /\.json$/,
        exclude: [
          path.resolve(__dirname, './routes.json'),
        ],
        loader: 'json-loader',
      },
      {
        test: /\.json$/,
        include: [
          path.resolve(__dirname, './routes.json'),
        ],
        loaders: [
          `babel-loader?${JSON.stringify(babelConfig)}`,
          path.resolve(__dirname, './utils/routes-loader.js'),
        ],
      },
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './utils/markdown-loader.js'),
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
      },
      {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
      },
    ],
  },

  // The list of plugins for PostCSS
  // https://github.com/postcss/postcss
  postcss(bundler) {
    return [
      // Transfer @import rule by inlining content, e.g. @import 'normalize.css'
      // https://github.com/postcss/postcss-import
      require('postcss-import')({ addDependencyTo: bundler }),
      // W3C variables, e.g. :root { --color: red; } div { background: var(--color); }
      // https://github.com/postcss/postcss-custom-properties
      require('postcss-custom-properties')(),
      // W3C CSS Custom Media Queries, e.g. @custom-media --small-viewport (max-width: 30em);
      // https://github.com/postcss/postcss-custom-media
      require('postcss-custom-media')(),
      // CSS4 Media Queries, e.g. @media screen and (width >= 500px) and (width <= 1200px) { }
      // https://github.com/postcss/postcss-media-minmax
      require('postcss-media-minmax')(),
      // W3C CSS Custom Selectors, e.g. @custom-selector :--heading h1, h2, h3, h4, h5, h6;
      // https://github.com/postcss/postcss-custom-selectors
      require('postcss-custom-selectors')(),
      // W3C calc() function, e.g. div { height: calc(100px - 2em); }
      // https://github.com/postcss/postcss-calc
      require('postcss-calc')(),
      // Allows you to nest one style rule inside another
      // https://github.com/jonathantneal/postcss-nesting
      require('postcss-nesting')(),
      // W3C color() function, e.g. div { background: color(red alpha(90%)); }
      // https://github.com/postcss/postcss-color-function
      require('postcss-color-function')(),
      // Convert CSS shorthand filters to SVG equivalent, e.g. .blur { filter: blur(4px); }
      // https://github.com/iamvdo/pleeease-filters
      require('pleeease-filters')(),
      // Generate pixel fallback for "rem" units, e.g. div { margin: 2.5rem 2px 3em 100%; }
      // https://github.com/robwierzbowski/node-pixrem
      require('pixrem')(),
      // W3C CSS Level4 :matches() pseudo class, e.g. p:matches(:first-child, .special) { }
      // https://github.com/postcss/postcss-selector-matches
      require('postcss-selector-matches')(),
      // Transforms :not() W3C CSS Level 4 pseudo class to :not() CSS Level 3 selectors
      // https://github.com/postcss/postcss-selector-not
      require('postcss-selector-not')(),
      // Add vendor prefixes to CSS rules using values from caniuse.com
      // https://github.com/postcss/autoprefixer
      require('autoprefixer')(),
    ];
  },

};

// Optimize the bundle in release (production) mode
if (!isDebug) {
  config.plugins.push(new webpack.optimize.DedupePlugin());
  config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: isVerbose } }));
  config.plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}

// Hot Module Replacement (HMR) + React Hot Reload
if (isDebug && useHMR) {
  babelConfig.plugins.unshift('react-hot-loader/babel');
  config.entry.unshift('react-hot-loader/patch', 'webpack-hot-middleware/client');
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(new webpack.NoErrorsPlugin());
}

module.exports = config;
<commit_msg>temporarily remove sourcemap causing images not to show up<commit_after>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

/* eslint-disable global-require */

const path = require('path');
const webpack = require('webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const pkg = require('./package.json');

const isDebug = global.DEBUG === false ? false : !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose') || process.argv.includes('-v');
const useHMR = !!global.HMR; // Hot Module Replacement (HMR)
const babelConfig = Object.assign({}, pkg.babel, {
  babelrc: false,
  cacheDirectory: useHMR,
});

// Webpack configuration (main.js => public/dist/main.{hash}.js)
// http://webpack.github.io/docs/configuration.html
const config = {

  // The base directory for resolving the entry option
  context: __dirname,

  // The entry point for the bundle
  entry: [
    /* Material Design Lite (https://getmdl.io) */
    '!!style!css!react-mdl/extra/material.min.css',
    'react-mdl/extra/material.min.js',
    /* The main entry point of your JavaScript application */
    './main.js',
  ],

  // Options affecting the output of the compilation
  output: {
    path: path.resolve(__dirname, './public/dist'),
    publicPath: '/dist/',
    filename: isDebug ? '[name].js?[hash]' : '[name].[hash].js',
    chunkFilename: isDebug ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
    sourcePrefix: '  ',
  },

  // Switch loaders to debug or release mode
  debug: isDebug,

  // Developer tool to enhance debugging, source maps
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'source-map' : false,

  // What information should be printed to the console
  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  // The list of plugins for Webpack compiler
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      __DEV__: isDebug,
    }),
    // Emit a JSON file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, './public/dist'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
  ],

  // Options affecting the normal modules
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, './components'),
          path.resolve(__dirname, './core'),
          path.resolve(__dirname, './pages'),
          path.resolve(__dirname, './main.js'),
        ],
        loader: `babel-loader?${JSON.stringify(babelConfig)}`,
      },
      {
        test: /\.css/,
        loaders: [
          'style-loader',
          `css-loader?${JSON.stringify({
            // sourceMap: isDebug,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
            // CSS Nano http://cssnano.co/options/
            minimize: !isDebug,
          })}`,
          'postcss-loader',
        ],
      },
      {
        test: /\.json$/,
        exclude: [
          path.resolve(__dirname, './routes.json'),
        ],
        loader: 'json-loader',
      },
      {
        test: /\.json$/,
        include: [
          path.resolve(__dirname, './routes.json'),
        ],
        loaders: [
          `babel-loader?${JSON.stringify(babelConfig)}`,
          path.resolve(__dirname, './utils/routes-loader.js'),
        ],
      },
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './utils/markdown-loader.js'),
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
      },
      {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
      },
    ],
  },

  // The list of plugins for PostCSS
  // https://github.com/postcss/postcss
  postcss(bundler) {
    return [
      // Transfer @import rule by inlining content, e.g. @import 'normalize.css'
      // https://github.com/postcss/postcss-import
      require('postcss-import')({ addDependencyTo: bundler }),
      // W3C variables, e.g. :root { --color: red; } div { background: var(--color); }
      // https://github.com/postcss/postcss-custom-properties
      require('postcss-custom-properties')(),
      // W3C CSS Custom Media Queries, e.g. @custom-media --small-viewport (max-width: 30em);
      // https://github.com/postcss/postcss-custom-media
      require('postcss-custom-media')(),
      // CSS4 Media Queries, e.g. @media screen and (width >= 500px) and (width <= 1200px) { }
      // https://github.com/postcss/postcss-media-minmax
      require('postcss-media-minmax')(),
      // W3C CSS Custom Selectors, e.g. @custom-selector :--heading h1, h2, h3, h4, h5, h6;
      // https://github.com/postcss/postcss-custom-selectors
      require('postcss-custom-selectors')(),
      // W3C calc() function, e.g. div { height: calc(100px - 2em); }
      // https://github.com/postcss/postcss-calc
      require('postcss-calc')(),
      // Allows you to nest one style rule inside another
      // https://github.com/jonathantneal/postcss-nesting
      require('postcss-nesting')(),
      // W3C color() function, e.g. div { background: color(red alpha(90%)); }
      // https://github.com/postcss/postcss-color-function
      require('postcss-color-function')(),
      // Convert CSS shorthand filters to SVG equivalent, e.g. .blur { filter: blur(4px); }
      // https://github.com/iamvdo/pleeease-filters
      require('pleeease-filters')(),
      // Generate pixel fallback for "rem" units, e.g. div { margin: 2.5rem 2px 3em 100%; }
      // https://github.com/robwierzbowski/node-pixrem
      require('pixrem')(),
      // W3C CSS Level4 :matches() pseudo class, e.g. p:matches(:first-child, .special) { }
      // https://github.com/postcss/postcss-selector-matches
      require('postcss-selector-matches')(),
      // Transforms :not() W3C CSS Level 4 pseudo class to :not() CSS Level 3 selectors
      // https://github.com/postcss/postcss-selector-not
      require('postcss-selector-not')(),
      // Add vendor prefixes to CSS rules using values from caniuse.com
      // https://github.com/postcss/autoprefixer
      require('autoprefixer')(),
    ];
  },

};

// Optimize the bundle in release (production) mode
if (!isDebug) {
  config.plugins.push(new webpack.optimize.DedupePlugin());
  config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: isVerbose } }));
  config.plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}

// Hot Module Replacement (HMR) + React Hot Reload
if (isDebug && useHMR) {
  babelConfig.plugins.unshift('react-hot-loader/babel');
  config.entry.unshift('react-hot-loader/patch', 'webpack-hot-middleware/client');
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(new webpack.NoErrorsPlugin());
}

module.exports = config;
<|endoftext|>


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

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

function getFolders(dir) {
	return fs.readdirSync(dir)
		.filter(function(file) {
			return fs.statSync(path.join(dir, file)).isDirectory();
		});
}

module.exports = (options) => {
	const webpackEntry = {

	};

	options.entries.map((entry) => {
		if (entry.forEachFolderIn) {
			var folders = getFolders(entry.forEachFolderIn);

			folders.map((folder) => {
				var entryKey = './' + path.join(
					entry.forEachFolderIn,
					folder,
					entry.entry
				);

				var entryValue = path.join(
					entry.forEachFolderIn,
					folder,
					entry.output
				);

				webpackEntry[entryValue] = entryKey;
			});
		} else {
			webpackEntry[entry.output] = entry.entry;
		}
	});

const config = {
	entry: webpackEntry,

	output: {
		path: './',
		filename: '[name].js'
	},

    devtool: isDevelopment ? 'source-map' : null,

	module: {
		loaders: [
			{
				test: /\.(js|jsx)$/,
				loader: require.resolve('babel-loader'),
				query: {
					presets: [
						require.resolve('babel-preset-es2015-loose')
					],
					plugins: [
						require.resolve('babel-plugin-transform-es3-property-literals'),
						require.resolve('babel-plugin-transform-es3-member-expression-literals')
					]
				}

				// TODO: configure load paths here. May slow down builds!!!
			},

			{
				test: /\.scss$/,
				loaders: ["style", "css", "sass"]
			},
			{
				test: /\.png$/,
				loader: "url-loader?limit=100000"
			},
			{
				test: /\.jpg$/,
				loader: "file-loader"
			},
			{
				test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
				loader: 'file-loader'
			}

		]
	},

	resolve: {
		extensions: ['', '.js', '.jsx', '.css'],
		modulesDirectories: [
			'node_modules',
            'bower_components'
		]
	},

	plugins: [
		new webpack.ProvidePlugin({
			'$': 'jquery'
		}),

		new webpack.NoErrorsPlugin()
	].concat(
        isDevelopment ? [] : new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		})
    ),

	externals: {
		jquery: 'window.jQuery',
		'_': 'window._'
	}
}

	return config;
};

<commit_msg>fix indentation<commit_after>var path = require("path");
var webpack = require('webpack');
var fs = require('fs');

const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';

function getFolders(dir) {
	return fs.readdirSync(dir)
		.filter(function(file) {
			return fs.statSync(path.join(dir, file)).isDirectory();
		});
}

module.exports = (options) => {
	const webpackEntry = {

	};

	options.entries.map((entry) => {
		if (entry.forEachFolderIn) {
			var folders = getFolders(entry.forEachFolderIn);

			folders.map((folder) => {
				var entryKey = './' + path.join(
					entry.forEachFolderIn,
					folder,
					entry.entry
				);

				var entryValue = path.join(
					entry.forEachFolderIn,
					folder,
					entry.output
				);

				webpackEntry[entryValue] = entryKey;
			});
		} else {
			webpackEntry[entry.output] = entry.entry;
		}
	});

const config = {
	entry: webpackEntry,

	output: {
		path: './',
		filename: '[name].js'
	},

    devtool: isDevelopment ? 'source-map' : null,

	module: {
		loaders: [
			{
				test: /\.(js|jsx)$/,
				loader: require.resolve('babel-loader'),
				query: {
					presets: [
						require.resolve('babel-preset-es2015-loose')
					],
					plugins: [
						require.resolve('babel-plugin-transform-es3-property-literals'),
						require.resolve('babel-plugin-transform-es3-member-expression-literals')
					]
				}

				// TODO: configure load paths here. May slow down builds!!!
			},

			{
				test: /\.scss$/,
				loaders: ["style", "css", "sass"]
			},
			{
				test: /\.png$/,
				loader: "url-loader?limit=100000"
			},
			{
				test: /\.jpg$/,
				loader: "file-loader"
			},
			{
				test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
				loader: 'file-loader'
			}

		]
	},

	resolve: {
		extensions: ['', '.js', '.jsx', '.css'],
		modulesDirectories: [
			'node_modules',
			'bower_components'
		]
	},

	plugins: [
		new webpack.ProvidePlugin({
			'$': 'jquery'
		}),

		new webpack.NoErrorsPlugin()
	].concat(
        isDevelopment ? [] : new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		})
    ),

	externals: {
		jquery: 'window.jQuery',
		'_': 'window._'
	}
}

	return config;
};

<|endoftext|>


<commit_before>
function DOMElement (node, options) {
    if (typeof options === 'string') {
        console.warn(
            'HTMLElement constructor signature changed!\n' +
            'Pass in an options object with {tagName: ' + options + '} instead.'
        );
        options = {
            tagName: options
        };
    }

    this._node = node;

    this._requestingUpdate = false;

    this._changeQueue = [];

    this._classes = ['fa-surface'];
    this._requestingEventListeners = [];
    this._styles = {
        display: 'none'
    };
    this._attributes = {};
    this._content = null;

    this._tagName = options && options.tagName ? options.tagName : 'div';
    this._id = node.addComponent(this);

    if (!options) return;

    if (options.classes) {
        for (var i = 0; i < options.classes.length; i++)
            this.addClass(options.classes[i]);
    }

    if (options.attributes) {
        for (var key in options.attributes)
            this.setAttribute(key, options.attributes[key]);
    }

    if (options.properties) {
        for (var key in options.properties)
            this.setProperty(key, options.properties[key]);
    }

    if (options.id) this.setId(options.id);
    if (options.content) this.setContent(options.content);
}

DOMElement.prototype.getValue = function getValue () {
    return {
        classes: this._classes,
        styles: this._styles,
        attributes: this._attributes,
        content: this._content
    };
};

DOMElement.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;
    var len = queue.length;

    if (len && node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());
        node.sendDrawCommand('DOM');

        while (len--) node.sendDrawCommand(queue.shift());
    }

    this._requestingUpdate = false;
};

DOMElement.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;
    this.draw();
    this.setAttribute('data-fa-path', node.getLocation());
};

DOMElement.prototype.onDismount = function onDismount () {
    this.setProperty('display', 'none');
    this.setAttribute('data-fa-path', '');
    this._changeQueue.push('RECALL');
    this._initialized = false;
};

DOMElement.prototype.onShow = function onShow () {
    this.setProperty('display', 'block');
};

DOMElement.prototype.onHide = function onHide () {
    this.setProperty('display', 'none');
    this._changeQueue.push('RECALL');
};

DOMElement.prototype.onTransformChange = function onTransformChange (transform) {
    this._changeQueue.push('CHANGE_TRANSFORM');
    for (var i = 0, len = transform.length ; i < len ; i++)
        this._changeQueue.push(transform[i]);

    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.onSizeChange = function onSizeChange (size) {
    var sizeMode = this._node.getSizeMode();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    this._changeQueue.push('CHANGE_SIZE',
            sizedX ? size[0] : sizedX,
            sizedY ? size[1] : sizedY);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    this._changeQueue.push('ADD_EVENT_LISTERNER', UIEvent);
    if (methods != null) this._changeQueue.push(methods);
    if (properties != null) this._changeQueue.push(properties);
    if (!this._requestingUpdate) this._requestUpdate();
    this._changeQueue.push('EVENT_END');
};

DOMElement.prototype.onSizeModeChange = function onSizeModeChange (sizeMode) {
    var size = this._node.getSize();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    if (sizedX) this.setProperty('width', size[0] + 'px');
    if (sizedY) this.setProperty('height', size[1] + 'px');
};

DOMElement.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

DOMElement.prototype.init = function init () {
    this._changeQueue.push('INIT_DOM', this._tagName);
    this._initialized = true;
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.setId = function setId (id) {
    this.setAttribute('id', id);
    return this;
};

DOMElement.prototype.addClass = function addClass (value) {
    if (this._classes.indexOf(value) < 0) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        this._classes.push(value);
        if (!this._requestingUpdate) this._requestUpdate();
        return this;
    }

    if (this._inDraw) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.removeClass = function removeClass (value) {
    var index = this._classes.indexOf(value);

    if (index < 0) return this;

    this._changeQueue.push('REMOVE_CLASS', value);

    this._classes.splice(index, 1);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.setAttribute = function setAttribute (name, value) {
    if (this._attributes[name] !== value || this._inDraw) {
        this._attributes[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_ATTRIBUTE', name, value);
        if (!this._requestUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setProperty = function setProperty (name, value) {
    if (this._styles[name] !== value || this._inDraw) {
        this._styles[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_PROPERTY', name, value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setContent = function setContent (content) {
    if (this._content !== content || this._inDraw) {
        this._content = content;
        if (this._initialized) this._changeQueue.push('CHANGE_CONTENT', content);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    for (i = 0, len = this._classes.length ; i < len ; i++)
        this.addClass(this._classes[i]);

    this.setContent(this._content);

    for (key in this._styles)
        if (this._styles[key])
            this.setProperty(key, this._styles[key]);

    for (key in this._attributes)
        if (this._attributes[key])
            this.setAttribute(key, this._attributes[key]);

    this._inDraw = false;
};

module.exports = DOMElement;

<commit_msg>fix: removed recall<commit_after>
function DOMElement (node, options) {
    if (typeof options === 'string') {
        console.warn(
            'HTMLElement constructor signature changed!\n' +
            'Pass in an options object with {tagName: ' + options + '} instead.'
        );
        options = {
            tagName: options
        };
    }

    this._node = node;

    this._requestingUpdate = false;

    this._changeQueue = [];

    this._classes = ['fa-surface'];
    this._requestingEventListeners = [];
    this._styles = {
        display: 'none'
    };
    this._attributes = {};
    this._content = null;

    this._tagName = options && options.tagName ? options.tagName : 'div';
    this._id = node.addComponent(this);

    if (!options) return;

    if (options.classes) {
        for (var i = 0; i < options.classes.length; i++)
            this.addClass(options.classes[i]);
    }

    if (options.attributes) {
        for (var key in options.attributes)
            this.setAttribute(key, options.attributes[key]);
    }

    if (options.properties) {
        for (var key in options.properties)
            this.setProperty(key, options.properties[key]);
    }

    if (options.id) this.setId(options.id);
    if (options.content) this.setContent(options.content);
}

DOMElement.prototype.getValue = function getValue () {
    return {
        classes: this._classes,
        styles: this._styles,
        attributes: this._attributes,
        content: this._content
    };
};

DOMElement.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;
    var len = queue.length;

    if (len && node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());
        node.sendDrawCommand('DOM');

        while (len--) node.sendDrawCommand(queue.shift());
    }

    this._requestingUpdate = false;
};

DOMElement.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;
    this.draw();
    this.setAttribute('data-fa-path', node.getLocation());
};

DOMElement.prototype.onDismount = function onDismount () {
    this.setProperty('display', 'none');
    this.setAttribute('data-fa-path', '');
    this._initialized = false;
};

DOMElement.prototype.onShow = function onShow () {
    this.setProperty('display', 'block');
};

DOMElement.prototype.onHide = function onHide () {
    this.setProperty('display', 'none');
};

DOMElement.prototype.onTransformChange = function onTransformChange (transform) {
    this._changeQueue.push('CHANGE_TRANSFORM');
    for (var i = 0, len = transform.length ; i < len ; i++)
        this._changeQueue.push(transform[i]);

    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.onSizeChange = function onSizeChange (size) {
    var sizeMode = this._node.getSizeMode();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    this._changeQueue.push('CHANGE_SIZE',
            sizedX ? size[0] : sizedX,
            sizedY ? size[1] : sizedY);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    this._changeQueue.push('ADD_EVENT_LISTERNER', UIEvent);
    if (methods != null) this._changeQueue.push(methods);
    if (properties != null) this._changeQueue.push(properties);
    if (!this._requestingUpdate) this._requestUpdate();
    this._changeQueue.push('EVENT_END');
};

DOMElement.prototype.onSizeModeChange = function onSizeModeChange (sizeMode) {
    var size = this._node.getSize();
    var sizedX = sizeMode[0] !== Node.RENDER_SIZE;
    var sizedY = sizeMode[1] !== Node.RENDER_SIZE;
    if (sizedX) this.setProperty('width', size[0] + 'px');
    if (sizedY) this.setProperty('height', size[1] + 'px');
};

DOMElement.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

DOMElement.prototype.init = function init () {
    this._changeQueue.push('INIT_DOM', this._tagName);
    this._initialized = true;
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    if (!this._requestingUpdate) this._requestUpdate();
};

DOMElement.prototype.setId = function setId (id) {
    this.setAttribute('id', id);
    return this;
};

DOMElement.prototype.addClass = function addClass (value) {
    if (this._classes.indexOf(value) < 0) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        this._classes.push(value);
        if (!this._requestingUpdate) this._requestUpdate();
        return this;
    }

    if (this._inDraw) {
        if (this._initialized) this._changeQueue.push('ADD_CLASS', value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.removeClass = function removeClass (value) {
    var index = this._classes.indexOf(value);

    if (index < 0) return this;

    this._changeQueue.push('REMOVE_CLASS', value);

    this._classes.splice(index, 1);

    if (!this._requestingUpdate) this._requestUpdate();
    return this;
};

DOMElement.prototype.setAttribute = function setAttribute (name, value) {
    if (this._attributes[name] !== value || this._inDraw) {
        this._attributes[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_ATTRIBUTE', name, value);
        if (!this._requestUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setProperty = function setProperty (name, value) {
    if (this._styles[name] !== value || this._inDraw) {
        this._styles[name] = value;
        if (this._initialized) this._changeQueue.push('CHANGE_PROPERTY', name, value);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.setContent = function setContent (content) {
    if (this._content !== content || this._inDraw) {
        this._content = content;
        if (this._initialized) this._changeQueue.push('CHANGE_CONTENT', content);
        if (!this._requestingUpdate) this._requestUpdate();
    }
    return this;
};

DOMElement.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    for (i = 0, len = this._classes.length ; i < len ; i++)
        this.addClass(this._classes[i]);

    this.setContent(this._content);

    for (key in this._styles)
        if (this._styles[key])
            this.setProperty(key, this._styles[key]);

    for (key in this._attributes)
        if (this._attributes[key])
            this.setAttribute(key, this._attributes[key]);

    this._inDraw = false;
};

module.exports = DOMElement;

<|endoftext|>


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

/**
 * Node dependencies
 */
const fs = require( 'fs' );
const path = require( 'path' );

/**
 * External dependencies
 */
const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WebpackBar = require( 'webpackbar' );
const { ProvidePlugin } = require( 'webpack' );

const projectPath = ( relativePath ) => {
	return path.resolve( fs.realpathSync( process.cwd() ), relativePath );
};

const noAMDParserRule = { parser: { amd: false } };

const siteKitExternals = {
	'googlesitekit-api': [ 'googlesitekit', 'api' ],
	'googlesitekit-data': [ 'googlesitekit', 'data' ],
	'googlesitekit-modules': [ 'googlesitekit', 'modules' ],
};

const externals = { ...siteKitExternals };

const rules = [
	noAMDParserRule,
	{
		test: /\.js$/,
		exclude: /node_modules/,
		use: [
			{
				loader: 'babel-loader',
				query: {
					presets: [ [ '@babel/env', {
						useBuiltIns: 'entry',
						corejs: 2,
					} ], '@babel/preset-react' ],
				},
			},
			{
				loader: 'eslint-loader',
				options: {
					quiet: true,
					formatter: require( 'eslint' ).CLIEngine.getFormatter( 'stylish' ),
				},
			},
		],
		...noAMDParserRule,
	},
];

const resolve = {
	alias: {
		'@wordpress/api-fetch__non-shim': require.resolve( '@wordpress/api-fetch' ),
		'@wordpress/api-fetch$': path.resolve( 'assets/js/api-fetch-shim.js' ),
		SiteKitCore: path.resolve( 'assets/js/' ),
		GoogleComponents: path.resolve( 'assets/js/components/' ),
		GoogleUtil: path.resolve( 'assets/js/util/' ),
		GoogleModules: path.resolve( './assets/js/modules/' ),
	},
	modules: [ projectPath( '.' ), 'node_modules' ],
};

const webpackConfig = ( mode ) => {
	return [
		// Build the settings js..
		{
			entry: {
				// New Modules (Post-JSR).
				'googlesitekit-api': './assets/js/googlesitekit-api.js',
				'googlesitekit-data': './assets/js/googlesitekit-data.js',
				'googlesitekit-datastore-site': './assets/js/googlesitekit-datastore-site.js',
				'googlesitekit-modules': './assets/js/googlesitekit-modules.js', // TODO: Add external following 1162.
				// Old Modules
				'googlesitekit-activation': './assets/js/googlesitekit-activation.js',
				'googlesitekit-settings': './assets/js/googlesitekit-settings.js',
				'googlesitekit-dashboard': './assets/js/googlesitekit-dashboard.js',
				'googlesitekit-dashboard-details': './assets/js/googlesitekit-dashboard-details.js',
				'googlesitekit-dashboard-splash': './assets/js/googlesitekit-dashboard-splash.js',
				'googlesitekit-wp-dashboard': './assets/js/googlesitekit-wp-dashboard.js',
				'googlesitekit-adminbar-loader': './assets/js/googlesitekit-adminbar-loader.js',
				'googlesitekit-admin': './assets/js/googlesitekit-admin.js',
				'googlesitekit-module': './assets/js/googlesitekit-module.js',
				// Needed to test if a browser extension blocks this by naming convention.
				ads: './assets/js/ads.js',
			},
			externals,
			output: {
				filename: '[name].js',
				path: __dirname + '/dist/assets/js',
				chunkFilename: '[name]-[chunkhash].js',
				publicPath: '',
			},
			performance: {
				maxEntrypointSize: 175000,
			},
			module: {
				rules,
			},
			plugins: [
				new ProvidePlugin( {
					React: 'react',
				} ),
				new WebpackBar( {
					name: 'Module Entry Points',
					color: '#fbbc05',
				} ),
				new CleanWebpackPlugin( {
					// Stop this build from removing unrelated JS and CSS files.
					cleanOnceBeforeBuildPatterns: [],
				} ),
			],
			optimization: {
				minimizer: [
					new TerserPlugin( {
						parallel: true,
						sourceMap: false,
						cache: true,
						terserOptions: {
							// We preserve function names that start with capital letters as
							// they're _likely_ component names, and these are useful to have
							// in tracebacks and error messages.
							keep_fnames: /__|_x|_n|_nx|sprintf|^[A-Z].+$/,
							output: {
								comments: /translators:/i,
							},
						},
						extractComments: false,
					} ),
				],
			},
			resolve,
		},

		// Build the main plugin admin css.
		{
			entry: {
				admin: './assets/sass/admin.scss',
				adminbar: './assets/sass/adminbar.scss',
				wpdashboard: './assets/sass/wpdashboard.scss',
			},
			module: {
				rules: [
					{
						test: /\.scss$/,
						use: [
							MiniCssExtractPlugin.loader,
							{
								loader: 'css-loader',
								options: {
									minimize: ( 'production' === mode ),
								},
							},
							'postcss-loader',
							{
								loader: 'sass-loader',
								options: {
									includePaths: [ 'node_modules' ],
								},
							},
						],
					},
					{
						test: /\.(png|woff|woff2|eot|ttf|svg|gif)$/,
						use: { loader: 'url-loader?limit=100000' },
					},
				],
			},
			plugins: [
				new MiniCssExtractPlugin( {
					filename: '/assets/css/[name].css',
				} ),
				new WebpackBar( {
					name: 'Plugin CSS',
					color: '#4285f4',
				} ),
				new CleanWebpackPlugin( {
					// Stop this build from removing unrelated JS and CSS files.
					cleanOnceBeforeBuildPatterns: [],
				} ),
			],
		},
	];
};

const testBundle = () => {
	return {
		entry: {
			'googlesitekit-tests': './assets/js/googlesitekit-tests.js',
			'e2e-utilities': './tests/e2e/e2e-utilities.js',
		},
		output: {
			filename: '[name].js',
			path: __dirname + '/dist/assets/js',
			chunkFilename: '[name].js',
			publicPath: '',
		},
		module: {
			rules,
		},
		plugins: [
			new WebpackBar( {
				name: 'Test files',
				color: '#34a853',
			} ),
			new CleanWebpackPlugin( {
				// Stop this build from removing unrelated JS and CSS files.
				cleanOnceBeforeBuildPatterns: [],
			} ),
		],
		externals,
		resolve,
	};
};

module.exports = ( ...args ) => {
	const { includeTests, mode } = args[ 1 ];
	const config = webpackConfig( mode );

	if ( mode !== 'production' || includeTests ) {
		// Build the test files if we aren't doing a production build.
		config.push( testBundle() );
	}

	return config;
};
<commit_msg>Linting fixes.<commit_after>/**
 * Webpack config.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Node dependencies
 */
const fs = require( 'fs' );
const path = require( 'path' );

/**
 * External dependencies
 */
const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
const { CleanWebpackPlugin } = require( 'clean-webpack-plugin' );
const WebpackBar = require( 'webpackbar' );
const { ProvidePlugin } = require( 'webpack' );

const projectPath = ( relativePath ) => {
	return path.resolve( fs.realpathSync( process.cwd() ), relativePath );
};

const noAMDParserRule = { parser: { amd: false } };

const siteKitExternals = {
	'googlesitekit-api': [ 'googlesitekit', 'api' ],
	'googlesitekit-data': [ 'googlesitekit', 'data' ],
	'googlesitekit-modules': [ 'googlesitekit', 'modules' ],
};

const externals = { ...siteKitExternals };

const rules = [
	noAMDParserRule,
	{
		test: /\.js$/,
		exclude: /node_modules/,
		use: [
			{
				loader: 'babel-loader',
				query: {
					presets: [ [ '@babel/env', {
						useBuiltIns: 'entry',
						corejs: 2,
					} ], '@babel/preset-react' ],
				},
			},
			{
				loader: 'eslint-loader',
				options: {
					quiet: true,
					formatter: require( 'eslint' ).CLIEngine.getFormatter( 'stylish' ),
				},
			},
		],
		...noAMDParserRule,
	},
];

const resolve = {
	alias: {
		'@wordpress/api-fetch__non-shim': require.resolve( '@wordpress/api-fetch' ),
		'@wordpress/api-fetch$': path.resolve( 'assets/js/api-fetch-shim.js' ),
		SiteKitCore: path.resolve( 'assets/js/' ),
		GoogleComponents: path.resolve( 'assets/js/components/' ),
		GoogleUtil: path.resolve( 'assets/js/util/' ),
		GoogleModules: path.resolve( './assets/js/modules/' ),
	},
	modules: [ projectPath( '.' ), 'node_modules' ],
};

const webpackConfig = ( mode ) => {
	return [
		// Build the settings js..
		{
			entry: {
				// New Modules (Post-JSR).
				'googlesitekit-api': './assets/js/googlesitekit-api.js',
				'googlesitekit-data': './assets/js/googlesitekit-data.js',
				'googlesitekit-datastore-site': './assets/js/googlesitekit-datastore-site.js',
				'googlesitekit-modules': './assets/js/googlesitekit-modules.js', // TODO: Add external following 1162.
				// Old Modules
				'googlesitekit-activation': './assets/js/googlesitekit-activation.js',
				'googlesitekit-settings': './assets/js/googlesitekit-settings.js',
				'googlesitekit-dashboard': './assets/js/googlesitekit-dashboard.js',
				'googlesitekit-dashboard-details': './assets/js/googlesitekit-dashboard-details.js',
				'googlesitekit-dashboard-splash': './assets/js/googlesitekit-dashboard-splash.js',
				'googlesitekit-wp-dashboard': './assets/js/googlesitekit-wp-dashboard.js',
				'googlesitekit-adminbar-loader': './assets/js/googlesitekit-adminbar-loader.js',
				'googlesitekit-admin': './assets/js/googlesitekit-admin.js',
				'googlesitekit-module': './assets/js/googlesitekit-module.js',
				// Needed to test if a browser extension blocks this by naming convention.
				ads: './assets/js/ads.js',
			},
			externals,
			output: {
				filename: '[name].js',
				path: __dirname + '/dist/assets/js',
				chunkFilename: '[name]-[chunkhash].js',
				publicPath: '',
			},
			performance: {
				maxEntrypointSize: 175000,
			},
			module: {
				rules,
			},
			plugins: [
				new ProvidePlugin( {
					React: 'react',
				} ),
				new WebpackBar( {
					name: 'Module Entry Points',
					color: '#fbbc05',
				} ),
				new CleanWebpackPlugin( {
					// Stop this build from removing unrelated JS and CSS files.
					cleanOnceBeforeBuildPatterns: [],
				} ),
			],
			optimization: {
				minimizer: [
					new TerserPlugin( {
						parallel: true,
						sourceMap: false,
						cache: true,
						terserOptions: {
							// We preserve function names that start with capital letters as
							// they're _likely_ component names, and these are useful to have
							// in tracebacks and error messages.
							keep_fnames: /__|_x|_n|_nx|sprintf|^[A-Z].+$/,
							output: {
								comments: /translators:/i,
							},
						},
						extractComments: false,
					} ),
				],
			},
			resolve,
		},

		// Build the main plugin admin css.
		{
			entry: {
				admin: './assets/sass/admin.scss',
				adminbar: './assets/sass/adminbar.scss',
				wpdashboard: './assets/sass/wpdashboard.scss',
			},
			module: {
				rules: [
					{
						test: /\.scss$/,
						use: [
							MiniCssExtractPlugin.loader,
							{
								loader: 'css-loader',
								options: {
									minimize: ( 'production' === mode ),
								},
							},
							'postcss-loader',
							{
								loader: 'sass-loader',
								options: {
									includePaths: [ 'node_modules' ],
								},
							},
						],
					},
					{
						test: /\.(png|woff|woff2|eot|ttf|svg|gif)$/,
						use: { loader: 'url-loader?limit=100000' },
					},
				],
			},
			plugins: [
				new MiniCssExtractPlugin( {
					filename: '/assets/css/[name].css',
				} ),
				new WebpackBar( {
					name: 'Plugin CSS',
					color: '#4285f4',
				} ),
				new CleanWebpackPlugin( {
					// Stop this build from removing unrelated JS and CSS files.
					cleanOnceBeforeBuildPatterns: [],
				} ),
			],
		},
	];
};

const testBundle = () => {
	return {
		entry: {
			'googlesitekit-tests': './assets/js/googlesitekit-tests.js',
			'e2e-utilities': './tests/e2e/e2e-utilities.js',
		},
		output: {
			filename: '[name].js',
			path: __dirname + '/dist/assets/js',
			chunkFilename: '[name].js',
			publicPath: '',
		},
		module: {
			rules,
		},
		plugins: [
			new WebpackBar( {
				name: 'Test files',
				color: '#34a853',
			} ),
			new CleanWebpackPlugin( {
				// Stop this build from removing unrelated JS and CSS files.
				cleanOnceBeforeBuildPatterns: [],
			} ),
		],
		externals,
		resolve,
	};
};

module.exports = ( ...args ) => {
	const { includeTests, mode } = args[ 1 ];
	const config = webpackConfig( mode );

	if ( mode !== 'production' || includeTests ) {
		// Build the test files if we aren't doing a production build.
		config.push( testBundle() );
	}

	return config;
};
<|endoftext|>


<commit_before>
"use strict";

class Model {

    constructor() {
        this.$data = {};
        this.$fields = [];
        this.$deleted = false;
    }

    $load(data = {}, recursive = true) {
        this.$initial = data;
        for (let key in data) {
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
            this.$fields.push(key);
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$update' in item && item.$dirty) {
                                item.$update();
                            } else if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $new() {
        return !('id' in this.$data && this.$data.id);
    }

    get $dirty() {
        let dirty = false;
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty) {
                            dirty = true;
                        }
                    });
                } else if (this[key].$dirty) {
                    return true;
                }
            }
        }
        return dirty;
    }

    $pluralize(field) {
        field = field.replace(/y$/, 'ie');
        return this[field + 's'];
    }

};

export {Model};

<commit_msg>switch order; deleted-check should come first so recursing works properly<commit_after>
"use strict";

class Model {

    constructor() {
        this.$data = {};
        this.$fields = [];
        this.$deleted = false;
    }

    $load(data = {}, recursive = true) {
        this.$initial = data;
        for (let key in data) {
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
            this.$fields.push(key);
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            } else if ('$update' in item && item.$dirty) {
                                item.$update();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $new() {
        return !('id' in this.$data && this.$data.id);
    }

    get $dirty() {
        if (this.$deleted) {
            return true;
        }
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    let dirty = false;
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty || elem.$deleted) {
                            dirty = true;
                        }
                    });
                    if (dirty) {
                        return true;
                    }
                } else if (this[key].$dirty || this[key].$deleted) {
                    return true;
                }
            }
        }
        return false;
    }

    $pluralize(field) {
        field = field.replace(/y$/, 'ie');
        return this[field + 's'];
    }

    $export() {
        let data = {};
        for (let prop in this) {
            if (prop.substring(0, 1) == '$') {
                continue;
            }
            data[prop] = this[prop];
        }
        return data;
    }

};

export {Model};

<|endoftext|>


<commit_before>'use strict';

const path = require('path');

module.exports = {
    entry: ['./src/js/app.js'],
    output: {
        path: path.join(__dirname, '/dist/js'),
        publicPath: 'js',
        filename: 'app.bundle.js',
    },
    devServer: {
        contentBase: 'src',
        host: '192.168.56.101'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.jsx?$/,
                exclude: /node_modules/,
            }
        ]
    },
};

<commit_msg>webpack-dev-server serve on localhost<commit_after>'use strict';

const path = require('path');

module.exports = {
    entry: ['./src/js/app.js'],
    output: {
        path: path.join(__dirname, '/dist/js'),
        publicPath: 'js',
        filename: 'app.bundle.js',
    },
    devServer: {
        contentBase: 'src',
        host: 'localhost'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.jsx?$/,
                exclude: /node_modules/,
            }
        ]
    },
};

<|endoftext|>


<commit_before>"use strict";
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
const GoogleFontsWebpackPlugin = require("google-fonts-webpack-plugin");
const HtmlWebpackDisplayLoaderPlugin = require("html-webpack-display-loader-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackPolyfillsPlugin = require("html-webpack-polyfills-plugin");
const webpack = require("webpack");

module.exports = {
    entry: {
        main: "./src"
    },
    output: {
        path: __dirname + "/dist",
        filename: "[name].js"
    },
    module: {
        rules: [{
            //
            // .vue拡張子のファイルは、vue-loaderで読み込みます。
            // <template>タグ、<style>タグ、<script>タグの内容が、HTML、CSS、javascriptとして読み込まれます。
            // lang属性を指定した場合には、対応するloader (sass-loader等) で読み込まれます。
            //
            test: /\.vue$/,
            use: [{
                loader: "vue-loader"
            }]
        }, {
            //
            // .js拡張子のファイルは、babel-loaderで読み込みます。
            // 最新の構文で書かれたスクリプトを、現行のブラウザで解釈できるスクリプトに変換してくれます。
            //
            test: /\.js$/,
            use: [{
                loader: "babel-loader"
            }]
        }, {
            //
            // 画像ファイルは、url-loaderで読み込みます。
            // ファイルの内容がエンコードされ、スクリプト内に埋め込まれます。
            // 32kB以上のファイルは、file-loaderで読み込みます。
            // ファイル名はハッシュ文字列に置き換えて配信されます。
            //
            test: /\.(?:ttf|woff2?|eot|png)$/,
            use: [{
                loader: "url-loader",
                options: {
                    limit: 32000,
                    name: "[hash].[ext]"
                }
            }]
        }]
    },
    resolve: {
        alias: {
            //
            // 各モジュールのビルドされたファイルへのエイリアスを設定します。
            // ex.) import vue from "vue" は import vue from "vue/dist/vue.esm" と同じです。
            //
            "vue$": "vue/dist/vue.esm.js"
        }
    },
    node: {
        __filename: true, // 各モジュール内で、そのモジュール自身の相対パスを__filenameで取得できます。
        __dirname: true // 各モジュール内で、そのモジュールを含むディレクトリの相対パスを__dirnameで取得できます。
    },
    devServer: {
        disableHostCheck: true,
        historyApiFallback: true,
        hot: true
    },
    devtool: process.env.NODE_ENV !== "production" && "cheap-module-eval-source-map" && "cheap-module-source-map",
    plugins: [
        //
        // スクリプト内の変数を環境変数で置き換えます。
        // 下記デフォルト値はテスト用のダミー変数です。
        //
        new webpack.EnvironmentPlugin({
            NODE_ENV: "development"
        }),
        //
        // EJSテンプレートからindex.htmlを作成します。
        // サイトにアクセスした時、最初に読み込まれるHTMLファイルになります。
        //
        new HtmlWebpackPlugin({
            title: "Frame | 1stop-st.org"
        }),
        //
        // 画像ファイルからマルチブラウザ対応のfaviconを生成します。
        // 生成されたfaviconへのリンクがindex.htmlに挿入されます。
        //
        new FaviconsWebpackPlugin({
            logo: "./resources/logo.png"
        }),
        //
        // Google Fonts から Webフォントを読み込む<style>タグがindex.htmlに挿入されます。
        //
        new GoogleFontsWebpackPlugin({
            fonts: [{
                family: "Roboto",
                variants: ["300", "400", "500"]
            }],
            local: false
        }),
        //
        // ブラウザに適したPolyfillを読み込む<script>タグがindex.htmlに挿入されます。
        // Polyfill service (https://polyfill.io)
        //
        new HtmlWebpackPolyfillsPlugin(),
        //
        // script読込み中にロード画面を表示するHTMLが挿入されます。
        //
        new HtmlWebpackDisplayLoaderPlugin({
            id: "frame-root"
        }),
        //
        // 開発用サーバーでHot Module Replacement (モジュール単位で変更を反映)を有効にします。
        //
        new webpack.HotModuleReplacementPlugin(),
        //
        // 開発中に変更されたモジュール名をコンソールに表示します。
        //
        new webpack.NamedModulesPlugin()
    ]
};
<commit_msg>node_modulesをbabelの対象から除外。(@materialを除く。)<commit_after>"use strict";
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
const GoogleFontsWebpackPlugin = require("google-fonts-webpack-plugin");
const HtmlWebpackDisplayLoaderPlugin = require("html-webpack-display-loader-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackPolyfillsPlugin = require("html-webpack-polyfills-plugin");
const webpack = require("webpack");

module.exports = {
    entry: {
        main: "./src"
    },
    output: {
        path: __dirname + "/dist",
        filename: "[name].js"
    },
    module: {
        rules: [{
            //
            // .vue拡張子のファイルは、vue-loaderで読み込みます。
            // <template>タグ、<style>タグ、<script>タグの内容が、HTML、CSS、javascriptとして読み込まれます。
            // lang属性を指定した場合には、対応するloader (sass-loader等) で読み込まれます。
            //
            test: /\.vue$/,
            use: [{
                loader: "vue-loader"
            }]
        }, {
            //
            // .js拡張子のファイルは、babel-loaderで読み込みます。
            // 最新の構文で書かれたスクリプトを、現行のブラウザで解釈できるスクリプトに変換してくれます。
            //
            test: /\.js$/,
            use: [{
                loader: "babel-loader"
            }],
            exclude: /(^|\/)node_modules\/(?!@material\/).*/
        }, {
            //
            // 画像ファイルは、url-loaderで読み込みます。
            // ファイルの内容がエンコードされ、スクリプト内に埋め込まれます。
            // 32kB以上のファイルは、file-loaderで読み込みます。
            // ファイル名はハッシュ文字列に置き換えて配信されます。
            //
            test: /\.(?:ttf|woff2?|eot|png)$/,
            use: [{
                loader: "url-loader",
                options: {
                    limit: 32000,
                    name: "[hash].[ext]"
                }
            }]
        }]
    },
    resolve: {
        alias: {
            //
            // 各モジュールのビルドされたファイルへのエイリアスを設定します。
            // ex.) import vue from "vue" は import vue from "vue/dist/vue.esm" と同じです。
            //
            "vue$": "vue/dist/vue.esm.js"
        }
    },
    node: {
        __filename: true, // 各モジュール内で、そのモジュール自身の相対パスを__filenameで取得できます。
        __dirname: true // 各モジュール内で、そのモジュールを含むディレクトリの相対パスを__dirnameで取得できます。
    },
    devServer: {
        disableHostCheck: true,
        historyApiFallback: true,
        hot: true
    },
    devtool: process.env.NODE_ENV !== "production" && "cheap-module-eval-source-map" && "cheap-module-source-map",
    plugins: [
        //
        // スクリプト内の変数を環境変数で置き換えます。
        // 下記デフォルト値はテスト用のダミー変数です。
        //
        new webpack.EnvironmentPlugin({
            NODE_ENV: "development"
        }),
        //
        // EJSテンプレートからindex.htmlを作成します。
        // サイトにアクセスした時、最初に読み込まれるHTMLファイルになります。
        //
        new HtmlWebpackPlugin({
            title: "Frame | 1stop-st.org"
        }),
        //
        // 画像ファイルからマルチブラウザ対応のfaviconを生成します。
        // 生成されたfaviconへのリンクがindex.htmlに挿入されます。
        //
        new FaviconsWebpackPlugin({
            logo: "./resources/logo.png"
        }),
        //
        // Google Fonts から Webフォントを読み込む<style>タグがindex.htmlに挿入されます。
        //
        new GoogleFontsWebpackPlugin({
            fonts: [{
                family: "Roboto",
                variants: ["300", "400", "500"]
            }],
            local: false
        }),
        //
        // ブラウザに適したPolyfillを読み込む<script>タグがindex.htmlに挿入されます。
        // Polyfill service (https://polyfill.io)
        //
        new HtmlWebpackPolyfillsPlugin(),
        //
        // script読込み中にロード画面を表示するHTMLが挿入されます。
        //
        new HtmlWebpackDisplayLoaderPlugin({
            id: "frame-root"
        }),
        //
        // 開発用サーバーでHot Module Replacement (モジュール単位で変更を反映)を有効にします。
        //
        new webpack.HotModuleReplacementPlugin(),
        //
        // 開発中に変更されたモジュール名をコンソールに表示します。
        //
        new webpack.NamedModulesPlugin()
    ]
};
<|endoftext|>


<commit_before>const path = require('path');
const TSLintPlugin = require('tslint-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    mode : "development",
    entry : {
        "entry":"./app/index.ts"
    },
    output : {
        path : path.resolve(__dirname, 'docs')
    },
    devtool : 'inline-source-map',
    output:{
        filename:"app.js"
    },
    module : {
        rules :[
            {
                test : /\.tsx?$/,
                use : 'ts-loader',
                exclude : /node_modules/
            },
            {
                test : /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test : /\.js$/,
                exclude : /node_modules/,
                loader: "babel-loader",
                options : {
                    presets : [[
                        "env", {
                            targets : {
                                browsers : ["last 2 versions"]
                            }
                        }
                    ]]
                }
            },
        ]
    },
    resolve : {
        extensions : [".tsx", ".ts", ".js"]
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from : './app/**/*',
            }
        ]),
        new TSLintPlugin({
            files : ['./app/**/*.ts'],
        })
    ]
};
<commit_msg>webpack.config.js<commit_after>const path = require('path');
const TSLintPlugin = require('tslint-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    mode : "development",
    entry : {
        "entry":"./app/index.ts"
    },
    output : {
        path : path.resolve(__dirname, 'docs')
    },
    devtool : 'inline-source-map',
    output:{
        filename:"app.js"
    },
    module : {
        rules :[
            {
                test : /\.tsx?$/,
                use : 'ts-loader',
                exclude : /node_modules/
            },
            {
                test : /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test : /\.js$/,
                exclude : /node_modules/,
                loader: "babel-loader",
                options : {
                    presets : [[
                        "env", {
                            targets : {
                                browsers : ["last 2 versions"]
                            }
                        }
                    ]]
                }
            },
        ]
    },
    resolve : {
        extensions : [".tsx", ".ts", ".js"]
    },
    plugins: [
        // new CopyWebpackPlugin([
        //     {
        //         from : './app/**/*',
        //     }
        // ]),
        new TSLintPlugin({
            files : ['./app/**/*.ts'],
        })
    ]
};
<|endoftext|>