|
| 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 | +} |
0 commit comments