tako774 / Twitter Auto Show New Tweets (for twitter 2019 web UI)

// ==UserScript==
// @name	Twitter Auto Show New Tweets (for twitter 2019 web UI)
// @namespace	tako774.net
// @version	0.5
// @description	Auto show refresh tweet if scrolled to top of page and not mouse over
// @match	https://twitter.com/home
// @author nanashi(@tako774)
// @license	MIT
// ==/UserScript==

/*
  when all conditions below OK, this script do auto refresh
    1) mouse is not on tweet area
    2) window position is (almost) top
*/

/*
  Memo
    When clicking "home" button, twitter web UI loads new tweets and
    scrolls to former latest tweet area.
    This script emulate clicking home button and scroll to the top (=latest) tweet.
*/


/* settings */
let loadInterval = 10 * 1000;
let checkNewTweetDelay = 1.5 * 1000; // interval from click home button to check new tweet loaded


/* main process */
let isMouseOnStream = false;
log('start');
window.setTimeout(timer, loadInterval);


/* functions */
function log(message)
{
  // console.log("[Twitter Auto Show New Tweets] " + message);
}

function check()
{
  let body = document.querySelector("body");
  if (!body.onmouseenter || !body.onmouseleave)
  {
    body.onmouseenter = function()
    {
      isMouseOnStream = true;
    }
    body.onmouseleave = function()
    {
      isMouseOnStream = false;
    }
  }

  /* URL path check; some actions navigates not /home URL */
  let path = location.pathname

  log("path: " + path);
  log("isMouseOnStream: " + isMouseOnStream);
  log("window.pageYOffset: " + window.pageYOffset);
  if (path == "/home" && !isMouseOnStream && window.pageYOffset <= 140)
	{
		showNewTweet();
	}

}

function showNewTweet()
{
  log("Load New Tweet");
  let home = document.querySelector("a.r-1habvwh:nth-child(1)");
  if (home){
	home.click();
    window.setTimeout(
      function() {
        log("Check New Tweet and Path");
        let newTweetSign = document.querySelector(".r-sdzlij.r-1yadl64.r-u8s1d.r-1gg5ah6.r-1ld3bg");
        let path = location.pathname
        log("path: " + path);
        if (path == "/home" && newTweetSign)
        {
          log("Show New Tweet")
          let firstTweet = document.querySelector("section.css-1dbjc4n > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)");
          firstTweet.scrollIntoView({
            behavior: 'smooth',
            block: 'end'
          });
        }
      },
      checkNewTweetDelay
    );
  }
  else
  {
    log("Can't get home button");
  }
}

function timer()
{
	check();
	window.setTimeout(timer, loadInterval);
}