<commit_before>const Argument = require('./argument');

/** Obtains, validates, and prompts for argument values */
class ArgumentCollector {
	/**
	 * @param {CommandoClient} client - Client the collector will use
	 * @param {ArgumentInfo[]} args - Arguments for the collector
	 * @param {number} [promptLimit=Infinity] - Maximum number of times to prompt for a single argument
	 */
	constructor(client, args, promptLimit = Infinity) {
		if(!client) throw new TypeError('Collector client must be specified.');
		if(!args || !Array.isArray(args)) throw new TypeError('Collector args must be an Array.');
		if(promptLimit === null) promptLimit = Infinity;

		/**
		 * Client this collector is for
		 * @name ArgumentCollector#client
		 * @type {CommandoClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * Arguments the collector handles
		 * @type {Argument[]}
		 */
		this.args = new Array(args.length);

		let hasInfinite = false;
		let hasOptional = false;
		for(let i = 0; i < args.length; i++) {
			if(hasInfinite) throw new Error('No other argument may come after an infinite argument.');
			if(args[i].default !== null) hasOptional = true;
			else if(hasOptional) throw new Error('Required arguments may not come after optional arguments.');
			this.args[i] = new Argument(this.client, args[i]);
			if(this.args[i].infinite) hasInfinite = true;
		}

		/**
		 * Maximum number of times to prompt for a single argument
		 * @type {number}
		 */
		this.promptLimit = promptLimit;
	}

	/**
	 * Result object from obtaining argument values from an {@link ArgumentCollector}
	 * @typedef {Object} ArgumentCollectorResult
	 * @property {?Object} values - Final values for the arguments, mapped by their keys
	 * @property {?string} cancelled - One of:
	 * - `user` (user cancelled)
	 * - `time` (wait time exceeded)
	 * - `promptLimit` (prompt limit exceeded)
	 * @property {Message[]} prompts - All messages that were sent to prompt the user
	 * @property {Message[]} answers - All of the user's messages that answered a prompt
	 */

	/**
	 * Obtains values for the arguments, prompting if necessary.
	 * @param {CommandoMessage} msg - Message that the collector is being triggered by
	 * @param {Array<*>} [provided=[]] - Values that are already available
	 * @param {number} [promptLimit=this.promptLimit] - Maximum number of times to prompt for a single argument
	 * @return {Promise<ArgumentCollectorResult>}
	 */
	async obtain(msg, provided = [], promptLimit = this.promptLimit) {
		this.client.dispatcher._awaiting.add(msg.message.author.id + msg.message.channel.id);
		const values = {};
		const results = [];

		try {
			for(let i = 0; i < this.args.length; i++) {
				/* eslint-disable no-await-in-loop */
				const arg = this.args[i];
				const result = await arg.obtain(msg, arg.infinite ? provided.slice(i) : provided[i], promptLimit);
				results.push(result);

				if(result.cancelled) {
					this.client.dispatcher._awaiting.delete(msg.message.author.id + msg.message.channel.id);
					return {
						values: null,
						cancelled: result.cancelled,
						prompts: [].concat(...results.map(res => res.prompts)),
						answers: [].concat(...results.map(res => res.answers))
					};
				}

				values[arg.key] = result.value;
				/* eslint-enable no-await-in-loop */
			}
		} catch(err) {
			this.client.dispatcher._awaiting.delete(msg.message.author.id + msg.message.channel.id);
			throw err;
		}

		this.client.dispatcher._awaiting.delete(msg.message.author.id + msg.message.channel.id);
		return {
			values,
			cancelled: null,
			prompts: [].concat(...results.map(res => res.prompts)),
			answers: [].concat(...results.map(res => res.answers))
		};
	}
}

module.exports = ArgumentCollector;
<commit_msg>Fix ArgumentCollector<commit_after>const Argument = require('./argument');

/** Obtains, validates, and prompts for argument values */
class ArgumentCollector {
	/**
	 * @param {CommandoClient} client - Client the collector will use
	 * @param {ArgumentInfo[]} args - Arguments for the collector
	 * @param {number} [promptLimit=Infinity] - Maximum number of times to prompt for a single argument
	 */
	constructor(client, args, promptLimit = Infinity) {
		if(!client) throw new TypeError('Collector client must be specified.');
		if(!args || !Array.isArray(args)) throw new TypeError('Collector args must be an Array.');
		if(promptLimit === null) promptLimit = Infinity;

		/**
		 * Client this collector is for
		 * @name ArgumentCollector#client
		 * @type {CommandoClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * Arguments the collector handles
		 * @type {Argument[]}
		 */
		this.args = new Array(args.length);

		let hasInfinite = false;
		let hasOptional = false;
		for(let i = 0; i < args.length; i++) {
			if(hasInfinite) throw new Error('No other argument may come after an infinite argument.');
			if(args[i].default !== null) hasOptional = true;
			else if(hasOptional) throw new Error('Required arguments may not come after optional arguments.');
			this.args[i] = new Argument(this.client, args[i]);
			if(this.args[i].infinite) hasInfinite = true;
		}

		/**
		 * Maximum number of times to prompt for a single argument
		 * @type {number}
		 */
		this.promptLimit = promptLimit;
	}

	/**
	 * Result object from obtaining argument values from an {@link ArgumentCollector}
	 * @typedef {Object} ArgumentCollectorResult
	 * @property {?Object} values - Final values for the arguments, mapped by their keys
	 * @property {?string} cancelled - One of:
	 * - `user` (user cancelled)
	 * - `time` (wait time exceeded)
	 * - `promptLimit` (prompt limit exceeded)
	 * @property {Message[]} prompts - All messages that were sent to prompt the user
	 * @property {Message[]} answers - All of the user's messages that answered a prompt
	 */

	/**
	 * Obtains values for the arguments, prompting if necessary.
	 * @param {CommandoMessage} msg - Message that the collector is being triggered by
	 * @param {Array<*>} [provided=[]] - Values that are already available
	 * @param {number} [promptLimit=this.promptLimit] - Maximum number of times to prompt for a single argument
	 * @return {Promise<ArgumentCollectorResult>}
	 */
	async obtain(msg, provided = [], promptLimit = this.promptLimit) {
		this.client.dispatcher._awaiting.add(msg.author.id + msg.channel.id);
		const values = {};
		const results = [];

		try {
			for(let i = 0; i < this.args.length; i++) {
				/* eslint-disable no-await-in-loop */
				const arg = this.args[i];
				const result = await arg.obtain(msg, arg.infinite ? provided.slice(i) : provided[i], promptLimit);
				results.push(result);

				if(result.cancelled) {
					this.client.dispatcher._awaiting.delete(msg.author.id + msg.channel.id);
					return {
						values: null,
						cancelled: result.cancelled,
						prompts: [].concat(...results.map(res => res.prompts)),
						answers: [].concat(...results.map(res => res.answers))
					};
				}

				values[arg.key] = result.value;
				/* eslint-enable no-await-in-loop */
			}
		} catch(err) {
			this.client.dispatcher._awaiting.delete(msg.author.id + msg.channel.id);
			throw err;
		}

		this.client.dispatcher._awaiting.delete(msg.author.id + msg.channel.id);
		return {
			values,
			cancelled: null,
			prompts: [].concat(...results.map(res => res.prompts)),
			answers: [].concat(...results.map(res => res.answers))
		};
	}
}

module.exports = ArgumentCollector;
<|endoftext|>


<commit_before>'use babel';
'use strict';

import { stripIndents, oneLine } from 'common-tags';
import Command from '../command';

export default class HelpCommand extends Command {
	constructor(bot) {
		super(bot, {
			name: 'help',
			module: 'info',
			memberName: 'help',
			aliases: ['commands'],
			description: 'Displays a list of available commands, or detailed information for a specified command.',
			usage: 'help [command]',
			details: 'The command may be part of a command name or a whole command name. If it isn\'t specified, all available commands will be listed.',
			examples: ['help', 'help roll']
		});
	}

	async run(message, args) {
		const util = this.bot.util;
		const modules = this.bot.registry.modules;
		const commands = this.bot.registry.findCommands(args[0], message);
		const showAll = args[0] && args[0].toLowerCase() === 'all';
		if(args[0] && !showAll) {
			if(commands.length === 1) {
				let help = stripIndents`
					__Command **${commands[0].name}**:__ ${commands[0].description}${commands[0].guildOnly ? ' (Usable only in servers)' : ''}

					**Usage:** ${util.usage(commands[0].usage, message.guild)}
				`;
				if(commands[0].aliases.length > 0) help += `\n**Aliases:** ${commands[0].aliases.join(', ')}`;
				help += `\n**Module:** ${this.bot.registry.findModules(commands[0].module)[0].name} (\`${commands[0].module}:${commands[0].memberName}\`)`;
				if(commands[0].details) help += `\n**Details:** ${commands[0].details}`;
				if(commands[0].examples) help += `\n**Examples:**\n${commands[0].examples.join('\n')}`;
				return { direct: help, reply: 'Sent a DM to you with information.' };
			} else if(commands.length > 1) {
				return util.disambiguation(commands, 'commands');
			} else {
				return `Unable to identify command. Use ${util.usage('help', message.guild)} to view the list of all commands.`;
			}
		} else {
			return {
				direct: util.split(stripIndents`
					${oneLine`
						To run a command in ${message.guild || 'any server'},
						use ${util.usage('command', message.guild, !message.guild)}.
						For example, ${util.usage('roll d20', message.guild, !message.guild)}.
					`}
					To run a command in this DM, simply use ${util.usage('command')} with no prefix. For example, ${util.usage('roll d20')}.
					Hyphens (\`-\`) are always optional in commands.

					Use ${util.usage('help <command>')} to view detailed information about a specific command.
					Use ${util.usage('help all')} to view a list of *all* commands, not just available ones.

					__**${showAll ? 'All commands' : `Available commands in ${message.guild || 'this DM'}`}**__

					${(showAll ? modules : modules.filter(mod => mod.commands.some(cmd => cmd.isUsable(message)))).map(mod => stripIndents`
						__${mod.name}__
						${(showAll ? mod.commands : mod.commands.filter(cmd => cmd.isUsable(message)))
							.map(cmd => `**${cmd.name}:** ${cmd.description}`).join('\n')
						}
					`).join('\n\n')}
				`),
				reply: 'Sent a DM to you with information.'
			};
		}
	}
}
<commit_msg>Changed example command<commit_after>'use babel';
'use strict';

