-
Notifications
You must be signed in to change notification settings - Fork 5
/
content.js
209 lines (187 loc) · 7.9 KB
/
content.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//TODO: Review
function addRankingToTweet(tweetElement, ranking) {
const actionBar = tweetElement.querySelector('div[role="group"]');
if (!actionBar) return;
// Check if ranking container already exists
let rankContainer = tweetElement.querySelector('.tweet-ranker-container');
if (!rankContainer) {
rankContainer = document.createElement('div');
rankContainer.className = 'tweet-ranker-container';
rankContainer.style.display = 'flex';
rankContainer.style.alignItems = 'center';
rankContainer.style.marginRight = '16px';
rankContainer.style.position = 'relative'; // For positioning the tooltip
actionBar.insertBefore(rankContainer, actionBar.firstChild);
}
chrome.storage.sync.get(['hideLowRankTweets', 'colorfulRanks'], (data) => {
const hideThreshold = parseInt(data.hideLowRankTweets, 10);
const colorfulRanks = data.colorfulRanks;
// Handle hiding low-ranked tweets
if (hideThreshold && hideThreshold > 0 && ranking !== null && ranking <= hideThreshold) {
tweetElement.style.display = 'none';
return;
}
// Update or create rank text
let rankText = rankContainer.querySelector('.tweet-ranker-rating');
if (!rankText) {
rankText = document.createElement('span');
rankText.className = 'tweet-ranker-rating';
rankContainer.appendChild(rankText);
}
// Set rank text content and style
if (ranking === null) {
rankText.textContent = 'Pending';
} else if (ranking === undefined) {
rankText.textContent = 'Error';
} else if (ranking === -1) {
rankText.textContent = 'Unsafe';
} else if (ranking >= 0 && ranking <= 10) {
rankText.textContent = `${ranking}/10`;
} else {
rankText.textContent = 'Error';
}
rankText.style.fontSize = '13px';
rankText.style.fontWeight = 'bold';
rankText.style.color = getRankColor(ranking, colorfulRanks);
// Add or update tooltip
if (!rankContainer.querySelector('.tweet-ranker-tooltip')) {
const tooltip = document.createElement('div');
tooltip.className = 'tweet-ranker-tooltip';
tooltip.textContent = 'Well Thought Rank';
tooltip.style.display = 'none';
rankContainer.appendChild(tooltip);
rankContainer.addEventListener('mouseenter', () => {
tooltip.style.display = 'block';
});
rankContainer.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
}
// Set title for built-in tooltip
rankContainer.title = 'Well Thought Rank';
});
}
function getTweetId(tweetElement) {
const tweetLink = tweetElement.querySelector('a[href*="/status/"]');
if (tweetLink) {
const urlParts = tweetLink.href.split('/');
const statusIndex = urlParts.indexOf('status');
if (statusIndex !== -1 && statusIndex + 1 < urlParts.length) {
const tweetId = urlParts[statusIndex + 1];
return tweetId.toString(); // Ensure ID is a string
}
}
return null;
}
function processTweets() {
const tweets = document.querySelectorAll('article[data-testid="tweet"]:not([data-ranked]):not([data-ranked="pending"]):not([data-testid*="reply"])');
const tweetsToRank = [];
tweets.forEach(tweet => {
const tweetText = tweet.querySelector('div[data-testid="tweetText"]')?.textContent;
const tweetId = getTweetId(tweet);
if (tweetId) {
const storedRanking = localStorage.getItem(`tweet-ranking-${tweetId}`);
if (storedRanking !== null && parseInt(storedRanking) > 0 && parseInt(storedRanking) <= 10) {
addRankingToTweet(tweet, parseInt(storedRanking));
tweet.setAttribute('data-ranked', 'true');
} else if (hasEmptyText(tweetText, tweetId)) {
addRankingToTweet(tweet, 0);
tweet.setAttribute('data-ranked', 'true');
} else if (tweetText) {
tweetsToRank.push({ id: tweetId, text: tweetText });
tweet.setAttribute('data-ranked', 'pending');
} else {
// Handle empty tweetText as emoji-only
addRankingToTweet(tweet, 0);
tweet.setAttribute('data-ranked', 'true');
}
}
});
if (tweetsToRank.length > 0) {
chrome.runtime.sendMessage({ action: 'rankTweets', tweets: tweetsToRank });
}
}
function hasEmptyText(text, id) {
if (!text) {
return true;
}
return false;
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'tweetRatings') {
const tweets = document.querySelectorAll('article[data-testid="tweet"]');
const tweetMap = new Map();
tweets.forEach(tweet => {
const tweetId = getTweetId(tweet);
if (tweetId) {
tweetMap.set(tweetId, tweet);
}
});
message.ratings.forEach(({ id, rating }) => {
const tweet = tweetMap.get(id.toString()); // Ensure ID is a string
if (tweet) {
if (rating >= -1 && rating <= 10) {
// Valid rating
addRankingToTweet(tweet, rating);
tweet.setAttribute('data-ranked', 'true');
localStorage.setItem(`tweet-ranking-${id.toString()}`, rating);
} else if (rating === null) {
// Pending rating
addRankingToTweet(tweet, 'Pending...');
tweet.setAttribute('data-ranked', 'pending');
} else {
// Error rating (-2, -3, -4)
addRankingToTweet(tweet, 'Error');
tweet.removeAttribute('data-ranked'); // Remove the data-ranked attribute to allow reprocessing
localStorage.removeItem(`tweet-ranking-${id.toString()}`); // Remove any stored ranking
}
}
});
}
if (message.action === 'clearRankings') {
console.log('Clearing tweets!!!!');
let clearedCount = 0;
for (let key in localStorage) {
if (key.startsWith('tweet-ranking-')) {
localStorage.removeItem(key);
clearedCount++;
}
}
console.log('Cleared', clearedCount, 'items from localStorage');
}
});
// Run processTweets immediately and then every 5 seconds
processTweets();
setInterval(processTweets, 2000);
// Modify the MutationObserver to only process new, unranked main tweets
const observer = new MutationObserver((mutations) => {
let newUnrankedTweetFound = false;
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE &&
node.matches('article[data-testid="tweet"]:not([data-testid*="reply"]):not([data-ranked]):not([data-ranked="pending"])')) {
newUnrankedTweetFound = true;
}
});
}
});
if (newUnrankedTweetFound) {
processTweets(); // Process all unranked tweets when a new one is added
}
});
observer.observe(document.body, { childList: true, subtree: true });
function getRankColor(ranking, colorfulRanks) {
if (!colorfulRanks) {
return 'rgb(83, 100, 113)'; // Default color
}
if (ranking === null || ranking === undefined) {
return 'rgb(83, 100, 113)'; // Default color for pending or error states
}
if (ranking >= 8) return '#32CD32';
if (ranking >= 7) return '#228B22';
if (ranking >= 5) return '#3CB371';
if (ranking >= 3) return '#6B8E23';
if (ranking >= 1) return '#024731';
return 'rgb(83, 100, 113)'; // Default color for any other case
}