Ultra Performance Desktop Max

Máxima performance para desktops – remove efeitos caros, otimiza renderização e mantém interatividade total. Exclusão de domínios unificada, preserva LCP e recalcula content-visibility.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

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

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Ultra Performance Desktop Max
// @version      1.2-desktop
// @description  Máxima performance para desktops – remove efeitos caros, otimiza renderização e mantém interatividade total. Exclusão de domínios unificada, preserva LCP e recalcula content-visibility.
// @author       11th Doctor Hooves
// @match        *://*/*
// @run-at       document-start
// @grant        none
// @noframes
// @namespace    https://greasyfork.org/users/1579850
// ==/UserScript==

// =====================================================
//  EXCLUSÃO DE DOMÍNIOS – FONTE ÚNICA DE VERDADE
// =====================================================
const __ULTRA_EXCLUDE_DOMAINS__ = [
    'figma.com', 'canva.com', 'photopea.com', 'excalidraw.com',
    'webglfundamentals.org', 'shadertoy.com', 'maps.google.com',
    'earth.google.com', 'krunker.io', 'agar.io', 'slither.io',
    'poki.com', 'crazygames.com', 'itch.io', 'gamejolt.com',
];

(function() {
    "use strict";
    const host = location.hostname.toLowerCase();
    window.__ultraExcluded = __ULTRA_EXCLUDE_DOMAINS__.some(d => host.includes(d) || host === d);
    if (window.__ultraExcluded) {
        console.debug(' Ultra Performance – domínio excluído, script inativo neste site');
    }
})();


// =====================================================
//  CORE – DISPATCHER ÚNICO DE MUTATION OBSERVER
// =====================================================
(function() {
    "use strict";
    if (window.__ultraExcluded) return;

    const handlers = [];

    function processMutations(mutations) {
        for (const mut of mutations) {
            for (const node of mut.addedNodes) {
                if (node.nodeType !== 1) continue;
                for (const h of handlers) {
                    try {
                        if (node.matches && node.matches(h.selector)) {
                            h.callback(node);
                        }
                        if (node.querySelectorAll) {
                            const descendants = node.querySelectorAll(h.selector);
                            for (const el of descendants) {
                                h.callback(el);
                            }
                        }
                    } catch (e) {
                        // silencia erros de cada handler
                    }
                }
            }
        }
    }

    const rootObserver = new MutationObserver(processMutations);
    rootObserver.observe(document.documentElement, { childList: true, subtree: true });

    window.__nuclear = {
        registerHandler: function(selector, callback) {
            handlers.push({ selector, callback });
        },
        scan: function(selector, callback) {
            const elements = document.querySelectorAll(selector);
            for (const el of elements) {
                try { callback(el); } catch (e) {}
            }
        },
        _handlers: handlers,
    };

    window.__nuclearDispatcherReady = true;
    console.debug(' Core Dispatcher – MutationObserver único ativado (Desktop Max)');
})();


