<commit_before>const WHITE  = tinycolor("#ffffff");
const BLACK  = tinycolor("#000000");
const AAANORMALRATIO = 7.0;
const AANORMALRATIO = 4.5;
const AALARGERATIO = 3.0;
var colorArray = [];

// Decimal Rounding: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

function round(number) {
  return Math.round(number);
}

// Preserves a place after the decimal
function round2places(number) {
  return (Math.round(number * 100) / 100).toFixed(2);
}

function decimalToPercent(number) {
  return Math.round(number * 100);
}

function getRoundedRatio(color1, color2) {
  var ratio = tinycolor.readability(color1, color2);
  return round2places(ratio);
}

function outputRatio(color, ratio, bg, target) {
  // Default values: AA normal and AAA large with failing grades
  var color = tinycolor(color),
      hex = color.toHexString(),
      background = tinycolor(bg),
      bghex = background.toHexString(),
      passfail = 'fail',
      output = '',
      targetclass = 'target-45',
      icontent = '✘', // x mark
      swatchcontent = '
AA
AAA 24px',
      difference = 0;

  // Check for passing grades
  if ( ratio >= (target + 0.5) ) {
    // It passes if the ratio is greater than our constant plus 0.5 for gamma correction
    passfail = 'pass';
    icontent = '✔'; // check mark
  } else if ( ratio <= (target + 0.5) && ratio > target ) {
    // It barely passes if the ratio is less than our constant plus 0.5 for gamma correction
    // AND greater than the constant. So, within 0.5.
    passfail = 'edge';
    icontent = '‼'; // double exclamation
  }

  // Check target ratios
  if ( target == AAANORMALRATIO ) {
    targetclass = 'target-7'
    swatchcontent = '
AAA
';
  }
  if ( target == AALARGERATIO ) {
    targetclass = 'target-3'
    swatchcontent = 'AA 24px';
  }

  difference = round2places( (ratio - target), -1 );

  var output =
  `

${ratio}: with ${bghex}

${swatchcontent}

      ${icontent}

        ${passfail} ${difference}

`;
  return output;
}

function outputAllRatios(color) {
  var ratio_onwhite = getRoundedRatio(color, WHITE),
      ratio_onblack = getRoundedRatio(color, BLACK),
      results = "";

  results =
    `

        ${outputRatio(color, ratio_onwhite, '#fff', AAANORMALRATIO)}
        ${outputRatio(color, ratio_onwhite, '#fff', AANORMALRATIO)}
        ${outputRatio(color, ratio_onwhite, '#fff', AALARGERATIO)}

        ${outputRatio(color, ratio_onblack, '#000', AAANORMALRATIO)}
        ${outputRatio(color, ratio_onblack, '#000', AANORMALRATIO)}
        ${outputRatio(color, ratio_onblack, '#000', AALARGERATIO)}

`;
  return results;
}

var button = document.querySelector('#brand-color-button');
button.onclick = function(e) {
  e.preventDefault();

  var resultsBlock = document.getElementById('results-content');
  var results = document.getElementById('results-output');

  // if there are already results displayed, clear them
  if ( results.children.length > 1 ) {
    results.innerHTML = '';
  }

  // Set the header row
  results.innerHTML =
  `

Original

Modify

With white

With black

Most legible from available

`;

  // get the colors inputted by the user
  var stringInput = document.querySelector('#brand-color-field').value;
  // if there's no input, get outta here
  if ( stringInput == '' ) {
    return;
  }
  // turn it into an array
  colorArray = stringInput.split("\n");

  for (var i = 0; i < colorArray.length; i++) {

    // get the color's contrast ratios
    var most_legible = tinycolor.mostReadable(colorArray[i], colorArray),
        ratio_mostlegible = getRoundedRatio(most_legible, colorArray[i]),
        color = tinycolor(colorArray[i]),
        hex = color.toHex(),
        hashhex = color.toHexString(),
        hslColor = color.toHsl();

    // outputRatio( {color & border color}, ratio, {background color}, {ratio to test against} )
    results.innerHTML +=
    `

${hashhex}

H: ${round(hslColor.h)}

S: ${decimalToPercent(hslColor.s)}

L: ${decimalToPercent(hslColor.l)}

${hashhex}

H<input type="number" class="adjust-hue" data-target="${i}" data-color="${hex}" id="adjust-hue-${i}" name="adjust-hue-${i}" value="${round(hslColor.h)}" min="0" max="360" />

S<input type="number" class="adjust-sat" data-target="${i}" data-color="${hex}" id="adjust-sat-${i}" name="adjust-sat-${i}" value="${decimalToPercent(hslColor.s)}" min="0" max="100" />

L<input type="number" class="adjust-lig" data-target="${i}" data-color="${hex}" id="adjust-lig-${i}" name="adjust-lig-${i}" value="${decimalToPercent(hslColor.l)}" min="0" max="100" />

          ${outputAllRatios(colorArray[i])}

          ${outputRatio(most_legible, ratio_mostlegible, colorArray[i], AAANORMALRATIO)}
          ${outputRatio(most_legible, ratio_mostlegible, colorArray[i], AANORMALRATIO)}
          ${outputRatio(most_legible, ratio_mostlegible, colorArray[i], AALARGERATIO)}

`;
  }

  // make the results content visible
  resultsBlock.style.display = 'block';
  resultsBlock.style.visibility = 'visible';

  // jump to the results
  window.location.href = '#results-content';
}

// Adjust Hue
$(document).on("change paste keyup blur", ".adjust-hue", function() {
  var target = $(this).data("target"),
      color = $(this).data("color"),
      newValue = $(this).val(),
      originalColor = tinycolor(color).toHsl(),
      newColorHSL = tinycolor("hsl(" + newValue + "," + originalColor.s + ", " + originalColor.l + ")"),
      newColorRAW = newColorHSL.toHex(),
      newColor = newColorHSL.toHexString(),
      targetSwatch = $('.mod-swatch-' + target),
      targetContainer = $('#row-' + target);

  // Change the starting color on the inputs, stored in data-color
  var inputs = $("input[data-target=" + target + "]");
  inputs.each(function() {
    $(this).data('color', newColorRAW);
  });
  $('.mod-label-' + target).html(newColor);

  // Change the swatch
  targetSwatch.css("background-color", newColor);

  // Change the contents of the white/black outputs
  //console.log(newColor);
  targetContainer.html('');
  targetContainer.html(outputAllRatios(newColor));
});

// Adjust Saturation
$(document).on("change paste keyup blur", ".adjust-sat", function() {
  var target = $(this).data("target"),
      color = $(this).data("color"),
      newValue = $(this).val(),
      originalColor = tinycolor(color).toHsl(),
      newColorHSL = tinycolor("hsl(" + originalColor.h + "," + newValue + ", " + originalColor.l + ")"),
      newColorRAW = newColorHSL.toHex(),
      newColor = newColorHSL.toHexString(),
      targetSwatch = $('.mod-swatch-' + target),
      targetContainer = $('#row-' + target);

  var inputs = $("input[data-target=" + target + "]");
  inputs.each(function() {
    $(this).data('color', newColorRAW);
  });
  $('.mod-label-' + target).html(newColor);

  targetSwatch.css("background-color", newColor);
  //console.log(newColor);
  targetContainer.html('');
  targetContainer.html(outputAllRatios(newColor));
});

// Adjust Lightness
$(document).on("change paste keyup blur", ".adjust-lig", function() {
  var target = $(this).data("target"),
      color = $(this).data("color"),
      newValue = $(this).val(),
      originalColor = tinycolor(color).toHsl(),
      newColorHSL = tinycolor("hsl(" + originalColor.h + "," + originalColor.s + ", " + newValue + ")"),
      newColorRAW = newColorHSL.toHex(),
      newColor = newColorHSL.toHexString(),
      targetSwatch = $('.mod-swatch-' + target),
      targetContainer = $('#row-' + target);

  var inputs = $("input[data-target=" + target + "]");
  inputs.each(function() {
    $(this).data('color', newColorRAW);
  });
  $('.mod-label-' + target).html(newColor);

  targetSwatch.css("background-color", newColor);
  //console.log(newColor);
  targetContainer.html('');
  targetContainer.html(outputAllRatios(newColor));
});
<commit_msg>MOAR functionality<commit_after>const AAANORMALRATIO = 7.0;
const AANORMALRATIO = 4.5;
const AALARGERATIO = 3.0;
var colorArray = [];

// Decimal Rounding: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

function round(number) {
  return Math.round(number);
}

// Preserves a place after the decimal
function round2places(number) {
  return (Math.round(number * 100) / 100).toFixed(2);
}

function decimalToPercent(number) {
  return Math.round(number * 100);
}

function getRoundedRatio(color1, color2) {
  var ratio = tinycolor.readability(color1, color2);
  return round2places(ratio);
}

