diff --git a/src/hooks/useScreenSleep.ts b/src/hooks/useScreenSleep.ts new file mode 100644 index 0000000..35f75dc --- /dev/null +++ b/src/hooks/useScreenSleep.ts @@ -0,0 +1,62 @@ +import { useCallback, useEffect, useMemo, useState } from 'react'; + +import { is_fully } from '../utils/is_fully'; + +type ScreenSleepConfig = { + screenOff?: () => void; + screenOn?: () => void; +}; + +window._fullykiosk = window._fullykiosk || {}; + +export const useScreenSleep = (config?: ScreenSleepConfig) => { + if (!is_fully()) + return { + isScreenOn: false, + turnOff: () => {}, + turnOn: () => {}, + forceSleep: () => {}, + startScreensaver: () => {}, + stopScreensaver: () => {}, + startDaydream: () => {}, + stopDaydream: () => {}, + }; + + const [isScreenOn, setScreenOn] = useState(fully.getScreenOn()); + + const vId = useMemo(() => Math.random().toString(36).slice(2, 11), []); + + const onToggle = useCallback((state: 'on' | 'off') => { + if (state == 'on' && config?.screenOn) { + config.screenOn(); + setScreenOn(true); + } else if (state == 'off' && config?.screenOff) { + config.screenOff(); + setScreenOn(false); + } + }, []); + + window._fullykiosk[vId] = onToggle; + + useEffect(() => { + // Register events + fully.bind('screenOff', `_fullykiosk['${vId}']('on');`); + fully.bind('screenOn', `_fullykiosk['${vId}']('off');`); + + return () => { + // Unregister events + window._fullykiosk[vId] = undefined; + }; + }, [0]); + + return { + isScreenOn, + turnOff: () => fully.turnScreenOff(), + turnOn: () => fully.turnScreenOn(), + forceSleep: () => fully.forceSleep(), + startScreensaver: () => fully.startScreensaver(), + stopScreensaver: () => fully.stopScreensaver(), + startDaydream: () => fully.startDaydream(), + stopDaydream: () => fully.stopDaydream(), + }; +}; diff --git a/src/index.ts b/src/index.ts index efe9b78..abe9f31 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ export * from './hooks/useIpv6Address'; export * from './hooks/useMacAddress'; export * from './hooks/useOrientation'; export * from './hooks/useScreenBrightness'; +export * from './hooks/useScreenSleep'; export * from './hooks/useSerialNumber'; export * from './hooks/useSimSerialNumber'; export * from './hooks/useWifiSignalLevel'; diff --git a/test/App.tsx b/test/App.tsx index 926961a..57c8616 100644 --- a/test/App.tsx +++ b/test/App.tsx @@ -16,6 +16,7 @@ import { useMacAddress, useOrientation, useScreenBrightness, + useScreenSleep, useSerialNumber, useSerialNumberDeviceOwner, useSimSerialNumber, @@ -47,6 +48,14 @@ export const App: FC = () => { const { brightness, setBrightness } = useScreenBrightness(); const orientation = useOrientation(); const { width, height } = useDisplaySize(); + const { + isScreenOn, + startDaydream, + stopDaydream, + startScreensaver, + stopScreensaver, + turnOff, + } = useScreenSleep(); return (
Display size: {width} x {height}
++ Screen state: {isScreenOn ? 'Screen is on' : 'Screen is off'} + + + + + +