<commit_before>var _ = require('lodash');
var async = require('async-chainable');
var fs = require('fs');
var traverse = require('traverse');
var xml2json = require('xml2json');

var revman = {};
module.exports = revman;

revman.parse = function parse(data, options, callback) {
	var warnings = [];

	// Deal with incomming arguments {{{
	if (_.isFunction(options)) { // Called via data, callback
		callback = options;
		options = {};
	} else if (!_.isFunction(callback)) {
		throw new Error('No callback specified');
	}
	// }}}

	// Process settings {{{
	var settings = _.defaults(options, {
		pRounding: 6,
		dateFields: ['modified'],
		floatFields: ['ciEnd', 'ciStart', 'effectSize', 'logCiEnd', 'logCiStart', 'logEffectSize', 'se', 'var', 'weight', 'i2', 'i2Q', 'q', 'scale', 'chi2', 'pChi2', 'pQ', 'pZ', 'tau2', 'z', 'oE'],
		numberFields:  ['events1', 'events2', 'order', 'no', 'studies', 'total1', 'total2', 'ciStudy', 'ciTotal', 'df'],
		booleanFields: ['estimable', 'random', 'subgroups', 'subgroupTest', 'swapEvents', 'totals'],
		arrayFields: [
			// Data fields:
			'person', 'whatsNewEntry', 'source', 'qualityItem', 'qualityItemDataEntry', 'comparison', 'feedbackItem', 'figure', 'subsection', 'study', 'reference', 'includedChar', 'excludedChar', 'contData', 'contOutcome', 'contSubgroup', 'dichOutcome', 'dichData', 'dichSubgroup', 'dichOutcome', 'ivData', 'appendix',

			// Pseudo HTML decorators:
			'p', 'a', 'i', 'b', 'link', 'ol', 'li', 'br', 'sup', 'tr', 'td', 'th',
			'additionalTable', 'extension', 'flowchartbox',
		],
		effectMeasureLookup: {
			'RR': 'Risk Ratio',
			'ARR': 'Absolute Risk Reduction',
			'CGR': 'Control Group Risk',
			'CCT': 'Controlled Clinical Trial',
			'IV': 'Inverse Variance',
			'M-H': 'Mantel-Haenszel',
			'MD': 'Mean Difference',
			'OR': 'Odds Ratio',
			'RD': 'Risk Difference',
			'SD': 'Standard Deviation',
			'SE': 'Standard Error',
			'SMD': 'Standardized Mean Difference',
		},
		outcomeKeys: [
			{type: 'dich', outcome: 'dichOutcome', study: 'dichData', subgroup: 'dichSubgroup'},
			{type: 'cont', outcome: 'contOutcome', study: 'contData', subgroup: 'contSubgroup'},
		],
		removeEmptyOutcomes: true,
		debugOutcomes: false,
	});
	// }}}

	async()
		// Read in file contents {{{
		.then('json', function(next) {
			try {
				var rmXML = xml2json.toJson(data, {
					object: true,
				});
				next(null, rmXML);
			} catch (e) {
				next(e);
			}
		})
		// }}}
		// Parse raw input into JS standard JSON {{{
		.then('json', function(next) {
			next(null, traverse(this.json).map(function(v) {
				if (_.includes(settings.arrayFields, this.key)) { // Translatevalue into array
					if (_.isObject(v) && _.has(v, '0')) { // Multiple items in array
						this.update(_.values(v));
					} else { // Single item array
						this.update([v]);
					}
				} else if (_.isObject(v)) { // Normalize keys
					this.update(_.mapKeys(v, function(c, k) {
						return _.camelCase(k.toLowerCase());
					}));
				} else if (_.includes(settings.dateFields, this.key)) { // Translate value into Date
					this.update(new Date(v));
				} else if (_.includes(settings.numberFields, this.key)) { // Translate into numbers
					this.update(parseInt(v));
				} else if (_.includes(settings.floatFields, this.key)) { // Translate into floats
					this.update(parseFloat(v));
				} else if (_.includes(settings.booleanFields, this.key)) { // Translate into floats
					this.update(v == 'YES');
				}
			}).cochraneReview);
		})
		// }}}
		.parallel([
			// Calculate comparison.outcome {{{
			function(next) {
				if (!settings.outcomeKeys) return next();
				this.json.analysesAndData.comparison.forEach(function(comparison, comparisonIndex) {
					comparison.outcome = [];
					settings.outcomeKeys.forEach(function(outcomeMeta) {
						if (_.has(comparison, outcomeMeta.outcome)) {
							comparison[outcomeMeta.outcome].forEach(function(outcome) {
								outcome.outcomeType = outcomeMeta.type;

								if (_.has(outcome, outcomeMeta.subgroup)) { // This outcome has subgroups
									outcome.subgroup = outcome[outcomeMeta.subgroup];
									outcome.subgroup.forEach(function(subgroup, subgroupIndex) {
										subgroup.study = subgroup[outcomeMeta.study];
									});
								} else if (_.has(outcome, outcomeMeta.study)) { // This outcome has no subgroups and just contains studies
									outcome.study = outcome[outcomeMeta.study];
								} else {
									warnings.push('Outcome at "comparison[' + comparisonIndex + '].outcome[' + (outcome.no-1) + ']" contains no subgroups or studies');
								}

								comparison.outcome.push(outcome);
							});
						}
					});

					// Resort the comparison outcomes so they are in the right order {{{
					comparison.outcome = _.sortBy(comparison.outcome, 'no');
					// }}}

					// Output warnings for any unknown `*Outcome` keys {{{
					if (settings.debugOutcomes) {
					_.keys(comparison)
						.filter(function(key) {
							// Ends with 'Outcome'...
							return (/Outcome$/.test(key));
						})
						.filter(function(key) {
							// AND is not already recognised
							return !_.includes(_.map(settings.outcomeKeys, 'outcome'), key);
						})
						.forEach(function(key) {
							warnings.push('Unrecognised Outcome key "' + key + '"');
						});
					}
					// }}}

					// Remove empty otucomes if (settings.removeEmptyOutcomes) {{{
					if (settings.removeEmptyOutcomes) {
						comparison.outcome = comparison.outcome.filter(function(outcome) {
							return (outcome.subgroup || outcome.study);
						});
					}
					// }}}
				});
				next();
			},
			// }}}
			// Calculate study.participants {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.participants = 0;
					comparison.dichOutcome.forEach(function(outcome) {
						outcome.total1 = parseInt(outcome.total1);
						outcome.total2 = parseInt(outcome.total2);
						outcome.participants = outcome.total1 + outcome.total2;
						comparison.participants += outcome.participants;

						if (outcome.dichSubgroup) {
							outcome.dichSubgroup.forEach(function(subgroup) {
								subgroup.participants = subgroup.total1 + subgroup.total2;
							});
						}
					});
				});
				next();
			},
			// }}}
			// Calculate study.pText {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.dichOutcome.forEach(function(outcome) {
						outcome.pZ = parseFloat(outcome.pZ);
						var p = outcome.p = _.round(outcome.pZ, settings.pRounding);
						outcome.pText =
							p <= 0.00001 ? 'P < 0.00001' :
							p <= 0.0001 ? 'P < 0.0001' :
							p <= 0.001 ? 'P < 0.001' :
							p <= 0.01 ? 'P < 0.01' :
							p <= 0.05 ? 'P < 0.05' :
							'P = ' + p;
					});
				});
				next();
			},
			// }}}
			// Calculate study.effectMeasureText {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.dichOutcome.forEach(function(outcome) {
						if (_.has(outcome, 'effectMeasure')) outcome.effectMeasureText = settings.effectMeasureLookup[outcome.effectMeasure];
					});
				});
				next();
			},
			// }}}
		])
		// End {{{
		.end(function(err) {
			callback(err, this.json, warnings);
		});
		// }}}
}

revman.parseFile = function parseFile(path, options, callback) {
	// Deal with incomming arguments {{{
	if (_.isFunction(options)) { // Called via data, callback
		callback = options;
		options = {};
	} else if (!_.isFunction(callback)) {
		throw new Error('No callback specified');
	}
	// }}}

	async()
		.then('contents', function(next) {
			fs.readFile(path, 'utf-8', next);
		})
		.end(function(err) {
			if (err) return callback(err);
			revman.parse(this.contents, options, callback);
		});
}
<commit_msg>Added iv / Inverse Varience outcome type<commit_after>var _ = require('lodash');
var async = require('async-chainable');
var fs = require('fs');
var traverse = require('traverse');
var xml2json = require('xml2json');

var revman = {};
module.exports = revman;

