<commit_before>$(document).ready(function() {
	/**
	 * Add all optional elements
	 */
	$('#optionals_all').delegate('#add-all', 'click', function(e) {
		$('#inactive_elements .element').each(function() {
			addElement(this, false);
		});
		e.preventDefault();
	});

	/**
	 * Add an optional element
	 */
	$('#inactive_elements').delegate('.element', 'click', function(e) {
		if (!$(this).hasClass('clicked')) {
			$(this).addClass('clicked');
			addElement(this);
		}
		e.preventDefault();
	});

	function addElement(element, animate, is_child) {
		if (typeof (animate) === 'undefined')
			animate = true;
		if (typeof (is_child) === 'undefined')
			is_child = false;

		var element_type_id = $(element).attr('data-element-type-id');
		var display_order = $(element).attr('data-element-display-order');
		$.get(baseUrl + "/" + moduleName + "/Default/ElementForm", {
			id : element_type_id,
			patient_id : et_patient_id,
		}, function(data) {
			if (is_child) {
				var container = $(element).closest('.inactive_child_elements').parent().find('.active_child_elements:first');
			} else {
				var container = $('#active_elements');
			}

			var insert_before = container.find('.element').first();

			while (parseInt(insert_before.attr('data-element-display-order')) < parseInt(display_order)) {
				insert_before = insert_before.nextAll('div:first');
			}
			$(element).remove();
			if (insert_before.length) {
				insert_before.before(data);
			} else {
				$(container).append(data);
			}
			$('#event_display textarea.autosize:visible').autosize();

			var inserted = (insert_before.length) ? insert_before.prevAll('div:first') : container.find('.element:last');
			if (animate) {
				var offTop = inserted.offset().top - 50;
				var speed = (Math.abs($(window).scrollTop() - offTop)) * 1.5;
				$('body').animate({
					scrollTop : offTop
				}, speed, null, function() {
					$('.elementTypeName', inserted).effect('pulsate', {
						times : 2
					}, 600);
				});
			}

			var el_class = $(element).attr('data-element-type-class');
			var initFunctionName = el_class.replace('Element_', '') + '_init';
			if(typeof(window[initFunctionName]) == 'function') {
				window[initFunctionName]();
			}

			// now init any children
			$(".element." + el_class).find('.active_child_elements').find('.element').each(function() {
				var initFunctionName = $(this).attr('data-element-type-class').replace('Element_', '') + '_init';
				if(typeof(window[initFunctionName]) == 'function') {
					window[initFunctionName]();
				}
			});
		});
	}

	/**
	 * Remove all optional elements
	 */
	$('#optionals_all').delegate('#remove-all', 'click', function(e) {
		$('#active_elements .element').each(function() {
			removeElement(this);
		});
		e.preventDefault();
	});

	/**
	 * Remove an optional element
	 */
	$('#active_elements').delegate('.removeElement button', 'click', function(e) {
		if (!$(this).parents('.active_child_elements').length) {
			var element = $(this).closest('.element');
			removeElement(element);
		}
		e.preventDefault();
	});

	/*
	 * Remove a child element
	 */
	$('#active_elements').delegate('.active_child_elements .removeElement button', 'click', function(e) {
		var element = $(this).closest('.element');
		removeElement(element, true);
		e.preventDefault();

	})

	function removeElement(element, is_child) {
		if (typeof(is_child) == 'undefined')
			is_child = false;
		var element_type_name = $(element).attr('data-element-type-name');
		var display_order = $(element).attr('data-element-display-order');
		$(element).html($('
' + element_type_name + '
'));
		if (is_child) {
			var container = $(element).closest('.active_child_elements').parent().find('.inactive_child_elements');
		}
		else {
			var container = $('#inactive_elements');
		}
		var insert_before = $(container).find('.element').first();
		while (parseInt(insert_before.attr('data-element-display-order')) < parseInt(display_order)) {
			insert_before = insert_before.next();
		}
		if (insert_before.length) {
			insert_before.before(element);
		} else {
			$(container).append(element);
		}
	}

	/**
	 * Add optional child element
	 */
	$("#active_elements").delegate('.inactive_child_elements .element', 'click', function(e) {
		if (!$(this).hasClass('clicked')) {
			$(this).addClass('clicked');
			addElement(this, true, true);
		}
		e.preventDefault();
	});
});<commit_msg>+ bugfix for removal of nested elements<commit_after>$(document).ready(function() {
	/**
	 * Add all optional elements
	 */
	$('#optionals_all').delegate('#add-all', 'click', function(e) {
		$('#inactive_elements .element').each(function() {
			addElement(this, false);
		});
		e.preventDefault();
	});

	/**
	 * Add an optional element
	 */
	$('#inactive_elements').delegate('.element', 'click', function(e) {
		if (!$(this).hasClass('clicked')) {
			$(this).addClass('clicked');
			addElement(this);
		}
		e.preventDefault();
	});

	function addElement(element, animate, is_child) {
		if (typeof (animate) === 'undefined')
			animate = true;
		if (typeof (is_child) === 'undefined')
			is_child = false;

		var element_type_id = $(element).attr('data-element-type-id');
		var display_order = $(element).attr('data-element-display-order');
		$.get(baseUrl + "/" + moduleName + "/Default/ElementForm", {
			id : element_type_id,
			patient_id : et_patient_id,
		}, function(data) {
			if (is_child) {
				var container = $(element).closest('.inactive_child_elements').parent().find('.active_child_elements:first');
			} else {
				var container = $('#active_elements');
			}

			var insert_before = container.find('.element').first();

			while (parseInt(insert_before.attr('data-element-display-order')) < parseInt(display_order)) {
				insert_before = insert_before.nextAll('div:first');
			}
			$(element).remove();
			if (insert_before.length) {
				insert_before.before(data);
			} else {
				$(container).append(data);
			}
			$('#event_display textarea.autosize:visible').autosize();

			var inserted = (insert_before.length) ? insert_before.prevAll('div:first') : container.find('.element:last');
			if (animate) {
				var offTop = inserted.offset().top - 50;
				var speed = (Math.abs($(window).scrollTop() - offTop)) * 1.5;
				$('body').animate({
					scrollTop : offTop
				}, speed, null, function() {
					$('.elementTypeName', inserted).effect('pulsate', {
						times : 2
					}, 600);
				});
			}

			var el_class = $(element).attr('data-element-type-class');
			var initFunctionName = el_class.replace('Element_', '') + '_init';
			if(typeof(window[initFunctionName]) == 'function') {
				window[initFunctionName]();
			}

			// now init any children
			$(".element." + el_class).find('.active_child_elements').find('.element').each(function() {
				var initFunctionName = $(this).attr('data-element-type-class').replace('Element_', '') + '_init';
				if(typeof(window[initFunctionName]) == 'function') {
					window[initFunctionName]();
				}
			});
		});
	}

	/**
	 * Remove all optional elements
	 */
	$('#optionals_all').delegate('#remove-all', 'click', function(e) {
		$('#active_elements .element').each(function() {
			removeElement(this);
		});
		e.preventDefault();
	});

	/**
	 * Remove an optional element
	 */
	$('#active_elements').delegate('.removeElement button', 'click', function(e) {
		if (!$(this).parents('.active_child_elements').length) {
			var element = $(this).closest('.element');
			removeElement(element);
		}
		e.preventDefault();
	});

	/*
	 * Remove a child element
	 */
	$('#active_elements').delegate('.active_child_elements .removeElement button', 'click', function(e) {
		var element = $(this).closest('.element');
		removeElement(element, true);
		e.preventDefault();

	})

	function removeElement(element, is_child) {
		if (typeof(is_child) == 'undefined')
			is_child = false;
		var element_type_name = $(element).attr('data-element-type-name');
		var display_order = $(element).attr('data-element-display-order');
		$(element).html($('
' + element_type_name + '
'));
		if (is_child) {
			var container = $(element).closest('.active_child_elements').parent().find('.inactive_child_elements:last');
		}
		else {
			var container = $('#inactive_elements');
		}
		var insert_before = $(container).find('.element').first();
		while (parseInt(insert_before.attr('data-element-display-order')) < parseInt(display_order)) {
			insert_before = insert_before.next();
		}
		if (insert_before.length) {
			insert_before.before(element);
		} else {
			$(container).append(element);
		}
	}

	/**
	 * Add optional child element
	 */
	$("#active_elements").delegate('.inactive_child_elements .element', 'click', function(e) {
		if (!$(this).hasClass('clicked')) {
			$(this).addClass('clicked');
			addElement(this, true, true);
		}
		e.preventDefault();
	});
});<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')
const WebpackPwaManifest = require('webpack-pwa-manifest')

const PUBLIC_PATH = 'https://loopingdoge.github.io/mesopotamia-jones/'

// Phaser webpack config
const phaserModule = path.join(__dirname, '/node_modules/phaser-ce/')
const phaser = path.join(phaserModule, 'build/custom/phaser-split.js')
const pixi = path.join(phaserModule, 'build/custom/pixi.js')
const p2 = path.join(phaserModule, 'build/custom/p2.js')

module.exports = {
    entry: {
        main: './src/index.tsx',
        vendor: ['react', 'mobx', 'aphrodite']
    },
    devtool: 'source-map',
    devServer: {
        contentBase: './dist'
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Mesopotamia Jones',
            template: 'src/index.ejs',
            favicon: path.resolve('assets/images/favicon.png')
        }),
        new webpack.HashedModuleIdsPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'runtime'
        }),
        new SWPrecacheWebpackPlugin({
            cacheId: 'mesopotamia-jones',
            dontCacheBustUrlsMatching: /\.\w{8}\./,
            filename: 'service-worker.js',
            minify: true,
            navigateFallback: PUBLIC_PATH,
            staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/]
        }),
        new WebpackPwaManifest({
            name: 'Mesopotamia Jones',
            short_name: 'MJ',
            description: 'Learn to code with games!',
            background_color: '#ffffff',
            orientation: 'landscape',
            display: 'fullscreen',
            icons: [
                {
                    src: path.resolve('assets/images/favicon.png'),
                    sizes: [96, 128, 192, 256, 384, 512]
                }
            ]
        })
    ],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        alias: {
            'phaser-ce': phaser,
            pixi: pixi,
            p2: p2
        },
        extensions: ['.ts', '.tsx', '.js', 'png', 'json']
    },
    module: {
        rules: [
            {
                test: /pixi\.js/,
                use: ['expose-loader?PIXI']
            },
            {
                test: /phaser-split\.js$/,
                use: ['expose-loader?Phaser']
            },
            {
                test: /p2\.js/,
                use: ['expose-loader?p2']
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader']
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: ['file-loader']
            },
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: ['awesome-typescript-loader']
            }
        ]
    }
}
<commit_msg>Changed PWA short name<commit_after>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')
const WebpackPwaManifest = require('webpack-pwa-manifest')

