-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy paththemeAgent.js
More file actions
64 lines (52 loc) · 2.02 KB
/
themeAgent.js
File metadata and controls
64 lines (52 loc) · 2.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
class ThemeAgent {
constructor(settingsStore, applyThemeCallback) {
this.settingsStore = settingsStore;
this.applyThemeCallback = applyThemeCallback;
this.intervalId = null;
}
start() {
this.stop();
const storeData = this.settingsStore.load() || {};
const config = storeData.themeAutomation;
// Defensive check: Ensure config is a valid object and is enabled
if (!config || typeof config !== 'object' || !config.enabled) return;
// Guard: Prevent invalid, negative, or tight-loop intervals (minimum 1 minute)
let minutes = parseInt(config.checkIntervalMinutes, 10);
if (isNaN(minutes) || minutes < 1) {
minutes = 30; // Safe default fallback
}
const intervalMs = minutes * 60 * 1000;
this.evaluateAndApplyTheme(config);
this.intervalId = setInterval(() => {
const currentStoreData = this.settingsStore.load() || {};
const currentConfig = currentStoreData.themeAutomation;
if (currentConfig && typeof currentConfig === 'object' && currentConfig.enabled) {
this.evaluateAndApplyTheme(currentConfig);
} else {
this.stop(); // Stop if disabled during active interval
}
}, intervalMs);
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
evaluateAndApplyTheme(config) {
if (!config || typeof config !== 'object' || !config.enabled) return;
try {
const currentHour = new Date().getHours();
const isDaytime = currentHour >= 6 && currentHour < 18; // 6 AM to 6 PM
const targetTheme = isDaytime ? config.dayTheme : config.nightTheme;
const storeData = this.settingsStore.load() || {};
if (targetTheme && storeData.selectedTheme !== targetTheme) {
console.log(`[ThemeAgent] Switching theme to: ${targetTheme}`);
this.applyThemeCallback(targetTheme);
}
} catch (error) {
console.error("ThemeAgent failed to evaluate time-based theme.", error);
}
}
}
module.exports = ThemeAgent;