useSafeArea.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { getSystemInfoSync, getMenuButtonBoundingClientRectSync } from './useNativeAPI'
  2. export function getSafeAreaInset(safeAreaStyle = 'default') {
  3. // StatusBar & NavBar
  4. const isDefault = ['default', 'navBar'].includes(safeAreaStyle)
  5. // iPhoneX 竖屏安全区域
  6. const safeAreaInset = {
  7. top: isDefault ? 88 : 44, // StatusBar & NavBar
  8. left: 0,
  9. right: 0,
  10. bottom: 34, // Home Indicator
  11. }
  12. try {
  13. const menuRect = getMenuButtonBoundingClientRectSync()
  14. const windowInfo = getSystemInfoSync(['window', 'device'])
  15. const { safeArea, screenHeight, windowHeight } = windowInfo
  16. const isIOS = !!(windowInfo.system.toLowerCase().search('ios') + 1)
  17. // 状态栏高度
  18. const statusBarHeight = !windowInfo.statusBarHeight
  19. ? screenHeight - windowHeight - 20
  20. : windowInfo.statusBarHeight
  21. // 胶囊高度
  22. const navBarHeight = (menuRect.top - statusBarHeight) * 2 + menuRect.height
  23. // 下方扩展 4 像素高度, 防止下方边距太小
  24. const navBarExtendHeight = windowInfo.statusBarHeight && isIOS ? 4 : 0
  25. safeAreaInset.top = isDefault
  26. ? statusBarHeight + navBarHeight + navBarExtendHeight
  27. : Math.max(statusBarHeight, safeAreaInset.top)
  28. safeAreaInset.bottom = screenHeight - safeArea.bottom
  29. } catch (e) {
  30. /** Ignore */
  31. }
  32. return safeAreaInset
  33. }
  34. export const checkIPhoneX = ({ model, windowHeight, windowWidth }) => {
  35. return /iphone (x|12|13|14)/.test(model.toLowerCase()) || (windowHeight >= 812 && windowHeight / windowWidth > 2)
  36. }