<commit_before>/* *****************************************************************************
 * Caleydo - Visualization for Molecular Biology - http://caleydo.org
 * Copyright (c) The Caleydo Team. All rights reserved.
 * Licensed under the new BSD license, available at http://caleydo.org/license
 **************************************************************************** */

const {libraryAliases, libraryExternals, modules, entries, ignores, type} = require('./.yo-rc.json')['generator-phovea'];
const resolve = require('path').resolve;
const pkg = require('./package.json');
const webpack = require('webpack');
const fs = require('fs');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const buildInfo = require('./buildInfo.js');

const now = new Date();
const prefix = (n) => n < 10 ? ('0' + n) : n.toString();
const buildId = `${now.getUTCFullYear()}${prefix(now.getUTCMonth())}${prefix(now.getUTCDate())}-${prefix(now.getUTCHours())}${prefix(now.getUTCMinutes())}${prefix(now.getUTCSeconds())}`;
pkg.version = pkg.version.replace('SNAPSHOT', buildId);

const year = (new Date()).getFullYear();
const banner = '/*! ' + (pkg.title || pkg.name) + ' - v' + pkg.version + ' - ' + year + '\n' +
  (pkg.homepage ? '* ' + pkg.homepage + '\n' : '') +
  '* Copyright (c) ' + year + ' ' + pkg.author.name + ';' +
  ' Licensed ' + pkg.license + '*/\n';

//list of loaders and their mappings
const webpackloaders = [
  {test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
  {test: /\.tsx?$/, loader: 'awesome-typescript-loader'},
  {test: /\.json$/, loader: 'json-loader'},
  {
    test: /\.(png|jpg)$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
    }
  },
  {
    test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
      mimetype: 'application/font-woff'
    }
  },
  {
    test: /\.svg(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
      mimetype: 'image/svg+xml'
    }
  },
  {test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader'}
];

/**
 * tests whether the given phovea module name is matching the requested file and if so convert it to an external lookup
 * depending on the loading type
 **/
function testPhoveaModule(moduleName, request) {
  if (!(new RegExp('^' + moduleName + '/src.*')).test(request)) {
    return false;
  }
  const subModule = request.match(/.*\/src\/?(.*)/)[1];
  //skip empty modules = root
  const path = subModule === '' ? [moduleName] : [moduleName, subModule];
  //phovea_<name> ... phovea.name
  const rootPath = /phovea_.*/.test(moduleName) ? ['phovea', moduleName.slice(7)].concat(path.slice(1)) : path;
  return {
    root: rootPath,
    commonjs2: path,
    commonjs: path,
    amd: request + (subModule === '' ? '/main' : '')
  };
}

function testPhoveaModules(modules) {
  return (context, request, callback) => {
    for (let i = 0; i < modules.length; ++i) {
      const r = testPhoveaModule(modules[i], request);
      if (r) {
        return callback(null, r);
      }
    }
    callback();
  };
}

// use workspace registry file if available
const isWorkspaceContext = fs.existsSync(resolve(__dirname, '..', 'phovea_registry.js'));
const registryFile = isWorkspaceContext ? '../phovea_registry.js' : './phovea_registry.js';
const actMetaData = `file-loader?name=phoveaMetaData.json!${buildInfo.metaDataTmpFile(pkg)}`;
const actBuildInfoFile = `file-loader?name=buildInfo.json!${buildInfo.tmpFile()}`;

/**
 * inject the registry to be included
 * @param entry
 * @returns {*}
 */
function injectRegistry(entry) {
  const extraFiles = [registryFile, actBuildInfoFile, actMetaData];
  //build also the registry
  if (typeof entry === 'string') {
    return extraFiles.concat(entry);
  } else {
    const transformed = {};
    Object.keys(entry).forEach((eentry) => {
      transformed[eentry] = extraFiles.concat(entry[eentry]);
    });
    return transformed;
  }

}
/**
 * generate a webpack configuration
 */
function generateWebpack(options) {
  let base = {
    entry: injectRegistry(options.entries),
    output: {
      path: resolve(__dirname, 'build'),
      filename: (options.name || (pkg.name + (options.bundle ? '_bundle' : ''))) + (options.min && !options.nosuffix ? '.min' : '') + '.js',
      publicPath: '' //no public path = relative
    },
    resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
      alias: Object.assign({}, options.libs || {}),
      //fallback to the directory above if they are siblings just in the workspace context
      modules: isWorkspaceContext ? [
        resolve(__dirname, '../'),
        'node_modules'
      ] : ['node_modules']
    },
    plugins: [
      new webpack.BannerPlugin({
        banner: banner,
        raw: true
      }),
      //define magic constants that are replaced
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify(options.isProduction ? 'production': 'development')
        },
        __VERSION__: JSON.stringify(pkg.version),
        __LICENSE__: JSON.stringify(pkg.license),
        __BUILD_ID__: buildId,
        __DEBUG__: options.isDev || options.isTest,
        __TEST__: options.isTest,
        __PRODUCTION__: options.isProduction,
        __APP_CONTEXT__: JSON.stringify('/')
      }),
      new webpack.optimize.MinChunkSizePlugin({
        minChunkSize: 10000 //at least 10.000 characters
      }),
      new webpack.optimize.AggressiveMergingPlugin()
      //rest depends on type
    ],
    externals: [],
    module: {
      loaders: webpackloaders.slice()
    },
    devServer: {
      proxy: {
        '/api/*': {
          target: 'http://localhost:9000',
          secure: false,
          ws: true
        },
        '/login': {
          target: 'http://localhost:9000',
          secure: false
        },
        '/logout': {
          target: 'http://localhost:9000',
          secure: false
        },
        '/loggedinas': {
          target: 'http://localhost:9000',
          secure: false
        }
      },
      contentBase: resolve(__dirname, 'build')
    }
  };

  if (options.library) {
    let libName = /phovea_.*/.test(pkg.name) ? ['phovea', pkg.name.slice(7)] : pkg.name;
    //generate a library, i.e. output the last entry element
    //create library name
    if (options.moduleBundle) {
      libName = 'phovea';
    }
    base.output.library = libName;
    base.output.libraryTarget = 'umd';
    base.output.umdNamedDefine = false; //anonymous require module
  }

  if (!options.bundle) {
    //if we don't bundle don't include external libraries and other phovea modules
    base.externals.push(...(options.externals || Object.keys(options.libs || {})));

    //ignore all phovea modules
    if (options.modules) {
      base.externals.push(testPhoveaModules(options.modules));
    }

    //ignore extra modules
    (options.ignore || []).forEach(function (d) {
      base.module.loaders.push({test: new RegExp(d), loader: 'null-loader'}); //use null loader
    });
    //ingore phovea module registry calls
    (options.modules || []).forEach(function (m) {
      base.module.loaders.push({test: new RegExp('.*[\\\\/]' + m + '[\\\\/]phovea_registry.js'), loader: 'null-loader'}); //use null loader
    });
  }
  if (!options.bundle || options.isApp) {
    //extract the included css file to own file
    let p = new ExtractTextPlugin({
      filename: (options.isApp || options.moduleBundle ? 'style' : pkg.name)  + (options.min && !options.nosuffix ? '.min' : '') + '.css',
      allChunks: true // there seems to be a bug in dynamically loaded chunk styles are not loaded, workaround: extract all styles from all chunks
    });
    base.plugins.push(p);
    base.module.loaders[0] = {
      test: /\.scss$/,
      loader: p.extract(['css-loader', 'sass-loader'])
    };
  }
  if (options.isApp) {
    // create manifest
    // base.plugins.push(new webpack.optimize.AppCachePlugin());
  }
  if (options.commons) {
    //build a commons plugin
    base.plugins.push(new webpack.optimize.CommonsChunkPlugin({
      // The order of this array matters
      names: ['common'],
      minChunks: 2
    }));
  }
  if (options.min) {
    //use a minifier
    base.plugins.push(
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
        output: {
          comments: false
        },
        sourceMap: false
      }));
  } else {
    //generate source maps
    base.devtool = 'source-map';
  }
  return base;
}

function generateWebpackConfig(env) {
  const isTest = env === 'test';
  const isProduction = env === 'prod';
  const isDev = !isProduction && !isTest;

  const base = {
    entries: entries,
    libs: libraryAliases,
    externals: libraryExternals,
    modules: modules,
    ignore: ignores,
    isProduction: isProduction,
    isDev: isDev,
    isTest: isTest
  };

  if (isTest) {
    return generateWebpack(Object.assign({}, base, {
      bundle: true
    }));
  }

  if (type.startsWith('app')) {
    base.isApp = true;
    base.bundle = true; //bundle everything together
    base.name = '[name]'; //multiple entries case
    base.commons = true; //extract commons module
  } else if (type === 'bundle') {
    base.library = true; //expose as library
    base.moduleBundle = true; //expose as library 'phovea'
    base.name = pkg.name; //to avoid adding _bundle
    base.bundle = true;
  } else { //type === 'lib'
    base.library = true;
  }

  //single generation
  if (isDev) {
    return generateWebpack(base);
  } else if (type.startsWith('app')) { //isProduction app
    return generateWebpack(Object.assign({}, base, {
        min: true,
        nosuffix: true
      }));
  } else { //isProduction
    return [
      //plain
      generateWebpack(base),
      //minified
      generateWebpack(Object.assign({}, base, {
        min: true
      }))
    ];
  }
}

