Twitter Endless Scroll [X]

Endless scrolling between image posts with mousewheel

// ==UserScript==
// @name         Twitter Endless Scroll [X]
// @namespace    Twitter
// @version      1.5
// @description  Endless scrolling between image posts with mousewheel
// @author       NightLancerX
// @match        https://x.com/*
// @match        https://twitter.com/*
// @match        https://mobile.twitter.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=twitter.com
// @license      CC-BY-NC-SA
// @grant        none
// @require      https://code.jquery.com/jquery-3.3.1.min.js
// @run-at       document-end
// @noframes
// ==/UserScript==

(function() {
	'use strict';

	let nextPost, shifted = false;

	function changePost(shift){
		let selector = 'img[src*="https://pbs.twimg.com/media/"]';
		let posts = [...document.querySelectorAll('[data-testid="cellInnerDiv"] img[src*="https://pbs.twimg.com/media/"]')];
		//console.log(posts);
		let index = posts.indexOf(document.querySelector(`[href='${location.pathname}']`)?.querySelector('img[src*="https://pbs.twimg.com/media/"]'));
		//console.log(index);

		nextPost = posts[index+shift];
		//console.log(nextPost);

		nextPost?.scrollIntoView();
		nextPost?.click();
		shifted = true;
	}

	$('body').on('wheel', '[aria-labelledby="modal-header"]', function(e){
		e.preventDefault();
		e.stopPropagation();

		let left;
		if (e.originalEvent.deltaY < 0){
			if (left = document.querySelector('[data-testid="Carousel-NavLeft"]'))
				left.click();
			else
				changePost(-1);
		}

		let right;
		if (e.originalEvent.deltaY > 0){
			if (right = document.querySelector('[data-testid="Carousel-NavRight"]'))
				right.click();
			else
				changePost(+1);
		}
	});

	$('body').on('click', '[aria-labelledby="modal-header"] [data-testid="swipe-to-dismiss"]', function(e){
		if (shifted) setTimeout(()=>{
			let offset = nextPost?.closest('[data-testid="cellInnerDiv"]').style.transform.match(/\d+/)?.[0];
			window.scroll(0, offset);
			shifted = false;
		}, 500);
	})
})();