[Refactoring] useBackgroundMode: Use signals
This commit is contained in:
parent
aaf19a4405
commit
02ada70d43
@ -1,26 +1,21 @@
|
|||||||
import { useEffect } from '../../lib/teact/teact';
|
import { useEffect } from '@teact';
|
||||||
|
|
||||||
import { createCallbackManager } from '../../util/callbacks';
|
import { createSignal } from '../../util/signals';
|
||||||
import useLastCallback from '../useLastCallback';
|
import useLastCallback from '../useLastCallback';
|
||||||
|
|
||||||
const blurCallbacks = createCallbackManager();
|
const [getIsInBackgroundLocal, setIsInBackground] = createSignal(!document.hasFocus());
|
||||||
const focusCallbacks = createCallbackManager();
|
export const getIsInBackground = getIsInBackgroundLocal;
|
||||||
|
|
||||||
let isFocused = document.hasFocus();
|
function handleBlur() {
|
||||||
|
setIsInBackground(true);
|
||||||
|
}
|
||||||
|
|
||||||
window.addEventListener('blur', () => {
|
function handleFocus() {
|
||||||
if (!isFocused) {
|
setIsInBackground(false);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
isFocused = false;
|
window.addEventListener('blur', handleBlur);
|
||||||
blurCallbacks.runCallbacks();
|
window.addEventListener('focus', handleFocus);
|
||||||
});
|
|
||||||
|
|
||||||
window.addEventListener('focus', () => {
|
|
||||||
isFocused = true;
|
|
||||||
focusCallbacks.runCallbacks();
|
|
||||||
});
|
|
||||||
|
|
||||||
export default function useBackgroundMode(
|
export default function useBackgroundMode(
|
||||||
onBlur?: AnyToVoidFunction,
|
onBlur?: AnyToVoidFunction,
|
||||||
@ -35,20 +30,20 @@ export default function useBackgroundMode(
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isFocused) {
|
if (getIsInBackground()) {
|
||||||
lastOnBlur();
|
lastOnBlur();
|
||||||
}
|
}
|
||||||
|
|
||||||
blurCallbacks.addCallback(lastOnBlur);
|
return getIsInBackground.subscribe(() => {
|
||||||
focusCallbacks.addCallback(lastOnFocus);
|
if (getIsInBackground()) {
|
||||||
|
lastOnBlur();
|
||||||
return () => {
|
} else {
|
||||||
focusCallbacks.removeCallback(lastOnFocus);
|
lastOnFocus();
|
||||||
blurCallbacks.removeCallback(lastOnBlur);
|
}
|
||||||
};
|
});
|
||||||
}, [isDisabled, lastOnBlur, lastOnFocus]);
|
}, [isDisabled, lastOnBlur, lastOnFocus]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isBackgroundModeActive() {
|
export function isBackgroundModeActive() {
|
||||||
return !isFocused;
|
return getIsInBackground();
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user