TriX Executor

A Comprehensive Script Executor for Territorial.io with multi-tab support, automation, and a user-friendly interface.

目前為 2025-07-02 提交的版本,檢視 最新版本

// ==UserScript==
// @name         TriX Executor
// @namespace    https://github.com/YourUsername/TriX-Executor
// @version      1.0.2
// @description  A Comprehensive Script Executor for Territorial.io with multi-tab support, automation, and a user-friendly interface.
// @author       You
// @match        *://territorial.io/*
// @match        *://www.territorial.io/*
// @icon         https://i.postimg.cc/0NkRZxDm/image.png
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_listValues
// @grant        GM_deleteValue
// @grant        GM_addValueChangeListener
// @grant        GM.xmlHttpRequest
// @run-at       document-end
// @license      MIT
// ==/UserScript==

/*
 *   _____  ____  _   __  ___________
 *  |_   _||_  _|| | / / |  _  | ___ \
 *    | |    | | | |/ /  | |/' | |_/ /
 *    | |    | | |    \  |  /| |  __/
 *   _| |_  _| |_| |\  \ \ |_/ / |
 *   \___/  \___/\_| \_/  \___/\_|
 *
 *   TriX Executor - v1.0.2
 *   Logo: https://i.postimg.cc/0NkRZxDm/image.png
 *
 *   An unparalleled level of control and automation for Territorial.io.
 */

