<commit_before>var path = require("path");
var webpack = require('webpack');
var fs = require('fs');
var extend = require('util')._extend;
var camelcase = require('camelcase');

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 webpackMultipleConfigs = [];

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

			folders.map((folder) => {
				var toPush = {};

				toPush.context = path.join(
					process.cwd(),
					entry.forEachFolderIn,
					folder
				);

				toPush.entry = entry.entry;

				toPush.output = Object.assign({}, entry.output, {
					path: './' + path.join(
						entry.forEachFolderIn,
						folder,
						entry.output.path
					),
					filename: '[name].js',
					jsonpFunction: camelcase(
						(entry.jsonpPrefix || 'webpack-jsonp-') + folder
					)
				});

				if (fs.existsSync(
					path.join(
						entry.forEachFolderIn,
						folder,
						entry.entry
					)
				)) {
					webpackMultipleConfigs.push(toPush);
				}

			});
		} else {
			var toPush = {};

			toPush['entry'] = entry.entry;
			toPush['output'] = entry.output;

			webpackMultipleConfigs.push(toPush);
		}
	});

	const commonConfig = {
		/*
		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'
			].concat(options.webpackIncludePaths),

			alias: options.webpackResolveAliases
		},

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

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

		externals: Object.assign({
			jquery: 'window.jQuery',
			'_': 'window._'
		}, options.webpackExternals)
	};

	var config = webpackMultipleConfigs.map((singleConfig) => {

		return Object.assign({}, commonConfig, singleConfig);

	});

	return config;
};

<commit_msg>use bower.json for main<commit_after>var path = require("path");
var webpack = require('webpack');
var fs = require('fs');
var extend = require('util')._extend;
var camelcase = require('camelcase');

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 webpackMultipleConfigs = [];

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

			folders.map((folder) => {
				var toPush = {};

				toPush.context = path.join(
					process.cwd(),
					entry.forEachFolderIn,
					folder
				);

				toPush.entry = entry.entry;

				toPush.output = Object.assign({}, entry.output, {
					path: './' + path.join(
						entry.forEachFolderIn,
						folder,
						entry.output.path
					),
					filename: '[name].js',
					jsonpFunction: camelcase(
						(entry.jsonpPrefix || 'webpack-jsonp-') + folder
					)
				});

				if (fs.existsSync(
					path.join(
						entry.forEachFolderIn,
						folder,
						entry.entry
					)
				)) {
					webpackMultipleConfigs.push(toPush);
				}

			});
		} else {
			var toPush = {};

			toPush['entry'] = entry.entry;
			toPush['output'] = entry.output;

			webpackMultipleConfigs.push(toPush);
		}
	});

	const commonConfig = {
		/*
		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'
			].concat(options.webpackIncludePaths),

			alias: options.webpackResolveAliases
		},

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

			new webpack.NoErrorsPlugin(),

			new webpack.ResolverPlugin([
				new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
			], ["normal", "loader"])
		].concat(
			isDevelopment ? [] : new webpack.optimize.UglifyJsPlugin({
				compress: {
					warnings: false
				}
			})
		).concat(
			options.webpackPlugins
		),

		externals: Object.assign({
			jquery: 'window.jQuery',
			'_': 'window._'
		}, options.webpackExternals)
	};

	var config = webpackMultipleConfigs.map((singleConfig) => {

		return Object.assign({}, commonConfig, singleConfig);

	});

	return config;
};

<|endoftext|>


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

module.exports = {
  entry: [
    path.normalize('es6-shim/es6-shim.min'),
    'reflect-metadata',
    'web-animations.min',
    path.normalize('zone.js/dist/zone-microtask'),
    path.resolve('app/app.ts')
  ],
  output: {
    path: path.resolve('www/build/js'),
    filename: 'app.bundle.js',
    pathinfo: false // show module paths in the bundle, handy for debugging
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript',
        query: {
          'doTypeCheck': false
        },
        include: path.resolve('app'),
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        include: path.resolve('node_modules/angular2'),
        loader: 'strip-sourcemap'
      }
    ],
    noParse: [
      /es6-shim/,
      /reflect-metadata/,
      /web-animations/,
      /zone\.js(\/|\\)dist(\/|\\)zone-microtask/
    ]
  },
  resolve: {
    alias: {
      'ionic': 'ionic-framework',
      'web-animations.min': path.normalize('ionic-framework/js/web-animations.min')
    },
    extensions: ['', '.js', '.ts']
  }
};
<commit_msg>chore(): remove unnecessary webpack require from webpack config<commit_after>var path = require('path');

module.exports = {
  entry: [
    path.normalize('es6-shim/es6-shim.min'),
    'reflect-metadata',
    'web-animations.min',
    path.normalize('zone.js/dist/zone-microtask'),
    path.resolve('app/app.ts')
  ],
  output: {
    path: path.resolve('www/build/js'),
    filename: 'app.bundle.js',
    pathinfo: false // show module paths in the bundle, handy for debugging
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript',
        query: {
          'doTypeCheck': false
        },
        include: path.resolve('app'),
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        include: path.resolve('node_modules/angular2'),
        loader: 'strip-sourcemap'
      }
    ],
    noParse: [
      /es6-shim/,
      /reflect-metadata/,
      /web-animations/,
      /zone\.js(\/|\\)dist(\/|\\)zone-microtask/
    ]
  },
  resolve: {
    alias: {
      'ionic': 'ionic-framework',
      'web-animations.min': path.normalize('ionic-framework/js/web-animations.min')
    },
    extensions: ['', '.js', '.ts']
  }
};
<|endoftext|>


<commit_before>const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
//const HtmlWebpackPlugin = require('html-webpack-plugin')
//const webpack = require('webpack')

module.exports = {
    entry: {
        demo: './src/demo/index.js',
        'browser-ui-state': './src/browser-ui-state/index.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            { from: 'index.html' },
            { from: 'src/demo' }
        ], { ignore: ['*.js'] })
        //TBD:
        /*, new HtmlWebpackPlugin({
            template: 'index.html'
        })*/
        //https://stackoverflow.com/questions/45384170/how-to-fix-modules-with-moduleconcatenation-bailout-module-is-not-an-ecmascrip
        //, new webpack.optimize.ModuleConcatenationPlugin()
    ]/*,
    stats: {
        // Examine all modules
        maxModules: Infinity,
        // Display bailout reasons
        optimizationBailout: true
    }*/
}
<commit_msg>Adjusting webpack.config.js to fix incorrect 1.0.2 release (patch)<commit_after>const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
//const HtmlWebpackPlugin = require('html-webpack-plugin')
//const webpack = require('webpack')

module.exports = {
    entry: {
        demo: './src/demo/index.js',
        'browser-ui-state': './src/browser-ui-state/index.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        library: 'BrowserUiState'
    },
    module: {
        rules: [
            { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            { from: 'index.html' },
            { from: 'src/demo' }
        ], { ignore: ['*.js'] })
        //TBD:
        /*, new HtmlWebpackPlugin({
            template: 'index.html'
        })*/
        //https://stackoverflow.com/questions/45384170/how-to-fix-modules-with-moduleconcatenation-bailout-module-is-not-an-ecmascrip
        //, new webpack.optimize.ModuleConcatenationPlugin()
    ]/*,
    stats: {
        // Examine all modules
        maxModules: Infinity,
        // Display bailout reasons
        optimizationBailout: true
    }*/
}
<|endoftext|>


<commit_before>const configBuilder = require('webpack-focus').configBuilder;
const customConfig = {
    externals: {
        react: 'React',
        'react-dom': 'ReactDOM',
        moment: 'moment',
        jquery: 'jQuery',
        backbone: 'Backbone',
        numeral: 'numeral'
    }
};

module.exports = configBuilder(customConfig);
<commit_msg>Fix externals<commit_after>const configBuilder = require('webpack-focus').configBuilder;
const customConfig = {
    externals: {
        react: 'React',
        'react-dom': 'ReactDOM',
        moment: 'moment',
        jquery: 'jQuery',
        numeral: 'numeral'
    }
};

module.exports = configBuilder(customConfig);
<|endoftext|>


<commit_before>/* eslint-env node, es6 */

'use strict';

const
  BASE_NAME = 'plain-draggable',
  OBJECT_NAME = 'PlainDraggable',
  LIMIT_TAGS = ['SNAP', 'SVG', 'LEFTTOP'],
  BUILD_MODE = process.env.NODE_ENV === 'production',
  LIMIT = process.env.EDITION === 'limit',
  BUILD_BASE_NAME = `${BASE_NAME}${LIMIT ? '-limit' : ''}`,
  PREPROC_REMOVE_TAGS = (BUILD_MODE ? ['DEBUG'] : []).concat(LIMIT ? LIMIT_TAGS : []),

  webpack = require('webpack'),
  preProc = require('pre-proc'),
  path = require('path'),
  fs = require('fs'),
  PKG = require('./package'),

  SRC_DIR_PATH = path.resolve(__dirname, 'src'),
  BUILD_DIR_PATH = BUILD_MODE ? __dirname : path.resolve(__dirname, 'test'),
  ESM_DIR_PATH = __dirname,
  ENTRY_PATH = path.join(SRC_DIR_PATH, `${BASE_NAME}.js`);

function writeFile(filePath, content, messageClass) {
  const HL = '='.repeat(48);
  fs.writeFileSync(filePath,
    `/* ${HL}\n        DON'T MANUALLY EDIT THIS FILE\n${HL} */\n\n${content}`);
  console.log(`Output (${messageClass}): ${filePath}`);
}