function outputRatio(color, ratio, bg, target, editable, iterator) {
  // Default values: AA normal and AAA large with failing grades
  var color = tinycolor(color),
      hex = color.toHexString(),
      background = tinycolor(bg),
      bghex = background.toHexString(),
      passfail = 'fail',
      output = '',
      targetclass = 'target-45',
      icontent = '✘', // x mark
      swatchcontent = '
AA
AAA 24px',
      difference = 0;

  // Check for passing grades
  if ( ratio >= (target + 0.5) ) {
    // It passes if the ratio is greater than our constant plus 0.5 for gamma correction
    passfail = 'pass';
    icontent = '✔'; // check mark
  } else if ( ratio <= (target + 0.5) && ratio > target ) {
    // It barely passes if the ratio is less than our constant plus 0.5 for gamma correction
    // AND greater than the constant. So, within 0.5.
    passfail = 'edge';
    icontent = '✔'; // ‼ double exclamation
  }

  // Check target ratios
  if ( target == AAANORMALRATIO ) {
    targetclass = 'target-7'
    swatchcontent = '
AAA
';
  }
  if ( target == AALARGERATIO ) {
    targetclass = 'target-3'
    swatchcontent = 'AA 24px';
  }

  difference = round2places( (ratio - target), -1 );

  if ( editable === true ) {
    var output =
      `

${ratio}: with <input class="cc__form__input adjust-custom" id="test-color-${iterator}" name="test-color-${iterator}" type="text" value="${hex}" data-target="${iterator}" data-color="${bghex}" />

${swatchcontent}

          ${icontent}

            ${passfail} ${difference}

`;
  } else {
    var output =
      `

${ratio}: with ${bghex}

${swatchcontent}

          ${icontent}

            ${passfail} ${difference}

`;
  }
  return output;
}

function outputAllRatios(color, light, dark) {
  var ratio_onlight = getRoundedRatio(color, light),
      ratio_ondark = getRoundedRatio(color, dark),
      results = "";

  results =
    `

        ${outputRatio(color, ratio_onlight, light, AAANORMALRATIO)}
        ${outputRatio(color, ratio_onlight, light, AANORMALRATIO)}
        ${outputRatio(color, ratio_onlight, light, AALARGERATIO)}

        ${outputRatio(color, ratio_ondark, dark, AAANORMALRATIO)}
        ${outputRatio(color, ratio_ondark, dark, AANORMALRATIO)}
        ${outputRatio(color, ratio_ondark, dark, AALARGERATIO)}

`;
  return results;
}

function outputCustomRatios(color, ratio, bg, iterator) {
  var results = outputRatio(color, ratio, bg, AAANORMALRATIO, true, iterator);
  results = results + outputRatio(color, ratio, bg, AANORMALRATIO, true, iterator);
  results = results + outputRatio(color, ratio, bg, AALARGERATIO, true, iterator);
  return results;
}

var button = document.querySelector('#brand-color-button');
button.onclick = function(e) {
  e.preventDefault();

  var resultsBlock = document.getElementById('results-content'),
      results = document.getElementById('results-output'),
      white = tinycolor(document.querySelector('#white-value').value),
      black = tinycolor(document.querySelector('#black-value').value);

  // if there are already results displayed, clear them
  if ( results.children.length > 1 ) {
    results.innerHTML = '';
  }

  // Set the header row
  results.innerHTML =
  `

Original

Modify

With light

With dark

Most legible or Custom

`;

  // get the colors inputted by the user
  var stringInput = document.querySelector('#brand-color-field').value;
  // if there's no input, get outta here
  if ( stringInput == '' ) {
    return;
  }
  // turn it into an array
  colorArray = stringInput.split("\n");

  for (var i = 0; i < colorArray.length; i++) {

    // get the color's contrast ratios
    var most_legible = tinycolor.mostReadable(colorArray[i], colorArray),
        ratio_mostlegible = getRoundedRatio(most_legible, colorArray[i]),
        color = tinycolor(colorArray[i]),
        hex = color.toHex(),
        hashhex = color.toHexString(),
        hslColor = color.toHsl();

    // outputRatio( {color & border color}, ratio, {background color}, {ratio to test against} )
    results.innerHTML +=
    `

${hashhex}

H: ${round(hslColor.h)}

S: ${decimalToPercent(hslColor.s)}

L: ${decimalToPercent(hslColor.l)}

${hashhex}

H<input type="number" class="cc__form__input adjust-hue" data-target="${i}" data-color="${hex}" id="adjust-hue-${i}" name="adjust-hue-${i}" value="${round(hslColor.h)}" min="0" max="360" />

S<input type="number" class="cc__form__input adjust-sat" data-target="${i}" data-color="${hex}" id="adjust-sat-${i}" name="adjust-sat-${i}" value="${decimalToPercent(hslColor.s)}" min="0" max="100" />

L<input type="number" class="cc__form__input adjust-lig" data-target="${i}" data-color="${hex}" id="adjust-lig-${i}" name="adjust-lig-${i}" value="${decimalToPercent(hslColor.l)}" min="0" max="100" />

          ${outputAllRatios(colorArray[i], white, black)}

          ${outputCustomRatios(most_legible, ratio_mostlegible, colorArray[i], i)}

`;
  }

  // make the results content visible
  resultsBlock.style.display = 'block';
  resultsBlock.style.visibility = 'visible';

  // jump to the results
  window.location.href = '#results-content';
}

// Adjust Hue, Saturation, or Lightness
$(document).on("change paste keyup blur", ".adjust-hue, .adjust-sat, .adjust-lig", function() {
  var target = $(this).data("target"),
      color = $(this).data("color"),
      newValue = $(this).val(),
      originalColor = tinycolor(color).toHsl(),
      newColorHSL = '';

  // Adjust the color based on the class of the input
  if ( $(this).hasClass('adjust-hue') ) {
    newColorHSL = tinycolor("hsl(" + newValue + "," + originalColor.s + ", " + originalColor.l + ")");
  } else if ( $(this).hasClass('adjust-sat') ) {
    newColorHSL = tinycolor("hsl(" + originalColor.h + "," + newValue + ", " + originalColor.l + ")");
  } else {
    newColorHSL = tinycolor("hsl(" + originalColor.h + "," + originalColor.s + ", " + newValue + ")");
  }

  var newColorRAW = newColorHSL.toHex(),
      newColor = newColorHSL.toHexString(),
      targetSwatch = $('.mod-swatch-' + target),
      targetContainer = $('#row-' + target),
      customContainer = $('#custom-pair-' + target),
      white = tinycolor(document.querySelector('#white-value').value),
      black = tinycolor(document.querySelector('#black-value').value),
      custom = tinycolor(document.querySelector('#test-color-' + target).value),
      ratio_custom = getRoundedRatio(custom, newColor);

  // Change the starting color on the inputs, stored in data-color
  var inputs = $("input[data-target=" + target + "]");
  inputs.each(function() {
    $(this).data('color', newColorRAW);
  });
  $('.mod-label-' + target).html(newColor);

  // Change the swatch
  targetSwatch.css("background-color", newColor);

  // Change the contents of the light/dark outputs
  //console.log(newColor);
  targetContainer.html('');
  targetContainer.html(outputAllRatios(newColor, white, black));

  // Change the contents of the Custom column
  customContainer.html('');
  customContainer.html(outputCustomRatios(custom, ratio_custom, newColor, target));
});

// If a custom color is supplied, redo the custom color test
$(document).on("blur", ".adjust-custom", function() {
  var target = $(this).data("target"),
      color = tinycolor($(this).data("color")),
      newColor = tinycolor($(this).val()),
      ratio_custom = getRoundedRatio(color, newColor),
      customContainer = $('#custom-pair-' + target);

  // Change the contents of the Custom column
  customContainer.html('');
  customContainer.html(outputCustomRatios(newColor, ratio_custom, color, target));
});
<|endoftext|>


<commit_before>;(function createEditPage() {
    let userJsonData = require('../../cookies/info.json')
    let feeds = userJsonData['feeds']
    console.log(feeds)

    /* Add save button to page */
    let saveButtonDiv = document.createElement('div')
    saveButtonDiv.className = 'saveContainer'
    let saveButton = document.createElement('button')
    saveButton.textContent = 'Save'
    saveButton.className = 'saveButton'
    saveButtonDiv.appendChild(saveButton)
    document.getElementById('editFeeds').appendChild(saveButtonDiv)

    for(let i = 0; i < feeds.length; i++) {
        let feedTitle = feeds[i]['title']
        let numberOfPhotosPerUser = feeds[i]['numberOfPhotosPerUser']
        let feedDiv = document.createElement('div')
        let titleDiv = document.createElement('div')
        let usersDiv = document.createElement('div')

        let title = document.createElement('div')
        let numberOfPhotos = document.createElement('div')

        titleDiv.className = 'titleContainer'
        title.textContent = feedTitle
        title.className = 'title'

        numberOfPhotos.textContent = numberOfPhotosPerUser
        numberOfPhotos.className = 'numberOfPhotos'

        titleDiv.appendChild(title)
        titleDiv.appendChild(numberOfPhotos)

        let users = feeds[i]['profiles']
        users.forEach((user) => {
            let oneUserDiv = document.createElement('div')
            let span = document.createElement('span')
            let userRemoveButton = document.createElement('button')
            userRemoveButton.textContent = 'Remove User'
            userRemoveButton.className = 'userRemoveButton'
            span.textContent = user
            oneUserDiv.appendChild(span)
            oneUserDiv.appendChild(userRemoveButton)
            oneUserDiv.className = 'user'
            usersDiv.appendChild(oneUserDiv) // add user to list of user
        })

        /* input to add a new user at the end of each feed */
        let addUserDiv = document.createElement('div')
        let addUserInput = document.createElement('input')
        let addUserButton = document.createElement('button')
        addUserButton.textContent = 'Add User'
        addUserButton.className = 'addUserButton'
        addUserDiv.className = 'addUserContainer'
        addUserDiv.appendChild(addUserInput)
        addUserDiv.appendChild(addUserButton)

        /* add the created divs to the page */
        feedDiv.appendChild(titleDiv)
        feedDiv.appendChild(usersDiv)
        feedDiv.appendChild(addUserDiv)
        feedDiv.appendChild(document.createElement('br')) //add a break between feeds

        document.getElementById('editFeeds').appendChild(feedDiv)
    }

}())<commit_msg>edit page created with javascript. still need to add css<commit_after>// TODO ADD COMMENTS