const PUBLIC_PATH = 'https://loopingdoge.github.io/mesopotamia-jones/'

// Phaser webpack config
const phaserModule = path.join(__dirname, '/node_modules/phaser-ce/')
const phaser = path.join(phaserModule, 'build/custom/phaser-split.js')
const pixi = path.join(phaserModule, 'build/custom/pixi.js')
const p2 = path.join(phaserModule, 'build/custom/p2.js')

module.exports = {
    entry: {
        main: './src/index.tsx',
        vendor: ['react', 'mobx', 'aphrodite']
    },
    devtool: 'source-map',
    devServer: {
        contentBase: './dist'
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Mesopotamia Jones',
            template: 'src/index.ejs',
            favicon: path.resolve('assets/images/favicon.png')
        }),
        new webpack.HashedModuleIdsPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'runtime'
        }),
        new SWPrecacheWebpackPlugin({
            cacheId: 'mesopotamia-jones',
            dontCacheBustUrlsMatching: /\.\w{8}\./,
            filename: 'service-worker.js',
            minify: true,
            navigateFallback: PUBLIC_PATH,
            staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/]
        }),
        new WebpackPwaManifest({
            name: 'Mesopotamia Jones',
            short_name: 'Mesopotamia Jones',
            description: 'Learn to code while having fun!',
            background_color: '#ffffff',
            orientation: 'landscape',
            display: 'fullscreen',
            icons: [
                {
                    src: path.resolve('assets/images/favicon.png'),
                    sizes: [96, 128, 192, 256, 384, 512]
                }
            ]
        })
    ],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        alias: {
            'phaser-ce': phaser,
            pixi: pixi,
            p2: p2
        },
        extensions: ['.ts', '.tsx', '.js', 'png', 'json']
    },
    module: {
        rules: [
            {
                test: /pixi\.js/,
                use: ['expose-loader?PIXI']
            },
            {
                test: /phaser-split\.js$/,
                use: ['expose-loader?Phaser']
            },
            {
                test: /p2\.js/,
                use: ['expose-loader?p2']
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader']
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: ['file-loader']
            },
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: ['awesome-typescript-loader']
            }
        ]
    }
}
<|endoftext|>


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

module.exports = {
	entry: './src/main.jsx',
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js',
	},
	module: {
		loaders: [
			{ test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel?stage=0&optional=runtime&plugins=typecheck'] },
			{ test: /\.css$/, loader: 'style-loader!css-loader' },
			{ test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader', },
			{ test: /\.(jpg|png|svg|woff|woff2|ttf|eot)$/, loader: 'url-loader', options: { limit: 25000, }, },
		]
	},
	devtool: 'source-map',
	devServer: {
		contentBase: './dist',
	},
}
<commit_msg>forcing fallback to index so refreshes work locally<commit_after>var path = require('path')

module.exports = {
	entry: './src/main.jsx',
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js',
	},
	module: {
		loaders: [
			{ test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel?stage=0&optional=runtime&plugins=typecheck'] },
			{ test: /\.css$/, loader: 'style-loader!css-loader' },
			{ test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader', },
			{ test: /\.(jpg|png|svg|woff|woff2|ttf|eot)$/, loader: 'url-loader', options: { limit: 25000, }, },
		]
	},
	devtool: 'source-map',
	devServer: {
		contentBase: './dist',
		historyApiFallback: true,
	},
}
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: [
    '../post-it/app/client/index.js'
  ],
  output: {
    path: path.resolve(__dirname, './app/client/dist'),
    filename: 'index_bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
      // { test: /\.(css)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }), exclude: /node_modules/ },
      { test: /\.(scss)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader!sass-loader' }), exclude: /node_modules/ }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './app/client/index.html'
    }),
    new ExtractTextPlugin({
      filename: 'css/main.css',
      allChunks: true
    })
  ]
};
<commit_msg>Resoved a useless parameter from webpack config<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: [
    '../post-it/app/client/index.js'
  ],
  output: {
    path: path.resolve(__dirname, './app/client/dist'),
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
      // { test: /\.(css)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' }), exclude: /node_modules/ },
      { test: /\.(scss)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader!sass-loader' }), exclude: /node_modules/ }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './app/client/index.html'
    }),
    new ExtractTextPlugin({
      filename: 'css/main.css',
      allChunks: true
    })
  ]
};
<|endoftext|>


<commit_before>/*!
 * Finds the person of the week and displays their required data from OICR
 * Written by Joshua Ching and Raunaq Suri
*/
/*alert*/
$(document).ready(function() {

var csvList;
var DEFAULT_DATE = new Date("April 20, 2014");
var date = new Date();
var timeDiff = Math.abs(date.getTime() - DEFAULT_DATE.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)) - 1;

var indexOfNames = parseInt(diffDays / 7);
console.log("Index of Names: "+indexOfNames);

console.log("Day offset:" + diffDays);

$.ajax({
        type: "GET",
        url: "files/IBC List_2014_v1.csv",
        dataType: "text",
        async: false,
        success: function(data) {
            processIBClist(data);
        }
});

function processIBClist(data){
    "use strict";
    csvList = data;
}

//Gets all the names of the people
var names = [];
var positions = [];
var csvLines = csvList.split("\n");

for( var i = 0; i < csvLines.length; i++){
    var csvData = csvLines[i].split(",");
    names.push(csvData[1].trim());
    //console.log(names[i]);
    positions.push(csvData[3].trim());
    //console.log(positions[i]);
}

//console.log(names);

if (indexOfNames >= names.length){
    indexOfNames = indexOfNames % names.length;
}

//get person of the week name and display it
function getNameOfWeek(name){
    var nameSplit = name.split(" ");
    return nameSplit[1];
}

//PUB MED
var person=getNameOfWeek(names[indexOfNames]); //insert name of the person of the week here
var pubMedUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&term=+ontario+AND+institute+AND+cancer+AND+research +AND+" + person;

$.getJSON(pubMedUrl,function(data){
    var eSearchResult = data.esearchresult; //search result data object
    var pubCount = parseInt(eSearchResult.count); //number of publications
    var pubList = eSearchResult.idlist; //array of publication IDs

    //if pub count is less than or equal to 0
    if (pubCount <= 0){
        console.log("No publications");
    }
    //if pub count is less than or equal to 1
    else if(pubCount <= 1){
        console.log("Pub med: "+pubList[0]);
    }
    //if pub count is greater than 1
    else{
        console.log("Pub med #1: "+pubList[0]);
        console.log("Pub med #2: "+pubList[1]);
    }
});

function parsePaper(id){
    $.ajax({
        type: "GET",
        crossDomain: true,
        url: "http://www.ncbi.nlm.nih.gov/pubmed/"+id+"?report=xml&format=text",
        dataType: "jsonp",
        async: false,
        success: function(data) {
            var xmlDoc = $.parseXML(data);
            console.log(xmlDoc.find("ArticleTitle"));
            return true;

        }
});

}

$("#name").text(names[indexOfNames]);
$("#position").text(positions[indexOfNames]);
});

<commit_msg>now gets json<commit_after>/*!
 * Finds the person of the week and displays their required data from OICR
 * Written by Joshua Ching and Raunaq Suri
*/
/*alert*/
$(document).ready(function() {

var csvList;
var DEFAULT_DATE = new Date("April 20, 2014");
var date = new Date();
var timeDiff = Math.abs(date.getTime() - DEFAULT_DATE.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)) - 1;

var indexOfNames = parseInt(diffDays / 7);
console.log("Index of Names: "+indexOfNames);

console.log("Day offset:" + diffDays);

$.ajax({
        type: "GET",
        url: "files/IBC List_2014_v1.csv",
        dataType: "text",
        async: false,
        success: function(data) {
            processIBClist(data);
        }
});

//Parses the xml by first turning it into a json then going through it to return the title
function parsePaper(id){
    var articleUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&id="+ id;

    console.log(articleUrl);
    var title;
    getTitle();

    function getTitle(){
        $.ajax({

            url : articleUrl,
            type: 'get',
            dataType : 'json',
            async : true,
            success : function(data){
                processTitle(data, title);
            }
        });
    }
    return title;
}
function processTitle(json, title){
    var data = json;
    var result = data["result"]; //search result data object
    console.log(result);
    var pubid = result["uids"][0];
    console.log("PUB ID " + pubid);
    title = result[pubid]["title"];
}
function processIBClist(data){
    "use strict";
    csvList = data;
}

//Gets all the names of the people
var names = [];
var positions = [];
var csvLines = csvList.split("\n");

for( var i = 0; i < csvLines.length; i++){
    var csvData = csvLines[i].split(",");
    names.push(csvData[1].trim());
    //console.log(names[i]);
    positions.push(csvData[3].trim());
    //console.log(positions[i]);
}

//console.log(names);

if (indexOfNames >= names.length){
    indexOfNames = indexOfNames % names.length;
}

//get person of the week name and display it
function getNameOfWeek(name){
    var nameSplit = name.split(" ");
    return nameSplit[1];
}

//PUB MED
var person=getNameOfWeek(names[indexOfNames]); //insert name of the person of the week here
var pubMedUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&term=+ontario+AND+institute+AND+cancer+AND+research +AND+" + person;

$.getJSON(pubMedUrl,function(data){
    var eSearchResult = data.esearchresult; //search result data object
    var pubCount = parseInt(eSearchResult.count); //number of publications
    var pubList = eSearchResult.idlist; //array of publication IDs

    //if pub count is less than or equal to 0
    if (pubCount <= 0){
        console.log("No publications");
    }
    //if pub count is less than or equal to 1
    else if(pubCount <= 1){
        console.log("Pub med: "+pubList[0]);
    }
    //if pub count is greater than 1
    else{
        console.log("Pub med #1: "+pubList[0] + "parsed " + parsePaper(pubList[0]));
        console.log("Pub med #2: "+pubList[1]) + "parsed " + parsePaper(pubList[1]);
    }
});

$("#name").text(names[indexOfNames]);
$("#position").text(positions[indexOfNames]);
});

<|endoftext|>


<commit_before>'use strict';

var webpack = require('webpack')

var env = process.env.NODE_ENV

var config = {
  entry: './src/main.js',
  module: {
    loaders: [
      { test: /\.js$/, loaders: ['babel-loader'], exclude: [/node_modules/, `/test/sazerac-v0.2.2.js/`] }
    ]
  },
  output: {
    library: 'Sazerac',
    libraryTarget: 'umd'
  },
  plugins: []
}