module.exports = {
  mode: BUILD_MODE ? 'production' : 'development',
  entry: ENTRY_PATH,
  output: {
    path: BUILD_DIR_PATH,
    filename: `${BUILD_BASE_NAME}${BUILD_MODE ? '.min' : ''}.js`,
    library: OBJECT_NAME,
    libraryTarget: 'var',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        resource: {and: [SRC_DIR_PATH, /\.js$/]},
        use: [
          // ================================ Save ESM file
          {
            loader: 'skeleton-loader',
            options: {
              procedure(content) {
                if (this.resourcePath === ENTRY_PATH) {
                  writeFile(
                    path.join(ESM_DIR_PATH, `${BUILD_BASE_NAME}${BUILD_MODE ? '' : '-debug'}.esm.js`),
                    content, 'ESM');
                }
                return content;
              }
            }
          },
          // ================================ Babel
          {
            loader: 'babel-loader',
            options: {presets: [['es2015', {modules: false}]]}
          },
          // ================================ Preprocess
          PREPROC_REMOVE_TAGS.length ? {
            loader: 'skeleton-loader',
            options: {
              procedure(content) {
                content = preProc.removeTag(PREPROC_REMOVE_TAGS, content);
                if (BUILD_MODE && this.resourcePath === ENTRY_PATH) {
                  writeFile(path.join(SRC_DIR_PATH, `${BUILD_BASE_NAME}.proc.js`), content, 'PROC');
                }
                return content;
              }
            }
          } : null
        ].filter(loader => !!loader)
      }
    ]
  },
  devtool: BUILD_MODE ? false : 'source-map',
  plugins: BUILD_MODE ? [
    new webpack.BannerPlugin(
      `${PKG.title || PKG.name} v${PKG.version} (c) ${PKG.author.name} ${PKG.homepage}`)
  ] : []
};
<commit_msg>Update for autoScroll as LIMIT<commit_after>/* eslint-env node, es6 */

'use strict';

const
  BASE_NAME = 'plain-draggable',
  OBJECT_NAME = 'PlainDraggable',
  LIMIT_TAGS = ['SNAP', 'AUTO-SCROLL', 'SVG', 'LEFTTOP'],
  BUILD_MODE = process.env.NODE_ENV === 'production',
  LIMIT = process.env.EDITION === 'limit',
  BUILD_BASE_NAME = `${BASE_NAME}${LIMIT ? '-limit' : ''}`,
  PREPROC_REMOVE_TAGS = (BUILD_MODE ? ['DEBUG'] : []).concat(LIMIT ? LIMIT_TAGS : []),

  webpack = require('webpack'),
  preProc = require('pre-proc'),
  path = require('path'),
  fs = require('fs'),
  PKG = require('./package'),

  SRC_DIR_PATH = path.resolve(__dirname, 'src'),
  BUILD_DIR_PATH = BUILD_MODE ? __dirname : path.resolve(__dirname, 'test'),
  ESM_DIR_PATH = __dirname,
  ENTRY_PATH = path.join(SRC_DIR_PATH, `${BASE_NAME}.js`);

function writeFile(filePath, content, messageClass) {
  const HL = '='.repeat(48);
  fs.writeFileSync(filePath,
    `/* ${HL}\n        DON'T MANUALLY EDIT THIS FILE\n${HL} */\n\n${content}`);
  console.log(`Output (${messageClass}): ${filePath}`);
}

module.exports = {
  mode: BUILD_MODE ? 'production' : 'development',
  entry: ENTRY_PATH,
  output: {
    path: BUILD_DIR_PATH,
    filename: `${BUILD_BASE_NAME}${BUILD_MODE ? '.min' : ''}.js`,
    library: OBJECT_NAME,
    libraryTarget: 'var',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        resource: {and: [SRC_DIR_PATH, /\.js$/]},
        use: [
          // ================================ Save ESM file
          {
            loader: 'skeleton-loader',
            options: {
              procedure(content) {
                if (this.resourcePath === ENTRY_PATH) {
                  writeFile(
                    path.join(ESM_DIR_PATH, `${BUILD_BASE_NAME}${BUILD_MODE ? '' : '-debug'}.esm.js`),
                    content, 'ESM');
                }
                return content;
              }
            }
          },
          // ================================ Babel
          {
            loader: 'babel-loader',
            options: {presets: [['es2015', {modules: false}]]}
          },
          // ================================ Preprocess
          PREPROC_REMOVE_TAGS.length ? {
            loader: 'skeleton-loader',
            options: {
              procedure(content) {
                content = preProc.removeTag(PREPROC_REMOVE_TAGS, content);
                if (BUILD_MODE && this.resourcePath === ENTRY_PATH) {
                  writeFile(path.join(SRC_DIR_PATH, `${BUILD_BASE_NAME}.proc.js`), content, 'PROC');
                }
                return content;
              }
            }
          } : null
        ].filter(loader => !!loader)
      }
    ]
  },
  devtool: BUILD_MODE ? false : 'source-map',
  plugins: BUILD_MODE ? [
    new webpack.BannerPlugin(
      `${PKG.title || PKG.name} v${PKG.version} (c) ${PKG.author.name} ${PKG.homepage}`)
  ] : []
};
<|endoftext|>


<commit_before><commit_msg>Ensures saved schedule data has length > 0<commit_after><|endoftext|>


<commit_before>/*
 * Webpack development server configuration
 *
 * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if
 * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload.
 */
'use strict';
var webpack = require('webpack');

module.exports = {

  output: {
    filename: 'main.js',
    publicPath: '/assets/'
  },

  cache: true,
  debug: true,
  devtool: false,
  entry: [
      'webpack/hot/only-dev-server',
      './src/components/main.js'
  ],

  stats: {
    colors: true,
    reasons: true
  },

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'styles': __dirname + '/src/styles',
      'mixins': __dirname + '/src/mixins',
      'components': __dirname + '/src/components/',
      'stores': __dirname + '/src/stores/',
      'actions': __dirname + '/src/actions/'
    }
  },
  module: {
    preLoaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'jsxhint'
    }],
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'react-hot!babel-loader'
    }, {
      test: /\.less/,
      loader: 'style-loader!css-loader!less-loader'
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192'
    }]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]

};
<commit_msg>code formatting<commit_after>/*
 * Webpack development server configuration
 *
 * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if
 * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload.
 */
'use strict';
var webpack = require('webpack');

module.exports = {

    output: {
        filename: 'main.js',
        publicPath: '/assets/'
    },

    cache: true,
    debug: true,
    devtool: false,
    entry: [
        'webpack/hot/only-dev-server',
        './src/components/main.js'
    ],

    stats: {
        colors: true,
        reasons: true
    },

    resolve: {
        extensions: ['', '.js'],
        alias: {
            'styles': __dirname + '/src/styles',
            'mixins': __dirname + '/src/mixins',
            'components': __dirname + '/src/components/',
            'stores': __dirname + '/src/stores/',
            'actions': __dirname + '/src/actions/'
        }
    },
    module: {
        preLoaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'jsxhint'
        }],
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'react-hot!babel-loader'
        }, {
            test: /\.less/,
            loader: 'style-loader!css-loader!less-loader'
        }, {
            test: /\.css$/,
            loader: 'style-loader!css-loader'
        }, {
            test: /\.(png|jpg)$/,
            loader: 'url-loader?limit=8192'
        }]
    },

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]

};
<|endoftext|>


<commit_before><commit_msg>handle data loading errors<commit_after><|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const md5 = require('md5');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const webpack = require('webpack');

const CACHE_INVALIDATE = getCacheInvalidateString();
const NODE_MODULE_PATH = path.join(__dirname, 'node_modules');
const SETTINGS_PATH = process.env.SETTINGS_PATH || './settings.js';
const THREADS = getThreadLoaderThreads();
// Used to fail CI for PRs which contain linter errors
const ESLINT_FAIL_ON_ERROR = process.env.ESLINT_FAIL_ON_ERROR === 'true';