let userJsonData = require('../../cookies/info.json')
let feeds = userJsonData['feeds']

;(function createEditPage() {
    /* Add save button to page */
    let saveButtonDiv = document.createElement('div')
    let saveButton = document.createElement('button')
    saveButtonDiv.className = 'saveContainer'
    saveButton.textContent = 'Save'
    saveButton.className = 'saveButton'
    saveButton.addEventListener('click', save, false)
    saveButtonDiv.appendChild(saveButton)
    document.getElementById('editFeeds').appendChild(saveButtonDiv)

    for(let i = 0; i < feeds.length; i++) {
        let feedTitle = feeds[i]['title']
        let numberOfPhotosPerUser = feeds[i]['numberOfPhotosPerUser']
        let feedDiv = document.createElement('div')
        let titleDiv = document.createElement('div')
        let usersDiv = document.createElement('div')

        let title = document.createElement('div')
        let numberOfPhotos = document.createElement('div')

        feedDiv.className = 'feed'
        usersDiv.id = feedTitle

        titleDiv.className = 'titleContainer'
        title.textContent = feedTitle
        title.className = 'title'

        numberOfPhotos.textContent = numberOfPhotosPerUser
        numberOfPhotos.className = 'numberOfPhotos'

        titleDiv.appendChild(title)
        titleDiv.appendChild(numberOfPhotos)

        let users = feeds[i]['profiles']
        users.forEach((user) => {
            let oneUserDiv = document.createElement('div')
            let span = document.createElement('span')
            let userRemoveButton = document.createElement('button')
            userRemoveButton.textContent = 'Remove User'
            userRemoveButton.className = 'userRemoveButton'
            userRemoveButton.addEventListener('click', () => removeUser(user, users), false)
            span.textContent = user
            oneUserDiv.id = user
            oneUserDiv.appendChild(span)
            oneUserDiv.appendChild(userRemoveButton)
            oneUserDiv.className = 'user'
            usersDiv.appendChild(oneUserDiv) // add user to list of user
        })

        /* input to add a new user at the end of each feed */
        let addUserDiv = document.createElement('div')
        let addUserInput = document.createElement('input')
        let addUserButton = document.createElement('button')
        addUserInput.className = 'newUser'
        addUserButton.textContent = 'Add User'
        addUserButton.className = 'addUserButton'
        addUserButton.addEventListener('click', () => addUser(i, feedTitle), false)
        addUserDiv.className = 'addUserContainer'
        addUserDiv.appendChild(addUserInput)
        addUserDiv.appendChild(addUserButton)

        /* add the created divs to the page */
        feedDiv.appendChild(titleDiv)
        feedDiv.appendChild(usersDiv)
        feedDiv.appendChild(addUserDiv)
        feedDiv.appendChild(document.createElement('br')) //add a break between feeds

        document.getElementById('editFeeds').appendChild(feedDiv)
    }
}())

/* need to pass in an index value so we know which feed we will be inserting into */
function addUser(feedIndex, feedTitle) {
    let newUser = document.getElementsByClassName('newUser')[feedIndex].value
    if(newUser !== '') {
        let newUserDiv = document.createElement('div')
        let span = document.createElement('span')
        let userRemoveButton = document.createElement('button')
        userRemoveButton.textContent = 'Remove User'
        userRemoveButton.className = 'userRemoveButton'
        userRemoveButton.addEventListener('click', () => removeUser(newUser, users), false)
        span.textContent = newUser
        newUserDiv.id = newUser
        newUserDiv.appendChild(span)
        newUserDiv.appendChild(userRemoveButton)
        newUserDiv.className = 'user'

        /* add new user div to feed */
        let feed = document.getElementById(feedTitle)
        feed.appendChild(newUserDiv)
    }
}

function removeUser(user, users) {
    // let userIndexToRemove = users.indexOf(user)
    // users.splice(userIndexToRemove, 1)
    let userDivToRemove = document.getElementById(user)
    userDivToRemove.parentElement.removeChild(userDivToRemove)
}

function save() {
    console.log('save')
    infoToSave = [] // array of feed objects
    feedsFromPage = document.getElementsByClassName('feed')
    for(let i = 0; i < feedsFromPage.length; i++) {
        let feedData = feedsFromPage[i]
        let obj = {}
        let titleContent = feedData.childNodes[0]
        let title = titleContent.childNodes[0].childNodes[0].textContent
        let numberOfPhotosPerUser = titleContent.childNodes[1].childNodes[0].textContent //probably changing
        let usernames = feedData.childNodes[1].childNodes
        let usernamesToSave = []
        for(let j = 0; j < usernames.length; j++) {
            let usernameToAdd = usernames[j].childNodes[0].textContent
            usernamesToSave.push(usernameToAdd)
        }
        obj['title'] = title
        obj['numberOfPhotosPerUser'] = numberOfPhotosPerUser
        obj['profiles'] = usernamesToSave
        infoToSave.push(obj)
    }
    console.log(infoToSave)

    // todo: save
    // window.history.go(-1)
}<|endoftext|>


<commit_before>function scrollPercentage() {
    var winTop = $(window).scrollTop(),
        docHeight = $(document).height(),
        winHeight = $(window).height();

    return (winTop / (docHeight - winHeight)) * 100;
}

function scrollSteps(imagesNumber) {
    var steps = [];

    for (var i = 1; i < imagesNumber; i++) {
        steps[steps.length] = 100 / imagesNumber * i;
    }

    steps[steps.length] = 150;

    return steps;
}

$(document).ready(function () {
    var slidebars = new $.slidebars();
    var showingText = false;

    var menu = $('.sb-menu');
    var topbar = $('.topbar');
    var menuHeight = 50;
    var windowHeight = $(window).height() + 10;
    var Gallery = blueimp.Gallery([], {carousel: true, continuous: true});
    Gallery.carousel = true;

    var fillerBlock = $('.filler-block');

    var menuLinks = $('.sb-menu a');

    $(window).resize(function () {
        windowHeight = $(window).height() + 10;
        if (!showingText) {
            fillerBlock.height(windowHeight);
        }
    });

    if (window.location.hash) {
        if (window.location.hash === '#referanser') {
            clickReferanser();
        } else if (window.location.hash === '#dokumentasjon') {
            clickDokumentasjon();
        } else {
            showingText = true;
            fillerBlock.height(200);
        }
    } else {
        fillerBlock.height(windowHeight);
        $('body').scrollTop(0);
        if (menuLinks.length) {
            disableScroll();
        }
    }

    $('.close-post').click(function (event) {
        scrollToTop();
    });

    $('body').click(function (event) {
        if (showingText && (event.target.tagName === 'BODY' || event.target.className.indexOf('filler-block') > -1)) {
            scrollToTop(function () {
                slidebars.slidebars.close();
            });
        } else {
            slidebars.slidebars.close();
        }
        window.location.hash = '#';

    });

    //$('#tekst a').attr('target', '_blank');

    function enableScroll() {
        $('html').css('overflow-y', 'auto');
        showingText = true;
    }

    function disableScroll() {
        $('html').css('overflow-y', 'hidden');
        showingText = false;
    }

    function scrollToTop(cb) {
        disableScroll();
        fillerBlock.animate({height: (windowHeight + $('body').scrollTop()) + 'px'}, {
            complete: function () {
                $('body').scrollTop(0);
                fillerBlock.height(windowHeight);
                if (cb) cb();
            }
        });
    }

    function clickReferanser() {
        scrollToTop(function () {
            slidebars.slidebars.close();
        });
        $('#links a').first().trigger('click').trigger('click');
    }

    function clickDokumentasjon() {
        scrollToTop(function () {
            slidebars.slidebars.close();
        });
        $('#dokumentasjon a').first().trigger('click').trigger('click');
    }

    menuLinks.click(function (event) {
        if(this.hash) {
            event.preventDefault();
        } else {
            return true;
        }
        var target = event.currentTarget.getAttribute('href');
        if (target === '#') {
            scrollToTop(function () {
                slidebars.slidebars.close();
            });
            window.location.hash = target;
            return false;
        } else if (target === '#referanser') {
            clickReferanser();
            var scrollmem = $('html,body').scrollTop();
            window.location.hash = target;
            $('html,body').scrollTop(scrollmem);
            return false;
        } else if (target === '#dokumentasjon') {
            clickDokumentasjon();
            var scrollmem = $('html,body').scrollTop();
            window.location.hash = target;
            $('html,body').scrollTop(scrollmem);
            return false;
        }
        enableScroll();
        slidebars.slidebars.close();
        return scrollToTarget(target);
    });

    function scrollToTarget(target) {
        var targetElm = $(target);
        if (targetElm.length) {
            var body = $('body');
            var newBottomPadding = (windowHeight - 200 - $('#sb-site').outerHeight());
            if (newBottomPadding > parseInt(body.css('padding-bottom'))) {
                body.css('padding-bottom', newBottomPadding + 'px');
            }
            body.animate({scrollTop: targetElm.offset().top - menuHeight}, {
                complete: function () {
                    fillerBlock.height(200);
                    window.location.hash = target;
                    $('body').scrollTop(targetElm.offset().top - menuHeight);
                    body.css('padding-bottom', '');
                }
            });
            return false;
        }

        window.location.hash = target;
        return true;
    }

});