revman.parse = function parse(data, options, callback) {
	var warnings = [];

	// Deal with incomming arguments {{{
	if (_.isFunction(options)) { // Called via data, callback
		callback = options;
		options = {};
	} else if (!_.isFunction(callback)) {
		throw new Error('No callback specified');
	}
	// }}}

	// Process settings {{{
	var settings = _.defaults(options, {
		pRounding: 6,
		dateFields: ['modified'],
		floatFields: ['ciEnd', 'ciStart', 'effectSize', 'logCiEnd', 'logCiStart', 'logEffectSize', 'se', 'var', 'weight', 'i2', 'i2Q', 'q', 'scale', 'chi2', 'pChi2', 'pQ', 'pZ', 'tau2', 'z', 'oE'],
		numberFields:  ['events1', 'events2', 'order', 'no', 'studies', 'total1', 'total2', 'ciStudy', 'ciTotal', 'df'],
		booleanFields: ['estimable', 'random', 'subgroups', 'subgroupTest', 'swapEvents', 'totals'],
		arrayFields: [
			// Outcome fields:
			'contOutcome', 'contData', 'contSubgroup',
			'dichOutcome', 'dichData', 'dichSubgroup', 'dichOutcome',
			'ivOutcome', 'ivData', 'ivSubgroup',

			// Data fields:
			'person', 'whatsNewEntry', 'source', 'qualityItem', 'qualityItemDataEntry', 'comparison', 'feedbackItem', 'figure', 'subsection', 'study', 'reference', 'includedChar', 'excludedChar', 'appendix',

			// Pseudo HTML decorators:
			'p', 'a', 'i', 'b', 'link', 'ol', 'li', 'br', 'sup', 'tr', 'td', 'th',
			'additionalTable', 'extension', 'flowchartbox',
		],
		effectMeasureLookup: {
			'RR': 'Risk Ratio',
			'ARR': 'Absolute Risk Reduction',
			'CGR': 'Control Group Risk',
			'CCT': 'Controlled Clinical Trial',
			'IV': 'Inverse Variance',
			'M-H': 'Mantel-Haenszel',
			'MD': 'Mean Difference',
			'OR': 'Odds Ratio',
			'RD': 'Risk Difference',
			'SD': 'Standard Deviation',
			'SE': 'Standard Error',
			'SMD': 'Standardized Mean Difference',
		},
		outcomeKeys: [
			{type: 'dich', outcome: 'dichOutcome', study: 'dichData', subgroup: 'dichSubgroup'},
			{type: 'cont', outcome: 'contOutcome', study: 'contData', subgroup: 'contSubgroup'},
			{type: 'iv', outcome: 'ivOutcome', study: 'ivData', subgroup: 'ivSubgroup'},
		],
		removeEmptyOutcomes: true,
		debugOutcomes: false,
	});
	// }}}

	async()
		// Read in file contents {{{
		.then('json', function(next) {
			try {
				var rmXML = xml2json.toJson(data, {
					object: true,
				});
				next(null, rmXML);
			} catch (e) {
				next(e);
			}
		})
		// }}}
		// Parse raw input into JS standard JSON {{{
		.then('json', function(next) {
			next(null, traverse(this.json).map(function(v) {
				if (_.includes(settings.arrayFields, this.key)) { // Translatevalue into array
					if (_.isObject(v) && _.has(v, '0')) { // Multiple items in array
						this.update(_.values(v));
					} else { // Single item array
						this.update([v]);
					}
				} else if (_.isObject(v)) { // Normalize keys
					this.update(_.mapKeys(v, function(c, k) {
						return _.camelCase(k.toLowerCase());
					}));
				} else if (_.includes(settings.dateFields, this.key)) { // Translate value into Date
					this.update(new Date(v));
				} else if (_.includes(settings.numberFields, this.key)) { // Translate into numbers
					this.update(parseInt(v));
				} else if (_.includes(settings.floatFields, this.key)) { // Translate into floats
					this.update(parseFloat(v));
				} else if (_.includes(settings.booleanFields, this.key)) { // Translate into floats
					this.update(v == 'YES');
				}
			}).cochraneReview);
		})
		// }}}
		.parallel([
			// Calculate comparison.outcome {{{
			function(next) {
				if (!settings.outcomeKeys) return next();
				this.json.analysesAndData.comparison.forEach(function(comparison, comparisonIndex) {
					comparison.outcome = [];
					settings.outcomeKeys.forEach(function(outcomeMeta) {
						if (_.has(comparison, outcomeMeta.outcome)) {
							comparison[outcomeMeta.outcome].forEach(function(outcome) {
								outcome.outcomeType = outcomeMeta.type;

								if (_.has(outcome, outcomeMeta.subgroup)) { // This outcome has subgroups
									outcome.subgroup = outcome[outcomeMeta.subgroup];
									outcome.subgroup.forEach(function(subgroup, subgroupIndex) {
										subgroup.study = subgroup[outcomeMeta.study];
									});
								} else if (_.has(outcome, outcomeMeta.study)) { // This outcome has no subgroups and just contains studies
									outcome.study = outcome[outcomeMeta.study];
								} else {
									warnings.push('Outcome at "comparison[' + comparisonIndex + '].outcome[' + (outcome.no-1) + ']" contains no subgroups or studies');
								}

								comparison.outcome.push(outcome);
							});
						}
					});

					// Resort the comparison outcomes so they are in the right order {{{
					comparison.outcome = _.sortBy(comparison.outcome, 'no');
					// }}}

					// Output warnings for any unknown `*Outcome` keys {{{
					if (settings.debugOutcomes) {
					_.keys(comparison)
						.filter(function(key) {
							// Ends with 'Outcome'...
							return (/Outcome$/.test(key));
						})
						.filter(function(key) {
							// AND is not already recognised
							return !_.includes(_.map(settings.outcomeKeys, 'outcome'), key);
						})
						.forEach(function(key) {
							warnings.push('Unrecognised Outcome key "' + key + '"');
						});
					}
					// }}}

					// Remove empty otucomes if (settings.removeEmptyOutcomes) {{{
					if (settings.removeEmptyOutcomes) {
						comparison.outcome = comparison.outcome.filter(function(outcome) {
							return (outcome.subgroup || outcome.study);
						});
					}
					// }}}
				});
				next();
			},
			// }}}
			// Calculate study.participants {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.participants = 0;
					comparison.dichOutcome.forEach(function(outcome) {
						outcome.total1 = parseInt(outcome.total1);
						outcome.total2 = parseInt(outcome.total2);
						outcome.participants = outcome.total1 + outcome.total2;
						comparison.participants += outcome.participants;

						if (outcome.dichSubgroup) {
							outcome.dichSubgroup.forEach(function(subgroup) {
								subgroup.participants = subgroup.total1 + subgroup.total2;
							});
						}
					});
				});
				next();
			},
			// }}}
			// Calculate study.pText {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.dichOutcome.forEach(function(outcome) {
						outcome.pZ = parseFloat(outcome.pZ);
						var p = outcome.p = _.round(outcome.pZ, settings.pRounding);
						outcome.pText =
							p <= 0.00001 ? 'P < 0.00001' :
							p <= 0.0001 ? 'P < 0.0001' :
							p <= 0.001 ? 'P < 0.001' :
							p <= 0.01 ? 'P < 0.01' :
							p <= 0.05 ? 'P < 0.05' :
							'P = ' + p;
					});
				});
				next();
			},
			// }}}
			// Calculate study.effectMeasureText {{{
			function(next) {
				this.json.analysesAndData.comparison.forEach(function(comparison) {
					comparison.dichOutcome.forEach(function(outcome) {
						if (_.has(outcome, 'effectMeasure')) outcome.effectMeasureText = settings.effectMeasureLookup[outcome.effectMeasure];
					});
				});
				next();
			},
			// }}}
		])
		// End {{{
		.end(function(err) {
			callback(err, this.json, warnings);
		});
		// }}}
}

revman.parseFile = function parseFile(path, options, callback) {
	// Deal with incomming arguments {{{
	if (_.isFunction(options)) { // Called via data, callback
		callback = options;
		options = {};
	} else if (!_.isFunction(callback)) {
		throw new Error('No callback specified');
	}
	// }}}

	async()
		.then('contents', function(next) {
			fs.readFile(path, 'utf-8', next);
		})
		.end(function(err) {
			if (err) return callback(err);
			revman.parse(this.contents, options, callback);
		});
}
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs.extra');
const electron = require('electron');
const tableify = require('tableify');
const {dialog} = require('electron');
const LineByLineReader = require('line-by-line');

const JSONParsed = [];
const logPath = path.join(os.homedir(), 'Saved Games', 'Frontier Developments', 'Elite Dangerous');
const app = electron.app;
let loadFile;
let win; // eslint-disable-line no-var
let htmlDone; // eslint-disable-line no-unused-vars
var alternateLoad;
const css = '<link href="https://fonts.googleapis.com/css?family=Lato:400,400italic,700" rel="stylesheet" type="text/css">';
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function createMainWindow() {
	win = new electron.BrowserWindow({
		width: 600,
		height: 400
	});

	win.on('closed', onClosed);

// menu functions be here
}
function onClosed() {
// dereference the window
// for multiple windows store them in an array
	mainWindow = null;
}
function funcLoad() {
	loadFile = dialog.showOpenDialog({defaultPath: logPath, buttonLabel: 'Load File', filters: [{name: 'Logs and saved HTML', extensions: ['log', 'html']}]}, {properties: ['openFile']});
	if (/\.[log]+$/i.test(loadFile) === true) {
		fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
			if (err) {
				return console.log(err);
			}
			readLine();
		});
		win.loadURL(`file:///${loadFile}`);
	} else if (/\.[html]+$/i.test(loadFile) === true) {
		win.loadURL(`file:///${loadFile}`);
	} else {
		console.log('Stop trying to break me!');
	}
}
function loadAlternate() {
	let html;
	process.alterateLoad = true;
	loadFile = dialog.showOpenDialog({properties: ['openFile']});
	const lr = new LineByLineReader(loadFile[0]);
	lr.on('error', err => {
		return console.log(err);
	});
	lr.on('line', function (line) { // eslint-disable-line prefer-arrow-callback
		let lineParse = JSON.parse(line); // eslint-disable-line prefer-const
		JSONParsed.push(lineParse);
		let htmlTabled = tableify(lineParse) + '
';  // eslint-disable-line prefer-const
		html += htmlTabled;
	});
	lr.on('end', err => {
		if (err) {
			console.log(err.message);
		}
		process.htmlDone = html;
		process.htmlDone = process.htmlDone.replace('undefined', '');
		win.loadURL('data:text/html,' + css + process.htmlDone);
	});
}
function readLine() {
	const loadPls = loadFile;
	const lr = new LineByLineReader(loadPls[0]);

	lr.on('error', err => {
		return console.log(err);
	});

	lr.on('line', line => {
		const lineParse = JSON.parse(line);
		JSONParsed.push(lineParse);
		const html = tableify(lineParse) + '
';
		fs.appendFile(`${process.resourcesPath}/index2.html`, html, err => {
			if (err) {
				return console.log(err);
			}
		});
	});
	fs.appendFile(`${process.resourcesPath}/index2.html`, css, err => {
		if (err) {
			return console.log(err);
		}
	});
	lr.on('end', () => {
		console.log('done!');
		console.log('The file was saved!');
		win.loadURL(`file://${process.resourcesPath}/index2.html`);
	});
	return win;
}
function funcSave() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
// fileName is a string that contains the path and filename created in the save file dialog.
if (process.alternateLoad = true) {
	fs.writeFile(fileName, css + process.htmlDone)
	} else {
		fs.copy(`${process.resourcesPath}/index2.html`, fileName, err => {
			if (err) {
				console.log(err.message);
			}
		});
	}
}
);
}
function funcSaveJSON() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
		const JSONParsedSave = JSON.stringify(JSONParsed);
		fs.writeFile(fileName, JSONParsedSave, err => {
			if (err) {
				console.log(err.message);
			}
		});
	});
}
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
	fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
		if (err) {
			return console.log(err);
		}
	});
});
app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
});

const {Menu} = require('electron');

const template = [
	{
		label: 'File',
		submenu: [
	{label: 'Save as HTML', click: funcSave},
	{label: 'Save as JSON', click: funcSaveJSON},
	{label: 'Load', click: funcLoad},
	{label: 'Load log(alternate)', click: loadAlternate}

		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: [
			{
				label: 'Reload',
				accelerator: 'CmdOrCtrl+R',
				click(item, focusedWindow) {
					if (focusedWindow) {
						focusedWindow.reload();
					}
				}
			},
			{
				role: 'togglefullscreen'
			}
		]
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			}
		]
	},
	{
		role: 'help',
		submenu: [
			{
				label: 'Learn More',
				click() {
					require('electron').shell.openExternal('http://electron.atom.io');
				}
			}
		]
	}
];

