|
| 1 | +import { createSignal } from 'solid-js' |
| 2 | +import { isServer } from 'solid-js/web' |
| 3 | +import useCssVar from '../useCssVar' |
| 4 | +import { useDebounceFn, useEventListener } from '..' |
| 5 | + |
| 6 | +const topName = '--hooks-safe-area-top' |
| 7 | +const rightName = '--hooks-safe-area-right' |
| 8 | +const bottomName = '--hooks-safe-area-bottom' |
| 9 | +const leftName = '--hooks-safe-area-left' |
| 10 | + |
| 11 | +type VarName = '--hooks-safe-area-top' | '--hooks-safe-area-right' | '--hooks-safe-area-bottom' | '--hooks-safe-area-left' |
| 12 | + |
| 13 | +function getValue(position: VarName) { |
| 14 | + return getComputedStyle(document.documentElement).getPropertyValue(position) |
| 15 | +} |
| 16 | + |
| 17 | +function useScreenSafeArea() { |
| 18 | + const [safeArea, setSafeArea] = createSignal({ |
| 19 | + top: '', |
| 20 | + right: '', |
| 21 | + bottom: '', |
| 22 | + left: '', |
| 23 | + }) |
| 24 | + |
| 25 | + if (!isServer) { |
| 26 | + const [, setTop] = useCssVar(topName) |
| 27 | + const [, setRight] = useCssVar(rightName) |
| 28 | + const [, setBottom] = useCssVar(bottomName) |
| 29 | + const [, setLeft] = useCssVar(leftName) |
| 30 | + |
| 31 | + setTop('env(safe-area-inset-top, 0px)') |
| 32 | + setRight('env(safe-area-inset-right, 0px)') |
| 33 | + setBottom('env(safe-area-inset-bottom, 0px)') |
| 34 | + setLeft('env(safe-area-inset-left, 0px)') |
| 35 | + |
| 36 | + const { run } = useDebounceFn(update) |
| 37 | + update() |
| 38 | + useEventListener('resize', run) |
| 39 | + } |
| 40 | + |
| 41 | + function update() { |
| 42 | + setSafeArea({ |
| 43 | + top: getValue(topName), |
| 44 | + right: getValue(rightName), |
| 45 | + bottom: getValue(bottomName), |
| 46 | + left: getValue(leftName), |
| 47 | + }) |
| 48 | + } |
| 49 | + |
| 50 | + return safeArea |
| 51 | +} |
| 52 | + |
| 53 | +export default useScreenSafeArea |
0 commit comments