nicolaslegland / scroll

// ==UserScript==
// @author      Nicolas Le Gland
// @copyright   2018, nicolaslegland (https://openuserjs.org/users/nicolaslegland)
// @description Scroll new tweets.
// @exclude     https://twitter.com/i/*
// @grant       none
// @homepageURL https://openuserjs.org/scripts/nicolaslegland/scroll
// @include     https://twitter.com/*
// @license     GPL-3.0
// @name        scroll
// @run-at      document-end
// @supportURL  https://openuserjs.org/scripts/nicolaslegland/scroll/issues
// @updateURL   https://openuserjs.org/src/scripts/nicolaslegland/scroll.user.js
// @version     4
// ==/UserScript==

// Scroll new tweets
function gScroll()
{
    // Suspend observer
    g_oObserver.disconnect();
    window.clearTimeout(g_oTimer);

    // Check for new tweets
    var l_oTimeline = document.getElementById('timeline'),
        l_oList = l_oTimeline.getElementsByClassName('new-tweets-bar');
    if ((1 === l_oList.length) && (0 === document.getElementsByClassName('permalink-container').length))
    {
        // Check visibility
        var l_oItem = l_oList[0],
            l_iTop = l_oItem.offsetTop,
            l_iLeft = l_oItem.offsetLeft,
            l_iWidth = l_oItem.offsetWidth,
            l_iHeight = l_oItem.offsetHeight;
        while (l_oItem.offsetParent instanceof HTMLElement)
        {
            l_oItem = l_oItem.offsetParent;
            l_iTop += l_oItem.offsetTop;
            l_iLeft += l_oItem.offsetLeft;
        }
        if ((l_iTop < (window.pageYOffset + window.innerHeight)) &&
            (l_iLeft < (window.pageXOffset + window.innerWidth)) &&
            (window.pageYOffset < (l_iTop + l_iHeight)) &&
            (window.pageXOffset < (l_iLeft + l_iWidth)))
        {
            // Click the new tweet bar
            l_oList[0].click();
        }
    }
    else
    {
        // Check tweet count
        l_oList = l_oTimeline.getElementsByClassName('stream-item');
        while (50 < l_oList.length)
        {
            // Remove 51st tweet
            l_oList[50].parentNode.removeChild(l_oList[50]);
        }
    }

    // Restart observer
    g_oObserver.observe(document.body,
    {
        childList: true,
        subtree: true,
    });
}

// Obverse additions of nodes
var g_oObserver = new MutationObserver(function ()
{
    // Rearm delayed process
    window.clearTimeout(g_oTimer);
    g_oTimer = window.setTimeout(gScroll, 1000);
}),

// Delay process
g_oTimer = window.setTimeout(gScroll, 1000);