module.exports = generateWebpackConfig;
module.exports.generateWebpack = generateWebpack;
<commit_msg>Added `ignore` property to webpack.config.js<commit_after>/* *****************************************************************************
 * Caleydo - Visualization for Molecular Biology - http://caleydo.org
 * Copyright (c) The Caleydo Team. All rights reserved.
 * Licensed under the new BSD license, available at http://caleydo.org/license
 **************************************************************************** */

const {libraryAliases, libraryExternals, modules, entries, ignores, type} = require('./.yo-rc.json')['generator-phovea'];
const resolve = require('path').resolve;
const pkg = require('./package.json');
const webpack = require('webpack');
const fs = require('fs');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const buildInfo = require('./buildInfo.js');

const now = new Date();
const prefix = (n) => n < 10 ? ('0' + n) : n.toString();
const buildId = `${now.getUTCFullYear()}${prefix(now.getUTCMonth())}${prefix(now.getUTCDate())}-${prefix(now.getUTCHours())}${prefix(now.getUTCMinutes())}${prefix(now.getUTCSeconds())}`;
pkg.version = pkg.version.replace('SNAPSHOT', buildId);

const year = (new Date()).getFullYear();
const banner = '/*! ' + (pkg.title || pkg.name) + ' - v' + pkg.version + ' - ' + year + '\n' +
  (pkg.homepage ? '* ' + pkg.homepage + '\n' : '') +
  '* Copyright (c) ' + year + ' ' + pkg.author.name + ';' +
  ' Licensed ' + pkg.license + '*/\n';

//list of loaders and their mappings
const webpackloaders = [
  {test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
  {test: /\.tsx?$/, loader: 'awesome-typescript-loader'},
  {test: /\.json$/, loader: 'json-loader'},
  {
    test: /\.(png|jpg)$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
    }
  },
  {
    test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
      mimetype: 'application/font-woff'
    }
  },
  {
    test: /\.svg(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'url-loader',
    query: {
      limit: 10000, //inline <= 10kb
      mimetype: 'image/svg+xml'
    }
  },
  {test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader'}
];

/**
 * tests whether the given phovea module name is matching the requested file and if so convert it to an external lookup
 * depending on the loading type
 **/
function testPhoveaModule(moduleName, request) {
  if (!(new RegExp('^' + moduleName + '/src.*')).test(request)) {
    return false;
  }
  const subModule = request.match(/.*\/src\/?(.*)/)[1];
  //skip empty modules = root
  const path = subModule === '' ? [moduleName] : [moduleName, subModule];
  //phovea_<name> ... phovea.name
  const rootPath = /phovea_.*/.test(moduleName) ? ['phovea', moduleName.slice(7)].concat(path.slice(1)) : path;
  return {
    root: rootPath,
    commonjs2: path,
    commonjs: path,
    amd: request + (subModule === '' ? '/main' : '')
  };
}

function testPhoveaModules(modules) {
  return (context, request, callback) => {
    for (let i = 0; i < modules.length; ++i) {
      const r = testPhoveaModule(modules[i], request);
      if (r) {
        return callback(null, r);
      }
    }
    callback();
  };
}

// use workspace registry file if available
const isWorkspaceContext = fs.existsSync(resolve(__dirname, '..', 'phovea_registry.js'));
const registryFile = isWorkspaceContext ? '../phovea_registry.js' : './phovea_registry.js';
const actMetaData = `file-loader?name=phoveaMetaData.json!${buildInfo.metaDataTmpFile(pkg)}`;
const actBuildInfoFile = `file-loader?name=buildInfo.json!${buildInfo.tmpFile()}`;

/**
 * inject the registry to be included
 * @param entry
 * @returns {*}
 */
function injectRegistry(entry) {
  const extraFiles = [registryFile, actBuildInfoFile, actMetaData];
  //build also the registry
  if (typeof entry === 'string') {
    return extraFiles.concat(entry);
  } else {
    const transformed = {};
    Object.keys(entry).forEach((eentry) => {
      transformed[eentry] = extraFiles.concat(entry[eentry]);
    });
    return transformed;
  }

}
/**
 * generate a webpack configuration
 */
function generateWebpack(options) {
  let base = {
    entry: injectRegistry(options.entries),
    output: {
      path: resolve(__dirname, 'build'),
      filename: (options.name || (pkg.name + (options.bundle ? '_bundle' : ''))) + (options.min && !options.nosuffix ? '.min' : '') + '.js',
      publicPath: '' //no public path = relative
    },
    resolve: {
      // Add `.ts` and `.tsx` as a resolvable extension.
      extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'],
      alias: Object.assign({}, options.libs || {}),
      //fallback to the directory above if they are siblings just in the workspace context
      modules: isWorkspaceContext ? [
        resolve(__dirname, '../'),
        'node_modules'
      ] : ['node_modules']
    },
    plugins: [
      new webpack.BannerPlugin({
        banner: banner,
        raw: true
      }),
      //define magic constants that are replaced
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify(options.isProduction ? 'production': 'development')
        },
        __VERSION__: JSON.stringify(pkg.version),
        __LICENSE__: JSON.stringify(pkg.license),
        __BUILD_ID__: buildId,
        __DEBUG__: options.isDev || options.isTest,
        __TEST__: options.isTest,
        __PRODUCTION__: options.isProduction,
        __APP_CONTEXT__: JSON.stringify('/')
      }),
      new webpack.optimize.MinChunkSizePlugin({
        minChunkSize: 10000 //at least 10.000 characters
      }),
      new webpack.optimize.AggressiveMergingPlugin()
      //rest depends on type
    ],
    externals: [],
    module: {
      loaders: webpackloaders.slice()
    },
    devServer: {
      ignored: '/node_modules/',
      proxy: {
        '/api/*': {
          target: 'http://localhost:9000',
          secure: false,
          ws: true
        },
        '/login': {
          target: 'http://localhost:9000',
          secure: false
        },
        '/logout': {
          target: 'http://localhost:9000',
          secure: false
        },
        '/loggedinas': {
          target: 'http://localhost:9000',
          secure: false
        }
      },
      contentBase: resolve(__dirname, 'build')
    }
  };

  if (options.library) {
    let libName = /phovea_.*/.test(pkg.name) ? ['phovea', pkg.name.slice(7)] : pkg.name;
    //generate a library, i.e. output the last entry element
    //create library name
    if (options.moduleBundle) {
      libName = 'phovea';
    }
    base.output.library = libName;
    base.output.libraryTarget = 'umd';
    base.output.umdNamedDefine = false; //anonymous require module
  }

  if (!options.bundle) {
    //if we don't bundle don't include external libraries and other phovea modules
    base.externals.push(...(options.externals || Object.keys(options.libs || {})));

    //ignore all phovea modules
    if (options.modules) {
      base.externals.push(testPhoveaModules(options.modules));
    }

    //ignore extra modules
    (options.ignore || []).forEach(function (d) {
      base.module.loaders.push({test: new RegExp(d), loader: 'null-loader'}); //use null loader
    });
    //ingore phovea module registry calls
    (options.modules || []).forEach(function (m) {
      base.module.loaders.push({test: new RegExp('.*[\\\\/]' + m + '[\\\\/]phovea_registry.js'), loader: 'null-loader'}); //use null loader
    });
  }
  if (!options.bundle || options.isApp) {
    //extract the included css file to own file
    let p = new ExtractTextPlugin({
      filename: (options.isApp || options.moduleBundle ? 'style' : pkg.name)  + (options.min && !options.nosuffix ? '.min' : '') + '.css',
      allChunks: true // there seems to be a bug in dynamically loaded chunk styles are not loaded, workaround: extract all styles from all chunks
    });
    base.plugins.push(p);
    base.module.loaders[0] = {
      test: /\.scss$/,
      loader: p.extract(['css-loader', 'sass-loader'])
    };
  }
  if (options.isApp) {
    // create manifest
    // base.plugins.push(new webpack.optimize.AppCachePlugin());
  }
  if (options.commons) {
    //build a commons plugin
    base.plugins.push(new webpack.optimize.CommonsChunkPlugin({
      // The order of this array matters
      names: ['common'],
      minChunks: 2
    }));
  }
  if (options.min) {
    //use a minifier
    base.plugins.push(
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
        output: {
          comments: false
        },
        sourceMap: false
      }));
  } else {
    //generate source maps
    base.devtool = 'source-map';
  }
  return base;
}

