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 ]

Difference between revisions of "MediaWiki:LocMaps.js"

From Project 1999 Wiki
Jump to: navigation, search
Line 1: Line 1:
 +
try {
 
(function() {
 
(function() {
  
Line 136: Line 137:
  
 
   var removeOpenMap = function(e) {
 
   var removeOpenMap = function(e) {
     if (window.$openMap) window.$openMap.remove();
+
    // Do nothing if there's no open map
 +
     if (!window.$openMap) return false;
 +
 
 +
    // Do nothing if the user clicked to open a map, then moused out of an area
 +
    // (otherwise it can close immediately)
 +
    var position = window.$openMap.css('position');
 +
    if (e.type === 'mouseleave' && position === 'fixed') return false;
 +
 
 +
    window.$openMap.remove();
 
     return false;
 
     return false;
 
   }
 
   }
Line 208: Line 217:
 
     }
 
     }
 
   }
 
   }
 +
 +
  /**
 +
  * Helper function to power parseLocs/extractNonLocText, since they both use
 +
  * the same logic.
 +
  *
 +
  * SIDE NOTE: If only the wiki didn't have to use 1999 JS, and could
 +
  *            destructure return values with ES2015, the two related functions
 +
  *            wouldn't even need to exist :(
 +
  */
 +
  var parseLocString = function(locString) {
 +
    var nonLocParts = '';
 +
    var bits = locString.split(/([\+\-]?\d+\.?\d*\D*,\D*[\+\-]?\d+\.?\d*)/g);
 +
    var relevantBits = bits.filter(function(part) {
 +
      // Filter out the non-loc parts, but save them
 +
      if (isLoc(part)) return true;
 +
      nonLocParts += part; // save as it might be something like "1st floor"
 +
    });
 +
    var locs = relevantBits.map(parseLoc);
 +
    return [locs, nonLocParts];
 +
  };
  
 
   /**
 
   /**
 
   * Extracts all of the locs (objects with x and y properties) from a provided
 
   * Extracts all of the locs (objects with x and y properties) from a provided
 
   * string such as:
 
   * string such as:
   * "500, 200"
+
   *   "500, 200"
   * "(200, 300), (300, 200)"
+
   *   "(200, 300), (300, 200)"
 +
  * and returns an array containing any locs found.
 
   */
 
   */
   var getLocs = function(locString) {
+
   var parseLocs = function(locString) {
     var nonLocParts = '';
+
     return parseLocString[0];
    return locString
+
  };
    .split(/([\+\-]?\d+\.?\d*\D*,\D*[\+\-]?\d+\.?\d*)/g)
+
 
    .filter(function(part) {
+
  /**
        // Filter out the non-loc parts, but save them
+
  * Extracts the non-loc parts (eg. "Level 1") from a provided string of text
        if (isLoc(part)) return true;
+
  * (presumably from an NPC's location <td> or somewhere similar). Although not
        nonLocParts += part; // save as it might be something like "1st floor"
+
  * actually a part of the loc, this text may still be useful in determining
      })
+
  * which map to show for the loc.
    .map(parseLoc)
+
  */
     .concat(nonLocParts);
+
  var extractNonLocText = function(locString) {
 +
     return parseLocString[1];
 
   };
 
   };
  
Line 287: Line 318:
 
   };
 
   };
  
   var handleLocBoxes = function() {
+
   /**
    // Get the mob's loc(s)
+
  * Determines whether the page has a "Location" <td> (as all NPC pages do)
 +
  * with parsable locs inside it (as only some do).  Also checks that
 +
  * "loc-mapped" zone data exists for the NPC's zone.
 +
  */
 +
  var hasLocBoxWithLocs = function() {
 
     var $locTd = $('b:contains("Location:")').parent();
 
     var $locTd = $('b:contains("Location:")').parent();
     var locs = getLocs($locTd.text());
+
    if (!$locTd.length) return false; // page isn't an NPC page (no loc box)
     if (locs.length <= 1) return; // No loc box to hook up
+
   
 +
     var locs = parseLocs($locTd.text());
 +
     if (!locs.length) return false; // no locs existed (or could be parsed)
  
     var nonLocParts = locs[locs.length - 1];
+
     return !!getZoneData(zoneName, locs, nonLocParts); // does zone data exist?
    locs = locs.slice(0, locs.length - 1);
+
  };
  
     // Find the zone name
+
  var handleLocBoxes = function() {
 +
    if (!hasLocBoxWithLocs()) return;
 +
     // Get the mob's loc(s)
 +
    var $locTd = $('b:contains("Location:")').parent();
 +
    var locs = parseLocs($locTd.text());
 +
   
 +
    var nonLocParts = parsedLocs[1];
 +
   
 
     var zoneName = getZoneName();
 
     var zoneName = getZoneName();
 
     // Do we have data for that zone's map?
 
     // Do we have data for that zone's map?
Line 303: Line 347:
  
 
     // Add the mouse-enter link
 
     // Add the mouse-enter link
     var $link = $(' <a href="#">(Map)</a>');
+
     var $link = $(' <a href="#">(Map)</a>')
 +
      // When it's moused-over, show the map nearby
 +
      .on('mouseenter', function(e) {
 +
        // If there is already a map "open" (because of a click), do nothing
 +
        if (window.$openMap && window.$openMap.parent().length) return false;
  
    // When it's moused-over, show the map
+
        var $map = showMapWithLocs('small', zoneData, locs, $locTd);
    $link
+
        $map.parent().one('mouseleave', removeOpenMap);
    .on('mouseenter', function(e) {
+
      })
      var clickedMapIsOpen = window.$openMap && window.$openMap.parent().length;
+
      // When it's clicked, show the map full-screen/lightbox style
      if (clickedMapIsOpen) return false;
+
      .on('click', function(e) {
      var $map = showMapWithLocs('small', zoneData, locs, $locTd);
+
        showMapWithLocs('full', zoneData, locs);
      $map.parent().one('mouseleave', removeOpenMap);
+
      });
    })
+
    .on('click', function(e) {
+
      showMapWithLocs('full', zoneData, locs);
+
    });
+
  
 
     // $locTd.find('b').html($('<span>Location </span>').append($link).append('<span>:</span>'));
 
     // $locTd.find('b').html($('<span>Location </span>').append($link).append('<span>:</span>'));
Line 326: Line 370:
  
  
   try {
+
   // Setup event listeners (code "starts" here)
    handleLocLinks();
+
  handleLocLinks();
    handleLocBoxes();
+
  handleLocBoxes();
   } catch (err) {/* Didn't work, move on */}
+
   
 
+
   // *** HELPER FUNCTIONS ***
 
   // Define two helper functions for building new zone definitions
 
   // Define two helper functions for building new zone definitions
  
Line 355: Line 399:
  
 
})();
 
})();
 +
} catch (err) {
 +
  console.error(err); // If anything goes wrong, move on but log the error
 +
}