import { stripIndents, oneLine } from 'common-tags';
import Command from '../command';

export default class HelpCommand extends Command {
	constructor(bot) {
		super(bot, {
			name: 'help',
			module: 'info',
			memberName: 'help',
			aliases: ['commands'],
			description: 'Displays a list of available commands, or detailed information for a specified command.',
			usage: 'help [command]',
			details: 'The command may be part of a command name or a whole command name. If it isn\'t specified, all available commands will be listed.',
			examples: ['help', 'help roll']
		});
	}

	async run(message, args) {
		const util = this.bot.util;
		const modules = this.bot.registry.modules;
		const commands = this.bot.registry.findCommands(args[0], message);
		const showAll = args[0] && args[0].toLowerCase() === 'all';
		if(args[0] && !showAll) {
			if(commands.length === 1) {
				let help = stripIndents`
					__Command **${commands[0].name}**:__ ${commands[0].description}${commands[0].guildOnly ? ' (Usable only in servers)' : ''}

					**Usage:** ${util.usage(commands[0].usage, message.guild)}
				`;
				if(commands[0].aliases.length > 0) help += `\n**Aliases:** ${commands[0].aliases.join(', ')}`;
				help += `\n**Module:** ${this.bot.registry.findModules(commands[0].module)[0].name} (\`${commands[0].module}:${commands[0].memberName}\`)`;
				if(commands[0].details) help += `\n**Details:** ${commands[0].details}`;
				if(commands[0].examples) help += `\n**Examples:**\n${commands[0].examples.join('\n')}`;
				return { direct: help, reply: 'Sent a DM to you with information.' };
			} else if(commands.length > 1) {
				return util.disambiguation(commands, 'commands');
			} else {
				return `Unable to identify command. Use ${util.usage('help', message.guild)} to view the list of all commands.`;
			}
		} else {
			return {
				direct: util.split(stripIndents`
					${oneLine`
						To run a command in ${message.guild || 'any server'},
						use ${util.usage('command', message.guild, !message.guild)}.
						For example, ${util.usage('prefix', message.guild, !message.guild)}.
					`}
					To run a command in this DM, simply use ${util.usage('command')} with no prefix. For example, ${util.usage('roll d20')}.
					Hyphens (\`-\`) are always optional in commands.

					Use ${util.usage('help <command>')} to view detailed information about a specific command.
					Use ${util.usage('help all')} to view a list of *all* commands, not just available ones.

					__**${showAll ? 'All commands' : `Available commands in ${message.guild || 'this DM'}`}**__

					${(showAll ? modules : modules.filter(mod => mod.commands.some(cmd => cmd.isUsable(message)))).map(mod => stripIndents`
						__${mod.name}__
						${(showAll ? mod.commands : mod.commands.filter(cmd => cmd.isUsable(message)))
							.map(cmd => `**${cmd.name}:** ${cmd.description}`).join('\n')
						}
					`).join('\n\n')}
				`),
				reply: 'Sent a DM to you with information.'
			};
		}
	}
}
<|endoftext|>


<commit_before>function drawGraph(titleName, container, unit, apiMethod) {
  var dataPoints = [];

  var chart = new CanvasJS.Chart(container,{
    title: {
      text: titleName
    },
    legend: {
      verticalAlign: "top",
      horizontalAlign: "center",
      fontSize: 14,
      fontWeight: "bold",
      fontFamily: "calibri",
      fontColor: "dimGrey"
    },
    axisX: {
      title: "Time",
      valueFormatString: "HH:mm:ss" ,
    },
    axisY:{
      title: "Value",
      suffix: " " + unit,
      includeZero: false
    },
    data: [{
      type: "line",
      xValueFormatString: "HH:mm:ss",
      xValueType: "dateTime",
      dataPoints: dataPoints
    }],
  });

  var updateInterval = 5000;
  var yValue1 = 0;
  var time = new Date;

  var updateChart = function (count) {
    time.setTime(time.getTime()+ updateInterval);
    // var deltaY1 = .5 + Math.random() *(-.5-.5);
    // yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
    yValue1 = apiCall(apiMethod, false);

    dataPoints.push({
      x: time.getTime(),
      y: yValue1.data
    });

    chart.render();
  };

  updateChart(100);
  // setInterval(function(){updateChart()}, updateInterval);
}

var rainStatusIcons = {"Rain": "wi wi-rain",
                       "High humidity / Light rain": "wi wi-humidity",
                       "Drought": "wi wi-day-sunny"};

function getRainStatus(rainStatusApi){
  var status = null;
  status = apiCall(rainStatusApi, false);
  $("#rainStatus").text(status.data);
  $("#rainStatusIcon").attr("class", rainStatusIcons[status.data]);
}

function setInitialValveState(valveStatusApi){
  var valveStatus = null;
  valveStatus = apiCall(valveStatusApi, false);
  if (valveStatus.data[0] == 0){
    $("#buttonValve").attr("class", "btn btn-danger");
    $("#buttonValve").text(valveStatus.data[1]);
    $("#dropdownValve").attr("class", "btn btn-danger dropdown-toggle");
  }else if (valveStatus.data[0] == 1) {
    $("#buttonValve").attr("class", "btn btn-success");
    $("#buttonValve").text(valveStatus.data[1]);
    $("#dropdownValve").attr("class", "btn btn-success dropdown-toggle");
  }
}

function turnValve(status){
  apiCall("setValve/"+status, false)
  if (status == "off"){
    $("#buttonValve").attr("class", "btn btn-danger");
    $("#buttonValve").text("OFF");
    $("#dropdownValve").attr("class", "btn btn-danger dropdown-toggle");
  }else if (status == "on") {
    $("#buttonValve").attr("class", "btn btn-success");
    $("#buttonValve").text("ON");
    $("#dropdownValve").attr("class", "btn btn-success dropdown-toggle");
  }
}

function updateCronTable(){
  response = apiCall('cronTable', false);
  $("#crons").html(response);
}

urlRoot = "http://127.0.0.1:5000/";

function addCron(){
  checkedDays = $("input[type=checkbox][name*='dow']:checked").length;
  if(!checkedDays) {
    alert("You must check at least one day!");
    return false;
  }
  checkedHours = $("input[type=checkbox][name*='hour']:checked").length;
  if(!checkedHours) {
    alert("You must check at least one hour!");
    return false;
  }

  $.ajax({
    url: urlRoot + 'addCron',
    data: $('#cronForm').serialize(),
    type: 'POST',
    success: function(response) {
      $('input[type=checkbox]').prop('checked', false);
      $('#addCronButton').blur();
      updateCronTable();
    },
    error: function(error) {
      console.log(error);
    }
  });
}

function deleteCron(id){
  apiCall("deleteCron/"+id, true);
  updateCronTable();
}

function apiCall(apiMethod, asyncType){
  var apiCallResult = null;
  $.ajax({
    url: urlRoot + apiMethod,
    async: asyncType,
    success: function(result){
        apiCallResult = result;
    }
  });

  return apiCallResult;
}
<commit_msg>minor changes<commit_after>function drawGraph(titleName, container, unit, apiMethod) {
  var dataPoints = [];

  var chart = new CanvasJS.Chart(container,{
    title: {
      text: titleName
    },
    legend: {
      verticalAlign: "top",
      horizontalAlign: "center",
      fontSize: 14,
      fontWeight: "bold",
      fontFamily: "calibri",
      fontColor: "dimGrey"
    },
    axisX: {
      title: "Time",
      valueFormatString: "HH:mm:ss" ,
    },
    axisY:{
      title: "Value",
      suffix: " " + unit,
      includeZero: false
    },
    data: [{
      type: "line",
      xValueFormatString: "HH:mm:ss",
      xValueType: "dateTime",
      dataPoints: dataPoints
    }],
  });

  var updateInterval = 5000;
  var yValue1 = 0;
  var time = new Date;

  var updateChart = function (count) {
    time.setTime(time.getTime()+ updateInterval);
    // var deltaY1 = .5 + Math.random() *(-.5-.5);
    // yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
    yValue1 = apiCall(apiMethod, false);

    dataPoints.push({
      x: time.getTime(),
      y: yValue1.data
    });

    chart.render();
  };

  updateChart(100);
  setInterval(function(){updateChart()}, updateInterval);
}

var rainStatusIcons = {"Rain": "wi wi-rain",
                       "High humidity / Light rain": "wi wi-humidity",
                       "Drought": "wi wi-day-sunny"};