$(document).load(function() {
    $('body').scrollTop(0);
});
<commit_msg>Fikset histrie bug.<commit_after>function scrollPercentage() {
    var winTop = $(window).scrollTop(),
        docHeight = $(document).height(),
        winHeight = $(window).height();

    return (winTop / (docHeight - winHeight)) * 100;
}

function scrollSteps(imagesNumber) {
    var steps = [];

    for (var i = 1; i < imagesNumber; i++) {
        steps[steps.length] = 100 / imagesNumber * i;
    }

    steps[steps.length] = 150;

    return steps;
}

$(document).ready(function () {
    var slidebars = new $.slidebars();
    var showingText = false;

    var menu = $('.sb-menu');
    var topbar = $('.topbar');
    var menuHeight = 50;
    var windowHeight = $(window).height() + 10;
    var Gallery = blueimp.Gallery([], {carousel: true, continuous: true});
    Gallery.carousel = true;

    var fillerBlock = $('.filler-block');

    var menuLinks = $('.sb-menu a');

    $(window).resize(function () {
        windowHeight = $(window).height() + 10;
        if (!showingText) {
            fillerBlock.height(windowHeight);
        }
    });

    if (window.location.hash) {
        if (window.location.hash === '#referanser') {
            clickReferanser();
        } else if (window.location.hash === '#dokumentasjon') {
            clickDokumentasjon();
        } else {
            showingText = true;
            fillerBlock.height(200);
        }
    } else {
        fillerBlock.height(windowHeight);
        $('body').scrollTop(0);
        if (menuLinks.length) {
            disableScroll();
        }
    }

    $('.close-post').click(function (event) {
        scrollToTop();
    });

    $('body').click(function (event) {
        if (showingText && (event.target.tagName === 'BODY' || event.target.className.indexOf('filler-block') > -1)) {
            scrollToTop(function () {
                slidebars.slidebars.close();
            });
        } else {
            slidebars.slidebars.close();
        }
        location.replace("#");

    });

    //$('#tekst a').attr('target', '_blank');

    function enableScroll() {
        $('html').css('overflow-y', 'auto');
        showingText = true;
    }

    function disableScroll() {
        $('html').css('overflow-y', 'hidden');
        showingText = false;
    }

    function scrollToTop(cb) {
        disableScroll();
        fillerBlock.animate({height: (windowHeight + $('body').scrollTop()) + 'px'}, {
            complete: function () {
                $('body').scrollTop(0);
                fillerBlock.height(windowHeight);
                if (cb) cb();
            }
        });
    }

    function clickReferanser() {
        scrollToTop(function () {
            slidebars.slidebars.close();
        });
        $('#links a').first().trigger('click').trigger('click');
    }

    function clickDokumentasjon() {
        scrollToTop(function () {
            slidebars.slidebars.close();
        });
        $('#dokumentasjon a').first().trigger('click').trigger('click');
    }

    menuLinks.click(function (event) {
        if(this.hash) {
            event.preventDefault();
        } else {
            return true;
        }
        var target = event.currentTarget.getAttribute('href');
        if (target === '#') {
            scrollToTop(function () {
                slidebars.slidebars.close();
            });
            location.replace(target);
            return false;
        } else if (target === '#referanser') {
            clickReferanser();
            //var scrollmem = $('html,body').scrollTop();
            location.replace(target);
            //$('html,body').scrollTop(scrollmem);
            return false;
        } else if (target === '#dokumentasjon') {
            clickDokumentasjon();
            //var scrollmem = $('html,body').scrollTop();
            //window.location.hash = target;
            location.replace(target);
            //$('html,body').scrollTop(scrollmem);
            return false;
        }
        enableScroll();
        slidebars.slidebars.close();
        return scrollToTarget(target);
    });

    function scrollToTarget(target) {
        var targetElm = $(target);
        if (targetElm.length) {
            var body = $('body');
            var newBottomPadding = (windowHeight - 200 - $('#sb-site').outerHeight());
            if (newBottomPadding > parseInt(body.css('padding-bottom'))) {
                body.css('padding-bottom', newBottomPadding + 'px');
            }
            body.animate({scrollTop: targetElm.offset().top - menuHeight}, {
                complete: function () {
                    //fillerBlock.height(200);
                    location.replace(target);
                    //$('body').scrollTop(targetElm.offset().top - menuHeight);
                    body.css('padding-bottom', '');
                }
            });
            return false;
        }

        location.replace(target);
        return true;
    }

});

$(document).load(function() {
    $('body').scrollTop(0);
});
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      dependencies: { }
    },
    {
      name: 'ember-release',
      dependencies: {
        'ember': 'components/ember#release'
      },
      resolutions: {
        'ember': 'release'
      }
    },
    {
      name: 'ember-beta',
      dependencies: {
        'ember': 'components/ember#beta'
      },
      resolutions: {
        'ember': 'beta'
      }
    },
    {
      name: 'ember-canary',
      dependencies: {
        'ember': 'components/ember#canary'
      },
      resolutions: {
        'ember': 'canary'
      }
    }
  ]
};
<commit_msg>Add ember-versions for testing.<commit_after>/*jshint node:true*/

module.exports = {
  scenarios: [
    {
      name: 'ember-1.10',
      dependencies: {
        "ember": "~1.10.0"
      }
    },
    {
      name: 'ember-1.11',
      dependencies: {
        "ember": "~1.11.3"
      }
    },
    {
      name: 'ember-1.12',
      dependencies: {
        "ember": "~1.12.1"
      }
    },
    {
      name: 'ember-1.13',
      dependencies: {
        "ember": "~1.13.8"
      }
    },
    {
      name: 'ember-2.0',
      dependencies: {
        "ember": "~2.0.0"
      }
    },
    {
      name: 'ember-2.1',
      dependencies: {
        "ember": "~2.1.0"
      }
    },
    {
      name: 'ember-release',
      dependencies: {
        "ember": "components/ember#release"
      },
      resolutions: {
        "ember": "release"
      }
    },
    {
      name: 'ember-beta',
      dependencies: {
        "ember": "components/ember#beta"
      },
      resolutions: {
        "ember": "beta"
      }
    },
    {
      name: 'ember-canary',
      dependencies: {
        "ember": "components/ember#canary"
      },
      resolutions: {
        "ember": "canary"
      }
    }
  ]
};
<|endoftext|>


<commit_before>"use strict";
setInterval(function () {
  if(alert('Your session has expired!')){}
  else    window.location.reload();
}, 7200000);

