File size: 2,043 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import { useEffect, useRef } from 'react';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { isTauriAppPlatform, isWebAppPlatform } from '@/services/environment';
export const useScreenWakeLock = (lock: boolean) => {
const wakeLockRef = useRef<WakeLockSentinel | null>(null);
const unlistenOnFocusChangedRef = useRef<Promise<() => void> | null>(null);
useEffect(() => {
const requestWakeLock = async () => {
try {
if ('wakeLock' in navigator) {
wakeLockRef.current = await navigator.wakeLock.request('screen');
wakeLockRef.current.addEventListener('release', () => {
wakeLockRef.current = null;
});
console.log('Wake lock acquired');
}
} catch (err) {
console.info('Failed to acquire wake lock:', err);
}
};
const releaseWakeLock = () => {
if (wakeLockRef.current) {
wakeLockRef.current.release();
wakeLockRef.current = null;
console.log('Wake lock released');
}
};
const handleVisibilityChange = () => {
if (document.hidden) {
releaseWakeLock();
} else {
requestWakeLock();
}
};
if (lock) {
requestWakeLock();
} else if (wakeLockRef.current) {
releaseWakeLock();
}
if (isWebAppPlatform() && lock) {
document.addEventListener('visibilitychange', handleVisibilityChange);
} else if (isTauriAppPlatform() && lock) {
unlistenOnFocusChangedRef.current = getCurrentWindow().onFocusChanged(
({ payload: focused }) => {
if (focused) {
requestWakeLock();
} else {
releaseWakeLock();
}
},
);
}
return () => {
releaseWakeLock();
if (isWebAppPlatform() && lock) {
document.removeEventListener('visibilitychange', handleVisibilityChange);
}
if (unlistenOnFocusChangedRef.current) {
unlistenOnFocusChangedRef.current.then((f) => f());
}
};
}, [lock]);
};
|