-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
379 lines (321 loc) · 10.9 KB
/
Copy pathcontent.js
File metadata and controls
379 lines (321 loc) · 10.9 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// TrendScope Content Script
// Scrapes GitHub trending page and injects floating action button
(function() {
'use strict';
// Prevent multiple injections
if (window.__trendScopeInjected) return;
window.__trendScopeInjected = true;
// Wait for DOM to be ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
function init() {
// Verify we're on the trending page
if (!window.location.pathname.startsWith('/trending')) return;
const repos = scrapeRepos();
injectFloatingButton(repos);
}
/**
* Scrape all repo data from the trending page
* Uses multiple fallback strategies for resilience
*/
function scrapeRepos() {
const repos = [];
// Primary selector: article.Box-row (most common as of 2025)
let repoRows = document.querySelectorAll('article.Box-row');
// Fallback: div.Box-row
if (repoRows.length === 0) {
repoRows = document.querySelectorAll('div.Box-row');
}
// Fallback: any element with repo structure
if (repoRows.length === 0) {
repoRows = document.querySelectorAll('[class*="Box-row"]');
}
repoRows.forEach((row, index) => {
try {
const repo = extractRepoData(row, index + 1);
if (repo) repos.push(repo);
} catch (err) {
console.warn(`TrendScope: Failed to extract repo at index ${index}`, err);
}
});
return repos;
}
/**
* Extract data from a single repo row
*/
function extractRepoData(row, rank) {
// Get repo link - try multiple selectors
const repoLink = row.querySelector('h2 a') ||
row.querySelector('h1 a') ||
row.querySelector('a[href*="/"][href$=""]');
if (!repoLink) {
console.warn('TrendScope: Could not find repo link in row');
return null;
}
const href = repoLink.getAttribute('href');
const pathParts = href.split('/').filter(Boolean);
if (pathParts.length < 2) {
console.warn('TrendScope: Invalid repo path:', href);
return null;
}
const owner = pathParts[0];
const name = pathParts[1];
const fullName = `${owner}/${name}`;
const url = `https://github.com/${fullName}`;
// Get description - try multiple approaches
const description = extractDescription(row);
// Get language
const language = extractLanguage(row);
// Get total stars
const starsTotal = extractTotalStars(row);
// Get stars this period
const starsThisWeek = extractPeriodStars(row);
// Get forks
const forks = extractForks(row);
return {
rank,
owner,
name,
fullName,
url,
description,
language,
starsTotal,
starsThisWeek,
forks,
// These will be populated during enrichment
openIssues: null,
topics: [],
license: null,
createdAt: null,
readme: null,
readmeStatus: 'pending',
fetchedAt: null
};
}
/**
* Extract description with fallbacks
*/
function extractDescription(row) {
// Primary: p.col-9 or similar
const descP = row.querySelector('p.col-9') ||
row.querySelector('p.color-fg-muted') ||
row.querySelector('p[class*="color-fg"]') ||
row.querySelector('p');
if (descP) {
return descP.textContent.trim();
}
// Fallback: look for description after the h2
const h2 = row.querySelector('h2, h1');
if (h2 && h2.nextElementSibling?.tagName === 'P') {
return h2.nextElementSibling.textContent.trim();
}
return '';
}
/**
* Extract language with fallbacks
*/
function extractLanguage(row) {
// Primary: span with itemprop
const langSpan = row.querySelector('span[itemprop="programmingLanguage"]');
if (langSpan) return langSpan.textContent.trim();
// Fallback: look for colored circle followed by language name
const langIndicator = row.querySelector('.repo-language-color, [class*="language-color"]');
if (langIndicator && langIndicator.nextElementSibling) {
return langIndicator.nextElementSibling.textContent.trim();
}
// Fallback: span in the bottom row that's not a number
const bottomSpans = row.querySelectorAll('.f6 span, .text-sm span');
for (const span of bottomSpans) {
const text = span.textContent.trim();
if (text && !text.includes('star') && !text.includes(',') && !/^\d/.test(text)) {
const circle = span.querySelector('.repo-language-color, [style*="background-color"]');
if (circle) return text;
}
}
return null;
}
/**
* Extract total stars
*/
function extractTotalStars(row) {
// Look for stargazers link
const starLink = row.querySelector('a[href*="/stargazers"]');
if (starLink) {
return parseNumber(starLink.textContent);
}
// Fallback: look for star icon followed by number
const starIcon = row.querySelector('svg.octicon-star, [class*="octicon-star"]');
if (starIcon) {
const parent = starIcon.closest('a') || starIcon.parentElement;
if (parent) {
return parseNumber(parent.textContent);
}
}
return 0;
}
/**
* Extract stars gained this period
*/
function extractPeriodStars(row) {
// Look for "stars this week/today/month" text
const allText = row.textContent;
const match = allText.match(/([\d,]+)\s*stars?\s*(this week|today|this month)/i);
if (match) {
return parseNumber(match[1]);
}
// Fallback: last inline-block float element
const floatElements = row.querySelectorAll('.float-sm-right, [class*="float-sm-right"]');
for (const el of floatElements) {
const text = el.textContent.trim();
if (text.includes('star')) {
return parseNumber(text);
}
}
// Fallback: look in the f6/text-sm section
const metaSection = row.querySelector('.f6, .text-sm');
if (metaSection) {
const spans = metaSection.querySelectorAll('span');
for (const span of spans) {
const text = span.textContent.trim();
if (text.includes('star') && text.includes('this')) {
return parseNumber(text);
}
}
}
return 0;
}
/**
* Extract forks count
*/
function extractForks(row) {
// Look for forks link
const forkLink = row.querySelector('a[href*="/forks"], a[href*="/network/members"]');
if (forkLink) {
return parseNumber(forkLink.textContent);
}
// Fallback: look for fork icon followed by number
const forkIcon = row.querySelector('svg.octicon-repo-forked, [class*="octicon-repo-forked"]');
if (forkIcon) {
const parent = forkIcon.closest('a') || forkIcon.parentElement;
if (parent) {
return parseNumber(parent.textContent);
}
}
return null;
}
/**
* Parse number from text (handles commas and K/M suffixes)
*/
function parseNumber(text) {
if (!text) return 0;
// Clean the text
text = text.trim().toLowerCase();
// Handle K/M suffixes
if (text.includes('k')) {
const num = parseFloat(text.replace(/[^0-9.]/g, ''));
return Math.round(num * 1000);
}
if (text.includes('m')) {
const num = parseFloat(text.replace(/[^0-9.]/g, ''));
return Math.round(num * 1000000);
}
// Remove commas and parse
const cleaned = text.replace(/[^0-9]/g, '');
return parseInt(cleaned, 10) || 0;
}
/**
* Detect trending period from URL or page
*/
function detectPeriod() {
const url = new URL(window.location.href);
const since = url.searchParams.get('since');
if (since === 'daily') return 'daily';
if (since === 'monthly') return 'monthly';
return 'weekly'; // Default
}
/**
* Inject floating action button
*/
function injectFloatingButton(repos) {
// Remove existing button if any
const existing = document.getElementById('trendscope-fab');
if (existing) existing.remove();
const button = document.createElement('button');
button.id = 'trendscope-fab';
button.innerHTML = `<span class="trendscope-icon">🔭</span> TrendScope (${repos.length} repos)`;
// Inline styles to avoid CSP issues
Object.assign(button.style, {
position: 'fixed',
bottom: '24px',
right: '24px',
padding: '12px 20px',
background: '#0f172a',
color: '#e2e8f0',
border: '1px solid #334155',
borderRadius: '24px',
fontSize: '14px',
fontWeight: '500',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
cursor: 'pointer',
zIndex: '9999',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
display: 'flex',
alignItems: 'center',
gap: '8px',
transition: 'transform 0.2s, box-shadow 0.2s'
});
button.addEventListener('mouseenter', () => {
button.style.transform = 'scale(1.05)';
button.style.boxShadow = '0 6px 16px rgba(0, 0, 0, 0.4)';
});
button.addEventListener('mouseleave', () => {
button.style.transform = 'scale(1)';
button.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)';
});
button.addEventListener('click', () => {
const period = detectPeriod();
// Check if extension context is still valid
if (typeof chrome === 'undefined' || !chrome.runtime || !chrome.runtime.sendMessage) {
button.innerHTML = '<span class="trendscope-icon">🔄</span> Refresh page';
button.style.background = '#b91c1c';
alert('TrendScope: Extension was reloaded. Please refresh this page (Ctrl+R / Cmd+R) and try again.');
return;
}
// Update button to show sending state
button.innerHTML = '<span class="trendscope-icon">⏳</span> Sending...';
button.style.pointerEvents = 'none';
// Send to background script
try {
chrome.runtime.sendMessage({
type: 'REPOS_SCRAPED',
payload: { repos, period }
}, (response) => {
if (chrome.runtime.lastError) {
console.error('TrendScope: Message failed', chrome.runtime.lastError);
button.innerHTML = '<span class="trendscope-icon">❌</span> Error - Click to retry';
button.style.pointerEvents = 'auto';
return;
}
// Success state
button.innerHTML = '<span class="trendscope-icon">✅</span> Sent! Open extension';
button.style.background = '#166534';
setTimeout(() => {
button.innerHTML = `<span class="trendscope-icon">🔭</span> TrendScope (${repos.length} repos)`;
button.style.background = '#0f172a';
button.style.pointerEvents = 'auto';
}, 3000);
});
} catch (err) {
console.error('TrendScope: Send error', err);
button.innerHTML = '<span class="trendscope-icon">🔄</span> Refresh page';
button.style.background = '#b91c1c';
button.style.pointerEvents = 'auto';
}
});
document.body.appendChild(button);
}
})();