function getRainStatus(rainStatusApi){
  var status = null;
  status = apiCall(rainStatusApi, false);
  $("#rainStatus").text(status.data);
  $("#rainStatusIcon").attr("class", rainStatusIcons[status.data]);
}

function setInitialValveState(valveStatusApi){
  var valveStatus = null;
  valveStatus = apiCall(valveStatusApi, false);
  if (valveStatus.data[0] == 0){
    $("#buttonValve").attr("class", "btn btn-danger");
    $("#buttonValve").text(valveStatus.data[1]);
    $("#dropdownValve").attr("class", "btn btn-danger dropdown-toggle");
  }else if (valveStatus.data[0] == 1) {
    $("#buttonValve").attr("class", "btn btn-success");
    $("#buttonValve").text(valveStatus.data[1]);
    $("#dropdownValve").attr("class", "btn btn-success dropdown-toggle");
  }
}

function turnValve(status){
  apiCall("setValve/"+status, false)
  if (status == "off"){
    $("#buttonValve").attr("class", "btn btn-danger");
    $("#buttonValve").text("OFF");
    $("#dropdownValve").attr("class", "btn btn-danger dropdown-toggle");
  }else if (status == "on") {
    $("#buttonValve").attr("class", "btn btn-success");
    $("#buttonValve").text("ON");
    $("#dropdownValve").attr("class", "btn btn-success dropdown-toggle");
  }
}

function updateCronTable(){
  response = apiCall('cronTable', false);
  $("#crons").html(response);
}

urlRoot = "http://127.0.0.1:5000/";

function addCron(){
  checkedDays = $("input[type=checkbox][name*='dow']:checked").length;
  if(!checkedDays) {
    alert("You must check at least one day!");
    return false;
  }
  checkedHours = $("input[type=checkbox][name*='hour']:checked").length;
  if(!checkedHours) {
    alert("You must check at least one hour!");
    return false;
  }

  $.ajax({
    url: urlRoot + 'addCron',
    data: $('#cronForm').serialize(),
    type: 'POST',
    success: function(response) {
      $('input[type=checkbox]').prop('checked', false);
      $('#addCronButton').blur();
      updateCronTable();
    },
    error: function(error) {
      console.log(error);
    }
  });
}

function deleteCron(id){
  apiCall("deleteCron/"+id, true);
  updateCronTable();
}

function apiCall(apiMethod, asyncType){
  var apiCallResult = null;
  $.ajax({
    url: urlRoot + apiMethod,
    async: asyncType,
    success: function(result){
        apiCallResult = result;
    }
  });

  return apiCallResult;
}
<|endoftext|>


<commit_before>(function () {
  var path = require('path')
  var FileSystemBlobStore = require('../src/file-system-blob-store')
  var NativeCompileCache = require('../src/native-compile-cache')

  var loadSettings = null
  var loadSettingsError = null
  var blobStore = null

  window.onload = function () {
    try {
      var startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      blobStore = FileSystemBlobStore.load(
        path.join(process.env.ATOM_HOME, 'blob-store/')
      )
      NativeCompileCache.setCacheStore(blobStore)
      NativeCompileCache.install()

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      if (loadSettingsError) {
        throw loadSettingsError
      }

      var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep)

      if (devMode) {
        setupDeprecatedPackages()
      }

      if (loadSettings.profileStartup) {
        profileStartup(loadSettings, Date.now() - startTime)
      } else {
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
      console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms')
    }
  }

  function handleSetupError (error) {
    var currentWindow = require('remote').getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow (loadSettings) {
    var CompileCache = require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)

    var ModuleCache = require('../src/module-cache')
    ModuleCache.register(loadSettings)
    ModuleCache.add(loadSettings.resourcePath)

    // Start the crash reporter before anything else.
    require('crash-reporter').start({
      productName: 'Atom',
      companyName: 'GitHub',
      // By explicitly passing the app version here, we could save the call
      // of "require('remote').require('app').getVersion()".
      extra: {_version: loadSettings.appVersion}
    })

    setupVmCompatibility()
    setupCsonCache(CompileCache.getCacheDirectory())

    var initialize = require(loadSettings.windowInitializationScript)
    initialize({blobStore: blobStore})
    require('ipc').sendChannel('window-command', 'window:loaded')
  }

  function setupCsonCache (cacheDir) {
    require('season').setCacheDir(path.join(cacheDir, 'cson'))
  }

  function setupVmCompatibility () {
    var vm = require('vm')
    if (!vm.Script.createContext) {
      vm.Script.createContext = vm.createContext
    }
  }

  function setupDeprecatedPackages () {
    var metadata = require('../package.json')
    if (!metadata._deprecatedPackages) {
      try {
        metadata._deprecatedPackages = require('../build/deprecated-packages.json')
      } catch(requireError) {
        console.error('Failed to setup deprecated packages list', requireError.stack)
      }
    }
  }

  function profileStartup (loadSettings, initialTime) {
    function profile () {
      console.profile('startup')
      try {
        var startTime = Date.now()
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime + initialTime)
      } catch (error) {
        handleSetupError(error)
      } finally {
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      }
    }

    var currentWindow = require('remote').getCurrentWindow()
    if (currentWindow.devToolsWebContents) {
      profile()
    } else {
      currentWindow.openDevTools()
      currentWindow.once('devtools-opened', function () {
        setTimeout(profile, 1000)
      })
    }
  }

  function parseLoadSettings () {
    var rawLoadSettings = decodeURIComponent(window.location.hash.substr(1))
    try {
      loadSettings = JSON.parse(rawLoadSettings)
    } catch (error) {
      console.error('Failed to parse load settings: ' + rawLoadSettings)
      loadSettingsError = error
    }
  }

  function setupWindowBackground () {
    if (loadSettings && loadSettings.isSpec) {
      return
    }

    var backgroundColor = window.localStorage.getItem('atom:window-background-color')
    if (!backgroundColor) {
      return
    }

    var backgroundStylesheet = document.createElement('style')
    backgroundStylesheet.type = 'text/css'
    backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + ' !important; }'
    document.head.appendChild(backgroundStylesheet)

    // Remove once the page loads
    window.addEventListener('load', function loadWindow () {
      window.removeEventListener('load', loadWindow, false)
      setTimeout(function () {
        backgroundStylesheet.remove()
        backgroundStylesheet = null
      }, 1000)
    }, false)
  }

  var setupAtomHome = function () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // issue #5142
    if (loadSettings && loadSettings.atomHome) {
      process.env.ATOM_HOME = loadSettings.atomHome
    }
  }

  parseLoadSettings()
  setupAtomHome()
  setupWindowBackground()
})()
<commit_msg>Link fully to issue<commit_after>(function () {
  var path = require('path')
  var FileSystemBlobStore = require('../src/file-system-blob-store')
  var NativeCompileCache = require('../src/native-compile-cache')

  var loadSettings = null
  var loadSettingsError = null
  var blobStore = null

  window.onload = function () {
    try {
      var startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      blobStore = FileSystemBlobStore.load(
        path.join(process.env.ATOM_HOME, 'blob-store/')
      )
      NativeCompileCache.setCacheStore(blobStore)
      NativeCompileCache.install()

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      if (loadSettingsError) {
        throw loadSettingsError
      }

      var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep)

      if (devMode) {
        setupDeprecatedPackages()
      }

      if (loadSettings.profileStartup) {
        profileStartup(loadSettings, Date.now() - startTime)
      } else {
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
      console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms')
    }
  }

  function handleSetupError (error) {
    var currentWindow = require('remote').getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow (loadSettings) {
    var CompileCache = require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)

    var ModuleCache = require('../src/module-cache')
    ModuleCache.register(loadSettings)
    ModuleCache.add(loadSettings.resourcePath)

    // Start the crash reporter before anything else.
    require('crash-reporter').start({
      productName: 'Atom',
      companyName: 'GitHub',
      // By explicitly passing the app version here, we could save the call
      // of "require('remote').require('app').getVersion()".
      extra: {_version: loadSettings.appVersion}
    })

    setupVmCompatibility()
    setupCsonCache(CompileCache.getCacheDirectory())

    var initialize = require(loadSettings.windowInitializationScript)
    initialize({blobStore: blobStore})
    require('ipc').sendChannel('window-command', 'window:loaded')
  }

  function setupCsonCache (cacheDir) {
    require('season').setCacheDir(path.join(cacheDir, 'cson'))
  }

  function setupVmCompatibility () {
    var vm = require('vm')
    if (!vm.Script.createContext) {
      vm.Script.createContext = vm.createContext
    }
  }

  function setupDeprecatedPackages () {
    var metadata = require('../package.json')
    if (!metadata._deprecatedPackages) {
      try {
        metadata._deprecatedPackages = require('../build/deprecated-packages.json')
      } catch(requireError) {
        console.error('Failed to setup deprecated packages list', requireError.stack)
      }
    }
  }

  function profileStartup (loadSettings, initialTime) {
    function profile () {
      console.profile('startup')
      try {
        var startTime = Date.now()
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime + initialTime)
      } catch (error) {
        handleSetupError(error)
      } finally {
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      }
    }

    var currentWindow = require('remote').getCurrentWindow()
    if (currentWindow.devToolsWebContents) {
      profile()
    } else {
      currentWindow.openDevTools()
      currentWindow.once('devtools-opened', function () {
        setTimeout(profile, 1000)
      })
    }
  }

  function parseLoadSettings () {
    var rawLoadSettings = decodeURIComponent(window.location.hash.substr(1))
    try {
      loadSettings = JSON.parse(rawLoadSettings)
    } catch (error) {
      console.error('Failed to parse load settings: ' + rawLoadSettings)
      loadSettingsError = error
    }
  }

  function setupWindowBackground () {
    if (loadSettings && loadSettings.isSpec) {
      return
    }

    var backgroundColor = window.localStorage.getItem('atom:window-background-color')
    if (!backgroundColor) {
      return
    }

    var backgroundStylesheet = document.createElement('style')
    backgroundStylesheet.type = 'text/css'
    backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + ' !important; }'
    document.head.appendChild(backgroundStylesheet)

    // Remove once the page loads
    window.addEventListener('load', function loadWindow () {
      window.removeEventListener('load', loadWindow, false)
      setTimeout(function () {
        backgroundStylesheet.remove()
        backgroundStylesheet = null
      }, 1000)
    }, false)
  }

  var setupAtomHome = function () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // https://github.com/atom/atom/issues/5142
    if (loadSettings && loadSettings.atomHome) {
      process.env.ATOM_HOME = loadSettings.atomHome
    }
  }

  parseLoadSettings()
  setupAtomHome()
  setupWindowBackground()
})()
<|endoftext|>


