Greasy Fork

Greasy Fork is available in English.

TriX Core Library

Core logic library for the TriX Executor. Not intended for direct installation.

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.icu/scripts/541461/1618060/TriX%20Core%20Library.js

// ==UserScript==
// @name        TriX Core Library
// @namespace   https://github.com/YourUsername/TriX-Executor
// @version     1.4.0
// @description Core logic library for the TriX Executor. Not intended for direct installation.
// @author      You
// @license     MIT
// ==/UserScript==

const TriX_Core = (function() {
    'use strict';

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

    // --- TabManager Module ---
    const TabManager = {
        tabs:[], myTabInfo:{}, uiInitialized:false, isMaster:false,
        init(username){this.myTabInfo={id:TAB_ID,username:username,loadTime:LOAD_TIME,lastSeen:Date.now()};GM_addValueChangeListener(TAB_LIST_KEY,(name,old_value,new_value,remote)=>{if(remote)this.pruneAndRefresh(new_value)});this.register();setInterval(()=>this.register(),HEARTBEAT_INTERVAL);window.addEventListener('beforeunload',()=>this.unregister())},
        async register(){let currentTabs=await GM_getValue(TAB_LIST_KEY,[]);const now=Date.now();currentTabs=currentTabs.filter(tab=>now-tab.lastSeen<STALE_TAB_TIMEOUT);this.myTabInfo.lastSeen=now;const myIndex=currentTabs.findIndex(tab=>tab.id===TAB_ID);if(myIndex>-1){currentTabs[myIndex]=this.myTabInfo}else{currentTabs.push(this.myTabInfo)}await GM_setValue(TAB_LIST_KEY,currentTabs);this.pruneAndRefresh(currentTabs)},
        async unregister(){let currentTabs=await GM_getValue(TAB_LIST_KEY,[]);currentTabs=currentTabs.filter(tab=>tab.id!==TAB_ID);await GM_setValue(TAB_LIST_KEY,currentTabs)},
        pruneAndRefresh(tabList){this.tabs=tabList;this.updateTabCountUI();this.checkMasterStatus()},
        updateTabCountUI(){const count=this.tabs.length;const openBtnBadge=document.getElementById('trix-open-btn-badge');const headerBadge=document.getElementById('trix-header-tab-counter');if(openBtnBadge)openBtnBadge.textContent=count;if(headerBadge)headerBadge.textContent=count},
        checkMasterStatus(){this.isMaster=this.amIMaster();if(this.isMaster&&!this.uiInitialized){this.initUI()}},
        amIMaster(){if(!this.myTabInfo.username||this.myTabInfo.username.startsWith('Guest_'))return true;const competingTabs=this.tabs.filter(tab=>tab.username===this.myTabInfo.username);if(competingTabs.length===0)return true;const earliestLoadTime=Math.min(...competingTabs.map(tab=>tab.loadTime));return this.myTabInfo.loadTime===earliestLoadTime},
        initUI(){if(this.uiInitialized)return;console.log('[TriX Core] This tab is the master. Initializing UI.');this.uiInitialized=true;TriX_UI.init();MultiTab.init()}
    };

    // --- ScriptManager, Executor, MultiTab Modules (minified) ---
    const ScriptManager={async saveScriptFromEditor(){const e=document.getElementById("trix-save-name").value.trim(),t=document.getElementById("trix-editor").value;e?t?(await GM_setValue(SCRIPT_PREFIX+e,t),TriX_UI.log(`Script '${e}' saved.`,"info"),this.populateScriptList(SCRIPT_PREFIX+e)):TriX_UI.log("Cannot save: Editor is empty.","warn"):TriX_UI.log("Cannot save: Name is required.","error")},async loadScriptToEditor(e){if(!e)return TriX_UI.log("Invalid script key.","error");const t=await GM_getValue(e,""),s=e.replace(SCRIPT_PREFIX,"");document.getElementById("trix-editor").value=t,document.getElementById("trix-save-name").value=s,TriX_UI.log(`Loaded script: ${s}`,"info"),TriX_UI.currentScriptName=s,TriX_UI.setActiveScriptItem(e)},async deleteCurrentScript(){const e=TriX_UI.currentScriptName;e&&confirm(`Are you sure you want to delete '${e}'?`)&&(await GM_deleteValue(SCRIPT_PREFIX+e),TriX_UI.log(`Script '${e}' deleted.`,"info"),document.getElementById("trix-editor").value="",document.getElementById("trix-save-name").value="",TriX_UI.currentScriptName="",this.populateScriptList())},async populateScriptList(e=null){const t=document.getElementById("trix-script-list");t.innerHTML="";const s=(await GM_listValues()).filter(e=>e.startsWith(SCRIPT_PREFIX));s.sort().forEach(e=>{const s=document.createElement("div");s.className="trix-script-item",s.textContent=e.replace(SCRIPT_PREFIX,""),s.dataset.scriptKey=e,t.appendChild(s)}),TriX_UI.setActiveScriptItem(e||TriX_UI.currentScriptName?SCRIPT_PREFIX+TriX_UI.currentScriptName:null)}};
    const Executor={execute(e){if(!e.trim())return void TriX_UI.log("Execution skipped: script is empty.","warn");TriX_UI.log("Executing script...","info");try{const t=this.createAPI(),s=new Function("TriX",e);s(t)}catch(e){TriX_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);TriX_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&&TriX_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),TriX_UI.log(`Broadcast sent: ${JSON.stringify(e)}`,"broadcast")}};

    // Expose modules to the global scope for other @require'd scripts to use.
    return { TabManager, ScriptManager, Executor, MultiTab };
})();