🧠 X.com Heavy JS Optimizer+

Enhance X.com/Twitter performance by removing heavy CSS, throttling FPS, limiting feed DOM, blocking analytics, and optimizing offscreen videos.

// ==UserScript==
// @name         🧠 X.com Heavy JS Optimizer+
// @name:vi      🧠 Trình tối ưu JavaScript nặng cho X.com+
// @name:en      🧠 X.com Heavy JS Optimizer+
// @name:zh-CN   🧠 X.com 高级 JavaScript 优化器+
// @name:zh-TW   🧠 X.com 高級 JavaScript 優化器+
// @name:ja      🧠 X.com 高性能 JavaScript オプティマイザー+
// @name:ko      🧠 X.com 고급 JS 최적화기+
// @name:fr      🧠 Optimiseur JavaScript Avancé pour X.com+
// @name:de      🧠 X.com Erweiterter JS-Optimierer+
// @name:es      🧠 Optimizador JS Avanzado para X.com+
// @name:pt      🧠 Otimizador JS Avançado para X.com+
// @name:it      🧠 Ottimizzatore JS Avanzato per X.com+
// @name:ru      🧠 Расширенный оптимизатор JS для X.com+
// @name:pl      🧠 Zaawansowany optymalizator JS dla X.com+
// @name:tr      🧠 X.com Gelişmiş JS Optimize Edici+
// @name:ar      🧠 مُحسِّن JavaScript متقدم لـ X.com+
// @name:hi      🧠 X.com के लिए उन्नत JS ऑप्टिमाइज़र+
// @name:th      🧠 ตัวเพิ่มประสิทธิภาพ JS ระดับสูงสำหรับ X.com+
// @name:id      🧠 Pengoptimal JS Tingkat Lanjut untuk X.com+
// @name:nl      🧠 Geavanceerde JS-Optimizer voor X.com+
// @name:uk      🧠 Розширений оптимізатор JS для X.com+