if (env === 'prod') {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin()
  )
}

module.exports = config
<commit_msg>Adding name in define for require.js<commit_after>'use strict';

var webpack = require('webpack')

var env = process.env.NODE_ENV

var config = {
  entry: './src/main.js',
  module: {
    loaders: [
      { test: /\.js$/, loaders: ['babel-loader'], exclude: [/node_modules/, `/test/sazerac-v0.2.2.js/`] }
    ]
  },
  output: {
    library: 'Sazerac',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  plugins: []
}

if (env === 'prod') {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin()
  )
}

module.exports = config
<|endoftext|>


<commit_before>var VersionChecker = require('ember-cli-version-checker');

module.exports = {

  name: 'ember-gestures',

  normalizeEntityName: function() {},

  afterInstall: function() {
    var addon = this;
    var bowerPackages = [
      { name: 'hammer.js', target: '2.0.6' }
    ];
    var addonPackages = [
      { name: 'ember-hammertime', target: '1.0.0' }
    ];

    var checker = new VersionChecker(addon);
    if (checker.for('ember', 'bower').satisfies('>= 2.3')) {
      addonPackages.push({name: 'ember-getowner-polyfill', target: '^1.0.0'});
    }

    return addon.addBowerPackagesToProject(bowerPackages).then(function() {
      return addon.addAddonsToProject({ packages: addonPackages });
    });
  }
};
<commit_msg>ember-getOwner-polyfill fix<commit_after>var VersionChecker = require('ember-cli-version-checker');

module.exports = {

  name: 'ember-gestures',

  normalizeEntityName: function() {},

  afterInstall: function() {
    var addon = this;
    var bowerPackages = [
      { name: 'hammer.js', target: '2.0.6' }
    ];
    var addonPackages = [
      { name: 'ember-hammertime', target: '1.0.0' }
    ];

    var checker = new VersionChecker(addon);
    if (checker.forEmber().satisfies('>= 2.3') === false) {
      addonPackages.push({name: 'ember-getowner-polyfill', target: '^1.0.0'});
    }

    return addon.addBowerPackagesToProject(bowerPackages).then(function() {
      return addon.addAddonsToProject({ packages: addonPackages });
    });
  }
};
<|endoftext|>


<commit_before>/* Spy factory */
define(['./pages', 'log'], function (pages, log) {
    function Spy(frame) {  /*user, channel*/
        //IDS = url.parseQueryParams(frame.location).IDS,
        var infoLoaded = function () {
                var contentWindow = frame.contentWindow,
                    doc = contentWindow.document,
                    location = contentWindow.location,
                    url = location.origin + location.pathname,
                    page = pages.getByUrl(url),
                    result;

                if (page) {
                    // TODO: do something useful with the result
                    log('Analyzing ' + page.name);
                    result = page.analyze(doc);
                    log(result);
                }
            },
            isEnabled = false,
            enable = function (value) {
                var oldEnabled = isEnabled;

                // update the status (and convert to boolean, just in case)
                isEnabled = !!value;

                if (oldEnabled === isEnabled) {  // nothing to do
                    return;
                }

                // register or unregister the load event handler
                if (isEnabled) {
                    frame.addEventListener('load', infoLoaded, false);
                } else {
                    frame.removeEventListener('load', infoLoaded, false);
                }
            };

        // start enabled
        enable(true);

        return Object.freeze({
            get enabled() {
                return isEnabled;
            },
            set enabled(value) {
                enable(value);
            }
        });
    }

    return Spy;
});
<commit_msg>Fixed the spy modules imports<commit_after>/* Spy factory */
define(['./nainwak', 'log'], function (nainwak, log) {
    function Spy(frame) {  /*user, channel*/
        //IDS = url.parseQueryParams(frame.location).IDS,
        var infoLoaded = function () {
                var contentWindow = frame.contentWindow,
                    doc = contentWindow.document,
                    location = contentWindow.location,
                    url = location.origin + location.pathname,
                    page = nainwak.pages.byUrl(url),
                    result;

                if (page) {
                    // TODO: do something useful with the result
                    log('Analyzing ' + page.name);
                    result = page.analyze(doc);
                    log(result);
                }
            },
            isEnabled = false,
            enable = function (value) {
                var oldEnabled = isEnabled;

                // update the status (and convert to boolean, just in case)
                isEnabled = !!value;

                if (oldEnabled === isEnabled) {  // nothing to do
                    return;
                }

                // register or unregister the load event handler
                if (isEnabled) {
                    frame.addEventListener('load', infoLoaded, false);
                } else {
                    frame.removeEventListener('load', infoLoaded, false);
                }
            };

        // start enabled
        enable(true);

        return Object.freeze({
            get enabled() {
                return isEnabled;
            },
            set enabled(value) {
                enable(value);
            }
        });
    }

    return Spy;
});
<|endoftext|>


<commit_before>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var dashboard = angular.module('dashboard',['openlmis', 'ui.calendar', 'ui.bootstrap','easypiechart','ui.chart','ngTable','nsPopover']).config(['$routeProvider', function ($routeProvider) {

    $routeProvider.
        when('/dashboard', {controller: AdminDashboardController, templateUrl: 'partials/dashboard.html', resolve : ResolveDashboardFormData}).
       // when('/dashboard', {controller: DashboardProgramController, templateUrl: 'partials/dashboard-program.html', resolve : ResolveDashboardFormData}).
        when('/dashboard-new', {controller: DashboardProgramController, templateUrl: 'partials/dashboard-program.html', resolve : ResolveDashboardFormData}).
        when('/view-stock-detail/:programId/:periodId/:productId', {controller: StockController, templateUrl: 'partials/stock.html', resolve : ResolveDashboardFormData}).
        when('/stock', {controller: StockController, templateUrl: 'partials/stock.html', resolve : ResolveDashboardFormData }).
        when('/leadTime', {controller: ShipmentLeadTimeController, templateUrl: 'partials/shipment-lead-time.html', resolve : ResolveDashboardFormData }).
        when('/stock-out', {controller: StockedOutController, templateUrl: 'partials/stocked-out.html', resolve : ResolveDashboardFormData }).
        when('/district-stock-out/:programId/:periodId/:zoneId/:productId', {controller: DistrictStockedOutController, templateUrl: 'partials/requisition-group-stocked-out.html', resolve : ResolveDashboardFormData }).
        when('/stock-out-detail/:programId/:periodId/:zoneId/:productId', {controller: StockedOutDetailController, templateUrl: 'partials/stocked-out-detail.html', resolve : ResolveDashboardFormData }).
        when('/notifications/:programId/:periodId/:zoneId/:productId/:detailTable', {controller: NotificationsDetailController, templateUrl: 'partials/notifications-detail.html', resolve : ResolveDashboardFormData }).
        when('/notifications/:programId/:periodId/:zoneId/:detailTable', {controller: NotificationsDetailController, templateUrl: 'partials/notifications-detail.html', resolve : ResolveDashboardFormData }).

        when('/notifications', {controller: SendNotificationController, templateUrl: 'partials/send-notifications.html', resolve : ResolveDashboardFormData }).
        when('/rnr-status-summary', {controller: RequisitionStatusSummaryController, templateUrl: 'partials/rnr-status-summary.html', resolve : ResolveDashboardFormData }).
        when('/reporting-performance/program/:programId/period/:periodId', {controller: ReportingPerformanceDetailController, templateUrl: 'partials/reporting-performance-detail.html', resolve : ResolveDashboardFormData }).
        when('/rnr-status-report/program/:programId/period/:periodId', {controller: RnRStatusDetailsController, templateUrl: 'partials/rnr-status-details.html', resolve : ResolveDashboardFormData }).
        otherwise({redirectTo: '/dashboard'});
}]);

dashboard.directive('notificationDetail', function ($compile, $http, $templateCache) {

    var getTemplate = function(contentType) {
        var templateLoader,
            baseUrl = '/public/pages/dashboard/templates/';
        var templateUrl = baseUrl + contentType.toLowerCase()+'.html';
        templateLoader = $http.get(templateUrl, {cache: $templateCache});

        return templateLoader;
    };

    var linker = function(scope, element, attrs) {
        var loader = getTemplate(scope.content.tableName);
        var promise = loader.success(function(html) {
            element.html(html);
        }).error(function(){
            var defaultLoader = getTemplate('default_template');
            defaultLoader.success(function(html){
                element.html(html);
            }).then(function(response){
                element.replaceWith($compile(element.html())(scope));
            });
        }).then(function (response) {
            element.replaceWith($compile(element.html())(scope));
        });
    };

    return {
        restrict: "E",
        rep1ace: true,
        link: linker,
        scope: {
            content:'=ngModel'
        }
    };
});
<commit_msg>Adds C3 angular directive<commit_after>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
var dashboard = angular.module('dashboard',['openlmis', 'ui.calendar', 'ui.bootstrap','easypiechart','ui.chart','ngTable','nsPopover','gridshore.c3js.chart']).config(['$routeProvider', function ($routeProvider) {

    $routeProvider.
        when('/dashboard', {controller: AdminDashboardController, templateUrl: 'partials/dashboard.html', resolve : ResolveDashboardFormData}).
       // when('/dashboard', {controller: DashboardProgramController, templateUrl: 'partials/dashboard-program.html', resolve : ResolveDashboardFormData}).
        when('/dashboard-new', {controller: DashboardProgramController, templateUrl: 'partials/dashboard-program.html', resolve : ResolveDashboardFormData}).
        when('/view-stock-detail/:programId/:periodId/:productId', {controller: StockController, templateUrl: 'partials/stock.html', resolve : ResolveDashboardFormData}).
        when('/stock', {controller: StockController, templateUrl: 'partials/stock.html', resolve : ResolveDashboardFormData }).
        when('/leadTime', {controller: ShipmentLeadTimeController, templateUrl: 'partials/shipment-lead-time.html', resolve : ResolveDashboardFormData }).
        when('/stock-out', {controller: StockedOutController, templateUrl: 'partials/stocked-out.html', resolve : ResolveDashboardFormData }).
        when('/district-stock-out/:programId/:periodId/:zoneId/:productId', {controller: DistrictStockedOutController, templateUrl: 'partials/requisition-group-stocked-out.html', resolve : ResolveDashboardFormData }).
        when('/stock-out-detail/:programId/:periodId/:zoneId/:productId', {controller: StockedOutDetailController, templateUrl: 'partials/stocked-out-detail.html', resolve : ResolveDashboardFormData }).
        when('/notifications/:programId/:periodId/:zoneId/:productId/:detailTable', {controller: NotificationsDetailController, templateUrl: 'partials/notifications-detail.html', resolve : ResolveDashboardFormData }).
        when('/notifications/:programId/:periodId/:zoneId/:detailTable', {controller: NotificationsDetailController, templateUrl: 'partials/notifications-detail.html', resolve : ResolveDashboardFormData }).

        when('/notifications', {controller: SendNotificationController, templateUrl: 'partials/send-notifications.html', resolve : ResolveDashboardFormData }).
        when('/rnr-status-summary', {controller: RequisitionStatusSummaryController, templateUrl: 'partials/rnr-status-summary.html', resolve : ResolveDashboardFormData }).
        when('/reporting-performance/program/:programId/period/:periodId', {controller: ReportingPerformanceDetailController, templateUrl: 'partials/reporting-performance-detail.html', resolve : ResolveDashboardFormData }).
        when('/rnr-status-report/program/:programId/period/:periodId', {controller: RnRStatusDetailsController, templateUrl: 'partials/rnr-status-details.html', resolve : ResolveDashboardFormData }).
        otherwise({redirectTo: '/dashboard'});
}]);