if (process.platform === 'darwin') {
	const name = require('electron').remote.app.getName();

	template.unshift({
		label: name,
		submenu: [
			{
				role: 'about'
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	});
// Edit menu.
	template[1].submenu.push(
		{
			type: 'separator'
		},
		{
			label: 'Speech',
			submenu: [
				{
					role: 'startspeaking'
				},
				{
					role: 'stopspeaking'
				}
			]
		}
);
// Window menu.
	template[3].submenu = [
		{
			label: 'Close',
			accelerator: 'CmdOrCtrl+W',
			role: 'close'
		},
		{
			label: 'Minimize',
			accelerator: 'CmdOrCtrl+M',
			role: 'minimize'
		},
		{
			label: 'Zoom',
			role: 'zoom'
		},
		{
			type: 'separator'
		},
		{
			label: 'Bring All to Front',
			role: 'front'
		}
	];
}

const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
<commit_msg>linting pls<commit_after>'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs.extra');
const electron = require('electron');
const tableify = require('tableify');
const {dialog} = require('electron');
const LineByLineReader = require('line-by-line');

const JSONParsed = [];
const logPath = path.join(os.homedir(), 'Saved Games', 'Frontier Developments', 'Elite Dangerous');
const app = electron.app;
let loadFile;
let win; // eslint-disable-line no-var
let htmlDone; // eslint-disable-line no-unused-vars
let alternateLoad; // eslint-disable-line no-unused-vars
const css = '<link href="https://fonts.googleapis.com/css?family=Lato:400,400italic,700" rel="stylesheet" type="text/css">';
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function createMainWindow() {
	win = new electron.BrowserWindow({
		width: 600,
		height: 400
	});

	win.on('closed', onClosed);

// menu functions be here
}
function onClosed() {
// dereference the window
// for multiple windows store them in an array
	mainWindow = null;
}
function funcLoad() {
	loadFile = dialog.showOpenDialog({defaultPath: logPath, buttonLabel: 'Load File', filters: [{name: 'Logs and saved HTML', extensions: ['log', 'html']}]}, {properties: ['openFile']});
	if (/\.[log]+$/i.test(loadFile) === true) {
		fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
			if (err) {
				return console.log(err);
			}
			readLine();
		});
		win.loadURL(`file:///${loadFile}`);
	} else if (/\.[html]+$/i.test(loadFile) === true) {
		win.loadURL(`file:///${loadFile}`);
	} else {
		console.log('Stop trying to break me!');
	}
}
function loadAlternate() {
	let html;
	process.alterateLoad = true;
	loadFile = dialog.showOpenDialog({properties: ['openFile']});
	const lr = new LineByLineReader(loadFile[0]);
	lr.on('error', err => {
		return console.log(err);
	});
	lr.on('line', function (line) { // eslint-disable-line prefer-arrow-callback
		let lineParse = JSON.parse(line); // eslint-disable-line prefer-const
		JSONParsed.push(lineParse);
		let htmlTabled = tableify(lineParse) + '
';  // eslint-disable-line prefer-const
		html += htmlTabled;
	});
	lr.on('end', err => {
		if (err) {
			console.log(err.message);
		}
		process.htmlDone = html;
		process.htmlDone = process.htmlDone.replace('undefined', '');
		win.loadURL('data:text/html,' + css + process.htmlDone);
	});
}
function readLine() {
	const loadPls = loadFile;
	const lr = new LineByLineReader(loadPls[0]);

	lr.on('error', err => {
		return console.log(err);
	});

	lr.on('line', line => {
		const lineParse = JSON.parse(line);
		JSONParsed.push(lineParse);
		const html = tableify(lineParse) + '
';
		fs.appendFile(`${process.resourcesPath}/index2.html`, html, err => {
			if (err) {
				return console.log(err);
			}
		});
	});
	fs.appendFile(`${process.resourcesPath}/index2.html`, css, err => {
		if (err) {
			return console.log(err);
		}
	});
	lr.on('end', () => {
		console.log('done!');
		console.log('The file was saved!');
		win.loadURL(`file://${process.resourcesPath}/index2.html`);
	});
	return win;
}
function funcSave() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
// fileName is a string that contains the path and filename created in the save file dialog.
		if (process.alternateLoad === true) {
			fs.writeFile(fileName, css + process.htmlDone);
		} else {
			fs.copy(`${process.resourcesPath}/index2.html`, fileName, err => {
				if (err) {
					console.log(err.message);
				}
			});
		}
	}
);
}
function funcSaveJSON() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
		const JSONParsedSave = JSON.stringify(JSONParsed);
		fs.writeFile(fileName, JSONParsedSave, err => {
			if (err) {
				console.log(err.message);
			}
		});
	});
}
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
	fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
		if (err) {
			return console.log(err);
		}
	});
});
app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
});

const {Menu} = require('electron');

const template = [
	{
		label: 'File',
		submenu: [
	{label: 'Save as HTML', click: funcSave},
	{label: 'Save as JSON', click: funcSaveJSON},
	{label: 'Load', click: funcLoad},
	{label: 'Load log(alternate)', click: loadAlternate}

		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: [
			{
				label: 'Reload',
				accelerator: 'CmdOrCtrl+R',
				click(item, focusedWindow) {
					if (focusedWindow) {
						focusedWindow.reload();
					}
				}
			},
			{
				role: 'togglefullscreen'
			}
		]
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			}
		]
	},
	{
		role: 'help',
		submenu: [
			{
				label: 'Learn More',
				click() {
					require('electron').shell.openExternal('http://electron.atom.io');
				}
			}
		]
	}
];