function configure(env, webpackOpts) {
  const WEBPACK_MODE = (webpackOpts && webpackOpts.mode) || 'development';
  const IS_PRODUCTION = WEBPACK_MODE === 'production';
  const IS_CI = !!process.env.TRAVIS || !!process.env.GITHUB_ACTIONS;
  const DISPLAY_PROGRESS = process.stdout.isTTY && !IS_CI;

  // eslint-disable-next-line no-console
  console.log('Webpack mode: ' + WEBPACK_MODE);

  const plugins = [
    new ESLintPlugin({}),
    new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true }),
    new CopyWebpackPlugin([
      { from: `${NODE_MODULE_PATH}/@spinnaker/styleguide/public/styleguide.html`, to: `./styleguide.html` },
      { from: `./plugin-manifest.json`, to: `./plugin-manifest.json` },
    ]),
    new HtmlWebpackPlugin({
      title: 'Spinnaker',
      template: './app/index.deck',
      favicon: process.env.NODE_ENV === 'production' ? 'app/prod-favicon.ico' : 'app/dev-favicon.ico',
      inject: true,
      hash: IS_PRODUCTION,
    }),
  ];

  if (process.env.NODE_ENV !== 'production') {
    plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  if (DISPLAY_PROGRESS) {
    plugins.push(new webpack.ProgressPlugin({ profile: false }));
  }

  const config = {
    context: __dirname,
    mode: WEBPACK_MODE,
    stats: 'errors-only',
    watch: process.env.WATCH === 'true',
    entry: {
      settings: SETTINGS_PATH,
      'settings-local': './settings-local.js',
      app: './app/scripts/modules/app.ts',
    },
    output: {
      path: path.join(__dirname, 'build', 'webpack', process.env.SPINNAKER_ENV || ''),
      filename: '[name].js',
    },
    devtool: IS_PRODUCTION ? 'source-map' : 'eval',
    optimization: {
      splitChunks: {
        chunks: 'all', // enables splitting of both initial and async chunks
        maxInitialRequests: 20, // allows up to 10 initial chunks
        cacheGroups: {
          // Put code matching each regexp in a separate chunk
          core: new RegExp('/app/scripts/modules/core/'),
          providers: new RegExp('/app/scripts/modules/(?!core)[^/]+/'),
          vendor_A_F: new RegExp('node_modules/[a-fA-F]'),
          vendor_G_O: new RegExp('node_modules/[g-oG-O]'),
          vendor_P_Q: new RegExp('node_modules/[^a-oA-Or-zR-Z]'),
          vendor_R_Z: new RegExp('node_modules/[r-zR-Z]'),
        },
      },
      minimizer: IS_PRODUCTION
        ? [
            new TerserPlugin({
              cache: true,
              parallel: true,
              sourceMap: true,
              terserOptions: {
                ecma: 6,
                mangle: false,
                output: {
                  comments: /webpackIgnore/,
                },
              },
            }),
          ]
        : [], // Disable minification unless production
    },
    resolve: {
      extensions: ['.json', '.ts', '.tsx', '.js', '.jsx', '.css', '.less', '.html'],
      alias: {
        root: __dirname,
        coreImports: path.resolve(
          __dirname,
          'app',
          'scripts',
          'modules',
          'core',
          'src',
          'presentation',
          'less',
          'imports',
          'commonImports.less',
        ),
      },
      plugins: [new TsconfigPathsPlugin({ logLevel: 'info', extensions: ['.ts', '.tsx', '.js', '.jsx'] })],
    },
    module: {
      rules: [
        {
          test: /settings\.js/,
          use: [{ loader: 'envify-loader' }],
        },
        {
          test: /\.js$/,
          use: [
            { loader: 'cache-loader', options: { cacheIdentifier: CACHE_INVALIDATE } },
            { loader: 'thread-loader', options: { workers: THREADS } },
            { loader: 'babel-loader' },
          ],
          exclude: /(node_modules(?!\/clipboard)|settings\.js)/,
        },
        {
          test: /\.tsx?$/,
          use: [
            { loader: 'cache-loader', options: { cacheIdentifier: CACHE_INVALIDATE } },
            { loader: 'thread-loader', options: { workers: THREADS } },
            { loader: 'ts-loader', options: { happyPackMode: true } },
          ],
          exclude: /node_modules/,
        },
        {
          test: /\.less$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'postcss-loader' },
            { loader: 'less-loader' },
          ],
        },
        {
          test: /\.css$/,
          use: [{ loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'postcss-loader' }],
        },
        {
          test: /\.svg$/,
          issuer: {
            test: /\.(tsx?|js)$/,
          },
          use: [{ loader: '@svgr/webpack' }],
          exclude: /node_modules/,
        },
        {
          test: /\.html$/,
          use: [{ loader: 'ngtemplate-loader?relativeTo=' + path.resolve(__dirname) + '/' }, { loader: 'html-loader' }],
        },
        {
          test: /\.(woff|woff2|otf|ttf|eot|png|gif|ico|svg)$/,
          use: [{ loader: 'file-loader', options: { name: '[name].[hash:5].[ext]' } }],
        },
        {
          test: require.resolve('jquery'),
          use: [{ loader: 'expose-loader?$' }, { loader: 'expose-loader?jQuery' }],
        },
        {
          test: /ui-sortable/,
          use: ['imports-loader?$UI=jquery-ui/ui/widgets/sortable'],
        },
        {
          test: /\.js$/,
          enforce: 'pre',
          use: [
            {
              loader: 'source-map-loader',
              options: {
                filterSourceMappingUrl: (url, resourcePath) => {
                  if (IS_PRODUCTION) return true;
                  if (/.*\/node_modules\/(rxjs-compat|graphql-tag)\/.*/.test(resourcePath)) {
                    return false;
                  }
                  return true;
                },
              },
            },
          ],
        },
      ],
    },
    plugins,
    devServer: {
      hot: true,
      disableHostCheck: true,
      port: process.env.DECK_PORT || 9000,
      host: process.env.DECK_HOST || 'localhost',
      https: process.env.DECK_HTTPS === 'true',
      stats: 'errors-only',
    },
    externals: {
      'react/addons': 'react',
      'react/lib/ExecutionEnvironment': 'react',
      'react/lib/ReactContext': 'react',
    },
  };

  if (process.env.DECK_CERT) {
    config.devServer.cert = fs.readFileSync(process.env.DECK_CERT);
    config.devServer.key = fs.readFileSync(process.env.DECK_KEY);
    if (process.env.DECK_CA_CERT) {
      config.devServer.ca = fs.readFileSync(process.env.DECK_CA_CERT);
    }
  }

  return config;
}

// invalidate cache-loader cache when these change
function getCacheInvalidateString() {
  return JSON.stringify({
    YARN_LOCK: md5(fs.readFileSync('yarn.lock')),
    WEBPACK_CONFIG: md5(fs.readFileSync(__filename)),
  });
}

function getThreadLoaderThreads() {
  const cpus = require('os').cpus().length;
  const physicalCpus = require('physical-cpu-count');
  const threads = process.env.THREADS || (physicalCpus > 3 ? 2 : 1);

  // eslint-disable-next-line no-console
  console.log(`INFO: cpus: ${cpus} physical: ${physicalCpus} thread-loader threads: ${threads}`);

  return threads;
}

module.exports = configure;
<commit_msg>fix(webpack): Wire in ESLINT_FAIL_ON_ERROR<commit_after>const fs = require('fs');
const path = require('path');
const md5 = require('md5');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const webpack = require('webpack');

const CACHE_INVALIDATE = getCacheInvalidateString();
const NODE_MODULE_PATH = path.join(__dirname, 'node_modules');
const SETTINGS_PATH = process.env.SETTINGS_PATH || './settings.js';
const THREADS = getThreadLoaderThreads();
// Used to fail CI for PRs which contain linter errors
const ESLINT_FAIL_ON_ERROR = process.env.ESLINT_FAIL_ON_ERROR === 'true';

function configure(env, webpackOpts) {
  const WEBPACK_MODE = (webpackOpts && webpackOpts.mode) || 'development';
  const IS_PRODUCTION = WEBPACK_MODE === 'production';
  const IS_CI = !!process.env.TRAVIS || !!process.env.GITHUB_ACTIONS;
  const DISPLAY_PROGRESS = process.stdout.isTTY && !IS_CI;

  // eslint-disable-next-line no-console
  console.log('Webpack mode: ' + WEBPACK_MODE);

  const plugins = [
    new ESLintPlugin({ failOnError: ESLINT_FAIL_ON_ERROR }),
    new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true }),
    new CopyWebpackPlugin([
      { from: `${NODE_MODULE_PATH}/@spinnaker/styleguide/public/styleguide.html`, to: `./styleguide.html` },
      { from: `./plugin-manifest.json`, to: `./plugin-manifest.json` },
    ]),
    new HtmlWebpackPlugin({
      title: 'Spinnaker',
      template: './app/index.deck',
      favicon: process.env.NODE_ENV === 'production' ? 'app/prod-favicon.ico' : 'app/dev-favicon.ico',
      inject: true,
      hash: IS_PRODUCTION,
    }),
  ];

  if (process.env.NODE_ENV !== 'production') {
    plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  if (DISPLAY_PROGRESS) {
    plugins.push(new webpack.ProgressPlugin({ profile: false }));
  }

  const config = {
    context: __dirname,
    mode: WEBPACK_MODE,
    stats: 'errors-only',
    watch: process.env.WATCH === 'true',
    entry: {
      settings: SETTINGS_PATH,
      'settings-local': './settings-local.js',
      app: './app/scripts/modules/app.ts',
    },
    output: {
      path: path.join(__dirname, 'build', 'webpack', process.env.SPINNAKER_ENV || ''),
      filename: '[name].js',
    },
    devtool: IS_PRODUCTION ? 'source-map' : 'eval',
    optimization: {
      splitChunks: {
        chunks: 'all', // enables splitting of both initial and async chunks
        maxInitialRequests: 20, // allows up to 10 initial chunks
        cacheGroups: {
          // Put code matching each regexp in a separate chunk
          core: new RegExp('/app/scripts/modules/core/'),
          providers: new RegExp('/app/scripts/modules/(?!core)[^/]+/'),
          vendor_A_F: new RegExp('node_modules/[a-fA-F]'),
          vendor_G_O: new RegExp('node_modules/[g-oG-O]'),
          vendor_P_Q: new RegExp('node_modules/[^a-oA-Or-zR-Z]'),
          vendor_R_Z: new RegExp('node_modules/[r-zR-Z]'),
        },
      },
      minimizer: IS_PRODUCTION
        ? [
            new TerserPlugin({
              cache: true,
              parallel: true,
              sourceMap: true,
              terserOptions: {
                ecma: 6,
                mangle: false,
                output: {
                  comments: /webpackIgnore/,
                },
              },
            }),
          ]
        : [], // Disable minification unless production
    },
    resolve: {
      extensions: ['.json', '.ts', '.tsx', '.js', '.jsx', '.css', '.less', '.html'],
      alias: {
        root: __dirname,
        coreImports: path.resolve(
          __dirname,
          'app',
          'scripts',
          'modules',
          'core',
          'src',
          'presentation',
          'less',
          'imports',
          'commonImports.less',
        ),
      },
      plugins: [new TsconfigPathsPlugin({ logLevel: 'info', extensions: ['.ts', '.tsx', '.js', '.jsx'] })],
    },
    module: {
      rules: [
        {
          test: /settings\.js/,
          use: [{ loader: 'envify-loader' }],
        },
        {
          test: /\.js$/,
          use: [
            { loader: 'cache-loader', options: { cacheIdentifier: CACHE_INVALIDATE } },
            { loader: 'thread-loader', options: { workers: THREADS } },
            { loader: 'babel-loader' },
          ],
          exclude: /(node_modules(?!\/clipboard)|settings\.js)/,
        },
        {
          test: /\.tsx?$/,
          use: [
            { loader: 'cache-loader', options: { cacheIdentifier: CACHE_INVALIDATE } },
            { loader: 'thread-loader', options: { workers: THREADS } },
            { loader: 'ts-loader', options: { happyPackMode: true } },
          ],
          exclude: /node_modules/,
        },
        {
          test: /\.less$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'postcss-loader' },
            { loader: 'less-loader' },
          ],
        },
        {
          test: /\.css$/,
          use: [{ loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'postcss-loader' }],
        },
        {
          test: /\.svg$/,
          issuer: {
            test: /\.(tsx?|js)$/,
          },
          use: [{ loader: '@svgr/webpack' }],
          exclude: /node_modules/,
        },
        {
          test: /\.html$/,
          use: [{ loader: 'ngtemplate-loader?relativeTo=' + path.resolve(__dirname) + '/' }, { loader: 'html-loader' }],
        },
        {
          test: /\.(woff|woff2|otf|ttf|eot|png|gif|ico|svg)$/,
          use: [{ loader: 'file-loader', options: { name: '[name].[hash:5].[ext]' } }],
        },
        {
          test: require.resolve('jquery'),
          use: [{ loader: 'expose-loader?$' }, { loader: 'expose-loader?jQuery' }],
        },
        {
          test: /ui-sortable/,
          use: ['imports-loader?$UI=jquery-ui/ui/widgets/sortable'],
        },
        {
          test: /\.js$/,
          enforce: 'pre',
          use: [
            {
              loader: 'source-map-loader',
              options: {
                filterSourceMappingUrl: (url, resourcePath) => {
                  if (IS_PRODUCTION) return true;
                  if (/.*\/node_modules\/(rxjs-compat|graphql-tag)\/.*/.test(resourcePath)) {
                    return false;
                  }
                  return true;
                },
              },
            },
          ],
        },
      ],
    },
    plugins,
    devServer: {
      hot: true,
      disableHostCheck: true,
      port: process.env.DECK_PORT || 9000,
      host: process.env.DECK_HOST || 'localhost',
      https: process.env.DECK_HTTPS === 'true',
      stats: 'errors-only',
    },
    externals: {
      'react/addons': 'react',
      'react/lib/ExecutionEnvironment': 'react',
      'react/lib/ReactContext': 'react',
    },
  };

  if (process.env.DECK_CERT) {
    config.devServer.cert = fs.readFileSync(process.env.DECK_CERT);
    config.devServer.key = fs.readFileSync(process.env.DECK_KEY);
    if (process.env.DECK_CA_CERT) {
      config.devServer.ca = fs.readFileSync(process.env.DECK_CA_CERT);
    }
  }

  return config;
}

