use-green-mode 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UdhayaKumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/index.d.mts CHANGED
@@ -6,7 +6,7 @@ interface GreenThresholds {
6
6
  ecoThemeAt?: number;
7
7
  }
8
8
  declare function useGreenMode(thresholds?: GreenThresholds): {
9
- score: number;
9
+ energyScore: number;
10
10
  lowRes: boolean;
11
11
  stopAnimations: boolean;
12
12
  ecoTheme: boolean;
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ interface GreenThresholds {
6
6
  ecoThemeAt?: number;
7
7
  }
8
8
  declare function useGreenMode(thresholds?: GreenThresholds): {
9
- score: number;
9
+ energyScore: number;
10
10
  lowRes: boolean;
11
11
  stopAnimations: boolean;
12
12
  ecoTheme: boolean;
package/dist/index.js CHANGED
@@ -36,47 +36,68 @@ var energyScore = (0, import_nanostores.atom)(100);
36
36
  var isBrowser = typeof window !== "undefined" && typeof navigator !== "undefined";
37
37
  function initGreenObserver() {
38
38
  if (!isBrowser) return;
39
- const calculateScore = () => {
39
+ let batteryLevel = 1;
40
+ let isCharging = true;
41
+ const getConnection = () => {
42
+ return navigator.connection || navigator.mozConnection || navigator.webkitConnection || null;
43
+ };
44
+ const evaluateScore = () => {
40
45
  let score = 100;
41
- if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) score -= 20;
42
- const connection = navigator.connection;
43
- if (connection) {
44
- if (connection.saveData) score -= 40;
45
- if (["slow-2g", "2g", "3g"].includes(connection.effectiveType)) score -= 30;
46
+ if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) {
47
+ score -= 20;
48
+ }
49
+ const conn2 = getConnection();
50
+ if (conn2) {
51
+ if (conn2.saveData) score -= 40;
52
+ if (["slow-2g", "2g", "3g"].includes(conn2.effectiveType)) score -= 30;
53
+ }
54
+ if (!isCharging && batteryLevel <= 0.2) {
55
+ score -= 50;
46
56
  }
47
- energyScore.set(Math.max(0, score));
57
+ energyScore.set(Math.max(0, Math.min(100, score)));
48
58
  };
59
+ const conn = getConnection();
60
+ if (conn && typeof conn.addEventListener === "function") {
61
+ conn.addEventListener("change", evaluateScore);
62
+ }
49
63
  if ("getBattery" in navigator) {
50
64
  navigator.getBattery().then((battery) => {
51
- const updateBatteryImpact = () => {
52
- let currentScore = energyScore.get();
53
- if (!battery.charging && battery.level <= 0.2) {
54
- energyScore.set(Math.max(0, currentScore - 50));
55
- } else {
56
- calculateScore();
57
- }
58
- };
59
- updateBatteryImpact();
60
- battery.addEventListener("levelchange", updateBatteryImpact);
61
- battery.addEventListener("chargingchange", updateBatteryImpact);
65
+ batteryLevel = battery.level;
66
+ isCharging = battery.charging;
67
+ evaluateScore();
68
+ battery.addEventListener("levelchange", () => {
69
+ batteryLevel = battery.level;
70
+ evaluateScore();
71
+ });
72
+ battery.addEventListener("chargingchange", () => {
73
+ isCharging = battery.charging;
74
+ evaluateScore();
75
+ });
76
+ }).catch(() => {
77
+ evaluateScore();
62
78
  });
63
79
  } else {
64
- calculateScore();
80
+ evaluateScore();
65
81
  }
66
82
  }
67
83
 
68
84
  // src/useGreenMode.ts
85
+ var isInitialized = false;
69
86
  function useGreenMode(thresholds = {}) {
70
87
  const { lowResAt = 70, stopAnimationsAt = 50, ecoThemeAt = 30 } = thresholds;
71
- const score = (0, import_react2.useStore)(energyScore);
88
+ const currentScore = (0, import_react2.useStore)(energyScore);
72
89
  (0, import_react.useEffect)(() => {
73
- initGreenObserver();
90
+ if (!isInitialized) {
91
+ initGreenObserver();
92
+ isInitialized = true;
93
+ }
74
94
  }, []);
75
95
  return {
76
- score,
77
- lowRes: score <= lowResAt,
78
- stopAnimations: score <= stopAnimationsAt,
79
- ecoTheme: score <= ecoThemeAt
96
+ energyScore: currentScore,
97
+ // FIXED: Now matches your README exactly!
98
+ lowRes: currentScore <= lowResAt,
99
+ stopAnimations: currentScore <= stopAnimationsAt,
100
+ ecoTheme: currentScore <= ecoThemeAt
80
101
  };
81
102
  }
82
103
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.mjs CHANGED
@@ -8,47 +8,68 @@ var energyScore = atom(100);
8
8
  var isBrowser = typeof window !== "undefined" && typeof navigator !== "undefined";
9
9
  function initGreenObserver() {
10
10
  if (!isBrowser) return;
11
- const calculateScore = () => {
11
+ let batteryLevel = 1;
12
+ let isCharging = true;
13
+ const getConnection = () => {
14
+ return navigator.connection || navigator.mozConnection || navigator.webkitConnection || null;
15
+ };
16
+ const evaluateScore = () => {
12
17
  let score = 100;
13
- if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) score -= 20;
14
- const connection = navigator.connection;
15
- if (connection) {
16
- if (connection.saveData) score -= 40;
17
- if (["slow-2g", "2g", "3g"].includes(connection.effectiveType)) score -= 30;
18
+ if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) {
19
+ score -= 20;
20
+ }
21
+ const conn2 = getConnection();
22
+ if (conn2) {
23
+ if (conn2.saveData) score -= 40;
24
+ if (["slow-2g", "2g", "3g"].includes(conn2.effectiveType)) score -= 30;
25
+ }
26
+ if (!isCharging && batteryLevel <= 0.2) {
27
+ score -= 50;
18
28
  }
19
- energyScore.set(Math.max(0, score));
29
+ energyScore.set(Math.max(0, Math.min(100, score)));
20
30
  };
31
+ const conn = getConnection();
32
+ if (conn && typeof conn.addEventListener === "function") {
33
+ conn.addEventListener("change", evaluateScore);
34
+ }
21
35
  if ("getBattery" in navigator) {
22
36
  navigator.getBattery().then((battery) => {
23
- const updateBatteryImpact = () => {
24
- let currentScore = energyScore.get();
25
- if (!battery.charging && battery.level <= 0.2) {
26
- energyScore.set(Math.max(0, currentScore - 50));
27
- } else {
28
- calculateScore();
29
- }
30
- };
31
- updateBatteryImpact();
32
- battery.addEventListener("levelchange", updateBatteryImpact);
33
- battery.addEventListener("chargingchange", updateBatteryImpact);
37
+ batteryLevel = battery.level;
38
+ isCharging = battery.charging;
39
+ evaluateScore();
40
+ battery.addEventListener("levelchange", () => {
41
+ batteryLevel = battery.level;
42
+ evaluateScore();
43
+ });
44
+ battery.addEventListener("chargingchange", () => {
45
+ isCharging = battery.charging;
46
+ evaluateScore();
47
+ });
48
+ }).catch(() => {
49
+ evaluateScore();
34
50
  });
35
51
  } else {
36
- calculateScore();
52
+ evaluateScore();
37
53
  }
38
54
  }
39
55
 
40
56
  // src/useGreenMode.ts
57
+ var isInitialized = false;
41
58
  function useGreenMode(thresholds = {}) {
42
59
  const { lowResAt = 70, stopAnimationsAt = 50, ecoThemeAt = 30 } = thresholds;
43
- const score = useStore(energyScore);
60
+ const currentScore = useStore(energyScore);
44
61
  useEffect(() => {
45
- initGreenObserver();
62
+ if (!isInitialized) {
63
+ initGreenObserver();
64
+ isInitialized = true;
65
+ }
46
66
  }, []);
47
67
  return {
48
- score,
49
- lowRes: score <= lowResAt,
50
- stopAnimations: score <= stopAnimationsAt,
51
- ecoTheme: score <= ecoThemeAt
68
+ energyScore: currentScore,
69
+ // FIXED: Now matches your README exactly!
70
+ lowRes: currentScore <= lowResAt,
71
+ stopAnimations: currentScore <= stopAnimationsAt,
72
+ ecoTheme: currentScore <= ecoThemeAt
52
73
  };
53
74
  }
54
75
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "use-green-mode",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "A lightweight, eco-friendly React hook that gracefully degrades your UI to save battery and data.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
package/src/engine.ts CHANGED
@@ -7,36 +7,74 @@ const isBrowser = typeof window !== 'undefined' && typeof navigator !== 'undefin
7
7
  export function initGreenObserver() {
8
8
  if (!isBrowser) return;
9
9
 
10
- const calculateScore = () => {
10
+ // Store hardware state internally
11
+ let batteryLevel = 1;
12
+ let isCharging = true;
13
+
14
+ // Safe fallback for Firefox/Safari
15
+ const getConnection = () => {
16
+ return (navigator as any).connection ||
17
+ (navigator as any).mozConnection ||
18
+ (navigator as any).webkitConnection ||
19
+ null;
20
+ };
21
+
22
+ // 1. Single Source of Truth for Math
23
+ const evaluateScore = () => {
11
24
  let score = 100;
12
-
13
- if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) score -= 20;
14
25
 
15
- const connection = (navigator as any).connection;
16
- if (connection) {
17
- if (connection.saveData) score -= 40;
18
- if (['slow-2g', '2g', '3g'].includes(connection.effectiveType)) score -= 30;
26
+ // CPU Penalty
27
+ if (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4) {
28
+ score -= 20;
19
29
  }
20
30
 
21
- energyScore.set(Math.max(0, score));
31
+ // Network Penalty
32
+ const conn = getConnection();
33
+ if (conn) {
34
+ if (conn.saveData) score -= 40;
35
+ if (['slow-2g', '2g', '3g'].includes(conn.effectiveType)) score -= 30;
36
+ }
37
+
38
+ // Battery Penalty
39
+ if (!isCharging && batteryLevel <= 0.2) {
40
+ score -= 50;
41
+ }
42
+
43
+ // Ensure score stays strictly between 0 and 100
44
+ energyScore.set(Math.max(0, Math.min(100, score)));
22
45
  };
23
46
 
47
+ // --- 2. Attach Listeners ---
48
+
49
+ // Listen for Network Changes (Fixes your DevTools issue!)
50
+ const conn = getConnection();
51
+ if (conn && typeof conn.addEventListener === 'function') {
52
+ conn.addEventListener('change', evaluateScore);
53
+ }
54
+
55
+ // Listen for Battery Changes
24
56
  if ('getBattery' in navigator) {
25
57
  (navigator as any).getBattery().then((battery: any) => {
26
- const updateBatteryImpact = () => {
27
- let currentScore = energyScore.get();
28
- if (!battery.charging && battery.level <= 0.2) {
29
- energyScore.set(Math.max(0, currentScore - 50));
30
- } else {
31
- calculateScore();
32
- }
33
- };
34
-
35
- updateBatteryImpact();
36
- battery.addEventListener('levelchange', updateBatteryImpact);
37
- battery.addEventListener('chargingchange', updateBatteryImpact);
58
+ // Set initial battery state
59
+ batteryLevel = battery.level;
60
+ isCharging = battery.charging;
61
+ evaluateScore();
62
+
63
+ // Update state on changes
64
+ battery.addEventListener('levelchange', () => {
65
+ batteryLevel = battery.level;
66
+ evaluateScore();
67
+ });
68
+ battery.addEventListener('chargingchange', () => {
69
+ isCharging = battery.charging;
70
+ evaluateScore();
71
+ });
72
+ }).catch(() => {
73
+ // Failsafe: Some strict browsers block the battery promise
74
+ evaluateScore();
38
75
  });
39
76
  } else {
40
- calculateScore();
77
+ // Failsafe: Safari/Firefox don't support getBattery
78
+ evaluateScore();
41
79
  }
42
80
  }
@@ -8,18 +8,27 @@ interface GreenThresholds {
8
8
  ecoThemeAt?: number;
9
9
  }
10
10
 
11
+ // Global flag to ensure we only add browser listeners once
12
+ let isInitialized = false;
13
+
11
14
  export function useGreenMode(thresholds: GreenThresholds = {}) {
12
15
  const { lowResAt = 70, stopAnimationsAt = 50, ecoThemeAt = 30 } = thresholds;
13
- const score = useStore(energyScore);
16
+
17
+ // Read the current score from the Nano Store
18
+ const currentScore = useStore(energyScore);
14
19
 
15
20
  useEffect(() => {
16
- initGreenObserver();
21
+ // Only initialize the engine once, even if the hook is used in 10 components
22
+ if (!isInitialized) {
23
+ initGreenObserver();
24
+ isInitialized = true;
25
+ }
17
26
  }, []);
18
27
 
19
28
  return {
20
- score,
21
- lowRes: score <= lowResAt,
22
- stopAnimations: score <= stopAnimationsAt,
23
- ecoTheme: score <= ecoThemeAt,
29
+ energyScore: currentScore, // FIXED: Now matches your README exactly!
30
+ lowRes: currentScore <= lowResAt,
31
+ stopAnimations: currentScore <= stopAnimationsAt,
32
+ ecoTheme: currentScore <= ecoThemeAt,
24
33
  };
25
34
  }