-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
268 lines (220 loc) · 7.68 KB
/
popup.js
File metadata and controls
268 lines (220 loc) · 7.68 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
// Popup script for handling recommendations and UI
// Constants
const WIKIPEDIA_API_ENDPOINT = 'https://en.wikipedia.org/w/api.php';
const MAX_RECOMMENDATIONS = 10;
const MAX_HISTORY_ITEMS = 20;
// Cache for API responses
const apiCache = new Map();
// UI Elements
let activeTab = 'recommendations';
// Initialize popup
document.addEventListener('DOMContentLoaded', () => {
initializeTabs();
loadUserStats();
loadRecommendations();
loadHistory();
});
// Tab handling
function initializeTabs() {
const tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabName = tab.dataset.tab;
switchTab(tabName);
});
});
}
function switchTab(tabName) {
// Update active tab
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.tab === tabName);
});
// Update visible content
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.toggle('active', content.id === `${tabName}-tab`);
});
activeTab = tabName;
}
// Load user statistics
function loadUserStats() {
chrome.storage.local.get({ visits: [] }, (result) => {
const visits = result.visits;
const stats = calculateStats(visits);
updateStatsDisplay(stats);
});
}
function calculateStats(visits) {
return {
totalArticles: visits.length,
totalReadingTime: visits.reduce((sum, visit) => sum + (visit.timeSpent || 0), 0),
averageEngagement: visits.reduce((sum, visit) => sum + (visit.engagementScore || 0), 0) / visits.length || 0
};
}
function updateStatsDisplay(stats) {
const statsElement = document.getElementById('stats');
const readingTime = formatReadingTime(stats.totalReadingTime);
const engagement = Math.round(stats.averageEngagement * 100);
statsElement.textContent =
`${stats.totalArticles} articles read • ${readingTime} total reading time • ${engagement}% engagement`;
}
// Load and display recommendations
async function loadRecommendations() {
try {
const recommendations = await generateRecommendations();
displayRecommendations(recommendations);
} catch (error) {
showError('Failed to load recommendations');
console.error('Error loading recommendations:', error);
}
}
async function generateRecommendations() {
const { visits = [] } = await chrome.storage.local.get({ visits: [] });
if (visits.length === 0) {
return { recent: [], popular: [] };
}
// Sort visits by engagement score and recency
const sortedVisits = [...visits].sort((a, b) => b.engagementScore - a.engagementScore);
const recentVisits = [...visits].sort((a, b) => b.timestamp - a.timestamp);
// Get recommendations based on most engaged and recent articles
const [engagementBased, recentBased] = await Promise.all([
getRelatedArticles(sortedVisits[0].title),
getRelatedArticles(recentVisits[0].title)
]);
return {
popular: engagementBased,
recent: recentBased
};
}
async function getRelatedArticles(title) {
// Check cache first
const cacheKey = `related_${title}`;
if (apiCache.has(cacheKey)) {
return apiCache.get(cacheKey);
}
// Fetch from Wikipedia API
const params = new URLSearchParams({
action: 'opensearch',
search: title,
limit: MAX_RECOMMENDATIONS,
namespace: 0,
format: 'json',
origin: '*'
});
const response = await fetch(`${WIKIPEDIA_API_ENDPOINT}?${params}`);
const [searchTerm, titles, descriptions, urls] = await response.json();
// Format results
const results = titles.map((title, index) => ({
title,
description: descriptions[index],
url: urls[index]
}));
// Cache results
apiCache.set(cacheKey, results);
return results;
}
function displayRecommendations(recommendations) {
const container = document.getElementById('recommendations');
container.innerHTML = '';
// Display popular recommendations
if (recommendations.popular.length > 0) {
const popularGroup = createRecommendationGroup('Based on Your Interests', recommendations.popular);
container.appendChild(popularGroup);
}
// Display recent recommendations
if (recommendations.recent.length > 0) {
const recentGroup = createRecommendationGroup('Related to Recent Reading', recommendations.recent);
container.appendChild(recentGroup);
}
if (recommendations.popular.length === 0 && recommendations.recent.length === 0) {
showNoData(container, 'No recommendations available. Try reading some Wikipedia articles first!');
}
}
// Load and display history
function loadHistory() {
chrome.storage.local.get({ visits: [] }, (result) => {
const visits = result.visits
.sort((a, b) => b.timestamp - a.timestamp)
.slice(0, MAX_HISTORY_ITEMS);
displayHistory(visits);
});
}
function displayHistory(visits) {
const container = document.getElementById('history');
container.innerHTML = '';
if (visits.length === 0) {
showNoData(container, 'No reading history available.');
return;
}
visits.forEach(visit => {
const articleCard = createArticleCard({
title: visit.title,
url: visit.url,
meta: `Read ${formatTimeAgo(visit.timestamp)} • ${formatReadingTime(visit.timeSpent)}`
});
container.appendChild(articleCard);
});
}
// UI Helper functions
function createRecommendationGroup(title, articles) {
const group = document.createElement('div');
group.className = 'recommendation-group';
const groupTitle = document.createElement('div');
groupTitle.className = 'group-title';
groupTitle.textContent = title;
group.appendChild(groupTitle);
articles.forEach(article => {
const articleCard = createArticleCard({
title: article.title,
url: article.url,
meta: article.description || 'No description available'
});
group.appendChild(articleCard);
});
return group;
}
function createArticleCard({ title, url, meta }) {
const card = document.createElement('div');
card.className = 'article-card';
const titleLink = document.createElement('a');
titleLink.className = 'article-title';
titleLink.href = url;
titleLink.target = '_blank';
titleLink.textContent = title;
card.appendChild(titleLink);
const metaDiv = document.createElement('div');
metaDiv.className = 'article-meta';
metaDiv.textContent = meta;
card.appendChild(metaDiv);
return card;
}
function showError(message) {
const container = document.getElementById('recommendations');
container.innerHTML = `<div class="error">${message}</div>`;
}
function showNoData(container, message) {
container.innerHTML = `<div class="no-data">${message}</div>`;
}
// Utility functions
function formatReadingTime(seconds) {
if (!seconds) return '0 min';
const minutes = Math.round(seconds / 60);
return minutes === 1 ? '1 min' : `${minutes} mins`;
}
function formatTimeAgo(timestamp) {
const seconds = Math.floor((Date.now() - timestamp) / 1000);
const intervals = {
year: 31536000,
month: 2592000,
week: 604800,
day: 86400,
hour: 3600,
minute: 60
};
for (const [unit, secondsInUnit] of Object.entries(intervals)) {
const interval = Math.floor(seconds / secondsInUnit);
if (interval >= 1) {
return `${interval} ${unit}${interval === 1 ? '' : 's'} ago`;
}
}
return 'just now';
}