dashboard.directive('notificationDetail', function ($compile, $http, $templateCache) {

    var getTemplate = function(contentType) {
        var templateLoader,
            baseUrl = '/public/pages/dashboard/templates/';
        var templateUrl = baseUrl + contentType.toLowerCase()+'.html';
        templateLoader = $http.get(templateUrl, {cache: $templateCache});

        return templateLoader;
    };

    var linker = function(scope, element, attrs) {
        var loader = getTemplate(scope.content.tableName);
        var promise = loader.success(function(html) {
            element.html(html);
        }).error(function(){
            var defaultLoader = getTemplate('default_template');
            defaultLoader.success(function(html){
                element.html(html);
            }).then(function(response){
                element.replaceWith($compile(element.html())(scope));
            });
        }).then(function (response) {
            element.replaceWith($compile(element.html())(scope));
        });
    };

    return {
        restrict: "E",
        rep1ace: true,
        link: linker,
        scope: {
            content:'=ngModel'
        }
    };
});
<|endoftext|>


<commit_before>/**
 * post-hover-tree.js
 *
 * Post hover tree. Because post-hover.js isn't russian enough.
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/settings.js';
 *   $config['additional_javascript'][] = 'js/post-hover-tree.js';
 *
 */

$(document).ready(function () {
    if (settings.postHover) {
        var hovering = false;
        var id;
        function init_hover_tree() {
            $("div.body > a, .mentioned > a").on({
                mouseenter: function() {
                    if(id = $(this).text().match(/^>>(\d+)$/)) {
                        $("#reply_" + id[1]).clone().addClass("hover")
                            .css({'position': 'absolute', 'top': $(this).offset().top+20, 'left': $(this).offset().left+20 })
                            .appendTo("body");
                        hovering = true;
                    } else {
                        hovering = false;
                        return;
                    }
                },
                mouseleave: function() {
                    $(".hover").hover(function() {
                        hovering = true;
                        $("#reply_" + id[1]).trigger(init_hover_tree());
                    }, function() {
                        hovering = false;
                    })
                }
            });
            $("html").mousemove(function() {
                if (!(hovering) && ($(".hover").is(":visible"))) {
                    setTimeout(function() {
                        $(".hover").remove();
                    }, 500);
                }
            })
            $("body").click(function(e) {
                if (!($(e.target).hasClass('hover'))) {
                    $(".hover").remove();
                }
            })
        }

        init_hover_tree(document);

        // allow to work with auto-reload.js, etc.
        $(document).bind('new_post', function(e, post) {
            init_hover_tree(post);
        });
    }
})<commit_msg>post-hover-tree.js: small refactor<commit_after>/**
 * post-hover-tree.js
 *
 * Post hover tree. Because post-hover.js isn't russian enough.
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/settings.js';
 *   $config['additional_javascript'][] = 'js/post-hover-tree.js';
 *
 */

$(document).ready(function () {
    if (settings.postHover) {
        var hovering = false;
        var id;

        // whatever this doesn't work anyway
        $("html *").click(function(e) {
            if ( e.target.className.indexOf("hover") < 0 ) {
                $(".hover").remove();
            }
        });

        function init_hover_tree() {
            $("div.body > a, .mentioned > a").on({
                mouseenter: function() {
                    if(id = $(this).text().match(/^>>(\d+)$/)) {
                        $("#reply_" + id[1]).clone().addClass("hover")
                            .css({'position': 'absolute', 'top': $(this).offset().top + 20, 'left': $(this).offset().left })
                            .appendTo("body");
                        hovering = true;
                    } else {
                        hovering = false;
                    }
                },
                mouseleave: function() {
                    $(".hover").hover(function() {
                        hovering = true;
                        $("#reply_" + id[1]).trigger(init_hover_tree());
                    }, function() {
                        hovering = false;
                    });

                    $("html").mousemove(function() {
                        if (!(hovering) && ($(".hover").is(":visible"))) {
                            setTimeout(function () {
                                $(".hover").remove();
                            }, 500);
                        }
                    })
                }
            });
        }

        init_hover_tree(document);

        // allow to work with auto-reload.js, etc.
        $(document).bind('new_post', function(e, post) {
            init_hover_tree(post);
        });
    }
})<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SourceMapFixPlugin = require("./webpack-ext/source-map-fix-webpack-plugin");

const PACKAGE = require("./package.json");
const BASE_URL = PACKAGE.homepage;
const SRC_PATH = path.resolve(__dirname, "src");
const CONTENT_PATH = path.resolve(__dirname, "public");

module.exports = function (env, { mode }) {

	const production = (mode === 'production');

	const config = {
		entry: {
			index: ["./src/index.tsx"],
		},
		output: {
			path: CONTENT_PATH,
			filename: "[name].js",
			publicPath: "/",
		},
		module: {
			rules: [
				{
					test: /\.pug$/,
					loader: "pug-loader"
				},
				{
					test: /\.[jt]sx?$/,
					exclude: /node_modules/,
					loader: "babel-loader"
				},
				{
					test: /\.scss$/,
					use: [
						MiniCssExtractPlugin.loader,
						{
							loader: 'css-loader',
							options: {
								modules: true,
								importLoaders: 2,
								...(production ? {} : { sourceMap: true })
							}
						},
						{
							loader: 'postcss-loader',
							options: {
								...(production ? {} : { sourceMap: true })
							}
						},
						{
							loader: 'sass-loader',
							options: {
								includePaths: [
									path.resolve(__dirname, "src/styles")
								],
								...(production ? {} : { sourceMap: true })
							}
						}
					]
				},
				{
					include: [CONTENT_PATH],
					type: 'javascript/auto',
					loader: "file-loader",
					options: {
						name: "[path][name].[ext]",
						outputPath: url => path.relative(CONTENT_PATH, url).replace(/\\/g, "/"),
						emitFile: false
					}
				},
				{
					test: /LICENSE$/,
					loader: "./webpack-ext/license-loader",
				}
			]
		},
		resolve: {
			modules: [SRC_PATH, "node_modules"],
			extensions: [".tsx", ".ts", ".js", ".json"],
			alias: {
				"project": __dirname,
				"assets": CONTENT_PATH
			},
		},
		resolveLoader: {
			plugins: [
				new SourceMapFixPlugin()
			]
		},
		plugins: [
			new MiniCssExtractPlugin({
				filename: "[name].css"
			}),
			new HtmlWebpackPlugin({
				template: "./src/index.pug",
				templateParameters: {
					process: { env: { NODE_ENV: mode } },
					baseUrl: BASE_URL,
				},
				inject: 'head'
			}),
			new ScriptExtHtmlWebpackPlugin({
				defaultAttribute: 'defer'
			}),
		]
	}

	if (env && env.serve) {
		Object.assign(config, {
			devServer: {
				contentBase: CONTENT_PATH,
				historyApiFallback: true,
				https: {
					key: fs.readFileSync("ssl/server.key"),
					cert: fs.readFileSync("ssl/server.crt"),
				},
			},
		});
	}

	return config;
}<commit_msg>ビルドの出力設定の変更<commit_after>const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SourceMapFixPlugin = require("./webpack-ext/source-map-fix-webpack-plugin");

const PACKAGE = require("./package.json");
const BASE_URL = PACKAGE.homepage;
const SRC_PATH = path.resolve(__dirname, "src");
const CONTENT_PATH = path.resolve(__dirname, "public");

module.exports = function (env, { mode }) {

	const production = (mode === 'production');

	const config = {
		stats: "minimal",
		entry: {
			index: ["./src/index.tsx"],
		},
		output: {
			path: CONTENT_PATH,
			filename: "[name].js",
			publicPath: "/",
		},
		module: {
			rules: [
				{
					test: /\.pug$/,
					loader: "pug-loader"
				},
				{
					test: /\.[jt]sx?$/,
					exclude: /node_modules/,
					loader: "babel-loader"
				},
				{
					test: /\.scss$/,
					use: [
						MiniCssExtractPlugin.loader,
						{
							loader: 'css-loader',
							options: {
								modules: true,
								importLoaders: 2,
								...(production ? {} : { sourceMap: true })
							}
						},
						{
							loader: 'postcss-loader',
							options: {
								...(production ? {} : { sourceMap: true })
							}
						},
						{
							loader: 'sass-loader',
							options: {
								includePaths: [
									path.resolve(__dirname, "src/styles")
								],
								...(production ? {} : { sourceMap: true })
							}
						}
					]
				},
				{
					include: [CONTENT_PATH],
					type: 'javascript/auto',
					loader: "file-loader",
					options: {
						name: "[path][name].[ext]",
						outputPath: url => path.relative(CONTENT_PATH, url).replace(/\\/g, "/"),
						emitFile: false
					}
				},
				{
					test: /LICENSE$/,
					loader: "./webpack-ext/license-loader",
				}
			]
		},
		resolve: {
			modules: [SRC_PATH, "node_modules"],
			extensions: [".tsx", ".ts", ".js", ".json"],
			alias: {
				"project": __dirname,
				"assets": CONTENT_PATH
			},
		},
		resolveLoader: {
			plugins: [
				new SourceMapFixPlugin()
			]
		},
		plugins: [
			new MiniCssExtractPlugin({
				filename: "[name].css"
			}),
			new HtmlWebpackPlugin({
				template: "./src/index.pug",
				templateParameters: {
					process: { env: { NODE_ENV: mode } },
					baseUrl: BASE_URL,
				},
				inject: 'head'
			}),
			new ScriptExtHtmlWebpackPlugin({
				defaultAttribute: 'defer'
			}),
		]
	}

	if (env && env.serve) {
		Object.assign(config, {
			devServer: {
				contentBase: CONTENT_PATH,
				historyApiFallback: true,
				https: {
					key: fs.readFileSync("ssl/server.key"),
					cert: fs.readFileSync("ssl/server.crt"),
				},
			},
		});
	}

	return config;
}<|endoftext|>


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