// invalidate cache-loader cache when these change
function getCacheInvalidateString() {
  return JSON.stringify({
    YARN_LOCK: md5(fs.readFileSync('yarn.lock')),
    WEBPACK_CONFIG: md5(fs.readFileSync(__filename)),
  });
}

function getThreadLoaderThreads() {
  const cpus = require('os').cpus().length;
  const physicalCpus = require('physical-cpu-count');
  const threads = process.env.THREADS || (physicalCpus > 3 ? 2 : 1);

  // eslint-disable-next-line no-console
  console.log(`INFO: cpus: ${cpus} physical: ${physicalCpus} thread-loader threads: ${threads}`);

  return threads;
}

module.exports = configure;
<|endoftext|>


<commit_before>import Grid from '../grid';

frappe.ui.form.ControlTable = class ControlTable extends frappe.ui.form.Control {
	make() {
		super.make();

		// add title if prev field is not column / section heading or html
		this.grid = new Grid({
			frm: this.frm,
			df: this.df,
			perm: this.perm || (this.frm && this.frm.perm) || this.df.perm,
			parent: this.wrapper,
			control: this
		});

		if (this.frm) {
			this.frm.grids[this.frm.grids.length] = this;
		}

		this.$wrapper.on('paste', ':text', e => {
			const table_field = this.df.fieldname;
			const grid = this.grid;
			const grid_pagination = grid.grid_pagination;
			const grid_rows = grid.grid_rows;
			const doctype = grid.doctype;
			const row_docname = $(e.target).closest('.grid-row').data('name');
			const in_grid_form = $(e.target).closest('.form-in-grid').length;

			let pasted_data = frappe.utils.get_clipboard_data(e);

			if (!pasted_data || in_grid_form) return;

			let data = frappe.utils.csv_to_array(pasted_data, '\t');

			if (data.length === 1 && data[0].length === 1) return;

			let fieldnames = [];
			// for raw data with column header
			if (this.get_field(data[0][0])) {
				data[0].forEach(column => {
					fieldnames.push(this.get_field(column));
				});
				data.shift();
			} else {
				// no column header, map to the existing visible columns
				const visible_columns = grid_rows[0].get_visible_columns();
				let target_column_matched = false;
				visible_columns.forEach(column => {
					// consider all columns after the target column.
					if (target_column_matched || column.fieldname === $(e.target).data('fieldname')) {
						fieldnames.push(column.fieldname);
						target_column_matched = true;
					}
				});
			}

			let row_idx = locals[doctype][row_docname].idx;
			let data_length = data.length;
			data.forEach((row, i) => {
				setTimeout(() => {
					let blank_row = !row.filter(Boolean).length;
					if (!blank_row) {
						if (row_idx > this.frm.doc[table_field].length) {
							this.grid.add_new_row();
						}

						if (row_idx > 1 && (row_idx - 1) % grid_pagination.page_length === 0) {
							grid_pagination.go_to_page(grid_pagination.page_index + 1);
						}

						const row_name = grid_rows[row_idx - 1].doc.name;
						row.forEach((value, data_index) => {
							if (fieldnames[data_index]) {
								frappe.model.set_value(doctype, row_name, fieldnames[data_index], value);
							}
						});
						row_idx++;
						if (data_length >= 10) {
							let progress = i + 1;
							frappe.show_progress(__('Processing'), progress, data_length, null, true);
						}
					}
				}, 0);
			});
			return false; // Prevent the default handler from running.
		});
	}
	get_field(field_name) {
		let fieldname;
		this.grid.meta.fields.some(field => {
			if (frappe.model.no_value_type.includes(field.fieldtype)) {
				return false;
			}

			field_name = field_name.toLowerCase();
			const is_field_matching = field_name => {
				return (
					field.fieldname.toLowerCase() === field_name ||
					(field.label || '').toLowerCase() === field_name
				);
			};

			if (is_field_matching()) {
				fieldname = field.fieldname;
				return true;
			}
		});
		return fieldname;
	}
	refresh_input() {
		this.grid.refresh();
	}
	get_value() {
		if(this.grid) {
			return this.grid.get_data();
		}
	}
	set_input( ) {
		//
	}
	validate() {
		return this.get_value();
	}
	check_all_rows() {
		this.$wrapper.find('.grid-row-check')[0].click();
	}
};
<commit_msg>fix: grid copy from excel with header, field label in user language<commit_after>import Grid from '../grid';

frappe.ui.form.ControlTable = class ControlTable extends frappe.ui.form.Control {
	make() {
		super.make();

		// add title if prev field is not column / section heading or html
		this.grid = new Grid({
			frm: this.frm,
			df: this.df,
			perm: this.perm || (this.frm && this.frm.perm) || this.df.perm,
			parent: this.wrapper,
			control: this
		});

		if (this.frm) {
			this.frm.grids[this.frm.grids.length] = this;
		}

		this.$wrapper.on('paste', ':text', e => {
			const table_field = this.df.fieldname;
			const grid = this.grid;
			const grid_pagination = grid.grid_pagination;
			const grid_rows = grid.grid_rows;
			const doctype = grid.doctype;
			const row_docname = $(e.target).closest('.grid-row').data('name');
			const in_grid_form = $(e.target).closest('.form-in-grid').length;

			let pasted_data = frappe.utils.get_clipboard_data(e);

			if (!pasted_data || in_grid_form) return;

			let data = frappe.utils.csv_to_array(pasted_data, '\t');

			if (data.length === 1 && data[0].length === 1) return;

			let fieldnames = [];
			// for raw data with column header
			if (this.get_field(data[0][0])) {
				data[0].forEach(column => {
					fieldnames.push(this.get_field(column));
				});
				data.shift();
			} else {
				// no column header, map to the existing visible columns
				const visible_columns = grid_rows[0].get_visible_columns();
				let target_column_matched = false;
				visible_columns.forEach(column => {
					// consider all columns after the target column.
					if (target_column_matched || column.fieldname === $(e.target).data('fieldname')) {
						fieldnames.push(column.fieldname);
						target_column_matched = true;
					}
				});
			}

			let row_idx = locals[doctype][row_docname].idx;
			let data_length = data.length;
			data.forEach((row, i) => {
				setTimeout(() => {
					let blank_row = !row.filter(Boolean).length;
					if (!blank_row) {
						if (row_idx > this.frm.doc[table_field].length) {
							this.grid.add_new_row();
						}

						if (row_idx > 1 && (row_idx - 1) % grid_pagination.page_length === 0) {
							grid_pagination.go_to_page(grid_pagination.page_index + 1);
						}

						const row_name = grid_rows[row_idx - 1].doc.name;
						row.forEach((value, data_index) => {
							if (fieldnames[data_index]) {
								frappe.model.set_value(doctype, row_name, fieldnames[data_index], value);
							}
						});
						row_idx++;
						if (data_length >= 10) {
							let progress = i + 1;
							frappe.show_progress(__('Processing'), progress, data_length, null, true);
						}
					}
				}, 0);
			});
			return false; // Prevent the default handler from running.
		});
	}
	get_field(field_name) {
		let fieldname;
		field_name = field_name.toLowerCase();
		this.grid.meta.fields.some(field => {
			if (frappe.model.no_value_type.includes(field.fieldtype)) {
				return false;
			}

			const is_field_matching = () => {
				return (
					field.fieldname.toLowerCase() === field_name ||
					(field.label || '').toLowerCase() === field_name  ||
					(__(field.label) || '').toLowerCase() === field_name
				);
			};

			if (is_field_matching()) {
				fieldname = field.fieldname;
				return true;
			}
		});
		return fieldname;
	}
	refresh_input() {
		this.grid.refresh();
	}
	get_value() {
		if(this.grid) {
			return this.grid.get_data();
		}
	}
	set_input( ) {
		//
	}
	validate() {
		return this.get_value();
	}
	check_all_rows() {
		this.$wrapper.find('.grid-row-check')[0].click();
	}
};
<|endoftext|>


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

module.exports = {
    entry: {
        login: "./src/js/login/app.js",
        room: './src/js/app.js',
        screen: './src/js/screen/app.js',
        whiteboard: './src/js/whiteboard/app.js'
    },
    output: {
        path: './public/js/',
        filename: "[name].bundle.min.js",
        chunkFilename: "[id].chunk.min.js"
    },
    devtool: 'source-map',
    module: {
        loaders: [
            { test: /\.css$/, loader: 'style!css' },
            { test: /codemirror\/mode(?!.*(javascript|markdown)).*/, loader: 'null' }
        ]
    },
    plugins: [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.optimize.CommonsChunkPlugin({
          filename: "commons.min.js",
          name: "commons"
      })
    ]
};
<commit_msg>Disable broken optimisation<commit_after>var webpack = require('webpack');

