☰

Imagic

Toggle clutter in feeds and blogs, stats, move actions to the left, and media downloads independently.

Terá de instalar uma extensão como Tampermonkey, Greasemonkey ou Violentmonkey para instalar este script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

Terá de instalar uma extensão como Tampermonkey ou Violentmonkey para instalar este script.

Terá de instalar uma extensão como Tampermonkey ou Userscripts para instalar este script.

Terá de instalar uma extensão como Tampermonkey para instalar este script.

Terá de instalar uma extensão de gestão de scripts de utilizador para instalar este script.

(Já tenho um gestor de scripts de utilizador, deixe-me instalá-lo!)

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

(Já tenho um gestor de estilos de utilizador, deixe-me instalá-lo!)

// ==UserScript==
// @name         Imagic
// @namespace    imagic
// @version      1.1.1
// @description  Toggle clutter in feeds and blogs, stats, move actions to the left, and media downloads independently.
// @match        *://*imaglr.com/*
// @run-at       document-start
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// @grant        GM_xmlhttpRequest
// @connect      *
// @license      MIT
// @icon         https://imaglr.com/favicon.ico
// ==/UserScript==

/* jshint esversion: 11 */

(() => {
    'use strict';

    // SETTINGS

    const STORAGE_PREFIX = 'streamCleaner.';

    const FEATURES = {
        hideClutter: {
            label: 'Hide clutter/layout elements',
            defaultValue: true,
        },

        hideComments: {
            label: 'Hide post comments',
            defaultValue: true,
        },

        hideStats: {
            label: 'Hide post stats',
            defaultValue: true,
        },

        swapActions: {
            label: 'Swap left/right action groups',
            defaultValue: true,
        },

        downloadButtons: {
            label: 'Add media download buttons',
            defaultValue: true,
        },
    };

    const CLUTTER_STYLE_ID = 'stream-cleaner-style-clutter';
    const COMMENTS_STYLE_ID = 'stream-cleaner-style-comments';
    const STATS_STYLE_ID = 'stream-cleaner-style-stats';

    const SWAPPED_ATTR = 'data-stream-cleaner-actions-swapped';
    const BUTTON_CLASS = 'stream-cleaner-image-download-button';

    const COMMENTS_SELECTOR = '.comment-input-wrapper';
    const COMMENTS_ACTION = '.comment-actions';

    const COMMENT_ELEMENTS_SELECTOR =
        `${COMMENTS_SELECTOR}, ${COMMENTS_ACTION}`;

    const CLUTTER_SELECTOR = String.raw`
        .mobile-cards-scroll,
        .data-v-b965c166,
        .lg\:max-w-\[610px\].max-w-full .x-au .px-4,
        .md\:px-4,
        .lg\:hidden.w-full,
        .mt-6,
        .pt-4,
        .border-t,
        .border-gray-200,
        .dark\:border-gray-700,
        .suggestions,
        .lg,
        .my-4,
        .adsbygoogle,
        .scrollbar-hide,
        .stream-post-reblog-sub,
        .stream-post-time
    `;

    let dynamicContentObserver = null;
    let commentsObserver = null;
    let menuCommandIds = [];

    /*
     * Saves the original inline display value of each comment
     * section so it can be restored if the feature is disabled.
     */
    const originalCommentDisplay = new WeakMap();

    // SETTINGS STORAGE

    function storageKey(featureName) {
        return `${STORAGE_PREFIX}${featureName}`;
    }

    function isEnabled(featureName) {
        const feature = FEATURES[featureName];

        return Boolean(
            GM_getValue(
                storageKey(featureName),
                feature.defaultValue
            )
        );
    }

    function setEnabled(featureName, enabled) {
        GM_setValue(
            storageKey(featureName),
            Boolean(enabled)
        );
    }

    // STYLE HELPERS

    function installStyle(id, cssText) {
        if (document.getElementById(id)) {
            return;
        }

        const style = document.createElement('style');

        style.id = id;
        style.textContent = cssText;

        (
            document.head ||
            document.documentElement
        ).appendChild(style);
    }

    function removeStyle(id) {
        document.getElementById(id)?.remove();
    }

    // FEATURE 1: HIDE CLUTTER

    function applyHideClutter(enabled) {
        if (enabled) {
            installStyle(
                CLUTTER_STYLE_ID,
                `
                    ${CLUTTER_SELECTOR} {
                        display: none !important;
                    }
                `
            );
        } else {
            removeStyle(CLUTTER_STYLE_ID);
        }
    }

    // FEATURE 2: HIDE POST COMMENTS

    function forceHideCommentElement(element) {
        if (
            !(element instanceof Element) ||
            !element.matches(COMMENT_ELEMENTS_SELECTOR)
        ) {
            return;
        }

        if (!originalCommentDisplay.has(element)) {
            originalCommentDisplay.set(element, {
                value: element.style.getPropertyValue('display'),
                priority: element.style.getPropertyPriority('display'),
            });
        }

        const currentValue =
            element.style.getPropertyValue('display');

        const currentPriority =
            element.style.getPropertyPriority('display');

        if (
            currentValue !== 'none' ||
            currentPriority !== 'important'
        ) {
            element.style.setProperty(
                'display',
                'none',
                'important'
            );
        }
    }

    function hideComments(root = document) {
        /*
         * The root may itself be a matching element.
         * Documents do not implement Element.matches().
         */
        if (
            root instanceof Element &&
            root.matches(COMMENT_ELEMENTS_SELECTOR)
        ) {
            forceHideCommentElement(root);
        }

        /*
         * Query both selectors and iterate over every match.
         * This also handles nested elements in newly added posts.
         */
        root
            .querySelectorAll?.(COMMENT_ELEMENTS_SELECTOR)
            ?.forEach(forceHideCommentElement);
    }

    function restoreCommentElement(element) {
        const original = originalCommentDisplay.get(element);

        /*
         * Only restore elements modified by this script.
         * Avoid removing display:none set by the website.
         */
        if (!original) {
            return;
        }

        if (original.value) {
            element.style.setProperty(
                'display',
                original.value,
                original.priority
            );
        } else {
            element.style.removeProperty('display');
        }

        originalCommentDisplay.delete(element);
    }

    function showComments() {
        document
            .querySelectorAll(COMMENT_ELEMENTS_SELECTOR)
            .forEach(restoreCommentElement);
    }

    function startCommentsObserver() {
        if (
            commentsObserver ||
            !document.documentElement
        ) {
            return;
        }

        commentsObserver = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                /*
                 * Handle newly inserted comments and comment
                 * containers containing nested comment sections.
                 */
                if (mutation.type === 'childList') {
                    for (const node of mutation.addedNodes) {
                        if (node instanceof Element) {
                            hideComments(node);
                        }
                    }
                }

                /*
                 * Handle elements receiving comment classes,
                 * losing comment classes, or having their
                 * inline display styles changed by the website.
                 */
                if (
                    mutation.type === 'attributes' &&
                    mutation.target instanceof Element
                ) {
                    const element = mutation.target;

                    /*
                     * If an element no longer matches either
                     * selector, restore its original display.
                     */
                    if (
                        !element.matches(COMMENT_ELEMENTS_SELECTOR) &&
                        originalCommentDisplay.has(element)
                    ) {
                        restoreCommentElement(element);
                    }

                    /*
                     * Reapply hiding if the site modifies an
                     * element's display style or classes.
                     */
                    hideComments(element);
                }
            }
        });

        commentsObserver.observe(
            document.documentElement,
            {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: [
                    'class',
                    'style',
                ],
            }
        );

        hideComments();
    }

    function stopCommentsObserver() {
        commentsObserver?.disconnect();
        commentsObserver = null;
    }

    function applyHideComments(enabled) {
        if (enabled) {
            installStyle(
                COMMENTS_STYLE_ID,
                `
                    ${COMMENT_ELEMENTS_SELECTOR} {
                        display: none !important;
                        visibility: hidden !important;
                    }
                `
            );

            hideComments();
            startCommentsObserver();
        } else {
            stopCommentsObserver();
            removeStyle(COMMENTS_STYLE_ID);
            showComments();
        }
    }

    //
    // FEATURE 3: HIDE POST STATS
    //

    function applyHideStats(enabled) {
        if (enabled) {
            installStyle(
                STATS_STYLE_ID,
                `
                    .stream-post-stats {
                        display: none !important;
                    }
                `
            );
        } else {
            removeStyle(STATS_STYLE_ID);
        }
    }

    //
    // FEATURE 4: SWAP ACTION GROUPS
    //

    function findActionContainers(root = document) {
        const containers = new Set();

        if (root instanceof Element) {
            const left = root.querySelector(
                ':scope > .stream-post-actions-left'
            );

            const right = root.querySelector(
                ':scope > .stream-post-actions-right'
            );

            if (left && right) {
                containers.add(root);
            }
        }

        root
            .querySelectorAll?.('.stream-post-actions-left')
            .forEach(left => {
                const parent = left.parentElement;

                if (!parent) {
                    return;
                }

                const right = parent.querySelector(
                    ':scope > .stream-post-actions-right'
                );

                if (right) {
                    containers.add(parent);
                }
            });

        return containers;
    }

    function applySwapActions(enabled, root = document) {
        for (const container of findActionContainers(root)) {
            const left = container.querySelector(
                ':scope > .stream-post-actions-left'
            );

            const right = container.querySelector(
                ':scope > .stream-post-actions-right'
            );

            if (!left || !right) {
                continue;
            }

            if (enabled) {
                if (!container.hasAttribute(SWAPPED_ATTR)) {
                    container.insertBefore(right, left);
                    container.setAttribute(SWAPPED_ATTR, '');
                }
            } else if (container.hasAttribute(SWAPPED_ATTR)) {
                container.insertBefore(left, right);
                container.removeAttribute(SWAPPED_ATTR);
            }
        }
    }

    //
    // FEATURE 5: MEDIA DOWNLOADS
    //

    function filenameFromUrl(url) {
        try {
            const parsed = new URL(url, location.href);

            let filename = decodeURIComponent(
                parsed.pathname.split('/').pop() || ''
            );

            filename = filename
                .replace(/[\\/:*?"<>|]/g, '_')
                .trim();

            if (filename) {
                return filename;
            }
        } catch (error) {
            console.warn(
                '[Stream Cleaner] Filename error:',
                error
            );
        }

        return `media-${Date.now()}`;
    }

    function downloadSingle(url, filename) {
        GM_xmlhttpRequest({
            method: 'GET',
            url,
            responseType: 'blob',
            timeout: 60000,

            onload(response) {
                if (
                    response.status < 200 ||
                    response.status >= 300
                ) {
                    console.error(
                        '[Stream Cleaner] Download failed:',
                        response.status,
                        response.statusText
                    );

                    alert(
                        `Media download failed (${response.status}).`
                    );

                    return;
                }

                const blob = response.response;

                if (!(blob instanceof Blob)) {
                    console.error(
                        '[Stream Cleaner] Response was not a Blob:',
                        response
                    );

                    alert(
                        'Media download failed: invalid response.'
                    );

                    return;
                }

                const blobUrl = URL.createObjectURL(blob);
                const link = document.createElement('a');

                link.href = blobUrl;
                link.download = filename;
                link.style.display = 'none';

                document.body.appendChild(link);

                link.click();
                link.remove();

                setTimeout(() => {
                    URL.revokeObjectURL(blobUrl);
                }, 5000);
            },

            onerror(error) {
                console.error(
                    '[Stream Cleaner] Download request failed:',
                    error
                );

                alert('Media download failed.');
            },

            ontimeout() {
                console.error(
                    '[Stream Cleaner] Download timed out.'
                );

                alert('Media download timed out.');
            },
        });
    }

    //
    // DOWNLOAD BUTTON
    //

    function createDownloadButton(mediaUrl) {
        const button = document.createElement('button');

        button.type = 'button';
        button.className = `stream-action ${BUTTON_CLASS}`;
        button.title = 'Download media';

        button.setAttribute(
            'aria-label',
            'Download media'
        );

        button.style.display = 'inline-flex';
        button.style.alignItems = 'center';
        button.style.justifyContent = 'center';
        button.style.width = '44px';
        button.style.height = '44px';
        button.style.color = 'currentColor';
        button.style.flex = '0 0 auto';

        button.innerHTML = `
            <svg
                viewBox="0 0 512 512"
                width="22"
                height="22"
                fill="currentColor"
                aria-hidden="true"
                style="display:block"
            >
                <path d="M256 352c-6.1 0-12.3-2.3-17-7l-96-96c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l55.1 55.1V24c0-13.3 10.7-24 24-24s24 10.7 24 24v246.1l55-55c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-96 96c-4.6 4.7-10.8 7-16.9 7zM96 464h320c17.7 0 32-14.3 32-32v-48c0-13.3-10.7-24-24-24s-24 10.7-24 24v32H112v-32c0-13.3-10.7-24-24-24s-24 10.7-24 24v48c0 17.7 14.3 32 32 32z"></path>
            </svg>
        `;

        button.addEventListener('click', event => {
            event.preventDefault();
            event.stopPropagation();

            if (!mediaUrl) {
                alert('No media URL found.');
                return;
            }

            downloadSingle(
                mediaUrl,
                filenameFromUrl(mediaUrl)
            );
        });

        return button;
    }

    //
    // FIND POSTS AND ADD DOWNLOAD BUTTONS
    //

    function addDownloadButtons(root = document) {
        const posts = new Set();

        if (
            root instanceof Element &&
            root.matches('.stream-post')
        ) {
            posts.add(root);
        }

        root
            .querySelectorAll?.('.stream-post')
            .forEach(post => posts.add(post));

        for (const post of posts) {
            const video = post.querySelector('video');

            const videoSource =
                video?.currentSrc ||
                video?.src ||
                video?.querySelector('source[src]')?.src;

            const image = post.querySelector('img');

            const imageSource =
                image?.currentSrc ||
                image?.src;

            /*
             * Prefer the video URL over its poster or thumbnail.
             */
            const mediaUrl =
                videoSource ||
                imageSource;

            if (!mediaUrl) {
                continue;
            }

            const actions =
                post.querySelector(
                    '.stream-post-actions-right'
                ) ||
                post.querySelector(
                    '.stream-post-actions-left'
                ) ||
                post.querySelector(
                    '.stream-post-actions'
                );

            if (!actions) {
                continue;
            }

            if (
                actions.querySelector(
                    `.${BUTTON_CLASS}`
                )
            ) {
                continue;
            }

            const button =
                createDownloadButton(mediaUrl);

            actions.appendChild(button);
        }
    }

    function removeDownloadButtons() {
        document
            .querySelectorAll(`.${BUTTON_CLASS}`)
            .forEach(button => {
                button.remove();
            });
    }

    function applyDownloadButtons(
        enabled,
        root = document
    ) {
        if (enabled) {
            addDownloadButtons(root);
        } else {
            removeDownloadButtons();
        }
    }

    //
    // DYNAMIC / INFINITE-SCROLL CONTENT
    //

    function dynamicContentObserverNeeded() {
        return (
            isEnabled('swapActions') ||
            isEnabled('downloadButtons')
        );
    }

    function handleAddedContent(root) {
        if (isEnabled('swapActions')) {
            applySwapActions(true, root);
        }

        if (isEnabled('downloadButtons')) {
            applyDownloadButtons(true, root);
        }

        if (isEnabled('hideComments')) {
            hideComments(root);
        }
    }

    function updateDynamicContentObserver() {
        if (!document.body) {
            return;
        }

        if (!dynamicContentObserverNeeded()) {
            dynamicContentObserver?.disconnect();
            dynamicContentObserver = null;
            return;
        }

        if (dynamicContentObserver) {
            return;
        }

        dynamicContentObserver =
            new MutationObserver(mutations => {
                for (const mutation of mutations) {
                    for (const node of mutation.addedNodes) {
                        if (node instanceof Element) {
                            handleAddedContent(node);
                        }
                    }
                }
            });

        dynamicContentObserver.observe(
            document.body,
            {
                childList: true,
                subtree: true,
            }
        );
    }

    //
    // APPLY INDIVIDUAL FEATURE
    //

    function applyFeature(featureName, enabled) {
        switch (featureName) {
            case 'hideClutter':
                applyHideClutter(enabled);
                break;

            case 'hideComments':
                applyHideComments(enabled);
                break;

            case 'hideStats':
                applyHideStats(enabled);
                break;

            case 'swapActions':
                applySwapActions(enabled);
                updateDynamicContentObserver();
                break;

            case 'downloadButtons':
                applyDownloadButtons(enabled);
                updateDynamicContentObserver();
                break;

            default:
                console.warn(
                    '[Stream Cleaner] Unknown feature:',
                    featureName
                );
        }
    }

    //
    // TAMPERMONKEY MENU
    //

    function unregisterMenus() {
        for (const id of menuCommandIds) {
            try {
                GM_unregisterMenuCommand(id);
            } catch {
                /*
                 * Ignore unsupported or already-unregistered
                 * menu commands.
                 */
            }
        }

        menuCommandIds = [];
    }

    function toggleFeature(featureName) {
        const enabled = !isEnabled(featureName);

        setEnabled(featureName, enabled);
        applyFeature(featureName, enabled);

        registerMenus();
    }

    function registerMenus() {
        unregisterMenus();

        for (
            const [featureName, feature]
            of Object.entries(FEATURES)
        ) {
            const enabled = isEnabled(featureName);
            const state = enabled ? 'ON' : 'OFF';

            const id = GM_registerMenuCommand(
                `${feature.label} — ${state}`,
                () => {
                    toggleFeature(featureName);
                }
            );

            menuCommandIds.push(id);
        }

        const resetId = GM_registerMenuCommand(
            '↺ Reset all features to defaults',
            () => {
                for (
                    const [featureName, feature]
                    of Object.entries(FEATURES)
                ) {
                    setEnabled(
                        featureName,
                        feature.defaultValue
                    );

                    applyFeature(
                        featureName,
                        feature.defaultValue
                    );
                }

                updateDynamicContentObserver();
                registerMenus();
            }
        );

        menuCommandIds.push(resetId);
    }

    //
    // STARTUP
    //

    function applyInitialStyles() {
        applyHideClutter(
            isEnabled('hideClutter')
        );

        applyHideComments(
            isEnabled('hideComments')
        );

        applyHideStats(
            isEnabled('hideStats')
        );
    }

    function startDomFeatures() {
        applySwapActions(
            isEnabled('swapActions')
        );

        applyDownloadButtons(
            isEnabled('downloadButtons')
        );

        if (isEnabled('hideComments')) {
            hideComments();
            startCommentsObserver();
        }

        updateDynamicContentObserver();
    }

    registerMenus();
    applyInitialStyles();

    if (document.body) {
        startDomFeatures();
    } else {
        document.addEventListener(
            'DOMContentLoaded',
            startDomFeatures,
            {
                once: true,
            }
        );
    }
})();