const sourcePath = path.join(__dirname, './src');
const staticsPath = path.join(__dirname, './dist');

module.exports = function(env) {
  const nodeEnv = env && env.prod ? 'production' : 'development';
  const isProd = nodeEnv === 'production';
  const plugins = [
    new webpack
    .optimize
    .CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity,
      filename: 'vendor.bundle.js'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv)
      }
    }),
    new webpack.NamedModulesPlugin()
  ];

  if (isProd) {
    const loaderOptionsPlugin = new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    });
    const uglifyJsPlugin = new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true
      },
      output: {
        comments: false
      }
    });
    plugins.push(loaderOptionsPlugin, uglifyJsPlugin);
  } else {
    plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  return {
    devtool: isProd ? 'source-map' : 'source-map',
    context: sourcePath,
    entry: {
      js: './index.js',
      vendor: ['react']
    },
    output: {
      path: staticsPath,
      filename: '[name].bundle.js'
    },
    module: {
      rules: [{
        test: /\.html$/,
        exclude: /node_modules/,
        use: {
          loader: 'file-loader',
          query: {
            name: '[name].[ext]'
          }
        }
      }, {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }, {
        test: /\.(js|jsx)$/,
        exclude: /node_modules\/(?!n3000)/,
        loader: 'babel-loader',
        query: {
          presets: [
            'babel-preset-es2015',
            'babel-preset-react'
          ].map(require.resolve),
        }
      }, {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }, {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: ['url-loader?limit=10000', 'img-loader?minimize']
      }]
    },
    resolve: {
      extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx', '.scss', '.css'],
      modules: [
        path.resolve(__dirname, 'node_modules'),
        sourcePath
      ]
    },
    plugins,
    performance: isProd && {
      maxAssetSize: 100,
      maxEntrypointSize: 300,
      hints: 'warning'
    },
    stats: {
      colors: {
        green: '\u001b[32m'
      }
    },
    devServer: {
      contentBase: './src',
      historyApiFallback: true,
      port: 3000,
      compress: isProd,
      inline: !isProd,
      hot: !isProd,
      proxy: {
        '/api': {
          target: 'http://rockplus.com.dev:8080',
          changeOrigin: true,
          secure: false
        }
      },
      stats: {
        assets: true,
        children: false,
        chunks: false,
        hash: false,
        modules: false,
        publicPath: false,
        timings: true,
        version: false,
        warnings: true,
        colors: {
          green: '\u001b[32m'
        }
      }
    }
  };
};<commit_msg>fixed build<commit_after>const webpack = require('webpack');
const path = require('path');

const sourcePath = path.join(__dirname, './src');
const staticsPath = path.join(__dirname, './dist');

module.exports = function(env) {
  const nodeEnv = env && env.prod ? 'production' : 'development';
  const isProd = nodeEnv === 'production';
  const plugins = [
    new webpack
    .optimize
    .CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity,
      filename: 'vendor.bundle.js'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv)
      }
    }),
    new webpack.NamedModulesPlugin()
  ];

  if (isProd) {
    const loaderOptionsPlugin = new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    });
    const uglifyJsPlugin = new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true
      },
      output: {
        comments: false
      }
    });
    plugins.push(loaderOptionsPlugin, uglifyJsPlugin);
  } else {
    plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  return {
    devtool: isProd ? 'source-map' : 'source-map',
    context: sourcePath,
    entry: {
      js: './index.js',
      vendor: ['react']
    },
    output: {
      path: staticsPath,
      filename: '[name].bundle.js'
    },
    module: {
      rules: [{
        test: /\.html$/,
        exclude: /node_modules/,
        use: {
          loader: 'file-loader',
          query: {
            name: '[name].[ext]'
          }
        }
      }, {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }, {
        test: /\.(js|jsx)$/,
        exclude: /node_modules\/(?!cms\-core|auto\-bind)/,
        loader: 'babel-loader',
        query: {
          presets: [
            'babel-preset-es2015',
            'babel-preset-react'
          ].map(require.resolve),
        }
      }, {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }, {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: ['url-loader?limit=10000', 'img-loader?minimize']
      }]
    },
    resolve: {
      extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx', '.scss', '.css'],
      modules: [
        path.resolve(__dirname, 'node_modules'),
        sourcePath
      ]
    },
    plugins,
    performance: isProd && {
      maxAssetSize: 100,
      maxEntrypointSize: 300,
      hints: 'warning'
    },
    stats: {
      colors: {
        green: '\u001b[32m'
      }
    },
    devServer: {
      contentBase: './src',
      historyApiFallback: true,
      port: 3000,
      compress: isProd,
      inline: !isProd,
      hot: !isProd,
      proxy: {
        '/api': {
          target: 'http://rockplus.com.dev:8080',
          changeOrigin: true,
          secure: false
        }
      },
      stats: {
        assets: true,
        children: false,
        chunks: false,
        hash: false,
        modules: false,
        publicPath: false,
        timings: true,
        version: false,
        warnings: true,
        colors: {
          green: '\u001b[32m'
        }
      }
    }
  };
};<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build'),
};

const commonConfig = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: PATHS.build,
    filename: '[name].js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo',
    }),
  ],
};

const productionConfig = () => commonConfig;

const developmentConfig = () => {
  const config = {
    devServer: {
      // Enable history API fallback so HTML5 History API based
      // routing works. Good for complex setups.
      historyApiFallback: true,

      // Display only errors to reduce the amount of output.
      stats: 'errors-only',

      // Parse host and port from env to allow customization.
      //
      // If you use Docker, Vagrant or Cloud9, set
      // host: options.host || '0.0.0.0';
      //
      // 0.0.0.0 is available to all network devices
      // unlike default `localhost`.
      host: process.env.HOST, // Defaults to `localhost`
      port: process.env.PORT, // Defaults to 8080
    },
  };

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

module.exports = (env) => {
  if (env === 'production') {
    return productionConfig();
  }

  return developmentConfig();
};<commit_msg>Connecting ESLint with webpack<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build'),
};

const commonConfig = {
  entry: {
    app: PATHS.app,
  },
  output: {
    path: PATHS.build,
    filename: '[name].js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo',
    }),
  ],
};

const productionConfig = () => commonConfig;

const developmentConfig = () => {
  const config = {
    devServer: {
      // Enable history API fallback so HTML5 History API based
      // routing works. Good for complex setups.
      historyApiFallback: true,

      // Display only errors to reduce the amount of output.
      stats: 'errors-only',

      // Parse host and port from env to allow customization.
      //
      // If you use Docker, Vagrant or Cloud9, set
      // host: options.host || '0.0.0.0';
      //
      // 0.0.0.0 is available to all network devices
      // unlike default `localhost`.
      host: process.env.HOST, // Defaults to `localhost`
      port: process.env.PORT, // Defaults to 8080
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          enforce: 'pre',
          loader: 'eslint-loader',
          options: {
            emitWarning: true,
          },
        },
      ],
    },
  };

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

module.exports = (env) => {
  if (env === 'production') {
    return productionConfig();
  }

  return developmentConfig();
};<|endoftext|>


<commit_before>/**
 * Class which handles individual tabs
 */
var Tab = Backbone.View.extend({
    tagName: 'li',

    events: {
        'click a': 'select',
        'mousedown a': 'remove',
        'click span': 'remove'
    },

    template: function() {
        // Generate caption
        var caption = '';
        if (this.content && this.content.query && this.content.query.name) {
            caption = this.content.query.name;
        } else {
            caption = "Unsaved query (" + this.parent.queryCount + ")";
        }

        // Create tab
        return _.template("<a href='#<%= id %>'><%= caption %>" +
                "Close tab")
            ({
                id: this.id,
                caption: caption
            });
    },

    /**
     * Assign a unique ID and assign a Backbone view
     * to handle the tab's contents
     * @param args
     */
    initialize: function(args) {
        _.extend(this, Backbone.Events);

        this.content = args && args.content ?
                args.content : new Workspace({ tab: this });
        this.id = _.uniqueId('tab_');
    },

    /**
     * Render the tab and its contents
     * @returns tab
     */
    render: function() {
        // Render the content
        this.content.render();

        // Generate the element
        $(this.el).html(this.template());

        return this;
    },

    /**
     * Destroy any data associated with this tab and ensure proper
     * garbage collection to avoid memory leaks
     */
    destroy: function() {
        // Delete data
        this.content && this.content.query && this.content.query.destroy();
    },

    /**
     * Select a tab
     * @param el
     */
    select: function() {
        // Deselect all tabs
        this.parent.select(this);

        // Select the selected tab
        $(this.el).addClass('selected');

        // Trigger select event
        this.trigger('tab:select');

        return false;
    },

    /**
     * Remove a tab
     * @returns {Boolean}
     */
    remove: function(event) {
        if (!event || event.which === 2) {
            // Remove the tab element
            $(this.el).remove();

            // Remove the tab
            this.destroy();

            // Remote the tab object from the container
            this.parent.remove(this);
        }

        return false;
    }
});

/**
 * Class which controls the tab collection
 */
