Lemmy expand when post is visible

expand post when visible lemmy

// ==UserScript==
// @name        Lemmy expand when post is visible
// @namespace   https://greasyfork.org/pt-BR/users/821661
// @match       *://*/*
// @grant       GM_registerMenuCommand
// @grant       GM_getValue
// @grant       GM_setValue
// @version     2.1
// @author      hdyzen
// @description expand post when visible lemmy
// ==/UserScript==
(function () {
    'use strict';

    const intersection = GM_getValue('intersection', true);

    // Set intersection on
    function setOn() {
        GM_setValue('intersection', true);
        location.reload();
    }

    // Set intersection off
    function setOff() {
        GM_setValue('intersection', false);
        location.reload();
    }

    // Detect links
    function detectLinks() {
        const thumbnails = document.querySelectorAll('button.thumbnail:not(.ob), a.text-body[aria-label]:not(.ob)');
        for (const thumbnail of thumbnails) {
            if (thumbnail) {
                thumbnail.classList.add('ob');
                switch (intersection) {
                    case true:
                        observer(thumbnail);
                        break;
                    case false:
                        thumbnail.click();
                        break;
                }
            }
        }
    }

    // Intersection observer targets
    function observer(target) {
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        entry.target.click();
                        observer.disconnect();
                    }
                });
            },
            {
                threshold: 1.0,
            }
        );
        observer.observe(target);
    }

    // Menu commands
    function menuCommands() {
        const item = GM_registerMenuCommand('Mode: Expand when visible', setOff, {
            title: 'Click for toggle',
        });
        if (intersection === false) {
            GM_registerMenuCommand('Mode: Expand all', setOn, {
                id: item,
                title: 'Click for toggle',
            });
        }
    }

    let isLemmy = document.querySelector('meta[content="Lemmy"]');

    try {
        if (isLemmy) isLemmy = true;
    } catch (e) {
        console.log(e);
    }

    if (isLemmy) {
        menuCommands();

        setInterval(detectLinks, 500);
    }
})();