-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
194 lines (158 loc) · 6.02 KB
/
background.js
File metadata and controls
194 lines (158 loc) · 6.02 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
// Track and update tab count and statistics
// Default color ranges
const DEFAULT_RANGES = {
green: { min: 1, max: 20 },
orange: { min: 21, max: 40 },
red: { min: 41, max: 60 },
darkRed: { min: 61, max: Infinity }
};
// Initialize data storage on installation
chrome.runtime.onInstalled.addListener(async () => {
const today = new Date().toISOString().split('T')[0];
// Initialize with default settings if not already set
const storage = await chrome.storage.local.get(['ranges', 'history', 'lastCount']);
if (!storage.ranges) {
await chrome.storage.local.set({ ranges: DEFAULT_RANGES });
}
if (!storage.history) {
await chrome.storage.local.set({
history: {
daily: { [today]: { startCount: 0, endCount: 0 } },
weekly: { [getWeekNumber(new Date())]: { startCount: 0, endCount: 0 } }
}
});
}
if (storage.lastCount === undefined) {
await chrome.storage.local.set({ lastCount: 0 });
}
// Get initial tab count and update badge
updateTabCount();
// Set alarm to run daily for stat tracking
chrome.alarms.create('dailyReset', { periodInMinutes: 1440 }); // Every 24 hours
});
// Listen for tab changes
chrome.tabs.onCreated.addListener(updateTabCount);
chrome.tabs.onRemoved.addListener(updateTabCount);
// Listen for messages from options page
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'updateBadge') {
if (message.count !== undefined) {
// Update badge with specified count
updateBadge(message.count);
} else {
// Update badge with current count
updateTabCount();
}
}
});
// Listen for alarms
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'dailyReset') {
const today = new Date().toISOString().split('T')[0];
const thisWeek = getWeekNumber(new Date());
// Get current history and tab count
const { history, lastCount } = await chrome.storage.local.get(['history', 'lastCount']);
// Initialize today if it doesn't exist
if (!history.daily[today]) {
history.daily[today] = { startCount: lastCount, endCount: lastCount };
}
// Initialize this week if it doesn't exist
if (!history.weekly[thisWeek]) {
history.weekly[thisWeek] = { startCount: lastCount, endCount: lastCount };
}
// Update end counts
history.daily[today].endCount = lastCount;
history.weekly[thisWeek].endCount = lastCount;
// Clean up old history (keep only last 30 days and 12 weeks)
const dailyEntries = Object.entries(history.daily).sort().reverse();
const weeklyEntries = Object.entries(history.weekly).sort().reverse();
if (dailyEntries.length > 30) {
history.daily = Object.fromEntries(dailyEntries.slice(0, 30));
}
if (weeklyEntries.length > 12) {
history.weekly = Object.fromEntries(weeklyEntries.slice(0, 12));
}
// Save updated history
await chrome.storage.local.set({ history });
}
});
// Get current tab count and update badge
async function updateTabCount() {
try {
const tabs = await chrome.tabs.query({});
const count = tabs.length;
// Save current count
await chrome.storage.local.set({ lastCount: count });
// Update today's stats
const today = new Date().toISOString().split('T')[0];
const thisWeek = getWeekNumber(new Date());
const { history } = await chrome.storage.local.get(['history']);
// Initialize today if it doesn't exist
if (!history.daily[today]) {
history.daily[today] = { startCount: count, endCount: count };
} else {
history.daily[today].endCount = count;
}
// Initialize this week if it doesn't exist
if (!history.weekly[thisWeek]) {
history.weekly[thisWeek] = { startCount: count, endCount: count };
} else {
history.weekly[thisWeek].endCount = count;
}
await chrome.storage.local.set({ history });
// Update badge with count and color
updateBadge(count);
} catch (error) {
console.error('Error updating tab count:', error);
}
}
// Update badge text and color based on count
async function updateBadge(count) {
// Set badge text
await chrome.action.setBadgeText({
text: count.toString()
});
// Set badge text color to white for better contrast
await chrome.action.setBadgeTextColor({
color: '#FFFFFF' // White text
});
// Get color ranges and previous color from storage
const { ranges, lastColor } = await chrome.storage.local.get(['ranges', 'lastColor']);
// Determine new color based on count
let newColor = '#006400'; // Default green
if (count >= ranges.darkRed.min) {
newColor = '#800000'; // Dark red
} else if (count >= ranges.red.min) {
newColor = '#4B0082'; // Red
} else if (count >= ranges.orange.min) {
newColor = '#000080'; // Orange
}
// If color changed, trigger blinking effect
if (lastColor && lastColor !== newColor) {
await blinkBadge(newColor);
} else {
// Set badge background color directly if no change
await chrome.action.setBadgeBackgroundColor({ color: newColor });
}
// Store the new color
await chrome.storage.local.set({ lastColor: newColor });
}
// Function to handle badge blinking
async function blinkBadge(targetColor) {
const blinkCount = 3; // Number of blinks
const blinkDuration = 300; // Duration of each blink in milliseconds
for (let i = 0; i < blinkCount; i++) {
// Turn off (transparent)
await chrome.action.setBadgeBackgroundColor({ color: [0, 0, 0, 0] }); // Transparent
await new Promise(resolve => setTimeout(resolve, blinkDuration));
// Turn back to target color
await chrome.action.setBadgeBackgroundColor({ color: targetColor });
await new Promise(resolve => setTimeout(resolve, blinkDuration));
}
}
// Helper function to get week number
function getWeekNumber(date) {
const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
}