$(function() {
    'use strict';
function showSize() {
  $('#size').html('HEIGHT : ' + $(window).height() + '
WIDTH : ' + $(window).width());
  $('#size2').html('HEIGHT : ' + screen.height + '
WIDTH : ' + screen.width);
  $('#size3').html('HEIGHT : ' + $('.main-content').height() + '
WIDTH : ' + $('.main-content').width());
}
  $(window).on('resize', showSize);
  showSize();
});
$(function() {
    "use strict";
    $('A[rel="external"]')
        .click(function() {
            window.open($(this).attr('href'),
                rel = "noopener noreferrer");
            return false;
            var newWnd = window.open();
            newWnd.opener = null;
        });
});
$(function() {
    "use strict";
    $('form#ajax').on('submit', function() {
        var that = $(this),
            url = that.attr('action'),
            type = that.attr('method'),
            data = {};
        that.find('[name]').each(function(index, value) {
            var that = $(this),
                name = that.attr('name'),
                value = that.val();
            data[name] = value;
        });
        $.ajax({
            url: url,
            type: type,
            data: data,
            success: function(response) {
                $('#display').html(response).delay(8000).fadeOut(1000);
            }
        });
        return false;
    });
});
for (var i = 0; i < document.links.length; i++) {/*this highlights the current active link*/
    if (document.links[i].href == document.URL) {
        document.links[i].className = 'current';
    }
}
$(function() {
  $("#date").datepicker();
});

 $(function(){
   $(".ancestryContent").hide();
  	$('button.grab').on('click', function(){
 		$(this).next('.ancestryContent').slideToggle('slow');
 	});
});

//  $(function(){
//     	$(".ancestryContent").hide();
//     $(".grab").on('click', function () {
//    $(".grab").toggle(
//      function(e) {
//          e.preventDefault();
//          $(this).next(".ancestryContent").slideDown('slow');
//          $(this).html("Hide Content");
//  		$(this).css("opacity", ".5")},
//     function(e) {
//          e.preventDefault();
//          $(this).next(".ancestryContent").hide("explode", { pieces: 16 }, 2000);
//          $(this).html("Read More");
//  		$(this).css("opacity", "1.0");
//    });
// });
// });
<commit_msg>Commented out expire<commit_after>"use strict";
// setInterval(function () {
//   if(alert('Your session has expired!')){}
//   else    window.location.reload();
// }, 7200000);

$(function() {
    'use strict';
function showSize() {
  $('#size').html('HEIGHT : ' + $(window).height() + '
WIDTH : ' + $(window).width());
  $('#size2').html('HEIGHT : ' + screen.height + '
WIDTH : ' + screen.width);
  $('#size3').html('HEIGHT : ' + $('.main-content').height() + '
WIDTH : ' + $('.main-content').width());
}
  $(window).on('resize', showSize);
  showSize();
});
$(function() {
    "use strict";
    $('A[rel="external"]')
        .click(function() {
            window.open($(this).attr('href'),
                rel = "noopener noreferrer");
            return false;
            var newWnd = window.open();
            newWnd.opener = null;
        });
});
$(function() {
    "use strict";
    $('form#ajax').on('submit', function() {
        var that = $(this),
            url = that.attr('action'),
            type = that.attr('method'),
            data = {};
        that.find('[name]').each(function(index, value) {
            var that = $(this),
                name = that.attr('name'),
                value = that.val();
            data[name] = value;
        });
        $.ajax({
            url: url,
            type: type,
            data: data,
            success: function(response) {
                $('#display').html(response).delay(8000).fadeOut(1000);
            }
        });
        return false;
    });
});
for (var i = 0; i < document.links.length; i++) {/*this highlights the current active link*/
    if (document.links[i].href == document.URL) {
        document.links[i].className = 'current';
    }
}
$(function() {
  $("#date").datepicker();
});

 $(function(){
   $(".ancestryContent").hide();
  	$('button.grab').on('click', function(){
 		$(this).next('.ancestryContent').slideToggle('slow');
 	});
});

//  $(function(){
//     	$(".ancestryContent").hide();
//     $(".grab").on('click', function () {
//    $(".grab").toggle(
//      function(e) {
//          e.preventDefault();
//          $(this).next(".ancestryContent").slideDown('slow');
//          $(this).html("Hide Content");
//  		$(this).css("opacity", ".5")},
//     function(e) {
//          e.preventDefault();
//          $(this).next(".ancestryContent").hide("explode", { pieces: 16 }, 2000);
//          $(this).html("Read More");
//  		$(this).css("opacity", "1.0");
//    });
// });
// });
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      bower: {
        dependencies: { }
      }
    },
    {
      name: 'ember-1.13',
      bower: {
        dependencies: {
          'ember': '~1.13.0'
        },
        resolutions: {
          'ember': '~1.13.0'
        }
      }
    },
    {
      name: 'ember-release',
      bower: {
        dependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      }
    },
    {
      name: 'ember-beta',
      bower: {
        dependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      }
    },
    {
      name: 'ember-canary',
      bower: {
        dependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      }
    }
  ]
};
<commit_msg>rm obsolete custom ember try configuration.<commit_after><|endoftext|>


<commit_before>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = async function() {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-lts-3.4',
        npm: {
          devDependencies: {
            'ember-source': '~3.4.0'
          }
        }
      },
      {
        name: 'ember-lts-3.8',
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0'
          }
        }
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release')
          }
        }
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta')
          }
        }
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary')
          }
        }
      },
      // The default `.travis.yml` runs this scenario via `npm test`,
      // not via `ember try`. It's still included here so that running
      // `ember try:each` manually or from a customized CI config will run it
      // along with all the other scenarios.
      {
        name: 'ember-default',
        npm: {
          devDependencies: {}
        }
      },
      {
        name: 'ember-default-with-jquery',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({
            'jquery-integration': true
          })
        },
        npm: {
          devDependencies: {
            '@ember/jquery': '^0.5.1'
          }
        }
      }
    ]
  };
};
<commit_msg>Remove Some ember-try Scenarios<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = async function() {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release')
          }
        }
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta')
          }
        }
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary')
          }
        }
      },
      // The default `.travis.yml` runs this scenario via `npm test`,
      // not via `ember try`. It's still included here so that running
      // `ember try:each` manually or from a customized CI config will run it
      // along with all the other scenarios.
      {
        name: 'ember-default',
        npm: {
          devDependencies: {}
        }
      },
      {
        name: 'ember-default-with-jquery',
        env: {
          EMBER_OPTIONAL_FEATURES: JSON.stringify({
            'jquery-integration': true
          })
        },
        npm: {
          devDependencies: {
            '@ember/jquery': '^0.5.1'
          }
        }
      }
    ]
  };
};
<|endoftext|>


<commit_before>var current_url = window.location;

function url_exists(url, cb){
    jQuery.ajax({
        url:      url,
		async:	  false,
        dataType: 'text',
        type:     'GET',
        complete:  function(xhr){
            if(typeof cb === 'function')
               cb.apply(this, [xhr.status]);
        }
    });
}

