Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
madawei2699 committed Nov 14, 2024
1 parent f22e33d commit 295e51f
Showing 1 changed file with 89 additions and 57 deletions.
146 changes: 89 additions & 57 deletions src/content/platforms/RedditSummarizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ export class RedditSummarizer extends BaseSummarizer {
}

setupCommentObserver() {
// Monitor DOM changes for comment loading
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.addedNodes.length) {
// Check if we have comments after each DOM change
const comments = document.querySelectorAll('shreddit-comment');
// console.log('Found shreddit comments:', comments.length);
if (comments.length > 0) {
// console.log('First comment properties:', {
// postId: comments[0].postId,
// author: comments[0].author,
// hasTimeElement: !!comments[0].querySelector('a[rel="nofollow noopener noreferrer"]')
// });
this.addTLDRLinks();
}
}
Expand All @@ -32,35 +36,59 @@ export class RedditSummarizer extends BaseSummarizer {

initializeUI() {
this.sidebar = this.getOrCreateSidebar();

if (this.parser.isDiscussionPage()) {
this.addTLDRLinks();
}
}

addTLDRLinks() {
const topLevelComments = this.parser.getTopLevelComments();
console.log('Found comments:', topLevelComments.length);
// console.log('Found top level comments:', topLevelComments.length);

topLevelComments.forEach(comment => {
if (!comment.querySelector('.tldr-summarize-btn')) {
// console.log('Processing comment:', {
// id: comment.id,
// postId: comment.postId,
// author: comment.author,
// hasExistingTLDR: !!comment.querySelector('.tldr-summarize-btn'),
// hasTimeElement: !!comment.querySelector('a[rel="nofollow noopener noreferrer"]')
// });

const timeElement = comment.querySelector('a[rel="nofollow noopener noreferrer"]');
if (!timeElement) {
console.log('Failed to find time element for comment');
return;
}

if (comment.querySelector('.tldr-summarize-btn')) {
console.log('TLDR button already exists for comment');
return;
}

try {
const tldrContainer = document.createElement('span');
tldrContainer.className = 'tldr-btn-container';
tldrContainer.setAttribute('data-thread-id', comment.id); // Add thread ID to container
tldrContainer.setAttribute('data-thread-id', comment.postId || comment.id);

const tldrLink = document.createElement('a');
tldrLink.href = 'javascript:void(0)';
tldrLink.textContent = 'TL;DR';
tldrLink.className = 'tldr-summarize-btn';
tldrLink.style.marginLeft = '10px';
tldrLink.style.cursor = 'pointer';
tldrLink.style.color = '#666';

tldrLink.addEventListener('mousedown', (event) => {
event.preventDefault();
event.stopPropagation();

const button = event.currentTarget;
button.textContent = 'Summarizing...';
button.style.color = '#999';

this.summarizeThread({
id: comment.id,
text: comment.innerText
id: comment.postId || comment.id,
author: comment.author || 'anonymous',
replyCount: this.countReplies(comment),
text: comment.innerText,
button: button
});
}, true);

Expand All @@ -71,79 +99,72 @@ export class RedditSummarizer extends BaseSummarizer {

tldrContainer.appendChild(tldrLink);

const timeElement = comment.querySelector('a[rel="nofollow noopener noreferrer"]');
if (timeElement) {
timeElement.parentNode.insertBefore(tldrContainer, timeElement.nextSibling);
}
// console.log('Attempting to insert TLDR button');
timeElement.parentNode.insertBefore(tldrContainer, timeElement.nextSibling);
// console.log('Successfully inserted TLDR button');
} catch (error) {
console.error('Error adding TLDR link:', error);
}
});
}

async summarizeThread({ id, text }) {
async summarizeThread({ id, author, replyCount, text, button }) {
console.log('Starting to summarize thread:', id);
const tldrButton = document.querySelector(`[data-thread-id="${id}"] .tldr-summarize-btn`);

try {
// Update button state to loading
if (tldrButton) {
tldrButton.textContent = 'Summarizing...';
tldrButton.style.color = '#999';
}

// Prepare content for summarization
const threadContent = `
Thread content:
${text}
Thread content:
${text}
Please summarize focusing on:
1. Main points and arguments
2. Key insights or conclusions
3. Any consensus or disagreements
`;
Please summarize focusing on:
1. Main points and arguments
2. Key insights or conclusions
3. Any consensus or disagreements
`;

// Get summary from AI
const summary = await this.summarizeContent({
content: threadContent,
type: 'thread'
});

// Store summary data
this.threadSummaries.set(id, {
summary,
author,
replyCount,
timestamp: Date.now()
});

// Update UI
this.updateThreadSummary(id);

// Show sidebar if hidden
if (!this.sidebarVisible) {
this.handleToggleSidebar();
}

// Update button to success state
if (tldrButton) {
tldrButton.textContent = 'TL;DR ✓';
tldrButton.style.color = '#090';
// Update button with checkmark
if (button) {
button.textContent = 'TL;DR ✓';
button.style.color = '#090';
}

} catch (error) {
console.error('Thread summarization error:', error);
if (tldrButton) {
tldrButton.textContent = 'TL;DR (error)';
tldrButton.style.color = '#c00';
if (button) {
button.textContent = 'TL;DR (error)';
button.style.color = '#c00';
}
}
}

countReplies(commentElement) {
// Count all nested replies
const allReplies = commentElement.querySelectorAll('shreddit-comment');
return allReplies.length;
}

updateThreadSummary(threadId) {
const summary = this.threadSummaries.get(threadId);
if (!summary) {
console.error('No summary found for thread:', threadId);
return;
}
const threadData = this.threadSummaries.get(threadId);
if (!threadData) return;

// Make sure threads container exists
let threadsList = this.sidebar.querySelector('#tldr-threads-list');
if (!threadsList) {
const content = this.sidebar.querySelector('.tldr-sidebar-content');
Expand All @@ -159,27 +180,38 @@ Please summarize focusing on:
threadsList = threadsContainer.querySelector('#tldr-threads-list');
}

// Create or update thread summary element
let threadElement = threadsList.querySelector(`[data-thread-id="${threadId}"]`);
if (!threadElement) {
threadElement = document.createElement('div');
threadElement.className = 'tldr-thread-summary';
threadElement.setAttribute('data-thread-id', threadId);
threadsList.insertBefore(threadElement, threadsList.firstChild);
}
// Create new thread summary element (always add to top)
let threadElement = document.createElement('div');
threadElement.className = 'tldr-thread-summary';
threadElement.setAttribute('data-thread-id', threadId);

threadElement.innerHTML = `
<div class="tldr-thread-header">
<span class="tldr-thread-author">${threadData.author}</span>
<span class="tldr-thread-replies">${threadData.replyCount} replies</span>
</div>
<div class="tldr-thread-content markdown-body">
${renderMarkdown(summary.summary)}
${renderMarkdown(threadData.summary)}
</div>
`;

// Style the summary header
const header = threadElement.querySelector('.tldr-thread-header');
if (header) {
header.style.marginBottom = '8px';
header.style.color = '#666';
header.style.fontSize = '12px';
}

// Add click handler to scroll to comment
threadElement.addEventListener('click', () => {
const commentElement = document.getElementById(threadId);
if (commentElement) {
commentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
});

// Insert at the top of the list
threadsList.insertBefore(threadElement, threadsList.firstChild);
}
}

0 comments on commit 295e51f

Please sign in to comment.