Script: Hacker News
Hacker News
A simple GM script to make browsing Hacker News easier. With this script I can click anywhere on the comment to collapse it. But it keeps links and text selection behavior working normally. Very convenient.
// ==UserScript==// @name Hacker News: Click to Collapse Threads// @match https://news.ycombinator.com/item?id=*// @run-at document-idle// @grant none// ==/UserScript==
(() => { const collapsedRows = new WeakSet();
function getIndent(row) { const indentCell = row.querySelector('td.ind'); const indent = Number.parseInt(indentCell?.getAttribute('indent'), 10); return Number.isNaN(indent) ? null : indent; }
function updateVisibility() { const collapsedIndents = [];
document.querySelectorAll('tr.athing.comtr').forEach(row => { const indent = getIndent(row); if (indent === null) return;
while ( collapsedIndents.length && collapsedIndents[collapsedIndents.length - 1] >= indent ) { collapsedIndents.pop(); }
row.hidden = collapsedIndents.length > 0;
if (collapsedRows.has(row)) { collapsedIndents.push(indent); } }); }
document.addEventListener('click', event => { if (!(event.target instanceof Element)) return;
const commentText = event.target.closest('.commtext'); const row = commentText?.closest('tr.athing.comtr');
// Keep links and text selection working normally. if (!row || event.target.closest('a')) return; if (window.getSelection()?.toString()) return;
if (collapsedRows.has(row)) { collapsedRows.delete(row); } else { collapsedRows.add(row); }
updateVisibility(); });})();