var TabSet = Backbone.View.extend({
    className: 'tabs',
    queryCount: 0,

    _tabs: [],

    /**
     * Render the tab containers
     * @returns tab_container
     */
    render: function() {
        $(this.el).html('

')
            .appendTo($('#header'));
        this.content = $('
').appendTo($('body'));
        return this;
    },

    /**
     * Add a tab to the collection
     * @param tab
     */
    add: function(tab) {
        // Add it to the set
        this._tabs.push(tab);
        this.queryCount++;
        tab.parent = this;

        // Render it in the background, then select it
        tab.render().select();
        $(tab.el).appendTo($(this.el).find('ul'));

        // Trigger 'render' event
        tab.trigger('tab:rendered', { tab: tab });

        // Trigger add event on session
        Saiku.session.trigger('tab:add', { tab: tab });
    },

    /**
     * Select a tab, and move its contents to the tab panel
     * @param tab
     */
    select: function(tab) {
        // Clear selections
        $(this.el).find('li').removeClass('selected');

        // Replace the contents of the tab panel with the new content
        this.content.children().detach();
        this.content.append(tab.content.el);
    },

    /**
     * Remove a tab from the collection
     * @param tab
     */
    remove: function(tab) {
        for (var i = 0; i < this._tabs.length; i++) {
            if (this._tabs[i] == tab) {
                // Remove the element
                this._tabs.splice(i, 1);

                // Add another tab if the last one has been deleted
                if (this._tabs.length == 0) {
                    this.add(new Tab);
                }

                // Select the previous, or first tab
                var next = this._tabs[i] ? i : 0;
                this._tabs[next].select();
            }
        }
    }
});<commit_msg>Fixed close tab button<commit_after>/**
 * Class which handles individual tabs
 */
var Tab = Backbone.View.extend({
    tagName: 'li',

    events: {
        'click a': 'select',
        'mousedown a': 'remove',
        'click .close_tab': 'remove'
    },

    template: function() {
        // Generate caption
        var caption = '';
        if (this.content && this.content.query && this.content.query.name) {
            caption = this.content.query.name;
        } else {
            caption = "Unsaved query (" + this.parent.queryCount + ")";
        }

        // Create tab
        return _.template("<a href='#<%= id %>'><%= caption %>" +
                "Close tab")
            ({
                id: this.id,
                caption: caption
            });
    },

    /**
     * Assign a unique ID and assign a Backbone view
     * to handle the tab's contents
     * @param args
     */
    initialize: function(args) {
        _.extend(this, Backbone.Events);

        this.content = args && args.content ?
                args.content : new Workspace({ tab: this });
        this.id = _.uniqueId('tab_');
    },

    /**
     * Render the tab and its contents
     * @returns tab
     */
    render: function() {
        // Render the content
        this.content.render();

        // Generate the element
        $(this.el).html(this.template());

        return this;
    },

    /**
     * Destroy any data associated with this tab and ensure proper
     * garbage collection to avoid memory leaks
     */
    destroy: function() {
        // Delete data
        this.content && this.content.query && this.content.query.destroy();
    },

    /**
     * Select a tab
     * @param el
     */
    select: function() {
        // Deselect all tabs
        this.parent.select(this);

        // Select the selected tab
        $(this.el).addClass('selected');

        // Trigger select event
        this.trigger('tab:select');

        return false;
    },

    /**
     * Remove a tab
     * @returns {Boolean}
     */
    remove: function(event) {
        if (!event || event.which === 2 || $(event.target).hasClass('close_tab')) {
            // Remove the tab element
            $(this.el).remove();

            // Remove the tab
            this.destroy();

            // Remote the tab object from the container
            this.parent.remove(this);
        }

        return false;
    }
});

/**
 * Class which controls the tab collection
 */
var TabSet = Backbone.View.extend({
    className: 'tabs',
    queryCount: 0,

    _tabs: [],

    /**
     * Render the tab containers
     * @returns tab_container
     */
    render: function() {
        $(this.el).html('

')
            .appendTo($('#header'));
        this.content = $('
').appendTo($('body'));
        return this;
    },

    /**
     * Add a tab to the collection
     * @param tab
     */
    add: function(tab) {
        // Add it to the set
        this._tabs.push(tab);
        this.queryCount++;
        tab.parent = this;

        // Render it in the background, then select it
        tab.render().select();
        $(tab.el).appendTo($(this.el).find('ul'));

        // Trigger 'render' event
        tab.trigger('tab:rendered', { tab: tab });

        // Trigger add event on session
        Saiku.session.trigger('tab:add', { tab: tab });
    },

    /**
     * Select a tab, and move its contents to the tab panel
     * @param tab
     */
    select: function(tab) {
        // Clear selections
        $(this.el).find('li').removeClass('selected');

        // Replace the contents of the tab panel with the new content
        this.content.children().detach();
        this.content.append(tab.content.el);
    },

    /**
     * Remove a tab from the collection
     * @param tab
     */
    remove: function(tab) {
        for (var i = 0; i < this._tabs.length; i++) {
            if (this._tabs[i] == tab) {
                // Remove the element
                this._tabs.splice(i, 1);

                // Add another tab if the last one has been deleted
                if (this._tabs.length == 0) {
                    this.add(new Tab);
                }

                // Select the previous, or first tab
                var next = this._tabs[i] ? i : 0;
                this._tabs[next].select();
            }
        }
    }
});<|endoftext|>


<commit_before>var DataHandler = function (url) {
	this.websocketUrl = url;
	this.websocket = null;
	this.handlers = {};
	this.queue = [];
};

DataHandler.prototype.connect = function () {
	if (this.websocket === null || this.websocket.readyState == WebSocket.CLOSED) {
		this.websocket = new WebSocket(this.websocketUrl);

		var handler = this;

		this.websocket.onopen = function () {
			handler.onOpen();
		};

		this.websocket.onmessage = function (e) {
			handler.onMessage(e);
		};

		this.websocket.onclose = function () {
			handler.onClose();
		};

		this.websocket.onerror = function (e) {
			handler.onError(e);
		};
	}
};

DataHandler.prototype.onError = function (e) {
	console.log(e);

	if ("error" in this.handlers) {
		this.handlers["error"]();
	}
};

DataHandler.prototype.onOpen = function () {
	console.debug("DataHandler::onOpen");

	var queue = this.queue;
	this.queue = [];

	if (queue.length !== 0) {
		this.send("lost-push", queue);
	}

	if ("open" in this.handlers) {
		this.handlers["open"]();
	}
};

DataHandler.prototype.onMessage = function (e) {
	if (document.getElementById("rooms") === null) { // TODO: Cache this, move away from here...
		document.getElementById("page").innerHTML = templateManager.get("chat")(user);

		var input = document.getElementById("input");
		input.focus();

		autocomplete(input);

		input.addEventListener("input", function (e) {
			var message = parseInt(this.getAttribute("data-message"));

			if (this.value === "" && (message || 0) === 0) {
				this.removeAttribute("data-compose");
				this.setAttribute("data-message", "0");
			} else {
				this.setAttribute("data-compose", "1");
			}

			adjustInput(this);
		});

		input.addEventListener("keydown", function (e) {
			if (e.which == 37 || e.which == 39) {
				input.setAttribute("data-compose", "1");
				return;
			}

			if (e.which == 13 && e.shiftKey) {
				e.preventDefault();

				input.setAttribute("data-compose", "1");

				var start = this.selectionStart;
				var end = this.selectionEnd;
				var value = this.value;
				var indent = "";
				var last_new_line = value.lastIndexOf("\n");

				if (last_new_line > 0) {
					indent = value.substring(last_new_line + 1);
				} else {
					indent = value;
				}

				indent = indent.replace(/(\S.*)/, "");

				this.value = value.substring(0, start) + "\n" + indent + value.substring(end);
				this.selectionStart = this.selectionEnd = start + 1 + indent.length;

				adjustInput(this);

				return false;
			}

			if (e.which == 13) {
				e.preventDefault();

				var text = input.value;
				var room = document.getElementsByClassName("room-current")[0].getAttribute("data-id");

				if (text === "") {
					return;
				}

				var tempId = generateToken(20);
				var editMessage = parseInt(input.getAttribute("data-message"));
				var node = roomHandler.getRoom(room);

				if (editMessage > 0) {
					var shouldScroll = node.scrollTop === node.scrollHeight - node.clientHeight;

					if (text === messageHandler.getDOM(editMessage).getAttribute("data-text")) {
						input.setAttribute("data-message", "0");
						input.value = "";
						input.focus();
						return;
					}

					var messageNode = messageHandler.getDOM(editMessage);
					messageNode.classList.add("chat-message-pending");
					messageNode.setAttribute("data-edit-id", tempId.toString());

					formatter.formatMessage(messageNode.querySelector(".chat-message-text"), text, null, user);
					this.removeAttribute("data-compose");

					dataHandler.send("message-edit", {
						messageId: +editMessage,
						text: text,
						tempId: tempId
					});

					if (shouldScroll) {
						node.scrollTop = node.scrollHeight;
					}
				} else {
					dataHandler.send("message", {
						roomId: +room,
						text: text,
						tempId: tempId
					});

					var message = nodeFromHTML(templateManager.get("chat_message")({
						tempId: tempId,
						roomId: +room,
						messageText: text,
						user: {
							id: user.id,
							name: user.name,
							avatar: user.imageUrl
						},
						stars: 0,
						starred: false,
						time: +moment() / 1000
					}));

					formatter.formatMessage(message.querySelector(".chat-message-text"), text, null, user);

					message.querySelector("time").textContent = moment().fromNow();
					message.querySelector("time").setAttribute("title", moment().format("LLL"));

					message.classList.add("chat-message-me");
					message.setAttribute("data-text", text);

					var prev = messageHandler.getDOM(roomHandler.rooms[room].lastMessage);

					if (prev && prev.getAttribute("data-author") == user.id
						&& +moment(prev.querySelector("time").getAttribute("datetime")) / 1000 > message.time - 60) {
						message.classList.add("chat-message-followup");
					}

					node.appendChild(message);
					node.scrollTop = node.scrollHeight;
				}

				input.removeAttribute("data-compose");
				input.setAttribute("data-message", "0");
				input.value = "";

				adjustInput(input);

				input.focus();

				return false;
			}

			else if (e.which == 38) {
				if (input.getAttribute("data-compose")) {
					return;
				}

				e.preventDefault();

				var editMessage = +input.getAttribute("data-message");

				var message;

				if (editMessage > 0) {
					message = window.prev(messageHandler.getDOM(editMessage), ".chat-message-me");
				} else {
					var nodes = document.querySelectorAll(".room-current .chat-message-me");
					message = nodes[nodes.length - 1];
				}

				if (message !== null) {
					if (+moment(message.querySelector("time").getAttribute("datetime")) / 1000 > +moment() / 1000 - 5 * 60) {
						input.value = message.getAttribute("data-text");
						input.setAttribute("data-message", message.getAttribute("data-id"));

						var caretPos = message.getAttribute("data-text").length;
						if (input.createTextRange) {
							var range = input.createTextRange();
							range.move('character', caretPos);
							range.select();
						} else {
							if (input.selectionStart) {
								input.setSelectionRange(caretPos, caretPos);
							}
						}
					} else {
						// FIXME: toastr.info('Previous message is older than 5 minutes and cannot be edited!');
						alert('Previous message is older than 5 minutes and cannot be edited!');
					}
				}

				adjustInput(input);

				return false;
			}

			else if (e.which == 40) {
				if (input.hasAttribute("data-compose")) {
					return;
				}

				e.preventDefault();

				var editMessage = parseInt(input.getAttribute("data-message"));

				var message = editMessage > 0
					? window.next(messageHandler.getDOM(editMessage), ".chat-message-me") // FIXME: replace next
					: null;

				if (message !== null) {
					input.value = message.getAttribute("data-text");
					input.setAttribute("data-message", message.getAttribute("data-id"));

					var caretPos = message.getAttribute("data-text").length;
					if (input.createTextRange) {
						var range = input.createTextRange();
						range.move('character', caretPos);
						range.select();
					} else {
						if (input.selectionStart) {
							input.setSelectionRange(caretPos, caretPos);
						}
					}
				} else {
					input.removeAttribute("data-compose");
					input.setAttribute("data-message", "0");
					input.value = "";
				}

				adjustInput(input);

				return false;
			}

			else if (e.which == 27) { // escape
				e.preventDefault();
				input.removeAttribute("data-compose");
				input.setAttribute("data-message", "0");
				input.value = "";
				adjustInput(input);

				return false;
			}

			else if (e.which == 9) { // tab
				e.preventDefault();

				var start = this.selectionStart;
				var end = this.selectionEnd;
				var value = this.value;
				var before = value.substr(0, start);
				var after = value.substr(end);

				if (start === end) {
					this.value = before + "\t" + after;
					this.selectionStart = this.selectionEnd = start + 1;
				} else {
					var selectStart = start;

					var line_before = before.substr(0, Math.max(0, before.lastIndexOf("\n") + 1));
					var line_after = after.substr(Math.max(0, after.indexOf("\n")));
					var text_to_indent = before.substr(Math.max(0, before.lastIndexOf("\n") + 1))
						+ value.substring(start, end)
						+ after.substr(0, Math.max(0, after.indexOf("\n")));

					if (e.shiftKey) {
						selectStart -= /(^|\n)(\t| {0,4})/g.exec(text_to_indent)[2].length;

						text_to_indent = text_to_indent.replace(/(^|\n)(\t| {0,4})/g, "\n");

						if (text_to_indent.indexOf("\n") === 0) { // TODO: Just get first char and compare
							text_to_indent = text_to_indent.substr(1);
						}

						this.value = line_before + text_to_indent + line_after;
					} else {
						selectStart++;

						this.value = line_before + "\t" + text_to_indent.replace(/\n/g, "\n\t") + line_after;
					}

					this.selectionStart = selectStart;
					this.selectionEnd = this.value.length - after.length;
				}
			}
		});
	}

	var payload = null;

	try {
		payload = JSON.parse(e.data);
	} catch (e) {
		alert(e);
		console.log(e);
	}

	if (payload == null || !"type" in payload || !"data" in payload) {
		return;
	}

	console.log("in", payload.type, payload.data);

	if (payload.type in this.handlers) {
		this.handlers[payload.type](payload.type, payload.data);
	} else {
		console.info("No handler has been registered for that type: " + payload.type);
	}
};

DataHandler.prototype.onClose = function () {
	console.debug("DataHandler::onClose");

	if ("close" in this.handlers) {
		this.handlers["close"]();
	}

	var handler = this;

	setTimeout(function () {
		handler.connect();
	}, 3000);
};

DataHandler.prototype.on = function (type, callback) {
	this.handlers[type] = callback;
};

DataHandler.prototype.send = function (type, data) {
	if (this.websocket.readyState === WebSocket.OPEN) {
		this.websocket.send(JSON.stringify({type: type, data: data}));
		console.log("out", type, data);
	} else {
		var handler = this;

		if (type === "lost-push") {
			forEach(data, function (i, o) {
				handler.queue.push(o);
			});
		} else {
			handler.queue.push({type: type, data: data});
		}
	}
};
<commit_msg>Allow selection with arrow keys<commit_after>var DataHandler = function (url) {
	this.websocketUrl = url;
	this.websocket = null;
	this.handlers = {};
	this.queue = [];
};

DataHandler.prototype.connect = function () {
	if (this.websocket === null || this.websocket.readyState == WebSocket.CLOSED) {
		this.websocket = new WebSocket(this.websocketUrl);

		var handler = this;

		this.websocket.onopen = function () {
			handler.onOpen();
		};

		this.websocket.onmessage = function (e) {
			handler.onMessage(e);
		};

		this.websocket.onclose = function () {
			handler.onClose();
		};

		this.websocket.onerror = function (e) {
			handler.onError(e);
		};
	}
};

DataHandler.prototype.onError = function (e) {
	console.log(e);

	if ("error" in this.handlers) {
		this.handlers["error"]();
	}
};

DataHandler.prototype.onOpen = function () {
	console.debug("DataHandler::onOpen");

	var queue = this.queue;
	this.queue = [];

	if (queue.length !== 0) {
		this.send("lost-push", queue);
	}

	if ("open" in this.handlers) {
		this.handlers["open"]();
	}
};

DataHandler.prototype.onMessage = function (e) {
	if (document.getElementById("rooms") === null) { // TODO: Cache this, move away from here...
		document.getElementById("page").innerHTML = templateManager.get("chat")(user);

		var input = document.getElementById("input");
		input.focus();

		autocomplete(input);

		input.addEventListener("input", function (e) {
			var message = parseInt(this.getAttribute("data-message"));

			if (this.value === "" && (message || 0) === 0) {
				this.removeAttribute("data-compose");
				this.setAttribute("data-message", "0");
			} else {
				this.setAttribute("data-compose", "1");
			}

			adjustInput(this);
		});

		input.addEventListener("keydown", function (e) {
			if (e.which == 37 || e.which == 39) {
				input.setAttribute("data-compose", "1");
				return;
			}

			if (e.which == 13 && e.shiftKey) {
				e.preventDefault();

				input.setAttribute("data-compose", "1");

				var start = this.selectionStart;
				var end = this.selectionEnd;
				var value = this.value;
				var indent = "";
				var last_new_line = value.lastIndexOf("\n");

				if (last_new_line > 0) {
					indent = value.substring(last_new_line + 1);
				} else {
					indent = value;
				}

				indent = indent.replace(/(\S.*)/, "");

				this.value = value.substring(0, start) + "\n" + indent + value.substring(end);
				this.selectionStart = this.selectionEnd = start + 1 + indent.length;

				adjustInput(this);

				return false;
			}

			if (e.which == 13) {
				e.preventDefault();

				var text = input.value;
				var room = document.getElementsByClassName("room-current")[0].getAttribute("data-id");

				if (text === "") {
					return;
				}

				var tempId = generateToken(20);
				var editMessage = parseInt(input.getAttribute("data-message"));
				var node = roomHandler.getRoom(room);

				if (editMessage > 0) {
					var shouldScroll = node.scrollTop === node.scrollHeight - node.clientHeight;

					if (text === messageHandler.getDOM(editMessage).getAttribute("data-text")) {
						input.setAttribute("data-message", "0");
						input.value = "";
						input.focus();
						return;
					}

					var messageNode = messageHandler.getDOM(editMessage);
					messageNode.classList.add("chat-message-pending");
					messageNode.setAttribute("data-edit-id", tempId.toString());

					formatter.formatMessage(messageNode.querySelector(".chat-message-text"), text, null, user);
					this.removeAttribute("data-compose");

					dataHandler.send("message-edit", {
						messageId: +editMessage,
						text: text,
						tempId: tempId
					});

					if (shouldScroll) {
						node.scrollTop = node.scrollHeight;
					}
				} else {
					dataHandler.send("message", {
						roomId: +room,
						text: text,
						tempId: tempId
					});

					var message = nodeFromHTML(templateManager.get("chat_message")({
						tempId: tempId,
						roomId: +room,
						messageText: text,
						user: {
							id: user.id,
							name: user.name,
							avatar: user.imageUrl
						},
						stars: 0,
						starred: false,
						time: +moment() / 1000
					}));

					formatter.formatMessage(message.querySelector(".chat-message-text"), text, null, user);

					message.querySelector("time").textContent = moment().fromNow();
					message.querySelector("time").setAttribute("title", moment().format("LLL"));

					message.classList.add("chat-message-me");
					message.setAttribute("data-text", text);

					var prev = messageHandler.getDOM(roomHandler.rooms[room].lastMessage);

					if (prev && prev.getAttribute("data-author") == user.id
						&& +moment(prev.querySelector("time").getAttribute("datetime")) / 1000 > message.time - 60) {
						message.classList.add("chat-message-followup");
					}

					node.appendChild(message);
					node.scrollTop = node.scrollHeight;
				}

				input.removeAttribute("data-compose");
				input.setAttribute("data-message", "0");
				input.value = "";

				adjustInput(input);

				input.focus();

				return false;
			}

			else if (e.which == 38 && !e.shiftKey) {
				if (input.getAttribute("data-compose")) {
					return;
				}

				e.preventDefault();

				var editMessage = +input.getAttribute("data-message");

				var message;

				if (editMessage > 0) {
					message = window.prev(messageHandler.getDOM(editMessage), ".chat-message-me");
				} else {
					var nodes = document.querySelectorAll(".room-current .chat-message-me");
					message = nodes[nodes.length - 1];
				}

				if (message !== null) {
					if (+moment(message.querySelector("time").getAttribute("datetime")) / 1000 > +moment() / 1000 - 5 * 60) {
						input.value = message.getAttribute("data-text");
						input.setAttribute("data-message", message.getAttribute("data-id"));

						var caretPos = message.getAttribute("data-text").length;
						if (input.createTextRange) {
							var range = input.createTextRange();
							range.move('character', caretPos);
							range.select();
						} else {
							if (input.selectionStart) {
								input.setSelectionRange(caretPos, caretPos);
							}
						}
					} else {
						// FIXME: toastr.info('Previous message is older than 5 minutes and cannot be edited!');
						alert('Previous message is older than 5 minutes and cannot be edited!');
					}
				}

				adjustInput(input);

				return false;
			}

			else if (e.which == 40 && !e.shiftKey) {
				if (input.hasAttribute("data-compose")) {
					return;
				}

				e.preventDefault();

				var editMessage = parseInt(input.getAttribute("data-message"));

				var message = editMessage > 0
					? window.next(messageHandler.getDOM(editMessage), ".chat-message-me") // FIXME: replace next
					: null;

				if (message !== null) {
					input.value = message.getAttribute("data-text");
					input.setAttribute("data-message", message.getAttribute("data-id"));

					var caretPos = message.getAttribute("data-text").length;
					if (input.createTextRange) {
						var range = input.createTextRange();
						range.move('character', caretPos);
						range.select();
					} else {
						if (input.selectionStart) {
							input.setSelectionRange(caretPos, caretPos);
						}
					}
				} else {
					input.removeAttribute("data-compose");
					input.setAttribute("data-message", "0");
					input.value = "";
				}

				adjustInput(input);

				return false;
			}

			else if (e.which == 27) { // escape
				e.preventDefault();
				input.removeAttribute("data-compose");
				input.setAttribute("data-message", "0");
				input.value = "";
				adjustInput(input);

				return false;
			}

			else if (e.which == 9) { // tab
				e.preventDefault();

				var start = this.selectionStart;
				var end = this.selectionEnd;
				var value = this.value;
				var before = value.substr(0, start);
				var after = value.substr(end);

				if (start === end) {
					this.value = before + "\t" + after;
					this.selectionStart = this.selectionEnd = start + 1;
				} else {
					var selectStart = start;

					var line_before = before.substr(0, Math.max(0, before.lastIndexOf("\n") + 1));
					var line_after = after.substr(Math.max(0, after.indexOf("\n")));
					var text_to_indent = before.substr(Math.max(0, before.lastIndexOf("\n") + 1))
						+ value.substring(start, end)
						+ after.substr(0, Math.max(0, after.indexOf("\n")));

					if (e.shiftKey) {
						selectStart -= /(^|\n)(\t| {0,4})/g.exec(text_to_indent)[2].length;

						text_to_indent = text_to_indent.replace(/(^|\n)(\t| {0,4})/g, "\n");

						if (text_to_indent.indexOf("\n") === 0) { // TODO: Just get first char and compare
							text_to_indent = text_to_indent.substr(1);
						}

						this.value = line_before + text_to_indent + line_after;
					} else {
						selectStart++;

						this.value = line_before + "\t" + text_to_indent.replace(/\n/g, "\n\t") + line_after;
					}

					this.selectionStart = selectStart;
					this.selectionEnd = this.value.length - after.length;
				}
			}
		});
	}

	var payload = null;

	try {
		payload = JSON.parse(e.data);
	} catch (e) {
		alert(e);
		console.log(e);
	}

	if (payload == null || !"type" in payload || !"data" in payload) {
		return;
	}

	console.log("in", payload.type, payload.data);

	if (payload.type in this.handlers) {
		this.handlers[payload.type](payload.type, payload.data);
	} else {
		console.info("No handler has been registered for that type: " + payload.type);
	}
};

DataHandler.prototype.onClose = function () {
	console.debug("DataHandler::onClose");

	if ("close" in this.handlers) {
		this.handlers["close"]();
	}

	var handler = this;

	setTimeout(function () {
		handler.connect();
	}, 3000);
};

DataHandler.prototype.on = function (type, callback) {
	this.handlers[type] = callback;
};

DataHandler.prototype.send = function (type, data) {
	if (this.websocket.readyState === WebSocket.OPEN) {
		this.websocket.send(JSON.stringify({type: type, data: data}));
		console.log("out", type, data);
	} else {
		var handler = this;

		if (type === "lost-push") {
			forEach(data, function (i, o) {
				handler.queue.push(o);
			});
		} else {
			handler.queue.push({type: type, data: data});
		}
	}
};
<|endoftext|>


<commit_before>var conf = require('./src_new/conf.js');
var StringReplacePlugin = require('string-replace-webpack-plugin');
var path = require('path');

var controllerPaths = {
	UAS: "./controllers/uas.js",
	DFP: "./controllers/gpt.js"
};

module.exports = {
    output: {
        filename: 'owt.js'
    },
    devtool: 'source-map',
    resolve: {
				modules: [path.resolve('./node_modules'), path.resolve('./src_new')]
    },
    resolveLoader: {
        modulesDirectories: ['node_modules']
    },
    module: {
        loaders: [
            {
                test: /owt.js$/,
                include: /(src_new)/,
                loader: StringReplacePlugin.replace({
                  replacements: [
                    {
                      pattern: /%%PATH_TO_CONTROLLER%%/g,
                      replacement: function (match, p1, offset, string) {
                        return controllerPaths[conf.pwt.adserver || "DFP"];
                      }
                    }
                  ]
                })
            }
        ],
				rules: [
		      {
		        test: /(\.js)$/,
		        loader: 'babel-loader',
		        exclude: /(node_modules)/
		      },
		      {
		        test: /(\.js)$/,
		        loader: 'eslint-loader',
		        exclude: /node_modules/
		      }
		    ]
    },
    plugins: [
        new StringReplacePlugin()
    ]
};
<commit_msg>added controller path<commit_after>var conf = require('./src_new/conf.js');
var StringReplacePlugin = require('string-replace-webpack-plugin');
var path = require('path');

var controllerPaths = {
	UAS: "./controllers/uas.js",
	DFP: "./controllers/gpt.js",
    CUSTOM: "./controllers/custom.js"
};

module.exports = {
    output: {
        filename: 'owt.js'
    },
    devtool: 'source-map',
    resolve: {
				modules: [path.resolve('./node_modules'), path.resolve('./src_new')]
    },
    resolveLoader: {
        modulesDirectories: ['node_modules']
    },
    module: {
        loaders: [
            {
                test: /owt.js$/,
                include: /(src_new)/,
                loader: StringReplacePlugin.replace({
                  replacements: [
                    {
                      pattern: /%%PATH_TO_CONTROLLER%%/g,
                      replacement: function (match, p1, offset, string) {
                        return controllerPaths[conf.pwt.adserver || "DFP"];
                      }
                    }
                  ]
                })
            }
        ],
				rules: [
		      {
		        test: /(\.js)$/,
		        loader: 'babel-loader',
		        exclude: /(node_modules)/
		      },
		      {
		        test: /(\.js)$/,
		        loader: 'eslint-loader',
		        exclude: /node_modules/
		      }
		    ]
    },
    plugins: [
        new StringReplacePlugin()
    ]
};
<|endoftext|>


<commit_before>class Polygone
{
    // Constructeur
	constructor()
	{
        this.id = ++Polygone.ID;

        this.edges = [];

        this.facePoint = null;
	}

    // Setter
    setEdges(edges)
    {
        this.edges = edges;
    }

    // Ajoute une edge à la liste des edges
    pushEdge(edge)
    {
        this.edges.push(edge);
    }

    // Enlève un point à la liste des points (s'il le point passé en paramètre se trouve dans la liste)
    removeEdges(edge)
    {
        // Récupération de l'index de l'élément à enlever
        var indexToRemove = this.edges.indexOf(edge);

        // Si l'élément se trouve dans la liste
        // On recrée une nouvelle liste sans l'élément à retirer (plus rapide en JS)
        if(indexToRemove != -1)
        {
            var tmpEdges = [];

            for(i = 0; i < this.edges.length; ++i)
            {
                if(i != indexToRemove)
                    tmpEdges.push(this.edges[i]);
            }

            this.edges = tmpEdges;
        }
    }

    // Calcul le facePoint du polygone (Catmull-Clark)
    computeFacePoint()
    {
        var tmpVertice = [];

        // On récupère tous les vertices des edges composant le polygone
        var arrayLength = this.edges.length;

        for(var i = 0; i < arrayLength; ++i)
        {
            if(tmpVertice.indexOf(this.edges[i].v1) == -1)
                tmpVertice.push(this.edges[i].v1);

            if(tmpVertice.indexOf(this.edges[i].v2) == -1)
                tmpVertice.push(this.edges[i].v2);
        }

        // On calcule la moyenne des différents vertices appartenant aux edges composant le polygone
        var arrayLength = tmpVertice.length;

        if(arrayLength > 0)
        {
            var vec3 = tmpVertice[0].clone();

            this.facePoint = new Vertex(vec3.x, vec3.y, vec3.z);

            for(i = 1; i < arrayLength; ++i)
                this.facePoint.add(tmpVertice[i]);

            this.facePoint.divideScalar(arrayLength);
        }
    }

    getUniqueVertices()
    {
        var res = [],
            map = {};

        for(var i = 0, len = this.edges.length; i < len; ++i)
        {
            if (!map[this.edges[i].v1.toKey()])
            {
                res.push(this.edges[i].v1);
                map[this.edges[i].v1.toKey()] = true;
            }

            if (!map[this.edges[i].v2.toKey()])
            {
                res.push(this.edges[i].v2);
                map[this.edges[i].v2.toKey()] = true;

            }
        }

        return res;
    }
}

Polygone.ID = 0;<commit_msg>Correction class base subdivision<commit_after>class Polygone
{
    // Constructeur
	constructor()
	{
        this.id = ++Polygone.ID;

        this.edges = [];

        this.facePoint = null;
	}

    // Setter
    setEdges(edges)
    {
        this.edges = edges;
    }

    // Ajoute une edge à la liste des edges
    pushEdge(edge)
    {
        this.edges.push(edge);
    }

    // Enlève un point à la liste des points (s'il le point passé en paramètre se trouve dans la liste)
    removeEdges(edge)
    {
        // Récupération de l'index de l'élément à enlever
        var indexToRemove = this.edges.indexOf(edge);

        // Si l'élément se trouve dans la liste
        // On recrée une nouvelle liste sans l'élément à retirer (plus rapide en JS)
        if(indexToRemove != -1)
        {
            var tmpEdges = [];

            for(i = 0; i < this.edges.length; ++i)
            {
                if(i != indexToRemove)
                    tmpEdges.push(this.edges[i]);
            }

            this.edges = tmpEdges;
        }
    }

    // Calcul le facePoint du polygone (Catmull-Clark)
    computeFacePoint()
    {
        var tmpVertice = [];

        // On récupère tous les vertices des edges composant le polygone
        var arrayLength = this.edges.length;

        for(var i = 0; i < arrayLength; ++i)
        {
            if(tmpVertice.indexOf(this.edges[i].v1) == -1)
                tmpVertice.push(this.edges[i].v1);

            if(tmpVertice.indexOf(this.edges[i].v2) == -1)
                tmpVertice.push(this.edges[i].v2);
        }

        // On calcule la moyenne des différents vertices appartenant aux edges composant le polygone
        var arrayLength = tmpVertice.length;

        if(arrayLength > 0)
        {
            this.facePoint = tmpVertice[0].clone();

            for(i = 1; i < arrayLength; ++i)
                this.facePoint.add(tmpVertice[i]);

            this.facePoint.divideScalar(arrayLength);
        }
    }

    getUniqueVertices()
    {
        var res = [],
            map = {};

        for(var i = 0, len = this.edges.length; i < len; ++i)
        {
            if (!map[this.edges[i].v1.toKey()])
            {
                res.push(this.edges[i].v1);
                map[this.edges[i].v1.toKey()] = true;
            }

            if (!map[this.edges[i].v2.toKey()])
            {
                res.push(this.edges[i].v2);
                map[this.edges[i].v2.toKey()] = true;

            }
        }

        return res;
    }
}

Polygone.ID = 0;<|endoftext|>