Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Player activity tracker: refactoring #768

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions core/code/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,42 @@ const formatDistance = (distance) => {
return `${IITC.utils.formatNumber(value)}${unit}`;
};

/**
* Formats the time difference between two timestamps (in milliseconds) as a string.
*
* @memberof IITC.utils
* @function formatAgo
* @param {number} time - The past timestamp in milliseconds.
* @param {number} now - The current timestamp in milliseconds.
* @param {Object} [options] - Options for formatting.
* @param {boolean} [options.showSeconds=false] - Whether to include seconds in the result.
* @returns {string} The formatted time difference (e.g., "45s", "5m", "2h 45m", "1d 3h 45m")
*/
const formatAgo = (time, now, options = { showSeconds: false }) => {
const secondsTotal = Math.floor(Math.max(0, (now - time) / 1000));

// Calculate time units
const days = Math.floor(secondsTotal / 86400);
const hours = Math.floor((secondsTotal % 86400) / 3600);
const minutes = Math.floor((secondsTotal % 3600) / 60);
const seconds = secondsTotal % 60;

const result = [];

// Include units conditionally based on non-zero values
if (days > 0) result.push(`${days}d`);
if (hours > 0 || result.length !== 0) result.push(`${hours}h`);
if (minutes > 0 || result.length !== 0) result.push(`${minutes}m`);
if (options.showSeconds && (result.length === 0 || seconds > 0)) result.push(`${seconds}s`);

// If no units were added, show "0" with the smallest available unit
if (result.length === 0) {
return options.showSeconds ? '0s' : '0m';
}

return result.join(' ');
};

/**
* Checks if the device is a touch-enabled device.
* Alias for `L.Browser.touch()`
Expand Down Expand Up @@ -448,6 +484,7 @@ IITC.utils = {
unixTimeToHHmm,
formatInterval,
formatDistance,
formatAgo,
isTouchDevice,
scrollBottom,
escapeJS,
Expand Down
27 changes: 12 additions & 15 deletions plugins/machina-tracker.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
// @name Machina tracker
// @author McBen
// @category Layer
// @version 1.0.1
// @version 1.1.0
// @description Show locations of Machina activities

/* exported setup, changelog --eslint */
/* global L */
/* global IITC, L */

var changelog = [
{
version: '1.1.0',
changes: ['Using `IITC.utils.formatAgo` instead of the plugin own function'],
},
{
version: '1.0.1',
changes: ['Version upgrade due to a change in the wrapper: plugin icons are now vectorized'],
Expand Down Expand Up @@ -146,17 +150,6 @@ machinaTracker.processNewData = function (data) {
});
};

machinaTracker.ago = function (time, now) {
var s = (now - time) / 1000;
var h = Math.floor(s / 3600);
var m = Math.floor((s % 3600) / 60);
var returnVal = m + 'm';
if (h > 0) {
returnVal = h + 'h' + returnVal;
}
return returnVal + ' ago';
};