function generateWebpackConfig(env) {
  const isTest = env === 'test';
  const isProduction = env === 'prod';
  const isDev = !isProduction && !isTest;

  const base = {
    entries: entries,
    libs: libraryAliases,
    externals: libraryExternals,
    modules: modules,
    ignore: ignores,
    isProduction: isProduction,
    isDev: isDev,
    isTest: isTest
  };

  if (isTest) {
    return generateWebpack(Object.assign({}, base, {
      bundle: true
    }));
  }

  if (type.startsWith('app')) {
    base.isApp = true;
    base.bundle = true; //bundle everything together
    base.name = '[name]'; //multiple entries case
    base.commons = true; //extract commons module
  } else if (type === 'bundle') {
    base.library = true; //expose as library
    base.moduleBundle = true; //expose as library 'phovea'
    base.name = pkg.name; //to avoid adding _bundle
    base.bundle = true;
  } else { //type === 'lib'
    base.library = true;
  }

  //single generation
  if (isDev) {
    return generateWebpack(base);
  } else if (type.startsWith('app')) { //isProduction app
    return generateWebpack(Object.assign({}, base, {
        min: true,
        nosuffix: true
      }));
  } else { //isProduction
    return [
      //plain
      generateWebpack(base),
      //minified
      generateWebpack(Object.assign({}, base, {
        min: true
      }))
    ];
  }
}

module.exports = generateWebpackConfig;
module.exports.generateWebpack = generateWebpack;
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var CompoundPath = this.CompoundPath = PathItem.extend({
	// PORT: port the reversing of segments and keepDirection flag
	initialize: function(items, keepDirection) {
		this.base();
		this._children = [];
		if (items) {
			for (var i = 0, l = items.length; i < l; i++) {
				var item = items[i];
				// All paths except for the first one are reversed when
				// creating a compound path, so that they draw holes.
				// When keepDirection is set to true, child paths aren't reversed.
				if (!keepDirection && i != l - 1)
					item.reverse();
				this.appendTop(items[i]);
			}
		}
	},

	/**
	 * If this is a compound path with only one path inside,
	 * the path is moved outside and the compound path is erased.
	 * Otherwise, the compound path is returned unmodified.
	 *
	 * @return the simplified compound path.
	 */
	simplify: function() {
		if (this._children.length == 1) {
			var child = this._children[0];
			child.moveAbove(this);
			this.remove();
			return child;
		}
		return this;
	},

	smooth: function() {
		for (var i = 0, l = this._children.length; i < l; i++)
			this._children[i].smooth();
	},

	draw: function(ctx, param) {
		var firstChild = this._children[0];
		ctx.beginPath();
		param.compound = true;
		for (var i = 0, l = this._children.length; i < l; i++)
			Item.draw(this._children[i], ctx, param);
		firstChild._setStyles(ctx);
		var fillColor = firstChild.getFillColor(),
			strokeColor = firstChild.getStrokeColor();
		if (fillColor) {
			ctx.fillStyle = fillColor.getCanvasStyle(ctx);
			ctx.fill();
		}
		if (strokeColor) {
			ctx.strokeStyle = strokeColor.getCanvasStyle(ctx);
			ctx.stroke();
		}
		param.compound = false;
	}
}, new function() { // Injection scope for PostScript-like drawing functions
	function getCurrentPath(that) {
		if (that._children.length) {
			return that._children[that._children.length - 1];
		} else {
			throw new Error('Use a moveTo() command first');
		}
	}

	var fields = {
		moveTo: function() {
			var path = new Path();
			this.appendTop(path);
			path.moveTo.apply(path, arguments);
		},

		moveBy: function() {
			var point = arguments.length ? Point.read(arguments) : new Point(),
				path = getCurrentPath(this),
				current = path.segments[path.segments.length - 1]._point;
			this.moveTo(current.add(point));
		},

		closePath: function() {
			getCurrentPath(this).setClosed(true);
		}
	};

	// Redirect all other drawing commands to the current path
	Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
			'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) {
		fields[key] = function() {
			var path = getCurrentPath(this);
			path[key].apply(path, arguments);
		};
	});

	return fields;
});
<commit_msg>Update comment a bit to make code more clear.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var CompoundPath = this.CompoundPath = PathItem.extend({
	// PORT: port the reversing of segments and keepDirection flag
	initialize: function(items, keepDirection) {
		this.base();
		this._children = [];
		if (items) {
			for (var i = 0, l = items.length; i < l; i++) {
				var item = items[i];
				// All paths except for the top one (last one in list) are
				// reversed when creating a compound path, so that they draw
				// holes. When keepDirection is set, children aren't reversed.
				if (!keepDirection && i != l - 1)
					item.reverse();
				this.appendTop(items[i]);
			}
		}
	},

	/**
	 * If this is a compound path with only one path inside,
	 * the path is moved outside and the compound path is erased.
	 * Otherwise, the compound path is returned unmodified.
	 *
	 * @return the simplified compound path.
	 */
	simplify: function() {
		if (this._children.length == 1) {
			var child = this._children[0];
			child.moveAbove(this);
			this.remove();
			return child;
		}
		return this;
	},

	smooth: function() {
		for (var i = 0, l = this._children.length; i < l; i++)
			this._children[i].smooth();
	},

	draw: function(ctx, param) {
		var firstChild = this._children[0];
		ctx.beginPath();
		param.compound = true;
		for (var i = 0, l = this._children.length; i < l; i++)
			Item.draw(this._children[i], ctx, param);
		firstChild._setStyles(ctx);
		var fillColor = firstChild.getFillColor(),
			strokeColor = firstChild.getStrokeColor();
		if (fillColor) {
			ctx.fillStyle = fillColor.getCanvasStyle(ctx);
			ctx.fill();
		}
		if (strokeColor) {
			ctx.strokeStyle = strokeColor.getCanvasStyle(ctx);
			ctx.stroke();
		}
		param.compound = false;
	}
}, new function() { // Injection scope for PostScript-like drawing functions
	function getCurrentPath(that) {
		if (that._children.length) {
			return that._children[that._children.length - 1];
		} else {
			throw new Error('Use a moveTo() command first');
		}
	}

	var fields = {
		moveTo: function() {
			var path = new Path();
			this.appendTop(path);
			path.moveTo.apply(path, arguments);
		},

		moveBy: function() {
			var point = arguments.length ? Point.read(arguments) : new Point(),
				path = getCurrentPath(this),
				current = path.segments[path.segments.length - 1]._point;
			this.moveTo(current.add(point));
		},

		closePath: function() {
			getCurrentPath(this).setClosed(true);
		}
	};

	// Redirect all other drawing commands to the current path
	Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
			'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) {
		fields[key] = function() {
			var path = getCurrentPath(this);
			path[key].apply(path, arguments);
		};
	});

	return fields;
});
<|endoftext|>


<commit_before>/* global document */
import getElements from '../utilities/getElements';
import {
  isEscPressed,
  isUpPressed,
  isDownPressed,
} from '../utilities/keypress';
import generateAriaControls from '../utilities/generateAriaControls';
import generateAriaOwns from '../utilities/generateAriaOwns';
import resetListItems from '../utilities/resetListItems';
import isElementVisible from '../utilities/isElementVisible';

const activeClass = 'sprk-c-Autocomplete__result--active';

const hideList = (autocompleteContainer, inputEl) => {
  if (isElementVisible('ul', autocompleteContainer)) {
    const listEl = autocompleteContainer.querySelector(
      '[data-sprk-autocomplete="results"]',
    );
    resetListItems(
      listEl.querySelectorAll('[data-sprk-autocomplete="result"]'),
      activeClass,
    );
    listEl.classList.add('sprk-u-Display--none');
    inputEl.removeAttribute('aria-activedescendant');
    inputEl.parentNode.setAttribute('aria-expanded', false);
  }
};

const highlightListItem = (result, inputEl) => {
  inputEl.setAttribute('aria-activedescendant', result.id);
  result.classList.add(activeClass);
  result.setAttribute('aria-selected', true);

  const listItemTop = result.getBoundingClientRect().top;
  const listItemBottom = result.getBoundingClientRect().bottom;

  const listTop = result.parentNode.getBoundingClientRect().top;
  const listBottom = result.parentNode.getBoundingClientRect().bottom;

  // if the list item is not vertically contained within the list
  if (listItemTop < listTop || listItemBottom > listBottom) {
    // the distance from the top of the
 to the top of the

    const childTop = result.offsetTop;

    // eslint-disable-next-line no-param-reassign
    result.parentNode.scrollTop = childTop;
  }
};

const getActiveItemIndex = (listEl) => {
  let activeIndex = null;
  listEl.forEach((listItem, index) => {
    if (listItem.classList.contains(activeClass)) {
      activeIndex = index;
    }
  });

  return activeIndex;
};

