UIPackage React Native
Search

Spotlight

Measured single-target highlight with stale-measurement protection and caller-composed content.

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 spotlight

Source files

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

components/ui/spotlight/Spotlight.tsx
import * as React from 'react'
import {
  Keyboard,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  View,
  useWindowDimensions,
  type ViewProps,
} from 'react-native'
import Svg, { Path } from 'react-native-svg'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useReducedMotion } from 'react-native-reanimated'
import { Button, type ButtonProps } from '@/components/ui/button'
import { renderTextChildren } from '@/lib/label-children'
import { useTheme, useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'
import { spotlightMaskPath, visibleSpotlightRect, type SpotlightRect } from './spotlight.utils'

export interface SpotlightHandle {
  /** Call from the owning scroll view's onScroll when its target can move. */
  update: () => void
}

export interface SpotlightProps extends ViewProps {
  anchorRef: React.RefObject<Pick<React.ComponentRef<typeof View>, 'measureInWindow'> | null>
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  disabled?: boolean
  padding?: number
  className?: string
}

const CloseContext = React.createContext<(() => void) | null>(null)

/** One measured target and caller-composed content. Sequenced tours belong in a block. */
export const Spotlight = React.forwardRef<SpotlightHandle, SpotlightProps>(
  (
    {
      anchorRef,
      open,
      defaultOpen = false,
      onOpenChange,
      disabled = false,
      padding = 8,
      children,
      className,
      style,
      onLayout,
      ...props
    },
    ref,
  ) => {
    const [internal, setInternal] = React.useState(defaultOpen)
    const [measurement, setMeasurement] = React.useState<{
      rect: SpotlightRect
      anchor: Pick<React.ComponentRef<typeof View>, 'measureInWindow'>
      width: number
      height: number
    } | null>(null)
    const [bodyHeight, setBodyHeight] = React.useState(0)
    const { width, height } = useWindowDimensions()
    const insets = useSafeAreaInsets()
    const reduced = useReducedMotion()
    const colors = useThemeColors()
    const { resolvedTheme } = useTheme()
    const resolvedOpen = !disabled && (open ?? internal)
    const current = React.useRef({ open: resolvedOpen, width, height })
    current.current = { open: resolvedOpen, width, height }
    const epoch = React.useRef(0)
    const mounted = React.useRef(true)

    React.useEffect(() => {
      const requests = epoch
      mounted.current = true
      return () => {
        mounted.current = false
        requests.current++
      }
    }, [])

    const update = React.useCallback(() => {
      const request = ++epoch.current
      const anchor = anchorRef.current
      if (!mounted.current) return
      if (!current.current.open || !anchor) {
        setMeasurement(null)
        return
      }
      const requestedWidth = width
      const requestedHeight = height
      anchor.measureInWindow((x, y, targetWidth, targetHeight) => {
        if (
          !mounted.current ||
          request !== epoch.current ||
          !current.current.open ||
          anchorRef.current !== anchor ||
          current.current.width !== requestedWidth ||
          current.current.height !== requestedHeight
        )
          return
        const rect = visibleSpotlightRect(
          { x, y, width: targetWidth, height: targetHeight },
          requestedWidth,
          requestedHeight,
          padding,
        )
        setMeasurement(rect ? { rect, anchor, width: requestedWidth, height: requestedHeight } : null)
      })
    }, [anchorRef, width, height, padding])

    React.useImperativeHandle(ref, () => ({ update }), [update])
    React.useEffect(() => {
      const requests = epoch
      update()
      if (!resolvedOpen) return
      const show = Keyboard.addListener('keyboardDidShow', update)
      const hide = Keyboard.addListener('keyboardDidHide', update)
      return () => {
        requests.current++
        show.remove()
        hide.remove()
      }
    }, [resolvedOpen, update])

    const close = React.useCallback(() => {
      if (!current.current.open) return
      if (open === undefined) {
        current.current.open = false
        epoch.current++
        setInternal(false)
        setMeasurement(null)
      }
      onOpenChange?.(false)
    }, [open, onOpenChange])

    if (
      !resolvedOpen ||
      !measurement ||
      measurement.anchor !== anchorRef.current ||
      measurement.width !== width ||
      measurement.height !== height
    )
      return null

    const { rect } = measurement
    const gap = 12
    const above = Math.max(0, rect.y - insets.top - gap * 2)
    const below = Math.max(0, height - insets.bottom - rect.y - rect.height - gap * 2)
    const placeBelow = below >= Math.min(bodyHeight || 160, above) || below >= above
    const available = Math.max(48, placeBelow ? below : above)
    const top = placeBelow
      ? Math.min(height - insets.bottom - 48, rect.y + rect.height + gap)
      : Math.max(insets.top + gap, rect.y - gap - (bodyHeight || 160))

    return (
      <Modal
        visible
        transparent
        animationType={reduced ? 'none' : 'fade'}
        presentationStyle="overFullScreen"
        supportedOrientations={['portrait', 'portrait-upside-down', 'landscape-left', 'landscape-right']}
        statusBarTranslucent
        navigationBarTranslucent
        onRequestClose={close}
      >
        <View style={{ flex: 1 }} accessibilityViewIsModal onAccessibilityEscape={close}>
          <Pressable
            accessible={false}
            focusable={false}
            style={StyleSheet.absoluteFill}
            onPress={(event) => {
              const { locationX: x, locationY: y } = event.nativeEvent
              if (x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height) return
              close()
            }}
          >
            <Svg width={width} height={height} pointerEvents="none">
              <Path
                d={spotlightMaskPath(rect, width, height)}
                fill={resolvedTheme === 'dark' ? colors.background : colors.foreground}
                fillOpacity={0.65}
                fillRule="evenodd"
              />
            </Svg>
          </Pressable>
          <CloseContext.Provider value={close}>
            <View
              {...props}
              className={cn('gap-[12px] rounded-xl border border-border bg-card p-[16px]', className)}
              style={[
                { position: 'absolute', top, left: insets.left + 16, right: insets.right + 16, maxHeight: available },
                style,
              ]}
              onLayout={(event) => {
                setBodyHeight(event.nativeEvent.layout.height)
                onLayout?.(event)
              }}
            >
              <ScrollView
                keyboardShouldPersistTaps="handled"
                style={{ flexGrow: 0 }}
                contentContainerStyle={{ gap: 12 }}
              >
                {renderTextChildren(children)}
              </ScrollView>
            </View>
          </CloseContext.Provider>
        </View>
      </Modal>
    )
  },
)
Spotlight.displayName = 'Spotlight'

export const SpotlightClose = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ onPress, disabled, loading, children = 'Close highlight', ...props }, ref) => {
    const close = React.useContext(CloseContext)
    if (!close) throw new Error('SpotlightClose must be inside Spotlight')
    return (
      <Button
        {...props}
        ref={ref}
        disabled={disabled}
        loading={loading}
        onPress={(event) => {
          if (disabled || loading) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) close()
        }}
      >
        {children}
      </Button>
    )
  },
)
SpotlightClose.displayName = 'SpotlightClose'
components/ui/spotlight/spotlight.utils.ts
export interface SpotlightRect {
  x: number
  y: number
  width: number
  height: number
}