<commit_before>var BBEvents = require('backbone-events-standalone');
var extend = require('extend-object');

var result = function (obj, prop) {
    if (typeof obj[prop] === 'function') return obj[prop]();
    return prop;
};

function FormView(opts) {
    this.el = opts.el;
    this.validCallback = opts.validCallback || this.validCallback || function () {};
    this.submitCallback = opts.submitCallback || this.submitCallback || function () {};

    if (opts.data) this.data = opts.data;
    if (opts.model) this.model = opts.model;

    this.clean = opts.clean || function (res) { return res; };
    this.valid = false;
    this.preventDefault = opts.preventDefault === false ? false : true;
    this.autoAppend = opts.autoAppend === false ? false : true;

    // storage for our fields
    this._fieldViews = {};
    this._fieldViewsArray = [];

    // add all our fields
    this.render();

    (opts.fields || result(this, 'fields') || []).forEach(this.addField.bind(this));

    if (this.initialize) this.initialize();

    //defer till after returning from initialize
    setTimeout(function () {
        this.checkValid(true);
    }.bind(this), 0);
}

extend(FormView.prototype, BBEvents, {
    data: null,
    model: null,
    fields: null,

    addField: function (fieldView) {
        this._fieldViews[fieldView.name] = fieldView;
        this._fieldViewsArray.push(fieldView);
        if (this.fieldContainerEl) {
            fieldView.parent = this;
            fieldView.render();
            this.fieldContainerEl.appendChild(fieldView.el);
        }
    },

    removeField: function (name) {
        delete this._fieldViews[fieldView.name];
        this._fieldViewsArray.splice(this._fieldViewsArray.indexOf(field), 1);
        this.getField(name).remove();
    },

    getField: function (name) {
        return this._fieldViews[name];
    },

    setValid: function (now, forceFire) {
        var prev = this.valid;
        this.valid = now;
        if (prev !== now || forceFire) {
            this.validCallback(now);
        }
    },

    checkValid: function (forceFire) {
        var valid = this._fieldViewsArray.every(function (field) {
            return field.valid;
        });
        this.setValid(valid, forceFire);
        return valid;
    },

    beforeSubmit: function () {
        this._fieldViewsArray.forEach(function (field) {
            if (field.beforeSubmit) field.beforeSubmit();
        });
    },

    update: function (field) {
        this.trigger('change:' + field.name, field);
        // if this one's good check 'em all
        if (field.valid) {
            this.checkValid();
        } else {
            this.setValid(false);
        }
    },

    remove: function () {
        this.el.removeEventListener('submit', this.handleSubmit, false);
        var parent = this.el.parentNode;
        if (parent) parent.removeChild(this.el);
        this._fieldViewsArray.forEach(function (field) {
            field.remove();
        });
    },

    handleSubmit: function (e) {
        this.beforeSubmit();
        this.checkValid();
        if (!this.valid) {
            e.preventDefault();
            return false;
        }

        if (this.preventDefault) {
            e.preventDefault();
            this.submitCallback(this.getData());
            return false;
        }
    },

    getData: function () {
        var res = {};
        for (var key in this._fieldViews) {
            res[key] = this._fieldViews[key].value;
        }
        return this.clean(res);
    },

    render: function () {
        if (this.rendered) return;
        if (!this.el) {
            this.el = document.createElement('form');
        }
        if (this.autoAppend) {
            this.fieldContainerEl = this.el.querySelector('[data-hook~=field-container]') || this.el;
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.el.addEventListener('submit', this.handleSubmit, false);
        this.rendered = true;
    }
});

FormView.extend = function (obj) {
    var child = function () {
       FormView.apply(this, arguments);
    };

    extend(child.prototype, FormView.prototype);
    extend(child.prototype, obj);

    return child;
};

module.exports = FormView;
<commit_msg>clearData convenience method<commit_after>var BBEvents = require('backbone-events-standalone');
var extend = require('extend-object');

var result = function (obj, prop) {
    if (typeof obj[prop] === 'function') return obj[prop]();
    return prop;
};

function FormView(opts) {
    this.el = opts.el;
    this.validCallback = opts.validCallback || this.validCallback || function () {};
    this.submitCallback = opts.submitCallback || this.submitCallback || function () {};

    if (opts.data) this.data = opts.data;
    if (opts.model) this.model = opts.model;

    this.clean = opts.clean || function (res) { return res; };
    this.valid = false;
    this.preventDefault = opts.preventDefault === false ? false : true;
    this.autoAppend = opts.autoAppend === false ? false : true;

    // storage for our fields
    this._fieldViews = {};
    this._fieldViewsArray = [];

    // add all our fields
    this.render();

    (opts.fields || result(this, 'fields') || []).forEach(this.addField.bind(this));

    if (this.initialize) this.initialize();

    //defer till after returning from initialize
    setTimeout(function () {
        this.checkValid(true);
    }.bind(this), 0);
}

extend(FormView.prototype, BBEvents, {
    data: null,
    model: null,
    fields: null,

    addField: function (fieldView) {
        this._fieldViews[fieldView.name] = fieldView;
        this._fieldViewsArray.push(fieldView);
        if (this.fieldContainerEl) {
            fieldView.parent = this;
            fieldView.render();
            this.fieldContainerEl.appendChild(fieldView.el);
        }
    },

    removeField: function (name) {
        delete this._fieldViews[fieldView.name];
        this._fieldViewsArray.splice(this._fieldViewsArray.indexOf(field), 1);
        this.getField(name).remove();
    },

    getField: function (name) {
        return this._fieldViews[name];
    },

    setValid: function (now, forceFire) {
        var prev = this.valid;
        this.valid = now;
        if (prev !== now || forceFire) {
            this.validCallback(now);
        }
    },

    checkValid: function (forceFire) {
        var valid = this._fieldViewsArray.every(function (field) {
            return field.valid;
        });
        this.setValid(valid, forceFire);
        return valid;
    },

    beforeSubmit: function () {
        this._fieldViewsArray.forEach(function (field) {
            if (field.beforeSubmit) field.beforeSubmit();
        });
    },

    update: function (field) {
        this.trigger('change:' + field.name, field);
        // if this one's good check 'em all
        if (field.valid) {
            this.checkValid();
        } else {
            this.setValid(false);
        }
    },

    remove: function () {
        this.el.removeEventListener('submit', this.handleSubmit, false);
        var parent = this.el.parentNode;
        if (parent) parent.removeChild(this.el);
        this._fieldViewsArray.forEach(function (field) {
            field.remove();
        });
    },

    handleSubmit: function (e) {
        this.beforeSubmit();
        this.checkValid();
        if (!this.valid) {
            e.preventDefault();
            return false;
        }

        if (this.preventDefault) {
            e.preventDefault();
            this.submitCallback(this.getData());
            return false;
        }
    },

    getData: function () {
        var res = {};
        for (var key in this._fieldViews) {
            res[key] = this._fieldViews[key].value;
        }
        return this.clean(res);
    },

    clearData: function () {
        for (var key in this._fieldViews) {
            this._fieldViews[key].value = null;
        }
    },

    render: function () {
        if (this.rendered) return;
        if (!this.el) {
            this.el = document.createElement('form');
        }

        if (this.autoAppend) {
            this.fieldContainerEl = this.el.querySelector('[data-hook~=field-container]') || this.el;
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.el.addEventListener('submit', this.handleSubmit, false);

        this.rendered = true;
    }
});

FormView.extend = function (obj) {
    var child = function () {
       FormView.apply(this, arguments);
    };

    extend(child.prototype, FormView.prototype);
    extend(child.prototype, obj);

    return child;
};

module.exports = FormView;
<|endoftext|>


<commit_before>(function () {
  var fs = require('fs')
  var path = require('path')

  var loadSettings = null
  var loadSettingsError = null

  window.onload = function () {
    try {
      var startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Ensure ATOM_HOME is always set before anything else is required
      setupAtomHome()

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      if (loadSettingsError) {
        throw loadSettingsError
      }

      var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep)

      if (devMode) {
        setupDeprecatedPackages()
      }

      if (loadSettings.profileStartup) {
        profileStartup(loadSettings, Date.now() - startTime)
      } else {
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
      console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms')
    }
  }

  function handleSetupError (error) {
    var currentWindow = require('remote').getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow (loadSettings) {
    var CompileCache = require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)

    var ModuleCache = require('../src/module-cache')
    ModuleCache.register(loadSettings)
    ModuleCache.add(loadSettings.resourcePath)

    // Only include deprecated APIs when running core spec
    require('grim').includeDeprecatedAPIs = isRunningCoreSpecs(loadSettings)

    // Start the crash reporter before anything else.
    require('crash-reporter').start({
      productName: 'Atom',
      companyName: 'GitHub',
      // By explicitly passing the app version here, we could save the call
      // of "require('remote').require('app').getVersion()".
      extra: {_version: loadSettings.appVersion}
    })

    setupVmCompatibility()
    setupCsonCache(CompileCache.getCacheDirectory())

    require(loadSettings.bootstrapScript)
    require('ipc').sendChannel('window-command', 'window:loaded')
  }

  function setupAtomHome () {
    if (!process.env.ATOM_HOME) {
      var home
      if (process.platform === 'win32') {
        home = process.env.USERPROFILE
      } else {
        home = process.env.HOME
      }
      var atomHome = path.join(home, '.atom')
      try {
        atomHome = fs.realpathSync(atomHome)
      } catch (error) {
        // Ignore since the path might just not exist yet.
      }
      process.env.ATOM_HOME = atomHome
    }
  }

  function setupCsonCache (cacheDir) {
    require('season').setCacheDir(path.join(cacheDir, 'cson'))
  }

  function setupVmCompatibility () {
    var vm = require('vm')
    if (!vm.Script.createContext) {
      vm.Script.createContext = vm.createContext
    }
  }

  function setupDeprecatedPackages () {
    var metadata = require('../package.json')
    if (!metadata._deprecatedPackages) {
      try {
        metadata._deprecatedPackages = require('../build/deprecated-packages.json')
      } catch(requireError) {
        console.error('Failed to setup deprecated packages list', requireError.stack)
      }
    }
  }

  function profileStartup (loadSettings, initialTime) {
    function profile () {
      console.profile('startup')
      try {
        var startTime = Date.now()
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime + initialTime)
      } catch (error) {
        handleSetupError(error)
      } finally {
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      }
    }

    var currentWindow = require('remote').getCurrentWindow()
    if (currentWindow.devToolsWebContents) {
      profile()
    } else {
      currentWindow.openDevTools()
      currentWindow.once('devtools-opened', function () {
        setTimeout(profile, 100)
      })
    }
  }

  function parseLoadSettings () {
    var rawLoadSettings = decodeURIComponent(window.location.hash.substr(1))
    try {
      loadSettings = JSON.parse(rawLoadSettings)
    } catch (error) {
      console.error('Failed to parse load settings: ' + rawLoadSettings)
      loadSettingsError = error
    }
  }

  function setupWindowBackground () {
    if (loadSettings && loadSettings.isSpec) {
      return
    }

    var backgroundColor = window.localStorage.getItem('atom:window-background-color')
    if (!backgroundColor) {
      return
    }

    var backgroundStylesheet = document.createElement('style')
    backgroundStylesheet.type = 'text/css'
    backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + '; }'
    document.head.appendChild(backgroundStylesheet)

    // Remove once the page loads
    window.addEventListener('load', function loadWindow () {
      window.removeEventListener('load', loadWindow, false)
      setTimeout(function () {
        backgroundStylesheet.remove()
        backgroundStylesheet = null
      }, 1000)
    }, false)
  }

  function isRunningCoreSpecs (loadSettings) {
    return !!(loadSettings &&
      loadSettings.isSpec &&
      loadSettings.specDirectory &&
      loadSettings.resourcePath &&
      path.dirname(loadSettings.specDirectory) === loadSettings.resourcePath)
  }

  parseLoadSettings()
  setupWindowBackground()
})()
<commit_msg>Enable Portable Mode<commit_after>(function () {
  var fs = require('fs')
  var path = require('path')

  var loadSettings = null
  var loadSettingsError = null

  window.onload = function () {
    try {
      var startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Ensure ATOM_HOME is always set before anything else is required
      setupAtomHome()

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      if (loadSettingsError) {
        throw loadSettingsError
      }

      var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep)

      if (devMode) {
        setupDeprecatedPackages()
      }

      if (loadSettings.profileStartup) {
        profileStartup(loadSettings, Date.now() - startTime)
      } else {
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function isPortableMode() {
    // No portable mode on non-Windows
    if (process.platform !== 'win32') return false

    // DevMode? Nope
    var devMode = loadSettings &&
      (loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep))

    if (devMode) return false

    // Compare our EXE's path to where it would normally be in an installed app
    var ourPath = process.execPath.toLowerCase()
    return (ourPath.indexOf(process.env.LOCALAPPDATA.toLowerCase()) === 0)
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
      console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms')
    }
  }

  function handleSetupError (error) {
    var currentWindow = require('remote').getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow (loadSettings) {
    var CompileCache = require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)

    var ModuleCache = require('../src/module-cache')
    ModuleCache.register(loadSettings)
    ModuleCache.add(loadSettings.resourcePath)

    // Only include deprecated APIs when running core spec
    require('grim').includeDeprecatedAPIs = isRunningCoreSpecs(loadSettings)

    // Start the crash reporter before anything else.
    require('crash-reporter').start({
      productName: 'Atom',
      companyName: 'GitHub',
      // By explicitly passing the app version here, we could save the call
      // of "require('remote').require('app').getVersion()".
      extra: {_version: loadSettings.appVersion}
    })

    setupVmCompatibility()
    setupCsonCache(CompileCache.getCacheDirectory())

    require(loadSettings.bootstrapScript)
    require('ipc').sendChannel('window-command', 'window:loaded')
  }

  function setupAtomHome () {
    if (!process.env.ATOM_HOME) {
      var home
      if (process.platform === 'win32') {
        home = process.env.USERPROFILE
      } else {
        home = process.env.HOME
      }
      var atomHome = path.join(home, '.atom')
      try {
        atomHome = fs.realpathSync(atomHome)
      } catch (error) {
        // If we're in portable mode *and* the user doesn't already have a .atom
        // folder in the normal place, we'll use the portable folder instead
        if (isPortableMode()) {
          atomHome = path.join(path.dirname(process.execPath), '.atom')
        }
      }
      process.env.ATOM_HOME = atomHome
    }
  }

  function setupCsonCache (cacheDir) {
    require('season').setCacheDir(path.join(cacheDir, 'cson'))
  }

  function setupVmCompatibility () {
    var vm = require('vm')
    if (!vm.Script.createContext) {
      vm.Script.createContext = vm.createContext
    }
  }

  function setupDeprecatedPackages () {
    var metadata = require('../package.json')
    if (!metadata._deprecatedPackages) {
      try {
        metadata._deprecatedPackages = require('../build/deprecated-packages.json')
      } catch(requireError) {
        console.error('Failed to setup deprecated packages list', requireError.stack)
      }
    }
  }

  function profileStartup (loadSettings, initialTime) {
    function profile () {
      console.profile('startup')
      try {
        var startTime = Date.now()
        setupWindow(loadSettings)
        setLoadTime(Date.now() - startTime + initialTime)
      } catch (error) {
        handleSetupError(error)
      } finally {
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      }
    }

    var currentWindow = require('remote').getCurrentWindow()
    if (currentWindow.devToolsWebContents) {
      profile()
    } else {
      currentWindow.openDevTools()
      currentWindow.once('devtools-opened', function () {
        setTimeout(profile, 100)
      })
    }
  }

  function parseLoadSettings () {
    var rawLoadSettings = decodeURIComponent(window.location.hash.substr(1))
    try {
      loadSettings = JSON.parse(rawLoadSettings)
    } catch (error) {
      console.error('Failed to parse load settings: ' + rawLoadSettings)
      loadSettingsError = error
    }
  }

  function setupWindowBackground () {
    if (loadSettings && loadSettings.isSpec) {
      return
    }

    var backgroundColor = window.localStorage.getItem('atom:window-background-color')
    if (!backgroundColor) {
      return
    }

    var backgroundStylesheet = document.createElement('style')
    backgroundStylesheet.type = 'text/css'
    backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + '; }'
    document.head.appendChild(backgroundStylesheet)

    // Remove once the page loads
    window.addEventListener('load', function loadWindow () {
      window.removeEventListener('load', loadWindow, false)
      setTimeout(function () {
        backgroundStylesheet.remove()
        backgroundStylesheet = null
      }, 1000)
    }, false)
  }

  function isRunningCoreSpecs (loadSettings) {
    return !!(loadSettings &&
      loadSettings.isSpec &&
      loadSettings.specDirectory &&
      loadSettings.resourcePath &&
      path.dirname(loadSettings.specDirectory) === loadSettings.resourcePath)
  }

  parseLoadSettings()
  setupWindowBackground()
})()
<|endoftext|>


<commit_before>define([
	'chai', 'd3', 'd3chart', 'd3ma'
], function(Chai, d3, d3chart, d3ma) {

	var expect = Chai.expect,
		should = Chai.should(),
		div,
		info,
		bars,
		testDefault;

	describe('d3.ma scale - core/scale.js', function() {
		beforeEach(function(done){
			div = document.createElement('div');
			var vis = document.body.appendChild(div);
			vis.id='vis';

			var visContainer = d3.ma.container('#vis').box(1400, 600);
			info = visContainer.info();

			var scaleChart = d3.chart('TestScale', {
				initialize: function(containerInfo) {
					bars = this.mixin('Bars', d3.select('.canvas').append('g'), {
						info: containerInfo,
						x: 'ordinal',
						y: 'log',
						width: this.base.attr('width'),  // optional
						height: this.base.attr('height')  // optional
					});

					testDefault =  this.mixin('Bars', d3.select('.canvas').append('g'), {
						info: containerInfo
					});
				}
			});

			visContainer.canvas().chart('TestScale', info );

			done();
		});

		afterEach(function(done){
			document.body.removeChild(div);
			done();
		});

		it('should have public keys property', function(done){
			//var barKeys = d3.keys(bars);
			bars.should.contain.keys(['width', 'height', 'info', 'xScale', 'yScale'  ]);
			done();
		});

		it('should have private keys property', function(done){
			bars.should.contain.keys(['_x', '_y']);
			done();
		});

		it('should have private functions', function(done){
			// 3 Private Fn: _scale, _switchXScale,  _switchYScale
			bars._scale.should.be.an('function');
			bars._switchXScale.should.be.an('function');
			bars._switchYScale.should.be.an('function');
			done();
		});

		it('should have a private fn called _scale and return a function', function(done){
			// _scale itself is a function,
			// when calling it, also return another d3.scale function
			bars._scale('linear').should.be.a('function');
			done();
		});

		it('should have scale public width property with string value', function(done){
			testDefault.width.should.be.a('number');
			bars.width.should.be.a('number');

			var width = bars.info.containerW - bars.info.marginLeft - bars.info.marginRight;
			bars.width.should.be.equal(width);

			done();
		});

		it('should have scale public height property with string value', function(done){
			testDefault.height.should.be.a('number');
			bars.height.should.be.a('number');

			var height = bars.info.containerH - bars.info.marginTop - bars.info.marginBottom;
			bars.height.should.be.equal(height);

			done();
		});

		it('should have scale public info property with string value', function(done){
			bars.info.should.be.exist;
			bars.info.should.be.an('object');
			bars.info.should.have.keys(['marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'containerW', 'containerH', 'canvasW', 'canvasH', 'id', 'cid']);
			done();
		});

		it('should have scale x property in options, match private _x property with string value', function(done){
			testDefault._x.should.be.a('string');
			bars._x.should.be.a('string');

			// default x value should be 'linear'
			testDefault._x.should.be.equal('linear');
			// can be overrided by passing x value from option
			bars._x.should.be.equal('ordinal');

			done();
		});

		it('should have scale y property in options, match private _y property with string value', function(done){
			testDefault._y.should.be.a('string');
			bars._y.should.be.a('string');

			// default x value should be 'linear'
			testDefault._y.should.be.equal('linear');
			// can be overrided by passing x value from option
			bars._y.should.be.equal('log');

			done();
		});
	});
});
<commit_msg>update the scaleTest all info to match the scale.js tets<commit_after>define([
	'chai', 'd3', 'd3chart', 'd3ma'
], function(Chai, d3, d3chart, d3ma) {

	var expect = Chai.expect,
		should = Chai.should(),
		div,
		info,
		bars,
		testDefault;

	describe('d3.ma scale - core/scale.js', function() {
		beforeEach(function(done){
			div = document.createElement('div');
			var vis = document.body.appendChild(div);
			vis.id='vis';

			var visContainer = d3.ma.container('#vis').box(1400, 600);
			info = visContainer.info();

			var scaleChart = d3.chart('TestScale', {
				initialize: function(containerInfo) {
					bars = this.mixin('Bars', d3.select('.canvas').append('g'), {
						info: containerInfo,
						x: 'ordinal',
						y: 'log',
						width: this.base.attr('width'),  // optional
						height: this.base.attr('height')  // optional
					});

					testDefault =  this.mixin('Bars', d3.select('.canvas').append('g'), {
						info: containerInfo
					});
				}
			});

			visContainer.canvas().chart('TestScale', info );

			done();
		});

		afterEach(function(done){
			document.body.removeChild(div);
			done();
		});

		it('should have public keys property', function(done){
			//var barKeys = d3.keys(bars);
			bars.should.contain.keys(['width', 'height', 'info', 'xScale', 'yScale'  ]);
			done();
		});

		it('should have private keys property', function(done){
			bars.should.contain.keys(['_x', '_y']);
			done();
		});

		it('should have private functions', function(done){
			// 3 Private Fn: _scale, _switchXScale,  _switchYScale
			bars._scale.should.be.an('function');
			bars._switchXScale.should.be.an('function');
			bars._switchYScale.should.be.an('function');
			done();
		});

		it('should have a private fn called _scale and return a function', function(done){
			// _scale itself is a function,
			// when calling it, also return another d3.scale function
			bars._scale('linear').should.be.a('function');
			done();
		});

		it('should have a private fn called _switchXScale and return a range', function(done){
			// _switchXScale called at intialization. Need to check the default range value
			//
			// testDefault has x-scale: 'linear', can be tested with range()
			testDefault.xScale.range().should.be.an('array');
			testDefault.xScale.range().should.be.eql([0, testDefault.info.canvasW]);
			// override the xScale with custom width, handle internally, should not call directly
			testDefault._switchXScale('linear', 1000);
			testDefault.xScale.range().should.be.eql([0, 1000]);

			// bars has x-scale: 'ordinal', can be tested with rangeRounds()
			bars.xScale.rangeExtent().should.be.an('array');
			bars.xScale.rangeExtent().should.be.eql([0, testDefault.info.canvasW]);
			done();
		});

		it('should have a private fn called _switchYScale and return a range', function(done){
			// _switchXScale called at intialization. Need to check the default range value
			//
			// testDefault has y-scale: 'linear', can be tested with range()
			testDefault.yScale.range().should.be.an('array');
			testDefault.yScale.range().should.be.eql([testDefault.info.canvasH, 0]);
			// override the yScale with custom width, handle internally, should not call directly
			testDefault._switchYScale('linear', 1000);
			testDefault.yScale.range().should.be.eql([1000, 0]);

			// bars has y-scale: 'log', can be tested with rangeRounds()
			bars.yScale.range().should.be.an('array');
			//bars.yScale.range().should.be.eql([testDefault.info.canvasH, 0]);
			done();
		});

		it('should have scale public width property with string value', function(done){
			testDefault.width.should.be.a('number');
			bars.width.should.be.a('number');

			var width = bars.info.containerW - bars.info.marginLeft - bars.info.marginRight;
			bars.width.should.be.equal(width);

			done();
		});

		it('should have scale public height property with string value', function(done){
			testDefault.height.should.be.a('number');
			bars.height.should.be.a('number');

			var height = bars.info.containerH - bars.info.marginTop - bars.info.marginBottom;
			bars.height.should.be.equal(height);

			done();
		});

		it('should have scale public info property with string value', function(done){
			bars.info.should.be.exist;
			bars.info.should.be.an('object');
			bars.info.should.have.keys(['marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'containerW', 'containerH', 'canvasW', 'canvasH', 'id', 'cid']);
			done();
		});

		it('should have scale x property in options, match private _x property with string value', function(done){
			testDefault._x.should.be.a('string');
			bars._x.should.be.a('string');

			// default x value should be 'linear'
			testDefault._x.should.be.equal('linear');
			// can be overrided by passing x value from option
			bars._x.should.be.equal('ordinal');

			done();
		});

		it('should have scale y property in options, match private _y property with string value', function(done){
			testDefault._y.should.be.a('string');
			bars._y.should.be.a('string');

			// default x value should be 'linear'
			testDefault._y.should.be.equal('linear');
			// can be overrided by passing x value from option
			bars._y.should.be.equal('log');

			done();
		});
	});
});
<|endoftext|>


<commit_before>import {
    some,
    every,
    toArray
} from '../../src/util/';

describe('some', () => {
    it('should return true', () => {
        expect(some([0, 1], (v) => { return v === 0; })).toBe(true);
    });

    it('should return false', () => {
        expect(some([1], (v) => { return v === 0; })).toBe(false);
    });
});

describe('every', () => {
    it('should return true', () => {
        expect(every([1, 2], (v) => { return v > 0; })).toBe(true);
    });

    it('should return false', () => {
        expect(every([], (v) => { return v > 0; })).toBe(false);
        expect(every([0, 1], (v) => { return v > 0; })).toBe(false);
    });
});

describe('toArray', () => {
    it('should return array', () => {
        expect(toArray([ 0, 1 ]).join(',') === '0,1').toBe(true);
    });

    it('should return array', () => {
        expect(toArray({
            0: 0,
            1: 1,
            length: 2
        }).join(',') === '0,1').toBe(true);
    });
});
<commit_msg>Specs for lang<commit_after>import {
    some,
    every,
    extend,
    toArray,
    toPrimitive,
    normalize
} from '../../src/util/';

describe('some', () => {
    it('should return true', () => {
        expect(some([0, 1], (v) => { return v === 0; })).toBe(true);
    });

    it('should return false', () => {
        expect(some([1], (v) => { return v === 0; })).toBe(false);
    });
});

describe('every', () => {
    it('should return true', () => {
        expect(every([1, 2], (v) => { return v > 0; })).toBe(true);
    });

    it('should return false', () => {
        expect(every([], (v) => { return v > 0; })).toBe(false);
        expect(every([0, 1], (v) => { return v > 0; })).toBe(false);
    });
});

describe('toArray', () => {
    it('should return array', () => {
        expect(toArray([ 0, 1 ]).join(',') === '0,1').toBe(true);
    });

    it('should return array', () => {
        expect(toArray({
            0: 0,
            1: 1,
            length: 2
        }).join(',') === '0,1').toBe(true);
    });
});

describe('toPrimitive', () => {
    it('should parse string', () => {
        expect(toPrimitive('')).toBe('');
        expect(toPrimitive('hello')).toBe('hello');
    });

    it('should parse number', () => {
        expect(toPrimitive('1')).toBe(1);
        expect(toPrimitive('-1')).toBe(-1);
        expect(toPrimitive('10')).toBe(10);
        expect(toPrimitive('10.1')).toBe(10.1);
        expect(toPrimitive('10e10')).toBe(10e10);
        expect(toPrimitive('10e+10')).toBe(10e10);
        expect(toPrimitive('10e-10')).toBe(10e-10);
    });

    it('should parse boolean', () => {
        expect(toPrimitive('true')).toBe(true);
        expect(toPrimitive('True')).toBe(true);
        expect(toPrimitive('false')).toBe(false);
        expect(toPrimitive('False')).toBe(false);
    });
});

describe('normalize', () => {
    it('should return small camel equivalent', () => {
        expect(normalize('my-name')).toBe('myName');
    });
});

describe('extend', () => {
    it('should copy properties', () => {
        const a = {};
        const b = { p1: 'p1', p2: 'p2' };

        extend(a, b);
        expect(a.p1).toBe(b.p1);
        expect(a.p2).toBe(b.p2);
    });

    it('should not copy inheried properties', () => {
        const a = {};
        const b = { p1: 'p1', p2: 'p2' };
        const c = Object.create(b);

        extend(a, c);
        expect(a.p1).toBeUndefined();
        expect(a.p2).toBeUndefined();
    });
});
<|endoftext|>


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

describe('Multiton axiom', function() {
  it('object sharing works', function() {
    foam.CLASS({
      name: 'Test',
      axioms: [
        foam.pattern.Multiton.create({property: 'id'})
      ],
      properties: [ 'id' ]
    });
    var a1 = Test.create({id: 'a'});
    var a2 = Test.create({id: 'a'});
    var b  = Test.create({id: 'b'});
    expect(a1.id === 'a');
    expect(a2.id === 'a');
    expect(b.id === 'a');
    expect(a1 === a2);
    expect(a1 !== b);
  });

  it('cloneing is disabled', function() {
    var a1 = Test.create({id: 'a'});
    expect(a1 === a1.clone());
  });

  it('equals works', function() {
    var a1 = Test.create({id: 'a'});
    var a2 = Test.create({id: 'a'});
    var b  = Test.create({id: 'b'});
    expect(a1.equals(a2));
    expect(a2.equals(a1));
    expect(! a1.equals(b));
    expect(! b.equals(a1));
  });
});
<commit_msg>Fix Multiton tests.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

describe('Multiton axiom', function() {
  it('object sharing works', function() {
    foam.CLASS({
      name: 'Test',
      axioms: [
        foam.pattern.Multiton.create({property: 'id'})
      ],
      properties: [ 'id' ]
    });
    var a1 = Test.create({id: 'a'});
    var a2 = Test.create({id: 'a'});
    var b  = Test.create({id: 'b'});
    expect(a1.id).toEqual('a');
    expect(a2.id).toEqual('a');
    expect(b.id).toEqual('b');
    expect(a1 === a2).toBe(true);
    expect(a1 === b).toBe(false);
  });

  it('cloneing is disabled', function() {
    var a1 = Test.create({id: 'a'});
    expect(a1).toBe(a1.clone());
  });

  it('equals works', function() {
    var a1 = Test.create({id: 'a'});
    var a2 = Test.create({id: 'a'});
    var b  = Test.create({id: 'b'});
    expect(a1).toEqual(a2);
    expect(a2).toEqual(a1);
    expect(a1.equals(b)).toBe(false);
    expect(b.equals(a1).toBe(false);
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import styles from '@sambego/storybook-styles';
import { Store, State } from '@sambego/storybook-state';
import { Island, Link, QTip, TextSmall } from '../components';
import { baseStyles, centerStyles } from '../.storybook/styles';
import { IconIdeaMediumOutline } from '@teamleader/ui-icons';

const store = new Store({
  closed: false,
});

const updateState = () => {
  store.set({ closed: !store.get('closed') });
};

storiesOf('Q-tip', module)
  .addDecorator((story, context) => withInfo('common info')(story)(context))
  .addDecorator(checkA11y)
  .addDecorator(styles({ ...baseStyles, ...centerStyles }))
  .add('Default', () => (
    <Island paddingHorizontal={0} paddingVertical={6} style={{ width: '500px' }}>
      <State store={store}>
        <QTip onChange={updateState} icon={<IconIdeaMediumOutline />}>
          <TextSmall color="teal">Lorem ipsum dolor sit amet, consectetur <Link href="#" inherit={false}>adipiscing</Link> elit.</TextSmall>
        </QTip>
      </State>
    </Island>
  ))
  .add('Highlighted', () => (
    <Island paddingHorizontal={0} paddingVertical={6} style={{ width: '500px' }}>
      <State store={store}>
        <QTip highlighted onChange={updateState} icon={<IconIdeaMediumOutline />}>
          <TextSmall color="teal">Lorem ipsum dolor sit amet, consectetur  <Link href="#" inherit={false}>adipiscing</Link> elit.</TextSmall>
        </QTip>
      </State>
    </Island>
  ));
<commit_msg>Refactored QTip stories to coöperate with Knobs<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import { withKnobs, boolean } from '@storybook/addon-knobs/react';
import styles from '@sambego/storybook-styles';
import { Store, State } from '@sambego/storybook-state';
import { Island, Link, QTip, TextSmall } from '../components';
import { baseStyles, centerStyles } from '../.storybook/styles';
import { IconIdeaMediumOutline } from '@teamleader/ui-icons';

const store = new Store({
  closed: false,
});

const updateState = () => {
  store.set({ closed: !store.get('closed') });
};

storiesOf('Q-tip', module)
  .addDecorator((story, context) => withInfo('common info')(story)(context))
  .addDecorator(checkA11y)
  .addDecorator(withKnobs)
  .addDecorator(styles({ ...baseStyles, ...centerStyles }))
  .add('Default', () => (
    <Island paddingHorizontal={0} paddingVertical={6} style={{ width: '500px' }}>
      <State store={store}>
        <QTip highlighted={boolean('Highlighted', false)} onChange={updateState} icon={<IconIdeaMediumOutline />}>
          <TextSmall color="teal">Lorem ipsum dolor sit amet, consectetur <Link href="#" inherit={false}>adipiscing</Link> elit.</TextSmall>
        </QTip>
      </State>
    </Island>
  ));
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'

import palette from '../m-btn/config/colorPalette'
import Mbtn, { setBackground } from '../m-btn'

const bg = setBackground('grey', 'lighter')

const Wrapper = styled.div`
  height: 400px;
  color: ${palette.primary.main};
  background-color: ${bg.color};
  display: flex;
  justify-content: center;
  padding: 2rem;
  margin: 2rem 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
`

const Section = styled.section`
  width: 100%;
  padding: 2rem;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
`

const SmallSection = styled(Section)`
  width: 100%;
`

export default class Content extends Component {

  getChildContext () {
    return {
      bg: bg
    }
  }

  render () {
    return (
      <Wrapper>
        <SmallSection>
          <Mbtn info accent icon textColorPalette='info' textNuance='dark' content='query_builder' />
          <Mbtn icon color='#4DD0E1' customTextColor='red' content='lock_open' />
          <Mbtn primary light icon textPlatte='success' textNuance='dark' content='check' />

          <Mbtn warning icon content='cloud_circle' />

          <Mbtn primary icon content='directions_bike' />
          <Mbtn danger accent light icon content='local_cafe' bold />
          <Mbtn info icon textColor='warning' textNuance='light' content='query_builder' />
          <Mbtn info light icon textColor='primary' textNuance='dark' content='airplanemode_active' />

          <Mbtn success icon content='code' />
          <Mbtn primary dark icon iconClass='fa fa-hand-peace-o' />
          <Mbtn icon grey darker iconClass='devicon-react-original colored' />
          <Mbtn warning light icon iconClass='devicon-github-plain colored' />
          <Mbtn color='#3B5998'icon iconClass='fa fa-facebook' bold />
          <Mbtn info light icon iconClass='fa fa-pied-piper-pp' />
        </SmallSection>

          <Mbtn primary dark content='Dark' />
          <Mbtn primary accent content='Accent' />

          <Mbtn info content='Info' bold />
          <Mbtn info light content='Light' />

          <Mbtn warning textColor='info' textNuance='dark' content='Warning' bold />
          <Mbtn warning light content='Light' />
          <Mbtn warning dark content='Dark' />

          <Mbtn primary lighter textColor='danger' textNuance='dark' content='custom' />
          <Mbtn success accent textColor='MidnightBlue ' content='custom' />
          <Mbtn success dark content=' ☀ Hi ☯ ' />
          <Mbtn color='#4DD0E1' content='Bonjour' />

      </Wrapper>
    )
  }

}
Content.childContextTypes = {
  bg: PropTypes.object
}
<commit_msg>change text color of one button<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'

import palette from '../m-btn/config/colorPalette'
import Mbtn, { setBackground } from '../m-btn'

const bg = setBackground('grey', 'lighter')

const Wrapper = styled.div`
  height: 400px;
  color: ${palette.primary.main};
  background-color: ${bg.color};
  display: flex;
  justify-content: center;
  padding: 2rem;
  margin: 2rem 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
`

const Section = styled.section`
  width: 100%;
  padding: 2rem;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
`

const SmallSection = styled(Section)`
  width: 100%;
`

export default class Content extends Component {

  getChildContext () {
    return {
      bg: bg
    }
  }

  render () {
    return (
      <Wrapper>
        <SmallSection>
          <Mbtn info accent icon textColorPalette='info' textNuance='dark' content='query_builder' />
          <Mbtn icon color='#4DD0E1' customTextColor='red' content='lock_open' />
          <Mbtn primary light icon textPlatte='success' textNuance='dark' content='check' />

          <Mbtn warning icon content='cloud_circle' />

          <Mbtn primary icon content='directions_bike' />
          <Mbtn danger accent light icon content='local_cafe' bold />
          <Mbtn info icon textColor='warning' textNuance='light' content='query_builder' />
          <Mbtn info light icon textColor='primary' textNuance='dark' content='airplanemode_active' />

          <Mbtn success icon content='code' />
          <Mbtn primary dark icon iconClass='fa fa-hand-peace-o' />
          <Mbtn icon grey darker iconClass='devicon-react-original colored' />
          <Mbtn warning light icon iconClass='devicon-github-plain colored' />
          <Mbtn color='#3B5998'icon iconClass='fa fa-facebook' bold />
          <Mbtn info light icon iconClass='fa fa-pied-piper-pp' />
        </SmallSection>

          <Mbtn primary dark content='Dark' />
          <Mbtn primary accent content='Accent' />

          <Mbtn info content='Info' bold />
          <Mbtn info light content='Light' />

          <Mbtn warning textColor='info' textNuance='dark' content='Warning' bold />
          <Mbtn warning light content='Light' />
          <Mbtn warning dark content='Dark' />

          <Mbtn primary lighter textColor='danger' textNuance='dark' content='custom' />
          <Mbtn success accent textColor='MidnightBlue ' content='custom' />
          <Mbtn success dark content=' ☀ Hi ☯ ' />
          <Mbtn color='#4DD0E1' textColor='primary' content='Bonjour' />

      </Wrapper>
    )
  }

}
Content.childContextTypes = {
  bg: PropTypes.object
}
<|endoftext|>


<commit_before>import AxisView from '../../../src/axis-view';

describe('AxisView', () => {
  it('should be a function', () => {
    expect(AxisView).to.be.a('function');
  });

  var axisView;
  describe('render', () => {
    var clock;
    beforeEach(() => {
      clock = useFakeTimers();
      axisView = new AxisView({
        el: document.createElement('div')
      });
      stub(axisView, '_update');
    });

    describe('when no speed is given', () => {
      it('should update immediately', () => {
        var options = {scrollOffset: 5};
        axisView.render(options);

        expect(axisView._update).to.have.been.calledOnce;
        expect(axisView._update).to.have.been.calledWithExactly(options);
      });
    });

    describe('when a slow speed is given', () => {
      it('should update immediately', () => {
        var options = {
          scrollOffset: 5,
          speed: 2
        };
        axisView.render(options);

        expect(axisView._update).to.have.been.calledOnce;
        expect(axisView._update).to.have.been.calledWithExactly(options);
      });
    });

    describe('when a fast speed is given', () => {
      var options;
      beforeEach(() => {
        options = {
          scrollOffset: 2,
          speed: 100
        };
        axisView.render(options);
      });

      it('should not update immediately', () => {
        expect(axisView._update).to.not.have.been.called;
      });

      it('should update after a few milliseconds', () => {
        clock.tick(50);
        expect(axisView._update).to.have.been.calledOnce;
        expect(axisView._update).to.have.been.calledWithExactly(options);
      });
    });

    describe('when a fast speed is given repeatedly, with time in-between', () => {
      it('should update after some time between the last call', () => {
        var options = {
          scrollOffset: 2,
          speed: 100
        };
        axisView.render(options);
        clock.tick(20);
        axisView.render(options);
        clock.tick(30);
        axisView.render(options);
        clock.tick(30);
        axisView.render(options);
        clock.tick(30);
        expect(axisView._update).to.not.have.been.called;
        clock.tick(20);
        expect(axisView._update).to.have.been.calledOnce;
        expect(axisView._update).to.have.been.calledWithExactly(options);
      });
    });
  });

  describe('_getIndices', () => {
    beforeEach(() => {
      axisView = new AxisView({
        el: document.createElement('div'),
        padding: 3,
        list: new Array(20)
      });
    });

    describe('when calling from well within the ends of the list', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(10, 3);
        expect(result.firstIndex).to.equal(7);
        expect(result.lastIndex).to.equal(16);
      });
    });

    describe('when calling near the start', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(2, 3);
        expect(result.firstIndex).to.equal(0);
        expect(result.lastIndex).to.equal(8);
      });
    });

    describe('when calling at the start', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(0, 3);
        expect(result.firstIndex).to.equal(0);
        expect(result.lastIndex).to.equal(6);
      });
    });

    describe('when calling near the end', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(18, 3);
        expect(result.firstIndex).to.equal(15);
        expect(result.lastIndex).to.equal(19);
      });
    });

    describe('when calling at the end', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(19, 3);
        expect(result.firstIndex).to.equal(16);
        expect(result.lastIndex).to.equal(19);
      });
    });

    describe('with an offset of 0', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(15, 0);
        expect(result.firstIndex).to.equal(12);
        expect(result.lastIndex).to.equal(18);
      });
    });
  });

  describe('_update', () => {
    var nodeListManager, list;
    // The initial index will be: 8
    beforeEach(() => {
      list = new Array(20);
      axisView = new AxisView({
        el: document.createElement('div'),
        padding: 3,
        initialIndex: 10,
        list
      });

      nodeListManager = {
        update: sinon.stub()
      };

      axisView.nodeListManager = nodeListManager;
    });

    // Only test for initialIndex less than the list length
    describe('when passing no scrollOffset & the initialIndex is within bounds', () => {
      it('should use the default value', () => {
        axisView._update({length: 6});
        expect(nodeListManager.update).to.have.been.calledOnce;
        expect(nodeListManager.update).to.have.been.calledWithExactly({
          list,
          firstIndex: 7,
          lastIndex: 19
        });
      });
    });

    describe('when passing a scrollOffset of 0', () => {
      it('should call `nodeListManager.update` with the correct arguments', () => {
        axisView._update({
          offset: 0,
          length: 6
        });
        expect(nodeListManager.update).to.have.been.calledOnce;
        expect(nodeListManager.update).to.have.been.calledWithExactly({
          list,
          firstIndex: 0,
          lastIndex: 9
        });
      });
    });

    describe('when passing a scrollOffset of 41', () => {
      it('should call `nodeListManager.update` with the correct arguments', () => {
        axisView._update({
          offset: 1,
          length: 6
        });
        expect(nodeListManager.update).to.have.been.calledOnce;
        expect(nodeListManager.update).to.have.been.calledWithExactly({
          list,
          firstIndex: 0,
          lastIndex: 10
        });
      });
    });

    describe('when passing a scrollOffset of 180', () => {
      it('should call `nodeListManager.update` with the correct arguments', () => {
        axisView._update({
          offset: 4,
          length: 6
        });
        expect(nodeListManager.update).to.have.been.calledOnce;
        expect(nodeListManager.update).to.have.been.calledWithExactly({
          list,
          firstIndex: 1,
          lastIndex: 13
        });
      });
    });

    describe('when passing a scrollOffset of 700', () => {
      it('should call `nodeListManager.update` with the correct arguments', () => {
        axisView._update({
          offset: 17,
          length: 6
        });
        expect(nodeListManager.update).to.have.been.calledOnce;
        expect(nodeListManager.update).to.have.been.calledWithExactly({
          list,
          firstIndex: 14,
          lastIndex: 19
        });
      });
    });
  });
});
<commit_msg>Remove ListView tests from AxisView tests<commit_after>import AxisView from '../../../src/axis-view';