(function() {
    'use strict';
    console.log('TriX Executor: Script starting...');

    // --- Configuration & Constants ---
    const SCRIPT_PREFIX = 'trix_script_';
    const BROADCAST_CHANNEL = 'trix_broadcast_channel';
    const TAB_ID = `tab_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;

    // --- UI Module ---
    const UI = {
        isDragging: false,
        dragOffsetX: 0,
        dragOffsetY: 0,

        init() {
            this.injectCSS();
            this.injectHTML();
            this.attachEventListeners();
            this.showTab('executor');
            ScriptManager.populateScriptSelector();
            this.log('TriX Executor v1.0.2 initialized.');
            this.log(`Tab ID: ${TAB_ID}`);
        },

        injectCSS() {
            GM_addStyle(`
                #trix-container {
                    position: fixed !important;
                    top: 20px !important;
                    left: 20px !important;
                    width: 500px;
                    max-width: 90vw;
                    background-color: #282c34;
                    border: 1px solid #4f5b66;
                    border-radius: 8px;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.5);
                    z-index: 1000000 !important; /* Increased z-index */
                    color: #abb2bf;
                    font-family: 'Menlo', 'Monaco', 'Consolas', monospace;
                    font-size: 14px;
                    display: flex !important; /* Changed to flex from none */
                    flex-direction: column;
                    resize: both;
                    overflow: hidden;
                    min-width: 350px;
                    min-height: 250px;
                }
                /* This class will be toggled to show/hide */
                #trix-container.hidden {
                    display: none !important;
                }
                #trix-open-btn {
                    position: fixed !important;
                    top: 20px !important;
                    right: 20px !important;
                    z-index: 999999 !important; /* Increased z-index */
                    display: block !important;
                }
                #trix-header {
                    background-color: #21252b;
                    padding: 8px 12px;
                    cursor: move;
                    user-select: none;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    border-bottom: 1px solid #4f5b66;
                }
                #trix-header-title {
                    display: flex;
                    align-items: center;
                    font-weight: bold;
                }
                #trix-logo {
                    width: 24px;
                    height: 24px;
                    margin-right: 8px;
                }
                #trix-controls button {
                    background: none;
                    border: none;
                    color: #abb2bf;
                    font-size: 18px;
                    cursor: pointer;
                    margin-left: 5px;
                }
                #trix-controls button:hover {
                    color: #61afef;
                }
                #trix-content {
                    padding: 10px;
                    flex-grow: 1;
                    display: flex;
                    flex-direction: column;
                    overflow: auto;
                }
                .trix-tab-content {
                    display: none;
                    height: 100%;
                    flex-direction: column;
                }
                .trix-tab-content.active {
                    display: flex;
                }
                #trix-tabs {
                    display: flex;
                    border-bottom: 1px solid #4f5b66;
                    margin-bottom: 10px;
                }
                .trix-tab-button {
                    padding: 8px 15px;
                    cursor: pointer;
                    border: none;
                    background-color: transparent;
                    color: #abb2bf;
                    border-bottom: 2px solid transparent;
                }
                .trix-tab-button.active {
                    color: #61afef;
                    border-bottom: 2px solid #61afef;
                }
                #trix-editor {
                    width: 100%;
                    flex-grow: 1;
                    background-color: #1e2227;
                    color: #d1d1d1;
                    border: 1px solid #4f5b66;
                    border-radius: 4px;
                    padding: 5px;
                    box-sizing: border-box;
                    resize: none;
                    min-height: 100px;
                }
                .trix-button-bar {
                    margin-top: 10px;
                    display: flex;
                    gap: 10px;
                    flex-wrap: wrap;
                }
                .trix-button, .trix-input {
                    background-color: #3a3f4b;
                    border: 1px solid #4f5b66;
                    color: #abb2bf;
                    padding: 8px 12px;
                    border-radius: 4px;
                    cursor: pointer;
                    font-family: inherit;
                    font-size: 13px;
                }
                .trix-button:hover {
                    background-color: #4b515f;
                }
                .trix-button.primary {
                    background-color: #61afef;
                    color: #282c34;
                    font-weight: bold;
                }
                .trix-button.primary:hover {
                    background-color: #72baff;
                }
                .trix-button.danger {
                    background-color: #e06c75;
                    color: #282c34;
                }
                #trix-console {
                    height: 100%;
                    background-color: #1e2227;
                    border: 1px solid #4f5b66;
                    padding: 5px;
                    overflow-y: auto;
                    font-size: 12px;
                    flex-grow: 1;
                }
                #trix-console div { padding: 2px 4px; border-bottom: 1px solid #2c313a; }
                #trix-console .log-error { color: #e06c75; }
                #trix-console .log-warn { color: #e5c07b; }
                #trix-console .log-info { color: #61afef; }
                #trix-console .log-broadcast { color: #98c379; font-style: italic; }
                #trix-script-manager { display: flex; align-items: center; gap: 10px; }
                #trix-script-selector { flex-grow: 1; }
            `);
        },

        injectHTML() {
            const html = `
                <div id="trix-container" class="hidden">
                    <div id="trix-header">
                        <div id="trix-header-title">
                            <img id="trix-logo" src="https://i.postimg.cc/0NkRZxDm/image.png" alt="TriX Logo">
                            <span>TriX Executor</span>
                        </div>
                        <div id="trix-controls">
                            <button id="trix-toggle-btn" title="Hide Executor Panel">▼</button>
                        </div>
                    </div>
                    <div id="trix-content">
                        <div id="trix-tabs">
                            <button class="trix-tab-button" data-tab="executor">Executor</button>
                            <button class="trix-tab-button" data-tab="scripts">Scripts</button>
                            <button class="trix-tab-button" data-tab="console">Console</button>
                        </div>
                        <div id="executor-tab" class="trix-tab-content">
                            <textarea id="trix-editor" placeholder="Enter your script here..."></textarea>
                            <div class="trix-button-bar">
                                <button id="trix-execute-btn" class="trix-button primary">Execute</button>
                                <button id="trix-clear-editor-btn" class="trix-button">Clear</button>
                            </div>
                        </div>
                        <div id="scripts-tab" class="trix-tab-content">
                            <div id="trix-script-manager">
                                <select id="trix-script-selector" class="trix-input"></select>
                                <button id="trix-load-script-btn" class="trix-button">Load</button>
                                <button id="trix-delete-script-btn" class="trix-button danger">Delete</button>
                            </div>
                            <input type="text" id="trix-script-name" class="trix-input" placeholder="Enter script name to save..." style="margin-top: 10px; width: 100%; box-sizing: border-box;">
                            <div class="trix-button-bar"><button id="trix-save-script-btn" class="trix-button primary">Save Current Script</button></div>
                            <hr style="width:100%; border-color:#4f5b66; margin: 15px 0;">
                            <input type="text" id="trix-external-url" class="trix-input" placeholder="https://example.com/script.js" style="width: 100%; box-sizing: border-box;">
                            <div class="trix-button-bar"><button id="trix-fetch-run-btn" class="trix-button">Fetch & Run</button></div>
                        </div>
                        <div id="console-tab" class="trix-tab-content">
                            <div id="trix-console"></div>
                            <div class="trix-button-bar"><button id="trix-clear-console-btn" class="trix-button">Clear Console</button></div>
                        </div>
                    </div>
                </div>
                <button id="trix-open-btn" class="trix-button">Open TriX</button>
            `;
            document.body.insertAdjacentHTML('beforeend', html);

            // Let's log the created button to the console for easy inspection.
            console.log('TriX Executor: UI Injected. You can inspect the button here:', document.getElementById('trix-open-btn'));
        },

        attachEventListeners() {
            // ... (dragging logic is the same)
            const header = document.getElementById('trix-header');
            const container = document.getElementById('trix-container');
            header.addEventListener('mousedown', (e) => {
                if (e.target.tagName === 'BUTTON') return; this.isDragging = true; this.dragOffsetX = e.clientX - container.offsetLeft; this.dragOffsetY = e.clientY - container.offsetTop;
            });
            document.addEventListener('mousemove', (e) => {
                if (!this.isDragging) return; container.style.left = `${e.clientX - this.dragOffsetX}px`; container.style.top = `${e.clientY - this.dragOffsetY}px`;
            });
            document.addEventListener('mouseup', () => { this.isDragging = false; });

            // Panel Visibility (Simplified Logic)
            document.getElementById('trix-open-btn').addEventListener('click', () => this.togglePanel(true));
            document.getElementById('trix-toggle-btn').addEventListener('click', () => this.togglePanel(false));

            // ... (rest of event listeners are the same)
            document.querySelectorAll('.trix-tab-button').forEach(btn => { btn.addEventListener('click', () => this.showTab(btn.dataset.tab)); });
            document.getElementById('trix-execute-btn').addEventListener('click', () => { Executor.execute(document.getElementById('trix-editor').value); });
            document.getElementById('trix-clear-editor-btn').addEventListener('click', () => { document.getElementById('trix-editor').value = ''; });
            document.getElementById('trix-save-script-btn').addEventListener('click', ScriptManager.saveScriptFromEditor);
            document.getElementById('trix-load-script-btn').addEventListener('click', ScriptManager.loadScriptToEditor);
            document.getElementById('trix-delete-script-btn').addEventListener('click', ScriptManager.deleteSelectedScript);
            document.getElementById('trix-fetch-run-btn').addEventListener('click', () => { const url = document.getElementById('trix-external-url').value; if (url) ScriptManager.fetchAndRun(url); else UI.log('External script URL is empty.', 'warn'); });
            document.getElementById('trix-clear-console-btn').addEventListener('click', () => { document.getElementById('trix-console').innerHTML = ''; });
        },

        togglePanel(forceShow) {
            const container = document.getElementById('trix-container');
            const openBtn = document.getElementById('trix-open-btn');
            const isHidden = container.classList.contains('hidden');

            if (forceShow === true || isHidden) { // Show panel
                container.classList.remove('hidden');
                openBtn.style.display = 'none';
            } else { // Hide panel
                container.classList.add('hidden');
                openBtn.style.display = 'block';
            }
        },
        // ... (rest of UI module is the same)
        showTab(tabId) {
            document.querySelectorAll('.trix-tab-content').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.trix-tab-button').forEach(btn => btn.classList.remove('active'));
            document.getElementById(`${tabId}-tab`).classList.add('active');
            document.querySelector(`.trix-tab-button[data-tab="${tabId}"]`).classList.add('active');
        },
        log(message, type = 'log') {
            const consoleEl = document.getElementById('trix-console');
            if (!consoleEl) return;
            const entry = document.createElement('div');
            const timestamp = new Date().toLocaleTimeString();
            entry.className = `log-${type}`;
            entry.textContent = `[${timestamp}] ${message}`;
            consoleEl.appendChild(entry);
            consoleEl.scrollTop = consoleEl.scrollHeight;
        }
    };

    // --- ScriptManager, Executor, MultiTab modules are identical, no changes needed ---
    const ScriptManager={async saveScriptFromEditor(){const e=document.getElementById("trix-script-name").value.trim(),t=document.getElementById("trix-editor").value;e?t?(await GM_setValue(SCRIPT_PREFIX+e,t),UI.log(`Script '${e}' saved successfully.`,"info"),this.populateScriptSelector()):UI.log("Cannot save script: Editor is empty.","warn"):UI.log("Cannot save script: Name is required.","error")},async loadScriptToEditor(){const e=document.getElementById("trix-script-selector"),t=e.value;t?(document.getElementById("trix-editor").value=await GM_getValue(t,""),document.getElementById("trix-script-name").value=t.replace(SCRIPT_PREFIX,""),UI.log(`Script '${t.replace(SCRIPT_PREFIX,"")}' loaded into editor.`,"info")):UI.log("No script selected to load.","warn")},async deleteSelectedScript(){const e=document.getElementById("trix-script-selector"),t=e.value;t&&confirm(`Are you sure you want to delete the script '${t.replace(SCRIPT_PREFIX,"")}'?`)&&(await GM_deleteValue(t),UI.log(`Script '${t.replace(SCRIPT_PREFIX,"")}' deleted.`,"info"),this.populateScriptSelector())},async populateScriptSelector(){const e=document.getElementById("trix-script-selector");e.innerHTML='<option value="">-- Select a saved script --</option>';const t=await GM_listValues(),s=t.filter(e=>e.startsWith(SCRIPT_PREFIX));s.forEach(t=>{const s=document.createElement("option");s.value=t,s.textContent=t.replace(SCRIPT_PREFIX,""),e.appendChild(s)})},fetchAndRun(e){UI.log(`Fetching script from: ${e}`,"info"),GM.xmlHttpRequest({method:"GET",url:e,onload:function(t){t.status>=200&&t.status<300?(UI.log(`Successfully fetched script from ${e}. Executing...`,"info"),Executor.execute(t.responseText)):UI.log(`Failed to fetch script. Status: ${t.status}`,"error")},onerror:function(e){UI.log(`Error fetching script: ${e.statusText}`,"error")}})}};
    const Executor={execute(e){if(!e.trim())return void UI.log("Execution skipped: script is empty.","warn");UI.log("Executing script...","info");try{const t=this.createAPI(),s=new Function("TriX",e);s(t)}catch(e){UI.log(`Execution Error: ${e.message}`,"error"),console.error("TriX Executor Error:",e)}},createAPI:()=>({log:(e,t="log")=>{const s="object"==typeof e?JSON.stringify(e):String(e);UI.log(s,t)},broadcast:e=>{MultiTab.broadcast(e)},query:(e,t="text")=>{const s=document.querySelector(e);return s?"html"===t?s.innerHTML:"value"===t?s.value:"element"===t?s:s.textContent:null},queryAll:(e,t="text")=>{const s=document.querySelectorAll(e);return Array.from(s).map(e=>"html"===t?e.innerHTML:"value"===t?e.value:"element"===t?e:e.textContent)}})};
    const MultiTab={init(){GM_addValueChangeListener(BROADCAST_CHANNEL,this.listener)},listener(e,t,s,o){o&&s.senderId!==TAB_ID&&UI.log(`Received broadcast: ${JSON.stringify(s.payload)}`,"broadcast")},broadcast(e){const t={senderId:TAB_ID,timestamp:Date.now(),payload:e};GM_setValue(BROADCAST_CHANNEL,t),UI.log(`Broadcast sent: ${JSON.stringify(e)}`,"broadcast")}};

    // --- Main Initialization ---
    function main() {
        if (!document.body) {
            console.warn('TriX Executor: document.body not ready, retrying in 200ms.');
            setTimeout(main, 200);
            return;
        }
        console.log('TriX Executor: Body ready. Initializing UI and systems.');
        UI.init();
        MultiTab.init();
        UI.togglePanel(false); // Ensure panel is hidden and button is visible on start
    }

    setTimeout(main, 0);

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址