if (process.platform === 'darwin') {
	const name = require('electron').remote.app.getName();

	template.unshift({
		label: name,
		submenu: [
			{
				role: 'about'
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	});
// Edit menu.
	template[1].submenu.push(
		{
			type: 'separator'
		},
		{
			label: 'Speech',
			submenu: [
				{
					role: 'startspeaking'
				},
				{
					role: 'stopspeaking'
				}
			]
		}
);
// Window menu.
	template[3].submenu = [
		{
			label: 'Close',
			accelerator: 'CmdOrCtrl+W',
			role: 'close'
		},
		{
			label: 'Minimize',
			accelerator: 'CmdOrCtrl+M',
			role: 'minimize'
		},
		{
			label: 'Zoom',
			role: 'zoom'
		},
		{
			type: 'separator'
		},
		{
			label: 'Bring All to Front',
			role: 'front'
		}
	];
}

const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
<|endoftext|>


<commit_before>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

var less = require('less');
var root = fis.project.getProjectPath();

module.exports = function(content, file, conf){
    conf.paths = [ file.dirname, root ];
    conf.syncImport = true;
    conf.relativeUrls = true;
    var parser = new(less.Parser)(conf);
    parser.parse(content, function (err, tree) {
        if(err){
            throw err;
        } else {
            if(parser.imports){
                fis.util.map(parser.imports.files, function(path){
                    file.cache.addDeps(path);
                });
            }
            content = tree.toCSS(conf);
        }
    });
	return content;
};<commit_msg>change the conf define so we can pass it from config file<commit_after>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

var less = require('less');
var root = fis.project.getProjectPath();

module.exports = function(content, file, conf){
    conf.paths = [ file.dirname, root ];
    if (conf.syncImport === undefined) conf.syncImport = true;
    if (conf.relativeUrls === undefined) conf.relativeUrls = true;
    var parser = new(less.Parser)(conf);
    parser.parse(content, function (err, tree) {
        if(err){
            throw err;
        } else {
            if(parser.imports){
                fis.util.map(parser.imports.files, function(path){
                    file.cache.addDeps(path);
                });
            }
            content = tree.toCSS(conf);
        }
    });
	return content;
};
<|endoftext|>


<commit_before>var placeholder = "Search, drag and drop video, or paste its URL...";

var playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";
var removeImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/x-4x.png";

var videoUrl;
var videoName;
var videoTime = null;

var videos = [];
var videoCounter = 0;
var videoIteration = 0;
var bufferTime = 2000;

var videoPaused;
var stayPaused;
var backRestart;

var loopTimer;
var progressTimer;

function Timer(callback, delay) {
  var id, started, remaining = delay, running;
  this.resume = function() {
    running = true;
    started = new Date();
    id = window.setTimeout(callback, remaining);
  }
  this.pause = function() {
    running = false;
    window.clearTimeout(id);
    remaining -= new Date() - started;
  }
  this.getTimeLeft = function() {
    if (running) {
      this.pause();
      this.resume();
    }
    return remaining;
  }
  this.getStateRunning = function() {
    return running;
  }
  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function addVideoToList(name, time) {
  name = decodeURIComponent(name);
  $("#videosTable").append("
" + name + "<button class=\"tableButton removeButton\" onclick=\"actionRemoveVideo(this);\"></button>" +
  "<button class=\"tableButton playButton\" onclick=\"actionPlayVideo(this);\"></button>	" + time + "
");
}

function resetTimer(which) {
  if (which != 0) {
      which.pause();
    }
    which = 0;
}

var ActionTimers = function() {
  this.pause = function() {
    loopTimer.pause();
    progressTimer.pause();
  }
  this.resume = function() {
    loopTimer.resume();
    progressTimer.resume();
  }
  this.clear = function() {
    resetTimer(loopTimer);
    resetTimer(progressTimer);
    $("#progress").css("width", "0%");
    $("#currentTime").text("0:00");
  }
}
var actionTimers = new ActionTimers();

function videoProgress() {
  $("#videoTime").text(msConversion(videos[videoIteration]["time"] * 1000));
  function progressLoop() {
    var currentTime = (videos[videoIteration]["time"] * 1000) - loopTimer.getTimeLeft();
    var currentPercent = currentTime / (videos[videoIteration]["time"] * 1000) * 100;
    progressTimer = new Timer(function() {
      if (currentTime > 0) {
        $("#progress").css("width", currentPercent + "%");
        $("#currentTime").text(msConversion(currentTime));
      }
      progressLoop();
    }, 500);
  }
  progressLoop();
}

function playVideo() {
  highlight(videoIteration);
  document.title = "Streamly - " + decodeURIComponent(videos[videoIteration]["name"]);
  var embedUrl = videos[videoIteration]["url"];

  var autoplay = "";
  if (!stayPaused) {
    autoplay = "?autoplay=1";
  }

  if (embedUrl.search(/file:\/\//i) == -1) {
    embedUrl = "https://www.youtube.com/embed/" + videos[videoIteration]["url"] + autoplay;
  }
  $("#youtube").attr("src", embedUrl);

  backRestart = false;
  window.setTimeout(function() {
    backRestart = true;
  }, 3000);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  loopTimer = new Timer(function() {
    if (videoIteration < videoCounter) {
      actionTimers.clear();
      loopVideo();
    }
    else {
      actionTimers.clear();
      $("#youtube").attr("src", "");
      document.title = "Streamly";
    }
  }, (videos[videoIteration]["time"] * 1000) + bufferTime);

  videoProgress();

  if (stayPaused) {
    actionTimers.pause();
  }
}

function pauseVideo() {
  if (!videoPaused) {
    actionTimers.pause();
    videoPaused = true;
    if (videos[0] !== null && videos[0] !== undefined) {
      document.title = "Streamly - " + decodeURIComponent(videos[0]);
    }
  }
  else {
    actionTimers.resume();
    videoPaused = false;
    stayPaused = false;
    document.title = "Streamly - " + decodeURIComponent(videos[videoIteration]["name"]);
  }
  $("#pauseOverlay").css("display", "none");
  setTimeout(function(){
    $("#pauseOverlay").css("display", "block");
    $("#youtube").blur();
  }, 500);
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    actionTimers.clear();

    if (videoPaused) {
      stayPaused = true;
    }
    loopVideo();
  }
}

function backVideo() {
  if (videoPaused) {
    stayPaused = true;
  }
  if (!backRestart) {
    if (videoIteration - 2 > -1) {
      videoIteration = videoIteration - 2;
      actionTimers.clear();
      loopVideo();
    }
  }
  else {
    videoIteration = videoIteration - 1;
    actionTimers.clear();
    loopVideo();
  }
}

function setPlaylist() {
  if (videos.length > 1) {
    var playlist = JSON.stringify(videos);
    playlist = window.btoa(playlist);
    playlist = encodeURIComponent(playlist);
    window.location.hash = playlist;
  }
  else {
    window.location.hash = "";
  }
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = decodeURIComponent(playlist);
    playlist = window.atob(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    if (videos[0] != undefined) {
      $("#playlistNameBox").val(decodeURIComponent(videos[0]));
    }

    for (i = 1; i < videos.length; i++) {
      videoCounter = i;
      var printTime = msConversion(videos[videoCounter]["time"] * 1000);
      addVideoToList(videos[videoCounter]["name"], printTime);
    }
    loopVideo();
  }
}

function getVideoData() {
  $.ajax({
    url: videoUrl,
    type: 'GET',
    success: function(res) {
      var data = $(res.responseText);
      try {
        videoName = data.find("span#eow-title");
        videoName = videoName[0].textContent;
        videoName = $("
").html(videoName).text();
        videoName = videoName.trim();
      } catch(err) {
        videoName = prompt("Please enter the name of the video", "");
      }
      videoName = encodeURIComponent(videoName).replace(/%20/g, " ");
      try {
        videoTime = null;
        for (iteration in data) {
          var str = data[iteration].innerHTML;
          if (videoTime == null && typeof str != "undefined") {
            videoTime = str.match(/,"length_seconds":"\d+",/g);
          }
        }
        videoTime = videoTime[0];
        videoTime = videoTime.replace(/,"length_seconds":"/g, "").replace(/",/g, "");
        videoTime = +videoTime * 1000;
      } catch(err) {
        videoTime = prompt("Please enter the length of the video", "3:00");
        videoTime = videoTime.split(":");
        videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
        videoTime = videoTime * 1000;
      }
    },
    complete: function(jqXHR, textStatus) {
      $("#inputBox").val("").attr("placeholder", placeholder);
      addVideo();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      videoName = prompt("Please enter the name of the video", "");

      videoTime = prompt("Please enter the length of the video", "3:00");
      videoTime = videoTime.split(":");
      videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
      videoTime = videoTime * 1000;
    }
  });
}

function addVideo() {
  videoCounter++;
  var video = {};
  video["name"] = videoName;
  video["time"] = videoTime / 1000;
  video["url"] = videoUrl.replace(/^htt(p|ps):\/\/www\.youtube\.com\/watch\?v=/i, "");
  videos[videoCounter] = video;

  var printTime = msConversion(videoTime);

  addVideoToList(videoName, printTime);

  setPlaylist();

  if (videoCounter == 1 || loopTimer.getStateRunning() === false) {
    loopVideo();
  }
}

function actionPlayVideo(element) {
  var index = $(".playButton").index(element);
  videoIteration = index;
  actionTimers.clear();
  loopVideo();
}

function actionRemoveVideo(element) {
  var index = $(".removeButton").index(element) + 1;
  if (index == videoIteration) {
    if (videoIteration + 1 <= videoCounter) {
      forwardVideo();
      videoIteration--;
    }
    else {
      actionTimers.clear();
      $("#youtube").attr("src", "");
      document.title = "Streamly";
      videoIteration--;
    }
  }
  else if (index < videoIteration) {
    videoIteration--;
  }
  videoCounter--;
  videos.splice(index, 1);
  $("tr:nth-child(" + index + ")").remove();
  setPlaylist();
}

function urlValidate(url) {
  var isValidYouTube = /^htt(p|ps):\/\/www\.youtube\.com\/watch\?v=.+$/i;
  var isValidFile = /^file:\/\/.+$/i;

  url = url.trim();
  url = url.replace(/&list=.+/g, "");

  if (url.search(isValidYouTube) > -1 || url.search(isValidFile) > -1) {
    return url;
  }
  else {
    return false;
  }
}

function input(type) {
  var inputBox = $("#inputBox").val();
  var playlistNameBox = $("#playlistNameBox").val();
  switch (type) {
    case 0:
      if (inputBox != "") {
        window.open("https://www.youtube.com/results?search_query=" + inputBox.replace(/ /g, "+"));
        $("#inputBox").val("").attr("placeholder", placeholder);
      }
      break;
    case 1:
      if (inputBox != "") {
        inputBox = urlValidate(inputBox);
        if (inputBox) {
          videoUrl = inputBox;
          $("#inputBox").val("").attr("placeholder", "Loading video data from YouTube...");
          getVideoData();
        }
        else {
          alert("That video's URL seems broken\n\nTry copying it again, or drag and drop the video directly");
        }
      }
      break;
    case 2:
      if (playlistNameBox != "") {
        videos[0] = encodeURIComponent(playlistNameBox).replace(/%20/g, " ");
        setPlaylist();
      }
      else {
        videos[0] = undefined;
      }
      break;
  }
}

document.addEventListener("drop", function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("URL");

  $("#inputBox").val(data);
  input(1);
});

document.addEventListener("dragover", function(event) {
  event.preventDefault();
});
<commit_msg>set doc title to the playlist name when playlist ends<commit_after>var placeholder = "Search, drag and drop video, or paste its URL...";

var playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";
var removeImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/x-4x.png";

var videoUrl;
var videoName;
var videoTime = null;

var videos = [];
var videoCounter = 0;
var videoIteration = 0;
var bufferTime = 2000;

var videoPaused;
var stayPaused;
var backRestart;

var loopTimer;
var progressTimer;

function Timer(callback, delay) {
  var id, started, remaining = delay, running;
  this.resume = function() {
    running = true;
    started = new Date();
    id = window.setTimeout(callback, remaining);
  }
  this.pause = function() {
    running = false;
    window.clearTimeout(id);
    remaining -= new Date() - started;
  }
  this.getTimeLeft = function() {
    if (running) {
      this.pause();
      this.resume();
    }
    return remaining;
  }
  this.getStateRunning = function() {
    return running;
  }
  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function addVideoToList(name, time) {
  name = decodeURIComponent(name);
  $("#videosTable").append("
" + name + "<button class=\"tableButton removeButton\" onclick=\"actionRemoveVideo(this);\"></button>" +
  "<button class=\"tableButton playButton\" onclick=\"actionPlayVideo(this);\"></button>	" + time + "
");
}

function resetTimer(which) {
  if (which != 0) {
      which.pause();
    }
    which = 0;
}

var ActionTimers = function() {
  this.pause = function() {
    loopTimer.pause();
    progressTimer.pause();
  }
  this.resume = function() {
    loopTimer.resume();
    progressTimer.resume();
  }
  this.clear = function() {
    resetTimer(loopTimer);
    resetTimer(progressTimer);
    $("#progress").css("width", "0%");
    $("#currentTime").text("0:00");
  }
}
var actionTimers = new ActionTimers();

function videoProgress() {
  $("#videoTime").text(msConversion(videos[videoIteration]["time"] * 1000));
  function progressLoop() {
    var currentTime = (videos[videoIteration]["time"] * 1000) - loopTimer.getTimeLeft();
    var currentPercent = currentTime / (videos[videoIteration]["time"] * 1000) * 100;
    progressTimer = new Timer(function() {
      if (currentTime > 0) {
        $("#progress").css("width", currentPercent + "%");
        $("#currentTime").text(msConversion(currentTime));
      }
      progressLoop();
    }, 500);
  }
  progressLoop();
}

function playVideo() {
  highlight(videoIteration);
  document.title = "Streamly - " + decodeURIComponent(videos[videoIteration]["name"]);
  var embedUrl = videos[videoIteration]["url"];

  var autoplay = "";
  if (!stayPaused) {
    autoplay = "?autoplay=1";
  }

  if (embedUrl.search(/file:\/\//i) == -1) {
    embedUrl = "https://www.youtube.com/embed/" + videos[videoIteration]["url"] + autoplay;
  }
  $("#youtube").attr("src", embedUrl);

  backRestart = false;
  window.setTimeout(function() {
    backRestart = true;
  }, 3000);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  loopTimer = new Timer(function() {
    if (videoIteration < videoCounter) {
      actionTimers.clear();
      loopVideo();
    }
    else {
      actionTimers.clear();
      $("#youtube").attr("src", "");
      if (videos[0] !== null && videos[0] !== undefined) {
        document.title = "Streamly - " + decodeURIComponent(videos[0]);
      }
      else {
        document.title = "Streamly";
      }
    }
  }, (videos[videoIteration]["time"] * 1000) + bufferTime);

  videoProgress();

  if (stayPaused) {
    actionTimers.pause();
  }
}

function pauseVideo() {
  if (!videoPaused) {
    actionTimers.pause();
    videoPaused = true;
    if (videos[0] !== null && videos[0] !== undefined) {
      document.title = "Streamly - " + decodeURIComponent(videos[0]);
    }
  }
  else {
    actionTimers.resume();
    videoPaused = false;
    stayPaused = false;
    document.title = "Streamly - " + decodeURIComponent(videos[videoIteration]["name"]);
  }
  $("#pauseOverlay").css("display", "none");
  setTimeout(function(){
    $("#pauseOverlay").css("display", "block");
    $("#youtube").blur();
  }, 500);
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    actionTimers.clear();

    if (videoPaused) {
      stayPaused = true;
    }
    loopVideo();
  }
}

function backVideo() {
  if (videoPaused) {
    stayPaused = true;
  }
  if (!backRestart) {
    if (videoIteration - 2 > -1) {
      videoIteration = videoIteration - 2;
      actionTimers.clear();
      loopVideo();
    }
  }
  else {
    videoIteration = videoIteration - 1;
    actionTimers.clear();
    loopVideo();
  }
}

function setPlaylist() {
  if (videos.length > 1) {
    var playlist = JSON.stringify(videos);
    playlist = window.btoa(playlist);
    playlist = encodeURIComponent(playlist);
    window.location.hash = playlist;
  }
  else {
    window.location.hash = "";
  }
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = decodeURIComponent(playlist);
    playlist = window.atob(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    if (videos[0] != undefined) {
      $("#playlistNameBox").val(decodeURIComponent(videos[0]));
    }

    for (i = 1; i < videos.length; i++) {
      videoCounter = i;
      var printTime = msConversion(videos[videoCounter]["time"] * 1000);
      addVideoToList(videos[videoCounter]["name"], printTime);
    }
    loopVideo();
  }
}

function getVideoData() {
  $.ajax({
    url: videoUrl,
    type: 'GET',
    success: function(res) {
      var data = $(res.responseText);
      try {
        videoName = data.find("span#eow-title");
        videoName = videoName[0].textContent;
        videoName = $("
").html(videoName).text();
        videoName = videoName.trim();
      } catch(err) {
        videoName = prompt("Please enter the name of the video", "");
      }
      videoName = encodeURIComponent(videoName).replace(/%20/g, " ");
      try {
        videoTime = null;
        for (iteration in data) {
          var str = data[iteration].innerHTML;
          if (videoTime == null && typeof str != "undefined") {
            videoTime = str.match(/,"length_seconds":"\d+",/g);
          }
        }
        videoTime = videoTime[0];
        videoTime = videoTime.replace(/,"length_seconds":"/g, "").replace(/",/g, "");
        videoTime = +videoTime * 1000;
      } catch(err) {
        videoTime = prompt("Please enter the length of the video", "3:00");
        videoTime = videoTime.split(":");
        videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
        videoTime = videoTime * 1000;
      }
    },
    complete: function(jqXHR, textStatus) {
      $("#inputBox").val("").attr("placeholder", placeholder);
      addVideo();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      videoName = prompt("Please enter the name of the video", "");

      videoTime = prompt("Please enter the length of the video", "3:00");
      videoTime = videoTime.split(":");
      videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
      videoTime = videoTime * 1000;
    }
  });
}

function addVideo() {
  videoCounter++;
  var video = {};
  video["name"] = videoName;
  video["time"] = videoTime / 1000;
  video["url"] = videoUrl.replace(/^htt(p|ps):\/\/www\.youtube\.com\/watch\?v=/i, "");
  videos[videoCounter] = video;

  var printTime = msConversion(videoTime);

  addVideoToList(videoName, printTime);

  setPlaylist();

  if (videoCounter == 1 || loopTimer.getStateRunning() === false) {
    loopVideo();
  }
}

function actionPlayVideo(element) {
  var index = $(".playButton").index(element);
  videoIteration = index;
  actionTimers.clear();
  loopVideo();
}

function actionRemoveVideo(element) {
  var index = $(".removeButton").index(element) + 1;
  if (index == videoIteration) {
    if (videoIteration + 1 <= videoCounter) {
      forwardVideo();
      videoIteration--;
    }
    else {
      actionTimers.clear();
      $("#youtube").attr("src", "");
      document.title = "Streamly";
      videoIteration--;
    }
  }
  else if (index < videoIteration) {
    videoIteration--;
  }
  videoCounter--;
  videos.splice(index, 1);
  $("tr:nth-child(" + index + ")").remove();
  setPlaylist();
}

function urlValidate(url) {
  var isValidYouTube = /^htt(p|ps):\/\/www\.youtube\.com\/watch\?v=.+$/i;
  var isValidFile = /^file:\/\/.+$/i;

  url = url.trim();
  url = url.replace(/&list=.+/g, "");

  if (url.search(isValidYouTube) > -1 || url.search(isValidFile) > -1) {
    return url;
  }
  else {
    return false;
  }
}

function input(type) {
  var inputBox = $("#inputBox").val();
  var playlistNameBox = $("#playlistNameBox").val();
  switch (type) {
    case 0:
      if (inputBox != "") {
        window.open("https://www.youtube.com/results?search_query=" + inputBox.replace(/ /g, "+"));
        $("#inputBox").val("").attr("placeholder", placeholder);
      }
      break;
    case 1:
      if (inputBox != "") {
        inputBox = urlValidate(inputBox);
        if (inputBox) {
          videoUrl = inputBox;
          $("#inputBox").val("").attr("placeholder", "Loading video data from YouTube...");
          getVideoData();
        }
        else {
          alert("That video's URL seems broken\n\nTry copying it again, or drag and drop the video directly");
        }
      }
      break;
    case 2:
      if (playlistNameBox != "") {
        videos[0] = encodeURIComponent(playlistNameBox).replace(/%20/g, " ");
        setPlaylist();
      }
      else {
        videos[0] = undefined;
      }
      break;
  }
}

document.addEventListener("drop", function(event) {
  event.preventDefault();
  var data = event.dataTransfer.getData("URL");

  $("#inputBox").val(data);
  input(1);
});

document.addEventListener("dragover", function(event) {
  event.preventDefault();
});
<|endoftext|>


<commit_before>'use strict'

var css = require('css')
var locations = require('vfile-location')
var vendors = require('vendors')

exports.parse = parse
exports.stringify = stringify

/* Constants. */
var EMPTY = ''

/* Characters. */
var C_SPACE = ' '
var C_DASH = '-'
var C_UNDERSCORE = '_'
var C_SEMI_COLON = ';'
var C_COLON = ':'

/* Suffix to wrap around declarations. */
var PREFIX = 'i{'
var SUFFIX = '}'

/* Configuration for `reworkcss/css`. */
var CSS_OPTIONS = {silent: true}

/* Parse CSS declarations to an object. */
function parse(value, options) {
  var input = String(value || EMPTY)
  var max = input.length
  var declarations = {}
  var settings = options || {}
  var warn = settings.warning
  var location
  var sheet
  var results
  var warnings
  var length
  var index
  var result
  var warning
  var offset

  input = PREFIX + input + SUFFIX
  location = locations(input)

  sheet = css.parse(input, CSS_OPTIONS).stylesheet
  results = sheet.rules[0].declarations || []
  warnings = sheet.parsingErrors

  index = -1
  length = results.length

  while (++index < length) {
    result = results[index]

    if (result.type === 'declaration') {
      declarations[toJavaScriptName(result.property)] = result.value
    }
  }

  index = -1
  length = warn && warnings.length

  while (++index < length) {
    warning = warnings[index]
    offset = Math.min(
      max,
      location.toOffset({
        line: warning.line,
        column: warning.column
      }) - PREFIX.length
    )

    warn(warning.reason, offset)
  }

  return declarations
}

/* Compile a declarations object to string. */
function stringify(values) {
  var results = []
  var key
  var value

  for (key in values) {
    value = values[key]

    if (value !== null && value !== undefined) {
      results.push([toCSSName(key), value].join(C_COLON + C_SPACE))
    }
  }

  value = results.join(C_SEMI_COLON + C_SPACE)

  return value ? value + C_SEMI_COLON : EMPTY
}

/* Transform `cssName` to `javaScriptName`. */
function toJavaScriptName(cssName) {
  var char = cssName.charAt(0)

  return camel(cssName.slice(char === C_DASH || char === C_UNDERSCORE ? 1 : 0))
}

/* Transform `javaScriptName` to `cssName`. */
function toCSSName(javaScriptName) {
  var cssName = param(javaScriptName)
  var pos = cssName.indexOf(C_DASH)
  var subvalue = pos === -1 ? null : cssName.slice(0, pos)

  if (subvalue && vendors.indexOf(subvalue) !== -1) {
    cssName = C_DASH + cssName
  }

  return cssName
}

function camel(val) {
  return val.replace(/-./g, replacer)
  function replacer($0) {
    return $0.charAt(1).toUpperCase()
  }
}

function param(val) {
  return val.replace(/[A-Z]/g, replacer)
  function replacer($0) {
    return '-' + $0.toLowerCase()
  }
}
<commit_msg>Refactor comment style<commit_after>'use strict'

var css = require('css')
var locations = require('vfile-location')
var vendors = require('vendors')

exports.parse = parse
exports.stringify = stringify

// Constants.
var EMPTY = ''

// Characters.
var C_SPACE = ' '
var C_DASH = '-'
var C_UNDERSCORE = '_'
var C_SEMI_COLON = ';'
var C_COLON = ':'

// Suffix to wrap around declarations.
var PREFIX = 'i{'
var SUFFIX = '}'

// Configuration for `reworkcss/css`.
var CSS_OPTIONS = {silent: true}

// Parse CSS declarations to an object.
function parse(value, options) {
  var input = String(value || EMPTY)
  var max = input.length
  var declarations = {}
  var settings = options || {}
  var warn = settings.warning
  var location
  var sheet
  var results
  var warnings
  var length
  var index
  var result
  var warning
  var offset

  input = PREFIX + input + SUFFIX
  location = locations(input)

  sheet = css.parse(input, CSS_OPTIONS).stylesheet
  results = sheet.rules[0].declarations || []
  warnings = sheet.parsingErrors

  index = -1
  length = results.length

  while (++index < length) {
    result = results[index]

    if (result.type === 'declaration') {
      declarations[toJavaScriptName(result.property)] = result.value
    }
  }

  index = -1
  length = warn && warnings.length

  while (++index < length) {
    warning = warnings[index]
    offset = Math.min(
      max,
      location.toOffset({
        line: warning.line,
        column: warning.column
      }) - PREFIX.length
    )

    warn(warning.reason, offset)
  }

  return declarations
}

// Compile a declarations object to string.
function stringify(values) {
  var results = []
  var key
  var value

  for (key in values) {
    value = values[key]

    if (value !== null && value !== undefined) {
      results.push([toCSSName(key), value].join(C_COLON + C_SPACE))
    }
  }

  value = results.join(C_SEMI_COLON + C_SPACE)

  return value ? value + C_SEMI_COLON : EMPTY
}

// Transform `cssName` to `javaScriptName`.
function toJavaScriptName(cssName) {
  var char = cssName.charAt(0)

  return camel(cssName.slice(char === C_DASH || char === C_UNDERSCORE ? 1 : 0))
}

// Transform `javaScriptName` to `cssName`.
function toCSSName(javaScriptName) {
  var cssName = param(javaScriptName)
  var pos = cssName.indexOf(C_DASH)
  var subvalue = pos === -1 ? null : cssName.slice(0, pos)

  if (subvalue && vendors.indexOf(subvalue) !== -1) {
    cssName = C_DASH + cssName
  }

  return cssName
}

function camel(val) {
  return val.replace(/-./g, replacer)
  function replacer($0) {
    return $0.charAt(1).toUpperCase()
  }
}

function param(val) {
  return val.replace(/[A-Z]/g, replacer)
  function replacer($0) {
    return '-' + $0.toLowerCase()
  }
}
<|endoftext|>


<commit_before>module.exports = {
  'parser': 'babel-eslint',
  'plugins': [
    'react'
  ],
  'globals': {
    '__DEV__': true
  },
  'env': {
    'browser': true,
    'node': true
  },
  'ecmaFeatures': {
    'arrowFunctions': true,
    'blockBindings': true,
    'classes': true,
    'defaultParams': true,
    'destructuring': true,
    'forOf': true,
    'generators': false,
    'modules': true,
    'objectLiteralComputedProperties': true,
    'objectLiteralDuplicateProperties': false,
    'objectLiteralShorthandMethods': true,
    'objectLiteralShorthandProperties': true,
    'spread': true,
    'superInFunctions': true,
    'templateStrings': true,
    'jsx': true
  },
  'rules': {
/**
 * Strict mode
 */
    // babel inserts 'use strict'; for us
    // http://eslint.org/docs/rules/strict
    'strict': [2, 'never'],

/**
 * ES6
 */
    'no-var': 2,                     // http://eslint.org/docs/rules/no-var

/**
 * Variables
 */
    'no-shadow': 2,                  // http://eslint.org/docs/rules/no-shadow
    'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
    'no-unused-vars': [2, {          // http://eslint.org/docs/rules/no-unused-vars
      'vars': 'local',
      'args': 'after-used'
    }],
    'no-use-before-define': 2,       // http://eslint.org/docs/rules/no-use-before-define

/**
 * Possible errors
 */
    'comma-dangle': [2, 'never'],    // http://eslint.org/docs/rules/comma-dangle
    'no-cond-assign': [2, 'always'], // http://eslint.org/docs/rules/no-cond-assign
    'no-console': 1,                 // http://eslint.org/docs/rules/no-console
    'no-debugger': 1,                // http://eslint.org/docs/rules/no-debugger
    'no-alert': 1,                   // http://eslint.org/docs/rules/no-alert
    'no-constant-condition': 1,      // http://eslint.org/docs/rules/no-constant-condition
    'no-dupe-keys': 2,               // http://eslint.org/docs/rules/no-dupe-keys
    'no-duplicate-case': 2,          // http://eslint.org/docs/rules/no-duplicate-case
    'no-empty': 2,                   // http://eslint.org/docs/rules/no-empty
    'no-ex-assign': 2,               // http://eslint.org/docs/rules/no-ex-assign
    'no-extra-boolean-cast': 0,      // http://eslint.org/docs/rules/no-extra-boolean-cast
    'no-extra-semi': 2,              // http://eslint.org/docs/rules/no-extra-semi
    'no-func-assign': 2,             // http://eslint.org/docs/rules/no-func-assign
    'no-inner-declarations': 2,      // http://eslint.org/docs/rules/no-inner-declarations
    'no-invalid-regexp': 2,          // http://eslint.org/docs/rules/no-invalid-regexp
    'no-irregular-whitespace': 2,    // http://eslint.org/docs/rules/no-irregular-whitespace
    'no-obj-calls': 2,               // http://eslint.org/docs/rules/no-obj-calls
    'no-sparse-arrays': 2,           // http://eslint.org/docs/rules/no-sparse-arrays
    'no-unreachable': 2,             // http://eslint.org/docs/rules/no-unreachable
    'use-isnan': 2,                  // http://eslint.org/docs/rules/use-isnan
    'block-scoped-var': 2,           // http://eslint.org/docs/rules/block-scoped-var

/**
 * Best practices
 */
    'consistent-return': 2,          // http://eslint.org/docs/rules/consistent-return
    'curly': [2, 'multi-line'],      // http://eslint.org/docs/rules/curly
    'default-case': 2,               // http://eslint.org/docs/rules/default-case
    'dot-notation': [2, {            // http://eslint.org/docs/rules/dot-notation
      'allowKeywords': true
    }],
    'eqeqeq': 2,                     // http://eslint.org/docs/rules/eqeqeq
    'guard-for-in': 2,               // http://eslint.org/docs/rules/guard-for-in
    'no-caller': 2,                  // http://eslint.org/docs/rules/no-caller
    'no-else-return': 2,             // http://eslint.org/docs/rules/no-else-return
    'no-eq-null': 2,                 // http://eslint.org/docs/rules/no-eq-null
    'no-eval': 2,                    // http://eslint.org/docs/rules/no-eval
    'no-extend-native': 2,           // http://eslint.org/docs/rules/no-extend-native
    'no-extra-bind': 2,              // http://eslint.org/docs/rules/no-extra-bind
    'no-fallthrough': 2,             // http://eslint.org/docs/rules/no-fallthrough
    'no-floating-decimal': 2,        // http://eslint.org/docs/rules/no-floating-decimal
    'no-implied-eval': 2,            // http://eslint.org/docs/rules/no-implied-eval
    'no-lone-blocks': 2,             // http://eslint.org/docs/rules/no-lone-blocks
    'no-loop-func': 2,               // http://eslint.org/docs/rules/no-loop-func
    'no-multi-str': 2,               // http://eslint.org/docs/rules/no-multi-str
    'no-native-reassign': 2,         // http://eslint.org/docs/rules/no-native-reassign
    'no-new': 2,                     // http://eslint.org/docs/rules/no-new
    'no-new-func': 2,                // http://eslint.org/docs/rules/no-new-func
    'no-new-wrappers': 2,            // http://eslint.org/docs/rules/no-new-wrappers
    'no-octal': 2,                   // http://eslint.org/docs/rules/no-octal
    'no-octal-escape': 2,            // http://eslint.org/docs/rules/no-octal-escape
    'no-param-reassign': 2,          // http://eslint.org/docs/rules/no-param-reassign
    'no-proto': 2,                   // http://eslint.org/docs/rules/no-proto
    'no-redeclare': 2,               // http://eslint.org/docs/rules/no-redeclare
    'no-return-assign': 2,           // http://eslint.org/docs/rules/no-return-assign
    'no-script-url': 2,              // http://eslint.org/docs/rules/no-script-url
    'no-self-compare': 2,            // http://eslint.org/docs/rules/no-self-compare
    'no-sequences': 2,               // http://eslint.org/docs/rules/no-sequences
    'no-throw-literal': 2,           // http://eslint.org/docs/rules/no-throw-literal
    'no-with': 2,                    // http://eslint.org/docs/rules/no-with
    'radix': 2,                      // http://eslint.org/docs/rules/radix
    'vars-on-top': 2,                // http://eslint.org/docs/rules/vars-on-top
    'wrap-iife': [2, 'any'],         // http://eslint.org/docs/rules/wrap-iife
    'yoda': 2,                       // http://eslint.org/docs/rules/yoda

/**
 * Style
 */
    'indent': [2, 2],                // http://eslint.org/docs/rules/
    'brace-style': [2,               // http://eslint.org/docs/rules/brace-style
      '1tbs', {
      'allowSingleLine': true
    }],
    'quotes': [
      2, 'single', 'avoid-escape'    // http://eslint.org/docs/rules/quotes
    ],
    'camelcase': [2, {               // http://eslint.org/docs/rules/camelcase
      'properties': 'never'
    }],
    'comma-spacing': [2, {           // http://eslint.org/docs/rules/comma-spacing
      'before': false,
      'after': true
    }],
    'comma-style': [2, 'last'],      // http://eslint.org/docs/rules/comma-style
    'eol-last': 2,                   // http://eslint.org/docs/rules/eol-last
    'func-names': 1,                 // http://eslint.org/docs/rules/func-names
    'key-spacing': [2, {             // http://eslint.org/docs/rules/key-spacing
        'beforeColon': false,
        'afterColon': true
    }],
    'new-cap': [2, {                 // http://eslint.org/docs/rules/new-cap
      'newIsCap': true,
      'capIsNew': false
    }],
    'no-multiple-empty-lines': [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
      'max': 2
    }],
    'no-nested-ternary': 2,          // http://eslint.org/docs/rules/no-nested-ternary
    'no-new-object': 2,              // http://eslint.org/docs/rules/no-new-object
    'no-spaced-func': 2,             // http://eslint.org/docs/rules/no-spaced-func
    'no-trailing-spaces': 2,         // http://eslint.org/docs/rules/no-trailing-spaces
    'no-underscore-dangle': 0,       // http://eslint.org/docs/rules/no-underscore-dangle
    'one-var': [2, 'never'],         // http://eslint.org/docs/rules/one-var
    'padded-blocks': [2, 'never'],   // http://eslint.org/docs/rules/padded-blocks
    'semi': [2, 'always'],           // http://eslint.org/docs/rules/semi
    'semi-spacing': [2, {            // http://eslint.org/docs/rules/semi-spacing
      'before': false,
      'after': true
    }],
    'space-after-keywords': 2,       // http://eslint.org/docs/rules/space-after-keywords
    'space-before-blocks': 2,        // http://eslint.org/docs/rules/space-before-blocks
    'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
    'space-infix-ops': 2,            // http://eslint.org/docs/rules/space-infix-ops
    'space-return-throw-case': 2,    // http://eslint.org/docs/rules/space-return-throw-case
    'spaced-comment': [2, 'always'],        // http://eslint.org/docs/rules/spaced-comment

/**
 * JSX style
 */
    'react/display-name': 0,
    'react/jsx-boolean-value': 2,
    'react/jsx-quotes': [2, 'single'],
    'react/jsx-no-undef': 2,
    'react/jsx-sort-props': 0,
    'react/jsx-sort-prop-types': 0,
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/no-did-mount-set-state': [2, 'allow-in-func'],
    'react/no-did-update-set-state': 2,
    'react/no-multi-comp': 2,
    'react/no-unknown-property': 2,
    'react/prop-types': 2,
    'react/react-in-jsx-scope': 2,
    'react/self-closing-comp': 2,
    'react/wrap-multilines': 2,
    'react/sort-comp': [2, {
      'order': [
        'displayName',
        'mixins',
        'statics',
        'contextTypes',
        'propTypes',
        'constructor',
        'getDefaultProps',
        'defaultProps',
        'getInitialState',
        'state',
        'componentWillMount',
        'componentDidMount',
        'componentWillReceiveProps',
        'shouldComponentUpdate',
        'componentWillUpdate',
        'componentWillUnmount',
        '/^(on|handle).+$/',
        '/^get.+$/',
        '/^render.+$/',
        'render'
      ]
    }]
  }
};
<commit_msg>Add componentDidUpdate to React component method order<commit_after>module.exports = {
  'parser': 'babel-eslint',
  'plugins': [
    'react'
  ],
  'globals': {
    '__DEV__': true
  },
  'env': {
    'browser': true,
    'node': true
  },
  'ecmaFeatures': {
    'arrowFunctions': true,
    'blockBindings': true,
    'classes': true,
    'defaultParams': true,
    'destructuring': true,
    'forOf': true,
    'generators': false,
    'modules': true,
    'objectLiteralComputedProperties': true,
    'objectLiteralDuplicateProperties': false,
    'objectLiteralShorthandMethods': true,
    'objectLiteralShorthandProperties': true,
    'spread': true,
    'superInFunctions': true,
    'templateStrings': true,
    'jsx': true
  },
  'rules': {
/**
 * Strict mode
 */
    // babel inserts 'use strict'; for us
    // http://eslint.org/docs/rules/strict
    'strict': [2, 'never'],

/**
 * ES6
 */
    'no-var': 2,                     // http://eslint.org/docs/rules/no-var

/**
 * Variables
 */
    'no-shadow': 2,                  // http://eslint.org/docs/rules/no-shadow
    'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
    'no-unused-vars': [2, {          // http://eslint.org/docs/rules/no-unused-vars
      'vars': 'local',
      'args': 'after-used'
    }],
    'no-use-before-define': 2,       // http://eslint.org/docs/rules/no-use-before-define

/**
 * Possible errors
 */
    'comma-dangle': [2, 'never'],    // http://eslint.org/docs/rules/comma-dangle
    'no-cond-assign': [2, 'always'], // http://eslint.org/docs/rules/no-cond-assign
    'no-console': 1,                 // http://eslint.org/docs/rules/no-console
    'no-debugger': 1,                // http://eslint.org/docs/rules/no-debugger
    'no-alert': 1,                   // http://eslint.org/docs/rules/no-alert
    'no-constant-condition': 1,      // http://eslint.org/docs/rules/no-constant-condition
    'no-dupe-keys': 2,               // http://eslint.org/docs/rules/no-dupe-keys
    'no-duplicate-case': 2,          // http://eslint.org/docs/rules/no-duplicate-case
    'no-empty': 2,                   // http://eslint.org/docs/rules/no-empty
    'no-ex-assign': 2,               // http://eslint.org/docs/rules/no-ex-assign
    'no-extra-boolean-cast': 0,      // http://eslint.org/docs/rules/no-extra-boolean-cast
    'no-extra-semi': 2,              // http://eslint.org/docs/rules/no-extra-semi
    'no-func-assign': 2,             // http://eslint.org/docs/rules/no-func-assign
    'no-inner-declarations': 2,      // http://eslint.org/docs/rules/no-inner-declarations
    'no-invalid-regexp': 2,          // http://eslint.org/docs/rules/no-invalid-regexp
    'no-irregular-whitespace': 2,    // http://eslint.org/docs/rules/no-irregular-whitespace
    'no-obj-calls': 2,               // http://eslint.org/docs/rules/no-obj-calls
    'no-sparse-arrays': 2,           // http://eslint.org/docs/rules/no-sparse-arrays
    'no-unreachable': 2,             // http://eslint.org/docs/rules/no-unreachable
    'use-isnan': 2,                  // http://eslint.org/docs/rules/use-isnan
    'block-scoped-var': 2,           // http://eslint.org/docs/rules/block-scoped-var

/**
 * Best practices
 */
    'consistent-return': 2,          // http://eslint.org/docs/rules/consistent-return
    'curly': [2, 'multi-line'],      // http://eslint.org/docs/rules/curly
    'default-case': 2,               // http://eslint.org/docs/rules/default-case
    'dot-notation': [2, {            // http://eslint.org/docs/rules/dot-notation
      'allowKeywords': true
    }],
    'eqeqeq': 2,                     // http://eslint.org/docs/rules/eqeqeq
    'guard-for-in': 2,               // http://eslint.org/docs/rules/guard-for-in
    'no-caller': 2,                  // http://eslint.org/docs/rules/no-caller
    'no-else-return': 2,             // http://eslint.org/docs/rules/no-else-return
    'no-eq-null': 2,                 // http://eslint.org/docs/rules/no-eq-null
    'no-eval': 2,                    // http://eslint.org/docs/rules/no-eval
    'no-extend-native': 2,           // http://eslint.org/docs/rules/no-extend-native
    'no-extra-bind': 2,              // http://eslint.org/docs/rules/no-extra-bind
    'no-fallthrough': 2,             // http://eslint.org/docs/rules/no-fallthrough
    'no-floating-decimal': 2,        // http://eslint.org/docs/rules/no-floating-decimal
    'no-implied-eval': 2,            // http://eslint.org/docs/rules/no-implied-eval
    'no-lone-blocks': 2,             // http://eslint.org/docs/rules/no-lone-blocks
    'no-loop-func': 2,               // http://eslint.org/docs/rules/no-loop-func
    'no-multi-str': 2,               // http://eslint.org/docs/rules/no-multi-str
    'no-native-reassign': 2,         // http://eslint.org/docs/rules/no-native-reassign
    'no-new': 2,                     // http://eslint.org/docs/rules/no-new
    'no-new-func': 2,                // http://eslint.org/docs/rules/no-new-func
    'no-new-wrappers': 2,            // http://eslint.org/docs/rules/no-new-wrappers
    'no-octal': 2,                   // http://eslint.org/docs/rules/no-octal
    'no-octal-escape': 2,            // http://eslint.org/docs/rules/no-octal-escape
    'no-param-reassign': 2,          // http://eslint.org/docs/rules/no-param-reassign
    'no-proto': 2,                   // http://eslint.org/docs/rules/no-proto
    'no-redeclare': 2,               // http://eslint.org/docs/rules/no-redeclare
    'no-return-assign': 2,           // http://eslint.org/docs/rules/no-return-assign
    'no-script-url': 2,              // http://eslint.org/docs/rules/no-script-url
    'no-self-compare': 2,            // http://eslint.org/docs/rules/no-self-compare
    'no-sequences': 2,               // http://eslint.org/docs/rules/no-sequences
    'no-throw-literal': 2,           // http://eslint.org/docs/rules/no-throw-literal
    'no-with': 2,                    // http://eslint.org/docs/rules/no-with
    'radix': 2,                      // http://eslint.org/docs/rules/radix
    'vars-on-top': 2,                // http://eslint.org/docs/rules/vars-on-top
    'wrap-iife': [2, 'any'],         // http://eslint.org/docs/rules/wrap-iife
    'yoda': 2,                       // http://eslint.org/docs/rules/yoda

/**
 * Style
 */
    'indent': [2, 2],                // http://eslint.org/docs/rules/
    'brace-style': [2,               // http://eslint.org/docs/rules/brace-style
      '1tbs', {
      'allowSingleLine': true
    }],
    'quotes': [
      2, 'single', 'avoid-escape'    // http://eslint.org/docs/rules/quotes
    ],
    'camelcase': [2, {               // http://eslint.org/docs/rules/camelcase
      'properties': 'never'
    }],
    'comma-spacing': [2, {           // http://eslint.org/docs/rules/comma-spacing
      'before': false,
      'after': true
    }],
    'comma-style': [2, 'last'],      // http://eslint.org/docs/rules/comma-style
    'eol-last': 2,                   // http://eslint.org/docs/rules/eol-last
    'func-names': 1,                 // http://eslint.org/docs/rules/func-names
    'key-spacing': [2, {             // http://eslint.org/docs/rules/key-spacing
        'beforeColon': false,
        'afterColon': true
    }],
    'new-cap': [2, {                 // http://eslint.org/docs/rules/new-cap
      'newIsCap': true,
      'capIsNew': false
    }],
    'no-multiple-empty-lines': [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
      'max': 2
    }],
    'no-nested-ternary': 2,          // http://eslint.org/docs/rules/no-nested-ternary
    'no-new-object': 2,              // http://eslint.org/docs/rules/no-new-object
    'no-spaced-func': 2,             // http://eslint.org/docs/rules/no-spaced-func
    'no-trailing-spaces': 2,         // http://eslint.org/docs/rules/no-trailing-spaces
    'no-underscore-dangle': 0,       // http://eslint.org/docs/rules/no-underscore-dangle
    'one-var': [2, 'never'],         // http://eslint.org/docs/rules/one-var
    'padded-blocks': [2, 'never'],   // http://eslint.org/docs/rules/padded-blocks
    'semi': [2, 'always'],           // http://eslint.org/docs/rules/semi
    'semi-spacing': [2, {            // http://eslint.org/docs/rules/semi-spacing
      'before': false,
      'after': true
    }],
    'space-after-keywords': 2,       // http://eslint.org/docs/rules/space-after-keywords
    'space-before-blocks': 2,        // http://eslint.org/docs/rules/space-before-blocks
    'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
    'space-infix-ops': 2,            // http://eslint.org/docs/rules/space-infix-ops
    'space-return-throw-case': 2,    // http://eslint.org/docs/rules/space-return-throw-case
    'spaced-comment': [2, 'always'],        // http://eslint.org/docs/rules/spaced-comment

/**
 * JSX style
 */
    'react/display-name': 0,
    'react/jsx-boolean-value': 2,
    'react/jsx-quotes': [2, 'single'],
    'react/jsx-no-undef': 2,
    'react/jsx-sort-props': 0,
    'react/jsx-sort-prop-types': 0,
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/no-did-mount-set-state': [2, 'allow-in-func'],
    'react/no-did-update-set-state': 2,
    'react/no-multi-comp': 2,
    'react/no-unknown-property': 2,
    'react/prop-types': 2,
    'react/react-in-jsx-scope': 2,
    'react/self-closing-comp': 2,
    'react/wrap-multilines': 2,
    'react/sort-comp': [2, {
      'order': [
        'displayName',
        'mixins',
        'statics',
        'contextTypes',
        'propTypes',
        'constructor',
        'getDefaultProps',
        'defaultProps',
        'getInitialState',
        'state',
        'componentWillMount',
        'componentDidMount',
        'componentWillReceiveProps',
        'shouldComponentUpdate',
        'componentWillUpdate',
        'componentDidUpdate',
        'componentWillUnmount',
        '/^(on|handle).+$/',
        '/^get.+$/',
        '/^render.+$/',
        'render'
      ]
    }]
  }
};
<|endoftext|>


<commit_before>/**
 * koa-body - index.js
 * Copyright(c) 2014
 * MIT Licensed
 *
 * @author  Daryl Lau (@dlau)
 * @author  Charlike Mike Reagent (@tunnckoCore)
 * @api private
 */

'use strict';

/**
 * Module dependencies.
 */

var buddy = require('co-body');
var forms = require('formidable');

/**
 * Expose `requestbody()`.
 */

module.exports = requestbody;

/**
 *
 * @param {Object} options
 * @see https://github.com/dlau/koa-body
 * @api public
 */
function requestbody(opts) {
  opts = opts || {};
  opts.patchNode = 'patchNode' in opts ? opts.patchNode : false;
  opts.patchKoa  = 'patchKoa'  in opts ? opts.patchKoa  : true;
  opts.multipart = 'multipart' in opts ? opts.multipart : false;
  opts.encoding  = 'encoding'  in opts ? opts.encoding  : 'utf-8';
  opts.jsonLimit = 'jsonLimit' in opts ? opts.jsonLimit : '1mb';
  opts.formLimit = 'formLimit' in opts ? opts.formLimit : '56kb';
  opts.formidable = 'formidable' in opts ? opts.formidable : {};
  opts.textLimit = 'textLimit' in opts ? opts.textLimit : '56kb';
  opts.strict = 'strict' in opts ? opts.strict : true;

  return function *(next){
    var body = {};
    // so don't parse the body in strict mode
    if (!opts.strict || ["GET", "HEAD", "DELETE"].indexOf(this.method.toUpperCase()) === -1) {
      if (this.is('json'))  {
        body = yield buddy.json(this, {encoding: opts.encoding, limit: opts.jsonLimit});
      }
      else if (this.is('urlencoded')) {
        body = yield buddy.form(this, {encoding: opts.encoding, limit: opts.formLimit});
      }
      else if (this.is('text')) {
        body = yield buddy.text(this, {encoding: opts.encoding, limit: opts.textLimit});
      }
      else if (opts.multipart && this.is('multipart')) {
        body = yield formy(this, opts.formidable);
      }
    }

    if (opts.patchNode) {
      this.req.body = body;
    }
    if (opts.patchKoa) {
      this.request.body = body;
    }
    yield next;
  };
}

/**
 * Donable formidable
 *
 * @param  {Stream} ctx
 * @param  {Object} opts
 * @return {Object}
 * @api private
 */
function formy(ctx, opts) {
  return function(done) {
    var form = new forms.IncomingForm(opts);
    var fields = {};
    var files = {};
    form
      .on('end', function() {
        done(null, {fields: fields, files: files});
      })
      .on('error', function(err) {
        done(err);
      })
      .on('field', function(field, value) {
        if (fields[field]) {
          if (Array.isArray(fields[field])) {
            fields[field].push(value);
          } else {
            fields[field] = [fields[field], value];
          }
        } else {
          fields[field] = value;
        }
      })
      .on('file', function(field, file) {
        if (files[field]) {
          if (Array.isArray(files[field])) {
            files[field].push(file);
          } else {
            files[field] = [files[field], file];
          }
        } else {
          files[field] = file;
        }
      });
    form.parse(ctx.req);
  };
}
<commit_msg>[index] 支持 text 类型的数据<commit_after>/**
 * koa-body - index.js
 * Copyright(c) 2014
 * MIT Licensed
 *
 * @author  Daryl Lau (@dlau)
 * @author  Charlike Mike Reagent (@tunnckoCore)
 * @api private
 */

'use strict';

/**
 * Module dependencies.
 */

var buddy = require('co-body');
var forms = require('formidable');

/**
 * Expose `requestbody()`.
 */

module.exports = requestbody;

/**
 *
 * @param {Object} options
 * @see https://github.com/dlau/koa-body
 * @api public
 */
function requestbody(opts) {
  opts = opts || {};
  opts.patchNode = 'patchNode' in opts ? opts.patchNode : false;
  opts.patchKoa  = 'patchKoa'  in opts ? opts.patchKoa  : true;
  opts.multipart = 'multipart' in opts ? opts.multipart : false;
  opts.encoding  = 'encoding'  in opts ? opts.encoding  : 'utf-8';
  opts.jsonLimit = 'jsonLimit' in opts ? opts.jsonLimit : '1mb';
  opts.formLimit = 'formLimit' in opts ? opts.formLimit : '56kb';
  opts.formidable = 'formidable' in opts ? opts.formidable : {};
  opts.textLimit = 'textLimit' in opts ? opts.textLimit : '56kb';
  opts.strict = 'strict' in opts ? opts.strict : true;

  return function *(next){
    var body = {};
    // so don't parse the body in strict mode
    if (!opts.strict || ["GET", "HEAD", "DELETE"].indexOf(this.method.toUpperCase()) === -1) {
      if (this.is('json'))  {
        body = yield buddy.json(this, {encoding: opts.encoding, limit: opts.jsonLimit});
      }
      else if (this.is('urlencoded')) {
        body = yield buddy.form(this, {encoding: opts.encoding, limit: opts.formLimit});
      }
      else if (this.is('text')) {
        body = yield buddy.text(this, {encoding: opts.encoding, limit: opts.textLimit});
      }
      else if (opts.multipart && this.is('multipart')) {
        body = yield formy(this, opts.formidable);
      }
      else {
        body = yield buddy.text(this);
      }
    }

    if (opts.patchNode) {
      this.req.body = body;
    }
    if (opts.patchKoa) {
      this.request.body = body;
    }
    yield next;
  };
}

/**
 * Donable formidable
 *
 * @param  {Stream} ctx
 * @param  {Object} opts
 * @return {Object}
 * @api private
 */
function formy(ctx, opts) {
  return function(done) {
    var form = new forms.IncomingForm(opts);
    var fields = {};
    var files = {};
    form
      .on('end', function() {
        done(null, {fields: fields, files: files});
      })
      .on('error', function(err) {
        done(err);
      })
      .on('field', function(field, value) {
        if (fields[field]) {
          if (Array.isArray(fields[field])) {
            fields[field].push(value);
          } else {
            fields[field] = [fields[field], value];
          }
        } else {
          fields[field] = value;
        }
      })
      .on('file', function(field, file) {
        if (files[field]) {
          if (Array.isArray(files[field])) {
            files[field].push(file);
          } else {
            files[field] = [files[field], file];
          }
        } else {
          files[field] = file;
        }
      });
    form.parse(ctx.req);
  };
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const path = require('path');

function addBaseDir(Plugin) {
  let type = typeof Plugin;

  if (type === 'function' && !Plugin.baseDir) {
    Plugin.baseDir = () => __dirname;
  } else if (type === 'object' && Plugin !== null && Plugin.default) {
    addBaseDir(Plugin.default);
  }
}

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    let checker = new VersionChecker(this);
    let dep = this.emberCLIChecker = checker.for('ember-cli', 'npm');

    this._shouldShowBabelDeprecations = !dep.lt('2.11.0-beta.2');
  },

  setupPreprocessorRegistry: function(type, registry) {
    let addon = this;

    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, addon._getBabelOptions());
      }
    });
  },

  _shouldIncludePolyfill: function() {
    let addonOptions = this._getAddonOptions();
    let babelOptions = addonOptions.babel;
    let customOptions = addonOptions['ember-cli-babel'];

    if (this._shouldShowBabelDeprecations && !this._polyfillDeprecationPrinted &&
      babelOptions && 'includePolyfill' in babelOptions) {

      this._polyfillDeprecationPrinted = true;

      // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
      this.ui.writeDeprecateLine(
        'Putting the "includePolyfill" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
    }

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else if (babelOptions && 'includePolyfill' in babelOptions) {
      return babelOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill: function(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  treeForVendor: function() {
    if (!this._shouldIncludePolyfill()) { return; }

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('babel-polyfill/dist/polyfill'));

    return new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('babel-preset-env').isPluginRequired;
    const pluginList = require('babel-preset-env/data/plugins');

    return isPluginRequired(targets, pluginList[pluginName]);
  },

  _getAddonOptions: function() {
    return (this.parent && this.parent.options) || (this.app && this.app.options) || {};
  },

  _getProvidedBabelConfig: function() {
    if (this._cachedProvidedConfig) {
      return this._cachedProvidedConfig;
    }

    let parentName;

    if (this.parent) {
      if (typeof this.parent.name === 'function') {
        parentName = this.parent.name();
      } else {
        parentName = this.parent.name;
      }
    }

    let addonOptions = this._getAddonOptions();
    let options = clone(addonOptions.babel || {});

    // used only to support using ember-cli-babel@6 at the
    // top level (app or addon during development) on ember-cli
    // older than 2.13
    //
    // without this, we mutate the same shared `options.babel.plugins`
    // that is used to transpile internally (via `_prunedBabelOptions`
    // in older ember-cli versions)
    let babel6Options = clone(addonOptions.babel6 || {});

    // options.modules is set only for things assuming babel@5 usage
    if (options.modules) {
      // using babel@5 configuration with babel@6
      // without overriding here we would trigger
      // an error
      options = {
        plugins: [].concat(
          babel6Options.plugins,
          options.plugins
        ).filter(Boolean)
      };
    }

    let plugins = [].concat(options.plugins, babel6Options.plugins).filter(Boolean);
    let postTransformPlugins = [].concat(options.postTransformPlugins, babel6Options.postTransformPlugins).filter(Boolean);

    delete options.plugins;
    delete options.postTransformPlugins;

    this._cachedProvidedConfig =  { options, plugins, postTransformPlugins };

    return this._cachedProvidedConfig;
  },

  _getBabelOptions() {
    let providedConfig = this._getProvidedBabelConfig();
    let shouldCompileModules = this._shouldCompileModules();

    let options = {};
    let userPlugins = providedConfig.plugins;
    let userPostTransformPlugins = providedConfig.postTransformPlugins;

    options.plugins = [].concat(
      userPlugins,
      shouldCompileModules && this._getModulesPlugin(),
      this._getPresetEnvPlugins(),
      userPostTransformPlugins
    ).filter(Boolean);
    options.moduleIds = true;

    if (shouldCompileModules) {
      options.resolveModuleSource = require('amd-name-resolver').moduleResolve;
    }

    options.highlightCode = false;

    return options;
  },

  _getPresetEnvPlugins() {
    let providedConfig = this._getProvidedBabelConfig();
    let options = providedConfig.options;

    let targets = this._getTargets();
    let browsers = targets && targets.browsers;
    let presetOptions = Object.assign({}, options, {
      modules: false,
      targets: { browsers },
    });

    let presetEnvPlugins = this._presetEnv(null, presetOptions).plugins;

    presetEnvPlugins.forEach(function(pluginArray) {
      let Plugin = pluginArray[0];
      addBaseDir(Plugin);
    });

    return presetEnvPlugins;
  },

  _presetEnv() {
    const presetEnv = require('babel-preset-env').default;

    return presetEnv.apply(null, arguments);
  },

  _getTargets() {
    return this.project && this.project.targets && this.project.targets;
  },

  _getModulesPlugin() {
    const ModulesTransform = require('babel-plugin-transform-es2015-modules-amd');

    addBaseDir(ModulesTransform);

    return [
      [ModulesTransform, { noInterop: true }],
    ];
  },

  _shouldCompileModules() {
    let addonOptions = this._getAddonOptions();

    if (addonOptions['ember-cli-babel'] && 'compileModules' in addonOptions['ember-cli-babel']) {
      return addonOptions['ember-cli-babel'].compileModules;
    } else if (addonOptions.babel && 'compileModules' in addonOptions.babel) {
      if (this._shouldShowBabelDeprecations && !this._compileModulesDeprecationPrinted) {
        this._compileModulesDeprecationPrinted = true;
        // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
        this.ui.writeDeprecateLine('Putting the "compileModules" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
      }

      return addonOptions.babel.compileModules;
    } else {
      return this.emberCLIChecker.gt('2.12.0-alpha.1');
    }
  },

};
<commit_msg>Fix clobbering behavior with babel vs babel6 config.<commit_after>/* jshint node: true */
'use strict';

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const path = require('path');

function addBaseDir(Plugin) {
  let type = typeof Plugin;

  if (type === 'function' && !Plugin.baseDir) {
    Plugin.baseDir = () => __dirname;
  } else if (type === 'object' && Plugin !== null && Plugin.default) {
    addBaseDir(Plugin.default);
  }
}

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    let checker = new VersionChecker(this);
    let dep = this.emberCLIChecker = checker.for('ember-cli', 'npm');

    this._shouldShowBabelDeprecations = !dep.lt('2.11.0-beta.2');
  },

  setupPreprocessorRegistry: function(type, registry) {
    let addon = this;

    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, addon._getBabelOptions());
      }
    });
  },

  _shouldIncludePolyfill: function() {
    let addonOptions = this._getAddonOptions();
    let babelOptions = addonOptions.babel;
    let customOptions = addonOptions['ember-cli-babel'];

    if (this._shouldShowBabelDeprecations && !this._polyfillDeprecationPrinted &&
      babelOptions && 'includePolyfill' in babelOptions) {

      this._polyfillDeprecationPrinted = true;

      // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
      this.ui.writeDeprecateLine(
        'Putting the "includePolyfill" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
    }

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else if (babelOptions && 'includePolyfill' in babelOptions) {
      return babelOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill: function(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  treeForVendor: function() {
    if (!this._shouldIncludePolyfill()) { return; }

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('babel-polyfill/dist/polyfill'));

    return new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('babel-preset-env').isPluginRequired;
    const pluginList = require('babel-preset-env/data/plugins');

    return isPluginRequired(targets, pluginList[pluginName]);
  },

  _getAddonOptions: function() {
    return (this.parent && this.parent.options) || (this.app && this.app.options) || {};
  },

  _getProvidedBabelConfig: function() {
    if (this._cachedProvidedConfig) {
      return this._cachedProvidedConfig;
    }

    let parentName;

    if (this.parent) {
      if (typeof this.parent.name === 'function') {
        parentName = this.parent.name();
      } else {
        parentName = this.parent.name;
      }
    }

    let addonOptions = this._getAddonOptions();
    let babelOptions = clone(addonOptions.babel || {});

    // used only to support using ember-cli-babel@6 at the
    // top level (app or addon during development) on ember-cli
    // older than 2.13
    //
    // without this, we mutate the same shared `options.babel.plugins`
    // that is used to transpile internally (via `_prunedBabelOptions`
    // in older ember-cli versions)
    let babel6Options = clone(addonOptions.babel6 || {});

    let options;
    // options.modules is set only for things assuming babel@5 usage
    if (babelOptions.modules) {
      // using babel@5 configuration with babel@6
      // without overriding here we would trigger
      // an error
      options = Object.assign({}, babel6Options);
    } else {
      // shallow merge both babelOptions and babel6Options
      // (plugins/postTransformPlugins are handled separately)
      options = Object.assign({}, babelOptions, babel6Options);
    }

    let plugins = [].concat(babelOptions.plugins, babel6Options.plugins).filter(Boolean);
    let postTransformPlugins = [].concat(babelOptions.postTransformPlugins, babel6Options.postTransformPlugins).filter(Boolean);

    this._cachedProvidedConfig =  { options, plugins, postTransformPlugins };

    return this._cachedProvidedConfig;
  },

  _getBabelOptions() {
    let providedConfig = this._getProvidedBabelConfig();
    let shouldCompileModules = this._shouldCompileModules();

    let options = {};
    let userPlugins = providedConfig.plugins;
    let userPostTransformPlugins = providedConfig.postTransformPlugins;

    options.plugins = [].concat(
      userPlugins,
      shouldCompileModules && this._getModulesPlugin(),
      this._getPresetEnvPlugins(),
      userPostTransformPlugins
    ).filter(Boolean);
    options.moduleIds = true;

    if (shouldCompileModules) {
      options.resolveModuleSource = require('amd-name-resolver').moduleResolve;
    }

    options.highlightCode = false;

    return options;
  },

  _getPresetEnvPlugins() {
    let providedConfig = this._getProvidedBabelConfig();
    let options = providedConfig.options;

    let targets = this._getTargets();
    let browsers = targets && targets.browsers;
    let presetOptions = Object.assign({}, options, {
      modules: false,
      targets: { browsers },
    });

    let presetEnvPlugins = this._presetEnv(null, presetOptions).plugins;

    presetEnvPlugins.forEach(function(pluginArray) {
      let Plugin = pluginArray[0];
      addBaseDir(Plugin);
    });

    return presetEnvPlugins;
  },

  _presetEnv() {
    const presetEnv = require('babel-preset-env').default;

    return presetEnv.apply(null, arguments);
  },

  _getTargets() {
    return this.project && this.project.targets && this.project.targets;
  },

  _getModulesPlugin() {
    const ModulesTransform = require('babel-plugin-transform-es2015-modules-amd');

    addBaseDir(ModulesTransform);

    return [
      [ModulesTransform, { noInterop: true }],
    ];
  },

  _shouldCompileModules() {
    let addonOptions = this._getAddonOptions();

    if (addonOptions['ember-cli-babel'] && 'compileModules' in addonOptions['ember-cli-babel']) {
      return addonOptions['ember-cli-babel'].compileModules;
    } else if (addonOptions.babel && 'compileModules' in addonOptions.babel) {
      if (this._shouldShowBabelDeprecations && !this._compileModulesDeprecationPrinted) {
        this._compileModulesDeprecationPrinted = true;
        // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
        this.ui.writeDeprecateLine('Putting the "compileModules" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
      }

      return addonOptions.babel.compileModules;
    } else {
      return this.emberCLIChecker.gt('2.12.0-alpha.1');
    }
  },

};
<|endoftext|>