Revision as of 05:20, 5 September 2019

try {
(function() {

  // TODO: Add support for cropping maps that have multiple maps.
  // For instance, the following CSS styles show only one of the three maps for 
  // Erudin Palace:
  // background-image:url(/images/Erudinpalace.jpg); 
  // background-position: 250px 0px; width: 275px; height: 272px
  // Figure out how to make the Xs line up with those styles added

  var locIsWithinAlternateData = function(loc, alternateData) {
    return loc.x < alternateData.maxX &&
    loc.x > alternateData.minX &&
    loc.y < alternateData.maxY &&
    loc.y > alternateData.minY;
  };


  /**
   * Determines if the provided name contains any of the provided words
   */
  // TODO: Add a some polyfill to make this a lot simpler
  var containsAny = function(name/* word1, word2, etc. */) {
    for(var arg = 1; arg < arguments.length; ++ arg) {
      var word = arguments[arg];
      if (name.includes(word)) return true;
    }
    return false;
  };

  var containsAnyNumber = function(name, number, suffix) {
    return containsAny.call(null, name, 
     number + suffix,
     'level ' + number,
     'level: ' + number
     );
  };

  var getZoneLevelData = function(levels, text) {
    // Check for part "level" aliases (eg. "1st floor" vs. "Level One")
    text = text.toLowerCase();
    if (containsAnyNumber(text, 0, 'th') || containsAny(text, 'basement', 'underground')) return levels[0];
    if (containsAnyNumber(text, 1, 'st') || containsAny(text, 'one', 'first', 'ground')) return levels[1];
    if (containsAnyNumber(text, 2, 'nd') || containsAny(text, 'two', 'second')) return levels[2];
    if (containsAnyNumber(text, 3, 'rd') || containsAny(text, 'three', 'third')) return levels[3];
    if (containsAnyNumber(text, 4, 'th') || containsAny(text, 'four', 'fourth')) return levels[4];
    if (containsAnyNumber(text, 5, 'th') || containsAny(text, 'five', 'fifth')) return levels[5];
    if (containsAnyNumber(text, 6, 'th') || containsAny(text, 'six', 'sixth')) return levels[6];
    if (containsAnyNumber(text, 7, 'th') || containsAny(text, 'seven', 'seventh')) return levels[7];
    if (containsAnyNumber(text, 8, 'th') || containsAny(text, 'eight', 'eighth')) return levels[8];
    if (containsAnyNumber(text, 9, 'th') || containsAny(text, 'nine', 'ninth')) return levels[9];

    var levelKeys = Object.keys(levels);
    var keyOfLastLevel = levelKeys[levelKeys.length - 1];
    if (containsAny(text, 'top')) return levels[keyOfLastLevel];

    // If we still couldn't match, and there is a ground/1st floor, use it
    return levels[1];
  };

  

  var findZoneData = function(zoneName, locs, nonLocParts) {
    var zone = zoneData[zoneName];

  // Handle aliases (eg. "North Ro" instead of "Northern Desert of Ro")
  if (typeof(zone) === 'string') zone = zoneData[zone];

  if (!zone) return null;

  // Handle Multi-Level Zones (with different maps for 1st, 2nd, etc. floor)
  if (zone.levels) return getZoneLevelData(zone.levels, nonLocParts);

  // Handle Zones with alternate maps on the same level (eg. Kelethin in GFay)
  if (!zone.alternateMaps) return zone;

  for (var i = 0; i < zone.alternateMaps.length; i++) {
    var alternateData = zone.alternateMaps[i];
    var allLocsAreWithin = true;
    // wish I had ES6 [].every
    $.each(locs, function(i, loc) {
      allLocsAreWithin = allLocsAreWithin && 
      locIsWithinAlternateData(loc, alternateData);
    });
    if (allLocsAreWithin) return alternateData;
  };
  return zone;
};

var addImageUrl = function(zoneData) {
  zoneData.imageUrl = '/images/' + zoneData.image;
  return zoneData;
};

var getZoneData = function(zoneName, locs, nonLocParts) {
  var zoneData = findZoneData(zoneName, locs, nonLocParts);
  if (!zoneData) return null;
  zoneData.zoneName = zoneName;
  return addImageUrl(zoneData);
};

  var build$MapImage = function(zoneData) {
    return $(
      '<img alt="Map of ' + zoneData.zoneName + '" ' +
      '     class="thumbborder" ' +
      '     height="'+ zoneData.height + '" ' +
      '     src="' + zoneData.imageUrl + '" ' +
      '     title="Map of ' + zoneData.zoneName + '"' +
      '     width="' + zoneData.width + '" ' +
      '>'
      );
  };``


  var build$WrappedMap = function(zoneData) {
    return $('<div class="x-container"></div>')
      .css({ position: 'relative' })
      .append(build$MapImage(zoneData));
  }


  var build$LightboxFramedMap = function(zoneData) {
    return build$WrappedMap(zoneData)
      .css({
        left: '50%',
        marginLeft: '-' + (zoneData.width / 2) + 'px', // centering
        marginTop: '-' + (zoneData.height / 2) + 'px',
        opacity: 1,
        top: '50%'
      });
  };

  var build$MapFrame = function() {
    return $('<div class="map-wrapper"></div>')
            .css({ position: 'absolute' });
  };

  var removeOpenMap = function(e) {
    // Do nothing if there's no open map
    if (!window.$openMap) return false;

    // Do nothing if the user clicked to open a map, then moused out of an area
    // (otherwise it can close immediately)
    var position = window.$openMap.css('position');
    if (e.type === 'mouseleave' && position === 'fixed') return false;

    window.$openMap.remove();
    return false;
  }

  var build$FullMap = function(zoneData) {
    var $frame = build$MapFrame()
      .css({
        background: 'rgba(0,0,0,0.8)',
        height: '100%',
        left: 0,
        position: 'fixed',
        top: 0,
        width: '100%',
        zIndex: 4 // one higher than #p-search's 3
      })
      .click(removeOpenMap);
    if (zoneData) {
      $frame.html(build$LightboxFramedMap(zoneData));
      $frame.zoneData = zoneData;
    }
    return $frame;
  };

  var build$SmallMap = function(zoneData) {
    return build$MapFrame().append(build$WrappedMap(zoneData));
  }


var buildX = function(left, top, sizeInEm) {
  sizeInEm = sizeInEm || 2.5;
  return $('<div class="x">x</div>')
    .css({
      color: 'red',
      fontSize: sizeInEm + 'em',
      fontWeight: 'bold',
      left: left,
      position: 'absolute',
      top: top
    })
}

/**
 * Draws a red "X" on the map at the provided coordinate
 */
var addX = function($xContainer, zoneData, x, y, xSize) {
  var left = (zoneData.zeroX || 0) + x * -1 * (zoneData.zoomX || 0.1);
  var top = (zoneData.zeroY || 0) + y * -1 * (zoneData.zoomY || 0.1);
  $xContainer.append(buildX(left, top, xSize));
}

var addXs = function($xContainer, zoneData, locs, xSize) {
  $.each(locs, function(i, loc) {
    addX($xContainer, zoneData, loc.x, loc.y, xSize);
  });
}


var parseLoc = function(locText) {
  if (typeof locText !== 'string') return locText;

  var match = locText.match(/\(? *([\+\-]?\d+\.?\d*), *([\+\-]?\d+\.?\d*)\)?/);
  return {x: parseFloat(match[2]), y: parseFloat(match[1]) };
}

var isLoc = function(locBit) {
    // If we can't split the string by its comma and find a number on either side, it's not a loc
    try {
      return locBit.split(',')[0].match(/\d+/) && locBit.split(',')[1].match(/\d+/);
    } catch (err) {
      return false;
    }
  }

  /**
   * Helper function to power parseLocs/extractNonLocText, since they both use
   * the same logic.
   *
   * SIDE NOTE: If only the wiki didn't have to use 1999 JS, and could
   *            destructure return values with ES2015, the two related functions
   *            wouldn't even need to exist :(
   */
  var parseLocString = function(locString) {
    var nonLocParts = '';
    var bits = locString.split(/([\+\-]?\d+\.?\d*\D*,\D*[\+\-]?\d+\.?\d*)/g);
    var relevantBits = bits.filter(function(part) {
      // Filter out the non-loc parts, but save them
      if (isLoc(part)) return true;
      nonLocParts += part; // save as it might be something like "1st floor"
    });
    var locs = relevantBits.map(parseLoc);
    return [locs, nonLocParts];
  };

  /**
   * Extracts all of the locs (objects with x and y properties) from a provided
   * string such as:
   *   "500, 200"
   *   "(200, 300), (300, 200)"
   * and returns an array containing any locs found.
   */
   var parseLocs = function(locString) {
    return parseLocString[0];
  };
  
  /**
   * Extracts the non-loc parts (eg. "Level 1") from a provided string of text
   * (presumably from an NPC's location <td> or somewhere similar). Although not
   * actually a part of the loc, this text may still be useful in determining
   * which map to show for the loc.
   */
  var extractNonLocText = function(locString) {
    return parseLocString[1];
  };

  var buildMap = function(mapSize, zoneData) {
    var $map;
    switch(mapSize){
      case 'full': return build$FullMap(zoneData);
      case 'small': return build$SmallMap(zoneData);
    } 
  };

  /**
   * Adds a loc map image to the page.
   */
  var showMapWithLocs = function(mapSize, zoneData, locs, $container) {
    removeOpenMap();
    zoneData = addImageUrl(zoneData);
    var $map = buildMap(mapSize, zoneData);

    var $xContainer = $map.find('.x-container');
    $map.find('img').load(function() {
      addXs($xContainer, zoneData, locs);
    });

    if (mapSize === 'small') $map.css({ marginTop: 40 });
    if ($container) $container.prepend($map);
    else $('body').append($map);

    window.$openMap = $map;
    return $map;
  };
  
  // Handle "loc links" (generated from {{loc}} templates)
  var handleLocLinks = function() {
    $('.loc-link').click(function() {
      var data = $(this).data();
      var locs = [parseLoc(data.loc)];
      var zoneData = getZoneData(data.zone, locs);
      if (zoneData) {
        showMapWithLocs('full', zoneData, locs);
       } else {
        // If not, stop here
        alert('We\'re sorry, but ' + data.zone + ' has not been loc mapped ' +
              'yet ... please see Category:Loc_Mapped for more information'); 
      }
      return false
    })
    .on('mouseenter', function(e) {
      var data = $(this).data();
      var zoneData = getZoneData(data.zone, [parseLoc(data.loc)]);
      if (!zoneData) return;

      var locs = [parseLoc(data.loc)];
      showMapWithLocs('small', zoneData, locs, $(e.target));
      $(this).on('mouseleave', removeOpenMap);
    })
  };

  var getZoneName = function() {
    return $('b:contains("Zone:")').parent().text().split('Zone:')[1].trim();
  };

  /**
   * Determines whether the page has a "Location" <td> (as all NPC pages do)
   * with parsable locs inside it (as only some do).  Also checks that
   * "loc-mapped" zone data exists for the NPC's zone.
   */
  var hasLocBoxWithLocs = function() {
    var $locTd = $('b:contains("Location:")').parent();
    if (!$locTd.length) return false; // page isn't an NPC page (no loc box)
    
    var locs = parseLocs($locTd.text());
    if (!locs.length) return false; // no locs existed (or could be parsed)

    return !!getZoneData(zoneName, locs, nonLocParts); // does zone data exist?
  };

  var handleLocBoxes = function() {
    if (!hasLocBoxWithLocs()) return;
    // Get the mob's loc(s)
    var $locTd = $('b:contains("Location:")').parent();
    var locs = parseLocs($locTd.text());
    
    var nonLocParts = parsedLocs[1];
    
    var zoneName = getZoneName();
    // Do we have data for that zone's map?
    var zoneData = getZoneData(zoneName, locs, nonLocParts);
    if (!zoneData) return;  // If not, stop here

    // Add the mouse-enter link
    var $link = $(' <a href="#">(Map)</a>')
      // When it's moused-over, show the map nearby
      .on('mouseenter', function(e) {
        // If there is already a map "open" (because of a click), do nothing
        if (window.$openMap && window.$openMap.parent().length) return false;

        var $map = showMapWithLocs('small', zoneData, locs, $locTd);
        $map.parent().one('mouseleave', removeOpenMap);
      })
      // When it's clicked, show the map full-screen/lightbox style
      .on('click', function(e) {
        showMapWithLocs('full', zoneData, locs);
      });

    // $locTd.find('b').html($('<span>Location </span>').append($link).append('<span>:</span>'));
    $locTd
      .find('b')
      .html($('<span>Location </span>')
      .append($link)
      .append('<span>:</span>'));
  };


  // Setup event listeners (code "starts" here)
  handleLocLinks();
  handleLocBoxes();
    
  // *** HELPER FUNCTIONS ***
  // Define two helper functions for building new zone definitions

  // 1) Use this function to find the correct 0,0 point
  window.testZero = window.testZeroZero = function(zoneData) {
    removeOpenMap(); // test functions don't clean up properly
    var locs = [{ x: 0, y: 0 }];
    showMapWithLocs('full', zoneData, locs);
  };


  // 2) Use this function to generate a grid of alignment of X's
  window.testGrid = function(zoneData) {
    removeOpenMap(); // test functions don't clean up properly
    var $locTd = $('b:contains("Location:")').parent();
    var locs = [];
    for (var x = zoneData.maxX; x >= zoneData.minX; x -= zoneData.interval) {
      for (var y = zoneData.maxY; y >= zoneData.minY; y -= zoneData.interval) {
        locs.push({ x: x, y: y });
      }
    };
    showMapWithLocs('full', zoneData, locs);
  };

})();
} catch (err) {
  console.error(err); // If anything goes wrong, move on but log the error
}