Registrati Accedi
n/chit-chat · 2025-08-20 · Modificato · 149 visualizzazioni
u/LOsEEDiamante
n/chit-chatu/LOsEE · 2025-08-20

Nodeloc帖子增强油猴脚本 标注已读 隐藏 高亮 置顶 等

众所周知 Discourse系统有新的文章回复会重新把文章顶起,并失去已读(颜色变浅)标注,这样就很可能点进一个已经看过且不想再进入的帖子,于是求助AI,做出来一个增强脚本

预览图片样式和内容:

脚本代码:

[upvote]

// ==UserScript==
// @name         Nodeloc帖子增强工具
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  在的帖子列表和帖子页面添加“标记已读”、“隐藏”、“高亮”和“置顶”功能,并提供一个统一的记录管理中心。
// @match        https://www.nodeloc.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @grant        GM_deleteValue
// @grant        GM_listValues
// ==/UserScript==

(function() {
    'use strict';

    const STORAGE_PREFIX = 'discourse_topic_';

    // --- 样式定义 ---
    GM_addStyle(`
        .topic-list-item.tm-read .title { color: #888 !important; }
        body.dark .topic-list-item.tm-read .title { color: #666 !important; }
        .topic-list-item.tm-read .topic-excerpt, .topic-list-item.tm-read .badge-category, .topic-list-item.tm-read .posters { opacity: 0.6; }
        .topic-list-item.tm-highlight { background-color: #fef8e0 !important; }
        body.dark .topic-list-item.tm-highlight { background-color: #4a412a !important; }
        .tm-controls { display: flex; gap: 10px; margin-top: 8px; align-items: center; flex-wrap: wrap; }
        .tm-btn { background: none; border: 1px solid #ccc; border-radius: 4px; padding: 2px 6px; font-size: 12px; cursor: pointer; transition: background-color 0.2s, color 0.2s; white-space: nowrap; }
        body.dark .tm-btn { border-color: #555; color: #ddd; }
        .tm-btn:hover { background-color: #e9e9e9; }
        body.dark .tm-btn:hover { background-color: #333; }
        .tm-btn.active { background-color: #007bff; color: white; border-color: #007bff; }
        body.dark .tm-btn.active { background-color: #009966; border-color: #009966; }
        .tm-btn.tm-btn-danger { border-color: #dc3545; color: #dc3545; }
        .tm-btn.tm-btn-danger:hover { background-color: #dc3545; color: white; }
        body.dark .tm-btn.tm-btn-danger { border-color: #a02a37; color: #e56d79; }
        body.dark .tm-btn.tm-btn-danger:hover { background-color: #a02a37; color: white; }
        #tm-pinned-container-wrapper { border: 1px solid var(--tertiary-300, #cde8e1); border-radius: 5px; margin-bottom: 15px; overflow: hidden; display: none; }
        body.dark #tm-pinned-container-wrapper { border-color: #333; }
        .tm-pinned-header { font-size: 14px; font-weight: bold; padding: 8px 12px; background-color: var(--tertiary-100, #f2fbf8); }
        body.dark .tm-pinned-header { background-color: #2c3e38; }
        .tm-topic-controls { display: flex; gap: 8px; margin-top: 8px; }
        #topic-title .title-wrapper.tm-topic-title-read h1 a, #topic-title .title-wrapper.tm-topic-title-read h1 span { color: #888 !important; }
        body.dark #topic-title .title-wrapper.tm-topic-title-read h1 a, body.dark #topic-title .title-wrapper.tm-topic-title-read h1 span { color: #666 !important; }
        #topic-title .title-wrapper.tm-topic-title-highlight { background-color: #fef8e0; padding: 2px 5px; border-radius: 3px; }
        body.dark #topic-title .title-wrapper.tm-topic-title-highlight { background-color: #4a412a; }
        #tm-records-btn { margin-left: 8px; }
        .tm-modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1001; display: flex; align-items: center; justify-content: center; }
        .tm-modal-content { background: #fff; padding: 20px; border-radius: 8px; width: 90%; max-width: 650px; max-height: 80vh; display: flex; flex-direction: column; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        body.dark .tm-modal-content { background: #252525; color: #ddd; }
        .tm-modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px; flex-shrink: 0; }
        body.dark .tm-modal-header { border-bottom-color: #444; }
        .tm-modal-title { font-size: 18px; font-weight: bold; margin: 0; }
        .tm-modal-close { font-size: 24px; cursor: pointer; background: none; border: none; color: #888; padding: 0 5px; line-height: 1; }
        body.dark .tm-modal-close { color: #aaa; }
        .tm-modal-body { flex-grow: 1; overflow-y: auto; }
        .tm-modal-tabs { display: flex; gap: 5px; margin-bottom: 15px; padding-top: 8px; }
        .tm-modal-tab { flex-grow: 1; position: relative; }
        .tm-modal-tab .tm-btn { width: 100%; }
        .tm-tab-count { background-color: #e45735; color: white; border-radius: 10px; padding: 1px 6px; font-size: 11px; font-weight: bold; position: absolute; top: -8px; right: -5px; line-height: 1.4; z-index: 1; }
        body.dark .tm-tab-count { background-color: #c84a36; }
        .tm-confirm-title { font-weight: bold; margin: 10px 0; padding: 10px; background-color: #f5f5f5; border-radius: 4px; word-break: break-all; }
        body.dark .tm-confirm-title { background-color: #222; }
        .tm-records-list { list-style: none; padding: 0; margin:0; }
        .tm-records-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 5px; border-bottom: 1px solid #f0f0f0; }
        body.dark .tm-records-item { border-bottom-color: #444; }
        .tm-records-item:last-child { border-bottom: none; }
        .tm-records-item a { text-decoration: none; color: var(--primary-high, #222); flex-grow: 1; margin-right: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        body.dark .tm-records-item a { color: var(--primary-high, #ddd); }
        .tm-records-item-controls { flex-shrink: 0; }
        .tm-records-item-controls button { margin-left: 8px; }
        .tm-empty-list-placeholder { color: #888; text-align: center; padding: 30px; font-style: italic; }
    `);

    const dataManager = {
        get: (topicId) => GM_getValue(STORAGE_PREFIX + topicId, {}),
        set: (topicId, data) => GM_setValue(STORAGE_PREFIX + topicId, data),
        update: (topicId, key, value) => {
            const data = dataManager.get(topicId);
            data[key] = value;
            const hasTrueValue = Object.keys(data).some(k => k !== 'title' && data[k]);
            if (!hasTrueValue) {
                GM_deleteValue(STORAGE_PREFIX + topicId);
            } else {
                dataManager.set(topicId, data);
            }
        },
        delete: (topicId) => GM_deleteValue(STORAGE_PREFIX + topicId),
        list: () => GM_listValues(),
        getAllData: () => dataManager.list()
            .filter(key => key.startsWith(STORAGE_PREFIX))
            .map(key => ({ topicId: key.replace(STORAGE_PREFIX, ''), ...GM_getValue(key) }))
    };

    const uiManager = {
        createModal: (id, title, bodyHtml, footerHtml = '') => {
            document.getElementById(id)?.remove();
            const overlay = document.createElement('div');
            overlay.id = id;
            overlay.className = 'tm-modal-overlay';
            overlay.style.display = 'none';
            overlay.innerHTML = `
                <div class="tm-modal-content">
                    <div class="tm-modal-header"><h2 class="tm-modal-title">${title}</h2><button class="tm-modal-close">&times;</button></div>
                    <div class="tm-modal-body">${bodyHtml}</div>
                    ${footerHtml ? `<div class="tm-modal-footer">${footerHtml}</div>` : ''}`;
            document.body.appendChild(overlay);
            const close = () => { overlay.style.display = 'none'; };
            overlay.querySelector('.tm-modal-close').onclick = close;
            overlay.addEventListener('click', e => { if (e.target === overlay) close(); });
            return overlay;
        },
        showConfirmation: (title, onConfirm) => {
            const modal = uiManager.createModal('tm-confirm-modal', '确认操作',
                `<p>您确定要隐藏这个帖子吗?</p><div class="tm-confirm-title">${title}</div>`,
                `<button id="tm-confirm-cancel" class="tm-btn">取消</button><button id="tm-confirm-ok" class="tm-btn active">确定</button>`
            );
            modal.style.display = 'flex';
            document.getElementById('tm-confirm-ok').onclick = () => { onConfirm(); modal.style.display = 'none'; };
            document.getElementById('tm-confirm-cancel').onclick = () => modal.style.display = 'none';
        },
        showRecordsModal: () => {
            const modal = uiManager.createModal('tm-records-modal', '查看记录', `
                <div id="tm-records-tabs" class="tm-modal-tabs"></div>
                <ul id="tm-records-list-ul" class="tm-records-list"></ul>`);
            const tabsContainer = modal.querySelector('#tm-records-tabs');
            const listEl = modal.querySelector('#tm-records-list-ul');
            const tabConfigs = [
                { key: 'hidden', label: '隐藏' }, { key: 'pinned', label: '置顶' },
                { key: 'highlight', label: '高亮' }, { key: 'read', label: '已读' }
            ];

            const populateList = (filterKey) => {
                const allData = dataManager.getAllData();
                listEl.innerHTML = '';
                const topics = allData.filter(item => item[filterKey]);
                const currentTabConfig = tabConfigs.find(t => t.key === filterKey);

                if (topics.length === 0) {
                    listEl.innerHTML = `<li class="tm-empty-list-placeholder">没有被标记为“${currentTabConfig.label}”的帖子。</li>`;
                    return;
                }
                topics.forEach(({ topicId, title }) => {
                    const item = document.createElement('li');
                    item.className = 'tm-records-item';
                    item.innerHTML = `
                        <a href="/t/${topicId}" target="_blank" title="${title}">${title || `帖子 #${topicId}`}</a>
                        <div class="tm-records-item-controls">
                            <button class="tm-btn action-btn">取消${currentTabConfig.label}</button>
                            <button class="tm-btn tm-btn-danger delete-btn">删除记录</button>
                        </div>`;
                    item.querySelector('.action-btn').onclick = () => {
                        dataManager.update(topicId, filterKey, false);
                        uiManager.updateTabCounts();
                        populateList(filterKey);
                        document.querySelectorAll(`tr[data-topic-id="${topicId}"]`).forEach(row => {
                            const btn = Array.from(row.querySelectorAll('.tm-controls .tm-btn')).find(b => b.dataset.key === filterKey);
                            if (btn) btn.classList.remove('active');
                            features.applyRowStyles(row, dataManager.get(topicId));
                        });
                    };
                    item.querySelector('.delete-btn').onclick = () => {
                        dataManager.delete(topicId);
                        uiManager.updateTabCounts();
                        populateList(filterKey);
                        document.querySelectorAll(`tr[data-topic-id="${topicId}"]`).forEach(row => {
                           features.applyRowStyles(row, {}); // Reset styles
                        });
                    };
                    listEl.appendChild(item);
                });
            };

            tabConfigs.forEach(tab => {
                const tabWrapper = document.createElement('div');
                tabWrapper.className = 'tm-modal-tab';
                const tabBtn = document.createElement('button');
                tabBtn.className = 'tm-btn';
                tabBtn.textContent = tab.label;
                tabBtn.dataset.key = tab.key;
                tabBtn.onclick = () => {
                    tabsContainer.querySelectorAll('.tm-btn').forEach(b => b.classList.remove('active'));
                    tabBtn.classList.add('active');
                    populateList(tab.key);
                };
                tabWrapper.appendChild(tabBtn);
                tabsContainer.appendChild(tabWrapper);
            });

            uiManager.updateTabCounts();
            modal.style.display = 'flex';
            tabsContainer.querySelector('button[data-key="hidden"]').click();
        },
        updateTabCounts: () => {
            const tabsContainer = document.getElementById('tm-records-tabs');
            if (!tabsContainer) return;
            const allData = dataManager.getAllData();
            tabsContainer.querySelectorAll('.tm-modal-tab').forEach(tabWrapper => {
                const key = tabWrapper.querySelector('.tm-btn').dataset.key;
                const count = allData.filter(item => item[key]).length;
                let countEl = tabWrapper.querySelector('.tm-tab-count');
                if (count > 0) {
                    if (!countEl) {
                        countEl = document.createElement('span');
                        countEl.className = 'tm-tab-count';
                        tabWrapper.appendChild(countEl);
                    }
                    countEl.textContent = count;
                } else if (countEl) {
                    countEl.remove();
                }
            });
        },
        addManagementButton: () => {
            if (document.getElementById('tm-records-btn')) return;
            const userMenu = document.querySelector('.d-header .header-buttons .user-menu-panel');
            if (userMenu) {
                const btn = document.createElement('button');
                btn.id = 'tm-records-btn';
                btn.className = 'btn no-text btn-icon icon btn-flat';
                btn.title = '查看记录';
                btn.innerHTML = `<svg class="fa d-icon d-icon-list-ul svg-icon svg-string" aria-hidden="true"><use href="#list-ul"></use></svg>`;
                btn.onclick = () => uiManager.showRecordsModal();
                userMenu.parentNode.insertBefore(btn, userMenu);
            }
        }
    };

    const features = {
        applyRowStyles(row, data) {
            row.classList.toggle('tm-read', !!data.read);
            row.classList.toggle('tm-highlight', !!data.highlight);
            row.style.display = data.hidden ? 'none' : '';

            const pinnedContainerWrapper = document.getElementById('tm-pinned-container-wrapper');
            const pinnedBody = pinnedContainerWrapper?.querySelector('.topic-list-body');
            const topicListBody = document.querySelector('table.topic-list:not(#tm-pinned-container-wrapper table) tbody.topic-list-body');

            if (data.pinned && !data.hidden) {
                if (row.parentElement !== pinnedBody) pinnedBody?.prepend(row);
            } else {
                if (row.parentElement === pinnedBody) topicListBody?.prepend(row);
            }

            if(pinnedContainerWrapper && pinnedBody) {
                const hasVisiblePinnedItems = pinnedBody.querySelector('tr:not([style*="display: none"])');
                pinnedContainerWrapper.style.display = hasVisiblePinnedItems ? 'block' : 'none';
            }

            row.querySelectorAll('.tm-controls .tm-btn').forEach(btn => {
                btn.classList.toggle('active', !!data[btn.dataset.key]);
                if (btn.dataset.key === 'pinned') btn.textContent = data.pinned ? '取消置顶' : '置顶';
                if (data.pinned) {
                    if (['read', 'hidden'].includes(btn.dataset.key)) btn.style.display = 'none';
                } else {
                    btn.style.display = '';
                }
            });
        },

        processTopicList() {
            const topicListBody = document.querySelector('table.topic-list tbody.topic-list-body');
            if (!topicListBody) return;

            let pinnedContainerWrapper = document.getElementById('tm-pinned-container-wrapper');
            if (!pinnedContainerWrapper) {
                const listArea = document.getElementById('list-area');
                if (!listArea) return;
                pinnedContainerWrapper = document.createElement('div');
                pinnedContainerWrapper.id = 'tm-pinned-container-wrapper';
                pinnedContainerWrapper.innerHTML = `
                    <div class="tm-pinned-header">📌 置顶的帖子</div>
                    <table class="topic-list"><tbody class="topic-list-body"></tbody></table>`;

                const showMoreBar = listArea.querySelector('.show-more');
                if (showMoreBar) {
                     listArea.insertBefore(pinnedContainerWrapper, showMoreBar.nextSibling);
                } else {
                    const listContainer = topicListBody.closest('.topic-list');
                    listContainer?.parentNode.insertBefore(pinnedContainerWrapper, listContainer);
                }
            }

            document.querySelectorAll('tr.topic-list-item').forEach(row => {
                if (row.querySelector('.tm-controls')) {
                    this.applyRowStyles(row, dataManager.get(row.dataset.topicId));
                    return;
                }
                const topicId = row.dataset.topicId;
                if (!topicId) return;

                const controlsContainer = document.createElement('div');
                controlsContainer.className = 'tm-controls';

                const createListButton = (text, key, action) => {
                    const btn = document.createElement('button');
                    btn.textContent = text;
                    btn.className = 'tm-btn';
                    btn.dataset.key = key;

                    btn.addEventListener('click', (e) => {
                        e.preventDefault(); e.stopPropagation();

                        const isCurrentlyActive = !!dataManager.get(topicId)[key];
                        const performAction = () => {
                            const isActive = !isCurrentlyActive;
                            dataManager.update(topicId, key, isActive);
                            action(row, isActive);
                            this.applyRowStyles(row, dataManager.get(topicId));
                        };

                        if (key === 'hidden' && !isCurrentlyActive) {
                            const title = row.querySelector('a.title')?.textContent.trim() || `帖子 #${topicId}`;
                            dataManager.update(topicId, 'title', title);
                            uiManager.showConfirmation(title, performAction);
                        } else {
                            performAction();
                        }
                    });
                    return btn;
                };

                controlsContainer.append(
                    createListButton('已读', 'read', ()=>{}),
                    createListButton('高亮', 'highlight', ()=>{}),
                    createListButton('置顶', 'pinned', ()=>{}),
                    createListButton('隐藏', 'hidden', ()=>{})
                );

                const targetCell = row.querySelector('td.main-link');
                if (targetCell) targetCell.appendChild(controlsContainer);
                this.applyRowStyles(row, dataManager.get(topicId));
            });
        },

        processSingleTopicView() {
            const topicId = document.getElementById('topic')?.dataset.topicId;
            const target = document.querySelector('.topic-details');
            if (!topicId || !target || document.querySelector('.tm-topic-controls')) return;

            const controlsContainer = document.createElement('div');
            controlsContainer.className = 'tm-topic-controls';

            const topicTitleElement = document.querySelector('#topic-title .title-wrapper');
            const updateTitleStyles = () => {
                if (!topicTitleElement) return;
                const data = dataManager.get(topicId);
                topicTitleElement.classList.toggle('tm-topic-title-read', !!data.read);
                topicTitleElement.classList.toggle('tm-topic-title-highlight', !!data.highlight);
            };

            const createTopicButton = (text, key) => {
                const btn = document.createElement('button');
                btn.className = 'tm-btn';
                btn.textContent = text;
                if (dataManager.get(topicId)[key]) btn.classList.add('active');
                btn.addEventListener('click', (e) => {
                    e.preventDefault(); e.stopPropagation();
                    const isActive = !dataManager.get(topicId)[key];
                    dataManager.update(topicId, key, isActive);
                    updateTitleStyles();
                    btn.classList.toggle('active', isActive);
                });
                return btn;
            };

            dataManager.update(topicId, 'title', document.querySelector('#topic-title .title-wrapper').textContent.trim());
            controlsContainer.append(createTopicButton('标记已读', 'read'), createTopicButton('高亮主题', 'highlight'));
            target.appendChild(controlsContainer);
            updateTitleStyles();
        }
    };

    function runAllFeatures() {
        uiManager.addManagementButton();
        features.processTopicList();
        features.processSingleTopicView();
    }

    let debounceTimer;
    const observer = new MutationObserver(() => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(runAllFeatures, 250);
    });

    function startObserving() {
        const mainOutlet = document.getElementById('main-outlet');
        if (mainOutlet) {
            runAllFeatures();
            observer.observe(mainOutlet, { childList: true, subtree: true });
        } else {
            setTimeout(startObserving, 300);
        }
    }

    startObserving();

})();

[/upvote]

1
4
Accedi per partecipare alla discussione.

4 risposte

Ordinamento
  1. BearPaw Maestro 2025-08-20

    OP棒棒哒 :xhj16:

    1
  2. ketto 🔥 Platino 3 ANNI 2025-08-20

    嗯,不错!感谢楼主的分享

    0
  3. anne Diamante 2025-08-20

    感谢分享

    0
  4. zhangyx Maestro 2 ANNI 2025-08-20

    看看~

    0