const advanceHighlightedItem = (results, inputEl) => {
  const activeIndex = getActiveItemIndex(results);
  resetListItems(results, activeClass);

  if (activeIndex === null) {
    highlightListItem(results[0], inputEl);
  } else if (activeIndex + 1 <= results.length - 1) {
    highlightListItem(results[activeIndex + 1], inputEl);
  } else {
    highlightListItem(results[0], inputEl);
  }
};

const retreatHighlightedItem = (results, inputEl) => {
  const activeIndex = getActiveItemIndex(results);
  resetListItems(results, activeClass);

  if (activeIndex === null || activeIndex - 1 === -1) {
    highlightListItem(results[results.length - 1], inputEl);
  } else {
    highlightListItem(results[activeIndex - 1], inputEl);
  }
};

const calculateListWidth = (listEl, inputEl) => {
  const currentInputWidth = inputEl.offsetWidth;
  listEl.setAttribute('style', `max-width:${currentInputWidth}px`);
};

const bindUIEvents = (autocompleteContainer) => {
  const inputEl = autocompleteContainer.querySelector(
    '[data-sprk-autocomplete="input"]',
  );
  const listEl = autocompleteContainer.querySelector(
    '[data-sprk-autocomplete="results"]',
  );

  generateAriaControls(inputEl, listEl, 'autocomplete');
  generateAriaOwns(inputEl.parentNode, listEl, 'autocomplete');

  inputEl.addEventListener('keydown', (e) => {
    const selectableListItems = listEl.querySelectorAll(
      'li:not([data-sprk-autocomplete-no-select])',
    );

    if (isUpPressed(e)) {
      e.stopPropagation();
      e.preventDefault();

      if (isElementVisible('ul', autocompleteContainer)) {
        retreatHighlightedItem(selectableListItems, inputEl);
      }
    } else if (isDownPressed(e)) {
      e.stopPropagation();
      e.preventDefault();

      if (isElementVisible('ul', autocompleteContainer)) {
        advanceHighlightedItem(selectableListItems, inputEl);
      }
    }
  });

  // Hide results if Escape is pressed
  document.addEventListener('keydown', (e) => {
    if (isEscPressed(e)) {
      hideList(autocompleteContainer, inputEl);
    }
  });

  // Hide results if the document body is clicked
  document.addEventListener('click', (e) => {
    if (!(inputEl.contains(e.target) || listEl.contains(e.target))) {
      hideList(autocompleteContainer, inputEl);
    }
  });

  // when the window resizes, reset the max-width of the list
  window.addEventListener('resize', () => {
    calculateListWidth(listEl, inputEl);
  });

  // calculate the max-width on init
  calculateListWidth(listEl, inputEl);
};

const autocomplete = () => {
  getElements('[data-sprk-autocomplete="container"]', bindUIEvents);
};

export { autocomplete, bindUIEvents };
<commit_msg>dont select on elements directly<commit_after>/* global document */
import getElements from '../utilities/getElements';
import {
  isEscPressed,
  isUpPressed,
  isDownPressed,
} from '../utilities/keypress';
import generateAriaControls from '../utilities/generateAriaControls';
import generateAriaOwns from '../utilities/generateAriaOwns';
import resetListItems from '../utilities/resetListItems';
import isElementVisible from '../utilities/isElementVisible';

const activeClass = 'sprk-c-Autocomplete__result--active';

const hideList = (autocompleteContainer, inputEl) => {
  if (
    isElementVisible(
      '[data-sprk-autocomplete="results"]',
      autocompleteContainer,
    )
  ) {
    const listEl = autocompleteContainer.querySelector(
      '[data-sprk-autocomplete="results"]',
    );
    resetListItems(
      listEl.querySelectorAll('[data-sprk-autocomplete="result"]'),
      activeClass,
    );
    listEl.classList.add('sprk-u-Display--none');
    inputEl.removeAttribute('aria-activedescendant');
    inputEl.parentNode.setAttribute('aria-expanded', false);
  }
};

const highlightListItem = (result, inputEl) => {
  inputEl.setAttribute('aria-activedescendant', result.id);
  result.classList.add(activeClass);
  result.setAttribute('aria-selected', true);

  const listItemTop = result.getBoundingClientRect().top;
  const listItemBottom = result.getBoundingClientRect().bottom;

  const listTop = result.parentNode.getBoundingClientRect().top;
  const listBottom = result.parentNode.getBoundingClientRect().bottom;

  // if the list item is not vertically contained within the list
  if (listItemTop < listTop || listItemBottom > listBottom) {
    // the distance from the top of the
 to the top of the

    const childTop = result.offsetTop;

    // eslint-disable-next-line no-param-reassign
    result.parentNode.scrollTop = childTop;
  }
};

const getActiveItemIndex = (listEl) => {
  let activeIndex = null;
  listEl.forEach((listItem, index) => {
    if (listItem.classList.contains(activeClass)) {
      activeIndex = index;
    }
  });

  return activeIndex;
};

const advanceHighlightedItem = (results, inputEl) => {
  const activeIndex = getActiveItemIndex(results);
  resetListItems(results, activeClass);

  if (activeIndex === null) {
    highlightListItem(results[0], inputEl);
  } else if (activeIndex + 1 <= results.length - 1) {
    highlightListItem(results[activeIndex + 1], inputEl);
  } else {
    highlightListItem(results[0], inputEl);
  }
};

const retreatHighlightedItem = (results, inputEl) => {
  const activeIndex = getActiveItemIndex(results);
  resetListItems(results, activeClass);

  if (activeIndex === null || activeIndex - 1 === -1) {
    highlightListItem(results[results.length - 1], inputEl);
  } else {
    highlightListItem(results[activeIndex - 1], inputEl);
  }
};

const calculateListWidth = (listEl, inputEl) => {
  const currentInputWidth = inputEl.offsetWidth;
  listEl.setAttribute('style', `max-width:${currentInputWidth}px`);
};

const bindUIEvents = (autocompleteContainer) => {
  const inputEl = autocompleteContainer.querySelector(
    '[data-sprk-autocomplete="input"]',
  );
  const listEl = autocompleteContainer.querySelector(
    '[data-sprk-autocomplete="results"]',
  );

  generateAriaControls(inputEl, listEl, 'autocomplete');
  generateAriaOwns(inputEl.parentNode, listEl, 'autocomplete');

  inputEl.addEventListener('keydown', (e) => {
    const selectableListItems = listEl.querySelectorAll(
      'li:not([data-sprk-autocomplete-no-select])',
    );

    if (isUpPressed(e)) {
      e.stopPropagation();
      e.preventDefault();

      if (
        isElementVisible(
          '[data-sprk-autocomplete="results"]',
          autocompleteContainer,
        )
      ) {
        retreatHighlightedItem(selectableListItems, inputEl);
      }
    } else if (isDownPressed(e)) {
      e.stopPropagation();
      e.preventDefault();

      if (
        isElementVisible(
          '[data-sprk-autocomplete="results"]',
          autocompleteContainer,
        )
      ) {
        advanceHighlightedItem(selectableListItems, inputEl);
      }
    }
  });

  // Hide results if Escape is pressed
  document.addEventListener('keydown', (e) => {
    if (isEscPressed(e)) {
      hideList(autocompleteContainer, inputEl);
    }
  });

  // Hide results if the document body is clicked
  document.addEventListener('click', (e) => {
    if (!(inputEl.contains(e.target) || listEl.contains(e.target))) {
      hideList(autocompleteContainer, inputEl);
    }
  });

  // when the window resizes, reset the max-width of the list
  window.addEventListener('resize', () => {
    calculateListWidth(listEl, inputEl);
  });

  // calculate the max-width on init
  calculateListWidth(listEl, inputEl);
};

const autocomplete = () => {
  getElements('[data-sprk-autocomplete="container"]', bindUIEvents);
};

export { autocomplete, bindUIEvents };
<|endoftext|>


<commit_before>'use strict';

const hardware = require('./hardware/index');
const _union = require('lodash/union');
const _flatten = require('lodash/flatten');

const basicBlockList = [
    require('./block_start'),
    require('./block_flow'),
    require('./block_moving'),
    require('./block_looks'),
    require('./block_brush'),
    require('./block_text'),
    require('./block_sound'),
    require('./block_judgement'),
    require('./block_calc'),
    require('./block_variable'),
    require('./block_func'),
    require('./block_ai'),
    require('./block_analysis'),
    require('./block_ai_learning'),
];

Entry.AI_UTILIZE_BLOCK = {};
require('./block_ai_utilize_audio');
require('./block_ai_utilize_tts');
require('./block_ai_utilize_translate');
require('./block_ai_utilize_video');
Entry.AI_UTILIZE_BLOCK_LIST = {
    audio: Entry.AI_UTILIZE_BLOCK.audio,
    tts: Entry.AI_UTILIZE_BLOCK.tts,
    translate: Entry.AI_UTILIZE_BLOCK.translate,
    video: Entry.AI_UTILIZE_BLOCK.video,
};

