Telegram Web K Sidebar Toggler

侧边栏折叠脚本,支持在油猴菜单中开启“记住状态”功能。

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

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Telegram Web K Sidebar Toggler
// @license MIT
// @namespace    http://tampermonkey.net/
// @version      6.0
// @description  侧边栏折叠脚本,支持在油猴菜单中开启“记住状态”功能。
// @author       Gemini
// @match        https://web.telegram.org/k/*
// @match        https://web.telegram.org/*
// @icon         https://web.telegram.org/favicon.ico
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// ==/UserScript==

(function() {
    'use strict';

    // ================= 配置与状态管理 =================
    const KEY_REMEMBER = 'tg_sidebar_remember_mode'; // 是否开启记忆功能的开关
    const KEY_STATUS = 'tg_sidebar_hidden_status';   // 实际的折叠状态

    // 读取配置(默认为 true,开启记忆功能,更符合直觉)
    let isRememberEnabled = GM_getValue(KEY_REMEMBER, true);

    // 初始化状态:如果开启了记忆,则读取上次状态;否则默认为不折叠
    let isFullscreen = isRememberEnabled ? GM_getValue(KEY_STATUS, false) : false;

    // ================= 样式注入 =================
    const css = `
        /* 隐藏侧边栏 */
        body.tg-fullscreen-mode .sidebar {
            display: none !important;
        }
        body.tg-fullscreen-mode .chat {
            width: 100% !important;
            max-width: 100% !important;
            flex: 0 0 100% !important;
        }

        /* 按钮样式 */
        #tg-side-toggle {
            position: fixed;
            top: 50%;
            left: 0;
            transform: translateY(-50%);
            width: 18px;
            height: 50px;
            border-radius: 0 30px 30px 0;
            background-color: rgba(51, 144, 236, 0.5);
            color: #fff;
            cursor: pointer;
            z-index: 99999;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: monospace;
            font-size: 14px;
            font-weight: bold;
            user-select: none;
            backdrop-filter: blur(2px);
            transition: background-color 0.15s;
        }
        #tg-side-toggle:hover {
            background-color: rgba(51, 144, 236, 1);
        }
    `;
    GM_addStyle(css);

    // ================= 逻辑初始化 =================

    // 1. 如果需要,立即应用折叠状态(防止页面加载时闪烁)
    if (isFullscreen) {
        document.body.classList.add('tg-fullscreen-mode');
    }

    // 2. 创建按钮
    const toggleBtn = document.createElement('div');
    toggleBtn.id = 'tg-side-toggle';
    // 根据初始状态决定箭头方向
    toggleBtn.innerHTML = isFullscreen ? '>' : '<';
    toggleBtn.title = "折叠/展开侧边栏";
    document.body.appendChild(toggleBtn);

    let sidebarSelector = '.sidebar';

    // 3. 按钮位置更新函数
    function updateButtonPosition() {
        if (isFullscreen) {
            toggleBtn.style.left = '0px';
        } else {
            const sidebar = document.querySelector(sidebarSelector);
            if (sidebar) {
                const width = sidebar.getBoundingClientRect().width;
                toggleBtn.style.left = width + 'px';
            } else {
                toggleBtn.style.left = '320px';
            }
        }
    }

    // 4. 点击事件处理
    toggleBtn.onclick = function() {
        if (!isFullscreen) {
            // -> 执行折叠
            document.body.classList.add('tg-fullscreen-mode');
            toggleBtn.innerHTML = '>';
            isFullscreen = true;
        } else {
            // -> 执行展开
            document.body.classList.remove('tg-fullscreen-mode');
            toggleBtn.innerHTML = '<';
            isFullscreen = false;
        }

        // 如果开启了记忆功能,保存当前状态
        if (isRememberEnabled) {
            GM_setValue(KEY_STATUS, isFullscreen);
        }

        updateButtonPosition();
        setTimeout(() => window.dispatchEvent(new Event('resize')), 0);
    };

    // 5. 监听与循环检查
    window.addEventListener('resize', () => requestAnimationFrame(updateButtonPosition));

    const initInterval = setInterval(() => {
        const sidebar = document.querySelector(sidebarSelector);
        if (sidebar && sidebar.offsetWidth > 0) {
            updateButtonPosition();
            clearInterval(initInterval);
        }
    }, 200);

    const observer = new MutationObserver(() => {
        if (!document.getElementById('tg-side-toggle')) {
            document.body.appendChild(toggleBtn);
            if (isFullscreen) document.body.classList.add('tg-fullscreen-mode');
        }
        updateButtonPosition();
    });
    observer.observe(document.body, { childList: true, subtree: true });


    // ================= 油猴/暴力猴 菜单功能 =================

    let menuId = null;

    // 刷新菜单显示的函数
    function updateMenuCommand() {
        // 如果之前注册过,先移除,避免重复
        if (menuId !== null) {
            GM_unregisterMenuCommand(menuId);
        }

        // 根据当前状态显示不同的图标和文字
        const statusIcon = isRememberEnabled ? '✅' : '⬜';
        const menuText = `${statusIcon} 记住侧边栏折叠状态`;

        menuId = GM_registerMenuCommand(menuText, function() {
            // 切换开关
            isRememberEnabled = !isRememberEnabled;
            GM_setValue(KEY_REMEMBER, isRememberEnabled);

            // 如果刚刚开启,立即保存当前状态
            if (isRememberEnabled) {
                GM_setValue(KEY_STATUS, isFullscreen);
                alert('已开启记忆功能:下次刷新将保持当前侧边栏状态。');
            } else {
                alert('已关闭记忆功能:下次刷新将恢复默认展开状态。');
            }

            // 更新菜单文字
            updateMenuCommand();
        });
    }

    // 初始注册菜单
    updateMenuCommand();

})();