module.exports = {
    entry: {
        login: "./src/js/login/app.js",
        room: './src/js/app.js',
        screen: './src/js/screen/app.js',
        whiteboard: './src/js/whiteboard/app.js'
    },
    output: {
        path: './public/js/',
        filename: "[name].bundle.min.js",
        chunkFilename: "[id].chunk.min.js"
    },
    devtool: 'source-map',
    module: {
        loaders: [
            { test: /\.css$/, loader: 'style!css' },
            // { test: /codemirror\/mode(?!.*(javascript|markdown)).*/, loader: 'null' }
        ]
    },
    plugins: [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.optimize.CommonsChunkPlugin({
          filename: "commons.min.js",
          name: "commons"
      })
    ]
};
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form.handlers");

frappe.ui.form.on = frappe.ui.form.on_change = function(doctype, fieldname, handler) {
	var add_handler = function(fieldname, handler) {
		if(!frappe.ui.form.handlers[doctype]) {
			frappe.ui.form.handlers[doctype] = {};
		}
		if(!frappe.ui.form.handlers[doctype][fieldname]) {
			frappe.ui.form.handlers[doctype][fieldname] = [];
		}
		frappe.ui.form.handlers[doctype][fieldname].push(handler);

		// add last handler to events so it can be called as
		// frm.events.handler(frm)
		if(cur_frm && cur_frm.doctype===doctype)
			cur_frm.events[fieldname] = handler;
	}

	if (!handler && $.isPlainObject(fieldname)) {
		// a dict of handlers {fieldname: handler, ...}
		for (var key in fieldname) {
			var fn = fieldname[key];
			if (typeof fn === "function") {
				add_handler(key, fn);
			}
		}
	} else {
		add_handler(fieldname, handler);
	}
}

frappe.ui.form.trigger = function(doctype, fieldname, callback) {
	cur_frm.script_manager.trigger(fieldname, doctype, null, callback);
}

frappe.ui.form.ScriptManager = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
	},
	make: function(ControllerClass) {
		this.frm.cscript = $.extend(this.frm.cscript, new ControllerClass({frm: this.frm}));
	},
	trigger: function(event_name, doctype, name, callback) {
		var me = this;
		doctype = doctype || this.frm.doctype;
		name = name || this.frm.docname;
		handlers = this.get_handlers(event_name, doctype, name, callback);
		if(callback) handlers.push(callback);

		return $.when.apply($, $.map(handlers, function(fn) { return fn(); }));
	},
	get_handlers: function(event_name, doctype, name, callback) {
		var handlers = [];
		var me = this;
		if(frappe.ui.form.handlers[doctype] && frappe.ui.form.handlers[doctype][event_name]) {
			$.each(frappe.ui.form.handlers[doctype][event_name], function(i, fn) {
				handlers.push(function() { return fn(me.frm, doctype, name) });
			});
		}
		if(this.frm.cscript[event_name]) {
			handlers.push(function() { return me.frm.cscript[event_name](me.frm.doc, doctype, name); });
		}
		if(this.frm.cscript["custom_" + event_name]) {
			handlers.push(function() { return me.frm.cscript["custom_" + event_name](me.frm.doc, doctype, name); });
		}
		return handlers;
	},
	setup: function() {
		var doctype = this.frm.meta;
		var me = this;

		// js
		var cs = doctype.__js;
		if(cs) {
			var tmp = eval(cs);
		}

		function setup_add_fetch(df) {
			if((df.fieldtype==="Read Only" || df.read_only==1)
				&& df.options && df.options.indexOf(".")!=-1) {
				var parts = df.options.split(".");
				me.frm.add_fetch(parts[0], parts[1], df.fieldname);
			}
		}

		// setup add fetch
		$.each(this.frm.fields, function(i, field) {
			setup_add_fetch(field.df);
			if(field.df.fieldtype==="Table") {
				$.each(frappe.meta.get_docfields(field.df.options, me.frm.docname), function(i, df) {
					setup_add_fetch(df);
				});
			}
		});

		// css
		doctype.__css && frappe.dom.set_style(doctype.__css);

		this.trigger('setup');
	},
	log_error: function(caller, e) {
		show_alert("Error in Client Script.");
		console.group && console.group();
		console.log("----- error in client script -----");
		console.log("method: " + caller);
		console.log(e);
		console.log("error message: " + e.message);
		console.trace && console.trace();
		console.log("----- end of error message -----");
		console.group && console.groupEnd();
	},
	validate_link_and_fetch: function(df, doctype, docname, value, callback) {
		var me = this;

		if(value) {
			var fetch = '';

			if(this.frm && this.frm.fetch_dict[df.fieldname])
				fetch = this.frm.fetch_dict[df.fieldname].columns.join(', ');

			return frappe.call({
				method:'frappe.desk.form.utils.validate_link',
				type: "GET",
				args: {
					'value': value,
					'options': doctype,
					'fetch': fetch
				},
				no_spinner: true,
				callback: function(r) {
					if(r.message=='Ok') {
						if(r.fetch_values)
							me.set_fetch_values(df, docname, r.fetch_values);
						if(callback) callback(r.valid_value);
					} else {
						if(callback) callback("");
					}
				}
			});
		} else if(callback) {
			callback(value);
		}
	},
	set_fetch_values: function(df, docname, fetch_values) {
		var fl = this.frm.fetch_dict[df.fieldname].fields;
		for(var i=0; i < fl.length; i++) {
			frappe.model.set_value(df.parent, docname, fl[i], fetch_values[i], df.fieldtype);
		}
	},
	copy_from_first_row: function(parentfield, current_row, fieldnames) {
		var doclist = this.frm.doc[parentfield];
		if(doclist.length===1 || doclist[0]===current_row) return;

		$.each(fieldnames, function(i, fieldname) {
			current_row[fieldname] = doclist[0][fieldname];
		});
	}
});
<commit_msg>[enhancement] [minor] frappe.ui.form.off will clear standard events<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form.handlers");

frappe.ui.form.get_event_handler_list = function(doctype, fieldname) {
	if(!frappe.ui.form.handlers[doctype]) {
		frappe.ui.form.handlers[doctype] = {};
	}
	if(!frappe.ui.form.handlers[doctype][fieldname]) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}
	return frappe.ui.form.handlers[doctype][fieldname];
}

frappe.ui.form.on = frappe.ui.form.on_change = function(doctype, fieldname, handler) {
	var add_handler = function(fieldname, handler) {
		var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
		handler_list.push(handler);

		// add last handler to events so it can be called as
		// frm.events.handler(frm)
		if(cur_frm && cur_frm.doctype===doctype) {
			cur_frm.events[fieldname] = handler;
		}
	}

	if (!handler && $.isPlainObject(fieldname)) {
		// a dict of handlers {fieldname: handler, ...}
		for (var key in fieldname) {
			var fn = fieldname[key];
			if (typeof fn === "function") {
				add_handler(key, fn);
			}
		}
	} else {
		add_handler(fieldname, handler);
	}
}

// remove standard event handlers
frappe.ui.form.off = function(doctype, fieldname, handler) {
	var handler_list = frappe.ui.form.get_event_handler_list(doctype, fieldname);
	if(handler_list.length) {
		frappe.ui.form.handlers[doctype][fieldname] = [];
	}

	if(cur_frm && cur_frm.doctype===doctype && cur_frm.events[fieldname]) {
		delete cur_frm.events[fieldname];
	}

	if(cur_frm && cur_frm.cscript && cur_frm.cscript[fieldname]) {
		delete cur_frm.cscript[fieldname];
	}
}

frappe.ui.form.trigger = function(doctype, fieldname, callback) {
	cur_frm.script_manager.trigger(fieldname, doctype, null, callback);
}

frappe.ui.form.ScriptManager = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
	},
	make: function(ControllerClass) {
		this.frm.cscript = $.extend(this.frm.cscript, new ControllerClass({frm: this.frm}));
	},
	trigger: function(event_name, doctype, name, callback) {
		var me = this;
		doctype = doctype || this.frm.doctype;
		name = name || this.frm.docname;
		handlers = this.get_handlers(event_name, doctype, name, callback);
		if(callback) handlers.push(callback);

		return $.when.apply($, $.map(handlers, function(fn) { return fn(); }));
	},
	get_handlers: function(event_name, doctype, name, callback) {
		var handlers = [];
		var me = this;
		if(frappe.ui.form.handlers[doctype] && frappe.ui.form.handlers[doctype][event_name]) {
			$.each(frappe.ui.form.handlers[doctype][event_name], function(i, fn) {
				handlers.push(function() { return fn(me.frm, doctype, name) });
			});
		}
		if(this.frm.cscript[event_name]) {
			handlers.push(function() { return me.frm.cscript[event_name](me.frm.doc, doctype, name); });
		}
		if(this.frm.cscript["custom_" + event_name]) {
			handlers.push(function() { return me.frm.cscript["custom_" + event_name](me.frm.doc, doctype, name); });
		}
		return handlers;
	},
	setup: function() {
		var doctype = this.frm.meta;
		var me = this;

		// js
		var cs = doctype.__js;
		if(cs) {
			var tmp = eval(cs);
		}

		function setup_add_fetch(df) {
			if((df.fieldtype==="Read Only" || df.read_only==1)
				&& df.options && df.options.indexOf(".")!=-1) {
				var parts = df.options.split(".");
				me.frm.add_fetch(parts[0], parts[1], df.fieldname);
			}
		}

		// setup add fetch
		$.each(this.frm.fields, function(i, field) {
			setup_add_fetch(field.df);
			if(field.df.fieldtype==="Table") {
				$.each(frappe.meta.get_docfields(field.df.options, me.frm.docname), function(i, df) {
					setup_add_fetch(df);
				});
			}
		});

		// css
		doctype.__css && frappe.dom.set_style(doctype.__css);

		this.trigger('setup');
	},
	log_error: function(caller, e) {
		show_alert("Error in Client Script.");
		console.group && console.group();
		console.log("----- error in client script -----");
		console.log("method: " + caller);
		console.log(e);
		console.log("error message: " + e.message);
		console.trace && console.trace();
		console.log("----- end of error message -----");
		console.group && console.groupEnd();
	},
	validate_link_and_fetch: function(df, doctype, docname, value, callback) {
		var me = this;

		if(value) {
			var fetch = '';

			if(this.frm && this.frm.fetch_dict[df.fieldname])
				fetch = this.frm.fetch_dict[df.fieldname].columns.join(', ');

			return frappe.call({
				method:'frappe.desk.form.utils.validate_link',
				type: "GET",
				args: {
					'value': value,
					'options': doctype,
					'fetch': fetch
				},
				no_spinner: true,
				callback: function(r) {
					if(r.message=='Ok') {
						if(r.fetch_values)
							me.set_fetch_values(df, docname, r.fetch_values);
						if(callback) callback(r.valid_value);
					} else {
						if(callback) callback("");
					}
				}
			});
		} else if(callback) {
			callback(value);
		}
	},
	set_fetch_values: function(df, docname, fetch_values) {
		var fl = this.frm.fetch_dict[df.fieldname].fields;
		for(var i=0; i < fl.length; i++) {
			frappe.model.set_value(df.parent, docname, fl[i], fetch_values[i], df.fieldtype);
		}
	},
	copy_from_first_row: function(parentfield, current_row, fieldnames) {
		var doclist = this.frm.doc[parentfield];
		if(doclist.length===1 || doclist[0]===current_row) return;

		$.each(fieldnames, function(i, fieldname) {
			current_row[fieldname] = doclist[0][fieldname];
		});
	}
});
<|endoftext|>