// onload
$(window).bind('load', function(){

		var converter = new Showdown.converter();
		var data = '';
		var this_project = '';
		var project_name = '';
		var progress = [];

		// fetch data from .md file
		$.get('project.md', function(data) {
		data = converter.makeHtml(data);
		data = $('
').append(data); // quick parsing fix
		//console.log(data);

		// logotype
		$('h1#logo').text($('h1',data).text());

		// logotype
		$('#compatibility').text($('p',data).text());

		// tabs
		$('.tab-pane').each(function(i) {

			$('ul:nth(' + i + ') > li',data).each(function(j) {

				project_name = $(this).text();
				project_name_sys = project_name.split(' ').join('_').toLowerCase() + '/'; // + '.html'
				this_project = $('.projects .table tbody:nth(' + i + ')');

				url_exists('project/' + project_name_sys, function(status){

					if(status === 200){
					   this_project.append('
  ' + project_name + ' 	  Ready
');
					}
					else{
					   this_project.append('
  ' + project_name + ' 	   In Progress
');
					}

				});

			});

			// create data array for the progress bar
			if($('.status',this).length){
				progress.push( $('.status.ready',this).length / $('.status',this).length * 100 );
			}

			// remove tab if there's no content
			if($('.status',this).length==0){
				$('ul.nav-tabs li:nth(' + i + ')').remove();
			}

		});

		// paint the progress bar
		$('.progress .bar').each(function(i) {
			$(this).css('width', progress[i]/  progress.length + '%');
		});

	});

});

<commit_msg>Update assets/js/projector.js<commit_after>var current_url = window.location;

function url_exists(url, cb){
	jQuery.ajax({
		url:      url,
		async:    false,
		dataType: 'text',
		type:     'HEAD',
		complete:  function(xhr){
			if(typeof cb === 'function')
				cb.apply(this, [xhr.status]);
		}
	});
}

// onload
$(window).bind('load', function(){

		var converter = new Showdown.converter();
		var data = '';
		var this_project = '';
		var project_name = '';
		var progress = [];

		// fetch data from .md file
		$.get('project.md', function(data) {
		data = converter.makeHtml(data);
		data = $('
').append(data); // quick parsing fix
		//console.log(data);

		// logotype
		$('h1#logo').text($('h1',data).text());

		// logotype
		$('#compatibility').text($('p',data).text());

		// tabs
		$('.tab-pane').each(function(i) {

			$('ul:nth(' + i + ') > li',data).each(function(j) {

				project_name = $(this).text();
				project_name_sys = project_name.split(' ').join('_').toLowerCase() + '/'; // + '.html'
				this_project = $('.projects .table tbody:nth(' + i + ')');

				url_exists('project/' + project_name_sys, function(status){

					if(status === 200){
						this_project.append('
  ' + project_name + ' 	  Ready
');
					}
					else{
						this_project.append('
  ' + project_name + ' 	   In Progress
');
					}

				});

			});

			// create data array for the progress bar
			if($('.status',this).length){
				progress.push( $('.status.ready',this).length / $('.status',this).length * 100 );
			}

			// remove tab if there's no content
			if($('.status',this).length===0){
				$('ul.nav-tabs li:nth(' + i + ')').remove();
			}

		});

		// paint the progress bar
		$('.progress .bar').each(function(i) {
			$(this).css('width', progress[i]/  progress.length + '%');
		});

	});

});
<|endoftext|>


<commit_before>/*jshint node:true*/
var command = [ 'ember', 'exam', '--split', '3', '--random' ];
var pr = process.env.TRAVIS_PULL_REQUEST;

if (pr) {
  command.push(pr);
}

module.exports = {
  command: command.join(' ')
};
<commit_msg>Remove PR # from randomization<commit_after>/*jshint node:true*/
var command = [ 'ember', 'exam', '--split', '3', '--random' ];

module.exports = {
  command: command.join(' ')
};
<|endoftext|>


<commit_before>$.fn.romoForm = function(givenSubmitElement, givenIndicatorElements) {
  return $.map(this, function(element) {
    return new RomoForm(element, givenSubmitElement, givenIndicatorElements);
  });
}

var RomoForm = function(element, givenSubmitElement, givenIndicatorElements) {
  this.elem = $(element);
  this.defaultSubmitElem = this.elem.find('button[type="submit"], input[type="submit"], [data-romo-form-submit]');
  this.submitElem = $(givenSubmitElement || this.defaultSubmitElem);
  this.defaultIndicatorElems = this.elem.find('[data-romo-indicator-auto="true"]');
  this.indicatorElems = $(givenIndicatorElements || this.defaultIndicatorElems);
  this.changeSubmitElems = this.elem.find('[data-romo-form-change-submit="true"]');
  this.onkeySubmitElems = this.elem.find('[data-romo-form-onkey-submit="true"]');

  this.defaultListValuesDelim = ',';
  this.onkeyDefaultSubmitDelay = 300;  // 0.3 secs
  this.submitQueued  = false;
  this.submitRunning = false;

  this.removeEmptyGetParams = this.elem.data('romo-form-remove-empty-get-params')
  if (this.removeEmptyGetParams === undefined) {
    this.removeEmptyGetParams = true;
  }

  this.decodeParams = this.elem.data('romo-form-decode-params')
  if (this.decodeParams === undefined) {
    this.decodeParams = true;
  }

  this.doInit();
  this.doBindForm();
  this.elem.trigger('form:clearMsgs', [this]);
  this.elem.trigger('form:ready', [this]);
}

RomoForm.prototype.doInit = function() {
  // override as needed
}

RomoForm.prototype.doBindForm = function() {
  this.defaultSubmitElem.unbind('click');
  this.submitElem.unbind('click');
  this.submitElem.on('click', $.proxy(this.onSubmitClick, this));

  this.changeSubmitElems.on('change', $.proxy(function(e) {
    this.elem.trigger('form:triggerSubmit');
  }, this));
  this.onkeySubmitElems.on('onkey:trigger', $.proxy(function(e, triggerEvent, onkey) {
    clearTimeout(this.onkeySubmitTimeout);
    this.onkeySubmitTimeout = setTimeout($.proxy(function() {
      this.elem.trigger('form:triggerSubmit');
    }, this), onkey.elem.data('romo-form-onkey-submit-delay') || this.onkeyDefaultSubmitDelay);
  }, this));
  this.elem.on('form:triggerSubmit', $.proxy(this.onSubmitClick, this));

  this.elem.on('keypress', $.proxy(this.onFormKeyPress, this));

  if (this.elem.data('romo-form-reload-page') === true) {
    this.elem.on('form:submitSuccess', function(e, data, form) {
      Romo.reloadPage();
    })
  }

}

RomoForm.prototype.onFormKeyPress = function(e) {
  if (this.elem.data('romo-form-disable-keypress') !== true) {
    var target = $(e.target);

    if (target.is(':not(TEXTAREA)') && e.keyCode === 13 /* Enter */) {
      e.preventDefault();
      this.onSubmitClick();
    }
  }
}

RomoForm.prototype.onSubmitClick = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.submitElem.data('romo-form-submit') === 'confirm') {
    this.elem.trigger('form:confirmSubmit', [this]);
  } else if (this.submitElem.hasClass('disabled') === false) {
    this.doSubmit();
  }
}

RomoForm.prototype.doSubmit = function() {
  this.submitQueued = true;
  if (this.submitRunning === false) {
    this._doSubmit();
  }
}

RomoForm.prototype.onSubmitSuccess = function(data, status, xhr) {
  this.elem.trigger('form:clearMsgs');
  this.elem.trigger('form:submitSuccess', [data, this]);
  this._doCompleteSubmit();
}

RomoForm.prototype.onSubmitError = function(xhr, errorType, error) {
  this.elem.trigger('form:clearMsgs');

  if(xhr.status === 422) {
    this.elem.trigger('form:submitInvalidMsgs', [$.parseJSON(xhr.responseText), xhr, this]);
  } else {
    this.elem.trigger('form:submitXhrError', [xhr, this]);
  }
  this.elem.trigger('form:submitError', [xhr, this]);
  this.indicatorElems.trigger('indicator:triggerStop');
  this._doCompleteSubmit();
}

// private

RomoForm.prototype._doCompleteSubmit = function() {
  this.elem.trigger('form:submitComplete', [this]);
  if (this.submitQueued === true) {
    this._doSubmit();
  } else {
    this.submitRunning = false;
  }
}

RomoForm.prototype._doSubmit = function() {
  this.submitQueued  = false;
  this.submitRunning = true;
  this.indicatorElems.trigger('indicator:triggerStart');
  this.elem.trigger('form:beforeSubmit', [this]);

  if(this.elem.data('romo-form-browser-submit') === true) {
    this._doBrowserSubmit();
  } else if (this.elem.attr('method').toUpperCase() === 'GET') {
    this._doNonBrowserGetSubmit();
  } else {
    this._doNonBrowserNonGetSubmit();
  }
}

RomoForm.prototype._doBrowserSubmit = function() {
  this.elem.submit();
  this.elem.trigger('form:browserSubmit', [this]);
}

RomoForm.prototype._doNonBrowserGetSubmit = function() {
  var data = this._getSerializeObj();

  if (this.elem.data('romo-form-redirect-page') === true) {
    var paramString = Romo.param(data, {
      removeEmpty:  this.removeEmptyGetParams,
      decodeValues: this.decodeParams
    });
    if (paramString !== '') {
      Romo.redirectPage(this.elem.attr('action') + '?' + paramString);
    } else {
      Romo.redirectPage(this.elem.attr('action'));
    }

  } else {
    this._doAjaxSubmit(data, true);
  }
}

RomoForm.prototype._doNonBrowserNonGetSubmit = function() {
  this._doAjaxSubmit(this._getFormData(), false);
}

RomoForm.prototype._doAjaxSubmit = function(data, process) {
  $.ajax({
    url:         this.elem.attr('action'),
    type:        this.elem.attr('method'),
    dataType:    this._getXhrDataType(),
    data:        data,
    processData: process,
    contentType: false,
    success:     $.proxy(this.onSubmitSuccess, this),
    error:       $.proxy(this.onSubmitError, this)
  });
}

RomoForm.prototype._getFormData = function() {
  var formData = new FormData();

  $.each(this._getSerializeObj(), function(k, v){ formData.append(k, v) });
  $.each(this.elem.find('INPUT[type="file"]'), function(i, fileInput) {
    var attrName = $(fileInput).attr('name')
    $.each(fileInput.files, function(i, file) { formData.append(attrName, file) });
  });

  return formData;
}

RomoForm.prototype._getSerializeObj = function() {
  var listNamesDelims = this._getListValueInputNamesDelims();

  return this.elem.serializeArray().reduce(function(prev, curr) {
    if (listNamesDelims[curr.name] !== undefined) {
      prev[curr.name] = $.map([prev[curr.name], curr.value], function(v) {
        return v; // $.map removes null/undefined vals, this acts like a compact function
      }).join(listNamesDelims[curr.name])
    } else {
      prev[curr.name] = curr.value;
    }

    return prev;
  }, {});
}

RomoForm.prototype._getListValueInputNamesDelims = function() {
  return Romo.toArray(this.elem.find('[data-romo-form-list-values="true"]')).reduce($.proxy(function(prev, curr) {
    prev[$(curr).attr('name')] = $(curr).data('romo-form-list-values-delim') || this.defaultListValuesDelim;
    return prev;
  }, this), {});
}

RomoForm.prototype._getXhrDataType = function() {
  if(this.elem.data('romo-form-xhr-data-type') !== undefined) {
    return this.elem.data('romo-form-xhr-data-type');
  } else {
    return 'json';
  }
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-form-auto="true"]').romoForm();
});

<commit_msg>add `data-romo-form-disable-enter-submit` option to forms/inputs<commit_after>$.fn.romoForm = function(givenSubmitElement, givenIndicatorElements) {
  return $.map(this, function(element) {
    return new RomoForm(element, givenSubmitElement, givenIndicatorElements);
  });
}

var RomoForm = function(element, givenSubmitElement, givenIndicatorElements) {
  this.elem = $(element);
  this.defaultSubmitElem = this.elem.find('button[type="submit"], input[type="submit"], [data-romo-form-submit]');
  this.submitElem = $(givenSubmitElement || this.defaultSubmitElem);
  this.defaultIndicatorElems = this.elem.find('[data-romo-indicator-auto="true"]');
  this.indicatorElems = $(givenIndicatorElements || this.defaultIndicatorElems);
  this.changeSubmitElems = this.elem.find('[data-romo-form-change-submit="true"]');
  this.onkeySubmitElems = this.elem.find('[data-romo-form-onkey-submit="true"]');

  this.defaultListValuesDelim = ',';
  this.onkeyDefaultSubmitDelay = 300;  // 0.3 secs
  this.submitQueued  = false;
  this.submitRunning = false;

  this.removeEmptyGetParams = this.elem.data('romo-form-remove-empty-get-params')
  if (this.removeEmptyGetParams === undefined) {
    this.removeEmptyGetParams = true;
  }

  this.decodeParams = this.elem.data('romo-form-decode-params')
  if (this.decodeParams === undefined) {
    this.decodeParams = true;
  }

  this.doInit();
  this.doBindForm();
  this.elem.trigger('form:clearMsgs', [this]);
  this.elem.trigger('form:ready', [this]);
}

RomoForm.prototype.doInit = function() {
  // override as needed
}

RomoForm.prototype.doBindForm = function() {
  this.defaultSubmitElem.unbind('click');
  this.submitElem.unbind('click');
  this.submitElem.on('click', $.proxy(this.onSubmitClick, this));

  this.changeSubmitElems.on('change', $.proxy(function(e) {
    this.elem.trigger('form:triggerSubmit');
  }, this));
  this.onkeySubmitElems.on('onkey:trigger', $.proxy(function(e, triggerEvent, onkey) {
    clearTimeout(this.onkeySubmitTimeout);
    this.onkeySubmitTimeout = setTimeout($.proxy(function() {
      this.elem.trigger('form:triggerSubmit');
    }, this), onkey.elem.data('romo-form-onkey-submit-delay') || this.onkeyDefaultSubmitDelay);
  }, this));
  this.elem.on('form:triggerSubmit', $.proxy(this.onSubmitClick, this));

  this.elem.on('keypress', $.proxy(this.onFormKeyPress, this));

  if (this.elem.data('romo-form-reload-page') === true) {
    this.elem.on('form:submitSuccess', function(e, data, form) {
      Romo.reloadPage();
    })
  }

}

RomoForm.prototype.onFormKeyPress = function(e) {
  if (this.elem.data('romo-form-disable-keypress') !== true) {
    var targetElem = $(e.target);
    if (targetElem.is(':not(TEXTAREA)') && e.keyCode === 13 /* Enter */) {
      e.preventDefault();
      if (this.elem.data('romo-form-disable-enter-submit') !== true &&
          targetElem.data('romo-form-disable-enter-submit') !== true) {
        this.onSubmitClick();
      }
    }
  }
}

RomoForm.prototype.onSubmitClick = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.submitElem.data('romo-form-submit') === 'confirm') {
    this.elem.trigger('form:confirmSubmit', [this]);
  } else if (this.submitElem.hasClass('disabled') === false) {
    this.doSubmit();
  }
}