machinaTracker.createPortalLink = function (portal) {
return $('<a>')
.addClass('text-overflow-ellipsis')
Expand Down Expand Up @@ -188,7 +181,7 @@ machinaTracker.drawData = function () {
var ageBucket = Math.min((now - event.time) / split, 3);
var position = event.from.latLng;

var title = isTouchDev ? '' : machinaTracker.ago(event.time, now);
var title = isTouchDev ? '' : IITC.utils.formatAgo(event.time, now) + ' ago';
var icon = machinaTracker.icon;
var opacity = 1 - 0.2 * ageBucket;

Expand All @@ -199,7 +192,11 @@ machinaTracker.drawData = function () {
linkList.appendTo(popup);

event.to.forEach((to) => {
$('<li>').append(machinaTracker.createPortalLink(to)).append(' ').append(machinaTracker.ago(to.time, now)).appendTo(linkList);
$('<li>')
.append(machinaTracker.createPortalLink(to))
.append(' ')
.append(IITC.utils.formatAgo(to.time, now) + ' ago')
.appendTo(linkList);
});

var m = L.marker(position, { icon: icon, opacity: opacity, desc: popup[0], title: title });
Expand Down
83 changes: 35 additions & 48 deletions plugins/player-activity-tracker.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
// @author breunigs
// @name Player activity tracker
// @category Layer
// @version 0.13.2
// @version 0.14.0
// @description Draw trails for the path a user took onto the map based on status messages in COMMs. Uses up to three hours of data. Does not request chat data on its own, even if that would be useful.

/* exported setup, changelog --eslint */
/* global L -- eslint */
/* global IITC, L -- eslint */

var changelog = [
{
version: '0.14.0',
changes: ['Using `IITC.utils.formatAgo` instead of the plugin own function', 'Refactoring to make it easier to extend plugin functions'],
},
{
version: '0.13.2',
changes: ['Refactoring: fix eslint'],
Expand All @@ -34,6 +38,7 @@ window.PLAYER_TRACKER_MAX_TIME = 3 * 60 * 60 * 1000; // in milliseconds
window.PLAYER_TRACKER_MIN_ZOOM = 9;
window.PLAYER_TRACKER_MIN_OPACITY = 0.3;
window.PLAYER_TRACKER_LINE_COLOUR = '#FF00FD';
window.PLAYER_TRACKER_MAX_DISPLAY_EVENTS = 10; // Maximum number of events in a popup

// use own namespace for plugin
window.plugin.playerTracker = function () {};
Expand Down Expand Up @@ -274,24 +279,12 @@ window.plugin.playerTracker.getLatLngFromEvent = function (ev) {
return L.latLng(lats / ev.latlngs.length, lngs / ev.latlngs.length);
};

window.plugin.playerTracker.ago = function (time, now) {
var s = (now - time) / 1000;
var h = Math.floor(s / 3600);
var m = Math.floor((s % 3600) / 60);
var returnVal = m + 'm';
if (h > 0) {
returnVal = h + 'h' + returnVal;
}
return returnVal;
};

window.plugin.playerTracker.drawData = function () {
var isTouchDev = window.isTouchDevice();

var gllfe = window.plugin.playerTracker.getLatLngFromEvent;

var polyLineByAgeEnl = [[], [], [], []];
var polyLineByAgeRes = [[], [], [], []];
var polyLineByPlayerAndAge = {};

var split = window.PLAYER_TRACKER_MAX_TIME / 4;
var now = Date.now();
Expand All @@ -308,13 +301,15 @@ window.plugin.playerTracker.drawData = function () {
var ageBucket = Math.min(Math.trunc((now - p.time) / split), 4 - 1);
var line = [gllfe(p), gllfe(playerData.events[i - 1])];

if (playerData.team === 'RESISTANCE') polyLineByAgeRes[ageBucket].push(line);
else polyLineByAgeEnl[ageBucket].push(line);
if (!polyLineByPlayerAndAge[plrname]) {
polyLineByPlayerAndAge[plrname] = [[], [], [], []];
}
polyLineByPlayerAndAge[plrname][ageBucket].push(line);
}

var evtsLength = playerData.events.length;
var last = playerData.events[evtsLength - 1];
var ago = window.plugin.playerTracker.ago;
const ago = IITC.utils.formatAgo;

// tooltip for marker - no HTML - and not shown on touchscreen devices
var tooltip = isTouchDev ? '' : plrname + ', ' + ago(last.time, now) + ' ago';
Expand Down Expand Up @@ -358,7 +353,7 @@ window.plugin.playerTracker.drawData = function () {
popup.append('<br>').append('<br>').append(document.createTextNode('previous locations:')).append('<br>');

var table = $('<table>').appendTo(popup).css('border-spacing', '0');
for (let i = evtsLength - 2; i >= 0 && i >= evtsLength - 10; i--) {
for (let i = evtsLength - 2; i >= 0 && i >= evtsLength - window.PLAYER_TRACKER_MAX_DISPLAY_EVENTS; i--) {
var ev = playerData.events[i];
$('<tr>')
.append($('<td>').text(ago(ev.time, now) + ' ago'))
Expand All @@ -375,7 +370,8 @@ window.plugin.playerTracker.drawData = function () {
var icon = playerData.team === 'RESISTANCE' ? new window.plugin.playerTracker.iconRes() : new window.plugin.playerTracker.iconEnl();
// as per OverlappingMarkerSpiderfier docs, click events (popups, etc) must be handled via it rather than the standard
// marker click events. so store the popup text in the options, then display it in the oms click handler
var m = L.marker(gllfe(last), { icon: icon, opacity: absOpacity, desc: popup[0], title: tooltip });
const markerPos = gllfe(last);
var m = L.marker(markerPos, { icon: icon, opacity: absOpacity, desc: popup[0], title: tooltip });
m.addEventListener('spiderfiedclick', window.plugin.playerTracker.onClickListener);

// m.bindPopup(title);
Expand All @@ -389,7 +385,7 @@ window.plugin.playerTracker.drawData = function () {

playerData.marker = m;

m.addTo(playerData.team === 'RESISTANCE' ? window.plugin.playerTracker.drawnTracesRes : window.plugin.playerTracker.drawnTracesEnl);
m.addTo(window.plugin.playerTracker.getDrawnTracesByTeam(playerData.team));
window.registerMarkerForOMS(m);

// jQueryUI doesn’t automatically notice the new markers
Expand All @@ -399,36 +395,27 @@ window.plugin.playerTracker.drawData = function () {
});

// draw the poly lines to the map
$.each(polyLineByAgeEnl, function (i, polyLine) {
if (polyLine.length === 0) return true;

var opts = {
weight: 2 - 0.25 * i,
color: window.PLAYER_TRACKER_LINE_COLOUR,
interactive: false,
opacity: 1 - 0.2 * i,
dashArray: '5,8',
};
for (const [playerName, polyLineByAge] of Object.entries(polyLineByPlayerAndAge)) {
polyLineByAge.forEach((polyLine, i) => {
if (polyLine.length === 0) return;

const opts = {
weight: 2 - 0.25 * i,
color: window.PLAYER_TRACKER_LINE_COLOUR,
interactive: false,
opacity: 1 - 0.2 * i,
dashArray: '5,8',
};

$.each(polyLine, function (ind, poly) {
L.polyline(poly, opts).addTo(window.plugin.playerTracker.drawnTracesEnl);
polyLine.forEach((poly) => {
L.polyline(poly, opts).addTo(window.plugin.playerTracker.getDrawnTracesByTeam(window.plugin.playerTracker.stored[playerName].team));
});
});
});
$.each(polyLineByAgeRes, function (i, polyLine) {
if (polyLine.length === 0) return true;

var opts = {
weight: 2 - 0.25 * i,
color: window.PLAYER_TRACKER_LINE_COLOUR,
interactive: false,
opacity: 1 - 0.2 * i,
dashArray: '5,8',
};
}
};

$.each(polyLine, function (ind, poly) {
L.polyline(poly, opts).addTo(window.plugin.playerTracker.drawnTracesRes);
});
});
window.plugin.playerTracker.getDrawnTracesByTeam = function (team) {
return team === 'RESISTANCE' ? window.plugin.playerTracker.drawnTracesRes : window.plugin.playerTracker.drawnTracesEnl;
};

window.plugin.playerTracker.getPortalLink = function (data) {
Expand Down
32 changes: 32 additions & 0 deletions test/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,38 @@ describe('IITC.utils.formatDistance', () => {
});
});

describe('IITC.utils.formatAgo', () => {
const now = Date.now();

describe('Basic functionality', () => {
it('should return "0s" when there is no time difference and seconds are enabled', () => {
expect(IITC.utils.formatAgo(now, now, { showSeconds: true })).to.equal('0s');
});

it('should return "0m" when time difference is negative and seconds are disabled', () => {
const futureTime = now + 1000;
expect(IITC.utils.formatAgo(futureTime, now)).to.equal('0m');
});
});

describe('Complex scenarios', () => {
it('should not show seconds if seconds are disabled', () => {
const time = now - 45 * 1000; // 45 seconds ago
expect(IITC.utils.formatAgo(time, now)).to.equal('0m');
});

it('should return only minutes if time difference is less than an hour', () => {
const time = now - 5 * 60 * 1000; // 5 minutes ago
expect(IITC.utils.formatAgo(time, now)).to.equal('5m');
});

it('should handle all units enabled', () => {
const time = now - (2 * 86400 + 5 * 3600 + 30 * 60 + 15) * 1000; // 2 days, 5 hours, 30 minutes, and 15 seconds ago
expect(IITC.utils.formatAgo(time, now, { showSeconds: true })).to.equal('2d 5h 30m 15s');
});
});
});

describe('IITC.utils.escapeJS', () => {
it('should escape double quotes in the string', () => {
const result = IITC.utils.escapeJS('Hello "World"');
Expand Down
Loading