UIPackage React Native
Search

Scroll Shadow

Bounded scroll viewport with measured SVG edge fades that animate smoothly as content overflows vertically or horizontally.

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 scroll-shadow

Source files

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

components/ui/scroll-shadow/ScrollShadow.tsx
import * as React from 'react'
import {
  ScrollView,
  View,
  type LayoutChangeEvent,
  type NativeScrollEvent,
  type NativeSyntheticEvent,
  type ScrollViewProps,
  type ViewStyle,
} from 'react-native'
import Animated, { useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated'
import Svg, { Defs, LinearGradient, Rect, Stop } from 'react-native-svg'
import { motionDurations } from '@/lib/motion'
import { useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'

const DEFAULT_SHADOW_SIZE = 28
const OVERFLOW_THRESHOLD = 1

export type ScrollShadowOrientation = 'vertical' | 'horizontal'

export interface ScrollShadowProps extends ScrollViewProps {
  /** Scroll axis for edge fades. Automatically inferred as `'horizontal'` when `horizontal={true}`. */
  orientation?: ScrollShadowOrientation
  /** Thickness of each edge fade in pixels. Clamped to `>= 0`. */
  size?: number
  /** Fade color; defaults to the active theme's `background` token so edges blend in light and dark modes. */
  shadowColor?: string
  /** Hide both edge fades without unmounting the scroll container. */
  hideShadows?: boolean
  /** Classes applied to the outer bounded viewport `View`. */
  className?: string
  /** Optional classes applied to the inner `ScrollView`. */
  scrollViewClassName?: string
}

interface ShadowVisibility {
  showLeading: boolean
  showTrailing: boolean
}

function computeShadowVisibility(viewportSize: number, contentSize: number, offset: number): ShadowVisibility {
  if (viewportSize <= 0 || contentSize <= viewportSize + OVERFLOW_THRESHOLD) {
    return { showLeading: false, showTrailing: false }
  }
  return {
    showLeading: offset > OVERFLOW_THRESHOLD,
    showTrailing: offset + viewportSize < contentSize - OVERFLOW_THRESHOLD,
  }
}

function sanitizeGradientId(id: string): string {
  return id.replace(/[^a-zA-Z0-9_-]/g, '')
}

export const ScrollShadow = React.forwardRef<React.ComponentRef<typeof ScrollView>, ScrollShadowProps>(
  (
    {
      orientation = 'vertical',
      horizontal,
      size = DEFAULT_SHADOW_SIZE,
      shadowColor,
      hideShadows = false,
      className,
      scrollViewClassName,
      scrollEventThrottle,
      onLayout,
      onContentSizeChange,
      onScroll,
      children,
      ...props
    },
    ref,
  ) => {
    const isHorizontal = horizontal ?? orientation === 'horizontal'
    const shadowSize = Number.isFinite(size) ? Math.max(0, size) : DEFAULT_SHADOW_SIZE
    const themeColors = useThemeColors()
    const resolvedColor = shadowColor ?? themeColors.background
    const reduced = useReducedMotion()

    const idPrefix = sanitizeGradientId(React.useId())
    const leadingGradientId = `scroll-shadow-leading-${idPrefix}`
    const trailingGradientId = `scroll-shadow-trailing-${idPrefix}`

    const viewportRef = React.useRef({ width: 0, height: 0 })
    const contentRef = React.useRef({ width: 0, height: 0 })
    const offsetRef = React.useRef({ x: 0, y: 0 })

    const [visibility, setVisibility] = React.useState<ShadowVisibility>({
      showLeading: false,
      showTrailing: false,
    })

    const syncVisibility = React.useCallback((axisHorizontal: boolean) => {
      const viewportSize = axisHorizontal ? viewportRef.current.width : viewportRef.current.height
      const contentSize = axisHorizontal ? contentRef.current.width : contentRef.current.height
      const offset = axisHorizontal ? offsetRef.current.x : offsetRef.current.y
      const next = computeShadowVisibility(viewportSize, contentSize, offset)
      setVisibility((prev) =>
        prev.showLeading === next.showLeading && prev.showTrailing === next.showTrailing ? prev : next,
      )
    }, [])

    React.useEffect(() => {
      syncVisibility(isHorizontal)
    }, [isHorizontal, syncVisibility])

    const leadingOpacity = useSharedValue(0)
    const trailingOpacity = useSharedValue(0)

    React.useEffect(() => {
      const targetLeading = !hideShadows && shadowSize > 0 && visibility.showLeading ? 1 : 0
      const targetTrailing = !hideShadows && shadowSize > 0 && visibility.showTrailing ? 1 : 0
      leadingOpacity.value = reduced ? targetLeading : withTiming(targetLeading, { duration: motionDurations.fast })
      trailingOpacity.value = reduced ? targetTrailing : withTiming(targetTrailing, { duration: motionDurations.fast })
    }, [
      hideShadows,
      shadowSize,
      visibility.showLeading,
      visibility.showTrailing,
      reduced,
      leadingOpacity,
      trailingOpacity,
    ])

    const leadingStyle = useAnimatedStyle(() => ({ opacity: leadingOpacity.value }))
    const trailingStyle = useAnimatedStyle(() => ({ opacity: trailingOpacity.value }))

    const handleLayout = (event: LayoutChangeEvent) => {
      const { width, height } = event.nativeEvent.layout
      viewportRef.current = { width: Math.max(0, width), height: Math.max(0, height) }
      syncVisibility(isHorizontal)
      onLayout?.(event)
    }

    const handleContentSizeChange = (contentWidth: number, contentHeight: number) => {
      contentRef.current = { width: Math.max(0, contentWidth), height: Math.max(0, contentHeight) }
      syncVisibility(isHorizontal)
      onContentSizeChange?.(contentWidth, contentHeight)
    }

    const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
      const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent
      offsetRef.current = { x: contentOffset.x, y: contentOffset.y }
      if (contentSize) {
        contentRef.current = { width: Math.max(0, contentSize.width), height: Math.max(0, contentSize.height) }
      }
      if (layoutMeasurement) {
        viewportRef.current = {
          width: Math.max(0, layoutMeasurement.width),
          height: Math.max(0, layoutMeasurement.height),
        }
      }
      syncVisibility(isHorizontal)
      onScroll?.(event)
    }

    const leadingPositionStyle: ViewStyle = isHorizontal
      ? { position: 'absolute', top: 0, bottom: 0, left: 0, width: shadowSize }
      : { position: 'absolute', top: 0, left: 0, right: 0, height: shadowSize }

    const trailingPositionStyle: ViewStyle = isHorizontal
      ? { position: 'absolute', top: 0, bottom: 0, right: 0, width: shadowSize }
      : { position: 'absolute', bottom: 0, left: 0, right: 0, height: shadowSize }

    const gradientCoords = isHorizontal
      ? { x1: '0', y1: '0', x2: '1', y2: '0' }
      : { x1: '0', y1: '0', x2: '0', y2: '1' }

    const renderOverlays = !hideShadows && shadowSize > 0

    return (
      <View className={cn('relative overflow-hidden', className)}>
        <ScrollView
          {...props}
          ref={ref}
          horizontal={isHorizontal}
          scrollEventThrottle={scrollEventThrottle ?? 16}
          className={scrollViewClassName}
          onLayout={handleLayout}
          onContentSizeChange={handleContentSizeChange}
          onScroll={handleScroll}
        >
          {children}
        </ScrollView>

        {renderOverlays ? (
          <>
            <Animated.View
              pointerEvents="none"
              accessibilityElementsHidden
              importantForAccessibility="no-hide-descendants"
              style={[leadingPositionStyle, leadingStyle]}
            >
              <Svg width="100%" height="100%">
                <Defs>
                  <LinearGradient id={leadingGradientId} {...gradientCoords}>
                    <Stop offset="0" stopColor={resolvedColor} stopOpacity="1" />
                    <Stop offset="1" stopColor={resolvedColor} stopOpacity="0" />
                  </LinearGradient>
                </Defs>
                <Rect x="0" y="0" width="100%" height="100%" fill={`url(#${leadingGradientId})`} />
              </Svg>
            </Animated.View>

            <Animated.View
              pointerEvents="none"
              accessibilityElementsHidden
              importantForAccessibility="no-hide-descendants"
              style={[trailingPositionStyle, trailingStyle]}
            >
              <Svg width="100%" height="100%">
                <Defs>
                  <LinearGradient id={trailingGradientId} {...gradientCoords}>
                    <Stop offset="0" stopColor={resolvedColor} stopOpacity="0" />
                    <Stop offset="1" stopColor={resolvedColor} stopOpacity="1" />
                  </LinearGradient>
                </Defs>
                <Rect x="0" y="0" width="100%" height="100%" fill={`url(#${trailingGradientId})`} />
              </Svg>
            </Animated.View>
          </>
        ) : null}
      </View>
    )
  },
)
ScrollShadow.displayName = 'ScrollShadow'
components/ui/scroll-shadow/index.ts
export { ScrollShadow, type ScrollShadowOrientation, type ScrollShadowProps } from './ScrollShadow'

Dependencies

Registry items

npm packages

  • react-native-reanimated
  • react-native-svg
Browse layout and navigation