Collapse comments

Add a button to collapse comments of lwn.net

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name        Collapse comments
// @namespace   https://franklinyu.github.io
// @match       https://lwn.net/Articles/*
// @grant       none
// @version     0.1
// @author      FranklinYu
// @description Add a button to collapse comments of lwn.net
// @license     Apache-2.0
// ==/UserScript==

const COLLAPSED = '▷'
const EXPANDED = '▽'

function getTree(comment) {
  const tree = comment?.nextElementSibling
  if (tree && tree.classList.contains('Comment')) {
    return tree
  } else {
    return null
  }
}

for (const comment of document.getElementsByClassName('CommentBox')) {
  if (!getTree(comment)) {
    continue  // leaf comment
  }

  const toggle = document.createElement('button')
  comment.append(toggle)
  toggle.textContent = EXPANDED

  toggle.addEventListener('click', e => {
    const button = e.target
    const tree = getTree(button.parentElement)
    if (!tree) {
      console.warn('unexpected comment event: ', e)
    }

    if (button.textContent === EXPANDED) {
      button.textContent = COLLAPSED
      tree.style.display = 'none'
    } else {
      button.textContent = EXPANDED
      tree.style.display = ''
    }
  })
}