Jump to content
This is a wiki for a reason. Anyone can contribute. If you see something that is inaccurate or can be improved, don't ask that it be fixed--just improve it.
[ Disclaimer, Create new user --- Wiki markup help, Install P99 ]

MediaWiki:MageloImport.js

From p99 Backup

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
var allSlots = [
  'Neck', 'Head', 'Ears1', 'Ears2', 'Face', 'Chest', 'Arms', 'Back', 'Waist', 'Shoulders',
  'Wrists1', 'Wrists2', 'Legs', 'Hands', 'Fingers1', 'Fingers2', 'Feet', 'Primary',
  'Secondary', 'Range', 'Ammo', 'Inv1', 'Inv2', 'Inv3', 'Inv4', 'Inv5', 'Inv6', 'Inv7', 'Inv8',
];

// Account for differences in slot names between output file and wiki
var convertSlot = function (rows, slot) {
  if (slot === 'Ear') return 'Ears' + (rows.Ears1 ? 2 : 1);
  if (slot === 'Fingers') return rows.Fingers1 ? 'Fingers2' : 'Fingers1';
  if (slot === 'Wrist') return rows.Wrists1 ? 'Wrists2' : 'Wrists1';
  if (slot.substr(0, 7) === 'General') {
    var index = slot.substr(7, 8);
    var isBagSlot = '-' === slot.substr(8, 9);
    if (!isBagSlot) return 'Inv' + index;
  }
  return slot;
};

// Convert output file text rows into an object of slot => item
// (but with a bunch of garbage values also)
var parseRows = function (eqText) {
  var rows = eqText.split('\n');
  return rows.reduce(function (memo, row) {
    var slot = convertSlot(memo, row.split('	')[0]);
    var value = row.split('	')[1];
    memo[slot] = value === 'Empty' ? '' : value;
    return memo;
  }, {});
};

// Take *only* the relevant values from parsed item rows and build a 
// new object with just those properties
var buildItemsBySlot = function (itemRows) {
  return allSlots.reduce(function (itemsBySlot, slot) {
    itemsBySlot[slot] = itemRows[slot];
    return itemsBySlot;
  }, {});
};

// Takes outputfile text, returns parsed object with relevant values only
var parseEqText = function (eqText) {
  var itemRows = parseRows(eqText);
  return buildItemsBySlot(itemRows);
};

// NOTE: These are for Magelo Import; for item ID generation

var buildItemIdMap = function(rows) {
  return rows.reduce(function(idMap, row) {
    var rowParts = row.split('\t');
    var name = rowParts[1];
    var id = rowParts[2];
    if (name === 'Empty' || name === 'Name') return idMap; // Ignore empty item slots
    var newItem = {};
    newItem[name] = id;
    return Object.assign(idMap, newItem);
  }, {})
};

var convertObjectToUl = function(data, containerId, includeCheckbox) {
  Object.entries(data).forEach(function(entry) {
    var checkboxHtml = includeCheckbox ? '<input data-item-id="' + entry[1] + '" type="checkbox" checked id="' +entry[0]+'"/>' : '';
    $(containerId).append('<li><label>' + entry[0] + ' (' + entry[1] + ') ' + checkboxHtml + '</label></li>');
  })
  addCheckboxUi();
  $('#output-caption').text('Your Item\'s (Hexadecimal) Links');
};

var reset = function() {
  $('#item-checkboxes, #checkbox-ui').empty();
  $('#eq-inventory-input').val('');
  $('#output-caption').text('Your Item\'s IDs');
}

var convertArrayToUl = function(data) {
  $('#item-checkboxes').empty();
  data.forEach(function(entry) {
    $('<li>').text(entry).appendTo('#item-checkboxes');
  })
  $('#checkbox-ui').html('<input type="submit" value="Reset" onClick="reset()" />');
};


var parseEqTextIntoIds = function(eqText) {
  var rows = eqText.split('\n');
  var idMap = buildItemIdMap(rows);
  convertObjectToUl(idMap, '#item-checkboxes', true);
}