Entry.EXPANSION_BLOCK = {};
require('./block_expansion_weather');
require('./block_expansion_festival');
require('./block_expansion_behaviorconduct_disaster');
require('./block_expansion_behaviorconduct_lifesafety');

Entry.EXPANSION_BLOCK_LIST = {
    weather: Entry.Expansion_Weather,
    festival: Entry.EXPANSION_BLOCK.festival,
    behaviorConductDisaster: Entry.EXPANSION_BLOCK.behaviorConductDisaster,
    behaviorConductLifeSafety: Entry.EXPANSION_BLOCK.behaviorConductLifeSafety,
};

function getBlockObject(items) {
    const blockObject = {};
    items.forEach((item) => {
        if ('getBlocks' in item) {
            Object.assign(blockObject, item.getBlocks());
        }
    });
    return blockObject;
}

/**
 * 하드웨어 블록을 EntryStatic 에 등록한다.
 * 하드웨어 블록에만 사용하는 이유는,
 * 기존 블록은 legacy 블록이 존재하기 때문에 전부 등록하면 안되기 때문이다.
 * 또한 값블록으로서만 사용하는 블록이 블록메뉴에 따로 나타나게 될 수 있다.
 *
 * @param {Object} hardwareModules
 * @return {void}
 */
function registerHardwareBlockToStatic(hardwareModules) {
    EntryStatic.DynamicHardwareBlocks = _union(
        _flatten(hardwareModules.map((hardware) => hardware.blockMenuBlocks || [])),
        EntryStatic.DynamicHardwareBlocks
    );
}

module.exports = {
    getBlocks() {
        const hardwareModules = hardware.getHardwareModuleList();
        registerHardwareBlockToStatic(hardwareModules);
        const basicAndExpansionBlockObjectList = getBlockObject(
            basicBlockList
                .concat(Object.values(Entry.EXPANSION_BLOCK_LIST))
                .concat(Object.values(Entry.AI_UTILIZE_BLOCK_LIST))
        );
        const hardwareBlockObjectList = getBlockObject(hardwareModules);
        return Object.assign({}, basicAndExpansionBlockObjectList, hardwareBlockObjectList);
    },
};
<commit_msg>라인 보안이슈 수정 이후 에러 수정<commit_after>'use strict';

const hardware = require('./hardware/index');
const _union = require('lodash/union');
const _flatten = require('lodash/flatten');

const basicBlockList = [
    require('./block_start'),
    require('./block_flow'),
    require('./block_moving'),
    require('./block_looks'),
    require('./block_brush'),
    require('./block_text'),
    require('./block_sound'),
    require('./block_judgement'),
    require('./block_calc'),
    require('./block_variable'),
    require('./block_func'),
    require('./block_ai'),
    require('./block_analysis'),
    require('./block_ai_learning'),
];

Entry.AI_UTILIZE_BLOCK = {};
require('./block_ai_utilize_audio');
require('./block_ai_utilize_tts');
require('./block_ai_utilize_translate');
require('./block_ai_utilize_video');
Entry.AI_UTILIZE_BLOCK_LIST = {
    audio: Entry.AI_UTILIZE_BLOCK.audio,
    tts: Entry.AI_UTILIZE_BLOCK.tts,
    translate: Entry.AI_UTILIZE_BLOCK.translate,
    video: Entry.AI_UTILIZE_BLOCK.video,
};

Entry.EXPANSION_BLOCK = {};
require('./block_expansion_weather');
require('./block_expansion_festival');
require('./block_expansion_behaviorconduct_disaster');
require('./block_expansion_behaviorconduct_lifesafety');

Entry.EXPANSION_BLOCK_LIST = {
    weather: Entry.Expansion_Weather,
    festival: Entry.EXPANSION_BLOCK.festival,
    behaviorConductDisaster: Entry.EXPANSION_BLOCK.behaviorConductDisaster,
    behaviorConductLifeSafety: Entry.EXPANSION_BLOCK.behaviorConductLifeSafety,
};

function getBlockObject(items) {
    const blockObject = {};
    items.forEach((item) => {
        try {
            if ('getBlocks' in item) {
                Object.assign(blockObject, item.getBlocks());
            }
        } catch (err) {
            console.log(err, item);
        }
    });
    return blockObject;
}

/**
 * 하드웨어 블록을 EntryStatic 에 등록한다.
 * 하드웨어 블록에만 사용하는 이유는,
 * 기존 블록은 legacy 블록이 존재하기 때문에 전부 등록하면 안되기 때문이다.
 * 또한 값블록으로서만 사용하는 블록이 블록메뉴에 따로 나타나게 될 수 있다.
 *
 * @param {Object} hardwareModules
 * @return {void}
 */
function registerHardwareBlockToStatic(hardwareModules) {
    EntryStatic.DynamicHardwareBlocks = _union(
        _flatten(hardwareModules.map((hardware) => hardware.blockMenuBlocks || [])),
        EntryStatic.DynamicHardwareBlocks
    );
}

module.exports = {
    getBlocks() {
        const hardwareModules = hardware.getHardwareModuleList();
        registerHardwareBlockToStatic(hardwareModules);
        const basicAndExpansionBlockObjectList = getBlockObject(
            basicBlockList
                .concat(Object.values(Entry.EXPANSION_BLOCK_LIST))
                .concat(Object.values(Entry.AI_UTILIZE_BLOCK_LIST))
        );
        const hardwareBlockObjectList = getBlockObject(hardwareModules);
        return Object.assign({}, basicAndExpansionBlockObjectList, hardwareBlockObjectList);
    },
};
<|endoftext|>


<commit_before>var m = require('mithril');
var socket = require('./socket');
var xhr = require('./xhr');

module.exports = function(env) {

  this.data;

  this.socket = new socket(env.socketSend, this);

  this.vm = {
    initiating: true,
    reloading: false
  };

  this.countActiveIn = function() {
    return this.data.in.filter(function(c) {
      return !c.declined;
    }).length;
  }

  var all = function() {
    return this.data.in ? this.data.in.concat(this.data.out) : [];
  }.bind(this);

  this.idsHash = function() {
    return all().map(function(c) {
      return c.id;
    }).join('');
  }.bind(this);

  this.update = function(data) {
    this.data = data;
    this.vm.initiating = false;
    this.vm.reloading = false;
    env.setCount(this.countActiveIn());
    this.notifyNew();
    m.redraw();
  }.bind(this);

  this.notifyNew = function() {
    this.data.in.forEach(function(c) {
      if (lichess.once('c-' + c.id)) {
        if (!lichess.quietMode) {
          env.show();
          $.sound.newChallenge();
        }
        lichess.desktopNotification(showUser(c.challenger) + ' challenges you!');
      }
    });
  }.bind(this);

  this.decline = function(id) {
    this.data.in.forEach(function(c) {
      if (c.id === id) {
        c.declined = true;
        xhr.decline(id);
      }
    }.bind(this));
  }.bind(this);

  this.cancel = function(id) {
    this.data.out.forEach(function(c) {
      if (c.id === id) {
        c.declined = true;
        xhr.cancel(id);
      }
    }.bind(this));
  }.bind(this);

  if (env.data) this.update(env.data)
  else xhr.load().then(this.update);

  var showUser = function(user) {
    var rating = user.rating + (user.provisional ? '?' : '');
    var fullName = (user.title ? user.title + ' ' : '') + user.name;
    return fullName + ' (' + rating + ')';
  };

  this.trans = lichess.trans(env.i18n);
};
<commit_msg>fix JS function declaration order<commit_after>var m = require('mithril');
var socket = require('./socket');
var xhr = require('./xhr');

module.exports = function(env) {

  this.data;

  this.socket = new socket(env.socketSend, this);

  this.vm = {
    initiating: true,
    reloading: false
  };

  this.countActiveIn = function() {
    return this.data.in.filter(function(c) {
      return !c.declined;
    }).length;
  }

  var all = function() {
    return this.data.in ? this.data.in.concat(this.data.out) : [];
  }.bind(this);

  var showUser = function(user) {
    var rating = user.rating + (user.provisional ? '?' : '');
    var fullName = (user.title ? user.title + ' ' : '') + user.name;
    return fullName + ' (' + rating + ')';
  };

  this.idsHash = function() {
    return all().map(function(c) {
      return c.id;
    }).join('');
  }.bind(this);

  this.update = function(data) {
    this.data = data;
    this.vm.initiating = false;
    this.vm.reloading = false;
    env.setCount(this.countActiveIn());
    this.notifyNew();
    m.redraw();
  }.bind(this);

  this.notifyNew = function() {
    this.data.in.forEach(function(c) {
      if (lichess.once('c-' + c.id)) {
        if (!lichess.quietMode) {
          env.show();
          $.sound.newChallenge();
        }
        lichess.desktopNotification(showUser(c.challenger) + ' challenges you!');
      }
    });
  }.bind(this);

  this.decline = function(id) {
    this.data.in.forEach(function(c) {
      if (c.id === id) {
        c.declined = true;
        xhr.decline(id);
      }
    }.bind(this));
  }.bind(this);

  this.cancel = function(id) {
    this.data.out.forEach(function(c) {
      if (c.id === id) {
        c.declined = true;
        xhr.cancel(id);
      }
    }.bind(this));
  }.bind(this);

  if (env.data) this.update(env.data)
  else xhr.load().then(this.update);

  this.trans = lichess.trans(env.i18n);
};
<|endoftext|>