RomoForm.prototype.doSubmit = function() {
  this.submitQueued = true;
  if (this.submitRunning === false) {
    this._doSubmit();
  }
}

RomoForm.prototype.onSubmitSuccess = function(data, status, xhr) {
  this.elem.trigger('form:clearMsgs');
  this.elem.trigger('form:submitSuccess', [data, this]);
  this._doCompleteSubmit();
}

RomoForm.prototype.onSubmitError = function(xhr, errorType, error) {
  this.elem.trigger('form:clearMsgs');

  if(xhr.status === 422) {
    this.elem.trigger('form:submitInvalidMsgs', [$.parseJSON(xhr.responseText), xhr, this]);
  } else {
    this.elem.trigger('form:submitXhrError', [xhr, this]);
  }
  this.elem.trigger('form:submitError', [xhr, this]);
  this.indicatorElems.trigger('indicator:triggerStop');
  this._doCompleteSubmit();
}

// private

RomoForm.prototype._doCompleteSubmit = function() {
  this.elem.trigger('form:submitComplete', [this]);
  if (this.submitQueued === true) {
    this._doSubmit();
  } else {
    this.submitRunning = false;
  }
}

RomoForm.prototype._doSubmit = function() {
  this.submitQueued  = false;
  this.submitRunning = true;
  this.indicatorElems.trigger('indicator:triggerStart');
  this.elem.trigger('form:beforeSubmit', [this]);

  if(this.elem.data('romo-form-browser-submit') === true) {
    this._doBrowserSubmit();
  } else if (this.elem.attr('method').toUpperCase() === 'GET') {
    this._doNonBrowserGetSubmit();
  } else {
    this._doNonBrowserNonGetSubmit();
  }
}

RomoForm.prototype._doBrowserSubmit = function() {
  this.elem.submit();
  this.elem.trigger('form:browserSubmit', [this]);
}

RomoForm.prototype._doNonBrowserGetSubmit = function() {
  var data = this._getSerializeObj();

  if (this.elem.data('romo-form-redirect-page') === true) {
    var paramString = Romo.param(data, {
      removeEmpty:  this.removeEmptyGetParams,
      decodeValues: this.decodeParams
    });
    if (paramString !== '') {
      Romo.redirectPage(this.elem.attr('action') + '?' + paramString);
    } else {
      Romo.redirectPage(this.elem.attr('action'));
    }

  } else {
    this._doAjaxSubmit(data, true);
  }
}

RomoForm.prototype._doNonBrowserNonGetSubmit = function() {
  this._doAjaxSubmit(this._getFormData(), false);
}

RomoForm.prototype._doAjaxSubmit = function(data, process) {
  $.ajax({
    url:         this.elem.attr('action'),
    type:        this.elem.attr('method'),
    dataType:    this._getXhrDataType(),
    data:        data,
    processData: process,
    contentType: false,
    success:     $.proxy(this.onSubmitSuccess, this),
    error:       $.proxy(this.onSubmitError, this)
  });
}

RomoForm.prototype._getFormData = function() {
  var formData = new FormData();

  $.each(this._getSerializeObj(), function(k, v){ formData.append(k, v) });
  $.each(this.elem.find('INPUT[type="file"]'), function(i, fileInput) {
    var attrName = $(fileInput).attr('name')
    $.each(fileInput.files, function(i, file) { formData.append(attrName, file) });
  });

  return formData;
}

RomoForm.prototype._getSerializeObj = function() {
  var listNamesDelims = this._getListValueInputNamesDelims();

  return this.elem.serializeArray().reduce(function(prev, curr) {
    if (listNamesDelims[curr.name] !== undefined) {
      prev[curr.name] = $.map([prev[curr.name], curr.value], function(v) {
        return v; // $.map removes null/undefined vals, this acts like a compact function
      }).join(listNamesDelims[curr.name])
    } else {
      prev[curr.name] = curr.value;
    }

    return prev;
  }, {});
}

RomoForm.prototype._getListValueInputNamesDelims = function() {
  return Romo.toArray(this.elem.find('[data-romo-form-list-values="true"]')).reduce($.proxy(function(prev, curr) {
    prev[$(curr).attr('name')] = $(curr).data('romo-form-list-values-delim') || this.defaultListValuesDelim;
    return prev;
  }, this), {});
}

RomoForm.prototype._getXhrDataType = function() {
  if(this.elem.data('romo-form-xhr-data-type') !== undefined) {
    return this.elem.data('romo-form-xhr-data-type');
  } else {
    return 'json';
  }
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-form-auto="true"]').romoForm();
});

<|endoftext|>


<commit_before>/**
 * @name pc.script
 * @namespace User Scripts
 */
pc.script = (function () {
    var _main = null;
    var _loader = null;

    var script = {
        /**
         * Register the main game script resource, this is executed by called pc.script.start()
         * @function
         * @name pc.script.main
         */
        main: function (callback) {
            if(_main) {
                throw new Error("'main' Object already registered");
            }
            _main = callback;
        },

        setLoader: function(loader) {
            if(loader && _loader) {
                throw new Error("pc.script already has loader object.");
            }

            _loader = loader;
        },

        /**
         * @function
         * @name pc.script.create
         * @description Create a script resource object. A script file should contain a single call to pc.script.create and the callback should return a script object which will be
         * instanciated when attached to Entities.
         * @param {Object} name The name of the script object.
         * @param {Object} callback The callback function which is passed an {pc.fw.ApplicationContext} object,
         * which is used to access Entities and Components, and should return the Type of the script resource
         * to be instanced for each Entity.
         * @example
         * pc.script.create( function (context) {
         *  var Scriptable = function (entity) {
         *      // store entity
         *      this.entity = entity;
         *
         *      // use context
         *      context.components.model.addComponent(entity, {...});
         *  };
         *
         *  return Scriptable;
         * }
         */
        create: function (name, callback) {
            if (typeof(callback) === 'undefined') {
                callback = attributes;
            }
            //_loader.add(name, callback);
            this.fire("created", name, callback);
        },

        /**
        * @function
        * @name pc.script.attribute
        * @description Creates a script attribute for the current script. The script attribute can be accessed
        * inside the script instance like so 'this.attributeName' or outside a script instance like so 'entity.script.attributeName'.
        * Script attributes can be edited from the Attribute Editor of the designer like normal Components.
        * @param {string} name The name of the attribute
        * @param {string} type The type of the attribute. Can be one of the following: 'number', 'string', 'boolean', 'asset', 'rgb', 'rgba', 'vector', 'enumeration'
        * @param {Object} defaultValue The default value of the attribute
        * @param {Object} options Optional parameters for the attribute. Valid values are:
        *

        *
{Number} min: The minimum value of the attribute

        *
{Number} max: The maximum value of the attribute

        *
{Number} step: The step that will be used when changing the attribute value in the designer

        *
{Number} decimalPrecision: A number that specifies the number of decimal digits allowed for the value

        *
{Array} enumerations: An array of name, value pairs from which the user can select one if the attribute type is an enumeration

        *

        * @example
        * pc.script.attribute('speed', 'number', 5);
        * pc.script.attribute('message', 'string', "My message");
        * pc.script.attribute('enemyPosition', 'vector', [1,0,0]);
        * pc.script.attribute('spellType', 'enumeration', 0, {
        *
        * pc.script.create( function (context) {
        *     enumerations: [{
        *        name: "Fire",
        *        value: 0
        *     }, {
        *        name: "Ice",
        *        value: 1
        *     }]
        *  });
        *
        *  var Scriptable = function (entity) {
        *      // store entity
        *      this.entity = entity;
        *  };
        *
        *  return Scriptable;
        * }
        */
        attribute: function (name, type, defaultValue, options) {
            // only works when parsing the script...
        },

        /**
         * Begin the scripted application by calling the function passed in to pc.script.main()
         * @function
         * @name pc.script.start
         */
        start: function () {
            _main();
        }
    };

    pc.extend(script, pc.events);

    return script;
}());<commit_msg>Fixed typo in script attribute docs<commit_after>/**
 * @name pc.script
 * @namespace User Scripts
 */
