UIPackage React Native
Search
Menu

Screen Footer

Sticky screen footer with safe-area bottom inset, keyboard avoidance, and scroll clearance context.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add screen-footer

Source files

Expand a file to read the source the installer copies into your app.

components/ui/screen-footer/ScreenFooter.tsx
import * as React from 'react'
import {
  Keyboard,
  Platform,
  View,
  useWindowDimensions,
  type KeyboardEvent,
  type LayoutChangeEvent,
  type ViewProps,
} from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { cn } from '@/lib/utils'

export interface ScreenFooterContextValue {
  height: number
  keyboardHeight: number
  clearance: number
}

interface ScreenFooterSetters {
  setHeight: React.Dispatch<React.SetStateAction<number>>
  setKeyboardHeight: React.Dispatch<React.SetStateAction<number>>
}

const DEFAULT_SCREEN_FOOTER_CONTEXT: ScreenFooterContextValue = {
  height: 0,
  keyboardHeight: 0,
  clearance: 0,
}

const ScreenFooterContext = React.createContext<ScreenFooterContextValue>(DEFAULT_SCREEN_FOOTER_CONTEXT)
const ScreenFooterSetterContext = React.createContext<ScreenFooterSetters | null>(null)

export interface ScreenFooterProviderProps {
  children?: React.ReactNode
}

export function ScreenFooterProvider({ children }: ScreenFooterProviderProps) {
  const [height, setHeight] = React.useState(0)
  const [keyboardHeight, setKeyboardHeight] = React.useState(0)

  const setters = React.useMemo<ScreenFooterSetters>(() => ({ setHeight, setKeyboardHeight }), [])

  const value = React.useMemo<ScreenFooterContextValue>(
    () => ({
      height,
      keyboardHeight,
      clearance: height + keyboardHeight,
    }),
    [height, keyboardHeight],
  )

  return (
    <ScreenFooterSetterContext.Provider value={setters}>
      <ScreenFooterContext.Provider value={value}>{children}</ScreenFooterContext.Provider>
    </ScreenFooterSetterContext.Provider>
  )
}

export function useScreenFooter(): ScreenFooterContextValue {
  return React.useContext(ScreenFooterContext)
}

export interface KeyboardOverlapInput {
  footerBottom?: number
  keyboardTop?: number
  keyboardHeight: number
  windowHeight?: number
}

/**
 * Computes how far a footer actually overlaps the soft keyboard in window coordinates.
 * When Android `adjustResize` has already shrunk the viewport above `keyboardTop`, overlap is `0`
 * (preventing double-lifting); on non-resized viewports (e.g. iOS), overlap equals the obscured height.
 */
export function computeKeyboardOverlap({
  footerBottom,
  keyboardTop,
  keyboardHeight,
  windowHeight,
}: KeyboardOverlapInput): number {
  if (!Number.isFinite(keyboardHeight) || keyboardHeight <= 0) return 0
  if (typeof keyboardTop === 'number' && Number.isFinite(keyboardTop)) {
    const referenceBottom =
      typeof footerBottom === 'number' && Number.isFinite(footerBottom)
        ? footerBottom
        : typeof windowHeight === 'number' && Number.isFinite(windowHeight) && windowHeight > 0
          ? windowHeight
          : undefined
    if (referenceBottom !== undefined) {
      const overlap = referenceBottom - keyboardTop
      if (overlap <= 0) return 0
      return Math.min(overlap, keyboardHeight)
    }
  }
  return keyboardHeight
}

export interface ScreenFooterProps extends ViewProps {
  avoidKeyboard?: boolean
  bordered?: boolean
  onHeightChange?: (height: number) => void
  className?: string
}

interface ActiveKeyboardMetrics {
  height: number
  screenY?: number
}