<commit_before>/**
 * Classe Base para identificação das classes de serviço
 * @class Mba.ux.incubator.service.Service
 */

Ext.define('Mba.ux.incubator.service.Service', {

    config: {
        serviceId: null
    },

    updateServiceId: function() {
        return Mba.ux.incubator.service.Manager.register(this);
    },

    constructor: function(config) {
        this.initConfig(config);
    },

    init: Ext.emptyFn
});
<commit_msg>inclusão de método para tratamento de erros de ajax<commit_after>/**
 * Classe Base para identificação das classes de serviço
 * @class Mba.ux.incubator.service.Service
 */

Ext.define('Mba.ux.incubator.service.Service', {

    config: {
        serviceId: null
    },

    updateServiceId: function() {
        return Mba.ux.incubator.service.Manager.register(this);
    },

    constructor: function(config) {
        this.initConfig(config);
    },

    tratarErro: function(response, deferred) {
        var mensagem, textResponse;
        if (response.responseText === '') {
            deferred.reject('O serviço está indisponível no momento.');
            return;
        }

        textResponse = Ext.decode(response.responseText);
        if (response.status == 405) {
            deferred.reject(textResponse.detail);
        } else if (response.status == 400 || response.status == 401) {
            mensagem = textResponse.detail;
            if (mensagem == 'Dados incorretos') {
                mensagem = 'MSG_ERRO_LOGIN';
            }
            deferred.reject(mensagem);
        } else if (response.status == 200) {
            deferred.reject('MSG_ERRO_AUTENTICAR');
        } else {
            deferred.reject('MSG_ERRO_TIMEOUT');
        }
    },

    init: Ext.emptyFn
});
<|endoftext|>


<commit_before>/**
 * # fast_demo_build.js
 *
 * This file allows to perform a "fast" build of the RxPlayer's demo, by using
 * esbuild.
 *
 * You can either run it directly as a script (run `node fast_demo_build.js -h`
 * to see the different options) or by requiring it as a node module.
 * If doing the latter you will obtain a function you will have to run with the
 * right options.
 */

const path = require("path");
const esbuild = require("esbuild");
const getHumanReadableHours = require("./utils/get_human_readable_hours");

// If true, this script is called directly
if (require.main === module) {
  const { argv } = process;
  if (argv.includes("-h") || argv.includes("--help")) {
    displayHelp();
    process.exit(0);
  }
  const shouldWatch = argv.includes("-w") || argv.includes("--watch");
  const shouldMinify = argv.includes("-m") || argv.includes("--minify");
  const production = argv.includes("-p") || argv.includes("--production-mode");
  fastDemoBuild({
    watch: shouldWatch,
    minify: shouldMinify,
    production,
  });
} else {
  // This script is loaded as a module
  module.exports = fastDemoBuild;
}

/**
 * Build the demo with the given options.
 * @param {Object} options
 * @param {boolean} [options.minify] - If `true`, the output will be minified.
 * @param {boolean} [options.production] - If `false`, the code will be compiled
 * in "development" mode, which has supplementary assertions.
 * @param {boolean} [options.watch] - If `true`, the RxPlayer's files involve
 * will be watched and the code re-built each time one of them changes.
 */
function fastDemoBuild(options) {
  const minify = !!options.minify;
  const watch = !!options.watch;
  const isDevMode = !options.production;
  let beforeTime = process.hrtime.bigint();

  esbuild.build({
    entryPoints: [path.join(__dirname, "../demo/full/scripts/index.jsx")],
    bundle: true,
    minify,
    outfile: path.join(__dirname, "../demo/full/bundle.js"),
    watch: !watch ? undefined : {
      onRebuild(error, result) {
        if (error) {
          console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Demo re-build failed:`,
                        err);
        } else {
          if (result.errors > 0 || result.warnings > 0) {
            const { errors, warnings } = result;
            console.log(`\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
                        `Demo re-built with ${errors.length} error(s) and ` +
                        ` ${warnings.length} warning(s) ` +
                        `(in ${stats.endTime - stats.startTime} ms).`);
          }
          console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m ` +
                      "Demo re-built!");
        }
      },
    },
    define: {
      "__DEV__": isDevMode,
      "__LOGGER_LEVEL__": "\"INFO\"",
      "process.env.NODE_ENV": JSON.stringify(isDevMode ? "development" : "production"),
      "__FEATURES__.BIF_PARSER": true,
      "__FEATURES__.DASH": true,
      "__FEATURES__.DIRECTFILE": true,
      "__FEATURES__.EME": true,
      "__FEATURES__.HTML_SAMI": true,
      "__FEATURES__.HTML_SRT": true,
      "__FEATURES__.HTML_TTML": true,
      "__FEATURES__.HTML_VTT": true,
      "__FEATURES__.LOCAL_MANIFEST": true,
      "__FEATURES__.METAPLAYLIST": true,
      "__FEATURES__.NATIVE_SAMI": true,
      "__FEATURES__.NATIVE_SRT": true,
      "__FEATURES__.NATIVE_TTML": true,
      "__FEATURES__.NATIVE_VTT": true,
      "__FEATURES__.SMOOTH": true,

      // Path relative to src/features where optional features are implemented
      "__RELATIVE_PATH__.BIF_PARSER": JSON.stringify("../parsers/images/bif.ts"),
      "__RELATIVE_PATH__.DASH": JSON.stringify("../transports/dash/index.ts"),
      "__RELATIVE_PATH__.DASH_JS_PARSER": JSON.stringify("../parsers/manifest/dash/js-parser/index.ts"),
      "__RELATIVE_PATH__.DIRECTFILE": JSON.stringify("../core/init/initialize_directfile.ts"),
      "__RELATIVE_PATH__.EME_MANAGER": JSON.stringify("../core/eme/index.ts"),
      "__RELATIVE_PATH__.HTML_SAMI": JSON.stringify("../parsers/texttracks/sami/html.ts"),
      "__RELATIVE_PATH__.HTML_SRT": JSON.stringify("../parsers/texttracks/srt/html.ts"),
      "__RELATIVE_PATH__.HTML_TEXT_BUFFER": JSON.stringify("../core/segment_buffers/implementations/text/html/index.ts"),
      "__RELATIVE_PATH__.HTML_TTML": JSON.stringify("../parsers/texttracks/ttml/html/index.ts"),
      "__RELATIVE_PATH__.HTML_VTT": JSON.stringify("../parsers/texttracks/webvtt/html/index.ts"),
      "__RELATIVE_PATH__.IMAGE_BUFFER": JSON.stringify("../core/segment_buffers/implementations/image/index.ts"),
      "__RELATIVE_PATH__.LOCAL_MANIFEST": JSON.stringify("../transports/local/index.ts"),
      "__RELATIVE_PATH__.MEDIA_ELEMENT_TRACK_CHOICE_MANAGER": JSON.stringify("../core/api/media_element_track_choice_manager.ts"),
      "__RELATIVE_PATH__.METAPLAYLIST": JSON.stringify("../transports/metaplaylist/index.ts"),
      "__RELATIVE_PATH__.NATIVE_SAMI": JSON.stringify("../parsers/texttracks/sami/native.ts"),
      "__RELATIVE_PATH__.NATIVE_SRT": JSON.stringify("../parsers/texttracks/srt/native.ts"),
      "__RELATIVE_PATH__.NATIVE_TEXT_BUFFER": JSON.stringify("../core/segment_buffers/implementations/text/native/index.ts"),
      "__RELATIVE_PATH__.NATIVE_TTML": JSON.stringify("../parsers/texttracks/ttml/native/index.ts"),
      "__RELATIVE_PATH__.NATIVE_VTT": JSON.stringify("../parsers/texttracks/webvtt/native/index.ts"),
      "__RELATIVE_PATH__.SMOOTH": JSON.stringify("../transports/smooth/index.ts"),
    }
  }).then(
  (result) => {
    if (result.errors > 0 || result.warnings > 0) {
      const { errors, warnings } = result;
      console.log(`\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
                  `Demo built with ${errors.length} error(s) and ` +
                  ` ${warnings.length} warning(s) ` +
                  `(in ${stats.endTime - stats.startTime} ms).`);
    }
    const fullTime = (process.hrtime.bigint() - beforeTime) / 1000000n;
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m ` +
                `Build done in ${fullTime}ms`);
  },
  (err) => {
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Demo build failed:`,
                  err);
    process.exit(1);
  });
}

