-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
260 lines (230 loc) · 6.92 KB
/
popup.js
File metadata and controls
260 lines (230 loc) · 6.92 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
// Popup script for Browsing Time Tracker
let chart = null;
// Initialize popup when opened
document.addEventListener('DOMContentLoaded', () => {
initializePopup();
setupEventListeners();
});
// Initialize popup with data
async function initializePopup() {
try {
const data = await chrome.runtime.sendMessage({ type: 'GET_DATA' });
updateUI(data);
} catch (error) {
console.error('Error loading data:', error);
showEmptyState();
}
}
// Update UI with tracking data
function updateUI(data) {
const siteData = data.siteData || {};
const currentDate = data.lastResetDate || new Date().toISOString().split('T')[0];
const isIdle = data.isIdle;
// Update date
const dateObj = new Date(currentDate);
document.getElementById('currentDate').textContent = dateObj.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
// Update status bar
const statusBar = document.getElementById('statusBar');
const statusText = document.getElementById('statusText');
if (isIdle) {
statusBar.classList.add('paused');
statusText.textContent = '⏸️ Tracking paused (idle)';
} else {
statusBar.classList.remove('paused');
statusText.textContent = '✅ Tracking active';
}
// Calculate totals
const sortedSites = Object.entries(siteData)
.sort((a, b) => b[1] - a[1]);
const totalSites = sortedSites.length;
const totalSeconds = sortedSites.reduce((sum, [, seconds]) => sum + seconds, 0);
// Add current tab time if active
if (data.currentDomain && data.currentExtraTime > 0 && !isIdle) {
const existingIndex = sortedSites.findIndex(([domain]) => domain === data.currentDomain);
if (existingIndex !== -1) {
sortedSites[existingIndex][1] += data.currentExtraTime;
}
}
// Update summary stats
document.getElementById('totalSites').textContent = totalSites;
document.getElementById('totalTime').textContent = formatTime(totalSeconds);
// Show chart and list
if (totalSites === 0) {
showEmptyState();
} else {
renderChart(sortedSites);
renderSitesList(sortedSites);
}
}
// Format seconds to HH:MM
function formatTime(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
}
// Render Chart.js chart
function renderChart(sortedSites) {
const ctx = document.getElementById('timeChart').getContext('2d');
// Take top 5 sites for chart
const topSites = sortedSites.slice(0, 5);
const labels = topSites.map(([domain]) => domain.length > 15 ? domain.substring(0, 12) + '...' : domain);
const data = topSites.map(([, seconds]) => Math.round(seconds / 60)); // Convert to minutes
const colors = [
'#667eea',
'#764ba2',
'#f093fb',
'#f5576c',
'#4facfe'
];
if (chart) {
chart.destroy();
}
chart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Minutes',
data: data,
backgroundColor: colors,
borderRadius: 4,
borderSkipped: false,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
const minutes = context.raw;
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours > 0) {
return `${hours}h ${mins}m`;
}
return `${mins}m`;
}
}
}
},
scales: {
y: {
beginAtZero: true,
grid: {
color: '#f0f0f0'
},
ticks: {
font: {
size: 10
}
}
},
x: {
grid: {
display: false
},
ticks: {
font: {
size: 9
},
maxRotation: 45
}
}
}
}
});
}
// Render sites list
function renderSitesList(sortedSites) {
const listContainer = document.getElementById('sitesList');
listContainer.innerHTML = '';
const maxTime = sortedSites[0][1]; // Top site time for bar calculation
sortedSites.forEach(([domain, seconds], index) => {
const siteItem = document.createElement('div');
siteItem.className = 'site-item';
// Rank badge
const rankClass = index === 0 ? 'top-1' : index === 1 ? 'top-2' : index === 2 ? 'top-3' : '';
const rankDisplay = index < 3 ? (index + 1).toString() : (index + 1).toString();
// Bar width percentage
const barWidth = maxTime > 0 ? (seconds / maxTime) * 100 : 0;
siteItem.innerHTML = `
<div class="site-rank ${rankClass}">${rankDisplay}</div>
<div class="site-info">
<div class="site-domain">${domain}</div>
<div class="site-bar-container">
<div class="site-bar" style="width: ${barWidth}%"></div>
</div>
</div>
<div class="site-time">${formatTime(seconds)}</div>
`;
listContainer.appendChild(siteItem);
});
}
// Show empty state
function showEmptyState() {
const listContainer = document.getElementById('sitesList');
listContainer.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">📊</div>
<div class="empty-state-text">No browsing data yet today.<br>Start browsing to track your time!</div>
</div>
`;
// Clear chart
if (chart) {
chart.destroy();
chart = null;
}
document.getElementById('totalSites').textContent = '0';
document.getElementById('totalTime').textContent = '0h 0m';
}
// Setup event listeners
function setupEventListeners() {
// Export button
document.getElementById('exportBtn').addEventListener('click', async () => {
try {
const result = await chrome.runtime.sendMessage({ type: 'EXPORT_CSV' });
if (result && result.csv) {
downloadCSV(result.csv.csv, result.csv.date);
}
} catch (error) {
console.error('Error exporting CSV:', error);
alert('Error exporting data. Please try again.');
}
});
// Reset button
document.getElementById('resetBtn').addEventListener('click', async () => {
if (confirm('Are you sure you want to reset all data for today?')) {
try {
await chrome.runtime.sendMessage({ type: 'RESET_DATA' });
showEmptyState();
} catch (error) {
console.error('Error resetting data:', error);
}
}
});
}
// Download CSV file
function downloadCSV(csvContent, date) {
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `browsing-time-${date}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}