<commit_before>var id_base = 40000;
var weathers = {
         "flags":{
           "ignore_rainy": "ignore_rainy",
           "ignore_windy": "ignore_windy",
           "rainy_buff":"rainy_buff",
           "windy_buff":"windy_buff",
           "ignore_sunny":"ignore_sunny",
           "sunny_buff":"sunny_buff"
         },
         "rainy": [
                                {"id": id_base+1,
                                "effect_name": "Muddy",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_rainy],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 90},
                                {"id": id_base+2,
                                "effect_name": "Falling Spring",
                                "effect_on_filter": [weathers.flags.rainy_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"mana",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 10,
                                "effect_percent": 100}
         ],
         "windy": [
                                {"id": id_base+3,
                                "effect_name": "Windy and Dusty",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_windy],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 90},
                                {"id": id_base+4,
                                "effect_name": "Dancing in Wind",
                                "effect_on_filter": [weathers.flags.windy_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 120}

         ],
         "sunny": [
                                {"id": id_base+5,
                                "effect_name": "Sunnyday",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_sunny],
                                "the_attribute_name":"staying",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 80},
                                {"id": id_base+6,
                                "effect_name": "Dancing in Wind",
                                "effect_on_filter": [weathers.flags.sunny_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"stength",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 105}

         ],
    };

module.exports.weathers = weathers;<commit_msg>add weathers<commit_after>var id_base = 40000;
var weathers = {
         "flags":{
           "ignore_rainy": "ignore_rainy",
           "ignore_windy": "ignore_windy",
           "rainy_buff":"rainy_buff",
           "windy_buff":"windy_buff",
           "ignore_sunny":"ignore_sunny",
           "sunny_buff":"sunny_buff"
         },
         "rainy": [
                                {"id": id_base+1,
                                "effect_name": "Muddy",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_rainy],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 90},
                                {"id": id_base+2,
                                "effect_name": "Falling Spring",
                                "effect_on_filter": [weathers.flags.rainy_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"mana",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 10,
                                "effect_percent": 100}
         ],
         "windy": [
                                {"id": id_base+3,
                                "effect_name": "Windy and Dusty",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_windy],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 90},
                                {"id": id_base+4,
                                "effect_name": "Dancing in Wind",
                                "effect_on_filter": [weathers.flags.windy_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"speed",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 120}

         ],
         "sunny": [
                                {"id": id_base+5,
                                "effect_name": "Firing",
                                "effect_on_filter": [],
                                "effect_off_filter":[weathers.flags.ignore_sunny],
                                "the_attribute_name":"staying",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 80},
                                {"id": id_base+6,
                                "effect_name": "Sunny Day",
                                "effect_on_filter": [weathers.flags.sunny_buff],
                                "effect_off_filter":[],
                                "the_attribute_name":"stength",
                                "effect_level": 0,
                                "effect_type": "the_weather",
                                "effect_value": 0,
                                "effect_percent": 105}

         ],
    };

module.exports.weathers = weathers;<|endoftext|>


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

/**
 * Convenience subtype of Property that constrains values to be true or false.
 * Truthy/falsy values are considered invalid.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var axon = require( 'AXON/axon' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );

  // phet-io modules
  var TBoolean = require( 'ifphetio!PHET_IO/types/TBoolean' );

  /**
   * @param {boolean} value - initial value
   * @param {Object} [options]
   * @constructor
   */
  function BooleanProperty( value, options ) {

    options = _.extend( {
      phetioType: TBoolean
    } );

    assert && assert( !options.isValidValue, 'isValidValue is provided by BooleanProperty' );
    options.isValidValue = isBoolean;

    assert && assert( !options.validValues, 'validValues is not supported by BooleanProperty' );

    Property.call( this, value, options );
  }

  axon.register( 'BooleanProperty', BooleanProperty );

  /**
   * @param {*} value
   * @returns {boolean}
   */
  function isBoolean( value ) {
    return ( typeof value === 'boolean' );
  }

  return inherit( Property, BooleanProperty );
} );<commit_msg>Fixed options for BooleanProperty, see https://github.com/phetsims/beers-law-lab/issues/218<commit_after>// Copyright 2016-2017, University of Colorado Boulder

/**
 * Convenience subtype of Property that constrains values to be true or false.
 * Truthy/falsy values are considered invalid.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var axon = require( 'AXON/axon' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );
  var TProperty = require( 'AXON/TProperty' );

  // phet-io modules
  var TBoolean = require( 'ifphetio!PHET_IO/types/TBoolean' );

  /**
   * @param {boolean} value - initial value
   * @param {Object} [options]
   * @constructor
   */
  function BooleanProperty( value, options ) {

    options = _.extend( {
      phetioType: TProperty( TBoolean )
    }, options );

    assert && assert( !options.isValidValue, 'isValidValue is provided by BooleanProperty' );
    options.isValidValue = isBoolean;

    assert && assert( !options.validValues, 'validValues is not supported by BooleanProperty' );

    Property.call( this, value, options );
  }

  axon.register( 'BooleanProperty', BooleanProperty );

  /**
   * @param {*} value
   * @returns {boolean}
   */
  function isBoolean( value ) {
    return ( typeof value === 'boolean' );
  }

  return inherit( Property, BooleanProperty );
} );<|endoftext|>


<commit_before>// ==UserScript==
// @name        Inbox by Gmail Title Updater
// @version     0.1.3
// @namespace   elesel/userscripts
// @decription  Updates page title to tell the browser when a new/snoozed email or chat arrives
// @include     https://inbox.google.com/*
// @license     MIT License; http://www.opensource.org/licenses/mit-license.php
// @run-at      document-start
// @grant       none
// @icon        https://ssl.gstatic.com/bt/C3341AA7A1A076756462EE2E5CD71C11/ic_product_inbox_16dp_r2_2x.png
// @updateURL   https://github.com/elesel/userscripts/raw/master/Inbox_by_Gmail_Title_Updater.user.js
// @downloadURL https://github.com/elesel/userscripts/raw/master/Inbox_by_Gmail_Title_Updater.user.js
// ==/UserScript==

"use strict";

var timeoutWaiting = false;

// Mutation handling
var MutationObserver = window.MutationObserver;
var myObserver = new MutationObserver(mutationHandler);
var obsConfig = {
  childList: true,
  attributes: true,
  subtree: true,
  attributeFilter: [
    'class'
  ]
};
myObserver.observe(document, obsConfig);

function mutationHandler(mutationRecords) {
  if (! timeoutWaiting) {
    window.setTimeout(updateTitle, 5000);
    timeoutWaiting = true;
  }
}

function updateTitle() {
  // Get unread email count
  var elements = document.getElementsByClassName("G3");
  var unreadCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV' && checkForText(element, 'Unread')) {
      unreadCount++;
    }
  }

  // Get total email count
  var elements = document.getElementsByClassName("top-level-item");
  var totalCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV') {
      totalCount++;
    }
  }

  // Get chat count
  var elements = document.getElementsByClassName("ez");
  var chatCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV' && (! checkForClass(element, 'k6')) && element.clientWidth > 1) {
      chatCount++;
    }
  }

  // Update title if changed
  var currentTitle = document.title;
  console.log('unreadCount =', unreadCount, ' chatCount =', chatCount, ' currentTitle =', currentTitle);
  if (currentTitle.match(/^Inbox/)) {
    var newTitle = currentTitle.replace(
      /^(Inbox)[^–]+/, '$1 ' +
      ((unreadCount || totalCount) ? '(' + unreadCount + '/' + totalCount + ') ' : '') +
      (chatCount ? '(' + chatCount + ' chat) ' : '')
    );
    if (newTitle != currentTitle) {
      console.log('newTitle =', newTitle);
      document.title = newTitle;
    }
  }

  timeoutWaiting = false;
}

function checkForClass(node, className) {
  return (
    node.nodeType === 1 &&
    node.classList.contains(className)
  );
}

function checkForText(node, text) {
  return (
    node.nodeType === 1 &&
    node.hasChildNodes() &&
    node.firstChild.nodeType === 3 &&
    node.firstChild.nodeValue.indexOf(text) > -1
  );
}
<commit_msg>Remove run-at to improve page load time<commit_after>// ==UserScript==
// @name        Inbox by Gmail Title Updater
// @version     0.1.4
// @namespace   elesel/userscripts
// @decription  Updates page title to tell the browser when a new/snoozed email or chat arrives
// @include     https://inbox.google.com/*
// @license     MIT License; http://www.opensource.org/licenses/mit-license.php
// @grant       none
// @icon        https://ssl.gstatic.com/bt/C3341AA7A1A076756462EE2E5CD71C11/ic_product_inbox_16dp_r2_2x.png
// @updateURL   https://github.com/elesel/userscripts/raw/master/Inbox_by_Gmail_Title_Updater.user.js
// @downloadURL https://github.com/elesel/userscripts/raw/master/Inbox_by_Gmail_Title_Updater.user.js
// ==/UserScript==

