I'm trying out GPT-4 and had it write me a script to navigate the HN comments tree sequentially, as I often wished. This is the start of an era where UIs can be remixed on the fly by end users, something I've always wished for. Here it is in its full sloppiness, but working:
(function () {
let currentIndex = 0;
let comments = [];
function buildCommentTree() {
let commentElems = Array.from(document.querySelectorAll('.comment-tree .comtr'));
let commentTree = [];
let stack = [];
commentElems.forEach(elem => {
let level = parseInt(elem.querySelector('.ind img').getAttribute('width')) / 40;
let comment = elem.querySelector('.comment span');
let commentObj = { level, comment };
if (!stack.length) {
commentTree.push(commentObj);
} else {
while (stack[stack.length - 1].level >= level) {
stack.pop();
}
if (!stack[stack.length - 1].children) {
stack[stack.length - 1].children = [];
}
stack[stack.length - 1].children.push(commentObj);
}
stack.push(commentObj);
});
return commentTree;
}
function flattenCommentTree(tree, arr, parentComment = null) {
tree.forEach(node => {
arr.push({ comment: node.comment, parentComment });
if (node.children) {
flattenCommentTree(node.children, arr, node.comment);
}
});
}
function displayComment(comment, parentComment) {
let parentCommentHTML = parentComment ? `<div style="position: fixed; top: 20%; left: 50%; transform: translate(-50%, 0); background-color: white; border: 1px solid black; padding: 20px;"><strong>Parent Comment:</strong><br>${parentComment.innerHTML}</div>` : '';
let currentCommentHTML = `<div style="position: fixed; top: 60%; left: 50%; transform: translate(-50%, 0); background-color: white; border: 1px solid black; padding: 20px;"><strong>Current Comment:</strong><br>${comment.innerHTML}</div>`;
document.body.innerHTML = parentCommentHTML + currentCommentHTML;
}
function nextComment() {
if (currentIndex < comments.length - 1) {
currentIndex++;
displayComment(comments[currentIndex].comment, comments[currentIndex].parentComment);
} else {
alert('No more comments to show.');
}
}
function prevComment() {
if (currentIndex > 0) {
currentIndex--;
displayComment(comments[currentIndex].comment, comments[currentIndex].parentComment);
} else {
alert('No previous comments to show.');
}
}
let commentTree = buildCommentTree();
flattenCommentTree(commentTree, comments);
displayComment(comments[currentIndex]);
document.addEventListener('keydown', e => {
if (e.code === 'ArrowRight') {
nextComment();
} else if (e.code === 'ArrowLeft') {
prevComment();
}
});
console.log('Hacker News comment slideshow is running. Use the right arrow key to go to the next comment and the left arrow key to go back.');
})();