Latest Tweets

Automatically switch back to latest tweets

// ==UserScript==
// @name Latest Tweets
// @description Automatically switch back to latest tweets
// @namespace simulacrumparty, krisu
// @include https://twitter.com/*
// @match https://twitter.com/home
// @grant none
// @license MIT/X11 License <https://opensource.org/licenses/mit-license.php>
// @version 0.2
// ==/UserScript==

// Based of "Latest Tweets" Firefox extension by simulacrumparty:
//  - AMO: https://addons.mozilla.org/en-US/firefox/addon/latest-tweets/
//  - Git: https://git.sr.ht/~simulacrumparty/latest-tweets

// I (krisu) haven't done any actual changes to the code, just copy and pasted "index.js" code from version 0.0.3.

const switchToLatest = async () => {
  const waitForElements = async (els) => {
    return new Promise(async (resolve, reject) => {
      let counter = 0;
      while (true) {
        if (counter === 100) {
          return reject();
        }

        for (let el of els) {
          if (document.querySelector(el)) {
            return resolve(els.map((el) => document.querySelector(el)));
          }
        }

        await new Promise((resolve, _reject) => requestAnimationFrame(resolve));

        counter += 1;
      }
    });
  };

  const topTweetsOffSelector = '[aria-label="Top Tweets off"]';
  const topTweetsOnSelector = '[aria-label="Top Tweets on"]';
  const latestTweetsSelector = 'div[role="menuitem"]';

  waitForElements([topTweetsOnSelector, topTweetsOffSelector])
    .then((els) => {
      const [topTweetsOn, _topTweetsOff] = els;
      if (topTweetsOn) {
        topTweetsOn.click();
        waitForElements([latestTweetsSelector])
          .then((els) => {
            els.filter((el) => !!el).forEach((el) => el.click());
          })
          .catch(() => {});
      }
    })
    .catch(() => {});
};

switchToLatest();