"use strict";

var timeoutWaiting = false;

// Mutation handling
var MutationObserver = window.MutationObserver;
var myObserver = new MutationObserver(mutationHandler);
var obsConfig = {
  childList: true,
  attributes: true,
  subtree: true,
  attributeFilter: [
    'class'
  ]
};
myObserver.observe(document, obsConfig);

function mutationHandler(mutationRecords) {
  if (! timeoutWaiting) {
    window.setTimeout(updateTitle, 5000);
    timeoutWaiting = true;
  }
}

function updateTitle() {
  // Get unread email count
  var elements = document.getElementsByClassName("G3");
  var unreadCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV' && checkForText(element, 'Unread')) {
      unreadCount++;
    }
  }

  // Get total email count
  var elements = document.getElementsByClassName("top-level-item");
  var totalCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV') {
      totalCount++;
    }
  }

  // Get chat count
  var elements = document.getElementsByClassName("ez");
  var chatCount = 0;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.tagName === 'DIV' && (! checkForClass(element, 'k6')) && element.clientWidth > 1) {
      chatCount++;
    }
  }

  // Update title if changed
  var currentTitle = document.title;
  console.log('unreadCount =', unreadCount, ' chatCount =', chatCount, ' currentTitle =', currentTitle);
  if (currentTitle.match(/^Inbox/)) {
    var newTitle = currentTitle.replace(
      /^(Inbox)[^–]+/, '$1 ' +
      ((unreadCount || totalCount) ? '(' + unreadCount + '/' + totalCount + ') ' : '') +
      (chatCount ? '(' + chatCount + ' chat) ' : '')
    );
    if (newTitle != currentTitle) {
      console.log('newTitle =', newTitle);
      document.title = newTitle;
    }
  }

  timeoutWaiting = false;
}

function checkForClass(node, className) {
  return (
    node.nodeType === 1 &&
    node.classList.contains(className)
  );
}

function checkForText(node, text) {
  return (
    node.nodeType === 1 &&
    node.hasChildNodes() &&
    node.firstChild.nodeType === 3 &&
    node.firstChild.nodeValue.indexOf(text) > -1
  );
}
<|endoftext|>


<commit_before><commit_msg>Add new displayErrorMessage method<commit_after><|endoftext|>


<commit_before>var Webpack           = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpack       = require('html-webpack-plugin');
var WebpackError      = require('webpack-error-notification');

var environment = (process.env.APP_ENV || 'development');
var config      = {
    entry   : ['./application/bootstrap.js'],
    plugins : [
        new ExtractTextPlugin('app.css', {allChunks : true}),
        new HtmlWebpack({template : './application/index.html'}),
        new Webpack.DefinePlugin({
            __BACKEND__     : process.env.BACKEND,
            __ENVIRONMENT__ : '\''+environment+'\''
        })
    ],
    reactLoaders : ['jsx?insertPragma=React.DOM'],
    sassOptions  : (
        '?outputStyle=' + (environment === 'production' ? 'compressed' : 'nested') +
        '&includePaths[]=' + __dirname + '/node_modules'
    )
};

if (environment === 'development') {
    config.entry = [
        'webpack/hot/dev-server',
        'webpack-dev-server/client?http://localhost:9000'
    ].concat(config.entry);

    config.reactLoaders = ['react-hot'].concat(config.reactLoaders);

    config.plugins = config.plugins.concat([
        new Webpack.HotModuleReplacementPlugin(),
        new WebpackError(process.platform)
    ]);
}

module.exports = {
    name   : 'browser bundle',
    entry  : config.entry,
    output : {
        filename : 'app.js',
        path     : __dirname + '/build'
    },
    module : {
        preLoaders : [
            {
                test    : /\.js?/,
                loader  : 'jshint-loader',
                exclude : __dirname + '/node_modules'
            },
            {
                test    : /\.jsx?/,
                loader  : 'jsxhint-loader',
                exclude : __dirname + '/node_modules'
            }
        ],
        loaders : [
            {
                test   : /\.(ico|jpg|png)$/,
                loader : 'file-loader',
                query  : {name : '[path][name].[ext]?[hash]'}
            },
            {
                test    : /\.(js|jsx)$/,
                loaders : config.reactLoaders,
                exclude : /node_modules/
            },
            {
                test   : /\.json$/,
                loader : 'json-loader'
            },
            {
                test   : /\.scss$/,
                loader : ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader!sass-loader' + config.sassOptions
                )
            }
        ]
    },
    plugins : config.plugins,
    resolve : {
        extensions : ['', '.css', '.js', '.json', '.jsx', '.scss', '.webpack.js', '.web.js']
    },
    devtool : '#inline-source-map',
};
<commit_msg>#69 | Only runing js files through jsx loader<commit_after>var Webpack           = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpack       = require('html-webpack-plugin');
var WebpackError      = require('webpack-error-notification');

var environment = (process.env.APP_ENV || 'development');
var config      = {
    entry   : ['./application/bootstrap.js'],
    plugins : [
        new ExtractTextPlugin('app.css', {allChunks : true}),
        new HtmlWebpack({template : './application/index.html'}),
        new Webpack.DefinePlugin({
            __BACKEND__     : process.env.BACKEND,
            __ENVIRONMENT__ : '\''+environment+'\''
        })
    ],
    reactLoaders : ['jsx?insertPragma=React.DOM'],
    sassOptions  : (
        '?outputStyle=' + (environment === 'production' ? 'compressed' : 'nested') +
        '&includePaths[]=' + __dirname + '/node_modules'
    )
};

if (environment === 'development') {
    config.entry = [
        'webpack/hot/dev-server',
        'webpack-dev-server/client?http://localhost:9000'
    ].concat(config.entry);

    config.reactLoaders = ['react-hot'].concat(config.reactLoaders);

    config.plugins = config.plugins.concat([
        new Webpack.HotModuleReplacementPlugin(),
        new WebpackError(process.platform)
    ]);
}

module.exports = {
    name   : 'browser bundle',
    entry  : config.entry,
    output : {
        filename : 'app.js',
        path     : __dirname + '/build'
    },
    module : {
        preLoaders : [
            {
                test    : /\.js?/,
                loader  : 'jshint-loader',
                exclude : __dirname + '/node_modules'
            },
            {
                test    : /\.jsx?/,
                loader  : 'jsxhint-loader',
                exclude : __dirname + '/node_modules'
            }
        ],
        loaders : [
            {
                test   : /\.(ico|jpg|png)$/,
                loader : 'file-loader',
                query  : {name : '[path][name].[ext]?[hash]'}
            },
            {
                test    : /\.jsx$/,
                loaders : config.reactLoaders,
                exclude : __dirname + '/node_modules'
            },
            {
                test   : /\.json$/,
                loader : 'json-loader'
            },
            {
                test   : /\.scss$/,
                loader : ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader!sass-loader' + config.sassOptions
                )
            }
        ]
    },
    plugins : config.plugins,
    resolve : {
        extensions : ['', '.css', '.js', '.json', '.jsx', '.scss', '.webpack.js', '.web.js']
    },
    devtool : '#inline-source-map',
};
<|endoftext|>


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

/**
 * The lovechild of a ComboBox and a NumberDisplay. Allows the user to choose one of N dynamic numeric values.
 * ComboBox was designed to display static choices, so this component ensures that none of its items grow wider/taller
 * than their initial size.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const ComboBox = require( 'SUN/ComboBox' );
  const ComboBoxItem = require( 'SUN/ComboBoxItem' );
  const NumberDisplay = require( 'SCENERY_PHET/NumberDisplay' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  const StringUtils = require( 'PHETCOMMON/util/StringUtils' );

  // constants
  const comboBoxDisplayValueUnitsString = require( 'string!SCENERY_PHET/comboBoxDisplay.valueUnits' );

  class ComboBoxDisplay extends ComboBox {

    /**
     * @param {Object[]} items - describes items in the ComboBox, each Object has these fields:
     *   {*} choice - a value of choiceProperty that corresponds to the item
     *   {NumberProperty} numberProperty - the value of the item
     *   {Range} [range] - the range of the item's value, required if numberProperty.range is null
     *   {string} units - the units used to label the item's value
     *   {Object} [numberDisplayOptions] - options passed to this item's NumberDisplay
     * @param {Property} choiceProperty - determines which item is currently selected
     * @param {Node} listParent - parent for the ComboBox list
     * @param {Object} [options]
     */
    constructor( items, choiceProperty, listParent, options ) {

      options = _.extend( {

        numberDisplayOptions: null, // {*|null} propagated to all NumberDisplay subcomponents

        // ComboBox options
        itemHighlightFill: 'rgba( 255, 0, 0, 0.1 )',
        align: 'right',
        buttonXMargin: 5,
        buttonYMargin: 2,
        buttonCornerRadius: 5,
        itemXMargin: 2,
        itemYMargin: 2,
        buttonLineWidth: 0.4

      }, options );

      // defaults for NumberDisplay
      options.numberDisplayOptions = _.extend( {
        backgroundFill: null,
        backgroundStroke: null,
        font: new PhetFont( 14 ),
        align: 'right',
        xMargin: 0,
        yMargin: 0
      }, options.numberDisplayOptions );

      assert && assert( !options.numberDisplayOptions.valuePattern,
        'ComboBoxDisplay sets numberDisplayOptions.valuePattern' );

      // Convert ComboBoxDisplay items to ComboBox items
      const comboBoxItems = [];
      items.forEach( item => {

        assert && assert( item.choice, 'missing item.choice' );
        assert && assert( item.numberProperty, 'missing item.numberProperty' );
        assert && assert( item.range || item.numberProperty.range, 'range or numberProperty.range must be provided' );
        assert && assert( item.units, 'missing item.units' );
        assert && assert( !item.numberDisplayOptions || !item.numberDisplayOptions.valuePattern,
          'ComboBoxDisplay sets item.numberDisplayOptions.valuePattern' );

        const itemNode = new NumberDisplay( item.numberProperty, item.range || item.numberProperty.range,
          _.extend( {}, options.numberDisplayOptions, item.numberDisplayOptions, {
            valuePattern: StringUtils.fillIn( comboBoxDisplayValueUnitsString, { units: item.units } )
          } ) );

        // Don't allow the NumberDisplay to grow, since it's in a ComboBox
        itemNode.maxWidth = itemNode.width;
        itemNode.maxHeight = itemNode.height;

        comboBoxItems.push( new ComboBoxItem( itemNode, item.choice ) );
      } );

      super( comboBoxItems, choiceProperty, listParent, options );
    }
  }

  return sceneryPhet.register( 'ComboBoxDisplay', ComboBoxDisplay );
} );<commit_msg>big ComboBox refactors, https://github.com/phetsims/sun/issues/430, https://github.com/phetsims/sun/issues/428, https://github.com/phetsims/sun/issues/419<commit_after>// Copyright 2019, University of Colorado Boulder