// @description        Enhance X.com/Twitter performance by removing heavy CSS, throttling FPS, limiting feed DOM, blocking analytics, and optimizing offscreen videos.
// @description:vi     Cải thiện hiệu năng X.com/Twitter bằng cách loại bỏ CSS nặng, giới hạn FPS, giảm tải DOM feed, chặn theo dõi và tối ưu video ngoài màn hình.
// @description:en     Improve X.com/Twitter performance: removes heavy CSS, throttles FPS, limits DOM size, pauses offscreen videos, blocks analytics, and auto-enables aggressive mode when lag is detected.
// @description:zh-CN  优化 X.com/Twitter 性能:移除高负载 CSS、限制 FPS、减少 DOM、暂停屏幕外视频、屏蔽分析并在卡顿时自动启用高性能模式。
// @description:zh-TW  優化 X.com/Twitter 效能:移除高負載 CSS、限制 FPS、減少 DOM、暫停螢幕外影片、封鎖分析並在延遲時自動啟用高效模式。
// @description:ja      X.com/Twitter のパフォーマンスを向上: 重い CSS を削除し、FPS を制限し、フィード DOM を縮小し、画面外の動画を一時停止し、分析をブロックし、遅延時に自動的にアグレッシブモードを有効化。
// @description:ko      X.com/Twitter 성능 최적화: 무거운 CSS 제거, FPS 제한, 피드 DOM 축소, 화면 밖 동영상 일시정지, 분석 차단, 렉 발생 시 자동 공격적 모드 전환.
// @description:fr      Améliorez les performances de X.com/Twitter : supprime les filtres CSS lourds, limite les FPS, réduit le DOM, met en pause les vidéos hors écran, bloque l’analytique et active le mode agressif en cas de ralentissement.
// @description:de      Optimiert die Leistung von X.com/Twitter: Entfernt schwere CSS-Filter, begrenzt FPS, reduziert das DOM, pausiert Videos außerhalb des Bildschirms, blockiert Analysen und aktiviert bei Lag den aggressiven Modus automatisch.
// @description:es      Mejora el rendimiento de X.com/Twitter: elimina CSS pesados, limita FPS, reduce DOM, pausa videos fuera de pantalla, bloquea analíticas y activa modo agresivo automáticamente al detectar lag.
// @description:pt      Melhora o desempenho do X.com/Twitter: remove CSS pesado, limita FPS, reduz o DOM, pausa vídeos fora da tela, bloqueia análises e ativa o modo agressivo automaticamente quando há lag.
// @description:it      Migliora le prestazioni di X.com/Twitter: rimuove CSS pesanti, limita FPS, riduce DOM, mette in pausa i video fuori schermo, blocca le analisi e attiva la modalità aggressiva quando rileva lag.
// @description:ru      Оптимизирует X.com/Twitter: удаляет тяжелые CSS, ограничивает FPS, сокращает DOM, приостанавливает видео вне экрана, блокирует аналитику и автоматически включает агрессивный режим при лагах.
// @description:pl      Popraw wydajność X.com/Twitter: usuwa ciężkie style CSS, ogranicza FPS, zmniejsza DOM, wstrzymuje filmy poza ekranem, blokuje analitykę i automatycznie włącza tryb agresywny przy lagach.
// @description:tr      X.com/Twitter performansını artırır: ağır CSS filtrelerini kaldırır, FPS sınırlar, DOM’u küçültür, ekrandışı videoları duraklatır, analitiği engeller ve gecikme durumunda agresif modu otomatik açar.
// @description:ar      تحسين أداء X.com/Twitter: إزالة CSS الثقيل، تحديد معدل الإطارات، تقليل DOM، إيقاف الفيديوهات خارج الشاشة، حظر التحليلات، وتفعيل الوضع العدواني تلقائيًا عند التأخير.
// @description:hi      X.com/Twitter का प्रदर्शन बेहतर करें: भारी CSS हटाएं, FPS सीमित करें, DOM कम करें, ऑफस्क्रीन वीडियो रोकें, एनालिटिक्स ब्लॉक करें और लैग पर स्वतः आक्रामक मोड चालू करें.
// @description:th      ปรับปรุงประสิทธิภาพ X.com/Twitter: ลบ CSS หนัก, จำกัด FPS, ลด DOM, หยุดวิดีโอนอกหน้าจอ, บล็อกการวิเคราะห์ และเปิดโหมดแรงอัตโนมัติเมื่อแลค.
// @description:id      Meningkatkan performa X.com/Twitter: menghapus CSS berat, membatasi FPS, mengurangi DOM, menjeda video di luar layar, memblokir analitik, dan otomatis mengaktifkan mode agresif saat lag terdeteksi.
// @description:nl      Verbeter de prestaties van X.com/Twitter: verwijdert zware CSS, beperkt FPS, vermindert DOM, pauzeert video's buiten beeld, blokkeert analyses en activeert automatisch agressieve modus bij lag.
// @description:uk      Оптимізує X.com/Twitter: видаляє важкі CSS, обмежує FPS, скорочує DOM, призупиняє відео поза екраном, блокує аналітику та автоматично вмикає агресивний режим при лагах.

// @author       Oppai1442
// @namespace    https://greasyfork.org/users/oppai1442
// @license      MIT
// @homepageURL  https://greasyfork.org/scripts/xcom-heavy-js-optimizer
// @version      1.3.2
// @icon         https://x.com/favicon.ico
// @match        https://x.com/*
// @match        https://twitter.com/*
// @grant        GM_registerMenuCommand
// @run-at       document-start
// ==/UserScript==



