|
1 | 1 | /* eslint-disable @typescript-eslint/no-explicit-any */ |
2 | 2 | import type { DependencyList } from 'react'; |
3 | | -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; |
| 3 | +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; |
| 4 | +import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context'; |
4 | 5 |
|
5 | 6 | type Destructor = () => void; |
6 | 7 | type AsyncEffectCallback = () => void | Destructor | Promise<void> | Promise<Destructor>; |
@@ -72,3 +73,31 @@ export const useFreshCallback = <T extends (...args: any[]) => any>(callback: T) |
72 | 73 | ref.current = callback; |
73 | 74 | return useCallback(((...args) => ref.current(...args)) as T, []); |
74 | 75 | }; |
| 76 | + |
| 77 | +type EdgePaddingMap = { |
| 78 | + left: 'paddingLeft'; |
| 79 | + right: 'paddingRight'; |
| 80 | + top: 'paddingTop'; |
| 81 | + bottom: 'paddingBottom'; |
| 82 | +}; |
| 83 | +const edgePaddingMap: EdgePaddingMap = { |
| 84 | + left: 'paddingLeft', |
| 85 | + right: 'paddingRight', |
| 86 | + top: 'paddingTop', |
| 87 | + bottom: 'paddingBottom', |
| 88 | +}; |
| 89 | +export const useSafeAreaPadding = < |
| 90 | + T extends keyof EdgeInsets, |
| 91 | + Result extends { [key in EdgePaddingMap[T]]: EdgeInsets[T] }, |
| 92 | +>( |
| 93 | + edges: T[], |
| 94 | +): Result => { |
| 95 | + const safeAreaInsets = useSafeAreaInsets(); |
| 96 | + return useMemo(() => { |
| 97 | + return edges.reduce((map, edge) => { |
| 98 | + const paddingKey = edgePaddingMap[edge]; |
| 99 | + map[paddingKey] = safeAreaInsets[edge]; |
| 100 | + return map; |
| 101 | + }, {} as { [key in EdgePaddingMap[T]]: EdgeInsets[T] }); |
| 102 | + }, edges) as Result; |
| 103 | +}; |
0 commit comments