Skip to content

Commit

Permalink
fix: reacquire wakelock when getting focus again
Browse files Browse the repository at this point in the history
  • Loading branch information
morteako committed Nov 29, 2024
1 parent c99b481 commit 83cf2dc
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions apps/frontend/src/context/WakeLockContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ export const WakeLockContextProvider = ({
const { isRunning } = useData();
const [wakeLock, setWakeLock] = React.useState<WakeLockSentinel | null>(null);

const documentVisibility = React.useSyncExternalStore(
(callback) => {
document.addEventListener('visibilitychange', callback);
return () => {
document.removeEventListener('visibilitychange', callback);
};
},
() => document.visibilityState
);

const acquireWakeLock = async () => {
const wl = await navigator.wakeLock.request('screen');
setWakeLock(wl);
Expand All @@ -19,14 +29,14 @@ export const WakeLockContextProvider = ({
});
};
React.useEffect(() => {
if (isRunning) {
if (isRunning && documentVisibility === 'visible') {
acquireWakeLock().catch(() => console.warn('Could not acquire wakeLock'));
} else if (wakeLock) {
wakeLock
.release()
.catch(() => console.warn('Could not release wakeLock'));
}
}, [isRunning]);
}, [isRunning, documentVisibility]);

return (
<WakeLockContext.Provider value={null}>{children}</WakeLockContext.Provider>
Expand Down

0 comments on commit 83cf2dc

Please sign in to comment.