/**
 * The lovechild of a ComboBox and a NumberDisplay. Allows the user to choose one of N dynamic numeric values.
 * ComboBox was designed to display static choices, so this component ensures that none of its items grow wider/taller
 * than their initial size.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const ComboBox = require( 'SUN/ComboBox' );
  const ComboBoxItem = require( 'SUN/ComboBoxItem' );
  const NumberDisplay = require( 'SCENERY_PHET/NumberDisplay' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  const StringUtils = require( 'PHETCOMMON/util/StringUtils' );

  // constants
  const comboBoxDisplayValueUnitsString = require( 'string!SCENERY_PHET/comboBoxDisplay.valueUnits' );

  class ComboBoxDisplay extends ComboBox {

    /**
     * @param {Object[]} items - describes items in the ComboBox, each Object has these fields:
     *   {*} choice - a value of choiceProperty that corresponds to the item
     *   {NumberProperty} numberProperty - the value of the item
     *   {Range} [range] - the range of the item's value, required if numberProperty.range is null
     *   {string} units - the units used to label the item's value
     *   {Object} [numberDisplayOptions] - options passed to this item's NumberDisplay
     * @param {Property} choiceProperty - determines which item is currently selected
     * @param {Node} listParent - parent for the ComboBox list
     * @param {Object} [options]
     */
    constructor( items, choiceProperty, listParent, options ) {

      options = _.extend( {

        numberDisplayOptions: null, // {*|null} propagated to all NumberDisplay subcomponents

        // ComboBox options
        highlightFill: 'rgba( 255, 0, 0, 0.1 )',
        align: 'right',
        cornerRadius: 5,
        buttonLineWidth: 0.4

      }, options );

      // defaults for NumberDisplay
      options.numberDisplayOptions = _.extend( {
        backgroundFill: null,
        backgroundStroke: null,
        font: new PhetFont( 14 ),
        align: 'right',
        xMargin: 0,
        yMargin: 0
      }, options.numberDisplayOptions );

      assert && assert( !options.numberDisplayOptions.valuePattern,
        'ComboBoxDisplay sets numberDisplayOptions.valuePattern' );

      // Convert ComboBoxDisplay items to ComboBox items
      const comboBoxItems = [];
      items.forEach( item => {

        assert && assert( item.choice, 'missing item.choice' );
        assert && assert( item.numberProperty, 'missing item.numberProperty' );
        assert && assert( item.range || item.numberProperty.range, 'range or numberProperty.range must be provided' );
        assert && assert( item.units, 'missing item.units' );
        assert && assert( !item.numberDisplayOptions || !item.numberDisplayOptions.valuePattern,
          'ComboBoxDisplay sets item.numberDisplayOptions.valuePattern' );

        const itemNode = new NumberDisplay( item.numberProperty, item.range || item.numberProperty.range,
          _.extend( {}, options.numberDisplayOptions, item.numberDisplayOptions, {
            valuePattern: StringUtils.fillIn( comboBoxDisplayValueUnitsString, { units: item.units } )
          } ) );

        // Don't allow the NumberDisplay to grow, since it's in a ComboBox
        itemNode.maxWidth = itemNode.width;
        itemNode.maxHeight = itemNode.height;

        comboBoxItems.push( new ComboBoxItem( itemNode, item.choice ) );
      } );

      super( comboBoxItems, choiceProperty, listParent, options );
    }
  }

  return sceneryPhet.register( 'ComboBoxDisplay', ComboBoxDisplay );
} );<|endoftext|>


<commit_before><commit_msg>Updated microblog.js to the new XEP.<commit_after><|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IS_DEV = process.env.NODE_ENV === 'development';

const regularJSOptions = {
  babelrc: false,
  presets: [['env', { modules: false }], 'stage-2'],
  plugins: ['yo-yoify']
};

module.exports = {
  entry: {
    vendor: ['babel-polyfill', 'fluent'],
    app: ['./app/main.js'],
    style: ['./app/main.css']
  },
  output: {
    filename: '[name].[chunkhash:8].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devtool: IS_DEV && 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        oneOf: [
          {
            include: require.resolve('./assets/cryptofill'),
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[hash:8].[ext]'
                }
              }
            ]
          },
          {
            include: require.resolve('./app/templates/header'),
            use: [
              {
                loader: 'babel-loader',
                options: regularJSOptions
              },
              './build/version_loader'
            ]
          },
          {
            include: [path.dirname(require.resolve('fluent'))],
            use: [
              {
                loader: 'expose-loader',
                options: 'fluent'
              },
              {
                loader: 'babel-loader',
                options: {
                  presets: [['env', { modules: false }]]
                }
              }
            ]
          },
          {
            loader: 'babel-loader',
            include: [
              path.resolve(__dirname, 'app'),
              path.resolve(__dirname, 'common'),
              path.resolve(__dirname, 'node_modules/testpilot-ga/src'),
              path.resolve(__dirname, 'node_modules/fluent-intl-polyfill'),
              path.resolve(__dirname, 'node_modules/intl-pluralrules')
            ],
            options: regularJSOptions
          },
          {
            include: [path.resolve(__dirname, 'node_modules')],
            loader: 'webpack-unassert-loader'
          }
        ]
      },
      {
        test: /\.(svg|png|jpg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[hash:8].[ext]'
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: { modules: false, importLoaders: 1 }
            },
            'postcss-loader'
          ]
        })
      },
      {
        test: require.resolve('./package.json'),
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'version.json'
            }
          },
          'extract-loader',
          './build/package_json_loader'
        ]
      },
      {
        test: /\.ftl$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[hash:8].js'
            }
          },
          'extract-loader',
          './build/fluent_loader'
        ]
      },
      {
        test: require.resolve('./build/generate_asset_map.js'),
        use: ['babel-loader', 'val-loader']
      },
      {
        test: require.resolve('./build/generate_l10n_map.js'),
        use: ['babel-loader', 'val-loader']
      }
    ]
  },
  plugins: [
    new CopyPlugin([
      {
        context: 'public',
        from: '*.*'
      }
    ]),
    new webpack.IgnorePlugin(/dist/),
    new webpack.IgnorePlugin(/require-from-string/),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: ({ resource }) => /node_modules/.test(resource)
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'runtime'
    }),
    new ExtractTextPlugin('style.[chunkhash:8].css'),
    new ManifestPlugin()
  ],
  devServer: {
    compress: true,
    before: IS_DEV ? require('./server/dev') : undefined
  }
};
<commit_msg>fixed css bundle filename hash<commit_after>const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IS_DEV = process.env.NODE_ENV === 'development';

const regularJSOptions = {
  babelrc: false,
  presets: [['env', { modules: false }], 'stage-2'],
  plugins: ['yo-yoify']
};

module.exports = {
  entry: {
    vendor: ['babel-polyfill', 'fluent'],
    app: ['./app/main.js'],
    style: ['./app/main.css']
  },
  output: {
    filename: '[name].[chunkhash:8].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devtool: IS_DEV && 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        oneOf: [
          {
            include: require.resolve('./assets/cryptofill'),
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[hash:8].[ext]'
                }
              }
            ]
          },
          {
            include: require.resolve('./app/templates/header'),
            use: [
              {
                loader: 'babel-loader',
                options: regularJSOptions
              },
              './build/version_loader'
            ]
          },
          {
            include: [path.dirname(require.resolve('fluent'))],
            use: [
              {
                loader: 'expose-loader',
                options: 'fluent'
              },
              {
                loader: 'babel-loader',
                options: {
                  presets: [['env', { modules: false }]]
                }
              }
            ]
          },
          {
            loader: 'babel-loader',
            include: [
              path.resolve(__dirname, 'app'),
              path.resolve(__dirname, 'common'),
              path.resolve(__dirname, 'node_modules/testpilot-ga/src'),
              path.resolve(__dirname, 'node_modules/fluent-intl-polyfill'),
              path.resolve(__dirname, 'node_modules/intl-pluralrules')
            ],
            options: regularJSOptions
          },
          {
            include: [path.resolve(__dirname, 'node_modules')],
            loader: 'webpack-unassert-loader'
          }
        ]
      },
      {
        test: /\.(svg|png|jpg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[hash:8].[ext]'
        }
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: { modules: false, importLoaders: 1 }
            },
            'postcss-loader'
          ]
        })
      },
      {
        test: require.resolve('./package.json'),
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'version.json'
            }
          },
          'extract-loader',
          './build/package_json_loader'
        ]
      },
      {
        test: /\.ftl$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[hash:8].js'
            }
          },
          'extract-loader',
          './build/fluent_loader'
        ]
      },
      {
        test: require.resolve('./build/generate_asset_map.js'),
        use: ['babel-loader', 'val-loader']
      },
      {
        test: require.resolve('./build/generate_l10n_map.js'),
        use: ['babel-loader', 'val-loader']
      }
    ]
  },
  plugins: [
    new CopyPlugin([
      {
        context: 'public',
        from: '*.*'
      }
    ]),
    new webpack.IgnorePlugin(/dist/),
    new webpack.IgnorePlugin(/require-from-string/),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: ({ resource }) => /node_modules/.test(resource)
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'runtime'
    }),
    new ExtractTextPlugin({
      filename: 'style.[contenthash:8].css'
    }),
    new ManifestPlugin()
  ],
  devServer: {
    compress: true,
    before: IS_DEV ? require('./server/dev') : undefined
  }
};
<|endoftext|>