/**
 * Display through `console.log` an helping message relative to how to run this
 * script.
 */
function displayHelp() {
  /* eslint-disable no-console */
  console.log(
  /* eslint-disable indent */
`Usage: node generate_full_demo.js [options]
Options:
  -h, --help             Display this help
  -m, --minify           Minify the built demo
  -p, --production-mode  Build all files in production mode (less runtime checks, mostly).
  -w, --watch            Re-build each time either the demo or library files change`,
  /* eslint-enable indent */
  );
  /* eslint-enable no-console */
}
<commit_msg>demo: fix esbuild-defined constants when building demo<commit_after>/**
 * # fast_demo_build.js
 *
 * This file allows to perform a "fast" build of the RxPlayer's demo, by using
 * esbuild.
 *
 * You can either run it directly as a script (run `node fast_demo_build.js -h`
 * to see the different options) or by requiring it as a node module.
 * If doing the latter you will obtain a function you will have to run with the
 * right options.
 */

const path = require("path");
const esbuild = require("esbuild");
const getHumanReadableHours = require("./utils/get_human_readable_hours");

// If true, this script is called directly
if (require.main === module) {
  const { argv } = process;
  if (argv.includes("-h") || argv.includes("--help")) {
    displayHelp();
    process.exit(0);
  }
  const shouldWatch = argv.includes("-w") || argv.includes("--watch");
  const shouldMinify = argv.includes("-m") || argv.includes("--minify");
  const production = argv.includes("-p") || argv.includes("--production-mode");
  fastDemoBuild({
    watch: shouldWatch,
    minify: shouldMinify,
    production,
  });
} else {
  // This script is loaded as a module
  module.exports = fastDemoBuild;
}

/**
 * Build the demo with the given options.
 * @param {Object} options
 * @param {boolean} [options.minify] - If `true`, the output will be minified.
 * @param {boolean} [options.production] - If `false`, the code will be compiled
 * in "development" mode, which has supplementary assertions.
 * @param {boolean} [options.watch] - If `true`, the RxPlayer's files involve
 * will be watched and the code re-built each time one of them changes.
 */