/** A missing/offscreen target must not leave an invisible modal above the app. */
export function visibleSpotlightRect(rect: SpotlightRect, width: number, height: number, padding = 8) {
  if (![rect.x, rect.y, rect.width, rect.height, width, height].every(Number.isFinite)) return null
  if (rect.width <= 0 || rect.height <= 0 || width <= 0 || height <= 0) return null
  if (rect.x >= width || rect.y >= height || rect.x + rect.width <= 0 || rect.y + rect.height <= 0) return null
  const inset = Number.isFinite(padding) ? Math.max(0, padding) : 8
  const x = Math.max(0, rect.x - inset)
  const y = Math.max(0, rect.y - inset)
  return {
    x,
    y,
    width: Math.min(width, rect.x + rect.width + inset) - x,
    height: Math.min(height, rect.y + rect.height + inset) - y,
  }
}

export function spotlightMaskPath(rect: SpotlightRect, width: number, height: number) {
  return `M0 0H${width}V${height}H0Z M${rect.x} ${rect.y}H${rect.x + rect.width}V${rect.y + rect.height}H${rect.x}Z`
}
components/ui/spotlight/index.ts
export * from './Spotlight'
export { visibleSpotlightRect, type SpotlightRect } from './spotlight.utils'

Dependencies

Registry items

npm packages

  • react-native-svg
  • react-native-safe-area-context
  • react-native-reanimated
Browse overlays and feedback