Ultra Performance Desktop Max

Máxima performance para desktops – remove efeitos caros, otimiza renderização e mantém interatividade total.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey, Greasemonkey of Violentmonkey.

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

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Violentmonkey.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Userscripts.

Voor het installeren van scripts heb je een extensie nodig, zoals {tampermonkey_link:Tampermonkey}.

Voor het installeren van scripts heb je een gebruikersscriptbeheerder nodig.

(Ik heb al een user script manager, laat me het downloaden!)

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

(Ik heb al een beheerder - laat me doorgaan met de installatie!)

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

// =====================================================
//  CORE – DISPATCHER ÚNICO DE MUTATION OBSERVER
// =====================================================
(function() {
    "use strict";

    const handlers = [];
    let isObserving = false;

    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
                    }
                }
            }
        }
    }

    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";

    const MODE = {
        level: 'desktop-max',
        removeFilters: true,
        removeShadows: true,
        removeAnimations: true,          // remove animações/transições para evitar repaints
        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 (importante para layout e estética)
        removeSticky: false,             // mantém sticky/fixed para usabilidade desktop
        pauseVideosOutsideViewport: true,
        lazyLoadIframes: true,
        removeSVGFilters: true,
        optimizeCanvas: true,            // apenas alpha:false/desynchronized, sem throttle
        forceFontDisplaySwap: true,      // adiciona font-display: swap em @font-face
        ignoreDomains: [
            
        ],
    };

    const host = location.hostname.toLowerCase();
    if (MODE.ignoreDomains.some(d => host.includes(d) || host === d)) return;
    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;
    const URL_FUNCTION = /url\(/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}`;
            }
        }
        // removeBackgroundImages = false, não remove imagens de fundo
        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);
        };
    }

    if (MODE.removeSVGFilters) {
        const svgStyle = document.createElement('style');
        svgStyle.textContent = `
            svg filter, svg feGaussianBlur, svg feDropShadow, svg feMorphology, svg feOffset, svg feColorMatrix {
                display: none !important;
            }
        `;
        document.head.appendChild(svgStyle);
    }

    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";

    const CONFIG = {
        enableContentVisibility: true,    // acelera scroll e renderização
        enableVideoPauseOnHidden: true,  // libera CPU quando vídeo sai da tela
        enableSVGFilterRemoval: true,
        enableVideoPreload: true,        // metadata
        // sem throttle de canvas, sem esconder imagens/iframes
    };

    const 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',
    ];
    const host = location.hostname.toLowerCase();
    if (EXCLUDE_DOMAINS.some(d => host.includes(d) || host === d)) return;

    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
    if (CONFIG.enableContentVisibility) {
        const sectionSelector = 'section, article, main, div[class*="list"], div[class*="grid"], div[class*="container"], div[class*="wrapper"]';

        function applySectionVisibility(el) {
            const rect = el.getBoundingClientRect();
            if (rect.height > 200) {
                el.style.contentVisibility = 'auto';
                el.style.containIntrinsicSize = el.dataset.intrinsicSize || `${rect.height}px`;
            }
        }

        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)
    if (CONFIG.enableSVGFilterRemoval) {
        function removeSVGFilters(svg) {
            const filters = svg.querySelectorAll('filter');
            for (const f of filters) {
                f.remove();
            }
        }
        register('svg', removeSVGFilters);
        scan('svg', (svg) => {
            const filters = svg.querySelectorAll('filter');
            for (const f of filters) {
                f.remove();
            }
        });
    }

    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";

    const CONFIG = {
        throttleRAF: false,                 // 60 fps nativos
        forcePassiveEvents: true,
        disableConsole: false,
        throttleTimers: false,
        reduceMotion: false,
        lazyLoadImages: true,
        throttleResizeObserver: true,
        resizeDebounce: 100,                // debounce leve para evitar excessos
    };

    // ── 1. RAF não modificado ──

    // ── 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 ──

    // ── 4. MATCHMEDIA NÃO MODIFICADO ──

    // ── 5. TIMERS SEM THROTTLE ──

    // ── 6. RESIZE OBSERVER (debounce leve) ──
    if (CONFIG.throttleResizeObserver) {
        const OriginalResizeObserver = window.ResizeObserver;
        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 ──
    function enhanceImage(img) {
        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();
    }
})();