Skip to content

Commit 80cd9ab

Browse files
committed
feat(utils): added useSafeAreaPadding hook
1 parent 7ba4461 commit 80cd9ab

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

packages/uikit-utils/src/hooks/index.ts

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* eslint-disable @typescript-eslint/no-explicit-any */
22
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';
45

56
type Destructor = () => void;
67
type AsyncEffectCallback = () => void | Destructor | Promise<void> | Promise<Destructor>;
@@ -72,3 +73,31 @@ export const useFreshCallback = <T extends (...args: any[]) => any>(callback: T)
7273
ref.current = callback;
7374
return useCallback(((...args) => ref.current(...args)) as T, []);
7475
};
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

Comments
 (0)