describe('AxisView', () => {
  it('should be a function', () => {
    expect(AxisView).to.be.a('function');
  });

  var axisView;
  describe('_getIndices', () => {
    beforeEach(() => {
      axisView = new AxisView({
        el: document.createElement('div'),
        padding: 3,
        list: new Array(20)
      });
    });

    describe('when calling from well within the ends of the list', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(10, 3);
        expect(result.firstIndex).to.equal(7);
        expect(result.lastIndex).to.equal(16);
      });
    });

    describe('when calling near the start', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(2, 3);
        expect(result.firstIndex).to.equal(0);
        expect(result.lastIndex).to.equal(8);
      });
    });

    describe('when calling at the start', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(0, 3);
        expect(result.firstIndex).to.equal(0);
        expect(result.lastIndex).to.equal(6);
      });
    });

    describe('when calling near the end', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(18, 3);
        expect(result.firstIndex).to.equal(15);
        expect(result.lastIndex).to.equal(19);
      });
    });

    describe('when calling at the end', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(19, 3);
        expect(result.firstIndex).to.equal(16);
        expect(result.lastIndex).to.equal(19);
      });
    });

    describe('with an offset of 0', () => {
      it('should return the correct indices', () => {
        var result = axisView._getIndices(15, 0);
        expect(result.firstIndex).to.equal(12);
        expect(result.lastIndex).to.equal(18);
      });
    });
  });
});
<|endoftext|>