Skip to content

Commit 0bae6bc

Browse files
committed
(Feature) Create useVisibility page
1 parent a44c81a commit 0bae6bc

2 files changed

Lines changed: 57 additions & 1 deletion

File tree

src/browser/useVisibility.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { debounce } from "lodash";
2+
import { useState, useEffect } from "react";
3+
4+
import { DEFAULT_DEBOUNCE_TIME, userDocument } from "../constants";
5+
6+
/**
7+
* @typedef {Object} visibilityStatus
8+
* @property {boolean} support
9+
* Specify if the property is supported or not
10+
* @property {boolean} visibility
11+
* Actual visibility status from the browser
12+
*
13+
* React hook intended to get browser's visibility status
14+
*
15+
* @category Browser
16+
*
17+
* @param {Object} [options={}]
18+
* Configuration object intended to contain the default used by the hook.
19+
* @param {boolean} [options.defaultVisibility=true]
20+
* Default visibility status
21+
* @param {number} [options.wait=80]
22+
* The number of milliseconds to delay from the last event.
23+
* @returns {visibilityStatus}
24+
*/
25+
export function useVisibility(options = {}) {
26+
const [_, eventType] =
27+
[
28+
["hidden", "visibilitychange"],
29+
["msHidden", "msvisibilitychange"],
30+
["webkitHidden", "webkitvisibilitychange"],
31+
].find(([prop]) => userDocument && userDocument[prop]) || [];
32+
33+
const support = Boolean(eventType);
34+
const [visibility, updateVisibility] = useState({
35+
support,
36+
visibility: options.defaultVisibility || true,
37+
});
38+
39+
useEffect(() => {
40+
const debouncedUpdateVisibility = debounce(event => {
41+
updateVisibility(previousState => ({
42+
...previousState,
43+
visibility: event.target.visibilityState === "visible",
44+
}));
45+
}, options.wait || DEFAULT_DEBOUNCE_TIME);
46+
47+
if (eventType) userDocument.addEventListener(eventType, debouncedUpdateVisibility);
48+
49+
return () => {
50+
if (eventType) userDocument.removeEventListener(eventType, debouncedUpdateVisibility);
51+
};
52+
}, [eventType, options.wait]);
53+
54+
return visibility;
55+
}

src/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
// Browser
2+
export { useBattery } from "./browser/useBattery";
23
export { useBrowserDimensions } from "./browser/useBrowserDimensions";
34
export { useMediaQuery } from "./browser/useMediaQuery";
45
export { useScreenDimensions } from "./browser/useScreenDimensions";
56
export { useScreenOrientation } from "./browser/useScreenOrientation";
6-
export { useBattery } from "./browser/useBattery";
7+
export { useVisibility } from "./browser/useVisibility";
78

89
// Network
910
export { useNetworkConnectionType } from "./network/useNetworkConnectionType";

0 commit comments

Comments
 (0)