// Format the object with data into wiki code
var makeMageloCode = function(eqText) {
  var parsed = parseEqText(eqText);
  var mageloCode = allSlots.map(function (slot) {
    // Wiki has newlines before these two "slots"
    var newLine = slot === 'Primary' || slot === 'Inv1' ? '\n' : '';

    return newLine + '* ' + slot + ': ' + (parsed[slot] || '');
  })
  .join('\n');

  $('#magelo-text-output').text(mageloCode);

  // Not sure timeout is necessary, but want to be sure text is on page
  // before we try to copy it (so wait 1ms)
  window.setTimeout(function() {
    copyMageloCode(message)
  });

};

// Once we've updated the page with the new Magelo code, this
// function adds it to the clipboard (or at least tries)
var copyMageloCode = function () {
  try {
      var copyText = $('#magelo-text-output')[0];

      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /*For mobile devices*/

      /* Copy the text inside the text field */
    if (!document.execCommand('copy')) throw new Error('copy failed');

    alert('Your Magelo code has been copied.  You can now paste in your Magelo profile, in ' +
          'place of your current equipment section.');
  } catch (err) {
    console.error(err);
    alert('Failed to copy code :( Please select and copy the code yourself.');
  } finally {
    window.getSelection().removeAllRanges();
  }
};

// When someone adds their outputfile code, trigger the whole process
var buildOnTextareaChange = function(parse) {
  return function (e) {
    var eqText = $(e.target).val();
    if (!eqText) return;

    parse(eqText);
  };
};

var paddWithZerosUpTo45 = function(numberString) {
  while(numberString.length < 45) {
    numberString += '0';
  }
  return numberString;
}

var dc2 = '\u0012';
var convertCheckedToHex = function() {
  var hexMapped = $(':checked').toArray().map(function(checkbox){
    var $checkbox = $(checkbox);
    var name = $checkbox.attr('id');
    var id = $checkbox.data('item-id');
    var hex = '00' + id.toString(16);
    var paddedHex = paddWithZerosUpTo45(hex);
    var withDc2 = dc2 + paddedHex + '      ' + name + ' '+ dc2;
    return withDc2;
  });
  convertArrayToUl(hexMapped);
}

var addCheckboxUi = function() {
  $('#checkbox-ui').html(
    '<a onClick="$(\':checkbox\').attr(\'checked\', true)">Check all</a> | ' +
    '<a onClick="$(\':checkbox\').attr(\'checked\', false)">Uncheck all</a> | ' +
    '<input onClick="convertCheckedToHex()" type="submit" value="Convert to Hexadecimal"/>'
  );
}

// Wiki won't let us have form HTML, so we need to bring it in via JS onLoad
// (this whole file is brought in "onLoad", so no need for event listener)
$('#magelo-import-placeholder').replaceWith(
  '<h3>Add Your Output File Code Below<h3>' +
  '<textarea id="eq-text-input" style="min-height: 6em; max-width:50em""></textarea>' +
  '<h3 style="margin-top:1em">Your Wiki Magelo Code<h3>' +
  '<textarea id="magelo-text-output" ' +
  'style="border: 2px dashed lightBlue; min-height: 10em; min-width: 20em; max-width:50em"' +
  '></textarea>'
);
$('#eq-text-input').change(buildOnTextareaChange(makeMageloCode));

// Similar code for id generator
$('#item-id-generator-placeholder').replaceWith(
  '<h3>Add Your Inventory Output File Code Below<h3>' +
  '<textarea id="eq-inventory-input" style="min-height: 6em; max-width:50em"></textarea>' +
  '<h3 style="margin-top:1em" id="output-caption">Your Item\'s IDs<h3>' +
  '<ul id="item-checkboxes" ' +
  'style="border: 2px dashed lightBlue; min-height: 10em; min-width: 20em; max-width:50em; list-style-type: none; padding: 1em;"' +
  '></ul>' +
  '<p id="checkbox-ui"></p>'
);


$('#eq-inventory-input').change(buildOnTextareaChange(parseEqTextIntoIds));