(() => {
  'use strict';

    // Kill React DevTools hook & metrics early
  delete window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
  Object.defineProperty(window, '__REACT_DEVTOOLS_GLOBAL_HOOK__', {
    value: {},
    writable: false,
    configurable: false
  });


  // ========= Config =========
  const LS_KEY_MODE = '__x_opt_aggressive__';
  const LS_KEY_LIMIT = '__x_opt_limit__';
  const LS_KEY_BLOCK = '__x_opt_block_metrics__';

  let AGGRESSIVE = localStorage.getItem(LS_KEY_MODE) === '1';
  let LIMIT_FEED = Number(localStorage.getItem(LS_KEY_LIMIT) ?? 60); // số tweet tối đa giữ lại trong DOM
  let BLOCK_METRICS = localStorage.getItem(LS_KEY_BLOCK) === '1';

  const TARGET_FPS = 45; // Aggressive rAF cap
  const LONGTASK_AUTO_ON_MS = 1500; // tổng longtask trong ~5s để tự bật aggressive
  const LONGTASK_ULTRA_ON_MS = 3000; // ngưỡng bật "siêu gắt" trong runtime
  const MAX_VIDEOS_DECODE = 1; // chỉ 1 video hoạt động

  // ========= Menu =========
  if (typeof GM_registerMenuCommand === 'function') {
    GM_registerMenuCommand(`Aggressive: ${AGGRESSIVE ? 'ON' : 'OFF'}`, () => {
      AGGRESSIVE = !AGGRESSIVE;
      localStorage.setItem(LS_KEY_MODE, AGGRESSIVE ? '1' : '0');
      location.reload();
    });
    GM_registerMenuCommand(`Giới hạn tweet DOM (hiện: ${LIMIT_FEED})`, () => {
      const v = prompt('Giới hạn số tweet giữ lại trong DOM (0 = không giới hạn):', String(LIMIT_FEED));
      if (v == null) return;
      const n = Math.max(0, parseInt(v, 10) || 0);
      LIMIT_FEED = n;
      localStorage.setItem(LS_KEY_LIMIT, String(n));
      alert('OK! Reload để áp dụng.');
    });
    GM_registerMenuCommand(`Block metrics rác: ${BLOCK_METRICS ? 'ON' : 'OFF'}`, () => {
      BLOCK_METRICS = !BLOCK_METRICS;
      localStorage.setItem(LS_KEY_BLOCK, BLOCK_METRICS ? '1' : '0');
      alert('OK! Reload để áp dụng.');
    });
  }

  // ========= Utils =========
  const onReady = (fn) => (document.readyState === 'loading')
    ? document.addEventListener('DOMContentLoaded', fn, { once: true })
    : fn();

  const injectCSS = (css) => {
    const el = document.createElement('style');
    el.textContent = css;
    document.documentElement.appendChild(el);
    return el;
  };

  // ========= CSS: dọn compositor nặng + skip paint offscreen =========
  // - content-visibility: auto → bỏ render offscreen, cực kỳ lợi cho feed dài
  // - contain-intrinsic-size: tránh layout nhảy; 800px là giá trị "đệm" hợp lý cho tweet có media
  injectCSS(`
    * { backdrop-filter: none !important; }
    [style*="backdrop-filter"], [style*="filter: blur"], *[style*="blur("] { filter: none !important; }
    html, body, * { scroll-behavior: auto !important; }
    video { transform: none !important; will-change: auto !important; background-color: black !important; }
    article[role="article"], [data-testid="cellInnerDiv"] {
      content-visibility: auto !important;
      contain: layout paint style !important;
      contain-intrinsic-size: 800px !important;
    }
    /* bớt gradient layer nặng */
    [style*="linear-gradient("] { background-image: none !important; }
    * { will-change: auto !important; transform: none !important; }
  `);

  if (AGGRESSIVE) {
    injectCSS(`
      * { animation: none !important; transition: none !important; }
    `);
  }


  // ========= Ép passive listeners cho scroll/touch/wheel =========
  (function patchAddEventListener() {
    const origAdd = EventTarget.prototype.addEventListener;
    const passiveEvents = new Set(['touchstart', 'touchmove', 'wheel', 'mousewheel', 'scroll']);
    EventTarget.prototype.addEventListener = function (type, listener, options) {
      if (passiveEvents.has(type)) {
        if (options == null) options = { passive: true };
        else if (typeof options === 'boolean') options = { capture: options, passive: true };
        else if (typeof options === 'object' && options.passive == null) options = { ...options, passive: true };
      }
      return origAdd.call(this, type, listener, options);
    };
  })();

  // ========= Chặn preload/prefetch link =========
  const nukePreloads = () => {
    document.querySelectorAll('link[rel="preload"], link[rel="prefetch"]').forEach(l => l.remove());
  };
  new MutationObserver(nukePreloads).observe(document.documentElement, { childList: true, subtree: true });
  onReady(nukePreloads);

  // ========= (Tuỳ chọn) Block metrics rác (an toàn, không đụng feed chính) =========
  // Chặn những endpoint "client_event", "impression", "engagement", "scribe", "metrics" để bớt spam
  if (BLOCK_METRICS) {
    const noisy = /\/(client_event|impression|engagement|scribe|metrics|ad_event)/i;
    const origFetch = window.fetch.bind(window);
    window.fetch = (input, init) => {
      try {
        const url = (typeof input === 'string') ? input : (input?.url ?? '');
        if (noisy.test(url)) {
          // trả response rỗng 204
          return Promise.resolve(new Response(null, { status: 204 }));
        }
      } catch { }
      return origFetch(input, init);
    };
  }

  // ========= Video: tối ưu + pause offscreen + chỉ 1 video hoạt động =========
  const activeVideos = new Set();
  let playingNow = null;

  const optimizeVideo = (v) => {
    if (!v || v.__xOptimized) return;
    v.__xOptimized = true;
    v.autoplay = false;
    v.loop = false;
    v.removeAttribute('controls');
    v.preload = 'metadata';
    v.style.transform = 'none';
    v.style.willChange = 'auto';
    v.style.backgroundColor = 'black';

    // chỉ 1 video hoạt động → pause cái khác khi play cái này
    v.addEventListener('play', () => {
      if (playingNow && playingNow !== v) {
        try { playingNow.pause(); } catch { }
      }
      playingNow = v;
      activeVideos.add(v);
    }, { passive: true });

    v.addEventListener('pause', () => {
      activeVideos.delete(v);
      if (playingNow === v) playingNow = null;
    }, { passive: true });
  };

  const scanVideos = (root = document) => {
    if (!root || typeof root.querySelectorAll !== 'function') return;
    root.querySelectorAll('video').forEach(optimizeVideo);
  };

  onReady(scanVideos);

  new MutationObserver((muts) => {
    for (const m of muts) {
      if (m.addedNodes) {
        m.addedNodes.forEach(node => {
          if (node && node.nodeType === 1) {
            if (node.tagName === 'VIDEO') optimizeVideo(node);
            else if (node.querySelectorAll) scanVideos(node);
          }
        });
      }
    }
  }).observe(document.documentElement, { childList: true, subtree: true });

  // Pause video khi offscreen (tiết kiệm decode)
  const io = new IntersectionObserver((entries) => {
    for (const e of entries) {
      const v = e.target;
      if (!(v instanceof HTMLVideoElement)) continue;
      if (e.isIntersecting) {
        // nếu không có video nào đang chạy, cho phép play khi user bấm
      } else {
        try { v.pause(); } catch { }
      }
    }
  }, { root: null, threshold: 0.001 });
  onReady(() => document.querySelectorAll('video').forEach(v => io.observe(v)));

  // ========= Giới hạn DOM feed: giữ tối đa N tweet để giảm memory/layout =========
  function gcFeed() {
    if (!LIMIT_FEED) return;
    const nodes = document.querySelectorAll('article[role="article"]');
    if (nodes.length <= LIMIT_FEED) return;
    // ẩn bớt mấy cái quá cũ (nhanh, ít rủi ro hơn remove)
    for (let i = 0; i < nodes.length - LIMIT_FEED; i++) {
      const el = nodes[i];
      if (!el.__xHidden) {
        el.style.display = 'none';
        el.__xHidden = true;
        // giải phóng video nếu có
        el.querySelectorAll('video').forEach(v => {
          try { v.pause(); } catch { }
        });
      }
    }
  }
  setInterval(gcFeed, 1500);

  // ========= Aggressive mode runtime (rAF cap + min setInterval) =========
  const origRAF = window.requestAnimationFrame.bind(window);
  const origSetInterval = window.setInterval.bind(window);
  let lastRAF = 0;
  let useRAFCap = AGGRESSIVE;
  let minInterval = AGGRESSIVE ? 100 : 0;

  window.requestAnimationFrame = (cb) => {
    if (!useRAFCap) return origRAF(cb);
    return origRAF((ts) => {
      if (ts - lastRAF >= (1000 / TARGET_FPS)) {
        lastRAF = ts;
        try { cb(ts); } catch { }
      } else {
        origRAF(cb);
      }
    });
  };
  window.setInterval = (fn, delay, ...args) => {
    const d = (delay == null || delay < minInterval) ? (minInterval || delay || 0) : delay;
    return origSetInterval(fn, d, ...args);
  };

  // ========= Auto-detect long tasks → tự bật Aggressive/Ultra =========
  try {
    // dùng PerformanceObserver (Long Task API)
    let bucket = 0;
    const po = new PerformanceObserver((list) => {
      for (const e of list.getEntries()) {
        bucket += e.duration || 0;
      }
    });
    po.observe({ type: 'longtask', buffered: true });

    setInterval(() => {
      const total = bucket; bucket = 0;
      // tự bật aggressive nếu lag nhiều
      if (!useRAFCap && total > LONGTASK_AUTO_ON_MS) {
        useRAFCap = true; minInterval = 100;
        console.warn('[Oppai1442] Aggressive ON (auto): longtasks=%dms', total | 0);
      }
      // siêu gắt nếu quá nặng
      if (total > LONGTASK_ULTRA_ON_MS) {
        useRAFCap = true; minInterval = 150; // nâng min interval lên thêm
        document.documentElement.classList.add('x-ultra');
        injectCSS(`.x-ultra *{ animation:none!important; transition:none!important; }`);
        console.warn('[Oppai1442] Ultra mode ON: longtasks=%dms', total | 0);
      }
    }, 5000);
  } catch { }

  // ========= Safety: pause hết khi tab ẩn =========
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      document.querySelectorAll('video').forEach(v => { try { v.pause(); } catch { } });
    }
  }, { passive: true });

  // ========= Ảnh: ép lazy/async decode (nhẹ layout) =========
  const tuneImg = (img) => {
    if (!img) return;
    img.loading = 'lazy';
    img.decoding = 'async';
  };
  const scanImg = (root = document) => {
    if (!root || typeof root.querySelectorAll !== 'function') return;
    root.querySelectorAll('img').forEach(tuneImg);
  };
  onReady(scanImg);
  new MutationObserver((muts) => {
    for (const m of muts) for (const n of m.addedNodes) {
      if (n && n.nodeType === 1) {
        if (n.tagName === 'IMG') tuneImg(n);
        else if (n.querySelectorAll) scanImg(n);
      }
    }
  }).observe(document.documentElement, { childList: true, subtree: true });

  // Brutal block all beacons & performance observers
  navigator.sendBeacon = () => true;
  const origPO = window.PerformanceObserver;
  window.PerformanceObserver = class extends origPO {
    constructor(type, ...a) {
      if (typeof type === 'object' && /(paint|longtask|resource)/i.test(type.type || '')) {
        return { observe:()=>{}, disconnect:()=>{} };
      }
      return new origPO(...arguments);
    }
  };

  setInterval(() => {
    const articles = document.querySelectorAll('article[role="article"]');
    if (articles.length > 80) {
      for (let i = 0; i < articles.length - 60; i++) {
        articles[i].remove();
      }
    }
  }, 2000);

  // Block global MutationObserver creation (except internal)
  const OrigMO = window.MutationObserver;
  window.MutationObserver = class extends OrigMO {
    constructor(cb, opt) {
      if (document.readyState !== 'complete') return new OrigMO(cb, opt);
      // block post-hydration observers
      if (opt && opt.subtree && opt.childList) return { observe:()=>{}, disconnect:()=>{} };
      return new OrigMO(cb, opt);
    }
  };



})();