function fastDemoBuild(options) {
  const minify = !!options.minify;
  const watch = !!options.watch;
  const isDevMode = !options.production;
  let beforeTime = process.hrtime.bigint();

  esbuild.build({
    entryPoints: [path.join(__dirname, "../demo/full/scripts/index.jsx")],
    bundle: true,
    minify,
    outfile: path.join(__dirname, "../demo/full/bundle.js"),
    watch: !watch ? undefined : {
      onRebuild(error, result) {
        if (error) {
          console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Demo re-build failed:`,
                        err);
        } else {
          if (result.errors > 0 || result.warnings > 0) {
            const { errors, warnings } = result;
            console.log(`\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
                        `Demo re-built with ${errors.length} error(s) and ` +
                        ` ${warnings.length} warning(s) ` +
                        `(in ${stats.endTime - stats.startTime} ms).`);
          }
          console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m ` +
                      "Demo re-built!");
        }
      },
    },
    define: {
      "process.env.NODE_ENV": JSON.stringify(isDevMode ? "development" : "production"),
      __FEATURES__: JSON.stringify({
        IS_DISABLED: 0,
        IS_ENABLED: 1,

        BIF_PARSER: 1,
        DASH: 1,
        DIRECTFILE: 1,
        EME: 1,
        HTML_SAMI: 1,
        HTML_SRT: 1,
        HTML_TTML: 1,
        HTML_VTT: 1,
        LOCAL_MANIFEST: 1,
        METAPLAYLIST: 1,
        NATIVE_SAMI: 1,
        NATIVE_SRT: 1,
        NATIVE_TTML: 1,
        NATIVE_VTT: 1,
        SMOOTH: 1,
      }),
      __ENVIRONMENT__: JSON.stringify({
        PRODUCTION: 0,
        DEV: 1,
        CURRENT_ENV: isDevMode ? 1 : 0,
      }),
      __LOGGER_LEVEL__: JSON.stringify({
        CURRENT_LEVEL: "INFO",
      }),
    }
  }).then(
  (result) => {
    if (result.errors > 0 || result.warnings > 0) {
      const { errors, warnings } = result;
      console.log(`\x1b[33m[${getHumanReadableHours()}]\x1b[0m ` +
                  `Demo built with ${errors.length} error(s) and ` +
                  ` ${warnings.length} warning(s) ` +
                  `(in ${stats.endTime - stats.startTime} ms).`);
    }
    const fullTime = (process.hrtime.bigint() - beforeTime) / 1000000n;
    console.log(`\x1b[32m[${getHumanReadableHours()}]\x1b[0m ` +
                `Build done in ${fullTime}ms`);
  },
  (err) => {
    console.error(`\x1b[31m[${getHumanReadableHours()}]\x1b[0m Demo build failed:`,
                  err);
    process.exit(1);
  });
}

/**
 * Display through `console.log` an helping message relative to how to run this
 * script.
 */
function displayHelp() {
  /* eslint-disable no-console */
  console.log(
  /* eslint-disable indent */
`Usage: node generate_full_demo.js [options]
Options:
  -h, --help             Display this help
  -m, --minify           Minify the built demo
  -p, --production-mode  Build all files in production mode (less runtime checks, mostly).
  -w, --watch            Re-build each time either the demo or library files change`,
  /* eslint-enable indent */
  );
  /* eslint-enable no-console */
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import ManyRelationship from "ember-data/-private/system/relationships/state/has-many";
import BelongsToRelationship from "ember-data/-private/system/relationships/state/belongs-to";
import EmptyObject from "ember-data/-private/system/empty-object";

var get = Ember.get;

function createRelationshipFor(record, relationshipMeta, store) {
  var inverseKey;
  var inverse = record.type.inverseFor(relationshipMeta.key, store);

  if (inverse) {
    inverseKey = inverse.name;
  }

  if (relationshipMeta.kind === 'hasMany') {
    return new ManyRelationship(store, record, inverseKey, relationshipMeta);
  } else {
    return new BelongsToRelationship(store, record, inverseKey, relationshipMeta);
  }
}

export default function Relationships(record) {
  this.record = record;
  this.initializedRelationships = new EmptyObject();
}

Relationships.prototype.has = function(key) {
  return !!this.initializedRelationships[key];
};

Relationships.prototype.get = function(key) {
  var relationships = this.initializedRelationships;
  var relationshipsByName = get(this.record.type, 'relationshipsByName');
  if (!relationships[key] && relationshipsByName.get(key)) {
    relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store);
  }
  return relationships[key];
};
<commit_msg>Don't do inverse calculation if inverse explicitly turned off<commit_after>import Ember from 'ember';
import ManyRelationship from "ember-data/-private/system/relationships/state/has-many";
import BelongsToRelationship from "ember-data/-private/system/relationships/state/belongs-to";
import EmptyObject from "ember-data/-private/system/empty-object";

var get = Ember.get;

function shouldFindInverse(relationshipMeta) {
  let options = relationshipMeta.options;
  return !(options && options.inverse === null);
}

function createRelationshipFor(record, relationshipMeta, store) {
  let inverseKey;
  let inverse = null;
  if (shouldFindInverse(relationshipMeta)) {
    inverse = record.type.inverseFor(relationshipMeta.key, store);
  }

  if (inverse) {
    inverseKey = inverse.name;
  }

  if (relationshipMeta.kind === 'hasMany') {
    return new ManyRelationship(store, record, inverseKey, relationshipMeta);
  } else {
    return new BelongsToRelationship(store, record, inverseKey, relationshipMeta);
  }
}

export default function Relationships(record) {
  this.record = record;
  this.initializedRelationships = new EmptyObject();
}

Relationships.prototype.has = function(key) {
  return !!this.initializedRelationships[key];
};

Relationships.prototype.get = function(key) {
  var relationships = this.initializedRelationships;
  var relationshipsByName = get(this.record.type, 'relationshipsByName');
  if (!relationships[key] && relationshipsByName.get(key)) {
    relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store);
  }
  return relationships[key];
};
<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>It can call a method on a derived object<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>import "../../../../@simonwep/pickr/dist/pickr.min.js";

document.head.insertAdjacentHTML("beforeend", `

`);

export default class InputColorPickerElement extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: "open" }).innerHTML = `

    `;

    this._pickr = window.Pickr.create({
      el: this.shadowRoot.querySelector("div"),
      comparison: false,
      components: {
        preview: true,
        opacity: true,
        hue: true,
        interaction: {
          hex: true,
          input: true,
          save: true,
        },
      },
    });

    this._pickr.on("init", () => {
      this._pickr.setColor(this.value);

      this._pickr.on("change", () => {
        this._value = this._pickr.getColor().toHEXA().toString();
        this.dispatchEvent(new Event("input"));
      });

      this._pickr.on("save", () => {
        this.dispatchEvent(new Event("input"));
      });
    });
  }

  get value() {
    return this._value;
  }

  set value(value) {
    this._value = value;
    this._pickr.setColor(this._value);
  }
}
<commit_msg>small fix on input-colorpicker<commit_after>import "../../../../@simonwep/pickr/dist/pickr.min.js";

document.head.insertAdjacentHTML("beforeend", `

`);

export default class InputColorPickerElement extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: "open" }).innerHTML = `

    `;

    this._pickr = window.Pickr.create({
      el: this.shadowRoot.querySelector("div"),
      comparison: false,
      components: {
        preview: true,
        opacity: true,
        hue: true,
        interaction: {
          hex: true,
          input: true,
          save: true,
        },
      },
    });

    this._pickr.on("init", () => {
      if (this.value) {
        this._pickr.setColor(this.value);
      }

      this._pickr.on("change", () => {
        this._value = this._pickr.getColor().toHEXA().toString();
        this.dispatchEvent(new Event("input"));
      });

      this._pickr.on("save", () => {
        this.dispatchEvent(new Event("input"));
      });
    });
  }

  get value() {
    return this._value;
  }

  set value(value) {
    this._value = value;
    this._pickr.setColor(this._value);
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { expandSearch } from 'mastodon/actions/search';
import Account from 'mastodon/containers/account_container';
import Status from 'mastodon/containers/status_container';
import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag';
import { List as ImmutableList } from 'immutable';
import LoadMore from 'mastodon/components/load_more';
import LoadingIndicator from 'mastodon/components/loading_indicator';

const mapStateToProps = state => ({
  isLoading: state.getIn(['search', 'isLoading']),
  results: state.getIn(['search', 'results']),
});

const appendLoadMore = (id, list, onLoadMore) => {
  if (list.size >= 5) {
    return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />);
  } else {
    return list;
  }
};

const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts').map(item => (
  <Account key={`account-${item}`} id={item} />
)), onLoadMore);

const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags').map(item => (
  <Hashtag key={`tag-${item.get('name')}`} hashtag={item} />
)), onLoadMore);

const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses').map(item => (
  <Status key={`status-${item}`} id={item} />
)), onLoadMore);

export default @connect(mapStateToProps)
class Results extends React.PureComponent {

  static propTypes = {
    results: ImmutablePropTypes.map,
    isLoading: PropTypes.bool,
    multiColumn: PropTypes.bool,
    dispatch: PropTypes.func.isRequired,
  };

  state = {
    type: 'all',
  };

  handleSelectAll = () => this.setState({ type: 'all' });
  handleSelectAccounts = () => this.setState({ type: 'accounts' });
  handleSelectHashtags = () => this.setState({ type: 'hashtags' });
  handleSelectStatuses = () => this.setState({ type: 'statuses' });
  handleLoadMoreAccounts = () => this.loadMore('accounts');
  handleLoadMoreStatuses = () => this.loadMore('statuses');
  handleLoadMoreHashtags = () => this.loadMore('hashtags');

  loadMore (type) {
    const { dispatch } = this.props;
    dispatch(expandSearch(type));
  }

  render () {
    const { isLoading, results } = this.props;
    const { type } = this.state;

    let filteredResults = ImmutableList();

    if (!isLoading) {
      switch(type) {
      case 'all':
        filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses));
        break;
      case 'accounts':
        filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts));
        break;
      case 'hashtags':
        filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags));
        break;
      case 'statuses':
        filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses));
        break;
      }

      if (filteredResults.size === 0) {
        filteredResults = (

            <FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' />

        );
      }
    }

    return (
      <React.Fragment>

          <button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button>
          <button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button>
          <button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button>
          <button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></button>

          {isLoading ? <LoadingIndicator /> : filteredResults}

      </React.Fragment>
    );
  }

}
<commit_msg>Fix crash when search fails in web UI (#17853)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { expandSearch } from 'mastodon/actions/search';
import Account from 'mastodon/containers/account_container';
import Status from 'mastodon/containers/status_container';
import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag';
import { List as ImmutableList } from 'immutable';
import LoadMore from 'mastodon/components/load_more';
import LoadingIndicator from 'mastodon/components/loading_indicator';

const mapStateToProps = state => ({
  isLoading: state.getIn(['search', 'isLoading']),
  results: state.getIn(['search', 'results']),
});

const appendLoadMore = (id, list, onLoadMore) => {
  if (list.size >= 5) {
    return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />);
  } else {
    return list;
  }
};

const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts', ImmutableList()).map(item => (
  <Account key={`account-${item}`} id={item} />
)), onLoadMore);

const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags', ImmutableList()).map(item => (
  <Hashtag key={`tag-${item.get('name')}`} hashtag={item} />
)), onLoadMore);

const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses', ImmutableList()).map(item => (
  <Status key={`status-${item}`} id={item} />
)), onLoadMore);

export default @connect(mapStateToProps)
class Results extends React.PureComponent {

  static propTypes = {
    results: ImmutablePropTypes.map,
    isLoading: PropTypes.bool,
    multiColumn: PropTypes.bool,
    dispatch: PropTypes.func.isRequired,
  };

  state = {
    type: 'all',
  };

  handleSelectAll = () => this.setState({ type: 'all' });
  handleSelectAccounts = () => this.setState({ type: 'accounts' });
  handleSelectHashtags = () => this.setState({ type: 'hashtags' });
  handleSelectStatuses = () => this.setState({ type: 'statuses' });
  handleLoadMoreAccounts = () => this.loadMore('accounts');
  handleLoadMoreStatuses = () => this.loadMore('statuses');
  handleLoadMoreHashtags = () => this.loadMore('hashtags');

  loadMore (type) {
    const { dispatch } = this.props;
    dispatch(expandSearch(type));
  }

  render () {
    const { isLoading, results } = this.props;
    const { type } = this.state;

    let filteredResults = ImmutableList();

    if (!isLoading) {
      switch(type) {
      case 'all':
        filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses));
        break;
      case 'accounts':
        filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts));
        break;
      case 'hashtags':
        filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags));
        break;
      case 'statuses':
        filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses));
        break;
      }

      if (filteredResults.size === 0) {
        filteredResults = (

            <FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' />

        );
      }
    }

    return (
      <React.Fragment>

          <button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button>
          <button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button>
          <button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button>
          <button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></button>

          {isLoading ? <LoadingIndicator /> : filteredResults}

      </React.Fragment>
    );
  }

}
<|endoftext|>


<commit_before>import styled from 'styled-components';
import irisTheme from 'theme/irisTheme';

const HeaderBar = styled.div.withConfig({ displayName: 'HeaderBar' })`
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: ${irisTheme.thicknesses.normal} solid ${irisTheme.colors.gray.border};
  padding-right: ${irisTheme.spacing.medium};
  padding-left: ${irisTheme.spacing.medium};
`;

/**
 * @component
 */
export default HeaderBar;
<commit_msg>BWDB-3718 SCL - Header bar. Switched to using themeGet<commit_after>import styled from 'styled-components';
import themeGet from 'extensions/themeGet';

const HeaderBar = styled.div.withConfig({ displayName: 'HeaderBar' })`
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: ${themeGet('thicknesses.normal')} solid ${themeGet('colors.gray.border')};
  padding-right: ${themeGet('spacing.medium')};
  padding-left: ${themeGet('spacing.medium')};
`;

/**
 * @component
 */
export default HeaderBar;
<|endoftext|>


<commit_before>var td              = require('testdouble');
var mockProject     = require('../../../../fixtures/corber-mock/project');
var CdvRawTask      = require('../../../../../lib/targets/cordova/tasks/raw');

var setupPrepareTask = function() {
  var PrepareTask = require('../../../../../lib/targets/cordova/tasks/prepare');
  return new PrepareTask(mockProject);
};

describe('Cordova Prepare Task', function() {
  afterEach(function() {
    td.reset();
  });

  it('runs cordova prepare with fetch defaulted', function() {
    var rawDouble = td.replace(CdvRawTask.prototype, 'run');
    var prepare = setupPrepareTask();
    prepare.run();

    td.verify(new rawDouble({fetch: true}));
  });
});
<commit_msg>fix(tests): pass eslint<commit_after>var td              = require('testdouble');
var mockProject     = require('../../../../fixtures/corber-mock/project');
var CdvRawTask      = require('../../../../../lib/targets/cordova/tasks/raw');

var setupPrepareTask = function() {
  var PrepareTask = require('../../../../../lib/targets/cordova/tasks/prepare');
  return new PrepareTask(mockProject);
};

describe('Cordova Prepare Task', function() {
  afterEach(function() {
    td.reset();
  });

  it('runs cordova prepare with fetch defaulted', function() {
    var RawDouble = td.replace(CdvRawTask.prototype, 'run');
    var prepare = setupPrepareTask();
    prepare.run();

    td.verify(new RawDouble({fetch: true}));
  });
});
<|endoftext|>