Axiom推文翻译

对axiom的推文监控,代币内推文,扫链出现的推文进行翻译

当前为 2025-07-08 提交的版本,查看 最新版本

// ==UserScript==
// @name         Axiom推文翻译
// @namespace    http://tampermonkey.net/
// @version      4.4
// @author       @Gufii_666
// @description  对axiom的推文监控,代币内推文,扫链出现的推文进行翻译
// @match        https://axiom.trade/pulse*
// @match        https://axiom.trade/trackers*
// @match        https://axiom.trade/meme/*
// @match        https://axiom.trade/discover*
// @license      MIT
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const TRANSLATION_BASE_URL = 'https://translate.googleapis.com/translate_a/single';
    const CLIENT_PARAM = 'gtx';
    const SOURCE_LANG = 'en';
    const TARGET_LANG = 'zh-CN';
    const DATA_TYPE = 't';

    const TRANSLATED_TEXT_CLASS = 'localized-content-display';
    const ORIGINAL_DATA_ATTR = 'data-translation-processed-status';
    const ORIGINAL_TEXT_STORE_ATTR = 'data-original-text';
    const UNIQUE_TRANSLATION_ID_ATTR = 'data-translation-id';

    const ONGOING_TRANSLATIONS = new Map();

    const LAZY_SCAN_INTERVAL_MS = 1500;
    let lazyScanTimer = null;

    async function obtainLocalizedText(inputString) {
        if (!inputString || typeof inputString !== 'string') {
            return '[Translation Input Error]';
        }

        const queryParams = new URLSearchParams({
            client: CLIENT_PARAM,
            sl: SOURCE_LANG,
            tl: TARGET_LANG,
            dt: DATA_TYPE,
            q: inputString
        });
        const fullUrl = `${TRANSLATION_BASE_URL}?${queryParams.toString()}`;

        try {
            const response = await fetch(fullUrl);
            const data = await response.json();
            if (data && data[0] && Array.isArray(data[0])) {
                return data[0].map(segment => segment[0]).join('');
            }
            throw new Error("Invalid translation response structure.");
        } catch (error) {
            console.error("Content localization failed:", error);
            return '[翻译失败]';
        }
    }

    // Function to apply layout fixes to a specific element
    function applyLayoutFixes(element) {
        if (!element) return;

        // Force block display if it's an inline-like container
        // This helps it respect content flow and height changes
        const currentDisplay = getComputedStyle(element).display;
        if (currentDisplay.includes('inline') && !currentDisplay.includes('flex') && !currentDisplay.includes('grid')) {
            element.style.display = 'block';
        }

        Object.assign(element.style, {
            maxHeight: "none",        // Remove max height restrictions
            height: "auto",           // Allow height to adapt to content
            overflow: "visible",      // Ensure content is not clipped
            overflowY: "visible",     // Specific for Y-axis
            overflowX: "visible",     // Specific for X-axis
            minHeight: "unset",       // Remove fixed min-heights
            flexShrink: "0",          // Prevent shrinking in flex containers
            alignSelf: "stretch"      // For flex items, ensure they stretch if needed
        });

        // Hide common gradient overlays that might obscure content
        const gradient = element.querySelector("div[class*='bg-gradient-to-b']");
        if (gradient) {
            gradient.style.display = "none";
        }
    }

    function updateTranslationBox(targetElement, statusOrContent, prepend = false) {
        if (!targetElement || !targetElement.parentElement) return;

        if (!targetElement.dataset.translationId) {
            targetElement.dataset.translationId = Math.random().toString(36).substring(2, 15);
        }
        const translationId = targetElement.dataset.translationId;

        let translationParagraph = targetElement.parentElement.querySelector(`p.${TRANSLATED_TEXT_CLASS}[${UNIQUE_TRANSLATION_ID_ATTR}="${translationId}"]`);

        if (!translationParagraph) {
            translationParagraph = document.createElement("p");
            translationParagraph.classList.add(TRANSLATED_TEXT_CLASS);
            translationParagraph.setAttribute(UNIQUE_TRANSLATION_ID_ATTR, translationId);
            if (prepend) {
                targetElement.parentElement.insertBefore(translationParagraph, targetElement);
            } else {
                targetElement.parentElement.appendChild(translationParagraph);
            }
        }

        translationParagraph.textContent = statusOrContent;

        Object.assign(translationParagraph.style, {
            color: "#FFFFFF",
            fontSize: "14px",
            padding: "8px 12px",
            borderRadius: "6px",
            margin: "8px 0",
            boxShadow: "0 2px 8px rgba(0, 0, 0, 0.3)",
            lineHeight: "1.5",
            textShadow: "1px 1px 2px rgba(0,0,0,0.2)",
            backgroundColor: "",
            border: "",
            fontWeight: "",
            cursor: "",
            opacity: ""
        });


        if (statusOrContent === '[翻译中...]') {
            Object.assign(translationParagraph.style, {
                backgroundColor: "#4A90E2",
                border: "1px solid #337AB7",
                fontWeight: "normal",
                cursor: "wait",
                opacity: "0.8"
            });
            translationParagraph.title = "翻译中,请稍候...";
            translationParagraph.onclick = null;
        } else if (statusOrContent === '[翻译失败]') {
            Object.assign(translationParagraph.style, {
                backgroundColor: "#DC3545",
                border: "1px solid #DC3545",
                fontWeight: "normal",
                cursor: "pointer",
                opacity: "1"
            });
            translationParagraph.title = "点击重试翻译";
            translationParagraph.onclick = () => {
                targetElement.removeAttribute(ORIGINAL_DATA_ATTR);
                targetElement.removeAttribute(ORIGINAL_TEXT_STORE_ATTR);
                targetElement.removeAttribute(UNIQUE_TRANSLATION_ID_ATTR);
                ONGOING_TRANSLATIONS.delete(targetElement);
                translationParagraph.remove();
                processElementForTranslation(targetElement);
            };
        } else {
            Object.assign(translationParagraph.style, {
                backgroundColor: "#2E8B57",
                border: "1px solid #4CAF50",
                fontWeight: "bold",
                cursor: "default",
                opacity: "1"
            });
            translationParagraph.title = "";
            translationParagraph.onclick = null;
        }

        // --- Layout Adjustment Logic ---
        // Apply fixes to the immediate parent of the targetElement
        applyLayoutFixes(targetElement.parentElement);

        // Also apply to relevant ancestors (up to 5 levels)
        let currentParent = targetElement.parentElement;
        let depth = 0;
        while (currentParent && depth < 5) {
            // Apply fixes to specific known containers
            if (currentParent.matches("div.hover\\:bg-primaryStroke\\/20") ||
                currentParent.matches("article.tweet-container_article__0ERPK") ||
                currentParent.matches("div.mt-2.border.border-secondaryStroke.rounded-\\[4px\\].relative.group.overflow-hidden") ||
                currentParent.matches("div.flex-1.min-w-0") // This class is often a flex item that might limit height
            ) {
                applyLayoutFixes(currentParent);
            }
            currentParent = currentParent.parentElement;
            depth++;
        }
        // --- END Layout Adjustment Logic ---
    }

    async function processElementForTranslation(el) {
        if (!el || ONGOING_TRANSLATIONS.has(el)) {
            return;
        }

        let prepend = true;
        if (el.matches("p.break-words") && el.tagName === 'P') {
            prepend = false;
        }

        initiateTextTranslation(el, prepend);
    }

    async function initiateTextTranslation(textElement, prepend) {
        const rawContent = textElement.innerText.trim();
        if (!rawContent) {
            textElement.setAttribute(ORIGINAL_DATA_ATTR, 'true');
            return;
        }

        const storedOriginalText = textElement.getAttribute(ORIGINAL_TEXT_STORE_ATTR);
        const isProcessed = textElement.getAttribute(ORIGINAL_DATA_ATTR) === 'true';
        const hasTranslationBox = textElement.parentElement.querySelector(`p.${TRANSLATED_TEXT_CLASS}[${UNIQUE_TRANSLATION_ID_ATTR}="${textElement.dataset.translationId}"]`);

        if (isProcessed) {
            if (rawContent !== storedOriginalText) {
                console.log('Content changed for element, re-processing:', rawContent);
                textElement.removeAttribute(ORIGINAL_DATA_ATTR);
                textElement.removeAttribute(ORIGINAL_TEXT_STORE_ATTR);
                textElement.removeAttribute(UNIQUE_TRANSLATION_ID_ATTR);
                if (hasTranslationBox) {
                    hasTranslationBox.remove();
                }
                ONGOING_TRANSLATIONS.delete(textElement);
            } else if (hasTranslationBox && hasTranslationBox.textContent.includes('[翻译失败]')) {
                console.log('Previous translation failed, re-processing:', rawContent);
                textElement.removeAttribute(ORIGINAL_DATA_ATTR);
                if (hasTranslationBox) {
                    hasTranslationBox.remove();
                }
                ONGOING_TRANSLATIONS.delete(textElement);
            } else {
                return;
            }
        }

        textElement.setAttribute(ORIGINAL_TEXT_STORE_ATTR, rawContent);
        updateTranslationBox(textElement, '[翻译中...]', prepend);

        const translationPromise = obtainLocalizedText(rawContent).then(localizedContent => {
            updateTranslationBox(textElement, localizedContent, prepend);
            textElement.setAttribute(ORIGINAL_DATA_ATTR, 'true');
        }).catch(() => {
            updateTranslationBox(textElement, '[翻译失败]', prepend);
            textElement.setAttribute(ORIGINAL_DATA_ATTR, 'true');
        }).finally(() => {
            ONGOING_TRANSLATIONS.delete(textElement);
        });

        ONGOING_TRANSLATIONS.set(textElement, translationPromise);
    }


    function performFullPageScan() {
        document.querySelectorAll(`.${TRANSLATED_TEXT_CLASS}`).forEach(el => el.remove());

        document.querySelectorAll(
            "p.tweet-body_root__ChzUj," +
            "p.text-textSecondary.mt-1.whitespace-pre-wrap," +
            "div.mt-2.border.border-secondaryStroke.rounded-\\[4px\\].relative.group.overflow-hidden p.text-textSecondary.mt-1," +
            "p.break-words"
        ).forEach(processElementForTranslation);
    }


    let lastPathname = window.location.pathname;
    let scanTimeoutId = null;

    const contentWatcher = new MutationObserver((mutations) => {
        if (window.location.pathname !== lastPathname) {
            lastPathname = window.location.pathname;
            clearTimeout(scanTimeoutId);
            scanTimeoutId = setTimeout(performFullPageScan, 500);
            return;
        }

        for (const mutationRecord of mutations) {
            for (const addedDomNode of mutationRecord.addedNodes) {
                if (addedDomNode.nodeType !== 1 || !addedDomNode.querySelector) continue;

                addedDomNode.querySelectorAll(
                    "p.tweet-body_root__ChzUj," +
                    "p.text-textSecondary.mt-1.whitespace-pre-wrap," +
                    "div.mt-2.border.border-secondaryStroke.rounded-\\[4px\\].relative.group.overflow-hidden p.text-textSecondary.mt-1," +
                    "p.break-words"
                ).forEach(processElementForTranslation);
            }
        }
    });

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

    performFullPageScan();

    lazyScanTimer = setInterval(function() {
        document.querySelectorAll(
            `p.tweet-body_root__ChzUj:not([${ORIGINAL_DATA_ATTR}]),` +
            `p.text-textSecondary.mt-1.whitespace-pre-wrap:not([${ORIGINAL_DATA_ATTR}]),` +
            `div.mt-2.border.border-secondaryStroke.rounded-\\[4px\\].relative.group.overflow-hidden p.text-textSecondary.mt-1:not([${ORIGINAL_DATA_ATTR}]),` +
            `p.break-words:not([${ORIGINAL_DATA_ATTR}])`
        ).forEach(processElementForTranslation);
    }, LAZY_SCAN_INTERVAL_MS);

    window.addEventListener('beforeunload', () => {
        if (scanTimeoutId) clearTimeout(scanTimeoutId);
        if (lazyScanTimer) clearInterval(lazyScanTimer);
    });

})();