// =====================================================
//  SEÇÃO 1: CSS ENGINE – DESKTOP MAX
// =====================================================
(function() {
    "use strict";
    if (window.__ultraExcluded) return;

    const MODE = {
        level: 'desktop-max',
        removeFilters: true,
        removeShadows: true,
        removeAnimations: true,
        removeBorderRadius: false,
        removeGradients: true,
        flatten3D: true,
        removePerspective: true,
        removePreserve3D: true,
        removeMixBlendMode: true,
        removeClipPath: true,
        removeMask: true,
        removeIsolation: true,
        removeObjectFit: false,
        removeOutline: false,
        removeSmoothScroll: true,
        removeScrollSnap: true,
        removeWillChange: true,
        forceOpacity: false,
        removeBackgroundImages: false,   // mantém imagens de fundo (layout e estética)
        removeSticky: false,             // mantém sticky/fixed para usabilidade desktop
        pauseVideosOutsideViewport: true,
        lazyLoadIframes: true,
        removeSVGFilters: true,          // remoção real acontece na Seção 2 (DOM)
        optimizeCanvas: true,            // apenas alpha:false/desynchronized, sem throttle
        forceFontDisplaySwap: true,      // adiciona font-display: swap em @font-face
    };

    if (!document.contentType?.includes('html')) return;

    const BLOCK_MAP = new Map([
        ['filter', 'none'],
        ['backdrop-filter', 'none'],
        ['-webkit-backdrop-filter', 'none'],
    ]);

    if (MODE.removeShadows) {
        BLOCK_MAP.set('box-shadow', 'none');
        BLOCK_MAP.set('text-shadow', 'none');
    }
    if (MODE.removeAnimations) {
        BLOCK_MAP.set('animation', 'none');
        BLOCK_MAP.set('transition', 'none');
        BLOCK_MAP.set('animation-duration', '0s');
        BLOCK_MAP.set('transition-duration', '0s');
    }
    if (MODE.removeMixBlendMode) BLOCK_MAP.set('mix-blend-mode', 'normal');
    if (MODE.removeClipPath) BLOCK_MAP.set('clip-path', 'none');
    if (MODE.removeMask) BLOCK_MAP.set('mask', 'none');
    if (MODE.removeIsolation) BLOCK_MAP.set('isolation', 'auto');
    if (MODE.removeWillChange) BLOCK_MAP.set('will-change', 'auto');
    if (MODE.removePerspective) BLOCK_MAP.set('perspective', 'none');
    if (MODE.removePreserve3D) BLOCK_MAP.set('transform-style', 'flat');
    if (MODE.removeSmoothScroll) BLOCK_MAP.set('scroll-behavior', 'auto');
    if (MODE.removeScrollSnap) {
        BLOCK_MAP.set('scroll-snap-type', 'none');
        BLOCK_MAP.set('scroll-snap-align', 'none');
    }

    const GRADIENT_FUNCTIONS = /gradient/i;

    function transformCSSDeclaration(prop, value) {
        prop = prop.trim().toLowerCase();
        value = value.trim();

        if (BLOCK_MAP.has(prop)) return `${prop}: ${BLOCK_MAP.get(prop)}`;

        if (MODE.removeGradients) {
            if ((prop === 'background-image' || prop === 'background') && GRADIENT_FUNCTIONS.test(value)) {
                return null;
            }
        }
        if (MODE.flatten3D && prop === 'transform') {
            const cleaned = value.replace(/(?:translate3d|scale3d|rotate3d|matrix3d)\s*\([^)]*\)/gi, 'none');
            if (cleaned !== value) {
                if (cleaned.trim() === 'none') return null;
                return `transform: ${cleaned}`;
            }
        }
        return `${prop}: ${value}`;
    }

    function splitDeclarations(s) {
        const out = [];
        let buf = '';
        let depth = 0;
        let inSingle = false;
        let inDouble = false;
        for (let i = 0; i < s.length; i++) {
            const ch = s[i];
            const prev = s[i - 1];
            if (ch === '"' && prev !== '\\' && !inSingle) inDouble = !inDouble;
            else if (ch === "'" && prev !== '\\' && !inDouble) inSingle = !inSingle;
            else if (!inSingle && !inDouble) {
                if (ch === '(') depth++;
                else if (ch === ')') depth = Math.max(0, depth - 1);
                else if (ch === ';' && depth === 0) {
                    out.push(buf);
                    buf = '';
                    continue;
                }
            }
            buf += ch;
        }
        if (buf.trim()) out.push(buf);
        return out.map(d => d.trim()).filter(Boolean);
    }

    function transformCSSRule(ruleText) {
        if (!ruleText.includes('{')) return ruleText;
        const idx = ruleText.indexOf('{');
        const selector = ruleText.substring(0, idx).trim();
        const isFontFace = selector.startsWith('@font-face');
        if (selector.startsWith('@') && !isFontFace) return ruleText;
        const body = ruleText.substring(idx + 1, ruleText.lastIndexOf('}')).trim();
        if (!body) return ruleText;

        const declarations = splitDeclarations(body);
        const newDeclarations = [];

        for (const decl of declarations) {
            const colonIndex = decl.indexOf(':');
            if (colonIndex === -1) continue;
            const prop = decl.substring(0, colonIndex).trim();
            const value = decl.substring(colonIndex + 1).trim();
            const transformed = transformCSSDeclaration(prop, value);
            if (transformed) newDeclarations.push(transformed);
        }

        if (isFontFace && MODE.forceFontDisplaySwap) {
            const hasFontDisplay = body.includes('font-display');
            if (!hasFontDisplay) {
                newDeclarations.push('font-display: swap');
            }
        }

        return `${selector} { ${newDeclarations.join('; ')} }`;
    }

    const originalInsertRule = CSSStyleSheet.prototype.insertRule;
    CSSStyleSheet.prototype.insertRule = function(rule, index) {
        try {
            return originalInsertRule.call(this, transformCSSRule(rule), index);
        } catch (e) {
            return originalInsertRule.call(this, rule, index);
        }
    };

    const originalSetProperty = CSSStyleDeclaration.prototype.setProperty;
    CSSStyleDeclaration.prototype.setProperty = function(property, value, priority) {
        const transformed = transformCSSDeclaration(property, value);
        if (transformed === null) {
            return this.removeProperty(property);
        }
        const colonIndex = transformed.indexOf(':');
        if (colonIndex === -1) {
            return originalSetProperty.call(this, property, value, priority);
        }
        const prop = transformed.substring(0, colonIndex).trim();
        const val = transformed.substring(colonIndex + 1).trim();
        return originalSetProperty.call(this, prop, val, priority);
    };

    function buildGlobalCSS() {
        let css = '';
        const add = (prop, val) => { css += `${prop}: ${val} !important; `; };

        css += '*, *::before, *::after { ';
        if (MODE.removeFilters) {
            add('filter', 'none');
            add('backdrop-filter', 'none');
            add('-webkit-backdrop-filter', 'none');
        }
        if (MODE.removeShadows) {
            add('box-shadow', 'none');
            add('text-shadow', 'none');
        }
        if (MODE.removeAnimations) {
            add('animation', 'none');
            add('transition', 'none');
            add('animation-duration', '0s');
            add('transition-duration', '0s');
        }
        if (MODE.removeMixBlendMode) add('mix-blend-mode', 'normal');
        if (MODE.removeClipPath) add('clip-path', 'none');
        if (MODE.removeMask) add('mask', 'none');
        if (MODE.removeIsolation) add('isolation', 'auto');
        if (MODE.removeWillChange) add('will-change', 'auto');
        if (MODE.removePerspective) add('perspective', 'none');
        if (MODE.removePreserve3D) add('transform-style', 'flat');
        css += '}';

        if (MODE.removeSmoothScroll) {
            css += 'html { scroll-behavior: auto !important; }';
        }
        if (MODE.removeScrollSnap) {
            css += '*, *::before, *::after { scroll-snap-type: none !important; scroll-snap-align: none !important; }';
        }
        return css;
    }

    function injectGlobalStylesheet() {
        const css = buildGlobalCSS();
        if (window.CSSStyleSheet && Array.isArray(document.adoptedStyleSheets)) {
            const sheet = new CSSStyleSheet();
            sheet.replaceSync(css);
            document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
            window.__upSheet = sheet;
            window.__upStyleText = null;
        } else {
            const style = document.createElement('style');
            style.textContent = css;
            (document.head || document.documentElement).appendChild(style);
            window.__upSheet = null;
            window.__upStyleText = css;
        }
    }

    const originalAttachShadow = Element.prototype.attachShadow;
    Element.prototype.attachShadow = function(init) {
        const shadow = originalAttachShadow.call(this, init);
        if (window.__upSheet) {
            shadow.adoptedStyleSheets = [...shadow.adoptedStyleSheets, window.__upSheet];
        } else if (window.__upStyleText) {
            const style = document.createElement('style');
            style.textContent = window.__upStyleText;
            shadow.appendChild(style);
        }
        return shadow;
    };

    if (MODE.optimizeCanvas) {
        const origGetContext = HTMLCanvasElement.prototype.getContext;
        HTMLCanvasElement.prototype.getContext = function(type, attrs) {
            attrs = attrs || {};
            if (type === '2d') {
                if (!('alpha' in attrs)) attrs.alpha = false;
                attrs.desynchronized = true;
            }
            return origGetContext.call(this, type, attrs);
        };
    }

    // Nota: a remoção de filtros SVG é feita via DOM na Seção 2.
    // (removida a regra CSS "svg filter{display:none}" da v1.1: <filter> não é
    // um elemento renderizado, então essa regra não tinha nenhum efeito.)

    if (window.__nuclear && window.__nuclearDispatcherReady) {
        if (MODE.lazyLoadIframes) {
            window.__nuclear.registerHandler('iframe', function(el) {
                if (!el.hasAttribute('loading')) el.loading = 'lazy';
            });
        }
    }

    function init() {
        injectGlobalStylesheet();
        if (MODE.lazyLoadIframes) {
            document.querySelectorAll('iframe:not([loading])').forEach(f => f.loading = 'lazy');
        }
        console.debug(` Ultra Performance CSS – Modo ${MODE.level.toUpperCase()} ativado`);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();


// =====================================================
//  SEÇÃO 2: DOM OPTIMIZER – DESKTOP MAX
// =====================================================
(function() {
    "use strict";
    if (window.__ultraExcluded) return;

    const CONFIG = {
        enableContentVisibility: true,
        enableVideoPauseOnHidden: true,
        enableSVGFilterRemoval: true,
        enableVideoPreload: true,
    };

    if (!window.__nuclear || !window.__nuclearDispatcherReady) {
        const localHandlers = [];
        const localObserver = new MutationObserver((mutations) => {
            for (const mut of mutations) {
                for (const node of mut.addedNodes) {
                    if (node.nodeType !== 1) continue;
                    for (const h of localHandlers) {
                        try {
                            if (node.matches && node.matches(h.selector)) h.callback(node);
                            if (node.querySelectorAll) {
                                node.querySelectorAll(h.selector).forEach(el => h.callback(el));
                            }
                        } catch(e) {}
                    }
                }
            }
        });
        localObserver.observe(document.documentElement, { childList: true, subtree: true });
        window.__nuclear = {
            registerHandler: (sel, cb) => localHandlers.push({ selector: sel, callback: cb }),
            scan: (sel, cb) => document.querySelectorAll(sel).forEach(el => cb(el)),
        };
    }

    const register = window.__nuclear.registerHandler;
    const scan = window.__nuclear.scan;

    // 1. Pausa de vídeos quando fora da viewport
    const videoElements = new Set();
    const videoObserver = new IntersectionObserver((entries) => {
        for (const entry of entries) {
            const video = entry.target;
            if (!entry.isIntersecting) {
                if (!video.paused) {
                    video.pause();
                    video.dataset.wasPausedByOptimizer = 'true';
                }
            } else {
                if (video.dataset.wasPausedByOptimizer === 'true') {
                    delete video.dataset.wasPausedByOptimizer;
                    // não damos play automaticamente, respeitamos o estado anterior
                }
            }
        }
    }, { threshold: 0.1 });

    function observeVideo(video) {
        if (videoElements.has(video)) return;
        videoElements.add(video);
        videoObserver.observe(video);
    }

    if (CONFIG.enableVideoPauseOnHidden) {
        register('video', observeVideo);
        scan('video', observeVideo);
    }

    // 2. content-visibility em seções grandes, com recálculo via ResizeObserver
    if (CONFIG.enableContentVisibility) {
        const sectionSelector = 'section, article, main, div[class*="list"], div[class*="grid"], div[class*="container"], div[class*="wrapper"]';

        // ResizeObserver nativo (não passa pelo override de debounce da Seção 3,
        // para manter o containIntrinsicSize sempre correto e evitar saltos de layout)
        const NativeResizeObserver = window.__nuclearNativeResizeObserver || window.ResizeObserver;
        const sizeObserver = new NativeResizeObserver((entries) => {
            for (const entry of entries) {
                const el = entry.target;
                const height = entry.contentBoxSize
                    ? (Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0].blockSize : entry.contentBoxSize.blockSize)
                    : entry.contentRect.height;
                if (height > 0) {
                    el.style.containIntrinsicSize = `${Math.round(height)}px`;
                }
            }
        });

        function applySectionVisibility(el) {
            const rect = el.getBoundingClientRect();
            if (rect.height > 200) {
                el.style.contentVisibility = 'auto';
                el.style.containIntrinsicSize = `${Math.round(rect.height)}px`;
                sizeObserver.observe(el);
            }
        }

        register(sectionSelector, applySectionVisibility);
        scan(sectionSelector, applySectionVisibility);
    }

    // 3. Vídeo preload metadata
    if (CONFIG.enableVideoPreload) {
        function applyVideoPreload(video) {
            if (!video.hasAttribute('preload') || video.getAttribute('preload') === 'auto') {
                video.setAttribute('preload', 'metadata');
            }
        }
        register('video', applyVideoPreload);
        scan('video', applyVideoPreload);
    }

    // 4. Remover filtros SVG (DOM) — única remoção real, a CSS morta foi retirada da Seção 1
    if (CONFIG.enableSVGFilterRemoval) {
        function removeSVGFilters(svg) {
            const filters = svg.querySelectorAll('filter');
            for (const f of filters) {
                f.remove();
            }
        }
        register('svg', removeSVGFilters);
        scan('svg', removeSVGFilters);
    }

    function init() {
        console.log(` DOM Optimizer – Desktop Max ativado`);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();


// =====================================================
//  SEÇÃO 3: JS OPTIMIZER – DESKTOP MAX
// =====================================================
(function() {
    "use strict";
    if (window.__ultraExcluded) return;

    const CONFIG = {
        throttleRAF: false,                 // 60 fps nativos
        forcePassiveEvents: true,
        disableConsole: false,
        throttleTimers: false,
        reduceMotion: false,
        lazyLoadImages: true,
        throttleResizeObserver: true,
        resizeDebounce: 100,
        // altura da "dobra" considerada LCP-sensível: imagens visíveis nesse
        // intervalo no momento do scan NÃO recebem fetchpriority='low'
        aboveFoldMarginPx: 0,
    };

    // Guarda o ResizeObserver nativo ANTES de sobrescrevê-lo, para que a
    // Seção 2 (content-visibility) possa usá-lo sem debounce de 100ms.
    window.__nuclearNativeResizeObserver = window.ResizeObserver;

    // ── 1. RAF não modificado (throttleRAF = false) ──

    // ── 2. PASSIVE EVENTS (scroll, wheel, mousewheel) – sem touchstart/touchmove ──
    if (CONFIG.forcePassiveEvents) {
        const passiveEvents = ['scroll', 'wheel', 'mousewheel'];
        const originalAddEventListener = EventTarget.prototype.addEventListener;
        EventTarget.prototype.addEventListener = function(type, listener, options) {
            let opts = options;
            if (passiveEvents.includes(type)) {
                if (typeof opts === 'boolean') {
                    opts = { capture: opts, passive: true };
                } else if (opts && typeof opts === 'object') {
                    if (opts.passive !== false) {
                        opts = Object.assign({}, opts, { passive: true });
                    }
                } else {
                    opts = { passive: true };
                }
            }
            return originalAddEventListener.call(this, type, listener, opts);
        };
    }

    // ── 3. CONSOLE ATIVO (disableConsole = false) ──

    // ── 4. MATCHMEDIA NÃO MODIFICADO (reduceMotion = false) ──

    // ── 5. TIMERS SEM THROTTLE (throttleTimers = false) ──

    // ── 6. RESIZE OBSERVER (debounce leve, para consumidores externos) ──
    if (CONFIG.throttleResizeObserver) {
        const OriginalResizeObserver = window.__nuclearNativeResizeObserver;
        if (OriginalResizeObserver) {
            window.ResizeObserver = class extends OriginalResizeObserver {
                constructor(callback) {
                    let timer = null;
                    const debouncedCallback = (entries, observer) => {
                        clearTimeout(timer);
                        timer = setTimeout(() => {
                            callback(entries, observer);
                        }, CONFIG.resizeDebounce);
                    };
                    super(debouncedCallback);
                }
            };
        }
    }

    // ── 7. LAZY LOAD IMAGES (preservando prioridade de imagens acima da dobra / LCP) ──
    function enhanceImage(img) {
        if (img.dataset.ultraProcessed === 'true') return;
        img.dataset.ultraProcessed = 'true';

        // Se já tem fetchpriority='high' ou loading='eager' explícitos, respeita a intenção do site
        const explicitHighPriority = img.getAttribute('fetchpriority') === 'high'
            || img.getAttribute('loading') === 'eager';
        if (explicitHighPriority) return;

        // Verifica se a imagem está (ou provavelmente estará) visível na primeira dobra.
        // Imagens sem geometria ainda (recém-inseridas, display:none, etc.) são tratadas
        // como não-críticas por segurança, e reavaliadas se aparecerem depois.
        const rect = img.getBoundingClientRect();
        const isAboveFold = rect.width > 0 && rect.height > 0 &&
            rect.top < (window.innerHeight + CONFIG.aboveFoldMarginPx) && rect.bottom > 0;

        if (isAboveFold) {
            // Prováveis candidatas a LCP: não mexe em loading/fetchpriority
            return;
        }

        if (!img.hasAttribute('loading')) img.loading = 'lazy';
        if (img.loading === 'lazy') {
            img.fetchPriority = 'low';
            img.decoding = 'async';
        }
    }

    if (window.__nuclear && window.__nuclearDispatcherReady) {
        window.__nuclear.registerHandler('img', enhanceImage);
        window.__nuclear.scan('img', enhanceImage);
    } else {
        const fallbackObserver = new MutationObserver((mutations) => {
            for (const m of mutations) {
                for (const node of m.addedNodes) {
                    if (node.nodeType === 1) {
                        if (node.matches('img')) enhanceImage(node);
                        if (node.querySelectorAll) {
                            node.querySelectorAll('img').forEach(enhanceImage);
                        }
                    }
                }
            }
        });
        fallbackObserver.observe(document.documentElement, { childList: true, subtree: true });
        document.querySelectorAll('img').forEach(enhanceImage);
    }

    function init() {
        if (window.__nuclear && window.__nuclearDispatcherReady) {
            window.__nuclear.scan('img', enhanceImage);
        }
        console.log(' Ultra Performance JS – Desktop Max ativado');
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();