melon / GameFAQs Show Icon

// ==UserScript==
// @name         GameFAQs Show Icon
// @namespace    https://gamefaqs.gamespot.com/
// @version      0.6
// @description  Shows user icon next to posts on GameFAQs
// @license      MIT
// @author       melon
// @match        https://gamefaqs.gamespot.com/boards/*/*
// @exclude      https://gamefaqs.gamespot.com/boards/*/*/*
// @grant        none
// @updateURL    https://openuserjs.org/meta/melon/GameFAQs_Show_Icon.meta.js
//
// ==/UserScript==
(function() {
  if (document.querySelector('.userIcon') !== null) {
    return; //prevent duplicate loading icons when revisiting page in Firefox
  }
  
  'use strict';
  var iconSize = 64; //max size without upscalling is 100px
  var posts = document.getElementsByClassName("msg");

  //if author is positioned to left or top of post
  var authorLeft = posts[0].querySelector('.msg_infobox').offsetWidth <= 150;

  //author position may change with window resize
  window.addEventListener("resize", positionIcons);

  for (var i = 0; i < posts.length; i++) {
    if (!posts[i].firstChild.classList.contains('deleted')) {
      let username = posts[i].querySelectorAll('.name.menu_toggle')[0].getAttribute("data-username").split(' ').join('_');
      let icon = makeIcon(username);
      positionIcon(icon, posts[i].querySelector('.msg_infobox'));
    }
  }

  //update the position of an icon
  function positionIcon(icon, box) {
    if (authorLeft) {
      icon.style.padding = '5px';
      icon.style.display = 'block';
      icon.style.margin = 'auto';
      box.insertBefore(icon, box.firstChild.nextSibling.nextSibling);
    }
    else {
      icon.style.padding = '0px 5px 0px 0px';
      box.insertBefore(icon, box.firstChild);
      icon.style.display = 'inline-block';
    }
  }

  //reposition all icons if author position changes
  function positionIcons() {
    var prev = authorLeft;
    authorLeft = posts[0].querySelector('.msg_infobox').offsetWidth <= 150;

    if ((!prev && authorLeft) || (prev && !authorLeft)) {
      for (var i = 0; i < posts.length; i++) {
        if (!posts[i].firstChild.classList.contains('deleted')) {
          let box = posts[i].querySelector('.msg_infobox');
          let icon = posts[i].querySelector('.userIcon')
          positionIcon(icon, box);
        }
      }
    }
  }

  function makeIcon(username) {
    var icon = document.createElement('a');
    icon.className = "userIcon";
    icon.style.height = iconSize + 'px';
    icon.style.width = iconSize + 'px';
    icon.href = "/community/" + username;
    var pic = document.createElement('img');
    pic.src = "/a/avatar/" + username + ".jpg?" + Date.now();
    pic.classList.add("imgboxart");
    icon.appendChild(pic);
    return icon;
  }
})();