export const ScreenFooter = React.forwardRef<React.ComponentRef<typeof View>, ScreenFooterProps>(
  ({ avoidKeyboard = true, bordered = true, onHeightChange, onLayout, className, style, ...props }, ref) => {
    const insets = useSafeAreaInsets()
    const { height: windowHeight } = useWindowDimensions()
    const setters = React.useContext(ScreenFooterSetterContext)
    const [keyboardVisible, setKeyboardVisible] = React.useState(false)
    const [keyboardLift, setKeyboardLift] = React.useState(0)

    const viewRef = React.useRef<React.ComponentRef<typeof View> | null>(null)
    const mountedRef = React.useRef(true)
    const liftRef = React.useRef(0)
    const windowHeightRef = React.useRef(windowHeight)
    windowHeightRef.current = windowHeight
    const activeKeyboardRef = React.useRef<ActiveKeyboardMetrics | null>(null)

    const setRefs = React.useCallback(
      (node: React.ComponentRef<typeof View> | null) => {
        viewRef.current = node
        if (typeof ref === 'function') {
          ref(node)
        } else if (ref) {
          ref.current = node
        }
      },
      [ref],
    )

    const commitLift = React.useCallback(
      (nextLift: number) => {
        if (!mountedRef.current) return
        const safeLift = Number.isFinite(nextLift) && nextLift > 0 ? nextLift : 0
        liftRef.current = safeLift
        setKeyboardLift(safeLift)
        setters?.setKeyboardHeight(safeLift)
      },
      [setters],
    )

    const reconcileKeyboardLift = React.useCallback(
      (metrics: ActiveKeyboardMetrics | null) => {
        if (!metrics || metrics.height <= 0) {
          commitLift(0)
          return
        }

        const node = viewRef.current
        if (node && typeof node.measureInWindow === 'function' && typeof metrics.screenY === 'number') {
          node.measureInWindow((_x, y, _width, measuredHeight) => {
            if (!mountedRef.current || activeKeyboardRef.current !== metrics) return
            const unshiftedBottom =
              Number.isFinite(y) && Number.isFinite(measuredHeight) ? y + measuredHeight + liftRef.current : undefined
            const overlap = computeKeyboardOverlap({
              footerBottom: unshiftedBottom,
              keyboardTop: metrics.screenY,
              keyboardHeight: metrics.height,
              windowHeight: windowHeightRef.current,
            })
            commitLift(overlap)
          })
          return
        }

        const overlap = computeKeyboardOverlap({
          keyboardTop: metrics.screenY,
          keyboardHeight: metrics.height,
          windowHeight: windowHeightRef.current,
        })
        commitLift(overlap)
      },
      [commitLift],
    )

    React.useEffect(() => {
      mountedRef.current = true
      return () => {
        mountedRef.current = false
        activeKeyboardRef.current = null
        liftRef.current = 0
        setters?.setHeight(0)
        setters?.setKeyboardHeight(0)
      }
    }, [setters])

    React.useEffect(() => {
      if (!avoidKeyboard) {
        activeKeyboardRef.current = null
        setKeyboardVisible(false)
        commitLift(0)
        return
      }
      if (typeof Keyboard?.addListener !== 'function') {
        return
      }

      const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow'
      const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide'

      const showSub = Keyboard.addListener(showEvent, (event: KeyboardEvent) => {
        const rawHeight = event?.endCoordinates?.height
        const safeHeight = typeof rawHeight === 'number' && Number.isFinite(rawHeight) && rawHeight > 0 ? rawHeight : 0
        const rawScreenY = event?.endCoordinates?.screenY
        const safeScreenY = typeof rawScreenY === 'number' && Number.isFinite(rawScreenY) ? rawScreenY : undefined
        if (safeHeight <= 0) {
          activeKeyboardRef.current = null
          setKeyboardVisible(false)
          commitLift(0)
          return
        }
        const metrics: ActiveKeyboardMetrics = { height: safeHeight, screenY: safeScreenY }
        activeKeyboardRef.current = metrics
        setKeyboardVisible(true)
        reconcileKeyboardLift(metrics)
      })

      const hideSub = Keyboard.addListener(hideEvent, () => {
        activeKeyboardRef.current = null
        setKeyboardVisible(false)
        commitLift(0)
      })

      return () => {
        showSub?.remove?.()
        hideSub?.remove?.()
      }
    }, [avoidKeyboard, commitLift, reconcileKeyboardLift])

    React.useEffect(() => {
      if (avoidKeyboard && activeKeyboardRef.current) {
        reconcileKeyboardLift(activeKeyboardRef.current)
      }
    }, [avoidKeyboard, reconcileKeyboardLift, windowHeight])

    const handleLayout = React.useCallback(
      (event: LayoutChangeEvent) => {
        const rawHeight = event.nativeEvent.layout.height
        const nextHeight = Number.isFinite(rawHeight) && rawHeight >= 0 ? rawHeight : 0
        setters?.setHeight(nextHeight)
        onHeightChange?.(nextHeight)
        onLayout?.(event)
        if (avoidKeyboard && activeKeyboardRef.current) {
          reconcileKeyboardLift(activeKeyboardRef.current)
        }
      },
      [avoidKeyboard, onHeightChange, onLayout, reconcileKeyboardLift, setters],
    )

    const safeBottom = Number.isFinite(insets.bottom) && insets.bottom > 0 ? insets.bottom : 0
    const paddingBottom = keyboardVisible ? 0 : safeBottom

    return (
      <View
        ref={setRefs}
        {...props}
        onLayout={handleLayout}
        className={cn('w-full bg-background', bordered && 'border-t border-border', className)}
        style={[{ paddingBottom, marginBottom: keyboardLift }, style]}
      />
    )
  },
)
ScreenFooter.displayName = 'ScreenFooter'
components/ui/screen-footer/index.ts
export {
  ScreenFooter,
  ScreenFooterProvider,
  computeKeyboardOverlap,
  useScreenFooter,
  type KeyboardOverlapInput,
  type ScreenFooterContextValue,
  type ScreenFooterProps,
  type ScreenFooterProviderProps,
} from './ScreenFooter'

Dependencies

Registry items

npm packages

  • react-native-safe-area-context
Browse layout and navigation