pc.script = (function () {
    var _main = null;
    var _loader = null;

    var script = {
        /**
         * Register the main game script resource, this is executed by called pc.script.start()
         * @function
         * @name pc.script.main
         */
        main: function (callback) {
            if(_main) {
                throw new Error("'main' Object already registered");
            }
            _main = callback;
        },

        setLoader: function(loader) {
            if(loader && _loader) {
                throw new Error("pc.script already has loader object.");
            }

            _loader = loader;
        },

        /**
         * @function
         * @name pc.script.create
         * @description Create a script resource object. A script file should contain a single call to pc.script.create and the callback should return a script object which will be
         * instanciated when attached to Entities.
         * @param {Object} name The name of the script object.
         * @param {Object} callback The callback function which is passed an {pc.fw.ApplicationContext} object,
         * which is used to access Entities and Components, and should return the Type of the script resource
         * to be instanced for each Entity.
         * @example
         * pc.script.create( function (context) {
         *  var Scriptable = function (entity) {
         *      // store entity
         *      this.entity = entity;
         *
         *      // use context
         *      context.components.model.addComponent(entity, {...});
         *  };
         *
         *  return Scriptable;
         * }
         */
        create: function (name, callback) {
            if (typeof(callback) === 'undefined') {
                callback = attributes;
            }
            //_loader.add(name, callback);
            this.fire("created", name, callback);
        },

        /**
        * @function
        * @name pc.script.attribute
        * @description Creates a script attribute for the current script. The script attribute can be accessed
        * inside the script instance like so 'this.attributeName' or outside a script instance like so 'entity.script.attributeName'.
        * Script attributes can be edited from the Attribute Editor of the designer like normal Components.
        * @param {string} name The name of the attribute
        * @param {string} type The type of the attribute. Can be one of the following: 'number', 'string', 'boolean', 'asset', 'rgb', 'rgba', 'vector', 'enumeration'
        * @param {Object} defaultValue The default value of the attribute
        * @param {Object} options Optional parameters for the attribute. Valid values are:
        *

        *
{Number} min: The minimum value of the attribute

        *
{Number} max: The maximum value of the attribute

        *
{Number} step: The step that will be used when changing the attribute value in the designer

        *
{Number} decimalPrecision: A number that specifies the number of decimal digits allowed for the value

        *
{Array} enumerations: An array of name, value pairs from which the user can select one if the attribute type is an enumeration

        *

        * @example
        * pc.script.attribute('speed', 'number', 5);
        * pc.script.attribute('message', 'string', "My message");
        * pc.script.attribute('enemyPosition', 'vector', [1,0,0]);
        * pc.script.attribute('spellType', 'enumeration', 0, {
        *     enumerations: [{
        *        name: "Fire",
        *        value: 0
        *     }, {
        *        name: "Ice",
        *        value: 1
        *     }]
        *  });
        *
        * pc.script.create('scriptable', function (context) {
        *  var Scriptable = function (entity) {
        *      // store entity
        *      this.entity = entity;
        *  };
        *
        *  return Scriptable;
        * }
        */
        attribute: function (name, type, defaultValue, options) {
            // only works when parsing the script...
        },

        /**
         * Begin the scripted application by calling the function passed in to pc.script.main()
         * @function
         * @name pc.script.start
         */
        start: function () {
            _main();
        }
    };

    pc.extend(script, pc.events);

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


<commit_before>import dialog from 'dialog';
import yargs from 'yargs';
import path from 'path';
import app from 'app';

import CrashReporter from 'crash-reporter';
import SquirrelEvents from './components/squirrel-events';

import manifest from '../../package.json';

// Handle uncaught exceptions
process.on('uncaughtException', function(ex) {
  const isSignatureEx = ex.message == 'Could not get code signature for running application';
  const isDevRelease = manifest.distrib == 'unset';
  if (isDevRelease && isSignatureEx) {
    logFatal('uncaught exception', ex.message);
  } else {
    dialog.showErrorBox('JavaScript error in the main process', ex.stack);
  }
});

(function() {
  // Define the CLI arguments and parse them
  const cliArgs = process.argv.slice(1, process.argv.length);
  const options = yargs(cliArgs)
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being ran by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('debug', {
      type: 'boolean',
      description: 'Run in debug mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Created with <3 by Alexandru Rosianu – http://www.aluxian.com/')
    .argv;

  log('cli args parsed', options);
  global.manifest = manifest;
  global.options = options;

  options.portable = options.portable || !!manifest.portable;
  options.debug = options.debug || !!process.env.DEBUG;

  if (options.debug) {
    log('debug mode enabled');
  }

  // Check for Squirrel.Windows CLI args
  if (process.platform == 'win32' && SquirrelEvents.check(options)) {
    log('Squirrel.Windows event detected');
    return;
  }

  // Print the version and exit
  if (options.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      const mainWindow = global.application.mainWindowManager.window;
      if (mainWindow) {
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();
      }
    }
    return true;
  });

  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Change the userData path if in portable mode
  if (options.portable) {
    log('running in portable mode');
    const filePaths = require('./utils/file-paths').default;
    const userDataPath = path.join(filePaths.getAppDir(), 'data');
    log('set userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Enable the crash reporter
  if (!process.mas) {
    app.on('will-finish-launching', function() {
      log('will finish launching');

      // Crash reporter
      const reporterOptions = {
        productName: manifest.productName,
        companyName: manifest.win.companyName,
        submitURL: manifest.crashReporter.url,
        autoSubmit: true
      };

      log('starting crash reporter', JSON.stringify(reporterOptions));
      CrashReporter.start(reporterOptions);
    });
  } else {
    log('mas release');
  }

  // Create the main app object and init
  app.on('ready', function() {
    log('ready, launching app');
    const Application = require('./application').default;
    global.application = new Application(manifest, options);
    global.application.init();
  });
})();
<commit_msg>Fixes options.debug order<commit_after>import dialog from 'dialog';
import yargs from 'yargs';
import path from 'path';
import app from 'app';

import CrashReporter from 'crash-reporter';
import SquirrelEvents from './components/squirrel-events';

import manifest from '../../package.json';

// Handle uncaught exceptions
process.on('uncaughtException', function(ex) {
  const isSignatureEx = ex.message == 'Could not get code signature for running application';
  const isDevRelease = manifest.distrib == 'unset';
  if (isDevRelease && isSignatureEx) {
    logFatal('uncaught exception', ex.message);
  } else {
    dialog.showErrorBox('JavaScript error in the main process', ex.stack);
  }
});

(function() {
  // Define the CLI arguments and parse them
  const cliArgs = process.argv.slice(1, process.argv.length);
  const options = yargs(cliArgs)
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being ran by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('debug', {
      type: 'boolean',
      description: 'Run in debug mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Created with <3 by Alexandru Rosianu – http://www.aluxian.com/')
    .argv;

  global.manifest = manifest;
  global.options = options;

  options.portable = options.portable || !!manifest.portable;
  options.debug = options.debug || !!process.env.DEBUG;

  log('cli args parsed', options);
  if (options.debug) {
    log('debug mode enabled');
  }

  // Check for Squirrel.Windows CLI args
  if (process.platform == 'win32' && SquirrelEvents.check(options)) {
    log('Squirrel.Windows event detected');
    return;
  }

  // Print the version and exit
  if (options.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      const mainWindow = global.application.mainWindowManager.window;
      if (mainWindow) {
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();
      }
    }
    return true;
  });

  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Change the userData path if in portable mode
  if (options.portable) {
    log('running in portable mode');
    const filePaths = require('./utils/file-paths').default;
    const userDataPath = path.join(filePaths.getAppDir(), 'data');
    log('set userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Enable the crash reporter
  if (!process.mas) {
    app.on('will-finish-launching', function() {
      log('will finish launching');

      // Crash reporter
      const reporterOptions = {
        productName: manifest.productName,
        companyName: manifest.win.companyName,
        submitURL: manifest.crashReporter.url,
        autoSubmit: true
      };

      log('starting crash reporter', JSON.stringify(reporterOptions));
      CrashReporter.start(reporterOptions);
    });
  } else {
    log('mas release');
  }

  // Create the main app object and init
  app.on('ready', function() {
    log('ready, launching app');
    const Application = require('./application').default;
    global.application = new Application(manifest, options);
    global.application.init();
  });
})();
<|endoftext|>