# AniUI — Full LLM Context > shadcn/ui for React Native. Beautiful. Minimal. Yours. This file contains the full source of every AniUI component and block. If you are an AI coding agent, prefer this file over scraping the docs — it is kept in sync with the registry on every release. ## Rules - ALL styling via className (Uniwind or NativeWind — same API). NEVER StyleSheet.create. - Named exports only. No default exports. - Import cn from @/lib/utils. - Import components from @/components/ui/{name}. - Use SafeAreaView from react-native-safe-area-context as the root wrapper. - accessibilityRole on every interactive element. - Strict TypeScript. No `any`. - Icons from lucide-react-native. Colors via useThemeColors(), never hardcoded hex. ## Install ```bash npx @aniui/cli init npx @aniui/cli add button text input card ``` Or via shadcn (registry is spec-compliant): ```bash npx shadcn@latest add https://aniui.dev/r/button.json ``` ## MCP ```json { "mcpServers": { "aniui": { "command": "npx", "args": ["-y", "@aniui/mcp"] } } } ``` Tools: list_components, search_components, get_component, get_component_usage, list_blocks, get_block, get_theme_tokens, get_theme_preset. --- # Components (150 total) ## Accordion - key: `accordion` - import: `import { Accordion } from "@/components/ui/accordion"` - description: Expandable content sections - tier: 3 - deps: lucide-react-native, react-native-svg, @rn-primitives/accordion, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, theme-provider ```tsx // components/ui/accordion.tsx import React from "react"; import { View, Pressable, Text } from "react-native"; import * as AccordionPrimitive from "@rn-primitives/accordion"; import Animated from "react-native-reanimated"; import { ChevronDown } from "lucide-react-native"; import { entering, exiting } from "@/components/ui/animate"; import { useThemeColors } from "@/components/ui/theme-provider"; import { cn } from "@/lib/utils"; export interface AccordionProps extends React.ComponentPropsWithoutRef { className?: string; defaultValue?: string; children?: React.ReactNode; type?: "single" | "multiple"; } export function Accordion({ className, defaultValue, children, type = "single", ...props }: AccordionProps) { // Split by `type` so TS can narrow Root's SingleRootProps | MultipleRootProps // discriminated union — a single-pass pass-through loses the discrimination. if (type === "single") { return ( {children} ); } return ( {children} ); } export interface AccordionItemProps extends React.ComponentPropsWithoutRef { className?: string; value: string; trigger: string; children?: React.ReactNode; } // Rendered inside the Item so useItemContext can read the open state. function AccordionTrigger({ label }: { label: string }) { const { isExpanded } = AccordionPrimitive.useItemContext(); const colors = useThemeColors(); return ( {label} ); } export function AccordionItem({ value, trigger, className, children, ...props }: AccordionItemProps) { return ( {children} ); } ``` ## ActionRail - key: `action-rail` - import: `import { ActionRail } from "@/components/ui/action-rail"` - description: Expandable icon toolbar that reveals labeled actions, with its own light/dark palette system - tier: 3 - deps: react-native-reanimated, lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/action-rail.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react"; import { Pressable, Text, useColorScheme, View } from "react-native"; import Animated, { FadeIn, FadeOut, LinearTransition, useAnimatedStyle, useReducedMotion, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { Ellipsis, X } from "lucide-react-native"; import { cn } from "@/lib/utils"; export type ActionRailSize = "sm" | "md"; export type ActionRailTheme = "light" | "dark"; export interface ActionRailPalette { track: string; border: string; action: string; actionText: string; toggle: string; toggleText: string; } interface ActionRailMetrics { trackPadding: number; gap: number; actionHeight: number; actionPaddingX: number; actionGap: number; toggleSize: number; iconSize: number; fontSize: number; } const SHELL_SPRING: WithSpringConfig = { damping: 13, stiffness: 150, mass: 0.5 }; const PRESS_SPRING: WithSpringConfig = { damping: 22, stiffness: 420, mass: 0.6 }; const PRESS_SCALE = 0.95; const GLYPH_SPRING: WithSpringConfig = { damping: 16, stiffness: 220, mass: 0.6 }; const GLYPH_MIN_SCALE = 0.55; const SIZES: Record = { sm: { trackPadding: 4, gap: 4, actionHeight: 32, actionPaddingX: 12, actionGap: 6, toggleSize: 32, iconSize: 14, fontSize: 12 }, md: { trackPadding: 6, gap: 6, actionHeight: 36, actionPaddingX: 14, actionGap: 8, toggleSize: 36, iconSize: 16, fontSize: 14 }, }; const LIGHT_PALETTE: ActionRailPalette = { track: "#ffffff", border: "#e3e7ec", action: "#f5f7fa", actionText: "#111111", toggle: "#111111", toggleText: "#ffffff", }; const DARK_PALETTE: ActionRailPalette = { track: "#171716", border: "#2b2a25", action: "#232320", actionText: "#f6f3ec", toggle: "#f6f3ec", toggleText: "#111111", }; const PALETTES: Record = { light: LIGHT_PALETTE, dark: DARK_PALETTE }; // Shared layout transition so the track resizes (as actions or the overflow // group mount/unmount) with the same spring feel as the press interactions, // instead of Reanimated's default linear layout animation. function shellLayout() { return LinearTransition.springify() .damping(SHELL_SPRING.damping as number) .stiffness(SHELL_SPRING.stiffness as number) .mass(SHELL_SPRING.mass as number); } interface ActionRailContextValue { expanded: boolean; setExpanded: (expanded: boolean) => void; notifyAction: (value?: string) => void; palette: ActionRailPalette; metrics: ActionRailMetrics; reduceMotion: boolean; } const ActionRailContext = createContext(null); function useActionRail(part: string) { const ctx = useContext(ActionRailContext); if (!ctx) throw new Error(`<${part}> must be rendered inside .`); return ctx; } const ActionRailTintContext = createContext(null); function useActionRailTint(fallback: string): string { return useContext(ActionRailTintContext) ?? fallback; } export interface ActionRailProps { children: React.ReactNode; className?: string; expanded?: boolean; defaultExpanded?: boolean; onExpandedChange?: (expanded: boolean) => void; onAction?: (value?: string) => void; collapseOnAction?: boolean; size?: ActionRailSize; theme?: ActionRailTheme; palette?: Partial; } /** * Expandable icon rail/toolbar: a track of always-visible actions plus a * `Trigger` that reveals an `Overflow` group of labeled actions. Ships its * own light/dark palette (independent of the app's shadcn theme tokens) so * the rail can sit as a floating overlay control on top of photos/maps/video * — override any color via the `palette` prop. */ export function ActionRail({ children, className, expanded: expandedProp, defaultExpanded = false, onExpandedChange, onAction, collapseOnAction = false, size = "md", theme: themeProp, palette: paletteProp, }: ActionRailProps) { const isControlled = expandedProp !== undefined; const [internalExpanded, setInternalExpanded] = useState(defaultExpanded); const expanded = isControlled ? (expandedProp as boolean) : internalExpanded; const reduceMotion = useReducedMotion(); const systemDark = useColorScheme() === "dark"; const theme = themeProp ?? (systemDark ? "dark" : "light"); const setExpanded = useCallback( (next: boolean) => { if (!isControlled) setInternalExpanded(next); onExpandedChange?.(next); }, [isControlled, onExpandedChange] ); const notifyAction = useCallback( (value?: string) => { onAction?.(value); if (collapseOnAction) setExpanded(false); }, [onAction, collapseOnAction, setExpanded] ); const palette = useMemo(() => ({ ...PALETTES[theme], ...paletteProp }), [theme, paletteProp]); const metrics = SIZES[size]; const ctx = useMemo( () => ({ expanded, setExpanded, notifyAction, palette, metrics, reduceMotion }), [expanded, setExpanded, notifyAction, palette, metrics, reduceMotion] ); return ( {children} ); } export interface ActionRailRowProps { children: React.ReactNode; className?: string; } export function ActionRailGroup({ children, className }: ActionRailRowProps) { const { metrics, reduceMotion } = useActionRail("ActionRailGroup"); return ( {children} ); } export function ActionRailOverflow({ children, className }: ActionRailRowProps) { const { expanded, metrics, reduceMotion } = useActionRail("ActionRailOverflow"); if (!expanded) return null; return ( {children} ); } export interface ActionRailActionProps { children: React.ReactNode; value?: string; onPress?: () => void; disabled?: boolean; className?: string; } export function ActionRailAction({ children, value, onPress, disabled = false, className }: ActionRailActionProps) { const { palette, metrics, notifyAction, reduceMotion } = useActionRail("ActionRailAction"); const pressed = useSharedValue(0); const hitSlop = Math.max(0, (48 - metrics.actionHeight) / 2); const pressStyle = useAnimatedStyle(() => ({ transform: [{ scale: 1 - (1 - PRESS_SCALE) * (reduceMotion ? 0 : pressed.value) }], })); const handlePress = useCallback(() => { onPress?.(); notifyAction(value); }, [onPress, notifyAction, value]); return ( { pressed.value = withSpring(1, PRESS_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, PRESS_SPRING); }} className={cn("flex-row items-center justify-center", disabled && "opacity-45", className)} style={{ backgroundColor: palette.action, height: metrics.actionHeight, minWidth: metrics.actionHeight, borderRadius: metrics.actionHeight / 2, paddingHorizontal: metrics.actionPaddingX, gap: metrics.actionGap, }} > {children} ); } export interface ActionRailIconProps { children: React.ReactNode | ((state: { color: string; size: number }) => React.ReactNode); className?: string; } export function ActionRailIcon({ children, className }: ActionRailIconProps) { const { palette, metrics } = useActionRail("ActionRailIcon"); const color = useActionRailTint(palette.actionText); const content = typeof children === "function" ? children({ color, size: metrics.iconSize }) : children; return ( {content} ); } export interface ActionRailLabelProps { children: React.ReactNode; className?: string; } export function ActionRailLabel({ children, className }: ActionRailLabelProps) { const { palette, metrics } = useActionRail("ActionRailLabel"); const color = useActionRailTint(palette.actionText); return ( {children} ); } export interface ActionRailTriggerProps { children?: React.ReactNode | ((state: { expanded: boolean; color: string; size: number }) => React.ReactNode); className?: string; } export function ActionRailTrigger({ children, className }: ActionRailTriggerProps) { const { expanded, setExpanded, palette, metrics, reduceMotion } = useActionRail("ActionRailTrigger"); const pressed = useSharedValue(0); const hitSlop = Math.max(0, (48 - metrics.toggleSize) / 2); const pressStyle = useAnimatedStyle(() => ({ transform: [{ scale: 1 - (1 - PRESS_SCALE) * (reduceMotion ? 0 : pressed.value) }], })); const state = { expanded, color: palette.toggleText, size: metrics.iconSize }; const content = typeof children === "function" ? children(state) : (children ?? null); return ( setExpanded(!expanded)} onPressIn={() => { pressed.value = withSpring(1, PRESS_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, PRESS_SPRING); }} className={cn("items-center justify-center", className)} style={{ backgroundColor: palette.toggle, width: metrics.toggleSize, height: metrics.toggleSize, borderRadius: metrics.toggleSize / 2 }} > {content ?? ( )} ); } interface DefaultTriggerGlyphProps { expanded: boolean; color: string; size: number; reduceMotion: boolean; } // Cross-fades the "more" glyph into a "close" glyph, each scaling up from // GLYPH_MIN_SCALE as it appears and back down as it leaves, plus a quarter // turn, so the swap reads as one continuous rotation rather than a hard cut. function DefaultTriggerGlyph({ expanded, color, size, reduceMotion }: DefaultTriggerGlyphProps) { const progress = useSharedValue(expanded ? 1 : 0); useEffect(() => { const target = expanded ? 1 : 0; progress.value = reduceMotion ? target : withSpring(target, GLYPH_SPRING); }, [expanded, reduceMotion, progress]); const moreStyle = useAnimatedStyle(() => { const shown = 1 - progress.value; return { opacity: shown, transform: [ { scale: GLYPH_MIN_SCALE + (1 - GLYPH_MIN_SCALE) * shown }, { rotate: `${progress.value * 90}deg` }, ], }; }); const closeStyle = useAnimatedStyle(() => ({ opacity: progress.value, transform: [ { scale: GLYPH_MIN_SCALE + (1 - GLYPH_MIN_SCALE) * progress.value }, { rotate: `${(progress.value - 1) * 90}deg` }, ], })); return ( ); } ``` ## ActionSheet - key: `action-sheet` - import: `import { ActionSheet } from "@/components/ui/action-sheet"` - description: Action sheet with options - tier: 3 - deps: @gorhom/bottom-sheet, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: bottom-sheet, theme-provider, fold ```tsx // components/ui/action-sheet.tsx import React, { forwardRef, useCallback } from "react"; import { View, Pressable, Text } from "react-native"; import { BottomSheetModal, BottomSheetBackdrop, BottomSheetView, } from "@gorhom/bottom-sheet"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { useFoldFeatures } from "@/components/ui/fold"; export interface ActionSheetAction { label: string; onPress: () => void; destructive?: boolean; } export interface ActionSheetProps { className?: string; title?: string; actions: ActionSheetAction[]; onCancel?: () => void; /** See BottomSheet's foldPane prop — same semantics. */ foldPane?: "left" | "right" | "full"; } export const ActionSheet = forwardRef( ({ className, title, actions, onCancel, foldPane = "left" }, ref) => { const colors = useThemeColors(); const fold = useFoldFeatures(); const renderBackdrop = useCallback( (backdropProps: React.ComponentProps) => ( ), [] ); const foldClamp = fold.foldX && foldPane !== "full" ? { width: fold.foldX, left: foldPane === "right" ? fold.foldX : 0 } : undefined; return ( {title && {title}} {actions.map((action, i) => ( {action.label} ))} {onCancel && ( Cancel )} ); } ); ActionSheet.displayName = "ActionSheet"; ``` ## Alert - key: `alert` - import: `import { Alert } from "@/components/ui/alert"` - description: Alert message with variants - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/alert.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const alertVariants = cva("rounded-lg border p-4", { variants: { variant: { default: "border-border bg-background", destructive: "border-destructive/50 bg-destructive/10", success: "border-green-500/50 bg-green-500/10", warning: "border-yellow-500/50 bg-yellow-500/10", }, }, defaultVariants: { variant: "default", }, }); const alertTitleVariants = cva("text-base font-semibold mb-1", { variants: { variant: { default: "text-foreground", destructive: "text-destructive", success: "text-green-600", warning: "text-yellow-600", }, }, defaultVariants: { variant: "default" }, }); export interface AlertProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; title?: string; titleClassName?: string; children?: React.ReactNode; } export function Alert({ variant, className, title, titleClassName, children, ...props }: AlertProps) { return ( {title && {title}} {children} ); } export interface AlertDescriptionProps extends React.ComponentPropsWithoutRef { className?: string; } export function AlertDescription({ className, ...props }: AlertDescriptionProps) { return ; } ``` ## AlertDialog - key: `alert-dialog` - import: `import { AlertDialog } from "@/components/ui/alert-dialog"` - description: Confirmation dialog with actions - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/alert-dialog.tsx import React from "react"; import { View, Pressable, Text, Modal } from "react-native"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; import { useFoldFeatures } from "@/components/ui/fold"; export interface AlertDialogProps { open: boolean; onOpenChange: (open: boolean) => void; children: React.ReactNode; } export function AlertDialog({ open, onOpenChange, children }: AlertDialogProps) { const fold = useFoldFeatures(); // Match Dialog's fold-awareness: center inside the left pane on an // unfolded Duo. No-op on every other device. const foldPadding = fold.foldX ? { paddingRight: fold.foldX } : undefined; return ( onOpenChange(false)}> {children} ); } export function AlertDialogContent({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children?: React.ReactNode }) { return ( {children} ); } export function AlertDialogHeader({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function AlertDialogTitle({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function AlertDialogDescription({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function AlertDialogFooter({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function AlertDialogAction({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children: React.ReactNode }) { return ( {typeof children === "string" ? {children} : children} ); } export function AlertDialogCancel({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children: React.ReactNode }) { return ( {typeof children === "string" ? {children} : children} ); } ``` ## Animate - key: `animate` - import: `import { Animate } from "@/components/ui/animate"` - description: Animation presets, spring configs, easing, and hooks for Reanimated 4 - tier: 2 - deps: react-native-reanimated ```tsx // components/ui/animate.tsx import { useCallback } from "react"; import { Easing, FadeIn, FadeOut, FadeInUp, FadeInDown, FadeOutUp, FadeOutDown, SlideInUp, SlideInDown, SlideInLeft, SlideInRight, SlideOutUp, SlideOutDown, SlideOutLeft, SlideOutRight, ZoomIn, ZoomOut, BounceIn, FlipInXUp, useSharedValue, useAnimatedStyle, useReducedMotion, withSpring, withTiming, withDelay, type WithSpringConfig, } from "react-native-reanimated"; // Single choke point for reduced-motion checks across the animated component // set (skeleton, typing-indicator, waveform, streaming-text, …) — components // import this instead of react-native-reanimated's useReducedMotion directly, // so a future change to how "reduced motion" is detected only touches one file. export { useReducedMotion }; // ── Spring Presets (iOS-quality physics) ────────────────────── export const springs: Record = { bouncy: { damping: 12, stiffness: 150, mass: 0.5 }, snappy: { damping: 18, stiffness: 250, mass: 0.8 }, gentle: { damping: 20, stiffness: 120, mass: 1 }, stiff: { damping: 26, stiffness: 350, mass: 1 }, default: { damping: 15, stiffness: 180, mass: 0.8 }, }; // ── Layout Animation Presets (entering) ─────────────────────── // Note: springify() makes content overshoot the target. Use it only for // transient surfaces like toasts/banners where bounce reads as "attention". // For dialogs and expand-in-place content (accordion/collapsible) we prefer // a clean ease-out so the layout doesn't visibly settle. export const entering = { fadeIn: FadeIn.duration(200), fadeInUp: FadeInUp.duration(220).easing(Easing.out(Easing.cubic)), fadeInDown: FadeInDown.duration(220).easing(Easing.out(Easing.cubic)), slideInUp: SlideInUp.duration(300).springify(), slideInDown: SlideInDown.duration(300).springify(), slideInLeft: SlideInLeft.duration(300).springify(), slideInRight: SlideInRight.duration(300).springify(), zoomIn: ZoomIn.duration(200).easing(Easing.out(Easing.cubic)), bounceIn: BounceIn.duration(400), flipInX: FlipInXUp.duration(400), }; // ── Layout Animation Presets (exiting) ──────────────────────── export const exiting = { fadeOut: FadeOut.duration(150), fadeOutUp: FadeOutUp.duration(200), fadeOutDown: FadeOutDown.duration(200), slideOutUp: SlideOutUp.duration(200), slideOutDown: SlideOutDown.duration(200), slideOutLeft: SlideOutLeft.duration(200), slideOutRight: SlideOutRight.duration(200), zoomOut: ZoomOut.duration(200), }; // ── Duration Presets (ms) ───────────────────────────────────── export const duration = { fast: 150, normal: 250, slow: 400, slower: 600, }; // ── Easing Presets ──────────────────────────────────────────── export const easing = { easeOut: Easing.out(Easing.cubic), easeIn: Easing.in(Easing.cubic), easeInOut: Easing.inOut(Easing.cubic), spring: Easing.bezier(0.175, 0.885, 0.32, 1.275), bounce: Easing.bounce, }; // ── Hooks ───────────────────────────────────────────────────── /** Spring-based scale for press feedback. Attach onPressIn/onPressOut to Pressable. */ export function usePressAnimation(scale = 0.96) { const pressed = useSharedValue(1); const animatedStyle = useAnimatedStyle(() => ({ transform: [{ scale: pressed.value }], })); const onPressIn = useCallback(() => { pressed.value = withSpring(scale, springs.snappy); }, [scale, pressed]); const onPressOut = useCallback(() => { pressed.value = withSpring(1, springs.snappy); }, [pressed]); return { animatedStyle, onPressIn, onPressOut }; } /** Staggered delay for child entrance animations. Returns delay(ms) for index. */ export function stagger(index: number, interval = 50) { return withDelay(index * interval, withTiming(1, { duration: duration.normal })); } ``` ## AnimatedHeaderScrollView - key: `animated-header-scrollview` - import: `import { AnimatedHeaderScrollView } from "@/components/ui/animated-header-scrollview"` - description: iOS-style collapsing large-title header ScrollView with blur backdrop on scroll - tier: 3 - deps: react-native-reanimated, expo-blur, react-native-safe-area-context, clsx, tailwind-merge ```tsx // components/ui/animated-header-scrollview.tsx import React from "react"; import { Platform, View, useColorScheme, type ScrollView } from "react-native"; import Animated, { Extrapolation, interpolate, useAnimatedProps, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, } from "react-native-reanimated"; import { BlurView } from "expo-blur"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { cn } from "@/lib/utils"; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const COMPACT_HEADER_HEIGHT = 44; export interface AnimatedHeaderScrollViewProps extends Omit, "onScroll"> { className?: string; /** Large title rendered inline at the top of the scroll content; shrinks into the compact header as the user scrolls. */ title: string; subtitle?: string; /** Right-aligned actions pinned to the compact header (e.g. icon buttons). Stays interactive while the header background is decorative. */ headerRight?: React.ReactNode; largeTitleClassName?: string; /** Scroll distance (px) over which the large title fully collapses into the compact header. */ collapseDistance?: number; /** Max BlurView intensity once fully scrolled. iOS only — Android falls back to a plain translucent backdrop. */ blurIntensity?: number; /** Space reserved above the header for the status bar/notch. Defaults to the * device's real safe-area inset — override (e.g. to 0) when this isn't * mounted at the actual top of the screen, such as inside a card or modal, * where the real inset would just add dead space. */ topInset?: number; } /** iOS-style collapsing large-title ScrollView: a big inline title fades/slides * away while a compact header title (and a blur+translucent backdrop) fades in, * both driven off a single `scrollY` shared value via `useAnimatedScrollHandler`. */ export function AnimatedHeaderScrollView({ className, title, subtitle, headerRight, largeTitleClassName, collapseDistance = 80, blurIntensity = 40, topInset: topInsetProp, children, contentContainerStyle, ...props }: AnimatedHeaderScrollViewProps) { const insets = useSafeAreaInsets(); const topInset = topInsetProp ?? insets.top; const dark = useColorScheme() === "dark"; const scrollY = useSharedValue(0); const headerHeight = COMPACT_HEADER_HEIGHT + topInset; const onScroll = useAnimatedScrollHandler({ onScroll: (event) => { scrollY.value = event.contentOffset.y; }, }); const headerBgStyle = useAnimatedStyle(() => ({ opacity: interpolate(scrollY.value, [0, collapseDistance], [0, 1], Extrapolation.CLAMP), })); const largeTitleStyle = useAnimatedStyle(() => ({ opacity: interpolate(scrollY.value, [0, collapseDistance * 0.75], [1, 0], Extrapolation.CLAMP), transform: [{ translateY: interpolate(scrollY.value, [0, collapseDistance], [0, -10], Extrapolation.CLAMP) }], })); const compactTitleStyle = useAnimatedStyle(() => ({ opacity: interpolate(scrollY.value, [collapseDistance * 0.5, collapseDistance], [0, 1], Extrapolation.CLAMP), transform: [ { translateY: interpolate(scrollY.value, [collapseDistance * 0.5, collapseDistance], [8, 0], Extrapolation.CLAMP) }, ], })); const blurProps = useAnimatedProps(() => ({ intensity: interpolate(scrollY.value, [0, collapseDistance], [0, blurIntensity], Extrapolation.CLAMP), })); return ( {Platform.OS === "ios" && ( )} {title} {headerRight && {headerRight}} {title} {subtitle && {subtitle}} {children} ); } ``` ## AnimatedInputBar - key: `animated-input-bar` - import: `import { AnimatedInputBar } from "@/components/ui/animated-input-bar"` - description: Text input with a per-character animated placeholder that cycles through multiple strings - tier: 3 - deps: react-native-reanimated, expo-blur, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/animated-input-bar.tsx import React, { useEffect, useMemo, useState } from "react"; import { Platform, TextInput, View, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import Animated, { Easing, FadeInDown, FadeOutUp, interpolate, useAnimatedProps, useSharedValue, withSequence, withTiming, } from "react-native-reanimated"; import { BlurView } from "expo-blur"; import { useThemeColors } from "@/components/ui/theme-provider"; import { cn } from "@/lib/utils"; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const CHAR_DELAY_STEP = 22; const ENTER_DURATION = 260; const EXIT_DURATION = 180; const animatedInputBarVariants = cva("flex-row items-center rounded-md border border-input bg-background py-2", { variants: { size: { sm: "min-h-9 px-3", md: "min-h-12 px-4", lg: "min-h-14 px-5", }, }, defaultVariants: { size: "md" }, }); const fontSizes = { sm: 14, md: 16, lg: 18 } as const; export interface AnimatedInputBarProps extends Omit, "placeholder" | "value" | "onChangeText">, VariantProps { className?: string; placeholderClassName?: string; /** Strings the placeholder cycles through, one at a time, while the field is empty and unfocused. */ placeholders: string[]; value?: string; onChangeText?: (text: string) => void; /** Milliseconds each placeholder stays visible before cycling to the next one. */ cycleInterval?: number; } /** A text input whose placeholder cycles through multiple strings, each swap * done character-by-character: outgoing glyphs fly out, incoming glyphs fly * in with a per-character stagger (Reanimated's `entering`/`exiting` layout * animations, keyed per cycle so every glyph remounts), plus a brief * `BlurView` pulse timed to the swap for a soft "typing" blur instead of an * instant cut. */ export const AnimatedInputBar = React.forwardRef, AnimatedInputBarProps>( function AnimatedInputBar( { className, placeholderClassName, size, placeholders, value, onChangeText, cycleInterval = 2600, style, ...props }, ref, ) { const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; const resolvedSize = size ?? "md"; const [focused, setFocused] = useState(false); const [internalValue, setInternalValue] = useState(value ?? ""); const [index, setIndex] = useState(0); const text = value ?? internalValue; const blurProgress = useSharedValue(0); const showPlaceholder = !focused && !text && placeholders.length > 0; useEffect(() => { if (!showPlaceholder || placeholders.length < 2) return; const id = setInterval(() => setIndex((i) => (i + 1) % placeholders.length), cycleInterval); return () => clearInterval(id); }, [showPlaceholder, placeholders.length, cycleInterval]); useEffect(() => { if (!showPlaceholder) return; blurProgress.value = withSequence(withTiming(1, { duration: 220 }), withTiming(0, { duration: 260 })); }, [index, showPlaceholder, blurProgress]); const animatedBlurProps = useAnimatedProps(() => ({ intensity: interpolate(blurProgress.value, [0, 1], [0, 6]), })); const characters = useMemo(() => Array.from(placeholders[index] ?? ""), [placeholders, index]); return ( {showPlaceholder && ( {characters.map((char, i) => ( {char === " " ? " " : char} ))} )} {Platform.OS === "ios" && showPlaceholder && ( )} { setInternalValue(next); onChangeText?.(next); }} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} placeholder="" className="flex-1 self-stretch p-0 text-foreground" style={[{ fontSize: fontSizes[resolvedSize] }, style]} textAlignVertical="center" keyboardAppearance={dark ? "dark" : "light"} selectionColor={caret} cursorColor={caret} {...props} /> ); }, ); ``` ## ArcList - key: `arc-list` - import: `import { ArcList } from "@/components/ui/arc-list"` - description: Items laid out along a curved arc with proximity scale/opacity, snap-to-focus, and a haptic tick on snap - tier: 2 - deps: react-native-reanimated, expo-haptics, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/arc-list.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react"; import { Pressable, Text, View, type LayoutChangeEvent, } from "react-native"; import * as Haptics from "expo-haptics"; import Animated, { Extrapolation, interpolate, interpolateColor, runOnJS, useAnimatedReaction, useAnimatedRef, useAnimatedScrollHandler, useAnimatedStyle, useDerivedValue, useSharedValue, type SharedValue, } from "react-native-reanimated"; import { useThemeColors } from "@/components/ui/theme-provider"; import { cn } from "@/lib/utils"; /** * A vertical list whose items are projected onto a curved arc (dial/wheel * picker), scaling and fading by distance from the focused center, snapping * to the nearest item on release with a haptic tick. */ export type ArcListSide = "left" | "right"; const DEFAULT_ITEM_HEIGHT = 56; const DEFAULT_SWEEP = 40; const MIN_SWEEP = 1; const MAX_SWEEP = 80; const MIN_RADIUS = 1; const HORIZON = Math.PI / 2; const DEFAULT_MIN_OPACITY = 0.3; const DEFAULT_MIN_SCALE = 0.82; const PLATEAU_FRACTION = 0.45; const PLATEAU_SCALE = 0.98; const PROXIMITY_SPAN = 1; const CENTER_Z = 1000; const Z_BAND_LIMIT = 3; const UNKNOWN_INDEX = -1; function radiusFromSweep(halfHeight: number, sweepDeg: number): number { "worklet"; const clamped = Math.min(Math.max(sweepDeg, MIN_SWEEP), MAX_SWEEP); const rad = (clamped * Math.PI) / 180; return Math.max(halfHeight / Math.sin(rad), MIN_RADIUS); } function offsetForIndex(index: number, itemHeight: number): number { "worklet"; return index * itemHeight; } function signedOffset( index: number, itemHeight: number, scrollY: number, ): number { "worklet"; return index * itemHeight - scrollY; } function arcPlacement(offset: number, radius: number, direction: 1 | -1) { "worklet"; const r = Math.max(radius, MIN_RADIUS); const theta = Math.max(-HORIZON, Math.min(HORIZON, offset / r)); const arcY = r * Math.sin(theta); return { bulge: r * (1 - Math.cos(theta)) * direction, lift: arcY - offset, tilt: (-theta * 180 * direction) / Math.PI, distance: Math.abs(arcY), onArc: Math.abs(offset / r) < HORIZON, }; } function nearestIndex( scrollY: number, itemHeight: number, count: number, ): number { "worklet"; if (count <= 0) return 0; return Math.max(0, Math.min(count - 1, Math.round(scrollY / itemHeight))); } interface ArcListContextValue { scrollY: SharedValue; count: SharedValue; itemHeight: number; radius: number; halfHeight: number; direction: 1 | -1; minOpacity: number; minScale: number; scrollToIndex: (index: number, animated?: boolean) => void; } interface ArcListItemContextValue { index: number; proximity: SharedValue; } const ArcListContext = createContext(null); const ArcListItemContext = createContext( null, ); const ArcListIndexContext = createContext(null); export interface ArcListProps extends React.ComponentPropsWithoutRef { itemHeight?: number; height?: number; sweep?: number; radius?: number; side?: ArcListSide; snap?: boolean; value?: number; defaultValue?: number; onValueChange?: (index: number) => void; minOpacity?: number; minScale?: number; haptics?: boolean; className?: string; } /** Scrollable arc/dial container. Children are `ArcListItem`s — index is auto-assigned by position. */ export function ArcList({ children, itemHeight = DEFAULT_ITEM_HEIGHT, height, sweep = DEFAULT_SWEEP, radius: radiusProp, side = "left", snap = true, value, defaultValue = 0, onValueChange, minOpacity = DEFAULT_MIN_OPACITY, minScale = DEFAULT_MIN_SCALE, haptics = true, className, style, ...props }: ArcListProps) { const initialIndex = value ?? defaultValue; const scrollRef = useAnimatedRef(); const scrollY = useSharedValue(offsetForIndex(initialIndex, itemHeight)); const count = useSharedValue(0); const [measuredHeight, setMeasuredHeight] = useState(0); const [activeIndex, setActiveIndex] = useState(initialIndex); const didRestore = useRef(false); const viewportHeight = height ?? measuredHeight; const halfHeight = viewportHeight / 2; const radius = radiusProp ?? radiusFromSweep(halfHeight, sweep); const direction: 1 | -1 = side === "right" ? -1 : 1; const handleLayout = useCallback( (e: LayoutChangeEvent) => { if (height !== undefined) return; setMeasuredHeight(e.nativeEvent.layout.height); }, [height], ); const scrollToIndex = useCallback( (index: number, animated = true) => { scrollRef.current?.scrollTo({ y: offsetForIndex(index, itemHeight), animated, }); }, [itemHeight, scrollRef], ); const handleFocus = useCallback( (index: number) => { setActiveIndex(index); onValueChange?.(index); if (haptics) Haptics.selectionAsync(); }, [onValueChange, haptics], ); useAnimatedReaction( () => count.value > 0 ? nearestIndex(scrollY.value, itemHeight, count.value) : UNKNOWN_INDEX, (current, previous) => { if (previous === null || previous === UNKNOWN_INDEX) return; if (current === UNKNOWN_INDEX || current === previous) return; runOnJS(handleFocus)(current); }, [itemHeight, handleFocus], ); useEffect(() => { if (value === undefined || value === activeIndex) return; scrollToIndex(value); }, [value, activeIndex, scrollToIndex]); const scrollHandler = useAnimatedScrollHandler({ onScroll: (e) => { scrollY.value = e.contentOffset.y; }, }); const total = React.Children.count(children); useEffect(() => { count.value = total; }, [total, count]); const handleContentSizeChange = useCallback(() => { if (didRestore.current) return; didRestore.current = true; if (initialIndex <= 0) return; scrollRef.current?.scrollTo({ y: offsetForIndex(initialIndex, itemHeight), animated: false, }); }, [initialIndex, itemHeight, scrollRef]); const contentPadding = Math.max(halfHeight - itemHeight / 2, 0); const rows = React.Children.map(children, (child, index) => ( {child} )); const contextValue = useMemo( () => ({ scrollY, count, itemHeight, radius, halfHeight, direction, minOpacity, minScale, scrollToIndex, }), [ scrollY, count, itemHeight, radius, halfHeight, direction, minOpacity, minScale, scrollToIndex, ], ); return ( {viewportHeight > 0 ? ( {rows} ) : null} ); } export interface ArcListItemProps extends Omit, "onPress"> { onPress?: (index: number) => void; className?: string; } /** A single arc-projected, snap-to row. Wrap label/indicator content as children. */ export function ArcListItem({ children, disabled = false, onPress, className, style, ...props }: ArcListItemProps) { const ctx = useContext(ArcListContext); if (!ctx) { throw new Error("ArcListItem must be rendered inside an ArcList"); } const injectedIndex = useContext(ArcListIndexContext); const index = injectedIndex ?? 0; const rItem = useAnimatedStyle(() => { const offset = signedOffset(index, ctx.itemHeight, ctx.scrollY.value); const placement = arcPlacement(offset, ctx.radius, ctx.direction); const plateau = ctx.halfHeight * PLATEAU_FRACTION; const opacity = placement.onArc ? interpolate( placement.distance, [0, plateau, ctx.halfHeight], [1, 1, ctx.minOpacity], Extrapolation.CLAMP, ) : 0; const scale = interpolate( placement.distance, [0, plateau, ctx.halfHeight], [1, PLATEAU_SCALE, ctx.minScale], Extrapolation.CLAMP, ); return { opacity, zIndex: CENTER_Z - Math.min(Math.round(placement.distance / ctx.itemHeight), Z_BAND_LIMIT), transform: [ { translateX: placement.bulge }, { translateY: placement.lift }, { rotate: `${placement.tilt}deg` }, { scale }, ], }; }, [index, ctx]); const proximity = useDerivedValue(() => { const offset = signedOffset(index, ctx.itemHeight, ctx.scrollY.value); return interpolate( Math.abs(offset), [0, ctx.itemHeight * PROXIMITY_SPAN], [1, 0], Extrapolation.CLAMP, ); }, [index, ctx]); const itemContextValue = useMemo( () => ({ index, proximity }), [index, proximity], ); const handlePress = useCallback(() => { ctx.scrollToIndex(index); onPress?.(index); }, [ctx, index, onPress]); return ( {children} ); } export interface ArcListLabelProps extends React.ComponentPropsWithoutRef { activeColor?: string; className?: string; } /** Convenience label whose color tints toward `activeColor` as its `ArcListItem` nears the center. */ export function ArcListLabel({ children, activeColor, className, style, numberOfLines = 1, ...props }: ArcListLabelProps) { const itemCtx = useContext(ArcListItemContext); if (!itemCtx) { throw new Error("ArcListLabel must be rendered inside an ArcListItem"); } const colors = useThemeColors(); const color = colors.mutedForeground; const tint = activeColor ?? colors.foreground; const rLabel = useAnimatedStyle( () => ({ color: interpolateColor(itemCtx.proximity.value, [0, 1], [color, tint]), }), [color, tint], ); return ( {children} ); } ``` ## AreaChart - key: `area-chart` - import: `import { AreaChart } from "@/components/ui/area-chart"` - description: Skia area chart with entrance draw-on, data morphing, and a drag-to-scrub tooltip - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip, theme-provider ```tsx // components/ui/area-chart.tsx import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, LayoutChangeEvent, useColorScheme } from "react-native"; import { Canvas, Circle, Group, LinearGradient, Path, vec } from "@shopify/react-native-skia"; import Animated, { Easing, cancelAnimation, runOnJS, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; import { ChartTooltip } from "@/components/ui/chart-tooltip"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface AreaChartDataPoint { label: string; value: number; } export interface AreaChartProps extends React.ComponentPropsWithoutRef { className?: string; data: AreaChartDataPoint[]; height?: number; color?: string; fillOpacity?: number; showGrid?: boolean; showLabels?: boolean; curved?: boolean; series?: { data: AreaChartDataPoint[]; color: string }[]; onPointChange?: (point: AreaChartDataPoint, index: number) => void; } type PixelPoint = { x: number; y: number }; type CurveFrame = { points: PixelPoint[]; tangents: number[] }; type Padding = { top: number; right: number; bottom: number; left: number }; const DRAW_DURATION = 900; const MORPH_DURATION = 550; const SPRING_CONFIG = { damping: 20, stiffness: 300, mass: 1 }; const MAX_MORPH_SAMPLES = 160; function lerpNum(from: number, to: number, t: number): number { "worklet"; return from + (to - from) * t; } // Plain-JS (JS-thread only) mapping of data values into plot-space pixels. function computePixelPoints(points: AreaChartDataPoint[], maxVal: number, pad: Padding, plotWidth: number, plotHeight: number): PixelPoint[] { const n = points.length; return points.map((p, i) => ({ x: pad.left + (n > 1 ? (i / (n - 1)) * plotWidth : 0), y: pad.top + plotHeight - (p.value / Math.max(maxVal, 1)) * plotHeight, })); } // Fritsch-Carlson monotone cubic Hermite tangents, clamped so a segment's // tangent/slope ratio never exceeds magnitude 3 (prevents overshoot). function computeMonotoneTangents(points: PixelPoint[]): number[] { "worklet"; const n = points.length; if (n < 2) return points.map(() => 0); const slopes: number[] = []; for (let i = 0; i < n - 1; i++) { const run = points[i + 1]!.x - points[i]!.x; slopes.push(run === 0 ? 0 : (points[i + 1]!.y - points[i]!.y) / run); } const tangents: number[] = [slopes[0]!]; for (let i = 1; i < n - 1; i++) { const a = slopes[i - 1]!; const b = slopes[i]!; tangents.push(a * b <= 0 ? 0 : (a + b) / 2); } tangents.push(slopes[n - 2]!); for (let i = 0; i < n - 1; i++) { const slope = slopes[i]!; if (slope === 0) { tangents[i] = 0; tangents[i + 1] = 0; continue; } const a = tangents[i]! / slope; const b = tangents[i + 1]! / slope; const magnitude = a * a + b * b; if (magnitude > 9) { const scale = 3 / Math.sqrt(magnitude); tangents[i] = scale * a * slope; tangents[i + 1] = scale * b * slope; } } return tangents; } function tangentsForCurve(points: PixelPoint[], curved: boolean): number[] { "worklet"; return curved ? computeMonotoneTangents(points) : []; } function buildCurvePath(points: PixelPoint[], tangents: number[], curved: boolean): string { "worklet"; if (points.length === 0) return "M 0 0"; if (points.length === 1) return `M ${points[0]!.x} ${points[0]!.y}`; let d = `M ${points[0]!.x} ${points[0]!.y}`; for (let i = 0; i < points.length - 1; i++) { const from = points[i]!; const to = points[i + 1]!; if (!curved) { d += ` L ${to.x} ${to.y}`; continue; } const run = (to.x - from.x) / 3; const c1x = from.x + run; const c1y = from.y + tangents[i]! * run; const c2x = to.x - run; const c2y = to.y - tangents[i + 1]! * run; d += ` C ${c1x} ${c1y} ${c2x} ${c2y} ${to.x} ${to.y}`; } return d; } // Line path + close down to the baseline — the standard "append L/L/Z" // technique for turning a line path into a filled area beneath it. function buildFillPath(points: PixelPoint[], tangents: number[], curved: boolean, baselineY: number): string { "worklet"; if (points.length < 2) return "M 0 0"; const line = buildCurvePath(points, tangents, curved); const first = points[0]!; const last = points[points.length - 1]!; return `${line} L ${last.x} ${baselineY} L ${first.x} ${baselineY} Z`; } function yAtX(points: PixelPoint[], tangents: number[], curved: boolean, x: number): number { "worklet"; if (points.length === 0) return 0; if (points.length === 1) return points[0]!.y; if (x <= points[0]!.x) return points[0]!.y; const last = points[points.length - 1]!; if (x >= last.x) return last.y; let idx = 0; for (let i = 0; i < points.length - 1; i++) { if (x >= points[i]!.x && x <= points[i + 1]!.x) { idx = i; break; } } const from = points[idx]!; const to = points[idx + 1]!; const run = to.x - from.x; if (run === 0) return to.y; const t = (x - from.x) / run; if (!curved) return lerpNum(from.y, to.y, t); const t2 = t * t; const t3 = t2 * t; const h00 = 2 * t3 - 3 * t2 + 1; const h10 = t3 - 2 * t2 + t; const h01 = -2 * t3 + 3 * t2; const h11 = t3 - t2; return h00 * from.y + h10 * run * (tangents[idx] ?? 0) + h01 * to.y + h11 * run * (tangents[idx + 1] ?? 0); } function slopeAtX(points: PixelPoint[], tangents: number[], curved: boolean, x: number): number { "worklet"; if (points.length < 2) return 0; let idx = points.length - 2; for (let i = 0; i < points.length - 1; i++) { if (x >= points[i]!.x && x <= points[i + 1]!.x) { idx = i; break; } } const from = points[idx]!; const to = points[idx + 1]!; const run = to.x - from.x; if (run === 0) return 0; if (!curved) return (to.y - from.y) / run; const t = Math.min(Math.max((x - from.x) / run, 0), 1); const m0 = tangents[idx] ?? 0; const m1 = tangents[idx + 1] ?? 0; return ((6 * t * t - 6 * t) * (from.y - to.y)) / run + (3 * t * t - 4 * t + 1) * m0 + (3 * t * t - 2 * t) * m1; } // Entrance "draw-on": keep only the points left of the progress cutoff, // synthesizing one extra point exactly at the cutoff so the reveal never jumps. function cutAtProgress(points: PixelPoint[], tangents: number[], curved: boolean, progress: number): CurveFrame { "worklet"; if (progress >= 1 || points.length < 2) return { points, tangents }; const first = points[0]!; const last = points[points.length - 1]!; const cutoff = first.x + (last.x - first.x) * progress; if (cutoff <= first.x) return { points: [], tangents: [] }; const kept: PixelPoint[] = []; const keptTangents: number[] = []; for (let i = 0; i < points.length; i++) { if (points[i]!.x > cutoff) break; kept.push(points[i]!); keptTangents.push(tangents[i] ?? 0); } const tail = kept[kept.length - 1]; if (tail == null || tail.x < cutoff) { kept.push({ x: cutoff, y: yAtX(points, tangents, curved, cutoff) }); keptTangents.push(slopeAtX(points, tangents, curved, cutoff)); } return { points: kept, tangents: keptTangents }; } // Point-by-point lerp — only valid once both frames share the same vertex // count, which is guaranteed by the JS-side resampling done before a morph. function interpolateFrames(fromPts: PixelPoint[], fromTans: number[], toPts: PixelPoint[], toTans: number[], progress: number, curved: boolean): CurveFrame { "worklet"; if (progress >= 1 || fromPts.length !== toPts.length) return { points: toPts, tangents: toTans }; const points: PixelPoint[] = []; const tangents: number[] = []; for (let i = 0; i < toPts.length; i++) { points.push({ x: toPts[i]!.x, y: lerpNum(fromPts[i]!.y, toPts[i]!.y, progress) }); if (curved) tangents.push(lerpNum(fromTans[i] ?? 0, toTans[i] ?? 0, progress)); } return { points, tangents }; } function nearestIndex(points: PixelPoint[], x: number): number { "worklet"; let nearest = 0; let shortest = Math.abs(points[0]!.x - x); for (let i = 1; i < points.length; i++) { const d = Math.abs(points[i]!.x - x); if (d < shortest) { shortest = d; nearest = i; } } return nearest; } // A shared x-sample grid along the NEW curve, capped at ~160 samples, dense // enough that resampling the OLD curve at the same x's stays smooth. function buildSampleGrid(fromPts: PixelPoint[], toPts: PixelPoint[], curved: boolean): number[] { if (!curved || toPts.length < 2) return toPts.map((p) => p.x); const segments = toPts.length - 1; const wanted = Math.min(MAX_MORPH_SAMPLES, Math.max(toPts.length, fromPts.length * 4)); const factor = Math.min(8, Math.max(1, Math.round(wanted / segments))); if (factor <= 1) return toPts.map((p) => p.x); const xs: number[] = []; for (let i = 0; i < segments; i++) { const start = toPts[i]!.x; const step = (toPts[i + 1]!.x - start) / factor; for (let k = 0; k < factor; k++) xs.push(start + step * k); } xs.push(toPts[segments]!.x); return xs; } function resamplePoints(points: PixelPoint[], tangents: number[], curved: boolean, xs: number[]): PixelPoint[] { return xs.map((x) => ({ x, y: yAtX(points, tangents, curved, x) })); } function toRgba(color: string, alpha: number): string { if (!color.startsWith("#")) return color; let hex = color.slice(1); if (hex.length === 3) hex = hex.split("").map((c) => c + c).join(""); const r = parseInt(hex.slice(0, 2), 16); const g = parseInt(hex.slice(2, 4), 16); const b = parseInt(hex.slice(4, 6), 16); return `rgba(${r}, ${g}, ${b}, ${alpha})`; } // Owns the draw-on / morph-on-data-change timeline for a single series: on // first mount it reveals left-to-right, on later data changes with a // different point count it resamples old+new onto a shared grid so the // vertices line up before lerping between them. function useCurveFrame(pixelPoints: PixelPoint[], curved: boolean, isMeasured: boolean) { const targetPoints = useSharedValue([]); const targetTangents = useSharedValue([]); const originPoints = useSharedValue([]); const originTangents = useSharedValue([]); const morph = useSharedValue(1); const draw = useSharedValue(0); const hasEntered = useRef(false); const frame = useDerivedValue( () => interpolateFrames(originPoints.value, originTangents.value, targetPoints.value, targetTangents.value, morph.value, curved), [curved] ); const drawnFrame = useDerivedValue( () => cutAtProgress(frame.value.points, frame.value.tangents, curved, draw.value), [curved] ); useEffect(() => { if (!isMeasured || pixelPoints.length < 2) return; const nextTangents = tangentsForCurve(pixelPoints, curved); const isEntrance = !hasEntered.current; hasEntered.current = true; if (isEntrance) { originPoints.value = pixelPoints; originTangents.value = nextTangents; targetPoints.value = pixelPoints; targetTangents.value = nextTangents; cancelAnimation(morph); morph.value = 1; cancelAnimation(draw); draw.value = 0; draw.value = withTiming(1, { duration: DRAW_DURATION, easing: Easing.out(Easing.cubic) }); return; } const current = frame.value; const hasCurrent = current.points.length > 1; const source = hasCurrent ? current.points : targetPoints.value; const sourceTangents = hasCurrent ? current.tangents : targetTangents.value; const grid = buildSampleGrid(source, pixelPoints, curved); const origin = resamplePoints(source, sourceTangents, curved, grid); const target = resamplePoints(pixelPoints, nextTangents, curved, grid); originPoints.value = origin; originTangents.value = tangentsForCurve(origin, curved); targetPoints.value = target; targetTangents.value = tangentsForCurve(target, curved); cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); }, [pixelPoints, curved, isMeasured, frame, morph, draw, originPoints, originTangents, targetPoints, targetTangents]); return { frame, drawnFrame }; } // Self-contained area+line for one extra series (index >= 1). The primary // series (index 0) is rendered inline in AreaChart so its frame can drive // the scrub crosshair without threading refs across components. function SeriesLayer({ data, color, fillOpacity, curved, maxVal, pad, plotWidth, plotHeight, canvasHeight, isMeasured, }: { data: AreaChartDataPoint[]; color: string; fillOpacity: number; curved: boolean; maxVal: number; pad: Padding; plotWidth: number; plotHeight: number; canvasHeight: number; isMeasured: boolean; }) { const pixelPoints = useMemo(() => computePixelPoints(data, maxVal, pad, plotWidth, plotHeight), [data, maxVal, pad, plotWidth, plotHeight]); const baselineY = pad.top + plotHeight; const { drawnFrame } = useCurveFrame(pixelPoints, curved, isMeasured); const linePath = useDerivedValue(() => buildCurvePath(drawnFrame.value.points, drawnFrame.value.tangents, curved), [curved]); const areaPath = useDerivedValue(() => buildFillPath(drawnFrame.value.points, drawnFrame.value.tangents, curved, baselineY), [curved, baselineY]); return ( ); } export function AreaChart({ className, data, height = 200, color, fillOpacity = 0.3, showGrid = true, showLabels = false, curved = true, series, onPointChange, ...props }: AreaChartProps) { const [width, setWidth] = useState(0); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const resolvedColor = color ?? colors.primary; const gridColor = colors.border; const labelColor = colors.mutedForeground; const onLayout = useCallback((e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width), []); const pad = useMemo( () => (showLabels ? { top: 10, right: 10, bottom: 24, left: 36 } : { top: 10, right: 10, bottom: 10, left: 10 }), [showLabels] ); const plotWidth = Math.max(width - pad.left - pad.right, 0); const plotHeight = Math.max(height - pad.top - pad.bottom, 0); const baselineY = pad.top + plotHeight; const isMeasured = width > 0 && height > 0; const allSeries = useMemo(() => series ?? [{ data, color: resolvedColor }], [series, data, resolvedColor]); const maxVal = useMemo(() => Math.max(...allSeries.flatMap((s) => s.data.map((d) => d.value)), 1), [allSeries]); const primary = allSeries[0]!; const restSeries = allSeries.slice(1); const primaryPoints = useMemo( () => computePixelPoints(primary.data, maxVal, pad, plotWidth, plotHeight), [primary.data, maxVal, pad, plotWidth, plotHeight] ); const { frame, drawnFrame } = useCurveFrame(primaryPoints, curved, isMeasured); const primaryLinePath = useDerivedValue(() => buildCurvePath(drawnFrame.value.points, drawnFrame.value.tangents, curved), [curved]); const primaryAreaPath = useDerivedValue( () => buildFillPath(drawnFrame.value.points, drawnFrame.value.tangents, curved, baselineY), [curved, baselineY] ); const isActive = useSharedValue(0); const cursorX = useSharedValue(0); const cursorY = useSharedValue(0); const selectedIndex = useSharedValue(-1); const tooltipWidth = useSharedValue(0); const tooltipHeight = useSharedValue(0); const [activeIndex, setActiveIndex] = useState(-1); const reportPoint = useCallback( (index: number) => { setActiveIndex(index); const point = primary.data[index]; if (point != null) onPointChange?.(point, index); }, [primary.data, onPointChange] ); const clearPoint = useCallback(() => setActiveIndex(-1), []); const scrubTo = useCallback( (x: number) => { "worklet"; const { points, tangents } = frame.value; if (points.length < 2) return; const clampedX = Math.min(Math.max(x, points[0]!.x), points[points.length - 1]!.x); cursorX.value = clampedX; cursorY.value = yAtX(points, tangents, curved, clampedX); const idx = nearestIndex(points, clampedX); if (idx !== selectedIndex.value) { selectedIndex.value = idx; runOnJS(reportPoint)(idx); } }, [frame, curved, cursorX, cursorY, selectedIndex, reportPoint] ); const panGesture = useMemo( () => Gesture.Pan() .minDistance(0) .onBegin((e) => { "worklet"; scrubTo(e.x); isActive.value = withTiming(1, { duration: 140 }); }) .onUpdate((e) => { "worklet"; scrubTo(e.x); }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; runOnJS(clearPoint)(); }), [scrubTo, isActive, selectedIndex, clearPoint] ); const crosshairPath = useDerivedValue(() => `M ${cursorX.value} ${pad.top} L ${cursorX.value} ${baselineY}`, [pad.top, baselineY]); const cursorScale = useDerivedValue(() => withSpring(isActive.value, SPRING_CONFIG)); const dotRadius = useDerivedValue(() => 5 * cursorScale.value); const dotBorderRadius = useDerivedValue(() => 8 * cursorScale.value); const tooltipStyle = useAnimatedStyle(() => { const half = tooltipWidth.value / 2; const translateX = Math.min(Math.max(cursorX.value - half, 0), Math.max(width - tooltipWidth.value, 0)); const translateY = Math.max(cursorY.value - tooltipHeight.value - 14, 0); return { opacity: isActive.value, transform: [{ translateX }, { translateY }] }; }); if (width === 0) { return ; } const activePoint = activeIndex >= 0 ? primary.data[activeIndex] : undefined; const tooltipItems = allSeries.length > 1 && activeIndex >= 0 ? allSeries.map((s) => ({ label: s.data[activeIndex]?.label ?? "", value: s.data[activeIndex]?.value ?? 0, color: s.color })) : undefined; return ( {showGrid && [0, 1, 2, 3].map((i) => { const y = pad.top + (i / 3) * plotHeight; return ; })} {restSeries.map((s, i) => ( ))} {showLabels && ( <> {data.map((d, i) => ( 1 ? (i / (data.length - 1)) * plotWidth : 0) - 20, top: height - 18, width: 40, fontSize: 10, color: labelColor, textAlign: "center", }} > {d.label} ))} {[0, 1, 2, 3].map((i) => ( {Math.round((i / 3) * maxVal)} ))} )} { tooltipWidth.value = e.nativeEvent.layout.width; tooltipHeight.value = e.nativeEvent.layout.height; }} style={[{ position: "absolute", left: 0, top: 0 }, tooltipStyle]} > ); } ``` ## AspectRatio - key: `aspect-ratio` - import: `import { AspectRatio } from "@/components/ui/aspect-ratio"` - description: Constrains children to a fixed width/height ratio - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/aspect-ratio.tsx import React from "react"; import { View } from "react-native"; import { cn } from "@/lib/utils"; export interface AspectRatioProps extends React.ComponentPropsWithoutRef { className?: string; ratio?: number; children?: React.ReactNode; } // `aspectRatio` is a dynamic numeric layout value, so it goes through the style // prop — NativeWind/Uniwind only expose static `aspect-*` utility classes. export function AspectRatio({ ratio = 1, className, style, children, ...props }: AspectRatioProps) { return ( {children} ); } ``` ## AutoComplete - key: `autocomplete` - import: `import { AutoComplete } from "@/components/ui/autocomplete"` - description: Free-text input with inline filtered suggestions, keyboard-safe dropdown, and async loading state - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/autocomplete.tsx import React, { useState } from "react"; import { View, TextInput, Pressable, Text, ScrollView, Keyboard, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { X } from "lucide-react-native"; import { useThemeColors } from "@/components/ui/theme-provider"; import { cn } from "@/lib/utils"; // Matches input.tsx's size scale so Input, SearchBar, and AutoComplete read as one family. const autoCompleteVariants = cva("flex-row items-center rounded-md border py-2", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-3", md: "min-h-12 px-4", lg: "min-h-14 px-5", }, }, defaultVariants: { variant: "default", size: "md" }, }); const fontSizes = { sm: 14, md: 16, lg: 18 } as const; export interface AutoCompleteOption { label: string; value: string; disabled?: boolean; } export interface AutoCompleteProps extends Omit, "value" | "onChangeText">, VariantProps { className?: string; options: AutoCompleteOption[]; value?: string; onChangeText?: (text: string) => void; onSelect?: (option: AutoCompleteOption) => void; filterFn?: (option: AutoCompleteOption, query: string) => boolean; minCharsToTrigger?: number; loading?: boolean; emptyText?: string; maxVisibleOptions?: number; } const defaultFilter = (option: AutoCompleteOption, query: string) => option.label.toLowerCase().includes(query.toLowerCase()); // Suggestions render as a normal View below the input, not position: "absolute" — // RN has no reliable viewport-relative overlay without a portal, so this pushes // sibling content down instead; keep AutoComplete out of tight-height rows. export function AutoComplete({ variant, size = "md", className, options, value, onChangeText, onSelect, filterFn = defaultFilter, minCharsToTrigger = 1, loading, emptyText = "No results", maxVisibleOptions = 5, style, ...props }: AutoCompleteProps) { const [internal, setInternal] = useState(""); const [open, setOpen] = useState(false); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; const resolvedSize = size ?? "md"; const text = value ?? internal; const setText = (t: string) => { if (value === undefined) setInternal(t); onChangeText?.(t); setOpen(t.length >= minCharsToTrigger); }; const handleSelect = (option: AutoCompleteOption) => { if (option.disabled) return; onSelect?.(option); if (value === undefined) setInternal(option.label); setOpen(false); Keyboard.dismiss(); }; const showDropdown = open && text.length >= minCharsToTrigger; const filtered = showDropdown ? options.filter((o) => filterFn(o, text)) : []; return ( setOpen(text.length >= minCharsToTrigger)} className="flex-1 self-stretch p-0 text-foreground placeholder:text-muted-foreground" style={[{ fontSize: fontSizes[resolvedSize] }, style]} textAlignVertical="center" placeholderTextColor={colors.mutedForeground} keyboardAppearance={dark ? "dark" : "light"} selectionColor={caret} cursorColor={caret} {...props} /> {!!text && ( { setText(""); setOpen(false); }} className="ms-2 min-h-8 min-w-8 items-center justify-center" hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }} accessible accessibilityRole="button" accessibilityLabel="Clear" > )} {showDropdown && ( {loading ? ( Loading… ) : filtered.length === 0 ? ( {emptyText} ) : ( filtered.map((option) => ( handleSelect(option)} disabled={option.disabled} className={cn("min-h-12 min-w-12 justify-center px-4", option.disabled && "opacity-40")} accessible accessibilityRole="button" accessibilityState={{ disabled: option.disabled }} > {option.label} )) )} )} ); } ``` ## Avatar - key: `avatar` - import: `import { Avatar } from "@/components/ui/avatar"` - description: User avatar with image and fallback - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/avatar.tsx import React, { useState } from "react"; import { View, Image, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const avatarVariants = cva("items-center justify-center rounded-full bg-muted overflow-hidden", { variants: { size: { sm: "h-8 w-8", md: "h-10 w-10", lg: "h-14 w-14", }, }, defaultVariants: { size: "md", }, }); const avatarTextVariants = cva("font-medium text-muted-foreground", { variants: { size: { sm: "text-xs", md: "text-sm", lg: "text-lg", }, }, defaultVariants: { size: "md", }, }); export interface AvatarProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; src?: string; fallback?: string; } export function Avatar({ size, className, src, fallback, ...props }: AvatarProps) { const [hasError, setHasError] = useState(false); return ( {src && !hasError ? ( setHasError(true)} /> ) : ( {fallback ?? "?"} )} ); } ``` ## AvatarGroup - key: `avatar-group` - import: `import { AvatarGroup } from "@/components/ui/avatar-group"` - description: Overlapping avatar stack with max count and +N overflow bubble - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: avatar ```tsx // components/ui/avatar-group.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; // spacing is applied as a negative left margin per item (not -space-x-*) because // neither NativeWind nor Uniwind supports Tailwind's sibling-selector space utilities. const avatarGroupItemVariants = cva("rounded-full border-2 border-background", { variants: { spacing: { sm: "-ml-2", md: "-ml-3", lg: "-ml-4", }, }, defaultVariants: { spacing: "md", }, }); export interface AvatarGroupProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; max?: number; children?: React.ReactNode; } export function AvatarGroup({ spacing, max = 4, className, children, ...props }: AvatarGroupProps) { const items = React.Children.toArray(children); const visible = items.slice(0, max); const overflow = items.length - visible.length; return ( {visible.map((child, index) => ( {child} ))} {overflow > 0 && ( +{overflow} )} ); } ``` ## Badge - key: `badge` - import: `import { Badge } from "@/components/ui/badge"` - description: Small status indicator - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/badge.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const badgeVariants = cva("flex-row items-center rounded-full px-2.5 py-0.5", { variants: { variant: { default: "bg-primary", secondary: "bg-secondary", outline: "border border-border bg-transparent", destructive: "bg-destructive", }, }, defaultVariants: { variant: "default", }, }); const badgeTextVariants = cva("text-xs font-semibold", { variants: { variant: { default: "text-primary-foreground", secondary: "text-secondary-foreground", outline: "text-foreground", destructive: "text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, }); export interface BadgeProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; textClassName?: string; children: string; } export function Badge({ variant, className, textClassName, children, ...props }: BadgeProps) { return ( {children} ); } ``` ## Banner - key: `banner` - import: `import { Banner } from "@/components/ui/banner"` - description: Full-width notification banner with variants and dismiss - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/banner.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { X } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const bannerVariants = cva( "flex-row items-center rounded-xl px-4 py-3 gap-3 border", { variants: { variant: { default: "bg-secondary/60 border-border", info: "bg-primary/8 border-primary/15", warning: "bg-yellow-50 border-yellow-200 dark:bg-yellow-950/30 dark:border-yellow-900/40", destructive: "bg-destructive/8 border-destructive/15", success: "bg-green-50 border-green-200 dark:bg-green-950/30 dark:border-green-900/40", }, }, defaultVariants: { variant: "default" }, } ); const bannerTextVariants = cva("text-sm font-medium", { variants: { variant: { default: "text-foreground", info: "text-primary", warning: "text-yellow-800 dark:text-yellow-200", destructive: "text-destructive", success: "text-green-800 dark:text-green-200", }, }, defaultVariants: { variant: "default" }, }); export interface BannerProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; children: string; icon?: React.ReactNode; action?: { label: string; onPress: () => void }; onDismiss?: () => void; } export function Banner({ variant, className, children, icon, action, onDismiss, ...props }: BannerProps) { const colors = useThemeColors(); return ( {icon} {children} {action && ( {action.label} )} {onDismiss && ( )} ); } ``` ## BarChart - key: `bar-chart` - import: `import { BarChart } from "@/components/ui/bar-chart"` - description: Skia bar chart with staggered grow-in, data morphing, and a drag-to-scrub tooltip - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip, theme-provider ```tsx // components/ui/bar-chart.tsx import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, LayoutChangeEvent } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { Easing, cancelAnimation, runOnJS, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import { Canvas, Path } from "@shopify/react-native-skia"; import { cn } from "@/lib/utils"; import { ChartTooltip } from "@/components/ui/chart-tooltip"; import { useThemeColors } from "@/components/ui/theme-provider"; const GROW_DURATION = 900; const MORPH_DURATION = 550; const STAGGER = 0.35; const SPRING_CONFIG = { damping: 22, stiffness: 320, mass: 1 }; const PAD_WITH_LABELS = { top: 10, right: 10, bottom: 28, left: 36 }; const PAD_NO_LABELS = { top: 10, right: 10, bottom: 10, left: 10 }; function lerp(a: number, b: number, t: number): number { "worklet"; return a + (b - a) * t; } function clamp(v: number, lo: number, hi: number): number { "worklet"; return Math.min(Math.max(v, lo), hi); } function staggerProgress(progress: number, index: number, count: number, spread: number): number { "worklet"; if (count < 2 || spread <= 0) return clamp(progress, 0, 1); const window = 1 / (1 + (count - 1) * spread); const start = index * spread * window; return clamp((progress - start) / window, 0, 1); } function roundedRect(x: number, y: number, w: number, h: number, radius: number): string { "worklet"; const r = Math.min(radius, w / 2, h / 2); const right = x + w; const bottom = y + h; return ( `M ${x + r} ${y} L ${right - r} ${y} A ${r} ${r} 0 0 1 ${right} ${y + r} ` + `L ${right} ${bottom - r} A ${r} ${r} 0 0 1 ${right - r} ${bottom} ` + `L ${x + r} ${bottom} A ${r} ${r} 0 0 1 ${x} ${bottom - r} ` + `L ${x} ${y + r} A ${r} ${r} 0 0 1 ${x + r} ${y} Z` ); } function nearestTouchKey(targets: TouchTarget[], value: number): number { "worklet"; if (targets.length === 0) return -1; let key = targets[0]!.key; let dist = Math.abs(targets[0]!.center - value); for (let i = 1; i < targets.length; i++) { const d = Math.abs(targets[i]!.center - value); if (d < dist) { dist = d; key = targets[i]!.key; } } return key; } interface SlotLayout { x: number; y: number; w: number; h: number } interface TouchTarget { center: number; key: number } interface BarRect { x: number; top: number; width: number; height: number } interface Geometry { cw: number; ch: number; baselineX: number; baselineY: number; maxVal: number; slots: SlotLayout[]; touchTargets: TouchTarget[]; barW: number; gap: number; groupW: number; barH: number; } export interface BarChartDataPoint { label: string; value: number; color?: string; } export interface BarChartProps extends React.ComponentPropsWithoutRef { className?: string; data: BarChartDataPoint[]; height?: number; color?: string; horizontal?: boolean; showGrid?: boolean; showLabels?: boolean; barRadius?: number; grouped?: { key: string; color: string }[]; groupedData?: { label: string; values: number[] }[]; onBarChange?: (index: number) => void; } interface BarShapeProps { bars: SharedValue; index: number; color: string; radius: number; selectedIndex: SharedValue; isActive: SharedValue; highlightKey: number; } const BarShape = React.memo(function BarShape( { bars, index, color, radius, selectedIndex, isActive, highlightKey }: BarShapeProps ) { const path = useDerivedValue(() => { const bar = bars.value[index]; if (!bar || bar.width <= 0.5 || bar.height <= 0.5) return "M 0 0"; return roundedRect(bar.x, bar.top, bar.width, bar.height, radius); }, [index, radius]); const selection = useDerivedValue(() => withSpring(selectedIndex.value === highlightKey ? 1 : 0, SPRING_CONFIG), [highlightKey]); const opacity = useDerivedValue(() => 1 - isActive.value * 0.4 * (1 - selection.value)); return ; }); export function BarChart({ className, data, height = 200, color, horizontal = false, showGrid = true, showLabels = false, barRadius = 4, grouped, groupedData, onBarChange, ...props }: BarChartProps) { const [width, setWidth] = useState(0); const [selectedKey, setSelectedKey] = useState(-1); const colors = useThemeColors(); const resolvedColor = color ?? colors.primary; const gridColor = colors.border; const labelColor = colors.mutedForeground; const onLayout = useCallback((e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width), []); const isMeasured = width > 0; const isGrouped = !!(grouped && groupedData && grouped.length > 0 && groupedData.length > 0); const effectiveHorizontal = horizontal && !isGrouped; const pad = showLabels ? PAD_WITH_LABELS : PAD_NO_LABELS; const groupSize = grouped?.length ?? 1; const geometry = useMemo(() => { const cw = Math.max(width - pad.left - pad.right, 0); const ch = Math.max(height - pad.top - pad.bottom, 0); const baselineX = pad.left; const baselineY = pad.top + ch; const slots: SlotLayout[] = []; const touchTargets: TouchTarget[] = []; if (isGrouped && groupedData && grouped) { const maxVal = Math.max(...groupedData.flatMap((d) => d.values), 1); const groupW = groupedData.length > 0 ? cw / groupedData.length : 0; const barW = (groupW * 0.7) / grouped.length; groupedData.forEach((_, gi) => { grouped.forEach((_, bi) => { slots.push({ x: pad.left + gi * groupW + groupW * 0.15 + bi * barW, y: 0, w: barW * 0.85, h: 0 }); }); touchTargets.push({ center: pad.left + gi * groupW + groupW / 2, key: gi }); }); return { cw, ch, baselineX, baselineY, maxVal, slots, touchTargets, barW: barW * 0.85, gap: 0, groupW, barH: 0 }; } const maxVal = Math.max(...data.map((d) => Math.abs(d.value)), 1); if (effectiveHorizontal) { const barH = data.length > 0 ? (ch / data.length) * 0.7 : 0; data.forEach((_, i) => { const y = pad.top + (i / data.length) * ch + (ch / data.length) * 0.15; slots.push({ x: 0, y, w: 0, h: barH }); touchTargets.push({ center: y + barH / 2, key: i }); }); return { cw, ch, baselineX, baselineY, maxVal, slots, touchTargets, barW: 0, gap: 0, groupW: 0, barH }; } const barW = data.length > 0 ? (cw / data.length) * 0.7 : 0; const gap = data.length > 0 ? (cw / data.length) * 0.3 : 0; data.forEach((_, i) => { const x = pad.left + i * (barW + gap) + gap / 2; slots.push({ x, y: 0, w: barW, h: 0 }); touchTargets.push({ center: x + barW / 2, key: i }); }); return { cw, ch, baselineX, baselineY, maxVal, slots, touchTargets, barW, gap, groupW: 0, barH: 0 }; }, [width, height, pad, isGrouped, groupedData, grouped, effectiveHorizontal, data]); const gridPath = useMemo(() => { if (!showGrid || effectiveHorizontal) return ""; let d = ""; for (let i = 0; i <= 3; i++) { const y = pad.top + (i / 3) * geometry.ch; d += `M ${pad.left} ${y} L ${pad.left + geometry.cw} ${y} `; } return d.trim(); }, [showGrid, effectiveHorizontal, pad, geometry.ch, geometry.cw]); const barMeta = useMemo(() => { if (isGrouped && groupedData && grouped) { return groupedData.flatMap((_, gi) => grouped.map((g) => ({ color: g.color ?? resolvedColor, highlightKey: gi })) ); } return data.map((d, i) => ({ color: d.color ?? resolvedColor, highlightKey: i })); }, [isGrouped, groupedData, grouped, data, resolvedColor]); const originValues = useSharedValue([]); const targetValues = useSharedValue([]); const morph = useSharedValue(1); const grow = useSharedValue(0); const slotsSV = useSharedValue([]); const touchTargetsSV = useSharedValue([]); const selectedIndex = useSharedValue(-1); const isActive = useSharedValue(0); const tooltipWidth = useSharedValue(0); const tooltipHeight = useSharedValue(0); const hasEnteredRef = useRef(false); useEffect(() => { slotsSV.value = geometry.slots; touchTargetsSV.value = geometry.touchTargets; }, [geometry, slotsSV, touchTargetsSV]); useEffect(() => { if (!isMeasured) return; const values = isGrouped && groupedData ? groupedData.flatMap((d) => d.values) : data.map((d) => d.value); const isEntrance = !hasEnteredRef.current; hasEnteredRef.current = true; if (isEntrance || targetValues.value.length !== values.length) { originValues.value = values; targetValues.value = values; cancelAnimation(morph); morph.value = 1; cancelAnimation(grow); grow.value = 0; grow.value = withTiming(1, { duration: GROW_DURATION, easing: Easing.out(Easing.cubic) }); return; } const from = originValues.value; const to = targetValues.value; const progress = morph.value; originValues.value = values.map((_, i) => lerp(from[i] ?? 0, to[i] ?? 0, progress)); targetValues.value = values; cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); }, [data, groupedData, isMeasured, isGrouped, morph, grow, originValues, targetValues]); const bars = useDerivedValue(() => { const slotList = slotsSV.value; const origin = originValues.value; const target = targetValues.value; const count = slotList.length; const out: BarRect[] = []; for (let i = 0; i < count; i++) { const slot = slotList[i]!; const value = lerp(origin[i] ?? 0, target[i] ?? 0, morph.value); const progress = staggerProgress(grow.value, i, count, STAGGER); if (effectiveHorizontal) { const length = (Math.abs(value) / geometry.maxVal) * geometry.cw * progress; out.push({ x: geometry.baselineX, top: slot.y, width: length, height: slot.h }); } else { const length = (Math.abs(value) / geometry.maxVal) * geometry.ch * progress; const top = value >= 0 ? geometry.baselineY - length : geometry.baselineY; out.push({ x: slot.x, top, width: slot.w, height: length }); } } return out; }, [effectiveHorizontal, geometry.maxVal, geometry.cw, geometry.ch, geometry.baselineX, geometry.baselineY]); const reportSelection = useCallback((key: number) => { setSelectedKey(key); onBarChange?.(key); }, [onBarChange]); const panGesture = useMemo(() => { const selectNearest = (e: { x: number; y: number }) => { "worklet"; const key = nearestTouchKey(touchTargetsSV.value, effectiveHorizontal ? e.y : e.x); if (key >= 0 && key !== selectedIndex.value) { selectedIndex.value = key; runOnJS(reportSelection)(key); } }; return Gesture.Pan() .minDistance(0) .onBegin((e) => { "worklet"; selectNearest(e); isActive.value = withTiming(1, { duration: 140 }); }) .onUpdate((e) => { "worklet"; selectNearest(e); }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; }); }, [effectiveHorizontal, reportSelection, selectedIndex, isActive, touchTargetsSV]); const tooltipStyle = useAnimatedStyle(() => { const key = selectedIndex.value; const target = touchTargetsSV.value[key]; if (key < 0 || !target) return { opacity: 0, transform: [{ translateX: 0 }, { translateY: 0 }] }; if (effectiveHorizontal) { const rect = bars.value[key]; const tipX = rect ? rect.x + rect.width : geometry.baselineX; const x = clamp(tipX + 12, 0, Math.max(width - tooltipWidth.value, 0)); const y = clamp(target.center - tooltipHeight.value / 2, 0, Math.max(height - tooltipHeight.value, 0)); return { opacity: isActive.value, transform: [{ translateX: x }, { translateY: y }] }; } const start = isGrouped ? key * groupSize : key; let top = height; for (let i = start; i < start + groupSize; i++) { const rect = bars.value[i]; if (rect && rect.top < top) top = rect.top; } const x = clamp(target.center - tooltipWidth.value / 2, 0, Math.max(width - tooltipWidth.value, 0)); const y = clamp(top - tooltipHeight.value - 12, 0, Math.max(height - tooltipHeight.value, 0)); return { opacity: isActive.value, transform: [{ translateX: x }, { translateY: y }] }; }, [effectiveHorizontal, isGrouped, groupSize, width, height, geometry.baselineX]); const onTooltipLayout = useCallback((e: LayoutChangeEvent) => { tooltipWidth.value = e.nativeEvent.layout.width; tooltipHeight.value = e.nativeEvent.layout.height; }, [tooltipWidth, tooltipHeight]); return ( {isMeasured && ( {gridPath !== "" && } {barMeta.map((m, i) => ( ))} {showLabels && !effectiveHorizontal && !isGrouped && data.map((d, i) => ( {d.label} ))} {showLabels && isGrouped && groupedData && groupedData.map((d, i) => ( {d.label} ))} {showLabels && effectiveHorizontal && data.map((d, i) => ( {d.label} ))} {isGrouped && groupedData && grouped && groupedData[selectedKey] ? ( ({ label: g.key, value: groupedData[selectedKey]!.values[i] ?? 0, color: g.color }))} /> ) : !isGrouped && data[selectedKey] ? ( ) : null} )} ); } ``` ## BarcodeBadge - key: `barcode-badge` - import: `import { BarcodeBadge } from "@/components/ui/barcode-badge"` - description: Width-encoded barcode strip with compound Root/Bars/Label API and palette overrides - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/barcode-badge.tsx import React, { createContext, useContext, useMemo } from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; export type BarcodePalette = { bars: string; label: string }; const DEFAULT_PALETTE: BarcodePalette = { bars: "#18181b", label: "#18181b" }; const BarcodeBadgeContext = createContext<{ palette: BarcodePalette; seed: string; barCount: number; } | null>(null); function useBarcodeBadge(component: string) { const context = useContext(BarcodeBadgeContext); if (!context) { throw new Error(`${component} must be rendered inside .`); } return context; } /** Deterministic per-index bar width (2-4px) seeded from the encoded string. */ function widthForBar(seed: string, index: number): number { const source = seed.length > 0 ? seed : "aniui"; const code = source.charCodeAt(index % source.length); return 2 + ((code + index * 5) % 3); } export interface BarcodeBadgeProps extends React.ComponentPropsWithoutRef { className?: string; /** String encoded into the bar widths, and used as the default label. */ value: string; /** Overrides the rendered label text without changing the encoded value. */ label?: string; /** Overrides the default Bars + Label composition. */ children?: React.ReactNode; palette?: Partial; barCount?: number; hideLabel?: boolean; } export function BarcodeBadge({ className, value, label, children, palette, barCount = 28, hideLabel = false, ...props }: BarcodeBadgeProps) { const resolvedLabel = label ?? value; const context = useMemo( () => ({ palette: { ...DEFAULT_PALETTE, ...palette }, seed: value, barCount }), [palette, value, barCount] ); return ( {children ?? ( <> {!hideLabel && } )} ); } export interface BarcodeBadgeBarsProps extends React.ComponentPropsWithoutRef { className?: string; height?: number; gap?: number; color?: string; } export function BarcodeBadgeBars({ className, height = 32, gap = 1, color, ...props }: BarcodeBadgeBarsProps) { const { palette, seed, barCount } = useBarcodeBadge("BarcodeBadgeBars"); const widths = useMemo( () => Array.from({ length: barCount }, (_, i) => widthForBar(seed, i)), [seed, barCount] ); return ( {widths.map((width, i) => ( ))} ); } export interface BarcodeBadgeLabelProps extends React.ComponentPropsWithoutRef { className?: string; color?: string; children?: React.ReactNode; } export function BarcodeBadgeLabel({ className, color, children, style, ...props }: BarcodeBadgeLabelProps) { const { palette, seed } = useBarcodeBadge("BarcodeBadgeLabel"); return ( {children ?? seed} ); } ``` ## BookPage - key: `book-page` - import: `import { BookPage } from "@/components/ui/book-page"` - description: Book cover with spine gradient, page-edge texture, and an openAngle-driven hinge - tier: 1 - deps: react-native-svg, clsx, tailwind-merge ```tsx // components/ui/book-page.tsx import React, { createContext, useContext, useId, useMemo } from "react"; import { View, Text, Image, Platform } from "react-native"; import type { ImageSourcePropType, StyleProp, ViewStyle } from "react-native"; import Svg, { Defs, Pattern, Rect } from "react-native-svg"; import { cn } from "@/lib/utils"; // Layout constants (mirrors a real hardcover: a narrow spine, inset pages, a // tighter radius on the spine-side corners than the outer corners). const BOOK_PAGE_WIDTH = 240; const BOOK_PAGE_ASPECT_RATIO = 3 / 4; const BOOK_PAGE_PERSPECTIVE = 1000; const PAGE_BLEED = 6; const PAGE_INSET = 4; const PAGE_SPINE_INSET = 12; const PAGE_LINE = 3; const PAGE_GAP = 1; const COVER_SPINE_WIDTH = 10; const COVER_RADIUS = 6; const COVER_SPINE_RADIUS = 2; const BOOK_PAGE_SERIF_FONT = Platform.select({ ios: "Georgia", android: "serif", default: "serif" }); const BOOK_PAGE_MONO_FONT = Platform.select({ ios: "Menlo", android: "monospace", default: "monospace" }); export type BookPagePalette = { cover: string; coverText: string; spine: string; page: string; pageEdge: string; rule: string; }; /** Dark cloth-bound cover — the default. */ export const BOOK_PAGE_DARK_PALETTE: BookPagePalette = { cover: "#18181B", coverText: "#FFFFFF", spine: "rgba(0,0,0,0.25)", page: "#FFFFFF", pageEdge: "#E4E4E7", rule: "rgba(255,255,255,0.2)", }; /** Cream paperback cover. */ export const BOOK_PAGE_PAPER_PALETTE: BookPagePalette = { cover: "#FFFBEB", coverText: "#18181B", spine: "rgba(0,0,0,0.12)", page: "#FFFFFF", pageEdge: "#E4E4E7", rule: "rgba(0,0,0,0.2)", }; interface BookPageContextValue { palette: BookPagePalette; width: number; openAngle: number; } const BookPageContext = createContext(null); function useBookPageContext(componentName: string): BookPageContextValue { const context = useContext(BookPageContext); if (!context) { throw new Error(`<${componentName} /> must be rendered inside a root.`); } return context; } export interface BookPageProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; /** Overrides for the default (dark) palette — merge in BOOK_PAGE_PAPER_PALETTE for a paperback look. */ palette?: Partial; width?: number; aspectRatio?: number; /** Degrees the cover has swung open around its spine hinge. 0 = closed (default). */ openAngle?: number; /** Depth of the 3D perspective applied while the cover is open. Ignored when openAngle is 0. */ perspective?: number; } export function BookPage({ className, children, palette, width = BOOK_PAGE_WIDTH, aspectRatio = BOOK_PAGE_ASPECT_RATIO, openAngle = 0, perspective = BOOK_PAGE_PERSPECTIVE, style, ...props }: BookPageProps) { const resolvedPalette = useMemo( () => ({ ...BOOK_PAGE_DARK_PALETTE, ...palette }), [palette] ); const contextValue = useMemo( () => ({ palette: resolvedPalette, width, openAngle }), [resolvedPalette, width, openAngle] ); return ( {children} ); } export interface BookPagePagesProps extends Omit, "children"> { className?: string; /** How far the page stack peeks out past the cover's right edge. */ bleed?: number; /** Vertical inset from the top/bottom of the cover. */ inset?: number; /** How far the page stack is tucked in from the spine, so it's revealed as the cover opens. */ spineInset?: number; } /** * The page-edge texture that sits behind the cover. A tiled two-tone * horizontal-line pattern reads as a stack of paper edges once the cover * rotates open. Purely decorative — hidden from screen readers. */ export function BookPagePages({ className, style, bleed = PAGE_BLEED, inset = PAGE_INSET, spineInset = PAGE_SPINE_INSET, ...props }: BookPagePagesProps) { const { palette } = useBookPageContext("BookPagePages"); const rawPatternId = useId(); const patternId = `book-page-pages-${rawPatternId.replace(/[^a-zA-Z0-9]/g, "")}`; const tileHeight = PAGE_LINE + PAGE_GAP; return ( ]} accessibilityElementsHidden importantForAccessibility="no-hide-descendants" {...props} > ); } export interface BookPageCoverProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; source?: ImageSourcePropType; alt?: string; /** Darkening wash over the cover image so text stays legible. Approximated with layered translucent Views (no gradient dependency). Default true. */ scrim?: boolean; spineWidth?: number; /** Corner radius for the outer (non-spine) edge of the cover. */ radius?: number; } /** * The cover: an image (optional) + scrim + spine shadow + slotted text, * hinged around its left (spine) edge so `openAngle` reads as a book cover * swinging open rather than a card spinning in place. */ export function BookPageCover({ className, children, source, alt, scrim = true, spineWidth = COVER_SPINE_WIDTH, radius = COVER_RADIUS, style, ...props }: BookPageCoverProps) { const { palette, width, openAngle } = useBookPageContext("BookPageCover"); // Rotating a View rotates around its own center by default. Translating by // half the width before and after the rotation shifts the pivot to the // left edge — the spine — instead. const hinge = openAngle === 0 ? null : { transform: [{ translateX: -width / 2 }, { rotateY: `${-openAngle}deg` }, { translateX: width / 2 }] }; return ( , ]} {...props} > {source ? ( ) : null} {scrim ? ( <> {/* A top-to-bottom gradient scrim (transparent -> 10% -> 70% black) would keep cover text legible over any image, but that needs expo-linear-gradient for a single consumer, so this is approximated with two flat translucent layers instead of a true fade. */} ) : null} {/* Spine shadow: a single flat translucent strip along the spine edge, kept flat rather than gradient-faded for the same reason as above. */} {children} ); } export interface BookPageAuthorProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } /** Small-caps-style byline, rendered at the top of the cover. */ export function BookPageAuthor({ className, style, ...props }: BookPageAuthorProps) { const { palette } = useBookPageContext("BookPageAuthor"); return ( ); } export interface BookPageTitleProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; numberOfLines?: number; } /** Large serif title, the cover's focal text. */ export function BookPageTitle({ className, style, ...props }: BookPageTitleProps) { const { palette } = useBookPageContext("BookPageTitle"); return ( ); } export interface BookPageNoteProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } /** Small printed-edition/ISBN-style note, ruled off from the title above it. */ export function BookPageNote({ className, style, ...props }: BookPageNoteProps) { const { palette } = useBookPageContext("BookPageNote"); return ( ); } export interface BookPageFooterProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } /** Stacks Title/Note (or any children) at the bottom of the cover — Cover is justify-between, so Footer settles below Author. */ export function BookPageFooter({ className, ...props }: BookPageFooterProps) { return ; } ``` ## BottomSheet - key: `bottom-sheet` - import: `import { BottomSheet } from "@/components/ui/bottom-sheet"` - description: Bottom sheet overlay - tier: 3 - deps: @gorhom/bottom-sheet, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: theme-provider, fold ```tsx // components/ui/bottom-sheet.tsx import React, { forwardRef, useCallback } from "react"; import { View } from "react-native"; import { BottomSheetModal, BottomSheetBackdrop, BottomSheetView, } from "@gorhom/bottom-sheet"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { useFoldFeatures } from "@/components/ui/fold"; export interface BottomSheetProps { className?: string; children: React.ReactNode; snapPoints?: (string | number)[]; /** * On an unfolded iPhone Duo / foldable, clamp the sheet to one pane instead * of spanning the full screen width. Defaults to "left" (the OS treats the * left pane as primary). Set to "full" to opt out and keep the pre-fold * screen-wide behavior. Ignored on non-fold devices. */ foldPane?: "left" | "right" | "full"; } export const BottomSheet = forwardRef( ({ className, children, snapPoints = ["25%", "50%"], foldPane = "left", ...props }, ref) => { const colors = useThemeColors(); const fold = useFoldFeatures(); const renderBackdrop = useCallback( (backdropProps: React.ComponentProps) => ( ), [] ); // Fold-aware width clamp: on an unfolded Duo, inherit one pane's width // (foldX, which is window.width / 2). Pre-fold / non-Duo renders behave // identically to today because fold.foldX is null. const foldClamp = fold.foldX && foldPane !== "full" ? { width: fold.foldX, left: foldPane === "right" ? fold.foldX : 0 } : undefined; return ( {children} ); } ); BottomSheet.displayName = "BottomSheet"; ``` ## Breadcrumb - key: `breadcrumb` - import: `import { Breadcrumb } from "@/components/ui/breadcrumb"` - description: Navigation trail: Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/breadcrumb.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { ChevronRight } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface BreadcrumbProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function Breadcrumb({ className, ...props }: BreadcrumbProps) { return ( ); } export interface BreadcrumbItemProps extends React.ComponentPropsWithoutRef { className?: string; } export function BreadcrumbItem({ className, ...props }: BreadcrumbItemProps) { return ; } export interface BreadcrumbLinkProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function BreadcrumbLink({ className, children, ...props }: BreadcrumbLinkProps) { return ( {children} ); } export interface BreadcrumbPageProps extends React.ComponentPropsWithoutRef { className?: string; } export function BreadcrumbPage({ className, ...props }: BreadcrumbPageProps) { return ( ); } export interface BreadcrumbSeparatorProps extends React.ComponentPropsWithoutRef { className?: string; } export function BreadcrumbSeparator({ className, children, ...props }: BreadcrumbSeparatorProps) { const colors = useThemeColors(); if (children == null) return ; return ( {children} ); } ``` ## Button - key: `button` - import: `import { Button } from "@/components/ui/button"` - description: A pressable button with variants - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/button.tsx import React from "react"; import { Pressable, Text, ActivityIndicator } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const buttonVariants = cva( "flex-row items-center justify-center rounded-md min-h-12 min-w-12", { variants: { variant: { default: "bg-primary", secondary: "bg-secondary", outline: "border border-input bg-transparent", ghost: "bg-transparent", destructive: "bg-destructive", link: "bg-transparent", }, size: { sm: "px-3 py-1.5 gap-1.5", md: "px-4 py-2.5 gap-2", lg: "px-6 py-3.5 gap-2.5", icon: "h-10 w-10 p-0", }, }, defaultVariants: { variant: "default", size: "md" }, } ); const buttonTextVariants = cva("text-center font-medium", { variants: { variant: { default: "text-primary-foreground", secondary: "text-secondary-foreground", outline: "text-foreground", ghost: "text-foreground", destructive: "text-destructive-foreground", link: "text-primary underline", }, size: { sm: "text-sm", md: "text-base", lg: "text-lg", icon: "text-sm" }, }, defaultVariants: { variant: "default", size: "md" }, }); export interface ButtonProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; textClassName?: string; children?: string; icon?: React.ReactNode; iconAfter?: React.ReactNode; loading?: boolean; } export function Button({ variant, size, className, textClassName, children, icon, iconAfter, loading, disabled, ...props }: ButtonProps) { const isDisabled = disabled || loading; const colors = useThemeColors(); const onFilledBg = variant === "default" || variant === "destructive"; const spinnerColor = onFilledBg ? colors.primaryForeground : colors.foreground; return ( {loading ? ( ) : icon ?? null} {children ? ( {children} ) : null} {!loading && iconAfter ? iconAfter : null} ); } ``` ## Calendar - key: `calendar` - import: `import { Calendar } from "@/components/ui/calendar"` - description: Month calendar with single and range selection - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/calendar.tsx import React, { useState } from "react"; import { View, Text, Pressable } from "react-native"; import { ChevronLeft, ChevronRight } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface CalendarProps { className?: string; selected?: Date; onSelect?: (date: Date) => void; rangeStart?: Date; rangeEnd?: Date; onRangeChange?: (start: Date, end: Date | undefined) => void; min?: Date; max?: Date; } const DAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const same = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); type Mode = "days" | "months" | "years"; export function Calendar({ className, selected, onSelect, rangeStart, rangeEnd, onRangeChange, min, max }: CalendarProps) { const [viewing, setViewing] = useState(() => selected ?? rangeStart ?? new Date()); const [mode, setMode] = useState("days"); const year = viewing.getFullYear(), month = viewing.getMonth(); const colors = useThemeColors(); const handlePress = (day: number) => { const date = new Date(year, month, day); if ((min && date < min) || (max && date > max)) return; if (onRangeChange) { if (!rangeStart || rangeEnd || date < rangeStart) onRangeChange(date, undefined); else onRangeChange(rangeStart, date); return; } onSelect?.(date); }; const handleHeaderPress = () => setMode(mode === "days" ? "years" : "days"); const pickYear = (y: number) => { setViewing(new Date(y, month, 1)); setMode("months"); }; const pickMonth = (m: number) => { setViewing(new Date(year, m, 1)); setMode("days"); }; const decadeStart = Math.floor(year / 12) * 12; const label = new Date(year, month).toLocaleString("default", { month: "long", year: "numeric" }); return ( mode === "days" ? setViewing(new Date(year, month - 1, 1)) : mode === "months" ? setViewing(new Date(year - 1, month, 1)) : setViewing(new Date(decadeStart - 12, month, 1))} className="h-12 w-12 items-center justify-center rounded-md" accessibilityRole="button" accessibilityLabel="Previous"> {mode === "days" ? label : mode === "months" ? `${year}` : `${decadeStart} – ${decadeStart + 11}`} mode === "days" ? setViewing(new Date(year, month + 1, 1)) : mode === "months" ? setViewing(new Date(year + 1, month, 1)) : setViewing(new Date(decadeStart + 12, month, 1))} className="h-12 w-12 items-center justify-center rounded-md" accessibilityRole="button" accessibilityLabel="Next"> {mode === "years" && ( {Array.from({ length: 12 }, (_, i) => decadeStart + i).map((y) => ( pickYear(y)} className={cn("h-12 w-full items-center justify-center rounded-md", y === year && "bg-primary")} accessibilityRole="button"> {y} ))} )} {/* Month grid */} {mode === "months" && ( {MONTHS.map((m, i) => ( pickMonth(i)} className={cn("h-12 w-full items-center justify-center rounded-md", i === month && year === viewing.getFullYear() && "bg-primary")} accessibilityRole="button"> {m} ))} )} {/* Days grid */} {mode === "days" && ( <> {DAYS.map((d) => {d})} {(() => { const firstDay = new Date(year, month, 1).getDay(); const daysInMonth = new Date(year, month + 1, 0).getDate(); const cells: (number | null)[] = [...Array(firstDay).fill(null), ...Array.from({ length: daysInMonth }, (_, i) => i + 1)]; return cells.map((day, i) => { if (day === null) return ; const date = new Date(year, month, day); const sel = selected && same(date, selected); const rs = rangeStart && same(date, rangeStart); const re = rangeEnd && same(date, rangeEnd); const inR = rangeStart && rangeEnd && date.getTime() >= rangeStart.getTime() && date.getTime() <= rangeEnd.getTime(); const today = same(date, new Date()); const off = (min && date < min) || (max && date > max); return ( handlePress(day)} disabled={!!off} className={cn("h-12 w-12 items-center justify-center rounded-full", sel || rs || re ? "bg-primary" : inR ? "bg-accent" : "", today && !sel && "border border-primary", off && "opacity-30")} accessibilityRole="button" accessibilityLabel={`${label} ${day}`}> {day} ); }); })()} )} ); } ``` ## Card - key: `card` - import: `import { Card } from "@/components/ui/card"` - description: Card container with header, content, footer - tier: 1 - deps: clsx, tailwind-merge - aniui deps: text ```tsx // components/ui/card.tsx import React from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; export interface CardProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function Card({ className, ...props }: CardProps) { return ( ); } export interface CardHeaderProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function CardHeader({ className, ...props }: CardHeaderProps) { return ; } export interface CardTitleProps extends React.ComponentPropsWithoutRef { className?: string; } export function CardTitle({ className, ...props }: CardTitleProps) { return ( ); } export interface CardDescriptionProps extends React.ComponentPropsWithoutRef { className?: string; } export function CardDescription({ className, ...props }: CardDescriptionProps) { return ; } export interface CardContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function CardContent({ className, ...props }: CardContentProps) { return ; } export interface CardFooterProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function CardFooter({ className, ...props }: CardFooterProps) { return ; } ``` ## Carousel - key: `carousel` - import: `import { Carousel } from "@/components/ui/carousel"` - description: Horizontal scrollable carousel with pagination dots - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/carousel.tsx import React, { useRef, useState } from "react"; import { View, FlatList } from "react-native"; import { cn } from "@/lib/utils"; export interface CarouselProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; showDots?: boolean; autoPlay?: boolean; interval?: number; } export function Carousel({ className, data, itemWidth, showDots = true, autoPlay, interval = 3000, onLayout, ...props }: CarouselProps) { const [active, setActive] = useState(0); const [measured, setMeasured] = useState(0); // Size each slide to the carousel's OWN width (measured), not the window — // otherwise slides overflow when the carousel sits inside padding. const width = itemWidth ?? measured; const ref = useRef(null); React.useEffect(() => { if (!autoPlay || data.length <= 1 || !width) return; const timer = setInterval(() => { const next = (active + 1) % data.length; ref.current?.scrollToOffset({ offset: next * width, animated: true }); }, interval); return () => clearInterval(timer); }, [autoPlay, active, data.length, interval, width]); return ( { setMeasured(e.nativeEvent.layout.width); onLayout?.(e); }} accessibilityRole="adjustable" accessibilityLabel={`Carousel, item ${active + 1} of ${data.length}`} {...props} > {width > 0 ? ( setActive(Math.round(e.nativeEvent.contentOffset.x / width))} renderItem={({ item }) => {item}} keyExtractor={(_, i) => String(i)} /> ) : null} {showDots && data.length > 1 && ( {data.map((_, i) => ( ))} )} ); } ``` ## Carousel3D - key: `carousel-3d` - import: `import { Carousel3D } from "@/components/ui/carousel-3d"` - description: 3D cylindrical carousel with real perspective-projected faces, pan gestures, and snap physics - tier: 3 - deps: react-native-gesture-handler, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/carousel-3d.tsx import React, { useCallback, useMemo } from "react"; import { Pressable, View, useWindowDimensions } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { Extrapolation, cancelAnimation, interpolate, runOnJS, useAnimatedReaction, useAnimatedStyle, useSharedValue, withSpring, type SharedValue, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; export interface Carousel3DProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; gap?: number; perspectiveFactor?: number; backOpacity?: number; onIndexChange?: (index: number) => void; onPressItem?: (index: number) => void; } const MIN_PROJECTION_DENOMINATOR = 1; function stepOf(count: number) { "worklet"; return 360 / Math.max(count, 1); } function frontIndex(rotation: number, step: number, count: number) { "worklet"; if (count <= 0) return 0; const index = Math.round(-rotation / step) % count; return index < 0 ? index + count : index; } function projectFace(angle: number, radius: number, perspective: number) { "worklet"; const radians = (angle * Math.PI) / 180; const cos = Math.cos(radians); const sin = Math.sin(radians); const distance = Math.max(perspective, MIN_PROJECTION_DENOMINATOR); const depth = radius * cos; return { matrix: [cos, 0, -sin, sin / distance, 0, 1, 0, 0, sin, 0, cos, -cos / distance, sin * radius, 0, depth, 1 - depth / distance], depth, facing: depth - (radius * radius) / distance, }; } export function Carousel3D({ className, data, itemWidth: itemWidthProp, gap = 8, perspectiveFactor = 3.5, backOpacity = 0.4, onIndexChange, onPressItem, ...props }: Carousel3DProps) { const { width: windowWidth } = useWindowDimensions(); const count = data.length; const step = stepOf(count); const itemWidth = itemWidthProp ?? Math.min(windowWidth * 0.55, 220); const itemHeight = itemWidth * 1.25; const radius = Math.max((count * (itemWidth + gap)) / (2 * Math.PI), itemWidth); const perspective = radius * perspectiveFactor; const rotation = useSharedValue(0); const dragOrigin = useSharedValue(0); const handleIndex = useCallback((index: number) => onIndexChange?.(index), [onIndexChange]); useAnimatedReaction( () => frontIndex(rotation.value, step, count), (current, prev) => { if (prev !== null && current !== prev) runOnJS(handleIndex)(current); }, [step, count, handleIndex] ); const pan = useMemo( () => Gesture.Pan() .activeOffsetX([-8, 8]) .onBegin(() => { cancelAnimation(rotation); dragOrigin.value = rotation.value; }) .onUpdate((e) => { const degreesPerPixel = 180 / (Math.PI * Math.max(radius, 1)); rotation.value = dragOrigin.value + e.translationX * degreesPerPixel; }) .onEnd((e) => { const degreesPerPixel = 180 / (Math.PI * Math.max(radius, 1)); const velocity = e.velocityX * degreesPerPixel; const projected = rotation.value + velocity * 0.28; rotation.value = withSpring(Math.round(projected / step) * step, { damping: 26, stiffness: 110, mass: 0.6, velocity, }); }), [rotation, dragOrigin, step, radius] ); const frontScale = perspectiveFactor / Math.max(perspectiveFactor - 1, 0.1); return ( {data.map((item, index) => ( onPressItem(index) : undefined} > {item} ))} ); } function Carousel3DFace({ index, rotation, step, radius, perspective, backOpacity, itemWidth, itemHeight, onPress, children, }: { index: number; rotation: SharedValue; step: number; radius: number; perspective: number; backOpacity: number; itemWidth: number; itemHeight: number; onPress?: () => void; children: React.ReactNode; }) { const facing = useSharedValue(1); const style = useAnimatedStyle(() => { const angle = rotation.value + index * step; const projected = projectFace(angle, radius, perspective); facing.value = projected.facing; return { opacity: interpolate(projected.depth, [-radius, radius], [backOpacity, 1], Extrapolation.CLAMP), zIndex: Math.round(projected.depth) + 1000, transform: [{ matrix: projected.matrix }], }; }, [index, step, radius, perspective, backOpacity]); const handlePress = useCallback(() => { if (facing.value <= 0) return; onPress?.(); }, [onPress, facing]); const body = ( {children} ); if (!onPress) return body; return ( {body} ); } ``` ## CarouselCircular - key: `carousel-circular` - import: `import { CarouselCircular } from "@/components/ui/carousel-circular"` - description: Scroll-driven coverflow carousel with per-item lift, tilt, and a blur fade on non-centered items - tier: 3 - deps: react-native-reanimated, expo-blur, clsx, tailwind-merge ```tsx // components/ui/carousel-circular.tsx import React, { useState } from "react"; import { FlatList, Platform, View, useWindowDimensions } from "react-native"; import { BlurView } from "expo-blur"; import Animated, { Extrapolation, interpolate, useAnimatedProps, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; const AnimatedFlatList = Animated.createAnimatedComponent(FlatList); const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); export interface CarouselCircularProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; spacing?: number; onIndexChange?: (index: number) => void; } export function CarouselCircular({ className, data, itemWidth: itemWidthProp, spacing = 20, onIndexChange, ...props }: CarouselCircularProps) { const { width } = useWindowDimensions(); const itemWidth = itemWidthProp ?? width * 0.75; const sideSpacing = (width - itemWidth) / 2; const snap = itemWidth + spacing; const scrollX = useSharedValue(0); const [active, setActive] = useState(0); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollX.value = e.contentOffset.x; }, }); return ( { const idx = Math.round(e.nativeEvent.contentOffset.x / snap); setActive(idx); onIndexChange?.(idx); }} style={{ flexGrow: 0 }} contentContainerStyle={{ paddingHorizontal: sideSpacing - spacing / 2, marginTop: 40, marginBottom: 20 }} renderItem={({ item, index }) => ( {item} )} keyExtractor={(_, i) => String(i)} /> ); } function CircularItem({ index, count, scrollX, itemWidth, spacing, sideSpacing, children, }: { index: number; count: number; scrollX: SharedValue; itemWidth: number; spacing: number; sideSpacing: number; children: React.ReactNode; }) { const snap = itemWidth + spacing; const inputRange = [(index - 2) * snap, (index - 1) * snap, index * snap, (index + 1) * snap, (index + 2) * snap]; const style = useAnimatedStyle(() => { const translateY = interpolate(scrollX.value, inputRange, [itemWidth / 4, itemWidth / 8, 0, itemWidth / 8, itemWidth / 4], Extrapolation.CLAMP); const opacity = interpolate(scrollX.value, inputRange, [0.5, 0.8, 1, 0.8, 0.5], Extrapolation.CLAMP); const scale = interpolate(scrollX.value, inputRange, [0.75, 0.85, 1, 0.85, 0.75], Extrapolation.CLAMP); const rotateZ = interpolate(scrollX.value, inputRange, [40, 20, 0, -20, -40], Extrapolation.CLAMP); return { opacity, transform: [{ translateY }, { scale }, { rotateZ: `${rotateZ}deg` }] }; }); // Android has no BlurView-behind-content pass, so it gets its own depth cue: // a CSS-filter blur on the whole item, same falloff curve as the iOS // BlurView overlay below. const androidBlurStyle = useAnimatedStyle(() => { const blur = interpolate(scrollX.value, inputRange, [4, 8, 0, 8, 4], Extrapolation.CLAMP); return { filter: [{ blur }] } as Record; }); const blurProps = useAnimatedProps(() => ({ intensity: interpolate(scrollX.value, inputRange, [80, 40, 0, 40, 80], Extrapolation.CLAMP), })); return ( {/* Shadow lives on the same opaque, rounded, clipped view as the content — casting it from a separate transparent parent made iOS fall back to a plain rectangular shadow silhouette instead of a rounded one. */} {children} {Platform.OS === "ios" && ( )} ); } ``` ## CarouselParallax - key: `carousel-parallax` - import: `import { CarouselParallax } from "@/components/ui/carousel-parallax"` - description: Horizontal carousel with real inner-layer parallax translation and a haptic tick on release - tier: 2 - deps: react-native-reanimated, expo-haptics, clsx, tailwind-merge ```tsx // components/ui/carousel-parallax.tsx import React, { useState } from "react"; import { View, FlatList, useWindowDimensions } from "react-native"; import Animated, { Extrapolation, interpolate, runOnJS, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import * as Haptics from "expo-haptics"; import { cn } from "@/lib/utils"; const AnimatedFlatList = Animated.createAnimatedComponent(FlatList); export interface CarouselParallaxProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; spacing?: number; parallaxIntensity?: number; showDots?: boolean; } export function CarouselParallax({ className, data, itemWidth: itemWidthProp, spacing = 16, parallaxIntensity = 0.7, showDots = true, ...props }: CarouselParallaxProps) { const { width } = useWindowDimensions(); const itemWidth = itemWidthProp ?? width * 0.78; const snap = itemWidth + spacing; const scrollX = useSharedValue(0); const [active, setActive] = useState(0); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollX.value = e.contentOffset.x; }, onEndDrag: () => { runOnJS(Haptics.impactAsync)(Haptics.ImpactFeedbackStyle.Rigid); }, }); return ( setActive(Math.round(e.nativeEvent.contentOffset.x / snap))} renderItem={({ item, index }) => ( {item} )} keyExtractor={(_, i) => String(i)} /> {showDots && data.length > 1 && ( {data.map((_, i) => ( ))} )} ); } function ParallaxSlide({ index, scrollX, width, intensity, children, }: { index: number; scrollX: SharedValue; width: number; intensity: number; children: React.ReactNode; }) { const offset = index * width; const style = useAnimatedStyle(() => { const translateX = interpolate( scrollX.value, [offset - width, offset, offset + width], [-width * intensity, 0, width * intensity], Extrapolation.CLAMP ); return { transform: [{ translateX }] }; }); return ( {children} ); } ``` ## CarouselScale - key: `carousel-scale` - import: `import { CarouselScale } from "@/components/ui/carousel-scale"` - description: Center-focused carousel where neighbors zoom up and rotate out, with a haptic tick on release - tier: 2 - deps: react-native-reanimated, expo-haptics, clsx, tailwind-merge ```tsx // components/ui/carousel-scale.tsx import React, { useState } from "react"; import { View, useWindowDimensions } from "react-native"; import Animated, { Extrapolation, interpolate, runOnJS, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import * as Haptics from "expo-haptics"; import { cn } from "@/lib/utils"; export interface CarouselScaleProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; spacing?: number; scaleRange?: [number, number, number]; rotationRange?: [number, number, number]; showDots?: boolean; } export function CarouselScale({ className, data, itemWidth: itemWidthProp, spacing = 12, scaleRange = [1.6, 1, 1.6], rotationRange = [15, 0, -10], showDots = true, ...props }: CarouselScaleProps) { const { width } = useWindowDimensions(); const itemWidth = itemWidthProp ?? width * 0.62; const snap = itemWidth + spacing; const scrollX = useSharedValue(0); const [active, setActive] = useState(0); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollX.value = e.contentOffset.x; }, onEndDrag: () => { runOnJS(Haptics.impactAsync)(Haptics.ImpactFeedbackStyle.Rigid); }, }); return ( setActive(Math.round(e.nativeEvent.contentOffset.x / snap))} > {data.map((item, index) => ( {item} ))} {showDots && data.length > 1 && ( {data.map((_, i) => ( ))} )} ); } function ScaleSlide({ index, scrollX, snap, width, scaleRange, rotationRange, children, }: { index: number; scrollX: SharedValue; snap: number; width: number; scaleRange: [number, number, number]; rotationRange: [number, number, number]; children: React.ReactNode; }) { const style = useAnimatedStyle(() => { const input = [(index - 1) * snap, index * snap, (index + 1) * snap]; const scale = interpolate(scrollX.value, input, scaleRange, Extrapolation.CLAMP); const rotate = interpolate(scrollX.value, input, rotationRange, Extrapolation.CLAMP); return { transform: [{ scale }, { rotate: `${rotate}deg` }] }; }); return ( {children} ); } ``` ## CarouselTilt - key: `carousel-tilt` - import: `import { CarouselTilt } from "@/components/ui/carousel-tilt"` - description: Z-axis fan carousel — slides rotate and lift from a bottom pivot, with an optional blur overlay - tier: 2 - deps: react-native-reanimated, expo-blur, clsx, tailwind-merge ```tsx // components/ui/carousel-tilt.tsx import React, { useState } from "react"; import { Platform, View, useWindowDimensions } from "react-native"; import { BlurView } from "expo-blur"; import Animated, { Extrapolation, interpolate, useAnimatedProps, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); export interface CarouselTiltProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemWidth?: number; itemHeight?: number; spacing?: number; rotationAngle?: number; translateYValue?: number; useBlur?: boolean; showDots?: boolean; } export function CarouselTilt({ className, data, itemWidth: itemWidthProp, itemHeight = 320, spacing = 14, rotationAngle = 20, translateYValue = 60, useBlur = false, showDots = true, ...props }: CarouselTiltProps) { const { width } = useWindowDimensions(); const itemWidth = itemWidthProp ?? width * 0.65; const fullWidth = itemWidth + spacing * 2; const scrollX = useSharedValue(0); const [active, setActive] = useState(0); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollX.value = e.contentOffset.x; }, }); return ( setActive(Math.round(e.nativeEvent.contentOffset.x / fullWidth))} > {data.map((item, index) => ( {item} ))} {showDots && data.length > 1 && ( {data.map((_, i) => ( ))} )} ); } function TiltSlide({ index, scrollX, fullWidth, itemWidth, itemHeight, spacing, rotationAngle, translateYValue, useBlur, children, }: { index: number; scrollX: SharedValue; fullWidth: number; itemWidth: number; itemHeight: number; spacing: number; rotationAngle: number; translateYValue: number; useBlur: boolean; children: React.ReactNode; }) { const inputRange = [(index - 1) * fullWidth, index * fullWidth, (index + 1) * fullWidth]; const style = useAnimatedStyle(() => { const rotateZ = interpolate(scrollX.value, inputRange, [rotationAngle, 0, -rotationAngle], Extrapolation.CLAMP); const translateY = interpolate(scrollX.value, inputRange, [translateYValue, 0, translateYValue], Extrapolation.CLAMP); return { transformOrigin: Platform.OS === "android" ? (`${itemWidth / 2}px ${itemHeight}px` as unknown as string) : "bottom", transform: [{ rotateZ: `${rotateZ}deg` }, { translateY }], }; }); const blurStyle = useAnimatedStyle(() => { const opacity = interpolate( scrollX.value, [(index - 0.35) * fullWidth, index * fullWidth, (index + 0.35) * fullWidth], [1, 0, 1], Extrapolation.CLAMP ); return { opacity }; }); const blurProps = useAnimatedProps(() => ({ intensity: interpolate(scrollX.value, inputRange, [25, 0, 25], Extrapolation.CLAMP), })); return ( {children} {useBlur && ( )} ); } ``` ## ChartTooltip - key: `chart-tooltip` - import: `import { ChartTooltip } from "@/components/ui/chart-tooltip"` - description: Tooltip overlay for chart data points - tier: 1 - deps: clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/chart-tooltip.tsx import React from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface ChartTooltipProps extends React.ComponentPropsWithoutRef { className?: string; label?: string; value?: string | number; indicator?: "line" | "dot" | "dashed"; color?: string; items?: { label: string; value: string | number; color: string }[]; } export function ChartTooltip({ className, label, value, indicator = "dot", color, items, ...props }: ChartTooltipProps) { const colors = useThemeColors(); const resolvedColor = color ?? colors.foreground; const indicatorEl = (c: string) => indicator === "line" ? ( ) : indicator === "dashed" ? ( ) : ( ); return ( {label && ( {label} )} {items ? ( items.map((item, i) => ( {indicatorEl(item.color)} {item.label} {item.value} )) ) : ( {indicatorEl(resolvedColor)} {value} )} ); } ``` ## ChatBubble - key: `chat-bubble` - import: `import { ChatBubble } from "@/components/ui/chat-bubble"` - description: Message bubble for chat with sent/received variants and status - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/chat-bubble.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { Check, CheckCheck } from "lucide-react-native"; import { useThemeColors } from "@/components/ui/theme-provider"; import { cn } from "@/lib/utils"; const bubbleVariants = cva("max-w-[80%] rounded-2xl px-4 py-2.5", { variants: { variant: { sent: "bg-primary self-end rounded-br-sm", received: "bg-secondary self-start rounded-bl-sm", }, }, defaultVariants: { variant: "received" }, }); const textVariants = cva("text-base", { variants: { variant: { sent: "text-primary-foreground", received: "text-secondary-foreground", }, }, defaultVariants: { variant: "received" }, }); export interface ChatBubbleProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; children: React.ReactNode; timestamp?: string; status?: "sent" | "delivered" | "read"; } export function ChatBubble({ variant, className, children, timestamp, status, ...props }: ChatBubbleProps) { const isSent = variant === "sent"; const colors = useThemeColors(); const tick = `${colors.primaryForeground}99`; return ( {children} {(timestamp || status) && ( {timestamp && ( {timestamp} )} {status && isSent && (status === "sent" ? ( ) : ( ))} )} ); } ``` ## Checkbox - key: `checkbox` - import: `import { Checkbox } from "@/components/ui/checkbox"` - description: Checkbox with checked state - tier: 3 - deps: lucide-react-native, react-native-svg, @rn-primitives/checkbox, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/checkbox.tsx import React from "react"; import { Pressable, View } from "react-native"; import * as CheckboxPrimitive from "@rn-primitives/checkbox"; import { Check } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface CheckboxProps extends React.ComponentPropsWithoutRef { className?: string; checked?: boolean; onCheckedChange?: (checked: boolean) => void; } export function Checkbox({ checked = false, onCheckedChange, className, disabled, ...props }: CheckboxProps) { const colors = useThemeColors(); // Primitive's Root requires a non-nullish onCheckedChange and a plain // boolean checked (no boolean | "indeterminate"-style widening). Fall back // to a no-op callback for the uncontrolled case so the Pressable below // still drives the visual state via its own onPress. return ( {})} // Pressable's `disabled` is `boolean | null | undefined`; primitive // only accepts `boolean | undefined`. Normalize null → false. disabled={disabled ?? false} asChild > !disabled && onCheckedChange?.(!checked)} {...props} > ); } ``` ## Chip - key: `chip` - import: `import { Chip } from "@/components/ui/chip"` - description: Interactive tag for filters and multi-select - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/chip.tsx import React from "react"; import { Text, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { X } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const chipVariants = cva( "flex-row items-center rounded-full min-h-8", { variants: { variant: { default: "bg-primary", secondary: "bg-secondary", outline: "border border-input bg-transparent", destructive: "bg-destructive", }, size: { sm: "px-2.5 py-1 gap-1", md: "px-3 py-1.5 gap-1.5", lg: "px-4 py-2 gap-2", }, }, defaultVariants: { variant: "default", size: "md" }, } ); const chipTextVariants = cva("font-medium", { variants: { variant: { default: "text-primary-foreground", secondary: "text-secondary-foreground", outline: "text-foreground", destructive: "text-destructive-foreground", }, size: { sm: "text-xs", md: "text-sm", lg: "text-base" }, }, defaultVariants: { variant: "default", size: "md" }, }); export interface ChipProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; textClassName?: string; children: string; selected?: boolean; onClose?: () => void; } export function Chip({ variant, size, className, textClassName, children, selected, onClose, ...props }: ChipProps) { const v = selected ? "default" : (variant ?? "outline"); const colors = useThemeColors(); const closeColor = v === "outline" ? colors.mutedForeground : v === "default" ? colors.primaryForeground : v === "secondary" ? colors.foreground : colors.destructiveForeground; return ( {children} {onClose && ( )} ); } ``` ## Collapsible - key: `collapsible` - import: `import { Collapsible } from "@/components/ui/collapsible"` - description: Animated show/hide content - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/collapsible.tsx import React, { createContext, useContext, useState } from "react"; import { View, Pressable } from "react-native"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; const CollapsibleCtx = createContext<{ isOpen: boolean; toggle: () => void }>({ isOpen: false, toggle: () => {} }); export interface CollapsibleProps extends React.ComponentPropsWithoutRef { className?: string; open?: boolean; onOpenChange?: (open: boolean) => void; children?: React.ReactNode; } export function Collapsible({ open: controlledOpen, onOpenChange, className, children, ...props }: CollapsibleProps) { const [uncontrolled, setUncontrolled] = useState(false); const isOpen = controlledOpen ?? uncontrolled; const toggle = () => { const next = !isOpen; setUncontrolled(next); onOpenChange?.(next); }; return ( {children} ); } export interface CollapsibleTriggerProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function CollapsibleTrigger({ className, children, ...props }: CollapsibleTriggerProps) { const { toggle } = useContext(CollapsibleCtx); return ( {children} ); } export interface CollapsibleContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function CollapsibleContent({ className, children, ...props }: CollapsibleContentProps) { const { isOpen } = useContext(CollapsibleCtx); if (!isOpen) return null; return ( {children} ); } ``` ## Combobox - key: `combobox` - import: `import { Combobox } from "@/components/ui/combobox"` - description: Searchable select with multi-select, groups, clear, and custom rendering - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/combobox.tsx import React, { useState, useMemo, useCallback, useEffect } from "react"; import { View, TextInput, Pressable, Text, FlatList, SectionList, Modal, ScrollView, useColorScheme, Keyboard, Platform, } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { X, ChevronDown } from "lucide-react-native"; export interface ComboboxOption { label: string; value: string; disabled?: boolean; } export interface ComboboxGroup { label: string; options: ComboboxOption[]; } export interface ComboboxProps extends React.ComponentPropsWithoutRef { className?: string; options: ComboboxOption[]; value?: string; onValueChange?: (value: string) => void; placeholder?: string; searchPlaceholder?: string; emptyText?: string; multiple?: boolean; selectedValues?: string[]; onSelectedValuesChange?: (values: string[]) => void; groups?: ComboboxGroup[]; renderItem?: (option: ComboboxOption, selected: boolean) => React.ReactNode; invalid?: boolean; disabled?: boolean; clearable?: boolean; autoHighlight?: boolean; mode?: "select" | "popup"; triggerClassName?: string; } // Inline chip for multi-select display function Chip({ label, onRemove }: { label: string; onRemove: () => void }) { const colors = useThemeColors(); return ( {label} ); } export function Combobox({ className, options, value, onValueChange, placeholder = "Select...", searchPlaceholder = "Search...", emptyText = "No results found", multiple = false, selectedValues = [], onSelectedValuesChange, groups, renderItem: renderItemProp, invalid = false, disabled = false, clearable = false, autoHighlight = false, mode = "select", triggerClassName, ...props }: ComboboxProps) { const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const [kbHeight, setKbHeight] = useState(0); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; // RN Modal doesn't resize for the keyboard on Android (and the sheet is // bottom-anchored), so track the keyboard height and pad the sheet up. useEffect(() => { const showEvt = Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow"; const hideEvt = Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide"; const show = Keyboard.addListener(showEvt, (e) => setKbHeight(e.endCoordinates.height)); const hide = Keyboard.addListener(hideEvt, () => setKbHeight(0)); return () => { show.remove(); hide.remove(); }; }, []); const allOptions = useMemo( () => (groups ? groups.flatMap((g) => g.options) : options), [groups, options] ); const selected = allOptions.find((o) => o.value === value); const isSelected = useCallback( (val: string) => (multiple ? selectedValues.includes(val) : val === value), [multiple, selectedValues, value] ); // Filter logic const filterFn = (opts: ComboboxOption[]) => opts.filter((o) => o.label.toLowerCase().includes(search.toLowerCase())); const filteredOptions = useMemo(() => filterFn(allOptions), [allOptions, search]); const filteredSections = useMemo(() => { if (!groups) return []; return groups .map((g) => ({ title: g.label, data: filterFn(g.options) })) .filter((s) => s.data.length > 0); }, [groups, search]); const handleSelect = (val: string) => { if (multiple) { const next = selectedValues.includes(val) ? selectedValues.filter((v) => v !== val) : [...selectedValues, val]; onSelectedValuesChange?.(next); } else { onValueChange?.(val); setOpen(false); } setSearch(""); }; const handleClear = () => { if (multiple) { onSelectedValuesChange?.([]); } else { onValueChange?.(""); } }; const hasValue = multiple ? selectedValues.length > 0 : !!value; // Trigger display const triggerLabel = multiple ? selectedValues.length > 0 ? `${selectedValues.length} selected` : placeholder : selected?.label ?? placeholder; const renderOption = (item: ComboboxOption) => { const sel = isSelected(item.value); if (renderItemProp) { return ( !item.disabled && handleSelect(item.value)} disabled={item.disabled} className={cn(item.disabled && "opacity-40")} > {renderItemProp(item, sel)} ); } return ( !item.disabled && handleSelect(item.value)} disabled={item.disabled} accessibilityRole="button" accessibilityState={{ selected: sel }} > {item.label} ); }; return ( {/* Trigger */} !disabled && setOpen(true)} disabled={disabled} accessible={true} accessibilityRole="button" accessibilityLabel={selected ? `Selected: ${selected.label}` : placeholder} accessibilityState={{ disabled }} > {triggerLabel} {clearable && hasValue && ( { e.stopPropagation(); handleClear(); }} className="p-1 me-1" accessible={true} accessibilityRole="button" accessibilityLabel="Clear selection" > )} {/* Multi-select chips */} {multiple && selectedValues.length > 0 && ( {selectedValues.map((val) => { const opt = allOptions.find((o) => o.value === val); return opt ? ( { onSelectedValuesChange?.(selectedValues.filter((v) => v !== val)); }} /> ) : null; })} )} {/* Modal */} setOpen(false)}> setOpen(false)} > {}}> {groups ? ( item.value} renderSectionHeader={({ section }) => ( {section.title} )} renderItem={({ item }) => renderOption(item)} ListEmptyComponent={ {emptyText} } /> ) : ( item.value} ListEmptyComponent={ {emptyText} } renderItem={({ item }) => renderOption(item)} /> )} ); } ``` ## CommandMenu - key: `command-menu` - import: `import { CommandMenu } from "@/components/ui/command-menu"` - description: Spotlight/kbar-style command palette — portal-based overlay with rigorous Android keyboard handling, groups, and shortcuts - tier: 3 - deps: lucide-react-native, react-native-svg, @rn-primitives/dialog, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, theme-provider, fold ```tsx // components/ui/command-menu.tsx import React, { useEffect, useMemo, useRef, useState } from "react"; import { View, Text, TextInput, Pressable, SectionList, useWindowDimensions, Keyboard, Platform } from "react-native"; import * as DialogPrimitive from "@rn-primitives/dialog"; import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { Search } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { useFoldFeatures } from "@/components/ui/fold"; export interface CommandItem { label: string; value: string; icon?: React.ReactNode; shortcut?: string; group?: string; disabled?: boolean; onSelect?: () => void; } export interface CommandMenuProps extends React.ComponentPropsWithoutRef { open: boolean; onOpenChange: (open: boolean) => void; items: CommandItem[]; placeholder?: string; emptyText?: string; onSelect?: (value: string) => void; className?: string; } // Anchored below the status bar; the palette grows down and the results list // scrolls within whatever space is left above the keyboard. const TOP_OFFSET = 96; export function CommandMenu({ open, onOpenChange, items, placeholder = "Type a command or search...", emptyText = "No results found.", onSelect, className, ...props }: CommandMenuProps) { const [search, setSearch] = useState(""); const colors = useThemeColors(); const { height: winH } = useWindowDimensions(); // Fold-aware: on an unfolded Duo, keep the command menu inside the left pane // instead of spanning the fold. Null on non-fold devices. const fold = useFoldFeatures(); const inputRef = useRef(null); const kb = useSharedValue(0); const filtered = useMemo(() => { const q = search.toLowerCase(); return items.filter( (item) => item.label.toLowerCase().includes(q) || item.value.toLowerCase().includes(q) || (item.group ?? "").toLowerCase().includes(q) ); }, [items, search]); const sections = useMemo(() => { const groups: Record = {}; for (const item of filtered) { const key = item.group ?? ""; (groups[key] ??= []).push(item); } return Object.entries(groups).map(([title, data]) => ({ title, data })); }, [filtered]); // Track the keyboard directly. RN Modal doesn't resize for the keyboard on // Android, so the old version's results got covered — rendering via the rn- // primitives Portal plus this listener keeps the palette above the keyboard. useEffect(() => { const showEvt = Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow"; const hideEvt = Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide"; const show = Keyboard.addListener(showEvt, (e) => { kb.value = withTiming(e.endCoordinates.height, { duration: 160 }); }); const hide = Keyboard.addListener(hideEvt, () => { kb.value = withTiming(0, { duration: 160 }); }); return () => { show.remove(); hide.remove(); }; }, [kb]); // Focus via ref on open (autoFocus is unreliable inside overlays on Android). useEffect(() => { if (!open) { setSearch(""); return; } const t = setTimeout(() => inputRef.current?.focus(), Platform.OS === "android" ? 150 : 50); return () => clearTimeout(t); }, [open]); const cardStyle = useAnimatedStyle(() => ({ maxHeight: Math.max(180, winH - TOP_OFFSET - kb.value - 24), })); const handleSelect = (item: CommandItem) => { if (item.disabled) return; item.onSelect?.(); onSelect?.(item.value); onOpenChange(false); }; return ( Command menu {filtered.length === 0 ? ( {emptyText} ) : ( item.value} style={{ flexShrink: 1 }} keyboardShouldPersistTaps="handled" keyboardDismissMode="on-drag" renderSectionHeader={({ section }) => section.title ? ( {section.title} ) : null } renderItem={({ item }) => ( handleSelect(item)} disabled={item.disabled} accessibilityRole="button" accessibilityState={{ disabled: item.disabled }} > {item.icon && {item.icon}} {item.label} {item.shortcut && ( {item.shortcut.split("+").map((key, i) => ( {i > 0 && +} {key.trim()} ))} )} )} stickySectionHeadersEnabled={false} /> )} ); } // Convenience sub-components for composition pattern export interface CommandInputProps extends React.ComponentPropsWithoutRef { className?: string; } export function CommandInput({ className, ...props }: CommandInputProps) { const colors = useThemeColors(); return ( ); } export function CommandEmpty({ children, className }: { children?: React.ReactNode; className?: string }) { return ( {children ?? "No results found."} ); } export function CommandSeparator({ className }: { className?: string }) { return ; } ``` ## ConnectionBanner - key: `connection-banner` - import: `import { ConnectionBanner } from "@/components/ui/connection-banner"` - description: Animated banner showing online/offline connection status - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/connection-banner.tsx import React from "react"; import { Text } from "react-native"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export interface ConnectionBannerProps { className?: string; /** Undefined = connectivity not yet known; the banner stays hidden. */ connected?: boolean; offlineText?: string; onlineText?: string; } export function ConnectionBanner({ className, connected, offlineText = "No internet connection", onlineText = "Back online", }: ConnectionBannerProps) { if (connected === undefined) return null; return ( {connected ? onlineText : offlineText} ); } ``` ## ContextMenu - key: `context-menu` - import: `import { ContextMenu } from "@/components/ui/context-menu"` - description: Long-press context menu with items and separators - tier: 3 - deps: @rn-primitives/context-menu, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/context-menu.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import * as ContextMenuPrimitive from "@rn-primitives/context-menu"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; export interface ContextMenuProps { children: React.ReactNode; onOpenChange?: (open: boolean) => void; } // @rn-primitives' ContextMenu Root is uncontrolled; it manages its own open // state internally and only emits via onOpenChange. There's no `open` prop // on the primitive to forward, so the wrapper doesn't take one either — // consumer-side controlled behavior would need to be rebuilt here with // the primitive's useRootContext() if we needed it later. export function ContextMenu({ children, onOpenChange }: ContextMenuProps) { return {children}; } export function ContextMenuTrigger({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children: React.ReactNode }) { return ( {children} ); } export interface ContextMenuContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function ContextMenuContent({ className, children, ...props }: ContextMenuContentProps) { const insets = useSafeAreaInsets(); const fold = useFoldFeatures(); // See popover.tsx for the pattern — fold line becomes a horizontal inset. const foldInsets = fold.foldX ? { ...insets, left: Math.max(insets.left, fold.foldX), right: Math.max(insets.right, fold.foldX) } : insets; return ( {children} ); } export interface ContextMenuItemProps extends React.ComponentPropsWithoutRef { className?: string; children: React.ReactNode; destructive?: boolean; } export function ContextMenuItem({ className, children, destructive, ...props }: ContextMenuItemProps) { return ( {typeof children === "string" ? ( {children} ) : children} ); } export function ContextMenuSeparator({ className }: { className?: string }) { return ; } ``` ## Coupon - key: `coupon` - import: `import { Coupon } from "@/components/ui/coupon"` - description: Two-section promotional coupon with a real tear-line, ticket icon, and orientation prop - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/coupon.tsx import React, { createContext, useContext, useMemo } from "react"; import { View, Text } from "react-native"; import { Ticket } from "lucide-react-native"; import { cn } from "@/lib/utils"; export interface CouponPalette { surface: string; border: string; code: string; icon: string; accent: string; accentLabel: string; } export const COUPON_DEFAULT_PALETTE: CouponPalette = { surface: "#FFFFFF", border: "#E4E4E7", code: "#18181B", icon: "#71717A", accent: "#FFE4E6", accentLabel: "#BE123C", }; export const COUPON_EMERALD_PALETTE: CouponPalette = { surface: "#FFFFFF", border: "#E4E4E7", code: "#18181B", icon: "#71717A", accent: "#D1FAE5", accentLabel: "#047857", }; export const COUPON_INK_PALETTE: CouponPalette = { surface: "#18181B", border: "#3F3F46", code: "#FAFAFA", icon: "#A1A1AA", accent: "#FAFAFA", accentLabel: "#18181B", }; type CouponOrientation = "horizontal" | "vertical"; type CouponBorderStyle = "dashed" | "solid"; interface CouponContextValue { palette: CouponPalette; orientation: CouponOrientation; border: CouponBorderStyle; borderWidth: number; } const CouponContext = createContext(null); function useCouponContext(component: string): CouponContextValue { const ctx = useContext(CouponContext); if (!ctx) throw new Error(`<${component} /> must be rendered inside a root.`); return ctx; } export interface CouponProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; palette?: Partial; orientation?: CouponOrientation; border?: CouponBorderStyle; borderWidth?: number; radius?: number; /** Shorthand fields — used only when no `children` are composed. */ code?: string; discount?: string; description?: string; expires?: string; } export function Coupon({ className, children, palette, orientation = "horizontal", border = "dashed", borderWidth = 2, radius = 10, code, discount, description, expires, ...props }: CouponProps) { const mergedPalette = useMemo(() => ({ ...COUPON_DEFAULT_PALETTE, ...palette }), [palette]); const contextValue = useMemo( () => ({ palette: mergedPalette, orientation, border, borderWidth }), [mergedPalette, orientation, border, borderWidth] ); const hasShorthand = !children && (discount !== undefined || code !== undefined); return ( {hasShorthand ? ( <> {discount} {description ? ( {`\n${description}`} ) : null} {code} {expires ? ( {`\n Expires ${expires}`} ) : null} ) : ( children )} ); } export interface CouponSectionProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; accented?: boolean; } export function CouponSection({ className, accented, children, ...props }: CouponSectionProps) { const { palette } = useCouponContext("CouponSection"); return ( {children} ); } export interface CouponDividerProps extends React.ComponentPropsWithoutRef { className?: string; } /** The tear-line perforation between two `CouponSection`s. Decorative — hidden from accessibility. */ export function CouponDivider({ className, ...props }: CouponDividerProps) { const { palette, orientation, border, borderWidth } = useCouponContext("CouponDivider"); return ( ); } export interface CouponDiscountProps extends React.ComponentPropsWithoutRef { className?: string; textClassName?: string; numberOfLines?: number; children?: React.ReactNode; } /** The accent-colored discount panel. Carries the tear-line on its own trailing edge. */ export function CouponDiscount({ className, textClassName, numberOfLines, children, ...props }: CouponDiscountProps) { const { palette, orientation, border, borderWidth } = useCouponContext("CouponDiscount"); return ( {children} ); } export interface CouponCodeProps extends React.ComponentPropsWithoutRef { className?: string; textClassName?: string; numberOfLines?: number; icon?: React.ReactNode; children?: React.ReactNode; } /** The code panel. Renders a ticket glyph beside a monospaced promo code. */ export function CouponCode({ className, textClassName, numberOfLines, icon, children, ...props }: CouponCodeProps) { const { palette } = useCouponContext("CouponCode"); return ( {icon ?? } {children} ); } ``` ## CurvedBottomTabs - key: `curved-bottom-tabs` - import: `import { CurvedBottomTabs } from "@/components/ui/curved-bottom-tabs"` - description: Bottom tab bar whose curved notch and floating gradient button slide to track the active tab, with badge support and keyboard auto-hide - tier: 3 - deps: react-native-svg, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/curved-bottom-tabs.tsx import React, { useEffect, useRef, useState } from "react"; import { View, Pressable, Text, Keyboard, useWindowDimensions, useColorScheme, type LayoutChangeEvent } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, type SharedValue } from "react-native-reanimated"; import Svg, { Path, Circle, Defs, LinearGradient, Stop } from "react-native-svg"; import { cn } from "@/lib/utils"; export type CurvedTab = { key: string; label: string; icon?: React.ReactNode; badge?: number; }; export interface CurvedBottomTabsProps extends React.ComponentPropsWithoutRef { className?: string; tabs: CurvedTab[]; activeIndex: number; onTabPress: (index: number) => void; hideOnKeyboard?: boolean; gradientColors?: readonly [string, string]; } const BAR_HEIGHT = 80; const NOTCH_HALF = 40; const FLOAT_SIZE = 56; const FLOAT_LIFT = 26; const CURVE_SPRING = { damping: 12, stiffness: 120, mass: 0.5 }; const LIFT_SPRING = { damping: 10, stiffness: 100, mass: 0.5 }; // Badge count: hidden for 0/undefined, capped display at "99+" once the // value exceeds 99 (the usual convention for notification-style badges). function formatBadge(badge?: number): string | null { if (badge === undefined || badge <= 0) return null; return badge > 99 ? "99+" : String(badge); } export function CurvedBottomTabs({ className, tabs, activeIndex, onTabPress, hideOnKeyboard = false, gradientColors, onLayout, ...props }: CurvedBottomTabsProps) { const { width: windowWidth } = useWindowDimensions(); const dark = useColorScheme() === "dark"; const [keyboardVisible, setKeyboardVisible] = useState(false); // The bar's math needs its own actual rendered width, not the device's — // a consumer rendering this inside a padded container (as our own example // app's screen does) made every calculation assume a wider bar than what // was really on screen, so the notch drifted further off-target with each // tab index. Falls back to the window width only until the first layout. const [measuredWidth, setMeasuredWidth] = useState(0); const width = measuredWidth || windowWidth; const handleLayout = (e: LayoutChangeEvent) => { const w = e.nativeEvent.layout.width; if (w > 0 && w !== measuredWidth) setMeasuredWidth(w); onLayout?.(e); }; const tabWidth = width / tabs.length; // The bar is rendered 3x screen-width with a single fixed notch at its own // midpoint, then clipped to `width` and slid horizontally via translateX so // the notch appears to travel to whichever tab is active — a wide strip // plus overflow:hidden, rather than redrawing the notch's path per tab. const patternWidth = width * 3; const patternMid = patternWidth / 2; // The notch's own curve is NOTCH_HALF wide on each side of its center — for // the first/last tab that center can sit closer to the screen edge than // that, which clips off one side of the dip against the bar's // overflow-hidden. Clamping keeps the whole symmetric notch on-screen, // trading a little centering under the very first/last tab for a shape // that never gets cut off. const targetFor = (index: number) => { const idealCenter = index * tabWidth + tabWidth / 2; const clampedCenter = Math.min(Math.max(idealCenter, NOTCH_HALF), width - NOTCH_HALF); return clampedCenter - patternMid; }; const curveX = useSharedValue(targetFor(activeIndex)); // One shared value per tab so the outgoing tab can ease back down while the // incoming one rises. Relies on `tabs.length` staying stable across renders. const lifts = useRef(tabs.map((_, i) => useSharedValue(i === activeIndex ? -FLOAT_LIFT : 0))).current; useEffect(() => { curveX.value = withSpring(targetFor(activeIndex), CURVE_SPRING); lifts.forEach((lift, i) => { lift.value = withSpring(i === activeIndex ? -FLOAT_LIFT : 0, LIFT_SPRING); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeIndex, tabWidth]); useEffect(() => { if (!hideOnKeyboard) return; const showSub = Keyboard.addListener("keyboardDidShow", () => setKeyboardVisible(true)); const hideSub = Keyboard.addListener("keyboardDidHide", () => setKeyboardVisible(false)); return () => { showSub.remove(); hideSub.remove(); }; }, [hideOnKeyboard]); const curveStyle = useAnimatedStyle(() => ({ transform: [{ translateX: curveX.value }] })); if (hideOnKeyboard && keyboardVisible) return null; const barGradient = gradientColors ?? (dark ? (["#18181b", "#27272a"] as const) : (["#ffffff", "#f4f4f5"] as const)); const floatGradient = dark ? (["#fafafa", "#d4d4d8"] as const) : (["#18181b", "#3f3f46"] as const); const notchPath = `M0,0 L${patternMid - NOTCH_HALF},0 Q${patternMid - 14},0 ${patternMid},32 Q${patternMid + 14},0 ${patternMid + NOTCH_HALF},0 L${patternWidth},0 L${patternWidth},${BAR_HEIGHT} L0,${BAR_HEIGHT} Z`; // The bar's fill is intentionally close to the page background (it's meant // to read as part of the screen, not a separate card) — which also means // the curve is invisible with nothing to set its top edge apart. A stroke // along the path plus a shadow on the whole bar keeps the notch visible // regardless of how close the two colors are. const strokeColor = dark ? "#3f3f46" : "#e4e4e7"; return ( {tabs.map((tab, index) => ( onTabPress(index)} /> ))} ); } function TabButton({ tab, active, lift, gradient, onPress, }: { tab: CurvedTab; active: boolean; lift: SharedValue; gradient: readonly [string, string]; onPress: () => void; }) { const liftStyle = useAnimatedStyle(() => ({ transform: [{ translateY: lift.value }] })); const badgeLabel = formatBadge(tab.badge); const gradientId = `curvedTabsFloat-${tab.key}`; return ( {active ? ( {tab.icon} {badgeLabel && ( {badgeLabel} )} ) : ( <> {tab.icon} {badgeLabel && ( {badgeLabel} )} {tab.label} )} ); } ``` ## DataTable - key: `data-table` - import: `import { DataTable } from "@/components/ui/data-table"` - description: Sortable, filterable data table with pagination and custom cell rendering - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/data-table.tsx import React, { useState, useMemo, useCallback } from "react"; import { View, Text, TextInput, Pressable, ScrollView, type ViewStyle } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { ChevronDown, ChevronUp } from "lucide-react-native"; export interface DataTableColumn { key: keyof T & string; header: string; sortable?: boolean; width?: number; render?: (value: T[keyof T], row: T) => React.ReactNode; } export interface DataTableProps extends React.ComponentPropsWithoutRef { columns: DataTableColumn[]; data: T[]; sortBy?: string; sortOrder?: "asc" | "desc"; onSort?: (key: string, order: "asc" | "desc") => void; searchable?: boolean; searchKeys?: string[]; searchPlaceholder?: string; pageSize?: number; emptyText?: string; className?: string; striped?: boolean; /** When true, fit columns to container width and truncate long content with ellipsis. * Default false: each column has a fixed width (col.width or defaultColumnWidth) and the * table scrolls horizontally if total content exceeds the viewport. */ truncate?: boolean; /** Default pixel width for columns that don't specify `col.width`. Used in scroll mode only. */ defaultColumnWidth?: number; } function SortIcon({ order }: { order?: "asc" | "desc" }) { const colors = useThemeColors(); return order === "asc" ? ( ) : ( ); } export function DataTable>({ columns, data, sortBy: controlledSortBy, sortOrder: controlledSortOrder, onSort, searchable = false, searchKeys, searchPlaceholder = "Search...", pageSize, emptyText = "No data", className, striped = false, truncate = false, defaultColumnWidth = 150, ...props }: DataTableProps) { const [internalSortBy, setInternalSortBy] = useState(); const [internalSortOrder, setInternalSortOrder] = useState<"asc" | "desc">("asc"); const [search, setSearch] = useState(""); const [page, setPage] = useState(0); const sortBy = controlledSortBy ?? internalSortBy; const sortOrder = controlledSortOrder ?? internalSortOrder; const handleSort = useCallback((key: string) => { if (onSort) { onSort(key, sortBy === key && sortOrder === "asc" ? "desc" : "asc"); } else { setInternalSortOrder(sortBy === key && internalSortOrder === "asc" ? "desc" : "asc"); setInternalSortBy(key); } setPage(0); }, [sortBy, sortOrder, internalSortOrder, onSort]); const keys = useMemo(() => searchKeys ?? columns.map((c) => c.key), [searchKeys, columns]); const filtered = useMemo(() => { if (!search.trim()) return data; const q = search.toLowerCase(); return data.filter((row) => keys.some((k) => String(row[k] ?? "").toLowerCase().includes(q)) ); }, [data, search, keys]); const sorted = useMemo(() => { if (!sortBy) return filtered; return [...filtered].sort((a, b) => { const aVal = a[sortBy] ?? ""; const bVal = b[sortBy] ?? ""; const cmp = String(aVal).localeCompare(String(bVal), undefined, { numeric: true }); return sortOrder === "asc" ? cmp : -cmp; }); }, [filtered, sortBy, sortOrder]); const totalPages = pageSize ? Math.max(1, Math.ceil(sorted.length / pageSize)) : 1; const paged = pageSize ? sorted.slice(page * pageSize, (page + 1) * pageSize) : sorted; const [contentWidth, setContentWidth] = useState(0); const fixedSum = columns.reduce((s, c) => s + (c.width ?? 0), 0); const autoCount = columns.filter((c) => !c.width).length; const truncatedAutoWidth = autoCount > 0 && contentWidth > 0 ? Math.max((contentWidth - fixedSum) / autoCount, 80) : 0; const colStyle = (col: DataTableColumn): ViewStyle => { if (col.width) return { width: col.width, overflow: "hidden" }; if (truncate) { if (truncatedAutoWidth > 0) return { width: truncatedAutoWidth, overflow: "hidden" }; return { flexGrow: 1, flexShrink: 1, flexBasis: 0, minWidth: 0, overflow: "hidden" }; } return { width: defaultColumnWidth, overflow: "hidden" }; }; const colors = useThemeColors(); return ( {searchable && ( { setSearch(v); setPage(0); }} accessibilityLabel="Search table" /> )} setContentWidth(e.nativeEvent.layout.width) : undefined} > {/* Header */} {columns.map((col) => ( col.sortable && handleSort(col.key)} disabled={!col.sortable} accessible={true} accessibilityRole={col.sortable ? "button" : "text"} > {col.header} {col.sortable && sortBy === col.key && } ))} {/* Body */} {paged.length === 0 ? ( {emptyText} ) : ( paged.map((item, index) => ( {columns.map((col) => ( {col.render ? ( col.render(item[col.key], item) ) : ( {String(item[col.key] ?? "")} )} ))} )) )} {pageSize && totalPages > 1 && ( {page * pageSize + 1}-{Math.min((page + 1) * pageSize, sorted.length)} of {sorted.length} setPage(Math.max(0, page - 1))} disabled={page === 0} className={cn("px-3 py-1.5 rounded-md border border-input", page === 0 && "opacity-40")} accessibilityRole="button" accessibilityLabel="Previous page" > Prev setPage(Math.min(totalPages - 1, page + 1))} disabled={page >= totalPages - 1} className={cn("px-3 py-1.5 rounded-md border border-input", page >= totalPages - 1 && "opacity-40")} accessibilityRole="button" accessibilityLabel="Next page" > Next )} ); } ``` ## DatePicker - key: `date-picker` - import: `import { DatePicker } from "@/components/ui/date-picker"` - description: Date picker with calendar popup and range support - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: calendar, theme-provider ```tsx // components/ui/date-picker.tsx import React, { useState } from "react"; import { View, Text, Pressable, Modal } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { Calendar } from "@/components/ui/calendar"; import { Calendar as CalendarIcon } from "lucide-react-native"; export interface DatePickerProps { className?: string; value?: Date; onChange?: (date: Date) => void; placeholder?: string; min?: Date; max?: Date; formatDate?: (date: Date) => string; } function PickerShell({ open, onClose, children }: { open: boolean; onClose: () => void; children: React.ReactNode }) { return ( {}} className="mx-6 rounded-xl bg-card p-2 shadow-xl" style={{ minHeight: 360 }}> {children} Cancel ); } function TriggerButton({ label, hasValue, className, onPress }: { label: string; hasValue: boolean; className?: string; onPress: () => void }) { const colors = useThemeColors(); return ( {label} ); } export function DatePicker({ className, value, onChange, placeholder = "Select date...", min, max, formatDate }: DatePickerProps) { const [open, setOpen] = useState(false); const display = value ? (formatDate ?? ((d: Date) => d.toLocaleDateString()))(value) : placeholder; return ( <> setOpen(true)} /> setOpen(false)}> { onChange?.(d); setOpen(false); }} min={min} max={max} /> ); } export interface DateRangePickerProps { className?: string; startDate?: Date; endDate?: Date; onRangeChange?: (start: Date, end: Date | undefined) => void; placeholder?: string; min?: Date; max?: Date; } export function DateRangePicker({ className, startDate, endDate, onRangeChange, placeholder = "Select range...", min, max }: DateRangePickerProps) { const [open, setOpen] = useState(false); const display = startDate ? `${startDate.toLocaleDateString()}${endDate ? ` - ${endDate.toLocaleDateString()}` : ""}` : placeholder; return ( <> setOpen(true)} /> setOpen(false)}> ); } ``` ## Dialog - key: `dialog` - import: `import { Dialog } from "@/components/ui/dialog"` - description: Modal dialog overlay - tier: 1 - deps: clsx, tailwind-merge - aniui deps: fold ```tsx // components/ui/dialog.tsx import React from "react"; import { View, Pressable, Text, Modal } from "react-native"; import { cn } from "@/lib/utils"; import { useFoldFeatures } from "@/components/ui/fold"; export interface DialogProps { open: boolean; onOpenChange: (open: boolean) => void; children: React.ReactNode; } export function Dialog({ open, onOpenChange, children }: DialogProps) { const fold = useFoldFeatures(); // On an unfolded iPhone Duo / foldable, center the dialog inside the left // pane instead of across the fold line. foldX is null on every other device, // so this is a no-op pre-fold. const foldPadding = fold.foldX ? { paddingRight: fold.foldX } : undefined; return ( onOpenChange(false)}> onOpenChange(false)} /> {children} ); } export function DialogContent({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children?: React.ReactNode }) { return ( {children} ); } export function DialogHeader({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function DialogTitle({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function DialogDescription({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function DialogFooter({ className, ...props }: React.ComponentPropsWithoutRef & { className?: string }) { return ; } export function DialogTrigger({ children }: { children: React.ReactNode }) { return <>{children}; } export function DialogClose({ children }: { children: React.ReactNode }) { return <>{children}; } ``` ## DirectionProvider - key: `direction-provider` - import: `import { DirectionProvider } from "@/components/ui/direction-provider"` - description: RTL/LTR direction context with I18nManager integration - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/direction-provider.tsx import React, { createContext, useContext, useState, useCallback } from "react"; import { I18nManager, View } from "react-native"; import { cn } from "@/lib/utils"; type Direction = "ltr" | "rtl"; interface DirectionContextValue { direction: Direction; isRTL: boolean; setDirection: (dir: Direction) => void; } const DirectionContext = createContext({ direction: I18nManager.isRTL ? "rtl" : "ltr", isRTL: I18nManager.isRTL, setDirection: () => {}, }); export function useDirection() { return useContext(DirectionContext); } export interface DirectionProviderProps extends React.ComponentPropsWithoutRef { children: React.ReactNode; defaultDirection?: Direction; className?: string; } /** * Provides RTL/LTR direction context for the app. * Note: Calling setDirection updates context immediately, but the full * layout flip via I18nManager requires an app restart on React Native. */ export function DirectionProvider({ children, defaultDirection, className, ...props }: DirectionProviderProps) { const initial = defaultDirection ?? (I18nManager.isRTL ? "rtl" : "ltr"); const [direction, setDir] = useState(initial); const setDirection = useCallback((dir: Direction) => { setDir(dir); I18nManager.allowRTL(true); I18nManager.forceRTL(dir === "rtl"); }, []); return ( {children} ); } ``` ## Drawer - key: `drawer` - import: `import { Drawer } from "@/components/ui/drawer"` - description: Slide-in side navigation panel - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/drawer.tsx import React, { useEffect, useState } from "react"; import { View, Pressable, Modal } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming } from "react-native-reanimated"; import { springs, duration } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export interface DrawerProps { open: boolean; onOpenChange: (open: boolean) => void; side?: "left" | "right"; children: React.ReactNode; } export function Drawer({ open, onOpenChange, side = "left", children }: DrawerProps) { // Keep the Modal mounted while the slide-out plays; unmounting on `open` // directly would cut the close animation short. const [visible, setVisible] = useState(open); const translate = useSharedValue(side === "left" ? -300 : 300); const opacity = useSharedValue(0); useEffect(() => { if (open) { setVisible(true); translate.value = withSpring(0, springs.snappy); opacity.value = withTiming(0.5, { duration: duration.normal }); return; } translate.value = withTiming(side === "left" ? -300 : 300, { duration: duration.normal }); opacity.value = withTiming(0, { duration: duration.normal }); const t = setTimeout(() => setVisible(false), duration.normal); return () => clearTimeout(t); }, [open, side, translate, opacity]); const overlayStyle = useAnimatedStyle(() => ({ opacity: opacity.value })); const drawerStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translate.value }], })); const close = () => onOpenChange(false); return ( {children} ); } export interface DrawerContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function DrawerContent({ className, ...props }: DrawerContentProps) { return ; } ``` ## DropdownMenu - key: `dropdown-menu` - import: `import { DropdownMenu } from "@/components/ui/dropdown-menu"` - description: Dropdown menu with items, separators, and destructive actions - tier: 3 - deps: @rn-primitives/dropdown-menu, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/dropdown-menu.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import * as DropdownMenuPrimitive from "@rn-primitives/dropdown-menu"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; export interface DropdownMenuProps { children: React.ReactNode; onOpenChange?: (open: boolean) => void; } // @rn-primitives' DropdownMenu Root is uncontrolled — see context-menu.tsx. export function DropdownMenu({ children, onOpenChange }: DropdownMenuProps) { return {children}; } export function DropdownMenuTrigger({ className, children, ...props }: React.ComponentPropsWithoutRef & { className?: string; children: React.ReactNode }) { return ( {/* rn-primitives measures this exact box to position the menu below it — min-h-12/min-w-12 would force a 48x48 measured box even for a small icon child, opening the menu ~48px below the trigger's top edge instead of just past the icon. hitSlop expands the tappable area to the 48dp minimum without inflating what gets measured. */} {children} ); } export interface DropdownMenuContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; // Primitive only supports vertical sides; "left" / "right" aren't valid here. side?: "top" | "bottom"; sideOffset?: number; align?: "start" | "center" | "end"; } export function DropdownMenuContent({ className, children, side = "bottom", sideOffset = 4, align = "start", ...props }: DropdownMenuContentProps) { const insets = useSafeAreaInsets(); const fold = useFoldFeatures(); // See popover.tsx for the pattern — fold line becomes a horizontal inset. const foldInsets = fold.foldX ? { ...insets, left: Math.max(insets.left, fold.foldX), right: Math.max(insets.right, fold.foldX) } : insets; return ( {children} ); } export interface DropdownMenuItemProps extends React.ComponentPropsWithoutRef { className?: string; children: React.ReactNode; destructive?: boolean; } export function DropdownMenuItem({ className, children, destructive, ...props }: DropdownMenuItemProps) { return ( {typeof children === "string" ? ( {children} ) : children} ); } export function DropdownMenuSeparator({ className }: { className?: string }) { return ; } ``` ## EmptyState - key: `empty-state` - import: `import { EmptyState } from "@/components/ui/empty-state"` - description: Placeholder for empty screens and error states - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/empty-state.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { cn } from "@/lib/utils"; export interface EmptyStateProps extends React.ComponentPropsWithoutRef { className?: string; icon?: React.ReactNode; title: string; description?: string; action?: { label: string; onPress: () => void }; } export function EmptyState({ className, icon, title, description, action, ...props }: EmptyStateProps) { return ( {icon && {icon}} {title} {description && {description}} {action && ( {action.label} )} ); } ``` ## EventTicket - key: `event-ticket` - import: `import { EventTicket } from "@/components/ui/event-ticket"` - description: Event ticket card with perforated edge, date, venue, and seat - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/event-ticket.tsx import React, { useState } from "react"; import { View, Text, LayoutChangeEvent, useColorScheme } from "react-native"; import Svg, { Path } from "react-native-svg"; import { Calendar, MapPin, Ticket } from "lucide-react-native"; import { cn } from "@/lib/utils"; const TICKET_RADIUS = 16; const NOTCH_RADIUS = 9; const STUB_WIDTH = 96; const BAR_COUNT = 18; // Kept deliberately thin (1-3px): at a 64px-tall barcode box, taller bars // (this used 4-22px before) don't fit 18 of them stacked and overflow the // box, which is why the barcode wasn't rendering as anything recognizable. const BAR_MIN_HEIGHT = 1; const BAR_MAX_HEIGHT = 3; export type EventTicketStubSide = "left" | "right"; export type EventTicketPerforation = "dashed" | "solid" | "none"; export interface EventTicketProps extends React.ComponentPropsWithoutRef { className?: string; title: string; date: string; venue: string; seat?: string; code?: string; stubSide?: EventTicketStubSide; perforation?: EventTicketPerforation; } // A closed circle subpath at (cx, cy) with radius r, wound the same direction // as the outer body path. Combined with fillRule="evenodd" on the parent // , any subpath that overlaps the body punches a hole through it. function notchHole(cx: number, cy: number, r: number) { return `M${cx - r} ${cy} a${r} ${r} 0 1 0 ${r * 2} 0 a${r} ${r} 0 1 0 ${-r * 2} 0 Z`; } // Builds the full ticket silhouette: a rounded-rect body plus two circular // notches straddling the top and bottom edge at tearX (the seam where the // stub meets the main section) -- the classic "torn ticket" cutout look. function buildSilhouettePath(width: number, height: number, radius: number, tearX: number, notchRadius: number) { const r = Math.min(radius, width / 2, height / 2); const body = [ `M${r} 0`, `H${width - r}`, `A${r} ${r} 0 0 1 ${width} ${r}`, `V${height - r}`, `A${r} ${r} 0 0 1 ${width - r} ${height}`, `H${r}`, `A${r} ${r} 0 0 1 0 ${height - r}`, `V${r}`, `A${r} ${r} 0 0 1 ${r} 0`, "Z", ].join(" "); if (notchRadius <= 0) return body; return `${body} ${notchHole(tearX, 0, notchRadius)} ${notchHole(tearX, height, notchRadius)}`; } // Deterministically derives a sequence of bar heights from a seed string, so // the same code always renders the same barcode instead of a random one. function buildBarHeights(seed: string, count: number) { const source = seed.length > 0 ? seed : "aniui"; const span = BAR_MAX_HEIGHT - BAR_MIN_HEIGHT; return Array.from({ length: count }, (_, i) => { const code = source.charCodeAt(i % source.length); return BAR_MIN_HEIGHT + ((code * 7 + i * 11) % (span + 1)); }); } export function EventTicket({ className, title, date, venue, seat, code, stubSide = "right", perforation = "dashed", ...props }: EventTicketProps) { const [size, setSize] = useState({ width: 0, height: 0 }); const dark = useColorScheme() === "dark"; const surfaceColor = dark ? "#09090b" : "#ffffff"; const strokeColor = dark ? "#27272a" : "#e4e4e7"; const onLayout = (e: LayoutChangeEvent) => { const { width, height } = e.nativeEvent.layout; if (width !== size.width || height !== size.height) setSize({ width, height }); }; const tearX = stubSide === "right" ? size.width - STUB_WIDTH : STUB_WIDTH; const path = size.width > 0 && size.height > 0 ? buildSilhouettePath(size.width, size.height, TICKET_RADIUS, tearX, NOTCH_RADIUS) : null; const bars = code ? buildBarHeights(code, BAR_COUNT) : []; const tearBorderClass = perforation === "none" ? "" : cn( stubSide === "right" ? "border-l" : "border-r", perforation === "dashed" ? "border-dashed" : "border-solid", "border-border" ); const main = ( Event Ticket {title} {date} {venue} {seat ? Seat {seat} : null} ); const stub = ( {code ? ( <> {bars.map((height, i) => ( ))} {/* Fixed-height box, not just the rotated Text alone: a rotate transform doesn't reflow surrounding layout to match its visual footprint, so an unwrapped rotated text keeps its pre-rotation (wide, short) footprint and can overlap the barcode above it. */} {code} ) : null} ); return ( {path ? ( ) : null} {stubSide === "right" ? ( <> {main} {stub} ) : ( <> {stub} {main} )} ); } ``` ## ExpandableView - key: `expandable-view` - import: `import { ExpandableView } from "@/components/ui/expandable-view"` - description: Generic expand/collapse container with spring-driven width/height/corner-radius morphing and a slot API - tier: 2 - deps: react-native-reanimated, lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/expandable-view.tsx import React, { Children, createContext, isValidElement, useCallback, useContext, useMemo, useState, } from "react"; import { Pressable } from "react-native"; import Animated, { interpolate, useAnimatedStyle, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { X } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); const PRESS_SPRING: WithSpringConfig = { damping: 12, stiffness: 250, mass: 0.5 }; const EXPAND_SPRING: WithSpringConfig = { damping: 13, stiffness: 120, mass: 0.5 }; interface ExpandableViewContextValue { progress: SharedValue; expanded: boolean; expand: () => void; collapse: () => void; } const ExpandableViewContext = createContext(null); function useExpandableView(component: string) { const ctx = useContext(ExpandableViewContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } export interface ExpandableViewSlotProps { children?: React.ReactNode; } // Slot markers — never rendered directly. ExpandableView pulls each one's // children out via Children.forEach and puts them in their own absolutely // positioned animated layer, so the collapsed pill and the expanded panel can // cross-fade over each other instead of one replacing the other in the tree. type SlotRole = "collapsed" | "expanded"; interface SlotComponent { (props: ExpandableViewSlotProps): null; role?: SlotRole; } export const ExpandableViewCollapsed: SlotComponent = () => null; ExpandableViewCollapsed.role = "collapsed"; export const ExpandableViewExpanded: SlotComponent = () => null; ExpandableViewExpanded.role = "expanded"; export interface ExpandableViewProps extends React.ComponentPropsWithoutRef { children: React.ReactNode; className?: string; collapsedWidth?: number; expandedWidth?: number; collapsedHeight?: number; expandedHeight?: number; collapsedRadius?: number; expandedRadius?: number; pressSpring?: WithSpringConfig; expandSpring?: WithSpringConfig; onExpandedChange?: (expanded: boolean) => void; } /** * Generic expand/collapse container: a collapsed pill morphs (width, height, * corner radius, all spring-driven) into an expanded panel. Reusable * primitive — screens compose their own collapsed/expanded content via the * `Collapsed`/`Expanded` slots and an optional `Close` button. */ export function ExpandableView({ children, className, collapsedWidth = 170, expandedWidth = 330, collapsedHeight = 50, expandedHeight = 350, collapsedRadius = 99, expandedRadius = 30, pressSpring = PRESS_SPRING, expandSpring = EXPAND_SPRING, onExpandedChange, style, ...props }: ExpandableViewProps) { const progress = useSharedValue(0); const scale = useSharedValue(1); const [expanded, setExpanded] = useState(false); const { collapsedNode, expandedNode } = useMemo(() => { let collapsedNode: React.ReactNode = null; let expandedNode: React.ReactNode = null; Children.forEach(children, (child) => { if (!isValidElement(child)) return; const role = (child.type as SlotComponent).role; const slotProps = child.props as ExpandableViewSlotProps; if (role === "collapsed") collapsedNode = slotProps.children; else if (role === "expanded") expandedNode = slotProps.children; }); return { collapsedNode, expandedNode }; }, [children]); const expand = useCallback(() => { setExpanded(true); onExpandedChange?.(true); scale.value = withSpring(1, pressSpring); progress.value = withSpring(1, expandSpring); }, [onExpandedChange, scale, progress, pressSpring, expandSpring]); const collapse = useCallback(() => { setExpanded(false); onExpandedChange?.(false); progress.value = withSpring(0, expandSpring); }, [onExpandedChange, progress, expandSpring]); const ctx = useMemo( () => ({ progress, expanded, expand, collapse }), [progress, expanded, expand, collapse] ); const containerStyle = useAnimatedStyle(() => ({ width: interpolate(progress.value, [0, 1], [collapsedWidth, expandedWidth]), height: interpolate(progress.value, [0, 1], [collapsedHeight, expandedHeight]), borderRadius: interpolate(progress.value, [0, 1], [collapsedRadius, expandedRadius]), transform: [{ scale: scale.value }], })); const collapsedStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.5], [1, 0]), transform: [{ translateY: interpolate(progress.value, [0, 1], [0, 60]) }], })); const expandedStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.15, 1], [0, 1]), })); return ( {expandedNode} { if (!expanded) scale.value = withSpring(1.06, pressSpring); }} onPressOut={() => { scale.value = withSpring(1, pressSpring); }} accessible={true} accessibilityRole="button" accessibilityState={{ expanded }} > {collapsedNode} ); } export interface ExpandableViewCloseProps { children?: React.ReactNode; className?: string; } /** Fades in once the panel is mostly expanded; collapses the view on press. */ export function ExpandableViewClose({ children, className }: ExpandableViewCloseProps) { const { progress, collapse } = useExpandableView("ExpandableViewClose"); const colors = useThemeColors(); const style = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.6, 1], [0, 1]), })); return ( {children ?? } ); } ``` ## FAB - key: `fab` - import: `import { FAB } from "@/components/ui/fab"` - description: Floating action button for primary screen actions - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/fab.tsx import React from "react"; import { Pressable, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const fabVariants = cva( "items-center justify-center shadow-lg", { variants: { variant: { default: "bg-primary", secondary: "bg-secondary", destructive: "bg-destructive", }, size: { sm: "h-12 w-12 rounded-full", md: "h-14 w-14 rounded-full", lg: "h-16 w-16 rounded-full", extended: "h-14 rounded-full px-6 flex-row gap-2", }, position: { "bottom-right": "absolute bottom-6 end-6", "bottom-left": "absolute bottom-6 start-6", "bottom-center": "absolute bottom-6 self-center", none: "", }, }, defaultVariants: { variant: "default", size: "md", position: "bottom-right" }, } ); const fabTextVariants = cva("font-semibold", { variants: { variant: { default: "text-primary-foreground", secondary: "text-secondary-foreground", destructive: "text-destructive-foreground", }, }, defaultVariants: { variant: "default" }, }); export interface FABProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; icon?: React.ReactNode; label?: string; } export function FAB({ variant, size, position, className, icon, label, ...props }: FABProps) { return ( {icon} {label && {label}} ); } ``` ## FanMenu - key: `fan-menu` - import: `import { FanMenu } from "@/components/ui/fan-menu"` - description: Radial fan menu that staggers labeled pill actions out from a FAB trigger, with tap-outside-to-dismiss backdrop and per-item blur - tier: 3 - deps: lucide-react-native, react-native-svg, react-native-reanimated, expo-blur, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/fan-menu.tsx import React, { useEffect, useState } from "react"; import { View, Pressable, Text, useWindowDimensions } from "react-native"; import Animated, { Extrapolation, interpolate, useAnimatedProps, useAnimatedStyle, useSharedValue, withDelay, withSpring, } from "react-native-reanimated"; import { BlurView } from "expo-blur"; import { Plus } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const AnimatedPressable = Animated.createAnimatedComponent(Pressable); const SPRING = { damping: 14, stiffness: 170, mass: 0.8 } as const; const PRESS_SPRING = { damping: 20, stiffness: 250, mass: 0.5 } as const; const STAGGER_MS = 30; export type FanMenuItem = { key: string; icon: React.ReactNode; label?: string; onPress?: () => void; angle?: number; }; export interface FanMenuProps extends React.ComponentPropsWithoutRef { className?: string; items: FanMenuItem[]; radius?: number; triggerIcon?: React.ReactNode; } export function FanMenu({ className, items, radius = 96, triggerIcon, ...props }: FanMenuProps) { const [open, setOpen] = useState(false); const colors = useThemeColors(); const { width: screenW, height: screenH } = useWindowDimensions(); const progress = useSharedValue(0); const pressed = useSharedValue(0); const spread = 120; const startAngle = -spread / 2; const count = items.length; useEffect(() => { progress.value = open ? withSpring(1, SPRING) : withDelay(Math.max(0, count - 1) * STAGGER_MS, withSpring(0, SPRING)); }, [open, count, progress]); const backdropStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 1], [0, 1], Extrapolation.CLAMP), })); const triggerStyle = useAnimatedStyle(() => ({ transform: [ { scale: interpolate(pressed.value, [0, 1], [1, 0.9], Extrapolation.CLAMP) }, { rotate: `${interpolate(progress.value, [0, 1], [0, 45], Extrapolation.CLAMP)}deg` }, ], })); return ( setOpen(false)} className="flex-1" accessible={true} accessibilityRole="button" accessibilityLabel="Close menu" /> {items.map((item, index) => { const angle = item.angle ?? startAngle + (spread / Math.max(count - 1, 1)) * index; const delay = (open ? index : count - 1 - index) * STAGGER_MS; return ; })} setOpen((v) => !v)} onPressIn={() => { pressed.value = withSpring(1, PRESS_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, PRESS_SPRING); }} accessible={true} accessibilityRole="button" accessibilityState={{ expanded: open }} accessibilityLabel={open ? "Close menu" : "Open menu"} className="h-14 w-14 items-center justify-center rounded-full bg-primary shadow-lg min-h-12 min-w-12" > {triggerIcon ?? } ); } function FanMenuAction({ open, angle, radius, delay, item, }: { open: boolean; angle: number; radius: number; delay: number; item: FanMenuItem; }) { const rad = (angle * Math.PI) / 180; const targetX = Math.sin(rad) * radius; const targetY = -Math.cos(rad) * radius; const t = useSharedValue(open ? 1 : 0); const pressed = useSharedValue(0); useEffect(() => { t.value = withDelay(delay, withSpring(open ? 1 : 0, SPRING)); }, [open, delay, t]); const style = useAnimatedStyle(() => { const p = t.value; return { opacity: interpolate(p, [0, 0.25, 1], [0, 0.4, 1], Extrapolation.CLAMP), transform: [ { translateX: targetX * p }, { translateY: targetY * p }, { scale: interpolate(p, [0, 1], [0.4, 1], Extrapolation.CLAMP) }, ], }; }); const pressableStyle = useAnimatedStyle(() => ({ transform: [{ scale: interpolate(pressed.value, [0, 1], [1, 1.06], Extrapolation.CLAMP) }], })); const blurProps = useAnimatedProps(() => ({ intensity: interpolate(t.value, [0, 0.25, 0.45, 1], [0, 30, 35, 0], Extrapolation.CLAMP), })); return ( { pressed.value = withSpring(1, PRESS_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, PRESS_SPRING); }} disabled={!open} accessible={true} accessibilityRole="button" accessibilityLabel={item.label ?? item.key} className={cn( "flex-row items-center justify-center gap-2 rounded-full border border-border bg-card/90 shadow-md min-h-12 min-w-12", item.label ? "px-4 py-2" : "h-12 w-12" )} style={pressableStyle} > {item.icon} {item.label ? {item.label} : null} ); } ``` ## Field - key: `field` - import: `import { Field } from "@/components/ui/field"` - description: Layout-focused form field with label, description, and error - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/field.tsx import React, { createContext, useContext } from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; type Orientation = "vertical" | "horizontal"; const FieldContext = createContext<{ orientation: Orientation }>({ orientation: "vertical", }); export interface FieldProps extends React.ComponentPropsWithoutRef { className?: string; orientation?: Orientation; children?: React.ReactNode; } export function Field({ orientation = "vertical", className, children, ...props }: FieldProps) { return ( {children} ); } export interface FieldLabelProps extends React.ComponentPropsWithoutRef { className?: string; } export function FieldLabel({ className, ...props }: FieldLabelProps) { const { orientation } = useContext(FieldContext); return ( ); } export interface FieldDescriptionProps extends React.ComponentPropsWithoutRef { className?: string; } export function FieldDescription({ className, ...props }: FieldDescriptionProps) { return ( ); } export interface FieldErrorProps extends React.ComponentPropsWithoutRef { className?: string; errors?: string[]; children?: React.ReactNode; } export function FieldError({ className, errors, children, ...props }: FieldErrorProps) { if (!errors?.length && !children) return null; return ( {errors?.map((err, i) => ( {err} ))} {children} ); } ``` ## FilePicker - key: `file-picker` - import: `import { FilePicker } from "@/components/ui/file-picker"` - description: File upload UI with dashed border, preview, and remove button - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/file-picker.tsx import React from "react"; import { View, Pressable, Text } from "react-native"; import { CloudUpload, X } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface FileInfo { name: string; size?: number; type?: string; uri?: string; } export interface FilePickerProps extends React.ComponentPropsWithoutRef { className?: string; file?: FileInfo; onPress: () => void; onRemove?: () => void; label?: string; accept?: string; } function formatSize(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } export function FilePicker({ className, file, onPress, onRemove, label = "Tap to select a file", ...props }: FilePickerProps) { const colors = useThemeColors(); return ( {!file ? ( {label} ) : ( {file.name} {file.size !== undefined && ( {formatSize(file.size)} )} {onRemove && ( )} )} ); } ``` ## FillingStack - key: `filling-stack` - import: `import { FillingStack } from "@/components/ui/filling-stack"` - description: Vertically browsable card stack with fling gestures and a blur "filling" transition between cards - tier: 3 - deps: react-native-reanimated, react-native-gesture-handler, expo-blur, clsx, tailwind-merge ```tsx // components/ui/filling-stack.tsx import React, { useState } from "react"; import { View, useColorScheme } from "react-native"; import { Directions, Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { Extrapolation, interpolate, runOnJS, useAnimatedProps, useAnimatedStyle, useSharedValue, withSpring, type SharedValue, } from "react-native-reanimated"; import { BlurView, type BlurViewProps } from "expo-blur"; import { cn } from "@/lib/utils"; export interface FillingStackProps extends React.ComponentPropsWithoutRef { className?: string; data: T[]; renderItem: (item: T, index: number) => React.ReactNode; /** How many cards peek behind the active one. */ visibleCount?: number; cardHeight?: number; onIndexChange?: (index: number) => void; } const SPRING = { damping: 18, stiffness: 140, mass: 0.5 }; const STACK_OFFSET = 14; const STACK_SCALE_STEP = 0.04; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); function FillingCard({ position, total, visibleCount, cardHeight, progress, dark, children, }: { position: number; total: number; visibleCount: number; cardHeight: number; progress: SharedValue; dark: boolean; children: React.ReactNode; }) { const back = Math.max(visibleCount - 1, 2); const cardStyle = useAnimatedStyle(() => { const depth = position - progress.value; const translateY = interpolate(depth, [-1, 0, 1, back], [-cardHeight * 1.25, 0, 0, -STACK_OFFSET * (back - 1)], Extrapolation.CLAMP); const scale = interpolate(depth, [-1, 0, 1, back], [1.06, 1, 1, 1 - STACK_SCALE_STEP * (back - 1)], Extrapolation.CLAMP); const opacity = interpolate(depth, [-1, -0.35, 0, back, back + 0.65], [0, 1, 1, 1, 0], Extrapolation.CLAMP); return { transform: [{ translateY }, { scale }], opacity, zIndex: total - position }; }); const blurProps = useAnimatedProps(() => { const depth = position - progress.value; return { intensity: interpolate(depth, [-1, 0, 1], [30, 0, 30], Extrapolation.CLAMP) }; }); return ( {children} ); } /** A vertically browsable card stack — fling up/down to cycle, with a blur "fill" between depths. */ export function FillingStack({ className, data, renderItem, visibleCount = 3, cardHeight = 260, onIndexChange, ...props }: FillingStackProps) { const dark = useColorScheme() === "dark"; const progress = useSharedValue(0); const [index, setIndex] = useState(0); const go = (dir: 1 | -1) => { setIndex((current) => { const next = current + dir; if (next < 0 || next >= data.length) return current; progress.value = withSpring(next, SPRING); onIndexChange?.(next); return next; }); }; const fling = Gesture.Race( Gesture.Fling().direction(Directions.UP).onStart(() => runOnJS(go)(1)), Gesture.Fling().direction(Directions.DOWN).onStart(() => runOnJS(go)(-1)) ); return ( {data.map((item, i) => ( {renderItem(item, i)} ))} ); } ``` ## FlexiButton - key: `flexi-button` - import: `import { FlexiButton } from "@/components/ui/flexi-button"` - description: Adaptive-width pill button that springs open to reveal a label, with a dimension-change callback - tier: 2 - deps: lucide-react-native, react-native-svg, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/flexi-button.tsx import React, { useCallback, useState } from "react"; import { Pressable, Text, type GestureResponderEvent, type LayoutChangeEvent } from "react-native"; import Animated, { useAnimatedStyle, useSharedValue, withSpring, interpolate, Extrapolation } from "react-native-reanimated"; import { Bell } from "lucide-react-native"; import { cn } from "@/lib/utils"; export interface FlexiButtonProps extends Omit, "onLayout"> { className?: string; /** Shown while collapsed; falls back to a bell glyph. Never receives className. */ icon?: React.ReactNode; label?: string; collapsedWidth?: number; expandedWidth?: number; defaultExpanded?: boolean; onExpandedChange?: (expanded: boolean) => void; onDimensionsChange?: (dimensions: { width: number; height: number; x: number; y: number }) => void; } const AnimatedPressable = Animated.createAnimatedComponent(Pressable); /** Pill button that springs between an icon-only and a labeled width on press. */ export function FlexiButton({ className, icon, label = "Clear all", collapsedWidth = 48, expandedWidth = 140, defaultExpanded = false, onExpandedChange, onDimensionsChange, onPress, ...props }: FlexiButtonProps) { const [expanded, setExpanded] = useState(defaultExpanded); const progress = useSharedValue(defaultExpanded ? 1 : 0); const handleLayout = useCallback( (e: LayoutChangeEvent) => { const { width, height, x, y } = e.nativeEvent.layout; onDimensionsChange?.({ width, height, x, y }); }, [onDimensionsChange] ); const handlePress = useCallback( (e: GestureResponderEvent) => { const next = !expanded; setExpanded(next); progress.value = withSpring(next ? 1 : 0, { damping: 16, stiffness: 180, overshootClamping: true }); onExpandedChange?.(next); onPress?.(e); }, [expanded, onExpandedChange, onPress, progress] ); const containerStyle = useAnimatedStyle(() => ({ width: interpolate(progress.value, [0, 1], [collapsedWidth, expandedWidth], Extrapolation.CLAMP), })); const iconStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.3], [1, 0], Extrapolation.CLAMP), transform: [{ scale: interpolate(progress.value, [0, 1], [1, 0.8], Extrapolation.CLAMP) }], })); const labelStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.15, 1], [0, 1], Extrapolation.CLAMP), transform: [{ scale: interpolate(progress.value, [0, 1], [0.85, 1], Extrapolation.CLAMP) }], })); return ( {icon ?? } {label} ); } ``` ## FlipCard - key: `flip-card` - import: `import { FlipCard } from "@/components/ui/flip-card"` - description: Tap-to-flip card with horizontal/vertical/depth 3D rotation, mid-flip glass blur, and haptic feedback - tier: 3 - deps: react-native-reanimated, expo-blur, expo-haptics, clsx, tailwind-merge ```tsx // components/ui/flip-card.tsx import React, { useEffect, useState } from "react"; import { Platform, Pressable, View } from "react-native"; import Animated, { Extrapolation, interpolate, useAnimatedStyle, useSharedValue, withSpring, } from "react-native-reanimated"; import { BlurView } from "expo-blur"; import * as Haptics from "expo-haptics"; import { cn } from "@/lib/utils"; const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const FLIP_SPRING = { dampingRatio: 0.72, duration: 600 } as const; const PRESS_SPRING = { damping: 18, stiffness: 320, mass: 0.5 } as const; export type FlipCardAnimation = "horizontal" | "vertical" | "depth"; /** Per-face 3D transform for a given flip mode. `offsetDeg` is 0 for the front face, 180 for the back. */ function faceTransform(mode: FlipCardAnimation, progressValue: number, offsetDeg: 0 | 180, scaleValue: number) { "worklet"; const angle = offsetDeg + progressValue * 180; const midFlipBulge = Math.sin(Math.PI * progressValue); if (mode === "vertical") { return [{ perspective: 1000 }, { rotateX: `${angle}deg` }, { scale: scaleValue }]; } if (mode === "depth") { return [ { perspective: 850 }, { translateY: -24 * midFlipBulge }, { rotateY: `${angle}deg` }, { scale: scaleValue * (1 - 0.15 * midFlipBulge) }, ]; } return [{ perspective: 1000 }, { rotateY: `${angle}deg` }, { scale: scaleValue }]; } export interface FlipCardProps extends React.ComponentPropsWithoutRef { className?: string; front: React.ReactNode; back: React.ReactNode; flipped?: boolean; onFlip?: (flipped: boolean) => void; /** 3D rotation axis used for the flip. Defaults to the classic horizontal card flip. */ animation?: FlipCardAnimation; } export function FlipCard({ className, front, back, flipped, onFlip, animation = "horizontal", ...props }: FlipCardProps) { const [internal, setInternal] = useState(false); const isFlipped = flipped ?? internal; const progress = useSharedValue(0); const scale = useSharedValue(1); useEffect(() => { progress.value = withSpring(isFlipped ? 1 : 0, FLIP_SPRING); }, [isFlipped, progress]); const frontStyle = useAnimatedStyle(() => ({ transform: faceTransform(animation, progress.value, 0, scale.value), opacity: progress.value < 0.5 ? 1 : 0, })); const backStyle = useAnimatedStyle(() => ({ transform: faceTransform(animation, progress.value, 180, scale.value), opacity: progress.value >= 0.5 ? 1 : 0, })); const edgeBlurStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.5, 1], [0, 1, 0], Extrapolation.CLAMP), })); const toggle = () => { const next = !isFlipped; if (flipped === undefined) setInternal(next); onFlip?.(next); Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); }; const onPressIn = () => { scale.value = withSpring(0.96, PRESS_SPRING); }; const onPressOut = () => { scale.value = withSpring(1, PRESS_SPRING); }; return ( {front} {Platform.OS === "ios" && ( )} {back} {Platform.OS === "ios" && ( )} ); } ``` ## Fold - key: `fold` - import: `import { Fold } from "@/components/ui/fold"` - description: useFoldFeatures() hook: iPhone Duo / Android foldable hinge state. Null-safe require of expo-hinge — returns null fields on non-fold devices and when the peer dep is absent, so consumers short-circuit back to pre-fold behavior. - tier: 3 - deps: expo-hinge ```tsx // components/ui/fold.tsx import { useEffect, useState } from "react"; import { useWindowDimensions } from "react-native"; /** * Fold-aware primitive for iPhone Duo and Android foldables. * * Returns null for every field on non-fold devices (and whenever `expo-hinge` * isn't installed), so the overlay components that consume this short-circuit * back to their pre-fold behavior with zero runtime cost. * * - `isFolded`: true when the device is closed / posture is near-closed. * false when open. null when unknown (not a foldable or dep missing). * - `foldX`: approximate x-coordinate of the fold line in window-dimension pixels. * Set only when the device is a foldable AND currently unfolded. * Overlays align themselves to one side of this value. * - `hingeAngle`: raw hinge angle in degrees (0 = closed, 180 = flat). null on * non-foldables. Exposed for consumers that want posture-reactive * behavior; the 10 fold-aware overlays don't use it directly. * - `postureHint`: coarse categorization of hingeAngle. "closed" < 15°, * "half-open" 15-150°, "flat" > 150°, null when unknown. */ export interface FoldFeatures { isFolded: boolean | null; foldX: number | null; hingeAngle: number | null; postureHint: "flat" | "half-open" | "closed" | null; } const NULL_FEATURES: FoldFeatures = { isFolded: null, foldX: null, hingeAngle: null, postureHint: null, }; // Static require with try/catch at module load — expo-hinge is a Tier 3 peer // dep, not auto-installed. If absent, every hook call returns NULL_FEATURES // without touching the module system again. let hingeModule: { useHinge?: () => { angle: number | null; isOpen: boolean | null }; getHinge?: () => { angle: number | null; isOpen: boolean | null }; addHingeListener?: ( cb: (e: { angle: number | null; isOpen: boolean | null }) => void ) => { remove: () => void }; } | null = null; try { hingeModule = require("expo-hinge"); } catch { hingeModule = null; } function hintFromAngle(angle: number | null): FoldFeatures["postureHint"] { if (angle == null) return null; if (angle < 15) return "closed"; if (angle > 150) return "flat"; return "half-open"; } export function useFoldFeatures(): FoldFeatures { const { width } = useWindowDimensions(); const [state, setState] = useState<{ angle: number | null; isOpen: boolean | null }>(() => { if (!hingeModule?.getHinge) return { angle: null, isOpen: null }; try { return hingeModule.getHinge(); } catch { return { angle: null, isOpen: null }; } }); useEffect(() => { if (!hingeModule?.addHingeListener) return; const sub = hingeModule.addHingeListener((e) => setState(e)); return () => sub.remove(); }, []); if (!hingeModule) return NULL_FEATURES; const { angle, isOpen } = state; if (angle == null && isOpen == null) return NULL_FEATURES; const folded = isOpen == null ? null : !isOpen; // Only expose foldX when the device is a foldable AND currently unfolded. // Fold line sits at the midpoint of the window — Apple's reserved region is // a thin strip there; aligning to width/2 is accurate enough for overlays. const foldX = isOpen === true ? width / 2 : null; return { isFolded: folded, foldX, hingeAngle: angle, postureHint: hintFromAngle(angle) }; } ``` ## Form - key: `form` - import: `import { Form } from "@/components/ui/form"` - description: Form context with validation, error handling, and compound components - tier: 1 - deps: clsx, tailwind-merge - aniui deps: label, text ```tsx // components/ui/form.tsx import React, { createContext, useContext, useState, useCallback } from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; type FieldError = string | undefined; type Validator = (value: string) => FieldError; type FormErrors = Record; const FormContext = createContext<{ errors: FormErrors; setFieldError: (field: string, error: FieldError) => void; validateField: (field: string, value: string, rules?: FieldRules) => boolean; }>({ errors: {}, setFieldError: () => {}, validateField: () => true }); const FormFieldContext = createContext<{ name: string; error: FieldError }>({ name: "", error: undefined, }); export type FieldRules = { required?: string | boolean; pattern?: { value: RegExp; message: string }; validate?: Validator; }; export interface FormProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function Form({ className, children, ...props }: FormProps) { const [errors, setErrors] = useState({}); const setFieldError = useCallback((field: string, error: FieldError) => { setErrors((prev) => ({ ...prev, [field]: error })); }, []); const validateField = useCallback( (field: string, value: string, rules?: FieldRules): boolean => { if (!rules) return true; if (rules.required && !value.trim()) { const msg = typeof rules.required === "string" ? rules.required : "This field is required"; setErrors((prev) => ({ ...prev, [field]: msg })); return false; } if (rules.pattern && !rules.pattern.value.test(value)) { setErrors((prev) => ({ ...prev, [field]: rules.pattern!.message })); return false; } if (rules.validate) { const error = rules.validate(value); setErrors((prev) => ({ ...prev, [field]: error })); return !error; } setErrors((prev) => ({ ...prev, [field]: undefined })); return true; }, [] ); return ( {children} ); } export function useFormField() { const form = useContext(FormContext); const field = useContext(FormFieldContext); return { ...field, ...form }; } export interface FormFieldProps { name: string; children: React.ReactNode; } export function FormField({ name, children }: FormFieldProps) { const { errors } = useContext(FormContext); return ( {children} ); } export interface FormItemProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function FormItem({ className, children, ...props }: FormItemProps) { return {children}; } export function FormMessage({ className, ...props }: { className?: string }) { const { error } = useContext(FormFieldContext); if (!error) return null; return ( {error} ); } ``` ## GooeyPopover - key: `gooey-popover` - import: `import { GooeyPopover } from "@/components/ui/gooey-popover"` - description: Skia gooey popover that morphs its trigger into the content panel - tier: 4 - deps: @shopify/react-native-skia, react-native-reanimated, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/gooey-popover.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { Dimensions, Pressable, Text, View, useWindowDimensions, type LayoutChangeEvent, type View as RNView } from "react-native"; import { Blur, Canvas, ColorMatrix, Group, Paint, RoundedRect } from "@shopify/react-native-skia"; import Animated, { interpolate, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; type GooeyPopoverSide = "top" | "bottom"; type GooeyPopoverAlign = "start" | "center" | "end"; type GooeyPopoverRect = { x: number; y: number; w: number; h: number; r: number }; type GooeyPopoverGeo = { layerW: number; layerH: number; left: number; top: number; trigger: GooeyPopoverRect; panel: GooeyPopoverRect; }; const OPEN_SPRING: WithSpringConfig = { stiffness: 115, damping: 18, mass: 0.4 }; const CLOSE_SPRING: WithSpringConfig = { stiffness: 115, damping: 18, mass: 0.4 }; const PRESS_IN_SPRING: WithSpringConfig = { stiffness: 400, damping: 26, mass: 0.5 }; const PRESS_OUT_SPRING: WithSpringConfig = { stiffness: 260, damping: 16, mass: 0.5 }; // Same alpha-threshold trick used elsewhere in this family: blur two shapes, then // sharpen alpha so they fuse into a single blob while they overlap. const GOO_MATRIX = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 22, -11]; type GooeyPopoverClamp = { screenW: number; triggerWinX: number; margin: number }; function buildGeo( triggerW: number, triggerH: number, panelW: number, panelH: number, side: GooeyPopoverSide, align: GooeyPopoverAlign, gap: number, panelRadius: number, clamp: GooeyPopoverClamp | null, ): GooeyPopoverGeo { const py = side === "bottom" ? triggerH + gap : -(gap + panelH); const idealPx = align === "start" ? 0 : align === "end" ? triggerW - panelW : (triggerW - panelW) / 2; // A wide (e.g. two-line) panel centered under a narrow trigger can overhang // past the screen edge. Once we know the trigger's actual on-screen X (via // measureInWindow, set once GooeyPopoverTrigger has laid out), slide the // panel back on-screen — same clamp shape as unfold-menu's clampToScreen. let px = idealPx; if (clamp) { const { screenW, triggerWinX, margin } = clamp; const minPx = margin - triggerWinX; const maxPx = screenW - margin - panelW - triggerWinX; px = Math.min(Math.max(idealPx, minPx), Math.max(maxPx, minPx)); } const left = Math.min(0, px); const top = Math.min(0, py); const layerW = Math.max(triggerW, px + panelW) - left; const layerH = Math.max(triggerH, py + panelH) - top; const triggerRadius = Math.min(triggerH / 2, panelRadius); return { layerW, layerH, left, top, trigger: { x: -left, y: -top, w: triggerW, h: triggerH, r: triggerRadius }, panel: { x: px - left, y: py - top, w: panelW, h: panelH, r: panelRadius }, }; } function rectAt(geo: GooeyPopoverGeo, p: number): GooeyPopoverRect { "worklet"; const t = geo.trigger; const panel = geo.panel; const lerp = (a: number, b: number) => a + (b - a) * p; return { x: lerp(t.x, panel.x), y: lerp(t.y, panel.y), w: lerp(t.w, panel.w), h: lerp(t.h, panel.h), r: lerp(t.r, panel.r) }; } type GooeyPopoverContextValue = { open: boolean; setOpen: (open: boolean) => void; toggle: () => void; progress: SharedValue; side: GooeyPopoverSide; align: GooeyPopoverAlign; gap: number; panelRadius: number; gooStrength: number; color: string; dismissOnOutsidePress: boolean; triggerSize: { w: number; h: number }; setTriggerSize: React.Dispatch>; triggerScale: SharedValue; triggerWindowPos: { x: number; y: number } | null; setTriggerWindowPos: React.Dispatch>; }; const GooeyPopoverContext = createContext(null); function useGooeyPopoverContext(component: string) { const ctx = useContext(GooeyPopoverContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } export interface GooeyPopoverProps { children: React.ReactNode; className?: string; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; side?: GooeyPopoverSide; align?: GooeyPopoverAlign; sideOffset?: number; panelRadius?: number; gooStrength?: number; /** Goo layer fill — the Skia canvas can't read className tokens, so this * defaults to the theme's resolved card color (via useThemeColors(), light * `#ffffff` / dark `#09090b`) and only needs overriding for a non-card surface. */ color?: string; dismissOnOutsidePress?: boolean; } /** Root: holds open/progress state and the trigger's measured size so * GooeyPopoverContent can compute where the panel should blob out from. */ export function GooeyPopover({ children, className, open: controlledOpen, defaultOpen = false, onOpenChange, side = "bottom", align = "center", sideOffset = 14, panelRadius = 16, gooStrength = 8, color, dismissOnOutsidePress = true, }: GooeyPopoverProps) { const colors = useThemeColors(); const resolvedColor = color ?? colors.card; const isControlled = controlledOpen !== undefined; const [uncontrolled, setUncontrolled] = useState(defaultOpen); const open = isControlled ? controlledOpen : uncontrolled; const progress = useSharedValue(defaultOpen ? 1 : 0); const triggerScale = useSharedValue(1); const [triggerSize, setTriggerSize] = useState({ w: 0, h: 0 }); const [triggerWindowPos, setTriggerWindowPos] = useState<{ x: number; y: number } | null>(null); const setOpen = useCallback( (next: boolean) => { if (!isControlled) setUncontrolled(next); onOpenChange?.(next); }, [isControlled, onOpenChange], ); const toggle = useCallback(() => setOpen(!open), [open, setOpen]); useEffect(() => { progress.value = withSpring(open ? 1 : 0, open ? OPEN_SPRING : CLOSE_SPRING); }, [open, progress]); const ctx = useMemo( () => ({ open, setOpen, toggle, progress, side, align, gap: sideOffset, panelRadius, gooStrength, color: resolvedColor, dismissOnOutsidePress, triggerSize, setTriggerSize, triggerScale, triggerWindowPos, setTriggerWindowPos }), [open, setOpen, toggle, progress, side, align, sideOffset, panelRadius, gooStrength, resolvedColor, dismissOnOutsidePress, triggerSize, triggerScale, triggerWindowPos], ); const { width: screenW, height: screenH } = Dimensions.get("window"); return ( {open && dismissOnOutsidePress ? ( setOpen(false)} style={{ position: "absolute", left: -screenW, top: -screenH, width: screenW * 2, height: screenH * 2, zIndex: 5 }} /> ) : null} {children} ); } export interface GooeyPopoverTriggerProps extends React.ComponentPropsWithoutRef { className?: string; pressScale?: number; } export function GooeyPopoverTrigger({ children, className, pressScale = 0.94, ...props }: GooeyPopoverTriggerProps) { const { toggle, open, setTriggerSize, triggerScale, setTriggerWindowPos } = useGooeyPopoverContext("GooeyPopoverTrigger"); const triggerRef = useRef(null); const onLayout = useCallback( (e: LayoutChangeEvent) => { const { width, height } = e.nativeEvent.layout; setTriggerSize((prev: { w: number; h: number }) => (prev.w === width && prev.h === height ? prev : { w: width, h: height })); // Needed to clamp a wide (e.g. two-line) panel back on-screen — the local // layout above has no idea where this trigger actually sits on the device. triggerRef.current?.measureInWindow((x, y) => { setTriggerWindowPos((prev) => (prev && prev.x === x && prev.y === y ? prev : { x, y })); }); }, [setTriggerSize, setTriggerWindowPos], ); const pressStyle = useAnimatedStyle(() => ({ transform: [{ scale: triggerScale.value }] })); // GooeyPopoverContent's backdrop Canvas sits at zIndex 0 and is a later sibling // of this trigger — a tied zIndex falls back to sibling order, which would let // the canvas's goo blob paint over (and fully hide) this real button. zIndex 1 // keeps the trigger above the canvas while staying below the open panel's // content overlay (zIndex 10). return ( { triggerScale.value = withSpring(pressScale, PRESS_IN_SPRING); }} onPressOut={() => { triggerScale.value = withSpring(1, PRESS_OUT_SPRING); }} accessible={true} accessibilityRole="button" accessibilityState={{ expanded: open }} className={cn("min-h-12 min-w-12 items-center justify-center rounded-full bg-primary px-4", className)} {...props} > {typeof children === "string" ? {children} : children} ); } export interface GooeyPopoverContentProps { children: React.ReactNode; className?: string; } /** Content: measures its own natural size off-screen, then animates a clip * window (borderRadius + bounds) from the trigger's rect to the panel's rect * while a Skia goo layer blends trigger + panel shapes underneath. */ export function GooeyPopoverContent({ children, className }: GooeyPopoverContentProps) { const { progress, side, align, gap, panelRadius, gooStrength, color, open, triggerSize, triggerScale, triggerWindowPos } = useGooeyPopoverContext("GooeyPopoverContent"); const { width: screenW } = useWindowDimensions(); const [contentSize, setContentSize] = useState({ w: 0, h: 0 }); const onMeasure = useCallback((e: LayoutChangeEvent) => { const { width, height } = e.nativeEvent.layout; setContentSize((prev) => (prev.w === width && prev.h === height ? prev : { w: width, h: height })); }, []); const clamp = useMemo( () => (triggerWindowPos ? { screenW, triggerWinX: triggerWindowPos.x, margin: 12 } : null), [screenW, triggerWindowPos], ); const geo = useMemo( () => buildGeo(triggerSize.w, triggerSize.h, contentSize.w, contentSize.h, side, align, gap, panelRadius, clamp), [triggerSize, contentSize, side, align, gap, panelRadius, clamp], ); const ready = geo.layerW > 0 && contentSize.w > 0; const rect = useDerivedValue(() => rectAt(geo, progress.value), [geo]); const rx = useDerivedValue(() => rect.value.x); const ry = useDerivedValue(() => rect.value.y); const rw = useDerivedValue(() => rect.value.w); const rh = useDerivedValue(() => rect.value.h); const rr = useDerivedValue(() => rect.value.r); const cx = geo.trigger.x + geo.trigger.w / 2; const cy = geo.trigger.y + geo.trigger.h / 2; const tx = useDerivedValue(() => cx - (geo.trigger.w * triggerScale.value) / 2, [geo]); const ty = useDerivedValue(() => cy - (geo.trigger.h * triggerScale.value) / 2, [geo]); const tw = useDerivedValue(() => geo.trigger.w * triggerScale.value, [geo]); const th = useDerivedValue(() => geo.trigger.h * triggerScale.value, [geo]); const tr = useDerivedValue(() => geo.trigger.r * triggerScale.value, [geo]); const clipStyle = useAnimatedStyle(() => { const m = rectAt(geo, progress.value); // Border fades in with the content below — at progress 0 this exactly // matches the trigger's own rounded-pill shape, and without fading it out // it would sit drawn on top of the trigger even while fully closed. return { left: m.x, top: m.y, width: m.w, height: m.h, borderRadius: m.r, opacity: interpolate(progress.value, [0, 0.45, 1], [0, 0.2, 1]) }; }, [geo]); const contentStyle = useAnimatedStyle(() => { const m = rectAt(geo, progress.value); return { left: geo.panel.x - m.x, top: geo.panel.y - m.y }; }, [geo]); return ( <> {children} {ready ? ( } > ) : null} {children} ); } ``` ## GooeySearchTabs - key: `gooey-search-tabs` - import: `import { GooeySearchTabs } from "@/components/ui/gooey-search-tabs"` - description: Skia gooey pill that morphs between a search bar and a tab switcher - tier: 4 - deps: @shopify/react-native-skia, react-native-reanimated, lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/gooey-search-tabs.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; import { Pressable, Text, TextInput, View, type LayoutChangeEvent } from "react-native"; import { Blur, Canvas, ColorMatrix, Group, Paint, RoundedRect } from "@shopify/react-native-skia"; import Animated, { Extrapolation, interpolate, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { Search, X } from "lucide-react-native"; import { cn } from "@/lib/utils"; const HEIGHT = 46; const PAD_V = 8; const CLOSE_W = HEIGHT; const ICON_SIZE = 18; const DEFAULT_SPRING: WithSpringConfig = { damping: 18, stiffness: 200, mass: 0.9 }; // Same alpha-threshold metaball trick used elsewhere in this family — // blur two capsules then sharpen alpha so they read as one continuous pill // while they overlap, without needing an SkSL shader for a smooth-min blend. const GOO_MATRIX = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 22, -11]; type TabLayout = { x: number; width: number }; type GooeySearchTabsContextValue = { progress: SharedValue; expanded: boolean; expand: () => void; collapse: () => void; toggle: () => void; value: string; setValue: (v: string) => void; activeTab: string; selectTab: (v: string) => void; registerTab: (value: string) => void; unregisterTab: (value: string) => void; reportLayout: (value: string, layout: TabLayout) => void; layouts: Record; tabsW: number; setTabsWidth: (w: number) => void; springConfig: WithSpringConfig; }; const GooeySearchTabsContext = createContext(null); const TabContext = createContext<{ value: string; active: boolean } | null>(null); function useGooeySearchTabsContext(component: string) { const ctx = useContext(GooeySearchTabsContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } function useTabContext(component: string) { const ctx = useContext(TabContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } export interface GooeySearchTabsProps { children: React.ReactNode; className?: string; value?: string; defaultValue?: string; onChange?: (value: string) => void; onSearch?: (value: string) => void; activeTab?: string; defaultActiveTab?: string; onTabChange?: (value: string) => void; placeholder?: string; springConfig?: WithSpringConfig; color?: string; } /** Root: a Skia goo layer draws two capsules — a left one that grows from an * icon-sized cap into the search input's width, and a right one that shrinks * from the tabs row into the close button — so the whole bar reads as one * continuously merged pill as it morphs between search and tabs mode. */ export function GooeySearchTabs({ children, className, value: controlledValue, defaultValue = "", onChange, onSearch, activeTab: controlledActiveTab, defaultActiveTab, onTabChange, placeholder = "Search", springConfig = DEFAULT_SPRING, color = "#ffffff", }: GooeySearchTabsProps) { const progress = useSharedValue(0); const [expanded, setExpanded] = useState(false); const [internalValue, setInternalValue] = useState(defaultValue); const [order, setOrder] = useState([]); const [internalActive, setInternalActive] = useState(defaultActiveTab ?? ""); const [tabsW, setTabsW] = useState(0); const [layouts, setLayouts] = useState>({}); const inputRef = useRef(null); const value = controlledValue ?? internalValue; const activeTab = controlledActiveTab ?? internalActive ?? order[0] ?? ""; const registerTab = useCallback((v: string) => { setOrder((prev) => (prev.includes(v) ? prev : [...prev, v])); }, []); const unregisterTab = useCallback((v: string) => { setOrder((prev) => prev.filter((x) => x !== v)); setLayouts((prev) => { if (!(v in prev)) return prev; const next = { ...prev }; delete next[v]; return next; }); }, []); const reportLayout = useCallback((v: string, layout: TabLayout) => { setLayouts((prev) => (prev[v]?.x === layout.x && prev[v]?.width === layout.width ? prev : { ...prev, [v]: layout })); }, []); const setTabsWidth = useCallback((w: number) => setTabsW((prev) => (prev === w ? prev : w)), []); useEffect(() => { if (!internalActive && order.length > 0) setInternalActive(order[0]); }, [order, internalActive]); const expand = useCallback(() => { setExpanded(true); progress.value = withSpring(1, springConfig); requestAnimationFrame(() => inputRef.current?.focus()); }, [progress, springConfig]); const collapse = useCallback(() => { setExpanded(false); progress.value = withSpring(0, springConfig); if (controlledValue === undefined) setInternalValue(""); inputRef.current?.blur(); }, [controlledValue, progress, springConfig]); const toggle = useCallback(() => (expanded ? collapse() : expand()), [expanded, expand, collapse]); const setValue = useCallback( (v: string) => { if (controlledValue === undefined) setInternalValue(v); onChange?.(v); }, [controlledValue, onChange], ); const selectTab = useCallback( (v: string) => { if (controlledActiveTab === undefined) setInternalActive(v); onTabChange?.(v); }, [controlledActiveTab, onTabChange], ); const ctx = useMemo( () => ({ progress, expanded, expand, collapse, toggle, value, setValue, activeTab, selectTab, registerTab, unregisterTab, reportLayout, layouts, tabsW, setTabsWidth, springConfig }), [progress, expanded, expand, collapse, toggle, value, setValue, activeTab, selectTab, registerTab, unregisterTab, reportLayout, layouts, tabsW, setTabsWidth, springConfig], ); const total = HEIGHT + tabsW; const leftX = useSharedValue(0); const leftW = useDerivedValue(() => HEIGHT + (tabsW - HEIGHT) * progress.value, [tabsW]); const rightW = useDerivedValue(() => tabsW + (CLOSE_W - tabsW) * progress.value, [tabsW]); const rightX = useDerivedValue(() => total - rightW.value, [total]); const inputStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.35, 0.9], [0, 1], Extrapolation.CLAMP), transform: [{ translateX: interpolate(progress.value, [0, 1], [-10, 0], Extrapolation.CLAMP) }], })); const closeStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.55, 1], [0, 1], Extrapolation.CLAMP), transform: [{ scale: interpolate(progress.value, [0.5, 1], [0.6, 1], Extrapolation.CLAMP) }], })); return ( {tabsW > 0 ? ( }> ) : null} {children} onSearch?.(value)} returnKeyType="search" /> ); } export interface GooeySearchTabsTriggerProps extends React.ComponentPropsWithoutRef { className?: string; } export function GooeySearchTabsTrigger({ children, className, ...props }: GooeySearchTabsTriggerProps) { const { expanded, expand } = useGooeySearchTabsContext("GooeySearchTabsTrigger"); return ( {children ?? } ); } export interface GooeySearchTabsTabsProps { children: React.ReactNode; className?: string; } export function GooeySearchTabsTabs({ children, className }: GooeySearchTabsTabsProps) { const { progress, expanded, activeTab, layouts, setTabsWidth, springConfig } = useGooeySearchTabsContext("GooeySearchTabsTabs"); const idxX = useSharedValue(0); const idxW = useSharedValue(0); useEffect(() => { const l = layouts[activeTab]; if (!l) return; const immediate = idxW.value === 0; idxX.value = immediate ? l.x : withSpring(l.x, springConfig); idxW.value = immediate ? l.width : withSpring(l.width, springConfig); }, [activeTab, layouts, springConfig, idxX, idxW]); const rowStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.45], [1, 0], Extrapolation.CLAMP) })); const indicatorStyle = useAnimatedStyle(() => ({ transform: [{ translateX: idxX.value }], width: idxW.value })); return ( setTabsWidth(e.nativeEvent.layout.width)} > {children} ); } export interface GooeySearchTabsTabProps { value: string; children: React.ReactNode; onPress?: (value: string) => void; className?: string; } export function GooeySearchTabsTab({ value, children, onPress, className }: GooeySearchTabsTabProps) { const { activeTab, selectTab, registerTab, unregisterTab, reportLayout } = useGooeySearchTabsContext("GooeySearchTabsTab"); useEffect(() => { registerTab(value); return () => unregisterTab(value); }, [value, registerTab, unregisterTab]); const active = value === activeTab; const tabCtx = useMemo(() => ({ value, active }), [value, active]); return ( { selectTab(value); onPress?.(value); }} onLayout={(e: LayoutChangeEvent) => reportLayout(value, { x: e.nativeEvent.layout.x, width: e.nativeEvent.layout.width })} accessible={true} accessibilityRole="tab" accessibilityState={{ selected: active }} className={cn("min-h-12 flex-row items-center gap-1.5 px-8", className)} > {children} ); } export interface GooeySearchTabsTabIconProps { children: React.ReactNode; className?: string; } export function GooeySearchTabsTabIcon({ children, className }: GooeySearchTabsTabIconProps) { const { active } = useTabContext("GooeySearchTabsTabIcon"); return {children}; } export interface GooeySearchTabsTabLabelProps { children: React.ReactNode; className?: string; } export function GooeySearchTabsTabLabel({ children, className }: GooeySearchTabsTabLabelProps) { const { active } = useTabContext("GooeySearchTabsTabLabel"); return ( {children} ); } ``` ## Gradient - key: `gradient` - import: `import { Gradient } from "@/components/ui/gradient"` - description: Linear gradient view with configurable colors and direction - tier: 3 - deps: react-native-svg, clsx, tailwind-merge ```tsx // components/ui/gradient.tsx import React from "react"; import { View } from "react-native"; import Svg, { Defs, LinearGradient as SvgLinearGradient, Stop, Rect } from "react-native-svg"; import { cn } from "@/lib/utils"; export interface GradientPoint { x: number; y: number; } export interface GradientProps extends React.ComponentPropsWithoutRef { className?: string; colors?: string[]; start?: GradientPoint; end?: GradientPoint; children?: React.ReactNode; } export function Gradient({ colors = ["#18181b", "#3f3f46"], start = { x: 0, y: 0 }, end = { x: 0, y: 1 }, className, children, ...props }: GradientProps) { // useId output contains ":" which is unsafe inside url(#...) references. const id = `grad-${React.useId().replace(/[^a-zA-Z0-9]/g, "")}`; return ( {colors.map((color, i) => ( ))} {children} ); } ``` ## Grid - key: `grid` - import: `import { Grid } from "@/components/ui/grid"` - description: FlatList-based grid layout with configurable columns and gap - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/grid.tsx import React from "react"; import { FlatList, View } from "react-native"; import { cn } from "@/lib/utils"; export interface GridProps extends Omit>, "numColumns"> { className?: string; columns?: number; gap?: number; data: T[]; renderItem: ({ item, index }: { item: T; index: number }) => React.ReactElement; keyExtractor: (item: T, index: number) => string; } export function Grid({ className, columns = 2, gap = 8, data, renderItem, keyExtractor, ...props }: GridProps) { return ( 1 ? { gap } : undefined} contentContainerStyle={{ gap }} renderItem={({ item, index }) => ( {renderItem({ item, index })} )} {...props} /> ); } ``` ## Hamburger - key: `hamburger` - import: `import { Hamburger } from "@/components/ui/hamburger"` - description: Animated hamburger ⇄ close icon morph driven by a single progress value - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/hamburger.tsx import React, { useEffect } from "react"; import { Pressable } from "react-native"; import Animated, { Easing, interpolate, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface HamburgerProps extends Omit, "onPress"> { className?: string; /** Fully controlled, like AniUI's Toggle. */ open?: boolean; onOpenChange?: (open: boolean) => void; size?: number; color?: string; } /** Animated hamburger <-> close icon morph — three bars rearranging into an X. */ export function Hamburger({ className, open = false, onOpenChange, size = 28, color, ...props }: HamburgerProps) { const colors = useThemeColors(); const tint = color ?? colors.foreground; const progress = useSharedValue(open ? 1 : 0); useEffect(() => { progress.value = withTiming(open ? 1 : 0, { duration: 280, easing: Easing.inOut(Easing.quad) }); }, [open, progress]); const lineWidth = size * 0.72; const strokeWidth = Math.max(2, size * 0.08); const gap = size * 0.26; const lineStyle = { width: lineWidth, height: strokeWidth, backgroundColor: tint }; const topStyle = useAnimatedStyle(() => ({ transform: [ { translateY: interpolate(progress.value, [0, 1], [-gap, 0]) }, { rotate: `${interpolate(progress.value, [0, 1], [0, 45])}deg` }, ], })); const middleStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.6, 1], [1, 0, 0]), transform: [{ scale: interpolate(progress.value, [0, 1], [1, 0]) }], })); const bottomStyle = useAnimatedStyle(() => ({ transform: [ { translateY: interpolate(progress.value, [0, 1], [gap, 0]) }, { rotate: `${interpolate(progress.value, [0, 1], [0, -45])}deg` }, ], })); return ( onOpenChange?.(!open)} accessibilityRole="button" accessibilityState={{ expanded: open }} accessibilityLabel={open ? "Close menu" : "Open menu"} accessible={true} className={cn("min-h-12 min-w-12 items-center justify-center", className)} style={{ width: size, height: size }} {...props} > ); } ``` ## Header - key: `header` - import: `import { Header } from "@/components/ui/header"` - description: Navigation header with back button, title, and right actions - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/header.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { ArrowLeft } from "lucide-react-native"; const headerVariants = cva("flex-row items-center min-h-14 px-4", { variants: { variant: { default: "bg-background border-b border-border", transparent: "bg-transparent", primary: "bg-primary", }, }, defaultVariants: { variant: "default" }, }); export interface HeaderProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; children?: React.ReactNode; } export function Header({ variant, className, children, ...props }: HeaderProps) { return ( {children} ); } export interface HeaderLeftProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function HeaderLeft({ className, children, ...props }: HeaderLeftProps) { return {children}; } export interface HeaderTitleProps extends React.ComponentPropsWithoutRef { className?: string; } export function HeaderTitle({ className, ...props }: HeaderTitleProps) { return ( ); } export interface HeaderRightProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function HeaderRight({ className, children, ...props }: HeaderRightProps) { return {children}; } export interface HeaderBackButtonProps extends React.ComponentPropsWithoutRef { className?: string; label?: React.ReactNode; onPress: () => void; } export function HeaderBackButton({ className, label, onPress, ...props }: HeaderBackButtonProps) { const colors = useThemeColors(); return ( {label === undefined ? ( ) : typeof label === "string" || typeof label === "number" ? ( {label} ) : ( label )} ); } ``` ## HoverCard - key: `hover-card` - import: `import { HoverCard } from "@/components/ui/hover-card"` - description: Preview content card triggered by hover or long-press - tier: 3 - deps: @rn-primitives/hover-card, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/hover-card.tsx import React from "react"; import { View, Pressable } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import * as HoverCardPrimitive from "@rn-primitives/hover-card"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; export interface HoverCardProps { children: React.ReactNode; onOpenChange?: (open: boolean) => void; openDelay?: number; closeDelay?: number; } // @rn-primitives' HoverCard Root is uncontrolled — see context-menu.tsx. export function HoverCard({ children, onOpenChange, openDelay, closeDelay }: HoverCardProps) { return ( {children} ); } export interface HoverCardTriggerProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function HoverCardTrigger({ className, children, ...props }: HoverCardTriggerProps) { return ( {/* rn-primitives measures this exact box to position HoverCardContent below it — min-h-12/min-w-12 would force a 48x48 measured box even for a small icon child, opening the content ~48px below the trigger's top edge instead of just past the icon. hitSlop expands the tappable area to the 48dp minimum without inflating what gets measured. */} {children} ); } export interface HoverCardContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; // Primitive only supports vertical sides. side?: "top" | "bottom"; sideOffset?: number; align?: "start" | "center" | "end"; } export function HoverCardContent({ className, children, side = "bottom", sideOffset = 8, align = "center", ...props }: HoverCardContentProps) { const insets = useSafeAreaInsets(); const fold = useFoldFeatures(); // See popover.tsx for the pattern — treat the fold line as a horizontal // inset so the content stays within one pane on an unfolded Duo. const foldInsets = fold.foldX ? { ...insets, left: Math.max(insets.left, fold.foldX), right: Math.max(insets.right, fold.foldX) } : insets; return ( {children} ); } ``` ## Image - key: `image` - import: `import { Image } from "@/components/ui/image"` - description: Image with loading placeholder, error fallback, and rounded variants - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/image.tsx import React, { useState } from "react"; import { Image as RNImage, View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const imageVariants = cva("overflow-hidden bg-muted", { variants: { rounded: { none: "", sm: "rounded-sm", md: "rounded-md", lg: "rounded-lg", xl: "rounded-xl", full: "rounded-full", }, }, defaultVariants: { rounded: "md" }, }); export interface ImageProps extends Omit, "source">, VariantProps { className?: string; src: string; alt?: string; width?: number; height?: number; fallback?: React.ReactNode; } export function Image({ rounded, className, src, alt, width, height, fallback, style, ...props }: ImageProps) { const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading"); return ( {status === "loading" && ( )} {status === "error" ? ( fallback ?? ( Failed to load ) ) : ( setStatus("loaded")} onError={() => setStatus("error")} {...props} /> )} ); } ``` ## ImageGallery - key: `image-gallery` - import: `import { ImageGallery } from "@/components/ui/image-gallery"` - description: Horizontal image carousel with fullscreen modal and pagination - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: image ```tsx // components/ui/image-gallery.tsx import React, { useRef, useState } from "react"; import { View, FlatList, Image, Pressable, Modal, useWindowDimensions } from "react-native"; import { X } from "lucide-react-native"; import { cn } from "@/lib/utils"; export interface GalleryImage { uri: string; alt?: string; } export interface ImageGalleryProps extends React.ComponentPropsWithoutRef { className?: string; images: GalleryImage[]; showPagination?: boolean; } export function ImageGallery({ className, images, showPagination = true, onLayout, ...props }: ImageGalleryProps) { const [activeIndex, setActiveIndex] = useState(0); const [fullscreen, setFullscreen] = useState(false); // Size slides to the gallery's OWN measured width (survives rotation / // split-screen); the fullscreen modal uses the live window width instead. const [width, setWidth] = useState(0); const { width: windowWidth } = useWindowDimensions(); const listRef = useRef(null); return ( { setWidth(e.nativeEvent.layout.width); onLayout?.(e); }} {...props} > {width > 0 && ( String(i)} onMomentumScrollEnd={(e) => { setActiveIndex(Math.round(e.nativeEvent.contentOffset.x / width)); }} renderItem={({ item, index }) => ( setFullscreen(true)} accessibilityRole="image" accessibilityLabel={item.alt ?? `Image ${index + 1}`} > )} /> )} {showPagination && images.length > 1 && ( {images.map((_, i) => ( ))} )} setFullscreen(false)}> setFullscreen(false)} className="absolute top-14 end-4 z-10 min-h-12 min-w-12 items-center justify-center" accessibilityRole="button" accessibilityLabel="Close" > ); } ``` ## InfiniteList - key: `infinite-list` - import: `import { InfiniteList } from "@/components/ui/infinite-list"` - description: FlatList with auto-loading more items on scroll - tier: 1 - deps: clsx, tailwind-merge - aniui deps: spinner, theme-provider ```tsx // components/ui/infinite-list.tsx import React from "react"; import { FlatList, View, ActivityIndicator } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface InfiniteListProps extends React.ComponentPropsWithoutRef> { className?: string; data: T[]; renderItem: ({ item, index }: { item: T; index: number }) => React.ReactElement; keyExtractor: (item: T, index: number) => string; onLoadMore?: () => void; hasMore?: boolean; loading?: boolean; threshold?: number; } export function InfiniteList({ className, data, renderItem, keyExtractor, onLoadMore, hasMore = false, loading = false, threshold = 0.5, ...props }: InfiniteListProps) { const colors = useThemeColors(); return ( ) : null } {...props} /> ); } ``` ## Input - key: `input` - import: `import { Input } from "@/components/ui/input"` - description: Text input with variants and states - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/input.tsx import React from "react"; import { View, TextInput, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; // Padding lives on the wrapping View, never on the raw TextInput — a TextInput // doesn't honor `px-*` reliably, so keeping padding on the View gives a // consistent inset with or without icons, under both NativeWind and Uniwind. const inputVariants = cva( "flex-row items-center rounded-md border py-2", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-3", md: "min-h-12 px-4", lg: "min-h-14 px-5", }, }, defaultVariants: { variant: "default", size: "md", }, } ); const fontSizes = { sm: 14, md: 16, lg: 18 } as const; export interface InputProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; leadingIcon?: React.ReactNode; trailingIcon?: React.ReactNode; } export const Input = React.forwardRef< React.ElementRef, InputProps >(function Input( { variant, size, className, leadingIcon, trailingIcon, style, ...props }, ref ) { const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; const resolvedSize = size ?? "md"; return ( {leadingIcon && {leadingIcon}} {trailingIcon && {trailingIcon}} ); }); ``` ## InputGroup - key: `input-group` - import: `import { InputGroup } from "@/components/ui/input-group"` - description: Compose inputs with addons, buttons, text, and focus-aware container - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/input-group.tsx import React, { createContext, useContext, useState, useCallback } from "react"; import { View, Text, TextInput, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; // Focus context — container shows ring when child input is focused const FocusCtx = createContext<{ focused: boolean; setFocused: (v: boolean) => void }>({ focused: false, setFocused: () => {}, }); export interface InputGroupProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function InputGroup({ className, children, ...props }: InputGroupProps) { const [focused, setFocused] = useState(false); return ( {children} ); } export interface InputGroupAddonProps extends React.ComponentPropsWithoutRef { className?: string; align?: "start" | "end"; children?: React.ReactNode; } export function InputGroupAddon({ className, align = "start", children, ...props }: InputGroupAddonProps) { return ( {children} ); } export interface InputGroupInputProps extends React.ComponentPropsWithoutRef { className?: string; } export function InputGroupInput({ className, onFocus, onBlur, ...props }: InputGroupInputProps) { const { setFocused } = useContext(FocusCtx); const colors = useThemeColors(); const handleFocus = useCallback((e: Parameters>[0]) => { setFocused(true); onFocus?.(e); }, [setFocused, onFocus]); const handleBlur = useCallback((e: Parameters>[0]) => { setFocused(false); onBlur?.(e); }, [setFocused, onBlur]); return ( ); } export interface InputGroupTextareaProps extends React.ComponentPropsWithoutRef { className?: string; } export function InputGroupTextarea({ className, onFocus, onBlur, ...props }: InputGroupTextareaProps) { const { setFocused } = useContext(FocusCtx); const colors = useThemeColors(); const handleFocus = useCallback((e: Parameters>[0]) => { setFocused(true); onFocus?.(e); }, [setFocused, onFocus]); const handleBlur = useCallback((e: Parameters>[0]) => { setFocused(false); onBlur?.(e); }, [setFocused, onBlur]); return ( ); } const buttonVariants = cva("items-center justify-center active:opacity-70", { variants: { size: { xs: "px-2.5 min-h-8", sm: "px-3 min-h-10", "icon-xs": "h-8 w-8", "icon-sm": "h-10 w-10", }, variant: { ghost: "bg-transparent", default: "bg-primary rounded-md", secondary: "bg-secondary rounded-md", outline: "border border-input rounded-md", }, }, defaultVariants: { size: "xs", variant: "ghost" }, }); const buttonTextVariants = cva("text-xs font-medium", { variants: { variant: { ghost: "text-muted-foreground", default: "text-primary-foreground", secondary: "text-secondary-foreground", outline: "text-foreground", }, }, defaultVariants: { variant: "ghost" }, }); export interface InputGroupButtonProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; textClassName?: string; children?: React.ReactNode; } export function InputGroupButton({ className, textClassName, size, variant, children, ...props }: InputGroupButtonProps) { return ( {typeof children === "string" ? ( {children} ) : ( children )} ); } export interface InputGroupTextProps extends React.ComponentPropsWithoutRef { className?: string; } export function InputGroupText({ className, ...props }: InputGroupTextProps) { return ; } ``` ## InputOTP - key: `input-otp` - import: `import { InputOTP } from "@/components/ui/input-otp"` - description: One-time password input with individual cells - tier: 1 - deps: clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/input-otp.tsx import React, { useRef, useState } from "react"; import { View, TextInput, useColorScheme } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface InputOTPProps extends React.ComponentPropsWithoutRef { className?: string; length?: number; value?: string; onValueChange?: (value: string) => void; } export function InputOTP({ length = 6, value = "", onValueChange, className, ...props }: InputOTPProps) { const refs = useRef<(TextInput | null)[]>([]); const [focused, setFocused] = useState(-1); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const digits = Array.from({ length }, (_, i) => value[i] ?? ""); const handleChange = (text: string, index: number) => { const char = text.slice(-1); const next = [...digits]; next[index] = char; onValueChange?.(next.join("")); if (char && index < length - 1) { refs.current[index + 1]?.focus(); } }; const handleKeyPress = (key: string, index: number) => { if (key === "Backspace" && !digits[index] && index > 0) { refs.current[index - 1]?.focus(); } }; const bg = dark ? colors.secondary : colors.background; // Dark border is lifted one shade above the dark bg (which equals colors.secondary) // so the box stays visible — colors.border in dark mode would blend into bg. const borderDefault = dark ? "#3f3f46" : colors.input; const borderFocused = colors.foreground; const textColor = colors.foreground; return ( {digits.map((digit, i) => ( { refs.current[i] = el; }} style={{ height: 48, width: 40, borderRadius: 8, borderWidth: focused === i ? 2 : 1, borderColor: focused === i ? borderFocused : borderDefault, backgroundColor: bg, textAlign: "center" as const, fontSize: 18, fontWeight: "600", color: textColor, }} value={digit} onChangeText={(t) => handleChange(t, i)} onKeyPress={({ nativeEvent }) => handleKeyPress(nativeEvent.key, i)} onFocus={() => setFocused(i)} onBlur={() => setFocused(-1)} keyboardType="number-pad" keyboardAppearance={dark ? "dark" : "light"} selectionColor={borderFocused} cursorColor={borderFocused} maxLength={1} selectTextOnFocus accessible={true} accessibilityLabel={`Digit ${i + 1} of ${length}`} /> ))} ); } ``` ## Kbd - key: `kbd` - import: `import { Kbd } from "@/components/ui/kbd"` - description: Keyboard key display with grouping and separator - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/kbd.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const kbdVariants = cva( "items-center justify-center rounded-md border border-border bg-muted", { variants: { size: { sm: "min-h-5 px-1", md: "min-h-6 px-1.5", lg: "min-h-7 px-2", }, }, defaultVariants: { size: "md" }, } ); const kbdTextVariants = cva("font-mono text-muted-foreground", { variants: { size: { sm: "text-[10px]", md: "text-xs", lg: "text-sm", }, }, defaultVariants: { size: "md" }, }); export interface KbdProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; textClassName?: string; children: string; } export function Kbd({ size, className, textClassName, children, ...props }: KbdProps) { return ( {children} ); } export interface KbdGroupProps extends React.ComponentPropsWithoutRef { className?: string; separator?: string; children: React.ReactNode; } export function KbdGroup({ className, separator = "+", children, ...props }: KbdGroupProps) { const items = React.Children.toArray(children); return ( {items.map((child, i) => ( {child} {i < items.length - 1 && ( {separator} )} ))} ); } ``` ## KeyboardView - key: `keyboard-view` - import: `import { KeyboardView } from "@/components/ui/keyboard-view"` - description: Keyboard-avoiding wrapper so forms stay visible above the keyboard - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/keyboard-view.tsx import React from "react"; import { KeyboardAvoidingView, Platform } from "react-native"; import { cn } from "@/lib/utils"; export interface KeyboardViewProps extends React.ComponentPropsWithoutRef { className?: string; offset?: number; } export function KeyboardView({ className, offset, behavior, ...props }: KeyboardViewProps) { return ( ); } ``` ## Label - key: `label` - import: `import { Label } from "@/components/ui/label"` - description: Form field label - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/label.tsx import React from "react"; import { Text } from "react-native"; import { cn } from "@/lib/utils"; export interface LabelProps extends React.ComponentPropsWithoutRef { className?: string; } export function Label({ className, ...props }: LabelProps) { return ( ); } ``` ## LabeledSeparator - key: `labeled-separator` - import: `import { LabeledSeparator } from "@/components/ui/labeled-separator"` - description: Horizontal separator with centered text label - tier: 1 - deps: clsx, tailwind-merge - aniui deps: separator ```tsx // components/ui/labeled-separator.tsx import React from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; export interface LabeledSeparatorProps extends React.ComponentPropsWithoutRef { className?: string; label: string; labelClassName?: string; } export function LabeledSeparator({ label, className, labelClassName, ...props }: LabeledSeparatorProps) { return ( {label} ); } ``` ## LineChart - key: `line-chart` - import: `import { LineChart } from "@/components/ui/line-chart"` - description: Skia line chart with draw-on entrance, morph-on-data-change, and a scrubbing crosshair tooltip - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip, theme-provider ```tsx // components/ui/line-chart.tsx import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, LayoutChangeEvent, useColorScheme } from "react-native"; import { Canvas, Path, Circle, Group, DashPathEffect } from "@shopify/react-native-skia"; import Animated, { Easing, Extrapolation, cancelAnimation, interpolate, runOnJS, useAnimatedReaction, useAnimatedStyle, useDerivedValue, useSharedValue, withDelay, withRepeat, withSequence, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { ChartTooltip } from "@/components/ui/chart-tooltip"; export interface LineChartDataPoint { label: string; value: number; } export interface LineChartSeries { data: LineChartDataPoint[]; color: string; dashed?: boolean; } export interface LineChartProps extends React.ComponentPropsWithoutRef { className?: string; data?: LineChartDataPoint[]; height?: number; color?: string; showDots?: boolean; showGrid?: boolean; showLabels?: boolean; curved?: boolean; series?: LineChartSeries[]; onPointChange?: (point: LineChartDataPoint, index: number) => void; } interface Vec { x: number; y: number; } interface Frame { points: Vec[]; tangents: number[]; } const SPRING_CONFIG = { damping: 20, stiffness: 300, mass: 1 }; const DRAW_DURATION = 900; const MORPH_DURATION = 550; const INDICATOR_RADIUS = 5; const INDICATOR_BORDER_MULTIPLIER = 1.9; const PULSE_RADIUS_MULTIPLIER = 4; const PULSE_DURATION = 1400; const PULSE_DELAY = 600; const MAX_MORPH_SAMPLES = 160; function lerp(from: number, to: number, t: number): number { "worklet"; return from + (to - from) * t; } // Fritsch-Carlson monotone cubic tangents: keeps the curve from overshooting // past local min/max points the way a naive Catmull-Rom spline would. function monotoneTangents(points: Vec[]): number[] { "worklet"; const count = points.length; if (count < 2) return points.map(() => 0); const slopes: number[] = []; for (let i = 0; i < count - 1; i++) { const run = points[i + 1].x - points[i].x; slopes.push(run === 0 ? 0 : (points[i + 1].y - points[i].y) / run); } const tangents: number[] = [slopes[0]]; for (let i = 1; i < count - 1; i++) { const prev = slopes[i - 1]; const next = slopes[i]; tangents.push(prev * next <= 0 ? 0 : (prev + next) / 2); } tangents.push(slopes[count - 2]); for (let i = 0; i < count - 1; i++) { const slope = slopes[i]; if (slope === 0) { tangents[i] = 0; tangents[i + 1] = 0; continue; } const a = tangents[i] / slope; const b = tangents[i + 1] / slope; const magnitude = a * a + b * b; if (magnitude > 9) { const scale = 3 / Math.sqrt(magnitude); tangents[i] = scale * a * slope; tangents[i + 1] = scale * b * slope; } } return tangents; } function buildPath(points: Vec[], tangents: number[], curved: boolean): string { "worklet"; if (points.length === 0) return "M 0 0"; if (points.length === 1) return `M ${points[0].x} ${points[0].y}`; let d = `M ${points[0].x} ${points[0].y}`; for (let i = 0; i < points.length - 1; i++) { const from = points[i]; const to = points[i + 1]; if (!curved) { d += ` L ${to.x} ${to.y}`; continue; } const run = (to.x - from.x) / 3; const c1y = from.y + (tangents[i] ?? 0) * run; const c2y = to.y - (tangents[i + 1] ?? 0) * run; d += ` C ${from.x + run} ${c1y} ${to.x - run} ${c2y} ${to.x} ${to.y}`; } return d; } // Shared "which segment does x fall in" search used by both the position and // slope evaluators below. function findSegment(points: Vec[], x: number): number { "worklet"; let idx = points.length - 2; for (let i = 0; i < points.length - 1; i++) { if (x >= points[i].x && x <= points[i + 1].x) { idx = i; break; } } return idx; } function yForX(points: Vec[], tangents: number[], curved: boolean, x: number): number { "worklet"; if (points.length === 0) return 0; if (points.length === 1) return points[0].y; if (x <= points[0].x) return points[0].y; const last = points[points.length - 1]; if (x >= last.x) return last.y; const idx = findSegment(points, x); const from = points[idx]; const to = points[idx + 1]; const run = to.x - from.x; if (run === 0) return to.y; const t = (x - from.x) / run; if (!curved) return lerp(from.y, to.y, t); const t2 = t * t; const t3 = t2 * t; const h00 = 2 * t3 - 3 * t2 + 1; const h10 = t3 - 2 * t2 + t; const h01 = -2 * t3 + 3 * t2; const h11 = t3 - t2; return h00 * from.y + h10 * run * (tangents[idx] ?? 0) + h01 * to.y + h11 * run * (tangents[idx + 1] ?? 0); } function slopeForX(points: Vec[], tangents: number[], curved: boolean, x: number): number { "worklet"; if (points.length < 2) return 0; const idx = findSegment(points, x); const from = points[idx]; const to = points[idx + 1]; const run = to.x - from.x; if (run === 0) return 0; if (!curved) return (to.y - from.y) / run; const t = Math.min(Math.max((x - from.x) / run, 0), 1); const m0 = tangents[idx] ?? 0; const m1 = tangents[idx + 1] ?? 0; return ((6 * t * t - 6 * t) * (from.y - to.y)) / run + (3 * t * t - 4 * t + 1) * m0 + (3 * t * t - 2 * t) * m1; } // "Draw-on" reveal: keep only the points left of the animated x-cutoff and // synthesize one extra vertex exactly at the cutoff so the tip never jumps. function sliceCurve(points: Vec[], tangents: number[], curved: boolean, progress: number): Frame { "worklet"; if (progress >= 1 || points.length < 2) return { points, tangents }; const first = points[0]; const last = points[points.length - 1]; const cutoff = first.x + (last.x - first.x) * progress; if (cutoff <= first.x) return { points: [], tangents: [] }; const kept: Vec[] = []; const keptTangents: number[] = []; for (let i = 0; i < points.length; i++) { if (points[i].x > cutoff) break; kept.push(points[i]); keptTangents.push(tangents[i] ?? 0); } const tail = kept[kept.length - 1]; if (tail == null || tail.x < cutoff) { kept.push({ x: cutoff, y: yForX(points, tangents, curved, cutoff) }); keptTangents.push(slopeForX(points, tangents, curved, cutoff)); } return { points: kept, tangents: keptTangents }; } function blendFrame( fromPoints: Vec[], fromTangents: number[], toPoints: Vec[], toTangents: number[], progress: number, curved: boolean ): Frame { "worklet"; if (progress >= 1 || fromPoints.length !== toPoints.length) return { points: toPoints, tangents: toTangents }; const points: Vec[] = []; const tangents: number[] = []; for (let i = 0; i < toPoints.length; i++) { points.push({ x: toPoints[i].x, y: lerp(fromPoints[i].y, toPoints[i].y, progress) }); if (curved) tangents.push(lerp(fromTangents[i] ?? 0, toTangents[i] ?? 0, progress)); } return { points, tangents }; } function indexForX(points: Vec[], x: number): number { "worklet"; if (points.length === 0) return -1; let nearest = 0; let shortest = Math.abs(points[0].x - x); for (let i = 1; i < points.length; i++) { const distance = Math.abs(points[i].x - x); if (distance < shortest) { shortest = distance; nearest = i; } } return nearest; } // JS-thread helpers (run once per data/layout change, not per-frame): build a // shared sample grid along the NEW curve so an old and a new curve with a // DIFFERENT point count can still be lerped index-for-index without glitching. function morphGrid(from: Vec[], to: Vec[]): number[] { if (to.length < 2) return to.map((p) => p.x); const segments = to.length - 1; const wanted = Math.min(MAX_MORPH_SAMPLES, Math.max(to.length, from.length * 4)); const factor = Math.min(8, Math.max(1, Math.round(wanted / segments))); if (factor <= 1) return to.map((p) => p.x); const xs: number[] = []; for (let i = 0; i < segments; i++) { const start = to[i].x; const step = (to[i + 1].x - start) / factor; for (let k = 0; k < factor; k++) xs.push(start + step * k); } xs.push(to[segments].x); return xs; } function sampleAt(points: Vec[], tangents: number[], curved: boolean, xs: number[]): Vec[] { return xs.map((x) => ({ x, y: yForX(points, tangents, curved, x) })); } function toPixelPoints(pts: LineChartDataPoint[], left: number, top: number, cw: number, ch: number, maxVal: number): Vec[] { return pts.map((d, i) => ({ x: left + (i / Math.max(pts.length - 1, 1)) * cw, y: top + ch - (d.value / maxVal) * ch, })); } interface AnimatedCurveProps { points: Vec[]; curved: boolean; color: string; dashed?: boolean; draw: SharedValue; showDots: boolean; frameOut?: SharedValue; } // Renders one series: handles its own entrance draw-on + morph-on-data-change // animation, then draws the (possibly sliced) Skia path plus fading-in dots. function AnimatedCurve({ points, curved, color, dashed, draw, showDots, frameOut }: AnimatedCurveProps) { const targetPoints = useSharedValue(points); const targetTangents = useSharedValue(curved ? monotoneTangents(points) : []); const originPoints = useSharedValue(points); const originTangents = useSharedValue(targetTangents.value); const morph = useSharedValue(1); const hasEntered = useRef(false); const frame = useDerivedValue( () => blendFrame(originPoints.value, originTangents.value, targetPoints.value, targetTangents.value, morph.value, curved), [curved] ); useEffect(() => { if (points.length === 0) return; const nextTangents = curved ? monotoneTangents(points) : []; if (!hasEntered.current) { hasEntered.current = true; originPoints.value = points; originTangents.value = nextTangents; targetPoints.value = points; targetTangents.value = nextTangents; cancelAnimation(morph); morph.value = 1; return; } const current = frame.value; const source = current.points.length > 1 ? current.points : targetPoints.value; const sourceTangents = current.points.length > 1 ? current.tangents : targetTangents.value; const grid = morphGrid(source, points); const origin = sampleAt(source, sourceTangents, curved, grid); const target = sampleAt(points, nextTangents, curved, grid); originPoints.value = origin; originTangents.value = curved ? monotoneTangents(origin) : []; targetPoints.value = target; targetTangents.value = curved ? monotoneTangents(target) : []; cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [points, curved]); useAnimatedReaction( () => frame.value, (current) => { if (frameOut) frameOut.value = current; }, [frameOut] ); const drawn = useDerivedValue(() => sliceCurve(frame.value.points, frame.value.tangents, curved, draw.value), [curved]); const path = useDerivedValue(() => buildPath(drawn.value.points, drawn.value.tangents, curved), [curved]); const cutoff = useDerivedValue(() => { const pts = frame.value.points; if (pts.length < 2) return 0; return pts[0].x + (pts[pts.length - 1].x - pts[0].x) * draw.value; }); return ( <> {dashed ? : null} {showDots && points.map((p, i) => )} ); } function SeriesDot({ x, y, color, cutoff }: { x: number; y: number; color: string; cutoff: SharedValue }) { const opacity = useDerivedValue(() => (cutoff.value >= x ? 1 : 0)); return ( ); } export function LineChart({ className, data, height = 200, color, showDots = true, showGrid = true, showLabels = false, curved = true, series, onPointChange, ...props }: LineChartProps) { const [width, setWidth] = useState(0); const [tooltipIndex, setTooltipIndex] = useState(-1); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const seriesColor = color ?? colors.primary; const gridColor = colors.border; const labelColor = colors.mutedForeground; // Punch-through ring behind the trailing indicator dot — light side is "#ffffff", // not "#fafafa", so it doesn't cleanly match the primaryForeground pair; left // as-is rather than forcing a mapping (see report). const ringColor = dark ? "#18181b" : "#ffffff"; const onLayout = (e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width); const allSeries: LineChartSeries[] = useMemo(() => series ?? [{ data: data ?? [], color: seriesColor }], [series, data, seriesColor]); const maxVal = useMemo(() => Math.max(...allSeries.flatMap((s) => s.data.map((d) => d.value)), 1), [allSeries]); const pad = showLabels ? { top: 10, right: 10, bottom: 24, left: 36 } : { top: 10, right: 10, bottom: 10, left: 10 }; const cw = width - pad.left - pad.right; const ch = height - pad.top - pad.bottom; const pixelSeries = useMemo( () => allSeries.map((s) => toPixelPoints(s.data, pad.left, pad.top, cw, ch, maxVal)), [allSeries, cw, ch, maxVal, pad.left, pad.top] ); const gridPath = useMemo( () => [3, 2, 1, 0].map((i) => `M ${pad.left} ${pad.top + (i / 3) * ch} L ${pad.left + cw} ${pad.top + (i / 3) * ch}`).join(" "), [pad.left, pad.top, cw, ch] ); const primaryPoints = pixelSeries[0] ?? []; const labels = allSeries[0]?.data ?? []; const primaryColor = allSeries[0]?.color ?? seriesColor; const draw = useSharedValue(0); const isActive = useSharedValue(0); const cursorX = useSharedValue(0); const cursorY = useSharedValue(0); const selectedIndex = useSharedValue(-1); const dataPoints = useSharedValue([]); const primaryFrame = useSharedValue({ points: [], tangents: [] }); const pulse = useSharedValue(0); const hasEnteredChart = useRef(false); const tooltipWidth = useSharedValue(0); const tooltipHeight = useSharedValue(0); useEffect(() => { if (width === 0 || primaryPoints.length === 0) return; dataPoints.value = primaryPoints; if (!hasEnteredChart.current) { hasEnteredChart.current = true; cancelAnimation(draw); draw.value = 0; draw.value = withTiming(1, { duration: DRAW_DURATION, easing: Easing.out(Easing.cubic) }); } }, [primaryPoints, width]); useEffect(() => { pulse.value = withRepeat( withDelay(PULSE_DELAY, withSequence(withTiming(1, { duration: PULSE_DURATION }), withTiming(0, { duration: 0 }))), -1 ); return () => cancelAnimation(pulse); }, []); const reportPoint = useCallback( (index: number) => { setTooltipIndex(index); const point = labels[index]; if (point) onPointChange?.(point, index); }, [labels, onPointChange] ); const clearPoint = useCallback(() => setTooltipIndex(-1), []); const gesture = useMemo(() => { const scrub = (x: number) => { "worklet"; const { points, tangents } = primaryFrame.value; if (points.length < 2) return; const clampedX = Math.min(Math.max(x, points[0].x), points[points.length - 1].x); cursorX.value = clampedX; cursorY.value = yForX(points, tangents, curved, clampedX); const index = indexForX(dataPoints.value, clampedX); if (index !== selectedIndex.value) { selectedIndex.value = index; runOnJS(reportPoint)(index); } }; return Gesture.Pan() .minDistance(0) .onBegin((e) => { "worklet"; scrub(e.x); isActive.value = withTiming(1, { duration: 140 }); }) .onUpdate((e) => { "worklet"; scrub(e.x); }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; runOnJS(clearPoint)(); }); }, [curved, reportPoint, clearPoint]); const lastX = useDerivedValue(() => { const pts = primaryFrame.value.points; return pts.length > 0 ? pts[pts.length - 1].x : 0; }); const lastY = useDerivedValue(() => { const pts = primaryFrame.value.points; return pts.length > 0 ? pts[pts.length - 1].y : 0; }); const indicatorOpacity = useDerivedValue( () => interpolate(draw.value, [0.85, 1], [0, 1], Extrapolation.CLAMP) * (1 - isActive.value) ); const pulseRadius = useDerivedValue(() => interpolate(pulse.value, [0, 1], [INDICATOR_RADIUS, INDICATOR_RADIUS * PULSE_RADIUS_MULTIPLIER]) ); const pulseOpacity = useDerivedValue(() => interpolate(pulse.value, [0, 1], [0.35, 0]) * indicatorOpacity.value); const cursorScale = useDerivedValue(() => withSpring(isActive.value, SPRING_CONFIG)); const cursorDotRadius = useDerivedValue(() => 6 * cursorScale.value); const cursorBorderRadius = useDerivedValue(() => 6 * INDICATOR_BORDER_MULTIPLIER * cursorScale.value); const crosshairPath = useDerivedValue( () => `M ${cursorX.value} ${pad.top} L ${cursorX.value} ${pad.top + ch}`, [pad.top, ch] ); const tooltipStyle = useAnimatedStyle(() => { const half = tooltipWidth.value / 2; const translateX = Math.min(Math.max(cursorX.value - half, 0), Math.max(width - tooltipWidth.value, 0)); const translateY = Math.max(cursorY.value - tooltipHeight.value - 14, 0); return { opacity: isActive.value, transform: [{ translateX }, { translateY }] }; }); const onTooltipLayout = (e: LayoutChangeEvent) => { tooltipWidth.value = e.nativeEvent.layout.width; tooltipHeight.value = e.nativeEvent.layout.height; }; const tooltipPoint = tooltipIndex >= 0 ? labels[tooltipIndex] : undefined; if (width === 0) { return ; } return ( {showGrid && } {allSeries.map((s, i) => ( ))} {showLabels && ( {labels.map((d, i) => ( {d.label} ))} {[0, 1, 2, 3].map((i) => ( {Math.round((i / 3) * maxVal)} ))} )} {tooltipPoint ? : null} ); } ``` ## List - key: `list` - import: `import { List } from "@/components/ui/list"` - description: Styled list items - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/list.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { cn } from "@/lib/utils"; export interface ListProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function List({ className, ...props }: ListProps) { return ; } export interface ListItemProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function ListItem({ className, ...props }: ListItemProps) { return ( ); } export interface ListItemTitleProps extends React.ComponentPropsWithoutRef { className?: string; } export function ListItemTitle({ className, ...props }: ListItemTitleProps) { return ; } export interface ListItemDescriptionProps extends React.ComponentPropsWithoutRef { className?: string; } export function ListItemDescription({ className, ...props }: ListItemDescriptionProps) { return ; } ``` ## Loader - key: `loader` - import: `import { Loader } from "@/components/ui/loader"` - description: Animated loading indicator — segmented comet-tail ring or bouncing dots - tier: 2 - deps: class-variance-authority, react-native-reanimated, react-native-svg, clsx, tailwind-merge - aniui deps: animate, theme-provider ```tsx // components/ui/loader.tsx import React, { useEffect } from "react"; import { View } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import Svg, { Circle } from "react-native-svg"; import Animated, { cancelAnimation, useAnimatedStyle, useSharedValue, withDelay, withRepeat, withTiming, Easing, } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const loaderVariants = cva("items-center justify-center", { variants: { variant: { circle: "", dots: "flex-row gap-1.5", }, size: { sm: "", md: "", lg: "" }, }, defaultVariants: { variant: "circle", size: "md" }, }); const sizes = { sm: 20, md: 32, lg: 44 } as const; const strokeWidths = { sm: 2, md: 2.5, lg: 3 } as const; // Segmented "comet tail" ring — strokeDasharray/strokeDashoffset per segment // plus exponential opacity falloff, rather than a plain spinning border. const SEGMENTS = 16; const ACTIVE_PCT = 0.75; const GRADIENT_PCT = 0.25; export interface LoaderProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; } export function Loader({ variant = "circle", size = "md", className, ...props }: LoaderProps) { const reducedMotion = useReducedMotion(); const spin = useSharedValue(0); const s = sizes[size ?? "md"]; const colors = useThemeColors(); const color = colors.foreground; useEffect(() => { if (reducedMotion) return; spin.value = withRepeat(withTiming(1, { duration: 900, easing: Easing.linear }), -1, false); return () => cancelAnimation(spin); }, [spin, reducedMotion]); const spinStyle = useAnimatedStyle(() => ({ transform: [{ rotate: `${spin.value * 360}deg` }], })); if (variant === "dots") { return ( {[0, 1, 2].map((i) => ( ))} ); } const strokeWidth = strokeWidths[size ?? "md"]; const radius = (s - strokeWidth) / 2; const cx = s / 2; const cy = s / 2; const circumference = 2 * Math.PI * radius; const solidPct = ACTIVE_PCT - GRADIENT_PCT; const segmentLength = (circumference * GRADIENT_PCT) / SEGMENTS; const activeLength = circumference * solidPct; return ( {Array.from({ length: SEGMENTS }).map((_, i) => { const progress = i / SEGMENTS; const opacity = 1 - Math.pow(progress, 1.5); if (opacity < 0.03) return null; return ( ); })} ); } function Dot({ index, size, reducedMotion }: { index: number; size: number; reducedMotion: boolean }) { // Vertical bounce (translateY), staggered per dot — a cy jump of // dotRadius * 0.85, staggered by duration / 3 across the dots. const progress = useSharedValue(0); const jump = size * 0.85; useEffect(() => { if (reducedMotion) return; progress.value = withDelay( index * 167, withRepeat(withTiming(1, { duration: 500, easing: Easing.inOut(Easing.ease) }), -1, true) ); return () => cancelAnimation(progress); }, [progress, index, reducedMotion]); const style = useAnimatedStyle(() => ({ transform: [{ translateY: -progress.value * jump }], })); return ( ); } ``` ## Marquee - key: `marquee` - import: `import { Marquee } from "@/components/ui/marquee"` - description: Infinite horizontal ticker for any content — reverse direction, tap-to-pause, and hold-to-speed-up - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, text ```tsx // components/ui/marquee.tsx import React, { useCallback, useState } from "react"; import { View, Pressable, LayoutChangeEvent } from "react-native"; import Animated, { useAnimatedStyle, useFrameCallback, useSharedValue, type FrameInfo, } from "react-native-reanimated"; import { Text } from "@/components/ui/text"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export interface MarqueeProps extends React.ComponentPropsWithoutRef { className?: string; /** Content to tick — a single copy is measured and repeated to fill the track. */ children: React.ReactNode; /** Pixels per second. */ speed?: number; /** Gap between repeated copies, in pixels. */ spacing?: number; /** Scroll right-to-left instead of the default left-to-right. */ reverse?: boolean; /** Tap to pause/resume the ticker. */ pauseOnPress?: boolean; /** Press-and-hold to fast-forward. Mutually exclusive with pauseOnPress's tap toggle. */ holdToSpeedUp?: boolean; speedUpMultiplier?: number; } export function Marquee({ className, children, speed = 50, spacing = 20, reverse = false, pauseOnPress = false, holdToSpeedUp = false, speedUpMultiplier = 3, ...props }: MarqueeProps) { const reducedMotion = useReducedMotion(); const offset = useSharedValue(0); const isPaused = useSharedValue(false); const speedMultiplier = useSharedValue(1); const [trackWidth, setTrackWidth] = useState(0); const [contentWidth, setContentWidth] = useState(0); const segmentWidth = contentWidth + spacing; // Enough copies to cover the visible track continuously, plus a couple of // spares so a wrap never exposes a gap at the track's edges. const copies = contentWidth > 0 && trackWidth > 0 ? Math.max(2, Math.ceil(trackWidth / segmentWidth) + 2) : 2; useFrameCallback((frameInfo: FrameInfo) => { "worklet"; if (reducedMotion || isPaused.value || contentWidth === 0) return; const dt = frameInfo.timeSincePreviousFrame ?? 0; const distance = (speed * speedMultiplier.value * dt) / 1000; if (reverse) { offset.value -= distance; if (offset.value <= -segmentWidth) offset.value += segmentWidth; } else { offset.value += distance; if (offset.value >= segmentWidth) offset.value -= segmentWidth; } }); const style = useAnimatedStyle(() => ({ transform: [{ translateX: -offset.value }] })); const onTrackLayout = useCallback((e: LayoutChangeEvent) => setTrackWidth(e.nativeEvent.layout.width), []); const onContentLayout = useCallback((e: LayoutChangeEvent) => setContentWidth(e.nativeEvent.layout.width), []); const handlePress = () => { if (holdToSpeedUp) return; if (pauseOnPress) isPaused.value = !isPaused.value; }; const handlePressIn = () => { if (holdToSpeedUp) speedMultiplier.value = speedUpMultiplier; }; const handlePressOut = () => { if (holdToSpeedUp) speedMultiplier.value = 1; }; // Bare strings can't be rendered directly inside a View/Pressable in RN. const content = typeof children === "string" ? {children} : children; const track = ( {Array.from({ length: copies }).map((_, i) => ( 0 ? { marginLeft: spacing } : undefined} onLayout={i === 0 ? onContentLayout : undefined} > {content} ))} ); const interactive = pauseOnPress || holdToSpeedUp; return ( {interactive ? ( {track} ) : ( track )} ); } ``` ## MaskedInput - key: `masked-input` - import: `import { MaskedInput } from "@/components/ui/masked-input"` - description: Text input with mask formatting for credit cards, phones, dates - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: input, theme-provider ```tsx // components/ui/masked-input.tsx import React, { useCallback } from "react"; import { TextInput, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const maskedVariants = cva( "rounded-md border py-2 text-foreground placeholder:text-muted-foreground", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-3 text-sm", md: "min-h-12 px-4 text-base", lg: "min-h-14 px-5 text-lg", }, }, defaultVariants: { variant: "default", size: "md" }, } ); type MaskPreset = "credit-card" | "phone" | "date"; const masks: Record = { "credit-card": "#### #### #### ####", phone: "(###) ###-####", date: "##/##/####", }; function applyMask(raw: string, mask: string): string { const digits = raw.replace(/\D/g, ""); let result = ""; let digitIdx = 0; for (let i = 0; i < mask.length && digitIdx < digits.length; i++) { if (mask[i] === "#") { result += digits[digitIdx++]; } else { result += mask[i]; } } return result; } export interface MaskedInputProps extends Omit, "onChangeText">, VariantProps { className?: string; mask?: string; preset?: MaskPreset; onChangeText?: (masked: string, raw: string) => void; } export const MaskedInput = React.forwardRef< React.ElementRef, MaskedInputProps & { value?: string } >(function MaskedInput( { variant, size, className, mask: customMask, preset, onChangeText, value: controlledValue, ...props }, ref ) { const maskPattern = customMask ?? (preset ? masks[preset] : ""); const [internal, setInternal] = React.useState(""); const displayValue = controlledValue ?? internal; const handleChange = useCallback( (text: string) => { if (!maskPattern) { setInternal(text); onChangeText?.(text, text); return; } const raw = text.replace(/\D/g, ""); const masked = applyMask(raw, maskPattern); setInternal(masked); onChangeText?.(masked, raw); }, [maskPattern, onChangeText] ); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; return ( ); }); ``` ## MatchedGeometry - key: `matched-geometry` - import: `import { MatchedGeometry } from "@/components/ui/matched-geometry"` - description: SwiftUI-style shared-element layout transition primitive — morphs one tagged view into another's position and size when they swap - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/matched-geometry.tsx import React, { createContext, useCallback, useContext, useMemo, useRef, useState, } from "react"; import { View, type LayoutChangeEvent } from "react-native"; import Animated, { Easing, runOnJS, useAnimatedStyle, useSharedValue, withTiming, type AnimatedStyle, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; /** * SwiftUI-`matchedGeometryEffect`-style shared-element transition primitive. * * Tag two `MatchedGeometryView`s with the same `id` — mounted and unmounted * in turn as a boolean/id-based state flips elsewhere in the tree (e.g. a * list-item view swapped for a detail-view) — and the outgoing view's last * measured rect morphs into the incoming view's freshly measured rect via a * shared animated overlay, while the incoming view cross-fades in over the * same duration. Only one `MatchedGeometryView` per `id` should be mounted * at a time; the provider should wrap the screen (or region) the transition * should be visible across. */ interface Rect { x: number; y: number; width: number; height: number; } interface MatchedGeometryContextValue { registerRect: (id: string, rect: Rect) => void; requestTransition: ( id: string, rect: Rect, node: React.ReactNode, duration: number, ) => boolean; originRef: React.RefObject<{ x: number; y: number }>; } const MatchedGeometryContext = createContext(null); const DEFAULT_TRANSITION_DURATION = 350; const ZERO_RECT: Rect = { x: 0, y: 0, width: 0, height: 0 }; const TRANSITION_EASING = Easing.out(Easing.cubic); export interface MatchedGeometryProviderProps extends React.ComponentPropsWithoutRef { className?: string; } /** Wrap the screen (or region) within which shared-element transitions should be visible. */ export function MatchedGeometryProvider({ children, className, style, ...props }: MatchedGeometryProviderProps) { const rects = useRef>(new Map()); const originRef = useRef({ x: 0, y: 0 }); const rootRef = useRef(null); const [overlayNode, setOverlayNode] = useState(null); const from = useSharedValue(ZERO_RECT); const to = useSharedValue(ZERO_RECT); const progress = useSharedValue(0); const clearOverlay = useCallback(() => setOverlayNode(null), []); const registerRect = useCallback((id: string, rect: Rect) => { rects.current.set(id, rect); }, []); const requestTransition = useCallback( (id: string, rect: Rect, node: React.ReactNode, duration: number) => { const previous = rects.current.get(id); rects.current.set(id, rect); if (!previous) return false; from.value = previous; to.value = rect; progress.value = 0; setOverlayNode(node); progress.value = withTiming( 1, { duration, easing: TRANSITION_EASING }, (finished) => { if (finished) runOnJS(clearOverlay)(); }, ); return true; }, [clearOverlay, from, progress, to], ); const handleRootLayout = useCallback((_e: LayoutChangeEvent) => { rootRef.current?.measureInWindow((x, y) => { originRef.current = { x, y }; }); }, []); const overlayStyle = useAnimatedStyle(() => { const f = from.value; const t = to.value; const p = progress.value; return { position: "absolute" as const, left: f.x + (t.x - f.x) * p, top: f.y + (t.y - f.y) * p, width: f.width + (t.width - f.width) * p, height: f.height + (t.height - f.height) * p, }; }); const contextValue = useMemo( () => ({ registerRect, requestTransition, originRef }), [registerRect, requestTransition], ); return ( {children} {overlayNode ? ( {overlayNode} ) : null} ); } export interface UseMatchedGeometryResult { ref: React.RefObject; onLayout: () => void; animatedStyle: AnimatedStyle<{ opacity: number }>; } /** * Registers `content` under `id`. The first layout after a *different* * previously-registered rect exists for the same `id` triggers a morph * overlay from that old rect to this one; the first-ever mount for an `id` * just appears (nothing to morph from yet). */ export function useMatchedGeometry( id: string, content: React.ReactNode, duration: number = DEFAULT_TRANSITION_DURATION, ): UseMatchedGeometryResult { const ctx = useContext(MatchedGeometryContext); if (!ctx) { throw new Error( "useMatchedGeometry must be used within a MatchedGeometryProvider", ); } const ref = useRef(null); const opacity = useSharedValue(1); const hasLaidOut = useRef(false); const onLayout = useCallback(() => { ref.current?.measureInWindow((x, y, width, height) => { const rect: Rect = { x: x - ctx.originRef.current.x, y: y - ctx.originRef.current.y, width, height, }; if (hasLaidOut.current) { ctx.registerRect(id, rect); return; } hasLaidOut.current = true; const didTransition = ctx.requestTransition(id, rect, content, duration); if (didTransition) { opacity.value = 0; opacity.value = withTiming(1, { duration, easing: TRANSITION_EASING, }); } else { ctx.registerRect(id, rect); } }); }, [content, ctx, duration, id, opacity]); const animatedStyle = useAnimatedStyle(() => ({ opacity: opacity.value })); return { ref, onLayout, animatedStyle }; } export interface MatchedGeometryViewProps extends React.ComponentPropsWithoutRef { id: string; duration?: number; className?: string; } /** Drop-in wrapper around `useMatchedGeometry` — tag two of these with the same `id` across a mount/unmount swap to get a shared-element morph for free. */ export function MatchedGeometryView({ id, duration, className, style, children, ...props }: MatchedGeometryViewProps) { const { ref, onLayout, animatedStyle } = useMatchedGeometry( id, children, duration, ); return ( {children} ); } ``` ## Menubar - key: `menubar` - import: `import { Menubar } from "@/components/ui/menubar"` - description: Horizontal menu bar with dropdown menus: Menubar, MenubarMenu, MenubarItem - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/menubar.tsx import React, { createContext, useContext, useRef, useState } from "react"; import { View, Text, Pressable, Modal } from "react-native"; import { cn } from "@/lib/utils"; const MenubarCloseContext = createContext<(() => void) | null>(null); export interface MenubarProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function Menubar({ className, ...props }: MenubarProps) { return ( ); } export interface MenubarMenuProps { trigger: React.ReactNode; className?: string; children?: React.ReactNode; } export function MenubarMenu({ trigger, className, children }: MenubarMenuProps) { const [open, setOpen] = useState(false); const [anchor, setAnchor] = useState({ x: 0, y: 0 }); const ref = useRef(null); const openMenu = () => { // Open immediately so the menu never depends on a measure callback firing; // measureInWindow (not measure) then refines the anchor inside the Modal. setOpen(true); ref.current?.measureInWindow((x, y, _w, h) => { setAnchor({ x, y: y + h + 4 }); }); }; return ( <> {typeof trigger === "string" ? {trigger} : trigger} setOpen(false)}> setOpen(false)} accessible={false}> setOpen(false)}>{children} ); } export interface MenubarItemProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function MenubarItem({ className, children, onPress, ...props }: MenubarItemProps) { const close = useContext(MenubarCloseContext); return ( { onPress?.(e); close?.(); }} className={cn("min-h-12 min-w-12 justify-center rounded-sm px-2", className)} {...props} > {typeof children === "string" ? {children} : children} ); } ``` ## MobileDock - key: `mobile-dock` - import: `import { MobileDock } from "@/components/ui/mobile-dock"` - description: Finger-tracked fisheye dock — drag across icons to magnify the one under your touch, release to tap the nearest one - tier: 3 - deps: react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge ```tsx // components/ui/mobile-dock.tsx import React, { useCallback, useMemo } from "react"; import { View, Text, LayoutChangeEvent } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, interpolate, Extrapolation, runOnJS, type SharedValue, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; export type DockItem = { key: string; icon: React.ReactNode; label?: string; onPress?: () => void; }; export interface MobileDockProps extends React.ComponentPropsWithoutRef { className?: string; items: DockItem[]; /** Resting icon size (dp) when nothing is being touched. */ itemSize?: number; /** Icon size (dp) directly under the finger. */ peakSize?: number; /** How many neighbors on either side still feel the magnification falloff. */ spread?: number; /** Horizontal gap (dp) between resting icons. */ gap?: number; /** Show a floating label above the touched icon. */ showLabels?: boolean; onItemPress?: (item: DockItem, index: number) => void; } // Fractional icon index under a touch: x=0 -> -0.5 (left of the first icon), // x=width -> count-0.5 (right of the last icon). Landing exactly on an // integer means the finger sits at that icon's center. function touchToIndex(x: number, width: number, count: number) { "worklet"; if (width <= 0) return -1; return (x / width) * count - 0.5; } // Conserved-width fisheye size for one icon: everyone's growth is funded by // shrinking everyone (including itself) by an even share of the dock-wide // extra width picked up under the touch, so the row's total width never // changes — only the finger's neighborhood visibly redistributes it. function iconSize( index: number, count: number, activeIndex: number, activeAmount: number, restSize: number, inputRange: number[], outputRange: number[] ) { "worklet"; // activeAmount is always blended from a fixed [0, 1] range, so the blend is // plain arithmetic (interpolate(t, [0,1], [a,b]) === a + t * (b - a)) rather // than a call to interpolate() with a freshly-built array literal each loop // iteration — that pattern was crashing on Android inside a worklet. const n = Math.max(count, 1); let totalExtra = 0; for (let j = 0; j < n; j++) { const distance = Math.abs(activeIndex - j); const grown = interpolate(distance, inputRange, outputRange, Extrapolation.CLAMP); totalExtra += activeAmount * (grown - restSize); } const myDistance = Math.abs(activeIndex - index); const myGrown = interpolate(myDistance, inputRange, outputRange, Extrapolation.CLAMP); const mine = restSize + activeAmount * (myGrown - restSize); return mine - totalExtra / n; } const ACTIVATE_SPRING = { damping: 22, stiffness: 400, mass: 0.35 }; const SETTLE_SPRING = { damping: 27, stiffness: 242, mass: 0.4 }; const ISACTIVE_INPUT = [0, 1]; const TOOLTIP_INPUT = [0, 0.5]; const TOOLTIP_OPACITY_OUTPUT = [1, 0]; const TOOLTIP_TRANSLATE_OUTPUT = [6, 0]; export function MobileDock({ className, items, itemSize = 50, peakSize = 70, spread = 1, gap = 6, showLabels = true, onItemPress, onLayout, ...props }: MobileDockProps) { const activeIndex = useSharedValue(-1); const isActive = useSharedValue(0); const dockWidth = useSharedValue(0); // Touch coordinates are relative to the gesture-attached (outer, padded) // view, but the icons only occupy the inner row inside that padding — // without this offset, touchToIndex mapped the raw touch x against the // full padded width, which under-registered touches near the edges (most // noticeably: holding the last icon could resolve to the previous one). const rowOffsetX = useSharedValue(0); const count = items.length; // spread=1 (default) -> inputRange [0, 1], outputRange [peakSize, itemSize]: // the touched icon peaks, its immediate neighbors are back to rest, and // everything beyond that is clamped at rest too. const { inputRange, outputRange } = useMemo(() => { const input: number[] = []; const output: number[] = []; for (let d = 0; d <= spread; d++) { input.push(d); output.push(d === 0 ? peakSize : itemSize + (peakSize - itemSize) * Math.max(0, 1 - d / spread)); } return { inputRange: input, outputRange: output }; }, [spread, itemSize, peakSize]); const fireTap = useCallback( (idx: number) => { const item = items[Math.round(idx)]; if (!item) return; item.onPress?.(); onItemPress?.(item, Math.round(idx)); }, [items, onItemPress] ); const gesture = useMemo( () => Gesture.Manual() .onTouchesDown((e, manager) => { if (e.allTouches.length === 0) return; activeIndex.value = touchToIndex(e.allTouches[0].x - rowOffsetX.value, dockWidth.value, count); isActive.value = withSpring(1, ACTIVATE_SPRING); manager.activate(); }) .onTouchesMove((e) => { if (e.allTouches.length === 0) return; activeIndex.value = touchToIndex(e.allTouches[0].x - rowOffsetX.value, dockWidth.value, count); }) .onTouchesUp((e) => { const idx = e.allTouches.length > 0 ? touchToIndex(e.allTouches[0].x - rowOffsetX.value, dockWidth.value, count) : activeIndex.value; if (idx >= -0.5) runOnJS(fireTap)(idx); isActive.value = withSpring(0, SETTLE_SPRING); }) .onTouchesCancelled((_e, manager) => { isActive.value = withSpring(0, SETTLE_SPRING); manager.end(); }) .shouldCancelWhenOutside(false), [activeIndex, isActive, dockWidth, rowOffsetX, count, fireTap] ); const handleRowLayout = (e: LayoutChangeEvent) => { dockWidth.value = e.nativeEvent.layout.width; rowOffsetX.value = e.nativeEvent.layout.x; }; return ( {items.map((item, index) => ( ))} ); } function DockIcon({ item, index, count, activeIndex, isActive, itemSize, gap, inputRange, outputRange, showLabel, }: { item: DockItem; index: number; count: number; activeIndex: SharedValue; isActive: SharedValue; itemSize: number; gap: number; inputRange: number[]; outputRange: number[]; showLabel: boolean; }) { // The wrapper's own width/height grow into the flex row (which is // bottom-aligned via `items-end`), so the slot itself pushes upward. const wrapperStyle = useAnimatedStyle(() => { const size = iconSize(index, count, activeIndex.value, isActive.value, itemSize, inputRange, outputRange); return { width: size, height: size }; }); // The icon inside is a fixed-size box scaled via transform. RN scales // around the center, which would grow the icon downward too — translateY // cancels exactly that downward half so growth reads as upward-only. const iconStyle = useAnimatedStyle(() => { const size = iconSize(index, count, activeIndex.value, isActive.value, itemSize, inputRange, outputRange); const scale = size / itemSize; return { transform: [{ translateY: -(itemSize * (scale - 1)) / 2 }, { scale }] }; }); const tooltipStyle = useAnimatedStyle(() => { const distance = Math.abs(activeIndex.value - index); const opacity = isActive.value * interpolate(distance, TOOLTIP_INPUT, TOOLTIP_OPACITY_OUTPUT, Extrapolation.CLAMP); const translateY = interpolate(isActive.value, ISACTIVE_INPUT, TOOLTIP_TRANSLATE_OUTPUT); return { opacity, transform: [{ translateY }] }; }); return ( {showLabel && ( {item.label} )} {item.icon} ); } ``` ## MorphFab - key: `morph-fab` - import: `import { MorphFab } from "@/components/ui/morph-fab"` - description: Skia gooey radial/directional FAB menu with staggered blob-merge spring animation - tier: 4 - deps: @shopify/react-native-skia, react-native-reanimated, lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/morph-fab.tsx import React, { createContext, useCallback, useContext, useEffect, useId, useMemo, useState, } from "react"; import { Dimensions, Pressable, Text, View, type LayoutChangeEvent } from "react-native"; import { Blur, Canvas, ColorMatrix, Group, Paint, RoundedRect } from "@shopify/react-native-skia"; import Animated, { Extrapolation, interpolate, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { Plus } from "lucide-react-native"; import { cn } from "@/lib/utils"; type MorphFabDirection = "up" | "down" | "left" | "right"; type MorphFabAlign = "start" | "center" | "end"; type MorphFabRect = { x: number; y: number; w: number; h: number; r: number }; type MorphFabItemEntry = { id: string; w: number; h: number; color?: string }; type MorphFabGeo = { layerW: number; layerH: number; left: number; top: number; fab: MorphFabRect; slots: MorphFabRect[]; }; const OPEN_SPRING: WithSpringConfig = { stiffness: 140, damping: 17, mass: 0.45 }; const CLOSE_SPRING: WithSpringConfig = { stiffness: 170, damping: 20, mass: 0.45 }; const PRESS_IN_SPRING: WithSpringConfig = { stiffness: 150, damping: 14, mass: 0.5 }; const PRESS_OUT_SPRING: WithSpringConfig = { stiffness: 260, damping: 16, mass: 0.5 }; // Alpha-threshold ColorMatrix: sharpens a blurred layer's alpha channel so // nearby blurred shapes visually fuse into one blob instead of overlapping // translucently — the same metaball technique used elsewhere in this family. const GOO_MATRIX = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 22, -11]; const LAYER_PADDING = 36; function clampRadius(r: number, w: number, h: number) { return Math.max(0, Math.min(r, Math.min(w, h) / 2)); } function crossOffset(align: MorphFabAlign, span: number, itemSpan: number) { if (align === "start") return 0; if (align === "end") return span - itemSpan; return (span - itemSpan) / 2; } function buildGeo( triggerW: number, triggerH: number, items: MorphFabItemEntry[], direction: MorphFabDirection, align: MorphFabAlign, sideOffset: number, spacing: number, itemRadius: number, triggerRadius: number, ): MorphFabGeo { const empty: MorphFabGeo = { layerW: 0, layerH: 0, left: 0, top: 0, fab: { x: 0, y: 0, w: 0, h: 0, r: 0 }, slots: [], }; if (triggerW <= 0 || triggerH <= 0) return empty; const vertical = direction === "up" || direction === "down"; const slots: MorphFabRect[] = []; let run = sideOffset; for (const item of items) { const r = clampRadius(itemRadius, item.w, item.h); let x = 0; let y = 0; if (direction === "up") { x = crossOffset(align, triggerW, item.w); y = -(run + item.h); } else if (direction === "down") { x = crossOffset(align, triggerW, item.w); y = triggerH + run; } else if (direction === "left") { x = -(run + item.w); y = crossOffset(align, triggerH, item.h); } else { x = triggerW + run; y = crossOffset(align, triggerH, item.h); } slots.push({ x, y, w: item.w, h: item.h, r }); run += (vertical ? item.h : item.w) + spacing; } let minX = 0; let minY = 0; let maxX = triggerW; let maxY = triggerH; for (const slot of slots) { minX = Math.min(minX, slot.x); minY = Math.min(minY, slot.y); maxX = Math.max(maxX, slot.x + slot.w); maxY = Math.max(maxY, slot.y + slot.h); } return { left: minX - LAYER_PADDING, top: minY - LAYER_PADDING, layerW: maxX - minX + LAYER_PADDING * 2, layerH: maxY - minY + LAYER_PADDING * 2, fab: { x: 0, y: 0, w: triggerW, h: triggerH, r: clampRadius(triggerRadius, triggerW, triggerH) }, slots, }; } function itemProgress(p: number, index: number, count: number, stagger: number) { "worklet"; const span = Math.max(0.0001, 1 - stagger * Math.max(0, count - 1)); const t = (p - index * stagger) / span; return t < 0 ? 0 : t > 1 ? 1 : t; } function slotAt(geo: MorphFabGeo, index: number, p: number): MorphFabRect { "worklet"; const fab = geo.fab; const slot = geo.slots[index]; if (!slot) return fab; const lerp = (a: number, b: number) => a + (b - a) * p; return { x: lerp(fab.x, slot.x), y: lerp(fab.y, slot.y), w: lerp(fab.w, slot.w), h: lerp(fab.h, slot.h), r: lerp(fab.r, slot.r), }; } type MorphFabContextValue = { open: boolean; toggle: () => void; setOpen: (open: boolean) => void; progress: SharedValue; triggerScale: SharedValue; items: MorphFabItemEntry[]; registerItem: (id: string, color?: string) => void; unregisterItem: (id: string) => void; updateItem: (id: string, w: number, h: number) => void; selectItem: (value: string | undefined, onSelect?: (value?: string) => void) => void; geo: MorphFabGeo; stagger: number; itemPadding: number; itemGap: number; }; const MorphFabContext = createContext(null); function useMorphFabContext(component: string) { const ctx = useContext(MorphFabContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } export interface MorphFabProps { children: React.ReactNode; className?: string; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; direction?: MorphFabDirection; align?: MorphFabAlign; sideOffset?: number; spacing?: number; itemRadius?: number; itemPadding?: number; itemGap?: number; triggerRadius?: number; triggerColor?: string; itemColor?: string; gooStrength?: number; stagger?: number; closeOnSelect?: boolean; dismissOnOutsidePress?: boolean; } /** Root: a Skia goo layer merges the trigger + item blobs, while real * Pressable content sits on top so taps, accessibility, and layout stay * ordinary React Native — the canvas is purely a visual metaball behind it. */ export function MorphFab({ children, className, open: controlledOpen, defaultOpen = false, onOpenChange, direction = "up", align = "center", sideOffset = 16, spacing = 12, itemRadius = 999, itemPadding = 16, itemGap = 10, triggerRadius = 999, triggerColor = "#18181b", itemColor = "#27272a", gooStrength = 9, stagger = 0.1, closeOnSelect = true, dismissOnOutsidePress = true, }: MorphFabProps) { const isControlled = controlledOpen !== undefined; const [uncontrolled, setUncontrolled] = useState(defaultOpen); const open = isControlled ? controlledOpen : uncontrolled; const progress = useSharedValue(defaultOpen ? 1 : 0); const triggerScale = useSharedValue(1); const [triggerSize, setTriggerSize] = useState({ w: 0, h: 0 }); const [items, setItems] = useState([]); const setOpen = useCallback( (next: boolean) => { if (!isControlled) setUncontrolled(next); onOpenChange?.(next); }, [isControlled, onOpenChange], ); const toggle = useCallback(() => setOpen(!open), [open, setOpen]); const selectItem = useCallback( (value?: string, onSelect?: (value?: string) => void) => { onSelect?.(value); if (closeOnSelect) setOpen(false); }, [closeOnSelect, setOpen], ); useEffect(() => { progress.value = withSpring(open ? 1 : 0, open ? OPEN_SPRING : CLOSE_SPRING); }, [open, progress]); const registerItem = useCallback((id: string, color?: string) => { setItems((prev) => (prev.some((i) => i.id === id) ? prev : [...prev, { id, w: 0, h: 0, color }])); }, []); const unregisterItem = useCallback((id: string) => { setItems((prev) => prev.filter((i) => i.id !== id)); }, []); const updateItem = useCallback((id: string, w: number, h: number) => { setItems((prev) => prev.map((i) => (i.id === id && (Math.abs(i.w - w) > 0.5 || Math.abs(i.h - h) > 0.5) ? { ...i, w, h } : i)), ); }, []); const geo = useMemo( () => buildGeo(triggerSize.w, triggerSize.h, items, direction, align, sideOffset, spacing, itemRadius, triggerRadius), [triggerSize, items, direction, align, sideOffset, spacing, itemRadius, triggerRadius], ); const ready = geo.layerW > 0 && items.every((i) => i.w > 0 && i.h > 0); const ctx = useMemo( () => ({ open, toggle, setOpen, progress, triggerScale, items, registerItem, unregisterItem, updateItem, selectItem, geo, stagger, itemPadding, itemGap, }), [open, toggle, setOpen, progress, triggerScale, items, registerItem, unregisterItem, updateItem, selectItem, geo, stagger, itemPadding, itemGap], ); const cx = geo.fab.x + geo.fab.w / 2; const cy = geo.fab.y + geo.fab.h / 2; const fx = useDerivedValue(() => cx - (geo.fab.w * triggerScale.value) / 2, [geo]); const fy = useDerivedValue(() => cy - (geo.fab.h * triggerScale.value) / 2, [geo]); const fw = useDerivedValue(() => geo.fab.w * triggerScale.value, [geo]); const fh = useDerivedValue(() => geo.fab.h * triggerScale.value, [geo]); const fr = useDerivedValue(() => geo.fab.r * triggerScale.value, [geo]); const { width: screenW, height: screenH } = Dimensions.get("window"); return ( {open && dismissOnOutsidePress ? ( setOpen(false)} style={{ position: "absolute", left: -screenW, top: -screenH, width: screenW * 2, height: screenH * 2, zIndex: 5 }} /> ) : null} {ready ? ( } > {items.map((item, index) => ( ))} ) : null} { const { width, height } = e.nativeEvent.layout; setTriggerSize((prev) => (prev.w === width && prev.h === height ? prev : { w: width, h: height })); }} style={{ alignSelf: "flex-start", zIndex: 10 }} > {children} ); } function MorphFabBlob({ index, count, geo, progress, stagger, color, }: { index: number; count: number; geo: MorphFabGeo; progress: SharedValue; stagger: number; color: string; }) { const rect = useDerivedValue( () => slotAt(geo, index, itemProgress(progress.value, index, count, stagger)), [geo, index, count, stagger], ); const x = useDerivedValue(() => rect.value.x); const y = useDerivedValue(() => rect.value.y); const w = useDerivedValue(() => rect.value.w); const h = useDerivedValue(() => rect.value.h); const r = useDerivedValue(() => rect.value.r); return ; } export interface MorphFabTriggerProps extends Omit, "children"> { children?: React.ReactNode; className?: string; size?: number; pressScale?: number; rotate?: number; } export function MorphFabTrigger({ children, className, size = 60, pressScale = 0.94, rotate = 45, ...props }: MorphFabTriggerProps) { const { toggle, open, progress, triggerScale } = useMorphFabContext("MorphFabTrigger"); const pressStyle = useAnimatedStyle(() => ({ transform: [{ scale: triggerScale.value }] })); const iconStyle = useAnimatedStyle(() => ({ transform: [{ rotate: `${interpolate(progress.value, [0, 1], [0, rotate])}deg` }], })); return ( { triggerScale.value = withSpring(pressScale, PRESS_IN_SPRING); }} onPressOut={() => { triggerScale.value = withSpring(1, PRESS_OUT_SPRING); }} accessible={true} accessibilityRole="button" accessibilityState={{ expanded: open }} className={cn("min-h-12 min-w-12 items-center justify-center", className)} style={{ width: size, height: size, borderRadius: size / 2 }} {...props} > {children ?? } ); } export interface MorphFabItemProps extends React.ComponentPropsWithoutRef { className?: string; value?: string; disabled?: boolean; onSelect?: (value?: string) => void; color?: string; pressScale?: number; } export function MorphFabItem({ children, className, value, disabled = false, onSelect, color, pressScale = 0.92, ...props }: MorphFabItemProps) { const id = useId(); const { items, registerItem, unregisterItem, updateItem, selectItem, geo, progress, stagger, open, itemPadding, itemGap } = useMorphFabContext("MorphFabItem"); const index = items.findIndex((i) => i.id === id); const count = items.length; const slot = index >= 0 ? geo.slots[index] : undefined; const pressed = useSharedValue(0); useEffect(() => { registerItem(id, color); return () => unregisterItem(id); }, [id, registerItem, unregisterItem, color]); const animatedStyle = useAnimatedStyle(() => { const t = index < 0 ? 0 : itemProgress(progress.value, index, count, stagger); const target = geo.slots[index] ?? geo.fab; const dx = geo.fab.x + geo.fab.w / 2 - (target.x + target.w / 2); const dy = geo.fab.y + geo.fab.h / 2 - (target.y + target.h / 2); return { opacity: interpolate(t, [0, 0.55, 1], [0, 0, 1], Extrapolation.CLAMP), transform: [ { translateX: dx * (1 - t) }, { translateY: dy * (1 - t) }, { scale: interpolate(t, [0, 1], [0.6, 1], Extrapolation.CLAMP) * interpolate(pressed.value, [0, 1], [1, pressScale]) }, ], }; }, [geo, index, count, stagger, pressScale]); return ( updateItem(id, e.nativeEvent.layout.width, e.nativeEvent.layout.height)} pointerEvents={open ? "box-none" : "none"} style={[{ position: "absolute", left: slot?.x ?? 0, top: slot?.y ?? 0, zIndex: 10 }, animatedStyle]} > selectItem(value, onSelect)} onPressIn={() => { pressed.value = withSpring(1, PRESS_IN_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, PRESS_OUT_SPRING); }} accessible={true} accessibilityRole="button" accessibilityState={{ disabled }} className={cn("min-h-12 min-w-12 flex-row items-center justify-center", className)} style={{ padding: itemPadding, gap: itemGap }} {...props} > {children} ); } export interface MorphFabItemIconProps { children: React.ReactNode; className?: string; } export function MorphFabItemIcon({ children, className }: MorphFabItemIconProps) { return {children}; } export interface MorphFabItemLabelProps { children: React.ReactNode; className?: string; } export function MorphFabItemLabel({ children, className }: MorphFabItemLabelProps) { return ( {children} ); } ``` ## MorphingTabBar - key: `morphing-tabbar` - import: `import { MorphingTabBar } from "@/components/ui/morphing-tabbar"` - description: Segmented tab bar where each tab's own corner radii and spacing morph to split the active tab into a separated pill - tier: 2 - deps: react-native-reanimated, expo-haptics, clsx, tailwind-merge ```tsx // components/ui/morphing-tabbar.tsx import React, { useEffect, useRef } from "react"; import { Pressable, Text, View } from "react-native"; import Animated, { Easing, Extrapolation, interpolate, useAnimatedStyle, useSharedValue, withTiming, type SharedValue, } from "react-native-reanimated"; import * as Haptics from "expo-haptics"; import { cn } from "@/lib/utils"; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); const GAP = 8; const MORPH_EASING = Easing.bezier(0.4, 0, 0.2, 1); export type MorphTab = { key: string; label: string; icon?: React.ReactNode }; export interface MorphingTabBarProps extends React.ComponentPropsWithoutRef { className?: string; tabs: MorphTab[]; activeKey: string; onTabPress: (key: string) => void; /** Corner radius each tab morphs toward when it becomes (or borders) the active tab. */ borderRadius?: number; animationDuration?: number; } /** * One corner-pair's animated radius for a single tab edge (left or right), driven by whether * this tab was/will be the active one, or merely sits beside the tab that was/will be active — * so the bar visually splits apart around the active tab instead of sliding a pill behind it. */ function morphRadius( progress: number, radius: number, willBeActive: boolean, wasActive: boolean, wasAdjacentToActive: boolean, willBeAdjacentToActive: boolean ) { "worklet"; if (willBeActive) { const from = wasActive || wasAdjacentToActive ? radius : 0; return interpolate(progress, [0, 1], [from, radius], Extrapolation.CLAMP); } if (wasActive) { const to = willBeAdjacentToActive ? radius : 0; return interpolate(progress, [0, 1], [radius, to], Extrapolation.CLAMP); } const from = wasAdjacentToActive ? radius : 0; const to = willBeAdjacentToActive ? radius : 0; return from === to ? from : interpolate(progress, [0, 1], [from, to], Extrapolation.CLAMP); } export function MorphingTabBar({ className, tabs, activeKey, onTabPress, borderRadius = 12, animationDuration = 300, ...props }: MorphingTabBarProps) { const activeIndex = tabs.findIndex((t) => t.key === activeKey); const previousIndex = useSharedValue(activeIndex); const progress = useSharedValue(1); const lastKey = useRef(activeKey); useEffect(() => { if (lastKey.current === activeKey) return; const fromIndex = tabs.findIndex((t) => t.key === lastKey.current); previousIndex.value = fromIndex === -1 ? activeIndex : fromIndex; progress.value = 0; progress.value = withTiming(1, { duration: animationDuration, easing: MORPH_EASING }); Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Soft); lastKey.current = activeKey; }, [activeKey, activeIndex, animationDuration, previousIndex, progress, tabs]); return ( {tabs.map((tab, index) => ( onTabPress(tab.key)} /> ))} ); } function MorphTabItem({ tab, index, isFirst, isLast, activeIndex, previousIndex, progress, borderRadius, selected, onPress, }: { tab: MorphTab; index: number; isFirst: boolean; isLast: boolean; activeIndex: number; previousIndex: SharedValue; progress: SharedValue; borderRadius: number; selected: boolean; onPress: () => void; }) { const style = useAnimatedStyle(() => { const p = progress.value; const prevIdx = previousIndex.value; const willBeActive = activeIndex === index; const wasActive = prevIdx === index; const left = morphRadius(p, borderRadius, willBeActive, wasActive, prevIdx === index - 1 || isFirst, activeIndex === index - 1 || isFirst); const right = morphRadius(p, borderRadius, willBeActive, wasActive, prevIdx === index + 1 || isLast, activeIndex === index + 1 || isLast); let marginHorizontal = 0; if (willBeActive && !wasActive) marginHorizontal = interpolate(p, [0, 1], [0, GAP]); else if (wasActive && !willBeActive) marginHorizontal = interpolate(p, [0, 1], [GAP, 0]); else if (willBeActive && wasActive) marginHorizontal = GAP; return { borderTopLeftRadius: left, borderBottomLeftRadius: left, borderTopRightRadius: right, borderBottomRightRadius: right, marginHorizontal, }; }); return ( {tab.icon} {tab.label} ); } ``` ## NumberInput - key: `number-input` - import: `import { NumberInput } from "@/components/ui/number-input"` - description: Numeric input with increment/decrement buttons and min/max - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/number-input.tsx import React, { useState, useCallback } from "react"; import { View, TextInput, Pressable, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { Minus, Plus } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const numberVariants = cva("flex-row items-center rounded-md border", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-2", md: "min-h-12 px-3", lg: "min-h-14 px-4", }, }, defaultVariants: { variant: "default", size: "md" }, }); export interface NumberInputProps extends Omit, "value" | "onChangeText">, VariantProps { className?: string; value?: number; onValueChange?: (value: number) => void; min?: number; max?: number; step?: number; } export const NumberInput = React.forwardRef< React.ElementRef, NumberInputProps >(function NumberInput( { variant, size, className, value: controlledValue, onValueChange, min = 0, max = 999999, step = 1, onBlur, ...props }, ref ) { const [internal, setInternal] = useState(controlledValue ?? min); const [text, setText] = useState(null); const value = controlledValue ?? internal; const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; // Matches `colors.muted` exactly, but that's a background-fill role, not one of // the four text/border roles this migration maps — left hardcoded (see report). const mutedIcon = colors.muted; const update = useCallback( (next: number) => { const clamped = Math.min(max, Math.max(min, next)); setInternal(clamped); onValueChange?.(clamped); }, [min, max, onValueChange] ); return ( { setText(null); update(value - step); }} disabled={value <= min} accessible={true} accessibilityRole="button" accessibilityLabel="Decrease" className="min-h-10 min-w-10 items-center justify-center" > { setText(t); const n = Number(t); if (t.trim() !== "" && !Number.isNaN(n)) update(n); }} onBlur={(e) => { setText(null); onBlur?.(e); }} accessibilityLabel="Number value" {...props} /> { setText(null); update(value + step); }} disabled={value >= max} accessible={true} accessibilityRole="button" accessibilityLabel="Increase" className="min-h-10 min-w-10 items-center justify-center" > = max ? mutedIcon : caret} strokeWidth={2.5} /> ); }); ``` ## Pagination - key: `pagination` - import: `import { Pagination } from "@/components/ui/pagination"` - description: Page navigation with numbered buttons and prev/next - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: button, theme-provider ```tsx // components/ui/pagination.tsx import React from "react"; import { View, Pressable, Text } from "react-native"; import { cn } from "@/lib/utils"; import { ChevronLeft, ChevronRight, Ellipsis } from "lucide-react-native"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface PaginationProps extends React.ComponentPropsWithoutRef { className?: string; total: number; current: number; onPageChange: (page: number) => void; siblings?: number; } function getPages(total: number, current: number, siblings: number): (number | "...")[] { const pages: (number | "...")[] = []; const start = Math.max(1, current - siblings); const end = Math.min(total, current + siblings); if (start > 1) { pages.push(1); if (start > 2) pages.push("..."); } for (let i = start; i <= end; i++) pages.push(i); if (end < total) { if (end < total - 1) pages.push("..."); pages.push(total); } return pages; } export function Pagination({ className, total, current, onPageChange, siblings = 1, ...props }: PaginationProps) { const pages = getPages(total, current, siblings); const colors = useThemeColors(); return ( onPageChange(current - 1)} disabled={current <= 1} accessible={true} accessibilityRole="button" accessibilityLabel="Previous page" className="min-h-10 min-w-10 items-center justify-center rounded-md" > {pages.map((page, i) => page === "..." ? ( ) : ( onPageChange(page)} accessible={true} accessibilityRole="button" accessibilityLabel={`Page ${page}`} accessibilityState={{ selected: page === current }} className={cn( "min-h-10 min-w-10 items-center justify-center rounded-md", page === current ? "bg-primary" : "bg-transparent" )} > {page} ) )} onPageChange(current + 1)} disabled={current >= total} accessible={true} accessibilityRole="button" accessibilityLabel="Next page" className="min-h-10 min-w-10 items-center justify-center rounded-md" > ); } ``` ## PasswordInput - key: `password-input` - import: `import { PasswordInput } from "@/components/ui/password-input"` - description: Password input with show/hide toggle and strength indicator - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: input, theme-provider ```tsx // components/ui/password-input.tsx import React, { useState } from "react"; import { View, TextInput, Pressable, Text, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { Eye, EyeOff } from "lucide-react-native"; const passwordVariants = cva( "flex-row items-center rounded-md border py-2 text-foreground", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-3", md: "min-h-12 px-4", lg: "min-h-14 px-5", }, }, defaultVariants: { variant: "default", size: "md" }, }, ); export interface PasswordInputProps extends Omit, "secureTextEntry">, VariantProps { className?: string; showStrength?: boolean; } function getStrength(value: string): number { let score = 0; if (value.length >= 8) score++; if (/[A-Z]/.test(value)) score++; if (/[0-9]/.test(value)) score++; if (/[^A-Za-z0-9]/.test(value)) score++; return score; } const strengthColors = [ "bg-destructive", "bg-orange-500", "bg-yellow-500", "bg-green-500", ]; const strengthLabels = ["Weak", "Fair", "Good", "Strong"]; export const PasswordInput = React.forwardRef< React.ElementRef, PasswordInputProps >(function PasswordInput( { variant, size, className, showStrength, onChangeText, ...props }, ref ) { const [visible, setVisible] = useState(false); const [value, setValue] = useState(""); const strength = getStrength(value); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; return ( { setValue(text); onChangeText?.(text); }} accessibilityLabel="Password" {...props} /> setVisible(!visible)} accessible={true} accessibilityRole="button" accessibilityLabel={visible ? "Hide password" : "Show password"} className="ms-2 min-h-8 min-w-8 items-center justify-center" hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}> {visible ? : } {showStrength && value.length > 0 && ( {[0, 1, 2, 3].map((i) => ( ))} {strengthLabels[strength - 1] ?? ""} )} ); }); ``` ## PhoneInput - key: `phone-input` - import: `import { PhoneInput } from "@/components/ui/phone-input"` - description: Phone number input with country code selector - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: input, masked-input, theme-provider ```tsx // components/ui/phone-input.tsx import React, { useState, useCallback } from "react"; import { View, TextInput, Pressable, Text, ScrollView, Modal, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { ChevronDown } from "lucide-react-native"; const phoneVariants = cva("flex-row items-center rounded-md border", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, size: { sm: "min-h-9 px-3", md: "min-h-12 px-4", lg: "min-h-14 px-5", }, }, defaultVariants: { variant: "default", size: "md" }, }); type Country = { code: string; dial: string; name: string }; const countries: Country[] = [ { code: "US", dial: "+1", name: "United States" }, { code: "GB", dial: "+44", name: "United Kingdom" }, { code: "IN", dial: "+91", name: "India" }, { code: "CA", dial: "+1", name: "Canada" }, { code: "AU", dial: "+61", name: "Australia" }, { code: "DE", dial: "+49", name: "Germany" }, { code: "FR", dial: "+33", name: "France" }, { code: "JP", dial: "+81", name: "Japan" }, { code: "BR", dial: "+55", name: "Brazil" }, { code: "MX", dial: "+52", name: "Mexico" }, ]; export interface PhoneInputProps extends Omit, "onChangeText" | "value">, VariantProps { className?: string; defaultCountry?: string; value?: string; onChangeText?: (fullPhone: string) => void; } export const PhoneInput = React.forwardRef< React.ElementRef, PhoneInputProps >(function PhoneInput( { variant, size, className, defaultCountry = "US", value, onChangeText, ...props }, ref ) { const [country, setCountry] = useState(countries.find((c) => c.code === defaultCountry) ?? countries[0]); const [open, setOpen] = useState(false); const [internal, setInternal] = useState(""); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; // Internal state is the fallback when no `value` prop is wired (uncontrolled usage) const fullPhone = value ?? internal; // Strip the dial code prefix to get just the number for display const rawNumber = fullPhone.startsWith(country.dial) ? fullPhone.slice(country.dial.length) : fullPhone.replace(/^\+\d+/, ""); const handleChange = useCallback( (text: string) => { const digits = text.replace(/\D/g, ""); const full = `${country.dial}${digits}`; setInternal(full); onChangeText?.(full); }, [country, onChangeText] ); return ( setOpen(true)} accessible={true} accessibilityRole="button" accessibilityLabel={`Country: ${country.name}`} className="flex-row items-center me-2 pe-2 border-e border-border min-h-8" > {country.dial} setOpen(false)}> setOpen(false)}> {countries.map((c) => ( { setCountry(c); setOpen(false); }} accessibilityRole="button" > {c.name} {c.dial} ))} ); }); ``` ## PhotoStack - key: `photo-stack` - import: `import { PhotoStack } from "@/components/ui/photo-stack"` - description: Overlapping stacked photos with a press-lift-and-straighten spring, and optional per-photo onPress - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/photo-stack.tsx import React from "react"; import { View, Image, Pressable } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring } from "react-native-reanimated"; import { cn } from "@/lib/utils"; export interface PhotoStackProps extends React.ComponentPropsWithoutRef { className?: string; sources: ({ uri: string } | number)[]; size?: number; maxVisible?: number; /** Called with the index of the photo that was pressed. Omit for a static, non-interactive stack. */ onPress?: (index: number) => void; } const LIFT = 10; const LIFT_SPRING = { damping: 16, stiffness: 220, mass: 0.6 }; // Static fan-out per stack position (translateX + base rotation + stacking // order). Press only adds a lift (translateY) and straightens the rotation // toward 0deg on top of these — it never touches translateX. const offsets = [ { rotateDeg: -8, translateX: -12, translateY: 4, zIndex: 1 }, { rotateDeg: 4, translateX: 0, translateY: 0, zIndex: 2 }, { rotateDeg: 10, translateX: 12, translateY: -4, zIndex: 3 }, ]; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); interface PhotoStackFrameProps { source: { uri: string } | number; size: number; offset: (typeof offsets)[number]; onPress?: () => void; } // One frame per photo — each needs its own `pressed` shared value, so this // has to be its own component (hooks can't be called inside the .map() below). function PhotoStackFrame({ source, size, offset, onPress }: PhotoStackFrameProps) { const pressed = useSharedValue(0); const liftStyle = useAnimatedStyle(() => ({ zIndex: offset.zIndex, transform: [ { translateX: offset.translateX }, { translateY: offset.translateY - LIFT * pressed.value }, { rotate: `${offset.rotateDeg * (1 - pressed.value)}deg` }, ], })); if (!onPress) { return ( ); } return ( { pressed.value = withSpring(1, LIFT_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, LIFT_SPRING); }} > ); } export function PhotoStack({ className, sources, size = 88, maxVisible = 3, onPress, ...props }: PhotoStackProps) { const visible = sources.slice(0, maxVisible); const width = size + 24; return ( {visible.map((source, index) => ( onPress(index) : undefined} /> ))} ); } ``` ## PieChart - key: `pie-chart` - import: `import { PieChart } from "@/components/ui/pie-chart"` - description: Skia pie/donut chart with grow-in sweep, data morphing, and drag-to-select slice push-out - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip ```tsx // components/ui/pie-chart.tsx import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, LayoutChangeEvent } from "react-native"; import { Canvas, Path } from "@shopify/react-native-skia"; import Animated, { Easing, cancelAnimation, clamp, runOnJS, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; import { ChartTooltip } from "@/components/ui/chart-tooltip"; export interface PieChartSegment { value: number; color: string; label?: string; } export interface PieChartProps extends React.ComponentPropsWithoutRef { className?: string; data: PieChartSegment[]; height?: number; innerRadius?: number; showLabels?: boolean; startAngle?: number; endAngle?: number; onSliceChange?: (segment: PieChartSegment, index: number) => void; } // Entrance/morph state machine + drag-select tuning — mirrors the other // Skia-driven charts in this effort: a shared "grow" value gates how much of // the pie is revealed (mount / slice-count change), a shared "morph" value // blends between old and new sweep fractions (same-count value change). const GROW_DURATION = 900; const MORPH_DURATION = 550; const SPRING_CONFIG = { damping: 20, stiffness: 260, mass: 1 }; const ACTIVE_OFFSET = 10; const TAU = Math.PI * 2; const ANGLE_ORIGIN = -Math.PI / 2; // 0 rad points at 12 o'clock, not 3 o'clock const EPSILON = 1e-4; interface PieArc { start: number; end: number; mid: number; } interface PieSlice { value: number; fraction: number; } function lerp(from: number, to: number, progress: number): number { "worklet"; return from + (to - from) * progress; } function toRadians(deg: number): number { "worklet"; return (deg * Math.PI) / 180; } function normalizeAngle(angle: number): number { "worklet"; const wrapped = angle % TAU; return wrapped < 0 ? wrapped + TAU : wrapped; } function polarPoint(cx: number, cy: number, r: number, angle: number) { "worklet"; const theta = ANGLE_ORIGIN + angle; return { x: cx + r * Math.cos(theta), y: cy + r * Math.sin(theta) }; } // Same washer/pie arc technique as the original static file, just rebuilt // from animated angles every frame instead of once. A slice whose sweep // covers the whole visible range is drawn as two half-arcs since SVG (and // Skia's SVG-string Path parser) can't express a true 360 degree single arc. function buildSlicePath(cx: number, cy: number, outerR: number, innerR: number, start: number, end: number): string { "worklet"; const sweep = end - start; if (outerR <= 0 || sweep <= EPSILON) return "M 0 0"; const inner = Math.min(Math.max(innerR, 0), outerR); if (sweep >= TAU - EPSILON) { const outerTop = polarPoint(cx, cy, outerR, 0); const outerBottom = polarPoint(cx, cy, outerR, Math.PI); let path = `M ${outerTop.x} ${outerTop.y} ` + `A ${outerR} ${outerR} 0 1 1 ${outerBottom.x} ${outerBottom.y} ` + `A ${outerR} ${outerR} 0 1 1 ${outerTop.x} ${outerTop.y} Z`; if (inner > 0) { const innerTop = polarPoint(cx, cy, inner, 0); const innerBottom = polarPoint(cx, cy, inner, Math.PI); path += ` M ${innerTop.x} ${innerTop.y} ` + `A ${inner} ${inner} 0 1 0 ${innerBottom.x} ${innerBottom.y} ` + `A ${inner} ${inner} 0 1 0 ${innerTop.x} ${innerTop.y} Z`; } return path; } const large = sweep > Math.PI ? 1 : 0; const outerStart = polarPoint(cx, cy, outerR, start); const outerEnd = polarPoint(cx, cy, outerR, end); if (inner <= 0) { return ( `M ${cx} ${cy} L ${outerStart.x} ${outerStart.y} ` + `A ${outerR} ${outerR} 0 ${large} 1 ${outerEnd.x} ${outerEnd.y} Z` ); } const innerEnd = polarPoint(cx, cy, inner, end); const innerStart = polarPoint(cx, cy, inner, start); return ( `M ${outerStart.x} ${outerStart.y} ` + `A ${outerR} ${outerR} 0 ${large} 1 ${outerEnd.x} ${outerEnd.y} ` + `L ${innerEnd.x} ${innerEnd.y} ` + `A ${inner} ${inner} 0 ${large} 0 ${innerStart.x} ${innerStart.y} Z` ); } function indexForAngle(spans: number[], angle: number): number { "worklet"; for (let i = 0; i < spans.length - 1; i++) { if (angle >= spans[i] && angle < spans[i + 1]) return i; } return -1; } function computeSlices(data: PieChartSegment[]): PieSlice[] { let total = 0; for (const d of data) total += Math.max(d.value, 0); const safeTotal = total || 1; return data.map((d) => { const value = Math.max(d.value, 0); return { value, fraction: value / safeTotal }; }); } interface PieSliceViewProps { index: number; color: string; centerX: number; centerY: number; outerRadius: number; innerRadius: number; arcs: SharedValue; selectedIndex: SharedValue; isActive: SharedValue; } // One memoized Path per slice: reads its own angle span out of the shared // `arcs` array every frame and, when selected, slides its effective center // outward along its own bisector before rebuilding the arc path. const PieSliceView = memo(function PieSliceView({ index, color, centerX, centerY, outerRadius, innerRadius, arcs, selectedIndex, isActive, }: PieSliceViewProps) { const selection = useDerivedValue(() => withSpring(selectedIndex.value === index ? 1 : 0, SPRING_CONFIG), [index]); const path = useDerivedValue(() => { const arc = arcs.value[index]; if (!arc) return "M 0 0"; const push = selection.value * isActive.value * ACTIVE_OFFSET; const theta = ANGLE_ORIGIN + arc.mid; const cx = centerX + Math.cos(theta) * push; const cy = centerY + Math.sin(theta) * push; return buildSlicePath(cx, cy, outerRadius, innerRadius, arc.start, arc.end); }, [index, centerX, centerY, outerRadius, innerRadius]); return ; }); export function PieChart({ className, data, height = 200, innerRadius = 0, showLabels = false, startAngle = 0, endAngle = 360, onSliceChange, ...props }: PieChartProps) { const [width, setWidth] = useState(0); const [activeIndex, setActiveIndex] = useState(-1); const onLayout = (e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width); const hasEntered = useRef(false); const size = Math.min(width, height); const centerX = width / 2; const centerY = height / 2; const outerR = Math.max(size / 2 - 10, 0); const innerRPx = outerR * innerRadius; const startRadians = toRadians(startAngle); const rangeRadians = toRadians(endAngle - startAngle); const slices = useMemo(() => computeSlices(data), [data]); const spans = useMemo(() => { const out: number[] = [0]; let cursor = 0; for (const slice of slices) { cursor += slice.fraction * rangeRadians; out.push(cursor); } return out; }, [slices, rangeRadians]); const originFractions = useSharedValue([]); const targetFractions = useSharedValue([]); const spansShared = useSharedValue([0]); const morph = useSharedValue(1); const grow = useSharedValue(0); const isActive = useSharedValue(0); const selectedIndex = useSharedValue(-1); const cardWidth = useSharedValue(0); const cardHeight = useSharedValue(0); useEffect(() => { spansShared.value = spans; }, [spans, spansShared]); const isMeasured = width > 0 && height > 0; useEffect(() => { if (!isMeasured || data.length === 0) return; const fractions = slices.map((s) => s.fraction); const isEntrance = !hasEntered.current; hasEntered.current = true; if (isEntrance || targetFractions.value.length !== fractions.length) { originFractions.value = fractions; targetFractions.value = fractions; cancelAnimation(morph); morph.value = 1; cancelAnimation(grow); grow.value = 0; grow.value = withTiming(1, { duration: GROW_DURATION, easing: Easing.out(Easing.cubic) }); return; } const from = originFractions.value; const to = targetFractions.value; const progress = morph.value; originFractions.value = fractions.map((_, i) => lerp(from[i] ?? 0, to[i] ?? 0, progress)); targetFractions.value = fractions; cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [data, isMeasured, slices]); const arcs = useDerivedValue(() => { const origin = originFractions.value; const target = targetFractions.value; const count = Math.max(origin.length, target.length); const limit = grow.value * rangeRadians; const out: PieArc[] = []; let cursor = 0; for (let i = 0; i < count; i++) { const sweep = lerp(origin[i] ?? 0, target[i] ?? 0, morph.value) * rangeRadians; const rawStart = cursor; const rawEnd = cursor + sweep; cursor = rawEnd; const start = Math.min(rawStart, limit); const end = Math.min(rawEnd, limit); out.push({ start: startRadians + start, end: startRadians + end, mid: startRadians + (rawStart + rawEnd) / 2, }); } return out; }, [rangeRadians, startRadians]); const reportSlice = useCallback( (index: number) => { setActiveIndex(index); const segment = data[index]; if (segment) onSliceChange?.(segment, index); }, [data, onSliceChange] ); const gesture = useMemo(() => { const resolveIndex = (x: number, y: number) => { "worklet"; const distance = Math.hypot(x - centerX, y - centerY); const inside = distance >= innerRPx && distance <= outerR + ACTIVE_OFFSET; if (!inside) return -1; const angle = normalizeAngle(Math.atan2(y - centerY, x - centerX) - ANGLE_ORIGIN - startRadians); return indexForAngle(spansShared.value, angle); }; return Gesture.Pan() .minDistance(0) .onBegin((e) => { "worklet"; const index = resolveIndex(e.x, e.y); if (index !== selectedIndex.value) { selectedIndex.value = index; if (index >= 0) runOnJS(reportSlice)(index); } isActive.value = withTiming(index >= 0 ? 1 : 0, { duration: 140 }); }) .onUpdate((e) => { "worklet"; const index = resolveIndex(e.x, e.y); if (index !== selectedIndex.value) { selectedIndex.value = index; if (index >= 0) runOnJS(reportSlice)(index); isActive.value = withTiming(index >= 0 ? 1 : 0, { duration: 140 }); } }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; }); }, [centerX, centerY, outerR, innerRPx, startRadians, spansShared, selectedIndex, isActive, reportSlice]); const onTooltipLayout = useCallback( (e: LayoutChangeEvent) => { cardWidth.value = e.nativeEvent.layout.width; cardHeight.value = e.nativeEvent.layout.height; }, [cardWidth, cardHeight] ); const tooltipStyle = useAnimatedStyle(() => { const arc = arcs.value[selectedIndex.value]; if (!arc) return { opacity: 0 }; const midRadius = (outerR + innerRPx) / 2; const point = polarPoint(centerX, centerY, midRadius, arc.mid); const x = clamp(point.x - cardWidth.value / 2, 0, Math.max(width - cardWidth.value, 0)); const y = clamp(point.y - cardHeight.value / 2, 0, Math.max(height - cardHeight.value, 0)); return { opacity: isActive.value, transform: [{ translateX: withSpring(x, SPRING_CONFIG) }, { translateY: withSpring(y, SPRING_CONFIG) }], }; }); if (width === 0) { return ; } const activeSegment = activeIndex >= 0 ? data[activeIndex] : undefined; const activeSlice = activeIndex >= 0 ? slices[activeIndex] : undefined; return ( {data.map((segment, i) => ( ))} {showLabels && ( {slices.map((slice, i) => { if (slice.fraction <= 0) return null; const mid = startRadians + (spans[i] + spans[i + 1]) / 2; const labelR = innerRPx > 0 ? (outerR + innerRPx) / 2 : outerR * 0.65; const point = polarPoint(centerX, centerY, labelR, mid); return ( {data[i]?.label ?? `${Math.round(slice.fraction * 100)}%`} ); })} )} {activeSegment && ( )} ); } ``` ## Polaroid - key: `polaroid` - import: `import { Polaroid } from "@/components/ui/polaroid"` - description: Polaroid-style photo frame with a press-lift-and-straighten spring and optional washi-tape decoration - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/polaroid.tsx import React from "react"; import { View, Text, Image, Pressable } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring } from "react-native-reanimated"; import { cn } from "@/lib/utils"; const TILT = -2; const LIFT = 6; const LIFT_SPRING = { damping: 16, stiffness: 220, mass: 0.6 }; export interface PolaroidTapeProps extends React.ComponentPropsWithoutRef { className?: string; width?: number; height?: number; rotate?: number; } // Decorative "washi tape" strip straddling the top edge of a Polaroid. Purely // visual, so it must never intercept touches or be announced by a screen reader. export function PolaroidTape({ className, width = 96, height = 28, rotate = -3, ...props }: PolaroidTapeProps) { return ( ); } export interface PolaroidProps extends React.ComponentPropsWithoutRef { className?: string; source: { uri: string } | number; caption?: string; /** Small mono stamp under the caption, e.g. a date or location. */ meta?: string; /** Resting tilt in degrees; straightens toward 0deg at full press. */ tilt?: number; /** Renders a built-in across the top edge. */ tape?: boolean; /** Called on press. Omit for a static, non-interactive card. */ onPress?: () => void; } const AnimatedPressable = Animated.createAnimatedComponent(Pressable); export function Polaroid({ className, source, caption, meta, tilt = TILT, tape, onPress, ...props }: PolaroidProps) { const pressed = useSharedValue(0); const liftStyle = useAnimatedStyle(() => ({ transform: [{ translateY: -LIFT * pressed.value }, { rotate: `${tilt * (1 - pressed.value)}deg` }], })); const content = ( <> {tape ? : null} {caption ? {caption} : null} {meta ? {meta} : null} ); if (!onPress) { return ( {content} ); } return ( { pressed.value = withSpring(1, LIFT_SPRING); }} onPressOut={() => { pressed.value = withSpring(0, LIFT_SPRING); }} {...props} > {content} ); } ``` ## Popover - key: `popover` - import: `import { Popover } from "@/components/ui/popover"` - description: Contextual overlay with trigger positioning - tier: 3 - deps: @rn-primitives/popover, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/popover.tsx import React from "react"; import { View, Pressable } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import * as PopoverPrimitive from "@rn-primitives/popover"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; export interface PopoverProps { onOpenChange?: (open: boolean) => void; children: React.ReactNode; } // @rn-primitives' Popover Root is uncontrolled — see context-menu.tsx. export function Popover({ onOpenChange, children }: PopoverProps) { return {children}; } export interface PopoverTriggerProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function PopoverTrigger({ className, children, ...props }: PopoverTriggerProps) { return ( {/* rn-primitives measures this exact box to position PopoverContent below it — min-h-12/min-w-12 would force a 48x48 measured box even when the child is a small icon, opening the content ~48px below the trigger's top edge instead of just past the icon. hitSlop expands the tappable area to the 48dp minimum without inflating what gets measured. */} {children} ); } export interface PopoverContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; // Primitive only supports vertical sides. side?: "top" | "bottom"; sideOffset?: number; align?: "start" | "center" | "end"; } export function PopoverContent({ className, children, side = "bottom", sideOffset = 8, align = "center", ...props }: PopoverContentProps) { const insets = useSafeAreaInsets(); const fold = useFoldFeatures(); // Teach the primitive's collision avoider about the fold line: treat it as // a right-side inset so the panel stays within one pane. Both left/right // kept as max(real inset, fold inset) so a trigger on the right pane also // gets clamped on its *left* side correctly. Null on non-fold devices. const foldInsets = fold.foldX ? { ...insets, left: Math.max(insets.left, fold.foldX), right: Math.max(insets.right, fold.foldX) } : insets; return ( {children} ); } export function PopoverClose({ children, className, ...props }: React.ComponentPropsWithoutRef & { className?: string; children?: React.ReactNode }) { return ( {children} ); } ``` ## Price - key: `price` - import: `import { Price } from "@/components/ui/price"` - description: Formatted currency display with locale and strikethrough support - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/price.tsx import React from "react"; import { View, Text } from "react-native"; import { cn } from "@/lib/utils"; export interface PriceProps extends React.ComponentPropsWithoutRef { className?: string; amount: number; currency?: string; locale?: string; strikethrough?: boolean; prefix?: string; textClassName?: string; } export function Price({ className, amount, currency = "USD", locale = "en-US", strikethrough, prefix, textClassName, ...props }: PriceProps) { const formatted = new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount); return ( {prefix && {prefix}} {formatted} ); } ``` ## ProfileCard - key: `profile-card` - import: `import { ProfileCard } from "@/components/ui/profile-card"` - description: Profile card with a cover image, overlapping avatar, location row, and a press-scale action button - tier: 2 - deps: react-native-reanimated, lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: avatar, badge ```tsx // components/ui/profile-card.tsx import React, { createContext, useContext } from "react"; import { View, Text, Image, Pressable, useColorScheme, type ImageSourcePropType, type GestureResponderEvent, } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withSpring } from "react-native-reanimated"; import { MapPin } from "lucide-react-native"; import { cn } from "@/lib/utils"; // Signature-look defaults, close to the reference design this component is // modeled after: a warm outline frame, a short cover band, and an avatar that // straddles the cover/body seam near the top-right corner. const CARD_RADIUS = 34; const OUTLINE_WIDTH = 10; const COVER_HEIGHT = 108; const COVER_BOTTOM_RADIUS = 20; const ACTION_RADIUS = 14; const AVATAR_SIZE = 60; const AVATAR_RADIUS = 18; const AVATAR_RING = 3; const AVATAR_INSET = 16; const AVATAR_OVERLAP = 0.45; export interface ProfileCardSpringConfig { damping: number; stiffness: number; mass: number; } const PRESS_SPRING: ProfileCardSpringConfig = { damping: 18, stiffness: 320, mass: 0.5 }; export interface ProfileCardPalette { surface: string; cover: string; name: string; handle: string; bio: string; location: string; action: string; actionLabel: string; avatarRing: string; outline: string; } const LIGHT_PALETTE: ProfileCardPalette = { surface: "#FAF7F0", cover: "#F4F4F5", name: "#18181B", handle: "#A1A1AA", bio: "#3F3F46", location: "#52525B", action: "#EDE9DD", actionLabel: "#18181B", avatarRing: "#FAF7F0", outline: "#FFFFFF", }; const DARK_PALETTE: ProfileCardPalette = { surface: "#131315", cover: "#1C1C1F", name: "#FAFAFA", handle: "#71717A", bio: "#D4D4D8", location: "#A1A1AA", action: "#26262A", actionLabel: "#FAFAFA", avatarRing: "#131315", outline: "#0B0B0C", }; interface ProfileCardContextValue { palette: ProfileCardPalette; coverHeight: number; springConfig: ProfileCardSpringConfig; } const ProfileCardContext = createContext(null); function useProfileCard() { const ctx = useContext(ProfileCardContext); if (!ctx) throw new Error("ProfileCard.* components must be rendered inside "); return ctx; } const AnimatedPressable = Animated.createAnimatedComponent(Pressable); // Root — the outline-frame construction: an outer View padded by // `outlineWidth` and filled with `palette.outline` sits behind an inner // surface View whose radius is exactly `radius - outlineWidth`, so the two // curves stay concentric no matter how the radius is customized. export interface ProfileCardProps extends React.ComponentPropsWithoutRef { className?: string; palette?: Partial; radius?: number; outlineWidth?: number; innerRadius?: number; coverHeight?: number; springConfig?: ProfileCardSpringConfig; children?: React.ReactNode; } export function ProfileCard({ className, palette, radius = CARD_RADIUS, outlineWidth = OUTLINE_WIDTH, innerRadius, coverHeight = COVER_HEIGHT, springConfig = PRESS_SPRING, children, ...props }: ProfileCardProps) { const isDark = useColorScheme() === "dark"; const resolvedPalette = { ...(isDark ? DARK_PALETTE : LIGHT_PALETTE), ...palette }; const resolvedInnerRadius = innerRadius ?? radius - outlineWidth; return ( {children} ); } // Cover — only the bottom corners round (the top corners are already square // against the surface's own rounded top edge from the outline frame above). export interface ProfileCardCoverProps extends React.ComponentPropsWithoutRef { className?: string; source?: ImageSourcePropType; bottomRadius?: number; children?: React.ReactNode; } export function ProfileCardCover({ className, source, bottomRadius = COVER_BOTTOM_RADIUS, children, ...props }: ProfileCardCoverProps) { const { palette, coverHeight } = useProfileCard(); return ( {source ? : null} {children} ); } // Avatar — the signature overlap math: with the default cover height (108), // size (60) and overlap share (0.45), `top = 108 - 60*0.55 = 75`, which // leaves 33px (55%) of the avatar sitting up inside the cover band and the // remaining 45% hanging down into the body below. export interface ProfileCardAvatarProps extends React.ComponentPropsWithoutRef { className?: string; source?: string; fallback?: string; size?: number; overlap?: number; inset?: number; radius?: number; ring?: number; } export function ProfileCardAvatar({ className, source, fallback, size = AVATAR_SIZE, overlap = AVATAR_OVERLAP, inset = AVATAR_INSET, radius = AVATAR_RADIUS, ring = AVATAR_RING, ...props }: ProfileCardAvatarProps) { const { palette, coverHeight } = useProfileCard(); const top = coverHeight - size * (1 - overlap); return ( {source ? ( ) : ( {fallback ?? "?"} )} ); } export interface ProfileCardBodyProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function ProfileCardBody({ className, children, ...props }: ProfileCardBodyProps) { return ( {children} ); } // Header — name + handle on a baseline-aligned row, combined into one export // rather than three separate Header/Name/Handle pieces. export interface ProfileCardHeaderProps extends React.ComponentPropsWithoutRef { className?: string; name: string; handle?: string; } export function ProfileCardHeader({ className, name, handle, ...props }: ProfileCardHeaderProps) { const { palette } = useProfileCard(); return ( {name} {handle ? ( {handle} ) : null} ); } export interface ProfileCardBioProps extends React.ComponentPropsWithoutRef { className?: string; children: string; } export function ProfileCardBio({ className, children, ...props }: ProfileCardBioProps) { const { palette } = useProfileCard(); return ( {children} ); } // Location — icon + text row; defaults to lucide's MapPin but accepts any // override via `icon` for a caller that wants a different glyph. export interface ProfileCardLocationProps extends React.ComponentPropsWithoutRef { className?: string; label: string; icon?: React.ReactNode; } export function ProfileCardLocation({ className, label, icon, ...props }: ProfileCardLocationProps) { const { palette } = useProfileCard(); return ( {icon ?? } {label} ); } // Action — a Pressable that springs to 0.97 scale on press-in and back to 1 // on press-out/press-cancel, driven by react-native-reanimated. export interface ProfileCardActionProps extends React.ComponentPropsWithoutRef { className?: string; label: string; radius?: number; } export function ProfileCardAction({ className, label, radius = ACTION_RADIUS, disabled, onPressIn, onPressOut, ...props }: ProfileCardActionProps) { const { palette, springConfig } = useProfileCard(); const scale = useSharedValue(1); const animatedStyle = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] })); return ( { scale.value = withSpring(0.97, springConfig); onPressIn?.(event); }} onPressOut={(event: GestureResponderEvent) => { scale.value = withSpring(1, springConfig); onPressOut?.(event); }} {...props} > {label} ); } ``` ## Progress - key: `progress` - import: `import { Progress } from "@/components/ui/progress"` - description: Progress bar - tier: 3 - deps: @rn-primitives/progress, clsx, tailwind-merge ```tsx // components/ui/progress.tsx import React from "react"; import { View } from "react-native"; import * as ProgressPrimitive from "@rn-primitives/progress"; import { cn } from "@/lib/utils"; export interface ProgressProps extends React.ComponentPropsWithoutRef { className?: string; value?: number; indicatorClassName?: string; } export function Progress({ value = 0, className, indicatorClassName, ...props }: ProgressProps) { const clampedValue = Math.min(100, Math.max(0, value)); return ( ); } ``` ## ProgressSteps - key: `progress-steps` - import: `import { ProgressSteps } from "@/components/ui/progress-steps"` - description: Multi-step progress indicator for wizards and onboarding - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/progress-steps.tsx import React, { createContext, useContext } from "react"; import { View, Text } from "react-native"; import { Check } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const StepsContext = createContext<{ current: number }>({ current: 0 }); export interface ProgressStepsProps extends React.ComponentPropsWithoutRef { className?: string; current: number; children?: React.ReactNode; } export function ProgressSteps({ current, className, children, ...props }: ProgressStepsProps) { return ( {React.Children.map(children, (child, index) => ( <> {index > 0 && ( )} {React.isValidElement(child) ? React.cloneElement(child as React.ReactElement<{ _index?: number }>, { _index: index }) : child} ))} ); } export interface ProgressStepProps extends React.ComponentPropsWithoutRef { className?: string; label?: string; icon?: React.ReactNode; _index?: number; } export function ProgressStep({ label, icon, className, _index = 0, ...props }: ProgressStepProps) { const { current } = useContext(StepsContext); const colors = useThemeColors(); const isCompleted = _index < current; const isActive = _index === current; return ( {icon ?? (isCompleted ? ( ) : ( {_index + 1} ))} {label && ( {label} )} ); } ``` ## PromptInput - key: `prompt-input` - import: `import { PromptInput } from "@/components/ui/prompt-input"` - description: ChatGPT/Claude-style AI composer — compound: PromptInput, Textarea, Toolbar, Button, Send (stop while streaming) - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/prompt-input.tsx import React, { createContext, useContext, useState } from "react"; import { View, TextInput, Pressable, useColorScheme } from "react-native"; import { ArrowUp, Square } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; // Compound composer (ChatGPT/Claude-style): textarea on top, toolbar below. // … type PromptInputCtx = { text: string; setText: (t: string) => void; send: () => void; streaming?: boolean; dark: boolean; colors: ReturnType; }; const Ctx = createContext(null); export function usePromptInput(): PromptInputCtx { const ctx = useContext(Ctx); if (!ctx) throw new Error("PromptInput.* components must be used inside "); return ctx; } export interface PromptInputProps extends React.ComponentPropsWithoutRef { className?: string; value?: string; onChangeText?: (text: string) => void; onSend?: (text: string) => void; /** While `streaming`, PromptInputSend becomes a stop button firing this. */ onStop?: () => void; streaming?: boolean; clearOnSend?: boolean; } export function PromptInput({ className, value, onChangeText, onSend, onStop, streaming, clearOnSend = true, children, ...props }: PromptInputProps) { const [internal, setInternal] = useState(""); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const text = value ?? internal; const setText = (t: string) => { if (value === undefined) setInternal(t); onChangeText?.(t); }; const send = () => { if (streaming) return onStop?.(); const t = text.trim(); if (!t) return; onSend?.(t); if (clearOnSend && value === undefined) setInternal(""); }; return ( {children} ); } export interface PromptInputTextareaProps extends Omit, "multiline" | "value" | "onChangeText"> { className?: string; /** Max height before the textarea scrolls (default 120). */ maxHeight?: number; } export const PromptInputTextarea = React.forwardRef< React.ElementRef, PromptInputTextareaProps >(function PromptInputTextarea({ className, maxHeight = 120, style, ...props }, ref) { const { text, setText, dark, colors } = usePromptInput(); const [height, setHeight] = useState(0); return ( setHeight(e.nativeEvent.contentSize.height)} // Grows with content up to maxHeight, then scrolls. Font size is inline // so the cursor stays centered on iOS (same convention as input.tsx). style={[{ fontSize: 16, maxHeight, height: Math.min(Math.max(24, height), maxHeight) }, style]} className={cn("p-0 text-foreground placeholder:text-muted-foreground", className)} placeholder="How can I help you today?" placeholderTextColor={colors.mutedForeground} keyboardAppearance={dark ? "dark" : "light"} selectionColor={colors.foreground} cursorColor={colors.foreground} // keep in sync with textarea.tsx's caret/placeholder colors textAlignVertical="top" {...props} /> ); }); export interface PromptInputToolbarProps extends React.ComponentPropsWithoutRef { className?: string; } /** Bottom action row — put leading tools first, then , then trailing tools. */ export function PromptInputToolbar({ className, ...props }: PromptInputToolbarProps) { return ; } export function PromptInputSpacer() { return ; } export interface PromptInputButtonProps extends React.ComponentPropsWithoutRef { className?: string; } /** Ghost icon button for toolbar actions (+, mic, model selector, …). */ export function PromptInputButton({ className, ...props }: PromptInputButtonProps) { return ( ); } export interface PromptInputSendProps extends React.ComponentPropsWithoutRef { className?: string; /** Shown when there is no text (e.g. a voice/waveform button); default hides into the send arrow. */ emptyFallback?: React.ReactNode; } export function PromptInputSend({ className, emptyFallback, ...props }: PromptInputSendProps) { const { text, send, streaming, colors } = usePromptInput(); const canSend = text.trim().length > 0; const fg = colors.primaryForeground; if (!canSend && !streaming && emptyFallback) return <>{emptyFallback}; return ( {streaming ? : } ); } ``` ## QrCode - key: `qr-code` - import: `import { QrCode } from "@/components/ui/qr-code"` - description: Real, scannable QR code behind an expand/collapse reveal with copy/close actions - tier: 3 - deps: react-native-qrcode-svg, react-native-svg, react-native-reanimated, lucide-react-native, clsx, tailwind-merge ```tsx // components/ui/qr-code.tsx import React, { useCallback, useState } from "react"; import { Pressable, Text, View, type ViewStyle } from "react-native"; import Animated, { ReduceMotion, interpolate, interpolateColor, useAnimatedStyle, useSharedValue, withSpring, type WithSpringConfig, } from "react-native-reanimated"; import QRCode from "react-native-qrcode-svg"; import { Copy, QrCodeIcon, X } from "lucide-react-native"; import { cn } from "@/lib/utils"; // Spring configs and interpolation ranges below drive the expand/collapse // reveal (stiffness/damping/mass + width/height/radius/color progress ranges); // the QR encoding itself comes from react-native-qrcode-svg. const SPRING_CONFIG: WithSpringConfig = { stiffness: 135, damping: 12.5, mass: 0.5, reduceMotion: ReduceMotion.System }; const PRESS_SPRING_CONFIG: WithSpringConfig = { stiffness: 250, damping: 30, mass: 0.5, reduceMotion: ReduceMotion.System }; const COLLAPSED_W = 200; const EXPANDED_W = 250; const COLLAPSED_H = 50; const EXPANDED_H = 320; const COLLAPSED_RADIUS = 100; const EXPANDED_RADIUS = 25; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); export interface QrCodeProps extends Omit, "style"> { className?: string; value: string; label?: string; size?: number; foreground?: string; background?: string; backgroundExpanded?: string; /** Called with `value` when the copy action is pressed. AniUI has no clipboard * dependency yet (none of components/ui/* needs it), so copying is left to the * consumer (e.g. `expo-clipboard`'s setStringAsync) instead of silently adding one. */ onCopy?: (value: string) => void; } function QrCodeActionButton({ onPress, accessibilityLabel, className, children, }: { onPress: () => void; accessibilityLabel: string; className?: string; children: React.ReactNode; }) { const press = useSharedValue(0); const pressStyle = useAnimatedStyle>(() => ({ transform: [{ scale: interpolate(press.value, [0, 1], [1, 1.1]) }], })); return ( { press.value = withSpring(1, PRESS_SPRING_CONFIG); }} onPressOut={() => { press.value = withSpring(0, PRESS_SPRING_CONFIG); }} accessible accessibilityRole="button" accessibilityLabel={accessibilityLabel} className={cn("min-h-12 min-w-12 flex-row items-center justify-center gap-2 rounded-full bg-white px-5", className)} style={pressStyle} > {children} ); } /** Interactive "Show QR Code" pill that springs open into a card with a real, * scannable QR code (react-native-qrcode-svg) plus copy/close actions. */ export function QrCode({ className, value, label = "Show QR Code", size = 190, foreground = "#18181b", background = "#eeedf4", backgroundExpanded = "#ffffff", onCopy, ...props }: QrCodeProps) { const [expanded, setExpanded] = useState(false); const progress = useSharedValue(expanded ? 1 : 0); const press = useSharedValue(0); const toggle = useCallback(() => { const next = progress.value === 1 ? 0 : 1; progress.value = withSpring(next, SPRING_CONFIG); setExpanded(next === 1); }, [progress]); const collapse = useCallback(() => { progress.value = withSpring(0, SPRING_CONFIG); setExpanded(false); }, [progress]); const handleCopy = useCallback(() => onCopy?.(value), [onCopy, value]); const containerStyle = useAnimatedStyle< Pick >(() => ({ width: interpolate(progress.value, [0, 1], [COLLAPSED_W, EXPANDED_W]), height: interpolate(progress.value, [0, 1], [COLLAPSED_H, EXPANDED_H]), borderRadius: interpolate(progress.value, [0, 1], [COLLAPSED_RADIUS, EXPANDED_RADIUS]), backgroundColor: interpolateColor(progress.value, [0, 1], [background, backgroundExpanded]), })); const pressStyle = useAnimatedStyle>(() => ({ transform: [{ scale: interpolate(press.value, [0, 1], [1, 1.5]) }], })); const labelStyle = useAnimatedStyle>(() => ({ opacity: interpolate(progress.value, [0, 1], [1, 0]), transform: [{ translateY: interpolate(progress.value, [0, 1], [0, 100]) }], })); const qrRevealStyle = useAnimatedStyle>(() => ({ opacity: interpolate(progress.value, [0, 0.5, 1], [0, 0.2, 1]), transform: [ { translateY: withSpring(interpolate(progress.value, [0, 0.5, 1], [0, -20, -30])) }, { scale: interpolate(progress.value, [0, 1], [0, 1]) }, ], })); const actionsStyle = useAnimatedStyle>(() => ({ opacity: interpolate(progress.value, [0, 1], [0, 1]), transform: [{ translateY: interpolate(progress.value, [0, 1], [0, 5]) }], })); return ( { press.value = withSpring(1, PRESS_SPRING_CONFIG); }} onPressOut={() => { press.value = withSpring(0, PRESS_SPRING_CONFIG); }} accessible accessibilityRole="button" accessibilityState={{ expanded }} accessibilityLabel={expanded ? `QR code for ${value}` : label} accessibilityHint={expanded ? "Double tap to collapse the QR code" : "Double tap to reveal the QR code"} className={cn("min-h-12 min-w-12 items-center justify-center self-start overflow-hidden", className)} style={[containerStyle, pressStyle]} {...props} > {label} Copy ); } ``` ## RadarChart - key: `radar-chart` - import: `import { RadarChart } from "@/components/ui/radar-chart"` - description: Skia radar/spider chart with staggered grow-in, data morphing, and a drag-to-select axis tooltip - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip, theme-provider ```tsx // components/ui/radar-chart.tsx import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, type LayoutChangeEvent } from "react-native"; import { Canvas, Path, Circle } from "@shopify/react-native-skia"; import Animated, { Easing, cancelAnimation, clamp, runOnJS, useAnimatedStyle, useDerivedValue, useSharedValue, withDelay, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface RadarChartDataPoint { label: string; value: number; } export interface RadarChartSeries { data: RadarChartDataPoint[]; color: string; fillOpacity?: number; } export interface RadarChartProps extends React.ComponentPropsWithoutRef { className?: string; data?: RadarChartDataPoint[]; height?: number; color?: string; fillOpacity?: number; showGrid?: boolean; showDots?: boolean; showLabels?: boolean; gridLevels?: number; series?: RadarChartSeries[]; onAxisChange?: (label: string, index: number) => void; } type Vertex = { x: number; y: number }; const TAU = Math.PI * 2; const GROW_DURATION = 900; const MORPH_DURATION = 550; const STAGGER = 0.3; const ROW_STAGGER = 55; const SPRING_CONFIG = { damping: 22, stiffness: 300, mass: 1 }; const TOOLTIP_SPRING_CONFIG = { damping: 18, stiffness: 220, mass: 0.9 }; const DOT_RADIUS = 3; const ACTIVE_DOT_RADIUS = 5; function polar(cx: number, cy: number, r: number, angle: number): Vertex { "worklet"; return { x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle) }; } function lerp(a: number, b: number, t: number) { "worklet"; return a + (b - a) * t; } function staggerProgress(progress: number, index: number, count: number, spread: number) { "worklet"; if (count < 2 || spread <= 0) return clamp(progress, 0, 1); const window = 1 / (1 + (count - 1) * spread); const start = index * spread * window; return clamp((progress - start) / window, 0, 1); } function polygonPath(points: Vertex[]) { "worklet"; if (points.length < 2) return "M 0 0"; let d = `M ${points[0]!.x} ${points[0]!.y}`; for (let i = 1; i < points.length; i++) d += ` L ${points[i]!.x} ${points[i]!.y}`; return `${d} Z`; } function indexForPoint(x: number, y: number, cx: number, cy: number, n: number) { "worklet"; if (n < 1) return -1; const raw = Math.atan2(y - cy, x - cx) + Math.PI / 2; const angle = ((raw % TAU) + TAU) % TAU; return Math.round(angle / (TAU / n)) % n; } const RadarDot = React.memo(function RadarDot({ vertices, seriesIndex, axisIndex, color, selectedIndex, isActive, }: { vertices: SharedValue; seriesIndex: number; axisIndex: number; color: string; selectedIndex: SharedValue; isActive: SharedValue; }) { const cx = useDerivedValue(() => vertices.value[seriesIndex]?.[axisIndex]?.x ?? 0); const cy = useDerivedValue(() => vertices.value[seriesIndex]?.[axisIndex]?.y ?? 0); const r = useDerivedValue(() => { const selected = selectedIndex.value === axisIndex ? 1 : 0; return withSpring(DOT_RADIUS + (ACTIVE_DOT_RADIUS - DOT_RADIUS) * selected * isActive.value, SPRING_CONFIG); }); return ( <> ); }); const RadarShape = React.memo(function RadarShape({ vertices, seriesIndex, axisCount, color, fillOpacity, showDots, selectedIndex, isActive, }: { vertices: SharedValue; seriesIndex: number; axisCount: number; color: string; fillOpacity: number; showDots: boolean; selectedIndex: SharedValue; isActive: SharedValue; }) { const path = useDerivedValue(() => { const row = vertices.value[seriesIndex]; if (!row || row.length < 2) return "M 0 0"; return polygonPath(row); }); return ( <> {showDots && Array.from({ length: axisCount }, (_, i) => ( ))} ); }); const TooltipRow = React.memo(function TooltipRow({ index, isActive, children, }: { index: number; isActive: SharedValue; children: React.ReactNode; }) { const entrance = useDerivedValue(() => withDelay(index * ROW_STAGGER, withSpring(isActive.value, TOOLTIP_SPRING_CONFIG)) ); const style = useAnimatedStyle(() => ({ opacity: entrance.value, transform: [{ translateY: (1 - entrance.value) * 8 }], })); return ( {children} ); }); const RadarTooltip = React.memo(function RadarTooltip({ axisLabel, rows, anglesShared, selectedIndex, isActive, centerX, centerY, radius, width, height, }: { axisLabel: string; rows: { label: string; value: number; color: string }[]; anglesShared: SharedValue; selectedIndex: SharedValue; isActive: SharedValue; centerX: number; centerY: number; radius: number; width: number; height: number; }) { const cardWidth = useSharedValue(0); const cardHeight = useSharedValue(0); const onLayout = useCallback( (e: LayoutChangeEvent) => { cardWidth.value = e.nativeEvent.layout.width; cardHeight.value = e.nativeEvent.layout.height; }, [cardWidth, cardHeight] ); const style = useAnimatedStyle(() => { const angle = anglesShared.value[selectedIndex.value]; if (angle == null) return { opacity: 0, transform: [] }; const point = polar(centerX, centerY, radius / 2, angle); const x = clamp(point.x - cardWidth.value / 2, 0, Math.max(width - cardWidth.value, 0)); const y = clamp(point.y - cardHeight.value / 2, 0, Math.max(height - cardHeight.value, 0)); const presence = withSpring(isActive.value, TOOLTIP_SPRING_CONFIG); return { opacity: presence, transform: [{ translateX: withSpring(x, SPRING_CONFIG) }, { translateY: withSpring(y, SPRING_CONFIG) }], }; }); return ( {axisLabel} {rows.map((row, i) => ( {row.label} {row.value} ))} ); }); export function RadarChart({ className, data, height = 200, color, fillOpacity = 0.2, showGrid = true, showDots = false, showLabels = true, gridLevels = 4, series, onAxisChange, ...props }: RadarChartProps) { const [width, setWidth] = useState(0); const colors = useThemeColors(); const gridColor = colors.border; const resolvedColor = color ?? colors.primary; const onLayout = (e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width); const [selectedAxis, setSelectedAxis] = useState(-1); const hasEntered = useRef(false); const originValues = useSharedValue([]); const targetValues = useSharedValue([]); const morph = useSharedValue(1); const grow = useSharedValue(0); const isActive = useSharedValue(0); const selectedIndex = useSharedValue(-1); const anglesShared = useSharedValue([]); const maxShared = useSharedValue(1); const size = Math.min(width, height); const centerX = width / 2; const centerY = height / 2; const radius = size / 2 - (showLabels ? 30 : 10); const allSeries: RadarChartSeries[] = series ?? [{ data: data ?? [], color: resolvedColor, fillOpacity }]; const labels = allSeries[0]?.data ?? []; const n = labels.length; const maxVal = Math.max(...allSeries.flatMap((s) => s.data.map((d) => d.value)), 1); const seriesSignature = allSeries .map((s) => s.data.map((d) => `${d.label}:${d.value}`).join(",")) .join("|"); const angles = useMemo(() => Array.from({ length: n }, (_, i) => (TAU * i) / n - Math.PI / 2), [n]); useEffect(() => { anglesShared.value = angles; }, [angles]); useEffect(() => { maxShared.value = maxVal; }, [maxVal]); useEffect(() => { if (width === 0) return; const values = allSeries.map((s) => s.data.map((d) => d.value)); const isEntrance = !hasEntered.current; hasEntered.current = true; const previous = targetValues.value; const isSameShape = !isEntrance && previous.length === values.length && previous.every((row, i) => row.length === (values[i]?.length ?? -1)); if (isEntrance || !isSameShape) { originValues.value = values; targetValues.value = values; cancelAnimation(morph); morph.value = 1; cancelAnimation(grow); grow.value = 0; grow.value = withTiming(1, { duration: GROW_DURATION, easing: Easing.out(Easing.cubic) }); return; } const from = originValues.value; const progress = morph.value; originValues.value = values.map((row, s) => row.map((_, i) => lerp(from[s]?.[i] ?? 0, previous[s]?.[i] ?? 0, progress)) ); targetValues.value = values; cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [width, seriesSignature]); const vertices = useDerivedValue(() => { const angleList = anglesShared.value; const origin = originValues.value; const target = targetValues.value; const count = Math.max(origin.length, target.length); const max = maxShared.value; const out: Vertex[][] = []; for (let s = 0; s < count; s++) { const entrance = staggerProgress(grow.value, s, count, STAGGER); const row: Vertex[] = []; for (let i = 0; i < angleList.length; i++) { const value = lerp(origin[s]?.[i] ?? 0, target[s]?.[i] ?? 0, morph.value); const distance = clamp((value / max) * radius, 0, radius) * entrance; row.push(polar(centerX, centerY, distance, angleList[i]!)); } out.push(row); } return out; // eslint-disable-next-line react-hooks/exhaustive-deps }, [centerX, centerY, radius]); const reportAxis = useCallback( (index: number) => { setSelectedAxis(index); const label = labels[index]?.label; if (label !== undefined) onAxisChange?.(label, index); }, [labels, onAxisChange] ); const gesture = useMemo( () => Gesture.Pan() .minDistance(0) .onBegin((event) => { "worklet"; const index = indexForPoint(event.x, event.y, centerX, centerY, n); if (index >= 0 && index !== selectedIndex.value) { selectedIndex.value = index; runOnJS(reportAxis)(index); } isActive.value = withTiming(1, { duration: 140 }); }) .onUpdate((event) => { "worklet"; const index = indexForPoint(event.x, event.y, centerX, centerY, n); if (index >= 0 && index !== selectedIndex.value) { selectedIndex.value = index; runOnJS(reportAxis)(index); } }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; }), [centerX, centerY, n, reportAxis, selectedIndex, isActive] ); const gridPath = useMemo(() => { if (!showGrid || n < 2) return ""; let path = ""; for (let level = 0; level < gridLevels; level++) { const r = ((level + 1) / gridLevels) * radius; const pts = angles.map((a) => polar(centerX, centerY, r, a)); path += `${polygonPath(pts)} `; } return path.trim(); }, [showGrid, gridLevels, angles, centerX, centerY, radius, n]); const axesPath = useMemo(() => { if (!showGrid || n < 1) return ""; let path = ""; for (const a of angles) { const p = polar(centerX, centerY, radius, a); path += `M ${centerX} ${centerY} L ${p.x} ${p.y} `; } return path.trim(); }, [showGrid, angles, centerX, centerY, radius, n]); const axisLabel = selectedAxis >= 0 ? labels[selectedAxis]?.label ?? "" : ""; const tooltipRows = selectedAxis >= 0 ? allSeries.map((s, i) => ({ label: `Series ${i + 1}`, value: s.data[selectedAxis]?.value ?? 0, color: s.color, })) : []; if (width === 0) { return ; } return ( {gridPath !== "" && } {axesPath !== "" && } {allSeries.map((s, i) => ( ))} {showLabels && ( {labels.map((d, i) => { const angle = angles[i]; if (angle === undefined) return null; const p = polar(centerX, centerY, radius + 14, angle); return ( {d.label} ); })} )} ); } ``` ## RadialChart - key: `radial-chart` - import: `import { RadialChart } from "@/components/ui/radial-chart"` - description: Skia concentric radial progress rings with grow-in, data morphing, and a drag-to-select tooltip - tier: 3 - deps: @shopify/react-native-skia, react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: chart-tooltip, theme-provider ```tsx // components/ui/radial-chart.tsx import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { View, Text, LayoutChangeEvent } from "react-native"; import { Canvas, Path } from "@shopify/react-native-skia"; import Animated, { Easing, cancelAnimation, clamp, runOnJS, useAnimatedReaction, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { ChartTooltip } from "@/components/ui/chart-tooltip"; export interface RadialChartSegment { value: number; maxValue?: number; color: string; label?: string; } export interface RadialChartProps extends React.ComponentPropsWithoutRef { className?: string; data: RadialChartSegment[]; height?: number; strokeWidth?: number; showLabels?: boolean; startAngle?: number; endAngle?: number; centerText?: string; centerSubText?: string; onRingChange?: (segment: RadialChartSegment, index: number) => void; } const GROW_DURATION = 900; const MORPH_DURATION = 550; const STAGGER = 0.08; const RING_PITCH_GAP = 6; const SPRING_CONFIG = { damping: 20, stiffness: 260, mass: 1 }; function lerpNum(from: number, to: number, progress: number): number { "worklet"; return from + (to - from) * progress; } function polarToCartesian(cx: number, cy: number, r: number, deg: number) { "worklet"; const rad = ((deg - 90) * Math.PI) / 180; return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) }; } function arcPath(cx: number, cy: number, r: number, start: number, end: number): string { "worklet"; const s = polarToCartesian(cx, cy, r, start); const e = polarToCartesian(cx, cy, r, end); const sweep = end - start; const large = sweep > 180 ? 1 : 0; return `M${s.x},${s.y} A${r},${r} 0 ${large} 1 ${e.x},${e.y}`; } function staggeredProgress(progress: number, index: number, spread: number): number { "worklet"; const delay = Math.min(index * spread, 0.8); return clamp((progress - delay) / Math.max(1 - delay, 0.2), 0, 1); } function angleForPoint(x: number, y: number, cx: number, cy: number): number { "worklet"; const rad = Math.atan2(y - cy, x - cx); const deg = (rad * 180) / Math.PI + 90; return ((deg % 360) + 360) % 360; } function isWithinSweep(angle: number, startAngle: number, range: number): boolean { "worklet"; if (range >= 360) return true; const relative = (((angle - startAngle) % 360) + 360) % 360; return relative <= range; } function ringIndexForDistance(distance: number, maxR: number, strokeWidth: number, gap: number, count: number): number { "worklet"; const pitch = strokeWidth + gap; if (pitch <= 0) return -1; const idx = Math.round((maxR - distance) / pitch); if (idx < 0 || idx >= count) return -1; const center = maxR - idx * pitch; return Math.abs(distance - center) <= strokeWidth / 2 + 2 ? idx : -1; } // Shared by onBegin/onUpdate: maps a touch point to the nearest ring index, // or -1 if it falls outside the sweep window or every ring's stroke band. function ringIndexForTouch( x: number, y: number, cx: number, cy: number, startAngle: number, range: number, maxR: number, strokeWidth: number, count: number ): number { "worklet"; const distance = Math.hypot(x - cx, y - cy); const angle = angleForPoint(x, y, cx, cy); return isWithinSweep(angle, startAngle, range) ? ringIndexForDistance(distance, maxR, strokeWidth, RING_PITCH_GAP, count) : -1; } interface RadialRingProps { index: number; cx: number; cy: number; radius: number; color: string; startAngle: number; range: number; strokeWidth: number; animatedFractions: SharedValue; selectedIndex: SharedValue; isActive: SharedValue; } // Selection feedback: widens the stroke on the active ring rather than // interpolating a synthetic "lighter" color, since ring colors are arbitrary // user-supplied hex values with no guaranteed lighter/darker counterpart. const RadialRing = memo(function RadialRing({ index, cx, cy, radius, color, startAngle, range, strokeWidth, animatedFractions, selectedIndex, isActive, }: RadialRingProps) { const selection = useDerivedValue( () => withSpring(selectedIndex.value === index ? 1 : 0, SPRING_CONFIG), [index] ); const path = useDerivedValue(() => { const fraction = animatedFractions.value[index] ?? 0; const sweep = fraction * range; if (sweep <= 0) return "M 0 0"; const safeEnd = sweep >= 360 ? startAngle + 359.99 : startAngle + sweep; return arcPath(cx, cy, radius, startAngle, safeEnd); }, [cx, cy, radius, startAngle, range]); const animatedStrokeWidth = useDerivedValue( () => strokeWidth + selection.value * isActive.value * 2, [strokeWidth] ); return ; }); export function RadialChart({ className, data, height = 200, strokeWidth = 12, showLabels = false, startAngle = 0, endAngle = 360, centerText, centerSubText, onRingChange, ...props }: RadialChartProps) { const [width, setWidth] = useState(0); const colors = useThemeColors(); const gridColor = colors.border; const labelColor = colors.mutedForeground; const centerColor = colors.foreground; const onLayout = useCallback((e: LayoutChangeEvent) => setWidth(e.nativeEvent.layout.width), []); const size = Math.min(width, height); const cx = width / 2; const cy = height / 2; const maxR = size / 2 - 10; const range = endAngle - startAngle; const ringCount = data.length; const ringRadii = useMemo( () => data.map((_, i) => maxR - i * (strokeWidth + RING_PITCH_GAP)), [ringCount, maxR, strokeWidth] ); const trackPaths = useMemo(() => { const bgEnd = range >= 360 ? startAngle + 359.99 : startAngle + range; return ringRadii.map((r) => (r > 0 ? arcPath(cx, cy, r, startAngle, bgEnd) : null)); }, [ringRadii, cx, cy, startAngle, range]); const currentFractions = useMemo( () => data.map((seg) => Math.min(Math.max(seg.value / (seg.maxValue ?? 100), 0), 1)), [data] ); const originFractions = useSharedValue([]); const targetFractions = useSharedValue([]); const morph = useSharedValue(1); const grow = useSharedValue(0); const isActive = useSharedValue(0); const selectedIndex = useSharedValue(-1); const cardWidth = useSharedValue(0); const cardHeight = useSharedValue(0); const hasEntered = useRef(false); const [activeIndex, setActiveIndex] = useState(-1); useEffect(() => { if (width === 0 || ringCount === 0) return; const fractions = currentFractions; const isEntrance = !hasEntered.current; hasEntered.current = true; if (isEntrance || targetFractions.value.length !== fractions.length) { originFractions.value = fractions; targetFractions.value = fractions; cancelAnimation(morph); morph.value = 1; cancelAnimation(grow); grow.value = 0; grow.value = withTiming(1, { duration: GROW_DURATION, easing: Easing.out(Easing.cubic) }); return; } const from = originFractions.value; const to = targetFractions.value; const progress = morph.value; originFractions.value = fractions.map((_, i) => lerpNum(from[i] ?? 0, to[i] ?? 0, progress)); targetFractions.value = fractions; cancelAnimation(morph); morph.value = 0; morph.value = withTiming(1, { duration: MORPH_DURATION, easing: Easing.inOut(Easing.cubic) }); }, [width, currentFractions, ringCount]); const animatedFractions = useDerivedValue(() => { const origin = originFractions.value; const target = targetFractions.value; const count = Math.max(origin.length, target.length); const out: number[] = []; for (let i = 0; i < count; i++) { const fraction = lerpNum(origin[i] ?? 0, target[i] ?? 0, morph.value); out.push(fraction * staggeredProgress(grow.value, i, STAGGER)); } return out; }, []); const reportRing = useCallback( (index: number) => { const seg = data[index]; if (seg) onRingChange?.(seg, index); }, [data, onRingChange] ); const panGesture = useMemo( () => Gesture.Pan() .minDistance(0) .onBegin((e) => { "worklet"; const idx = ringIndexForTouch(e.x, e.y, cx, cy, startAngle, range, maxR, strokeWidth, ringCount); if (idx !== selectedIndex.value) { selectedIndex.value = idx; if (idx >= 0) runOnJS(reportRing)(idx); } isActive.value = withTiming(idx >= 0 ? 1 : 0, { duration: 140 }); }) .onUpdate((e) => { "worklet"; const idx = ringIndexForTouch(e.x, e.y, cx, cy, startAngle, range, maxR, strokeWidth, ringCount); if (idx !== selectedIndex.value) { selectedIndex.value = idx; if (idx >= 0) runOnJS(reportRing)(idx); isActive.value = withTiming(idx >= 0 ? 1 : 0, { duration: 140 }); } }) .onFinalize(() => { "worklet"; isActive.value = withTiming(0, { duration: 220 }); selectedIndex.value = -1; }), [cx, cy, startAngle, range, maxR, strokeWidth, ringCount, selectedIndex, isActive, reportRing] ); useAnimatedReaction( () => selectedIndex.value, (current, previous) => { if (current !== previous) runOnJS(setActiveIndex)(current); }, [] ); const onTooltipLayout = useCallback( (e: LayoutChangeEvent) => { cardWidth.value = e.nativeEvent.layout.width; cardHeight.value = e.nativeEvent.layout.height; }, [cardWidth, cardHeight] ); const tooltipStyle = useAnimatedStyle(() => { const idx = selectedIndex.value; const r = ringRadii[idx]; if (r == null || r <= 0) { return { opacity: isActive.value, transform: [{ translateX: 0 }, { translateY: 0 }] }; } const fraction = animatedFractions.value[idx] ?? 0; const angleDeg = startAngle + fraction * range; const point = polarToCartesian(cx, cy, r, angleDeg); const x = clamp(point.x - cardWidth.value / 2, 0, Math.max(width - cardWidth.value, 0)); const y = clamp(point.y - cardHeight.value / 2, 0, Math.max(height - cardHeight.value, 0)); return { opacity: isActive.value, transform: [{ translateX: x }, { translateY: y }] }; }, [ringRadii, cx, cy, startAngle, range, width, height]); const activeSeg = activeIndex >= 0 ? data[activeIndex] : undefined; return ( {width > 0 && ( {data.map((seg, i) => { const r = ringRadii[i]; if (r == null || r <= 0) return null; return ( ); })} {(centerText || centerSubText) && ( {centerText && {centerText}} {centerSubText && {centerSubText}} )} {showLabels && data.map((seg, i) => { const r = ringRadii[i]; if (r == null || r <= 0) return null; const pos = polarToCartesian(cx, cy, r, startAngle - 10); return ( {seg.label ?? `${seg.value}`} ); })} {activeSeg && } )} ); } ``` ## RadioGroup - key: `radio-group` - import: `import { RadioGroup } from "@/components/ui/radio-group"` - description: Radio button group - tier: 3 - deps: @rn-primitives/radio-group, clsx, tailwind-merge ```tsx // components/ui/radio-group.tsx import React from "react"; import { View, Pressable, Text } from "react-native"; import * as RadioGroupPrimitive from "@rn-primitives/radio-group"; import { cn } from "@/lib/utils"; export interface RadioGroupProps extends React.ComponentPropsWithoutRef { className?: string; value: string; onValueChange: (value: string) => void; children?: React.ReactNode; } export function RadioGroup({ value, onValueChange, className, children, ...props }: RadioGroupProps) { return ( {children} ); } export interface RadioGroupItemProps extends React.ComponentPropsWithoutRef { className?: string; value: string; label?: string; } export function RadioGroupItem({ value, label, className, ...props }: RadioGroupItemProps) { return ( {label && {label}} ); } ``` ## Rating - key: `rating` - import: `import { Rating } from "@/components/ui/rating"` - description: Star rating with interactive and read-only modes - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/rating.tsx import React from "react"; import { View, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { Star } from "lucide-react-native"; import { cn } from "@/lib/utils"; const ratingVariants = cva("flex-row items-center", { variants: { size: { sm: "gap-0.5", md: "gap-1", lg: "gap-1.5", }, }, defaultVariants: { size: "md" }, }); const starSizes = { sm: 16, md: 20, lg: 24 } as const; export interface RatingProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; value: number; max?: number; onChange?: (value: number) => void; readOnly?: boolean; } export function Rating({ size, className, value, max = 5, onChange, readOnly, ...props }: RatingProps) { const s = size ?? "md"; return ( {Array.from({ length: max }, (_, i) => { const filled = i < value; const star = ( ); return readOnly ? ( {star} ) : ( onChange?.(i + 1)} accessible={true} accessibilityRole="button" accessibilityLabel={`${i + 1} star`}> {star} ); })} ); } ``` ## ReceiptCard - key: `receipt-card` - import: `import { ReceiptCard } from "@/components/ui/receipt-card"` - description: Tilted, torn-edge receipt card with dotted item leaders and a printed barcode - tier: 1 - deps: react-native-svg, clsx, tailwind-merge ```tsx // components/ui/receipt-card.tsx import React, { useMemo } from "react"; import { View, Text, Platform } from "react-native"; import Svg, { Path } from "react-native-svg"; import { cn } from "@/lib/utils"; const MONO_FONT = Platform.select({ ios: "Menlo", android: "monospace", default: "monospace" }); const RECEIPT_WIDTH = 320; const TOOTH_WIDTH = 20; const TOOTH_HEIGHT = 10; const BAR_COUNT = 32; const BARCODE_HEIGHT = 32; const BARCODE_WIDTH = 160; export type ReceiptCardPalette = { paper: string; ink: string; muted: string; rule: string; leader: string; accent: string; }; const DEFAULT_RECEIPT_PALETTE: ReceiptCardPalette = { paper: "#FFFFFF", ink: "#18181B", muted: "#71717A", rule: "#D4D4D8", leader: "#A1A1AA", accent: "#18181B", }; export interface ReceiptLine { label: string; value: string; bold?: boolean; /** Dotted rule stretching between label and value, like a printed menu. Default true. */ leader?: boolean; } /** * Builds a "torn paper" sawtooth silhouette: `Math.ceil(width / toothWidth)` * triangles spanning the full width, each rising from a flat base edge (the * side that meets the paper body) to a point on the ragged/open side. */ function buildTornEdgePath(width: number, toothWidth: number, toothHeight: number, side: "top" | "bottom"): string { const teeth = Math.ceil(width / toothWidth); const baseY = side === "bottom" ? 0 : toothHeight; const tipY = side === "bottom" ? toothHeight : 0; let d = `M0,${baseY}`; for (let i = 0; i < teeth; i++) { const start = i * toothWidth; const mid = start + toothWidth / 2; const end = Math.min(start + toothWidth, width); d += ` L${mid},${tipY} L${end},${baseY}`; } return `${d} Z`; } /** Deterministic per-bar width (2-5px) seeded from the printed code, so the same code always draws the same bars. */ function receiptBarWidth(code: string, index: number): number { const source = code.length > 0 ? code : "aniui"; const char = source.charCodeAt(index % source.length); return 2 + ((char * (index + 1)) % 4); } export interface ReceiptCardProps extends React.ComponentPropsWithoutRef { className?: string; merchant: string; date: string; lines: ReceiptLine[]; total: string; /** Default "Total". */ totalLabel?: string; /** Small centered muted line under the total, e.g. "THANK YOU". */ note?: string; /** Seeds the printed code + width-encoded barcode at the bottom. Omit to hide the barcode entirely. */ code?: string; /** Print the code string under the bars. Default true. */ showCode?: boolean; /** Small tilt on the whole card, like a receipt tossed on a desk. Default true. */ tilted?: boolean; /** Card width in px — also sizes the torn-edge paths. Default 320. */ width?: number; palette?: Partial; } export function ReceiptCard({ className, merchant, date, lines, total, totalLabel = "Total", note, code, showCode = true, tilted = true, width = RECEIPT_WIDTH, palette, style, ...props }: ReceiptCardProps) { const p = useMemo(() => ({ ...DEFAULT_RECEIPT_PALETTE, ...palette }), [palette]); const topEdge = useMemo(() => buildTornEdgePath(width, TOOTH_WIDTH, TOOTH_HEIGHT, "top"), [width]); const bottomEdge = useMemo(() => buildTornEdgePath(width, TOOTH_WIDTH, TOOTH_HEIGHT, "bottom"), [width]); const bars = useMemo( () => (code ? Array.from({ length: BAR_COUNT }, (_, i) => receiptBarWidth(code, i)) : []), [code] ); return ( {/* A real drop shadow (shadowOpacity 0.12, radius 12, offset {0,6}, elevation 4) — without it the card reads as flat, and the torn-paper edges above/below have nothing to visually separate them from the page. */} {merchant} {date} {lines.map((line) => ( {line.label} {line.leader !== false ? ( ) : ( )} {line.value} ))} {totalLabel} {total} {note ? ( {note} ) : null} {code ? ( {bars.map((barWidth, i) => ( ))} {showCode ? ( {code} ) : null} ) : null} ); } ``` ## RefreshControl - key: `refresh-control` - import: `import { RefreshControl } from "@/components/ui/refresh-control"` - description: Themed pull-to-refresh control for ScrollView and FlatList - tier: 1 - aniui deps: theme-provider ```tsx // components/ui/refresh-control.tsx import React from "react"; import { RefreshControl as RNRefreshControl } from "react-native"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface RefreshControlProps extends React.ComponentPropsWithoutRef { refreshing: boolean; onRefresh: () => void; tintColor?: string; colors?: string[]; } export function RefreshControl({ refreshing, onRefresh, tintColor, colors, ...props }: RefreshControlProps) { const themeColors = useThemeColors(); const tint = tintColor ?? themeColors.foreground; return ( ); } ``` ## RollingCounter - key: `rolling-counter` - import: `import { RollingCounter } from "@/components/ui/rolling-counter"` - description: Animated odometer-style rolling number counter with motion-blur, squash/stretch, staggered digits, and correct wrap-around rollover - tier: 3 - deps: react-native-reanimated, expo-blur, clsx, tailwind-merge ```tsx // components/ui/rolling-counter.tsx import React, { useEffect, useState } from "react"; import { View, Text } from "react-native"; import Animated, { Easing, interpolate, runOnJS, useAnimatedProps, useAnimatedReaction, useAnimatedStyle, useDerivedValue, useSharedValue, withDelay, withTiming, type SharedValue, } from "react-native-reanimated"; import { BlurView } from "expo-blur"; import { cn } from "@/lib/utils"; export interface RollingCounterProps extends React.ComponentPropsWithoutRef { className?: string; value: number; digits?: number; prefix?: string; suffix?: string; } const AnimatedBlurView = Animated.createAnimatedComponent(BlurView); const TILES = 11; const STAGGER_MS = 38; const MAX_BLUR = 24; const SQUASH_Y = 0.12; const SQUASH_X = 0.035; const ROLL_EASING = Easing.bezier(0.22, 1, 0.28, 1); const ROLL_TIMING = { duration: 620, easing: ROLL_EASING }; const WIDTH_TIMING = { duration: 380, easing: ROLL_EASING }; function wrap(num: number, mod: number) { "worklet"; return ((num % mod) + mod) % mod; } function digitAt(num: number, place: number) { "worklet"; const str = Math.abs(Math.floor(num)).toString(); return parseInt(str[str.length - 1 - place] ?? "0", 10); } function digitCount(num: number) { "worklet"; return Math.max(Math.abs(Math.floor(num)).toString().length, 1); } function Digit({ place, counterValue, height, width, stagger }: { place: number; counterValue: SharedValue; height: number; width: number; stagger: number }) { const settled = digitAt(counterValue.value, place); const offset = useSharedValue(settled); const travelFrom = useSharedValue(settled); const travelTo = useSharedValue(settled); useAnimatedReaction( () => counterValue.value, (current, previous) => { if (previous === null || current === previous) return; const next = digitAt(current, place); if (next === digitAt(previous, place)) return; const from = wrap(offset.value, 10); const forward = current > previous; const delta = forward ? wrap(next - from, 10) : -wrap(from - next, 10); if (delta === 0) return; travelFrom.value = offset.value; travelTo.value = offset.value + delta; const roll = withTiming(travelTo.value, ROLL_TIMING); offset.value = stagger > 0 ? withDelay(place * stagger, roll) : roll; }, [place, stagger] ); // Bell curve (sin^2 of roll progress) scaled by how far this digit is // travelling — near-zero for a single-step roll, near-1 for a full 0-9 span. const motion = useDerivedValue(() => { const span = travelTo.value - travelFrom.value; if (span === 0) return 0; const progress = Math.min(Math.max((offset.value - travelFrom.value) / span, 0), 1); const bell = Math.sin(Math.PI * progress) ** 2; const reach = Math.min(Math.max(Math.abs(span) / 9, 0), 1); return bell * reach; }); const windowStyle = useAnimatedStyle(() => ({ transform: [{ scaleY: 1 - SQUASH_Y * motion.value }, { scaleX: 1 - SQUASH_X * motion.value }], })); const stripStyle = useAnimatedStyle(() => ({ transform: [{ translateY: -height * wrap(offset.value, 10) }], })); const blurProps = useAnimatedProps(() => ({ intensity: interpolate(motion.value, [0, 1], [0, MAX_BLUR]), })); return ( {Array.from({ length: TILES }, (_, n) => ( {n % 10} ))} ); } export function RollingCounter({ className, value, digits = 4, prefix, suffix, ...props }: RollingCounterProps) { const clamped = Math.max(0, Math.floor(value)); const digitHeight = 36; const digitWidth = 24; const counterValue = useSharedValue(clamped); useEffect(() => { counterValue.value = clamped; }, [clamped, counterValue]); const [totalDigits, setTotalDigits] = useState(() => Math.max(digits, digitCount(clamped))); const rowWidth = useSharedValue(totalDigits * digitWidth); useAnimatedReaction( () => Math.max(digits, digitCount(counterValue.value)), (next, previous) => { if (previous === null || next === previous) return; rowWidth.value = withTiming(next * digitWidth, WIDTH_TIMING); runOnJS(setTotalDigits)(next); }, [digits, digitWidth] ); const rowStyle = useAnimatedStyle(() => ({ width: rowWidth.value })); return ( {prefix ? {prefix} : null} {Array.from({ length: totalDigits }, (_, i) => { const place = totalDigits - 1 - i; return ; })} {suffix ? {suffix} : null} ); } ``` ## SafeArea - key: `safe-area` - import: `import { SafeArea } from "@/components/ui/safe-area"` - description: Styled SafeAreaView wrapper with theme variants - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge, react-native-safe-area-context ```tsx // components/ui/safe-area.tsx import React from "react"; import { View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const safeAreaVariants = cva("flex-1", { variants: { variant: { default: "bg-background", card: "bg-card", transparent: "bg-transparent", }, }, defaultVariants: { variant: "default" }, }); export interface SafeAreaProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; children?: React.ReactNode; } export function SafeArea({ variant, className, children, style, ...props }: SafeAreaProps) { // Background + flex live on a plain View (className works reliably under both // NativeWind and Uniwind, and colors the full screen incl. the inset areas). // The SafeAreaView only applies the insets — className isn't applied to that // third-party component by the styling engines, so we keep flex inline there. return ( {children} ); } ``` ## SaveButton - key: `save-button` - import: `import { SaveButton } from "@/components/ui/save-button"` - description: Idle → loading → success → done state-machine save button with animated phase transitions - tier: 2 - deps: lucide-react-native, react-native-svg, react-native-reanimated, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/save-button.tsx import React, { useCallback, useEffect, useRef, useState } from "react"; import { Pressable, Text } from "react-native"; import Animated, { cancelAnimation, Easing, interpolate, interpolateColor, useAnimatedStyle, useSharedValue, withDelay, withRepeat, withSpring, withTiming, } from "react-native-reanimated"; import { Check } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export type SaveButtonPhase = "idle" | "loading" | "success" | "done"; export interface SaveButtonProps extends Omit, "onPress" | "disabled"> { className?: string; label?: string; savedLabel?: string; onSave?: () => void | Promise; onSaved?: () => void; minLoading?: number; successPause?: number; /** Reverts back to idle after this many ms once done. Stays "done" if omitted. */ resetAfter?: number; disabled?: boolean; } const IDLE_WIDTH = 116; const CIRCLE_WIDTH = 48; const DONE_WIDTH = 148; const SPRING = { damping: 18, stiffness: 180, mass: 1 }; /** Idle -> loading -> success -> done state-machine button for async save actions. */ export function SaveButton({ className, label = "Save", savedLabel = "Saved", onSave, onSaved, minLoading = 1100, successPause = 600, resetAfter, disabled = false, ...props }: SaveButtonProps) { const colors = useThemeColors(); const idleBg = colors.secondary; const activeBg = colors.primary; const idleText = colors.foreground; const [phase, setPhase] = useState("idle"); const phaseRef = useRef("idle"); const timers = useRef[]>([]); const width = useSharedValue(IDLE_WIDTH); const bg = useSharedValue(0); const labelP = useSharedValue(1); const spinP = useSharedValue(0); const spin = useSharedValue(0); const checkP = useSharedValue(0); const savedP = useSharedValue(0); const setBoth = useCallback((p: SaveButtonPhase) => { phaseRef.current = p; setPhase(p); }, []); const runReset = useCallback(() => { setBoth("idle"); savedP.value = withTiming(0, { duration: 150 }); checkP.value = withTiming(0, { duration: 150 }); bg.value = withTiming(0, { duration: 200 }); width.value = withSpring(IDLE_WIDTH, SPRING); labelP.value = withDelay(120, withTiming(1, { duration: 200 })); }, [savedP, checkP, bg, width, labelP, setBoth]); const runDone = useCallback(() => { setBoth("done"); width.value = withSpring(DONE_WIDTH, SPRING); checkP.value = withTiming(0, { duration: 180 }); savedP.value = withDelay(20, withTiming(1, { duration: 240 })); onSaved?.(); if (resetAfter != null) timers.current.push(setTimeout(runReset, resetAfter)); }, [width, checkP, savedP, onSaved, resetAfter, runReset, setBoth]); const runSuccess = useCallback(() => { setBoth("success"); spinP.value = withTiming(0, { duration: 160 }); cancelAnimation(spin); checkP.value = withDelay(140, withSpring(1, { damping: 11, stiffness: 220 })); timers.current.push(setTimeout(runDone, successPause)); }, [spinP, spin, checkP, successPause, runDone, setBoth]); const runLoading = useCallback(() => { setBoth("loading"); width.value = withSpring(CIRCLE_WIDTH, SPRING); bg.value = withTiming(1, { duration: 260 }); labelP.value = withDelay(50, withTiming(0, { duration: 180 })); spinP.value = withDelay(240, withTiming(1, { duration: 180 })); spin.value = 0; spin.value = withRepeat(withTiming(360, { duration: 750, easing: Easing.linear }), -1, false); }, [width, bg, labelP, spinP, spin, setBoth]); const handlePress = useCallback(async () => { if (disabled || phaseRef.current !== "idle") return; runLoading(); const started = Date.now(); try { await onSave?.(); } catch { // A failed save still resolves through to "success" — callers surface errors themselves. } timers.current.push(setTimeout(runSuccess, Math.max(0, minLoading - (Date.now() - started)))); }, [disabled, runLoading, onSave, minLoading, runSuccess]); useEffect(() => () => timers.current.forEach(clearTimeout), []); const containerStyle = useAnimatedStyle(() => ({ width: width.value, backgroundColor: interpolateColor(bg.value, [0, 1], [idleBg, activeBg]), })); const labelStyle = useAnimatedStyle(() => ({ opacity: labelP.value, transform: [{ scale: interpolate(labelP.value, [0, 1], [0.6, 1]) }], })); const spinnerStyle = useAnimatedStyle(() => ({ opacity: spinP.value, transform: [{ rotate: `${spin.value}deg` }], })); const checkStyle = useAnimatedStyle(() => ({ opacity: checkP.value, transform: [{ scale: interpolate(checkP.value, [0, 1], [0.5, 1]) }], })); const savedStyle = useAnimatedStyle(() => ({ opacity: savedP.value, transform: [{ translateY: interpolate(savedP.value, [0, 1], [6, 0]) }], })); const busy = phase !== "idle"; return ( {label} {savedLabel} ); } ``` ## SearchBar - key: `search-bar` - import: `import { SearchBar } from "@/components/ui/search-bar"` - description: Search input with icon, clear button, and cancel - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/search-bar.tsx import React from "react"; import { View, TextInput, Pressable, Text, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { Search, X } from "lucide-react-native"; const searchBarVariants = cva( "flex-row items-center rounded-lg bg-muted px-3 min-h-12", { variants: { size: { sm: "min-h-10 px-2.5", md: "min-h-12 px-3", lg: "min-h-14 px-4", }, }, defaultVariants: { size: "md" }, } ); const iconSizes = { sm: 14, md: 16, lg: 20 } as const; export interface SearchBarProps extends Omit, "placeholderTextColor">, VariantProps { className?: string; icon?: React.ReactNode; onClear?: () => void; showCancel?: boolean; onCancel?: () => void; } export const SearchBar = React.forwardRef< React.ElementRef, SearchBarProps >(function SearchBar( { size = "md", className, value, icon, onClear, showCancel, onCancel, ...props }, ref ) { const iconSize = iconSizes[size ?? "md"]; const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; return ( {icon ?? } {value ? ( { onClear?.(); props.onChangeText?.(""); }} className="ms-1 h-6 w-6 items-center justify-center rounded-full bg-muted-foreground/20" accessible={true} accessibilityRole="button" accessibilityLabel="Clear search" hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}> ) : null} {showCancel && ( Cancel )} ); }); ``` ## SegmentedControl - key: `segmented-control` - import: `import { SegmentedControl } from "@/components/ui/segmented-control"` - description: iOS-style segmented control for view switching - tier: 1 - aniui deps: theme-provider ```tsx // components/ui/segmented-control.tsx import React from "react"; import { View, Pressable, Text, useColorScheme } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const heights = { sm: 36, md: 44, lg: 56 } as const; export type SegmentedOption = { value: T; label?: string; disabled?: boolean; }; export interface SegmentedControlProps extends Omit, "children"> { className?: string; options: T[] | SegmentedOption[]; labels?: string[]; value: T; onValueChange: (value: T) => void; size?: "sm" | "md" | "lg"; } function isOptionObject(o: T | SegmentedOption): o is SegmentedOption { return typeof o === "object" && o !== null && "value" in (o as object); } export function SegmentedControl({ size = "md", className, style, options, labels, value, onValueChange, ...rest }: SegmentedControlProps) { const dark = useColorScheme() === "dark"; const colors = useThemeColors(); // Dark active segment is lifted one shade above colors.secondary (#27272a) so // the active pill is visibly elevated against the muted track — see 0.2.26 changelog. const activeBg = dark ? "#37373a" : colors.background; const activeFg = colors.foreground; const inactiveFg = colors.mutedForeground; const disabledFg = dark ? "#52525b" : "#d4d4d8"; const items: SegmentedOption[] = options.map((o, i) => isOptionObject(o) ? { value: o.value, label: o.label ?? String(o.value), disabled: o.disabled } : { value: o, label: labels?.[i] ?? String(o) } ); return ( {items.map(({ value: v, label, disabled }) => { const active = v === value; return ( { if (!active) onValueChange(v); }} accessible={true} accessibilityRole="tab" accessibilityState={{ selected: active, disabled: !!disabled }} > {label} ); })} ); } ``` ## Select - key: `select` - import: `import { Select } from "@/components/ui/select"` - description: Dropdown select with search support - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/select.tsx import React, { useState, useRef } from "react"; import { View, Text, Pressable, TextInput, Modal, ScrollView, Dimensions, LayoutChangeEvent, useColorScheme } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { Check, ChevronDown } from "lucide-react-native"; export interface SelectOption { label: string; value: string } export interface SelectProps { className?: string; placeholder?: string; options: SelectOption[]; value?: string; onValueChange?: (value: string) => void; label?: string; searchable?: boolean; searchPlaceholder?: string; } export function Select({ className, placeholder = "Select...", options, value, onValueChange, label, searchable = false, searchPlaceholder = "Search...", }: SelectProps) { const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const triggerRef = useRef(null); const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; const [pos, setPos] = useState({ x: 0, y: 0, w: 0, h: 0 }); const selected = options.find((o) => o.value === value); const filtered = searchable && search ? options.filter((o) => o.label.toLowerCase().includes(search.toLowerCase())) : options; const handleOpen = () => { triggerRef.current?.measureInWindow((x, y, width, height) => { setPos({ x, y, w: width, h: height }); setOpen(true); }); }; const close = () => { setOpen(false); setSearch(""); }; const pick = (val: string) => { onValueChange?.(val); close(); }; const screenH = Dimensions.get("window").height; const triggerY = pos.y; const belowY = triggerY + pos.h + 4; const listH = Math.min(filtered.length * 48, 264); const totalH = listH + (searchable ? 60 : 0); const fitsBelow = belowY + totalH < screenH; return ( {selected?.label ?? placeholder} {/* Backdrop */} {/* Dropdown */} {searchable && ( )} {filtered.map((o) => { const isSelected = o.value === value; return ( pick(o.value)} accessible={true} accessibilityRole="button" accessibilityState={{ selected: isSelected }} > {o.label} {isSelected && } ); })} {filtered.length === 0 && ( No results )} ); } ``` ## Separator - key: `separator` - import: `import { Separator } from "@/components/ui/separator"` - description: Visual divider - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/separator.tsx import React from "react"; import { View } from "react-native"; import { cn } from "@/lib/utils"; export interface SeparatorProps extends React.ComponentPropsWithoutRef { className?: string; orientation?: "horizontal" | "vertical"; } export function Separator({ orientation = "horizontal", className, ...props }: SeparatorProps) { return ( ); } ``` ## Shimmer - key: `shimmer` - import: `import { Shimmer } from "@/components/ui/shimmer"` - description: Content-aware skeleton with sweep/pulse variants, 4 directions, named color presets, and isLoading reveal - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/shimmer.tsx import React, { useEffect, useState } from "react"; import { View, type LayoutChangeEvent } from "react-native"; import Animated, { cancelAnimation, useAnimatedStyle, useSharedValue, withRepeat, withSequence, withTiming, } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export type ShimmerVariant = "shimmer" | "pulse"; export type ShimmerDirection = "leftToRight" | "rightToLeft" | "topToBottom" | "bottomToTop"; export type ShimmerPreset = "default" | "neutral" | "inverted" | "brand" | "subtle"; // "container" = the placeholder's resting background; "highlight" = the // moving (shimmer) or breathing (pulse) overlay drawn on top of it. // "default"/"brand" ride the theme's CSS vars so they stay correct in dark // mode automatically; the rest are fixed tones for a caller that wants a // specific loading surface regardless of the app's color scheme. const SHIMMER_PRESETS: Record = { default: { container: "bg-muted", highlight: "bg-foreground/20" }, neutral: { container: "bg-zinc-200", highlight: "bg-white/70" }, inverted: { container: "bg-zinc-900", highlight: "bg-white/25" }, brand: { container: "bg-primary/10", highlight: "bg-primary/40" }, subtle: { container: "bg-muted/50", highlight: "bg-foreground/10" }, }; export interface ShimmerProps extends React.ComponentPropsWithoutRef { className?: string; /** True (default) renders the placeholder. Flip to false once real content is ready. */ isLoading?: boolean; /** Real content, faded in once `isLoading` becomes false. Ignored while loading. */ children?: React.ReactNode; /** "shimmer" sweeps a highlight band across the placeholder; "pulse" breathes its opacity instead. */ variant?: ShimmerVariant; /** Sweep axis + direction. Only affects the "shimmer" variant. */ direction?: ShimmerDirection; preset?: ShimmerPreset; } export function Shimmer({ className, onLayout, isLoading = true, children, variant = "shimmer", direction = "leftToRight", preset = "default", ...props }: ShimmerProps) { const translate = useSharedValue(0); const pulse = useSharedValue(1); const reveal = useSharedValue(isLoading ? 0 : 1); const [size, setSize] = useState(0); const reducedMotion = useReducedMotion(); const theme = SHIMMER_PRESETS[preset] ?? SHIMMER_PRESETS.default; const horizontal = direction === "leftToRight" || direction === "rightToLeft"; const forward = direction === "leftToRight" || direction === "topToBottom"; const sweeps = variant === "shimmer"; useEffect(() => { if (!isLoading) { cancelAnimation(translate); cancelAnimation(pulse); reveal.value = withTiming(1, { duration: 400 }); return; } reveal.value = 0; if (reducedMotion || !size) return; if (sweeps) { translate.value = forward ? -size * 0.5 : size * 1.5; translate.value = withRepeat( withTiming(forward ? size * 1.5 : -size * 0.5, { duration: 1200 }), -1, false ); return () => cancelAnimation(translate); } pulse.value = withRepeat( withSequence(withTiming(0.4, { duration: 700 }), withTiming(1, { duration: 700 })), -1, false ); return () => cancelAnimation(pulse); }, [isLoading, sweeps, forward, size, reducedMotion, translate, pulse, reveal]); const highlightStyle = useAnimatedStyle(() => ({ transform: horizontal ? [{ translateX: translate.value }] : [{ translateY: translate.value }], })); const pulseStyle = useAnimatedStyle(() => ({ opacity: pulse.value })); const revealStyle = useAnimatedStyle(() => ({ opacity: reveal.value })); const handleLayout = (e: LayoutChangeEvent) => { setSize(horizontal ? e.nativeEvent.layout.width : e.nativeEvent.layout.height); onLayout?.(e); }; return ( {!isLoading && {children}} {isLoading && !reducedMotion && !sweeps && ( )} {isLoading && !reducedMotion && sweeps && size > 0 && ( )} ); } ``` ## Sidebar - key: `sidebar` - import: `import { Sidebar } from "@/components/ui/sidebar"` - description: Collapsible animated side navigation panel: SidebarProvider, Sidebar, SidebarTrigger, useSidebar - tier: 2 - deps: lucide-react-native, react-native-svg, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, theme-provider ```tsx // components/ui/sidebar.tsx import React, { createContext, useContext, useState } from "react"; import { View, Pressable } from "react-native"; import Animated, { useAnimatedStyle, withTiming } from "react-native-reanimated"; import { Menu } from "lucide-react-native"; import { duration } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; interface SidebarCtx { open: boolean; toggle: () => void; setOpen: (open: boolean) => void; } const Ctx = createContext(null); export function useSidebar(): SidebarCtx { const ctx = useContext(Ctx); if (!ctx) throw new Error("useSidebar must be used within "); return ctx; } export interface SidebarProviderProps { defaultOpen?: boolean; children: React.ReactNode; } export function SidebarProvider({ defaultOpen = true, children }: SidebarProviderProps) { const [open, setOpen] = useState(defaultOpen); return ( setOpen((o) => !o) }}> {children} ); } export interface SidebarProps extends React.ComponentPropsWithoutRef { className?: string; width?: number; children?: React.ReactNode; } export function Sidebar({ className, width = 256, children, ...props }: SidebarProps) { const { open } = useSidebar(); const style = useAnimatedStyle(() => ({ width: withTiming(open ? width : 0, { duration: duration.normal }), })); return ( {children} ); } export interface SidebarTriggerProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function SidebarTrigger({ className, children, ...props }: SidebarTriggerProps) { const { toggle } = useSidebar(); const colors = useThemeColors(); return ( {children ?? } ); } ``` ## Skeleton - key: `skeleton` - import: `import { Skeleton } from "@/components/ui/skeleton"` - description: Animated loading placeholder - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/skeleton.tsx import React, { useEffect } from "react"; import { View } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withSequence, withTiming, cancelAnimation, } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export interface SkeletonProps extends React.ComponentPropsWithoutRef { className?: string; } export function Skeleton({ className, ...props }: SkeletonProps) { const opacity = useSharedValue(1); const reducedMotion = useReducedMotion(); useEffect(() => { if (reducedMotion) { // A static dim instead of a pulsing loop — still reads as "loading" // without the motion a reduced-motion user asked to avoid. opacity.value = 0.6; return; } opacity.value = withRepeat( withSequence( withTiming(0.4, { duration: 800 }), withTiming(1, { duration: 800 }) ), -1, false ); return () => cancelAnimation(opacity); }, [opacity, reducedMotion]); const animatedStyle = useAnimatedStyle(() => ({ opacity: opacity.value, })); return ( ); } ``` ## SlideToConfirm - key: `slide-to-confirm` - import: `import { SlideToConfirm } from "@/components/ui/slide-to-confirm"` - description: Slide-to-pay/confirm control with spring-back and confirmed state - tier: 3 - deps: lucide-react-native, react-native-svg, react-native-gesture-handler, react-native-reanimated, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/slide-to-confirm.tsx import React, { useState } from "react"; import { View, Text } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming, interpolate, runOnJS } from "react-native-reanimated"; import { ChevronRight, Check } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const THUMB = 48; const PAD = 4; export interface SlideToConfirmProps extends React.ComponentPropsWithoutRef { className?: string; label?: string; confirmedLabel?: string; disabled?: boolean; /** Fired once when the thumb reaches the end. Remount (key) to reset. */ onConfirm: () => void; } export function SlideToConfirm({ className, label = "Slide to confirm", confirmedLabel = "Confirmed", disabled, onConfirm, onLayout, ...props }: SlideToConfirmProps) { const [confirmed, setConfirmed] = useState(false); const [trackWidth, setTrackWidth] = useState(0); const tx = useSharedValue(0); const end = Math.max(0, trackWidth - THUMB - PAD * 2); const colors = useThemeColors(); const confirm = () => { setConfirmed(true); onConfirm(); }; const gesture = Gesture.Pan() .enabled(!disabled && !confirmed && end > 0) .onUpdate((e) => { tx.value = Math.max(0, Math.min(end, e.translationX)); }) .onEnd(() => { if (tx.value >= end * 0.92) { tx.value = withTiming(end, { duration: 120 }, () => runOnJS(confirm)()); } else { tx.value = withSpring(0); } }); const thumbStyle = useAnimatedStyle(() => ({ transform: [{ translateX: tx.value }] })); // The hint label fades out as the thumb travels across it. const labelStyle = useAnimatedStyle(() => ({ opacity: interpolate(tx.value, [0, end || 1], [1, 0]), })); return ( { setTrackWidth(e.nativeEvent.layout.width); onLayout?.(e); }} accessible={true} accessibilityRole="button" accessibilityLabel={confirmed ? confirmedLabel : label} accessibilityState={{ disabled: !!disabled }} {...props} > {label} {confirmed && ( {confirmedLabel} )} {confirmed ? ( ) : ( )} ); } ``` ## Slider - key: `slider` - import: `import { Slider } from "@/components/ui/slider"` - description: Draggable slider for numeric values - tier: 2 - deps: react-native-gesture-handler, react-native-reanimated, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/slider.tsx import React, { useCallback, useEffect } from "react"; import { View } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { useSharedValue, useAnimatedStyle, runOnJS } from "react-native-reanimated"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const sliderVariants = cva("w-full justify-center", { variants: { size: { sm: "h-8", md: "h-10", lg: "h-12", }, }, defaultVariants: { size: "md" }, }); export interface SliderProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; value?: number; min?: number; max?: number; step?: number; disabled?: boolean; onValueChange?: (value: number) => void; } export function Slider({ value = 0, min = 0, max = 100, step = 1, disabled, size, onValueChange, className, ...props }: SliderProps) { const trackWidth = useSharedValue(0); // The thumb/fill follow this shared value so they track the finger even if // the consumer doesn't echo `value` back synchronously. const pct = useSharedValue(max > min ? ((value - min) / (max - min)) * 100 : 0); const isDragging = useSharedValue(false); const thumbSize = size === "lg" ? 24 : size === "sm" ? 16 : 20; const colors = useThemeColors(); useEffect(() => { if (!isDragging.value) { pct.value = max > min ? ((value - min) / (max - min)) * 100 : 0; } }, [value, min, max, pct, isDragging]); const setFromX = useCallback((locationX: number) => { "worklet"; const w = trackWidth.value; if (w <= 0) return; const ratio = Math.max(0, Math.min(1, locationX / w)); const raw = min + ratio * (max - min); const stepped = Math.round(raw / step) * step; const clamped = Math.max(min, Math.min(max, stepped)); pct.value = max > min ? ((clamped - min) / (max - min)) * 100 : 0; if (onValueChange) runOnJS(onValueChange)(clamped); }, [min, max, step, onValueChange, trackWidth, pct]); const gesture = Gesture.Pan() .enabled(!disabled) .onBegin((e) => { isDragging.value = true; setFromX(e.x); }) .onUpdate((e) => { setFromX(e.x); }) .onFinalize(() => { isDragging.value = false; }) .minDistance(0); // transform: scaleX instead of width — the fill's box is always full-width, // only its visual scale changes, so this never triggers a native layout // pass the way animating `width` on every drag frame would. const fillStyle = useAnimatedStyle(() => ({ transform: [{ scaleX: pct.value / 100 }], transformOrigin: "left", })); const thumbStyle = useAnimatedStyle(() => ({ position: "absolute" as const, left: `${pct.value}%`, marginLeft: -(thumbSize / 2), width: thumbSize, height: thumbSize, borderRadius: thumbSize / 2, borderWidth: 2, borderColor: colors.foreground, backgroundColor: colors.background, })); return ( { trackWidth.value = e.nativeEvent.layout.width; }} {...props} > ); } ``` ## SocialButton - key: `social-button` - import: `import { SocialButton } from "@/components/ui/social-button"` - description: Branded social sign-in button with default Google/Apple/GitHub/X marks, outline/filled/ghost variants, and a press-scale spring - tier: 2 - deps: class-variance-authority, react-native-svg, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/social-button.tsx import React from "react"; import { Pressable, Text, type GestureResponderEvent } from "react-native"; import Animated, { useAnimatedStyle, useSharedValue, withSpring, type WithSpringConfig } from "react-native-reanimated"; import Svg, { Path } from "react-native-svg"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; export type SocialProvider = "google" | "apple" | "github" | "twitter"; export type SocialButtonVariant = "outline" | "filled" | "ghost"; const PRESS_SPRING: WithSpringConfig = { damping: 18, stiffness: 320, mass: 0.5 }; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); // --- Brand marks ----------------------------------------------------------- // `color` flattens every path in a mark to one tone (used for the "filled" // variant's on-brand-surface silhouette); omit it to keep each mark's own // brand-accurate colors (used for "outline"/"ghost"). export interface SocialMarkProps { size?: number; color?: string; } // Confidence: HIGH — this is Google's own widely-published 4-color "G" // lockup (the same geometry used in Google's official Sign-in button // assets), reproduced independently from public knowledge of the mark. function GoogleMark({ size = 20, color }: SocialMarkProps) { return ( ); } // Confidence: HIGH — the classic single-path GitHub "octocat" mark, the // same silhouette geometry GitHub itself ships (octicons `mark-github`). function GitHubMark({ size = 20, color }: SocialMarkProps) { return ( ); } // Confidence: HIGH — the bold crossing-strokes "X" glyph (post-rebrand // Twitter/X wordmark), a simple geometric mark reproduced from public // knowledge of the shape. function XMark({ size = 20, color }: SocialMarkProps) { return ( ); } // Confidence: LOW / BEST-EFFORT PLACEHOLDER — this is a hand-constructed, // deliberately simplified apple silhouette (rounded twin-lobe body tapering // to a point, plus a separate stem + leaf), NOT a verified redraw of Apple's // official press-kit bezier geometry (that path has many precise control // points I can't reproduce from memory with confidence, and lucide's own // "Apple" icon is the fruit emoji glyph, not the brand mark, so it isn't a // usable fallback either). Recommend a follow-up pass swapping this for // path data verified against Apple's official brand assets. function AppleMark({ size = 20, color }: SocialMarkProps) { const fill = color ?? "#000000"; return ( ); } const BRAND_MARKS: Record React.ReactElement> = { google: GoogleMark, apple: AppleMark, github: GitHubMark, twitter: XMark, }; const BRAND_LABELS: Record = { google: "Continue with Google", apple: "Continue with Apple", github: "Continue with GitHub", twitter: "Continue with X", }; // Provider brand color used only for the "filled" surface/border/icon — Google // is deliberately excluded (its brand surface is already white, so "filled" // falls back to the same look as "outline" instead of a solid brand block). const BRAND_FILLED: Record, { surface: string; border: string }> = { apple: { surface: "bg-[#000000]", border: "border-[#000000]" }, github: { surface: "bg-[#181717]", border: "border-[#181717]" }, twitter: { surface: "bg-[#000000]", border: "border-[#000000]" }, }; interface SocialPalette { surface: string; border: string; label: string; icon?: string; } function paletteFor(provider: SocialProvider, variant: SocialButtonVariant): SocialPalette { if (variant === "filled") { if (provider === "google") { return { surface: "bg-background", border: "border-border", label: "text-foreground" }; } const brand = BRAND_FILLED[provider]; return { surface: brand.surface, border: brand.border, label: "text-white", icon: "#FFFFFF" }; } if (variant === "ghost") { return { surface: "bg-transparent", border: "border-transparent", label: "text-foreground" }; } return { surface: "bg-background", border: "border-border", label: "text-foreground" }; // outline (default) } const socialButtonVariants = cva( "flex-row items-center justify-center gap-2 rounded-lg border min-h-12 px-4", { variants: { size: { sm: "h-10", md: "h-12", lg: "h-14" } }, defaultVariants: { size: "md" }, } ); const labelVariants = cva("text-sm font-semibold"); export interface SocialButtonProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; provider?: SocialProvider; variant?: SocialButtonVariant; label?: string; icon?: React.ReactNode; } export function SocialButton({ provider, variant, size, className, label, icon, disabled, onPressIn, onPressOut, ...props }: SocialButtonProps) { const p = provider ?? "google"; const v = variant ?? "outline"; const palette = paletteFor(p, v); const Mark = BRAND_MARKS[p]; const scale = useSharedValue(1); const animatedStyle = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] })); const handlePressIn = (e: GestureResponderEvent) => { scale.value = withSpring(0.97, PRESS_SPRING); onPressIn?.(e); }; const handlePressOut = (e: GestureResponderEvent) => { scale.value = withSpring(1, PRESS_SPRING); onPressOut?.(e); }; return ( {icon ?? } {label ?? BRAND_LABELS[p]} ); } ``` ## SpinButton - key: `spin-button` - import: `import { SpinButton } from "@/components/ui/spin-button"` - description: Toggle button with a custom SVG arc spinner and crossfading label on press - tier: 2 - deps: react-native-svg, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/spin-button.tsx import React, { useCallback, useEffect } from "react"; import { Pressable, Text, View } from "react-native"; import Animated, { Easing, cancelAnimation, interpolate, useAnimatedStyle, useSharedValue, withRepeat, withSpring, withTiming, } from "react-native-reanimated"; import Svg, { Circle } from "react-native-svg"; import { cn } from "@/lib/utils"; export interface SpinButtonProps extends Omit, "onPress"> { className?: string; idleText?: string; activeText?: string; /** Fully controlled — the parent owns the saving state, like other AniUI toggles. */ saving?: boolean; onSavingChange?: (saving: boolean) => void; disabled?: boolean; } /** Button that swaps its label for a custom spinning SVG arc while `saving`. */ export function SpinButton({ className, idleText = "Save", activeText = "Saving", saving = false, onSavingChange, disabled = false, ...props }: SpinButtonProps) { const progress = useSharedValue(saving ? 1 : 0); const pressed = useSharedValue(0); const rotation = useSharedValue(0); useEffect(() => { progress.value = withTiming(saving ? 1 : 0, { duration: 220 }); if (saving) { rotation.value = withRepeat(withTiming(rotation.value + 360, { duration: 850, easing: Easing.linear }), -1, false); } else { cancelAnimation(rotation); } }, [saving, progress, rotation]); const handlePress = useCallback(() => { if (disabled) return; onSavingChange?.(!saving); }, [disabled, saving, onSavingChange]); const buttonStyle = useAnimatedStyle(() => ({ transform: [{ scale: interpolate(pressed.value, [0, 1], [1, 0.96]) }], })); const idleStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 1], [1, 0]), transform: [{ translateY: interpolate(progress.value, [0, 1], [0, -10]) }], })); const activeStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 1], [0, 1]), transform: [{ translateY: interpolate(progress.value, [0, 1], [10, 0]) }], })); const spinnerStyle = useAnimatedStyle(() => ({ opacity: progress.value, transform: [{ rotate: `${rotation.value}deg` }], })); const size = 16; const strokeWidth = 2; const radius = (size - strokeWidth) / 2; const circumference = 2 * Math.PI * radius; return ( (pressed.value = withSpring(1, { damping: 14, stiffness: 220 }))} onPressOut={() => (pressed.value = withSpring(0, { damping: 14, stiffness: 220 }))} disabled={disabled} accessibilityRole="button" accessibilityState={{ disabled, busy: saving }} accessibilityLabel={saving ? activeText : idleText} accessible={true} className={cn("min-h-12 min-w-12 flex-row items-center justify-center gap-2 rounded-full bg-primary px-6", disabled && "opacity-50", className)} {...props} > {idleText.length >= activeText.length ? idleText : activeText} {idleText} {activeText} ); } ``` ## Spinner - key: `spinner` - import: `import { Spinner } from "@/components/ui/spinner"` - description: Loading spinner with sizes - tier: 1 - deps: clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/spinner.tsx import React from "react"; import { ActivityIndicator, View } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const sizeMap = { sm: "small", md: "small", lg: "large" } as const; export interface SpinnerProps extends React.ComponentPropsWithoutRef { className?: string; size?: "sm" | "md" | "lg"; color?: string; } export function Spinner({ size = "md", color, className, ...props }: SpinnerProps) { const colors = useThemeColors(); return ( ); } ``` ## SplitView - key: `split-view` - import: `import { SplitView } from "@/components/ui/split-view"` - description: Draggable, resizable top/bottom split pane with snap points and spring physics - tier: 3 - deps: react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge ```tsx // components/ui/split-view.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react"; import { Text, View, type LayoutChangeEvent } from "react-native"; import { Gesture, GestureDetector, type PanGesture } from "react-native-gesture-handler"; import Animated, { Extrapolation, interpolate, runOnJS, useAnimatedStyle, useSharedValue, withSpring, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; const DEFAULT_SPRING: WithSpringConfig = { damping: 12, stiffness: 150, mass: 0.5 }; const HANDLE_HIT_SLOP = 12; const SNAP_BIAS = 20; function clamp(value: number, min: number, max: number): number { "worklet"; return Math.min(Math.max(value, min), max); } /** * Pick the snap point for a settled drag. A fast fling jumps to the next * point in the fling direction; a slow release lands on the nearest point. */ function resolveSnapTarget( current: number, velocity: number, snapPoints: readonly number[], threshold: number ): number { "worklet"; if (Math.abs(velocity) > threshold) { if (velocity > 0) { for (let i = 0; i < snapPoints.length; i++) { if (snapPoints[i] > current + SNAP_BIAS) return snapPoints[i]; } return snapPoints[snapPoints.length - 1]; } for (let i = snapPoints.length - 1; i >= 0; i--) { if (snapPoints[i] < current - SNAP_BIAS) return snapPoints[i]; } return snapPoints[0]; } let best = snapPoints[0]; let bestDistance = Math.abs(snapPoints[0] - current); for (let i = 1; i < snapPoints.length; i++) { const distance = Math.abs(snapPoints[i] - current); if (distance < bestDistance) { bestDistance = distance; best = snapPoints[i]; } } return best; } interface SplitViewContextValue { topHeight: SharedValue; handleScale: SharedValue; gap: number; minTop: number; maxTop: number; gesture: PanGesture; } const SplitViewContext = createContext(null); function useSplitView(component: string) { const ctx = useContext(SplitViewContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } export interface SplitViewProps { children: React.ReactNode; className?: string; initialTopHeight?: number; minTopHeight?: number; minBottomHeight?: number; maxTopHeight?: number; gap?: number; snapPoints?: number[]; velocityThreshold?: number; springConfig?: WithSpringConfig; onHeightChange?: (height: number) => void; } /** * Draggable, resizable top/bottom split pane. The handle's pan gesture drives * the top pane's height directly while dragging, then projects the release * velocity forward to decide which snap point (nearest for a slow release, * next-in-direction for a fast flick) to spring to — same technique as a * bottom sheet's detents, applied to an in-page divider instead of a modal. */ export function SplitView({ children, className, initialTopHeight = 300, minTopHeight = 80, minBottomHeight = 80, maxTopHeight, gap = 28, snapPoints, velocityThreshold = 500, springConfig = DEFAULT_SPRING, onHeightChange, }: SplitViewProps) { const [containerHeight, setContainerHeight] = useState(0); const topHeight = useSharedValue(initialTopHeight); const startY = useSharedValue(0); const handleScale = useSharedValue(1); const minTop = minTopHeight; const maxTop = maxTopHeight ?? Math.max(minTop + 1, containerHeight - gap - minBottomHeight); const resolvedSnapPoints = useMemo(() => { if (snapPoints && snapPoints.length > 0) return [...snapPoints].sort((a, b) => a - b); return [minTop, (minTop + maxTop) / 2, maxTop]; }, [snapPoints, minTop, maxTop]); useEffect(() => { if (containerHeight <= 0) return; const bounded = clamp(topHeight.value, minTop, maxTop); if (bounded !== topHeight.value) topHeight.value = withSpring(bounded, springConfig); // topHeight is a SharedValue ref, safe to omit from deps. // eslint-disable-next-line react-hooks/exhaustive-deps }, [containerHeight, minTop, maxTop]); const gesture = useMemo( () => Gesture.Pan() .hitSlop({ top: HANDLE_HIT_SLOP, bottom: HANDLE_HIT_SLOP }) .onStart(() => { startY.value = topHeight.value; handleScale.value = withSpring(1.18, springConfig); }) .onUpdate((event) => { topHeight.value = clamp(startY.value + event.translationY, minTop, maxTop); }) .onEnd((event) => { const velocity = clamp(event.velocityY, -4000, 4000); const target = resolveSnapTarget( topHeight.value, velocity, resolvedSnapPoints, velocityThreshold ); topHeight.value = withSpring(target, { ...springConfig, overshootClamping: true }); if (onHeightChange) runOnJS(onHeightChange)(target); }) .onFinalize(() => { handleScale.value = withSpring(1, springConfig); }), [ minTop, maxTop, resolvedSnapPoints, velocityThreshold, springConfig, onHeightChange, topHeight, startY, handleScale, ] ); const onLayout = useCallback((event: LayoutChangeEvent) => { setContainerHeight(event.nativeEvent.layout.height); }, []); const ctx = useMemo( () => ({ topHeight, handleScale, gap, minTop, maxTop, gesture }), [topHeight, handleScale, gap, minTop, maxTop, gesture] ); return ( {children} ); } export interface SplitViewPaneProps { children: React.ReactNode; className?: string; } export function SplitViewTop({ children, className }: SplitViewPaneProps) { const { topHeight, minTop } = useSplitView("SplitViewTop"); const style = useAnimatedStyle(() => ({ height: topHeight.value, opacity: interpolate(topHeight.value, [minTop, minTop + 60], [0.2, 1], Extrapolation.CLAMP), })); return ( {children} ); } export function SplitViewBottom({ children, className }: SplitViewPaneProps) { const { topHeight, maxTop } = useSplitView("SplitViewBottom"); const style = useAnimatedStyle(() => ({ opacity: interpolate(topHeight.value, [maxTop - 60, maxTop], [1, 0.2], Extrapolation.CLAMP), })); return ( {children} ); } export interface SplitViewHandleProps { className?: string; barClassName?: string; } export function SplitViewHandle({ className, barClassName }: SplitViewHandleProps) { const { gesture, handleScale, gap } = useSplitView("SplitViewHandle"); const barStyle = useAnimatedStyle(() => ({ transform: [{ scale: handleScale.value }], })); return ( ); } export interface SplitViewTitleProps { children: React.ReactNode; className?: string; } export function SplitViewTitle({ children, className }: SplitViewTitleProps) { return ( {children} ); } ``` ## StackedChips - key: `stacked-chips` - import: `import { StackedChips } from "@/components/ui/stacked-chips"` - description: Nested, depth-aware expandable chip menu — a trigger reveals further stacked chips - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/stacked-chips.tsx import React, { createContext, useContext, useState } from "react"; import { Pressable, Text, View, type LayoutChangeEvent } from "react-native"; import Animated, { interpolate, useAnimatedStyle, useDerivedValue, withSpring } from "react-native-reanimated"; import { cn } from "@/lib/utils"; interface ChipContextValue { open: boolean; toggle: () => void; depth: number; parentOpen: boolean; triggerWidth: number; setTriggerWidth: (w: number) => void; } const ChipContext = createContext(null); export interface StackedChipsProps extends React.ComponentPropsWithoutRef { children: React.ReactNode; className?: string; } /** Root of a nested/expandable chip menu — wrap another StackedChips inside Content to go deeper. */ export function StackedChips({ children, className, style, ...props }: StackedChipsProps) { const parent = useContext(ChipContext); const [open, setOpen] = useState(false); const [triggerWidth, setTriggerWidth] = useState(0); const depth = parent ? parent.depth + 1 : 0; const parentOpen = parent ? parent.open : true; return ( setOpen((o) => !o), depth, parentOpen, triggerWidth, setTriggerWidth }} > {children} ); } export interface StackedChipsTriggerProps { children: React.ReactNode; className?: string; onPress?: () => void; } export function StackedChipsTrigger({ children, className, onPress }: StackedChipsTriggerProps) { const ctx = useContext(ChipContext); if (!ctx) throw new Error("StackedChipsTrigger must be used within StackedChips"); const { toggle, depth, parentOpen, setTriggerWidth, open } = ctx; const progress = useDerivedValue(() => withSpring(parentOpen ? 1 : 0)); const revealStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 1], [0, 1]), transform: [{ scale: interpolate(progress.value, [0, 1], [0.85, 1]) }], })); const handleLayout = (e: LayoutChangeEvent) => setTriggerWidth(e.nativeEvent.layout.width); return ( 0 ? revealStyle : undefined} onLayout={handleLayout}> { toggle(); onPress?.(); }} accessibilityRole="button" accessibilityState={{ expanded: open }} accessible={true} className={cn("min-h-12 min-w-12 flex-row items-center justify-center rounded-full bg-secondary px-4", className)} > {typeof children === "string" ? {children} : children} ); } export interface StackedChipsContentProps { children: React.ReactNode; className?: string; } /** The chips revealed beside a trigger once it's open. */ export function StackedChipsContent({ children, className }: StackedChipsContentProps) { const ctx = useContext(ChipContext); if (!ctx) throw new Error("StackedChipsContent must be used within StackedChips"); const { open, triggerWidth, depth } = ctx; const [contentWidth, setContentWidth] = useState(0); const style = useAnimatedStyle(() => ({ opacity: withSpring(open ? 1 : 0), transform: [{ translateX: withSpring(open ? 0 : -contentWidth + 60) }], })); return ( setContentWidth(e.nativeEvent.layout.width)} pointerEvents={open ? "auto" : "none"} style={[{ position: "absolute", left: triggerWidth + 8, top: 0, zIndex: 99 - depth }, style]} className={cn("min-h-12 flex-row items-center justify-center gap-2 rounded-full bg-secondary/95 py-1 pl-3 pr-2", className)} > {children} ); } ``` ## StatCard - key: `stat-card` - import: `import { StatCard } from "@/components/ui/stat-card"` - description: KPI display card with value, trend indicator, and change percentage - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: card ```tsx // components/ui/stat-card.tsx import React from "react"; import { View, Text } from "react-native"; import { ArrowDown, ArrowUp } from "lucide-react-native"; import { cn } from "@/lib/utils"; export interface StatCardProps extends React.ComponentPropsWithoutRef { className?: string; label: string; value: string | number; change?: number; trend?: "up" | "down" | "neutral"; icon?: React.ReactNode; } export function StatCard({ className, label, value, change, trend, icon, ...props }: StatCardProps) { const trendColor = trend === "up" ? "text-green-500" : trend === "down" ? "text-destructive" : "text-muted-foreground"; return ( {label} {icon && {icon}} {value} {change !== undefined && ( {trend === "up" && } {trend === "down" && } {change > 0 ? "+" : ""}{change}% )} ); } ``` ## StatusIndicator - key: `status-indicator` - import: `import { StatusIndicator } from "@/components/ui/status-indicator"` - description: Colored dot for online/offline/away/busy status - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/status-indicator.tsx import React from "react"; import { View } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const statusVariants = cva("rounded-full", { variants: { status: { online: "bg-green-500", offline: "bg-muted-foreground", away: "bg-amber-500", busy: "bg-destructive", }, size: { sm: "h-2 w-2", md: "h-3 w-3", lg: "h-4 w-4", }, }, defaultVariants: { status: "offline", size: "md" }, }); export interface StatusIndicatorProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; pulse?: boolean; } export function StatusIndicator({ status, size, pulse, className, ...props }: StatusIndicatorProps) { return ( ); } ``` ## Stepper - key: `stepper` - import: `import { Stepper } from "@/components/ui/stepper"` - description: Numeric increment/decrement control with min/max/step - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/stepper.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { Minus, Plus } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const stepperVariants = cva("flex-row items-center self-start rounded-lg border border-border", { variants: { size: { sm: "h-9", md: "h-12", lg: "h-14", }, }, defaultVariants: { size: "md" }, }); const buttonVariants = cva("items-center justify-center border-border", { variants: { size: { sm: "w-9", md: "w-12", lg: "w-14", }, }, defaultVariants: { size: "md" }, }); export interface StepperProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; value: number; onChange: (value: number) => void; min?: number; max?: number; step?: number; } export function Stepper({ size, className, value, onChange, min = 0, max = 99, step = 1, ...props }: StepperProps) { const colors = useThemeColors(); const fg = colors.foreground; const canDec = value - step >= min; const canInc = value + step <= max; return ( { if (canDec) onChange(value - step); }} disabled={!canDec} accessible={true} accessibilityRole="button" accessibilityLabel="Decrease" > {value} { if (canInc) onChange(value + step); }} disabled={!canInc} accessible={true} accessibilityRole="button" accessibilityLabel="Increase" > ); } ``` ## StreamingText - key: `streaming-text` - import: `import { StreamingText } from "@/components/ui/streaming-text"` - description: Typewriter-style streaming AI response text with a blinking cursor - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/streaming-text.tsx import React, { useEffect, useRef, useState } from "react"; import { Text } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withTiming, cancelAnimation } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; export interface StreamingTextProps extends React.ComponentPropsWithoutRef { className?: string; /** Target text — may grow over time as tokens stream in from an API. */ text: string; /** Reveal `text` progressively (default true). false renders it instantly. */ typewriter?: boolean; /** Reveal speed in characters per second (default 60). */ speed?: number; /** Keep the cursor blinking even when caught up (e.g. between API chunks). */ streaming?: boolean; showCursor?: boolean; onComplete?: () => void; } function Cursor() { const opacity = useSharedValue(1); const reducedMotion = useReducedMotion(); useEffect(() => { if (reducedMotion) return; opacity.value = withRepeat(withTiming(0, { duration: 500 }), -1, true); return () => cancelAnimation(opacity); }, [opacity, reducedMotion]); const style = useAnimatedStyle(() => ({ opacity: opacity.value })); // The cursor is a typographic block glyph (not an icon) so it flows inline // with the revealed text; Animated.Text lets it blink via opacity. return ▍; } export function StreamingText({ className, text, typewriter = true, speed = 60, streaming, showCursor = true, onComplete, ...props }: StreamingTextProps) { const [count, setCount] = useState(typewriter ? 0 : text.length); const shown = useRef(""); // If `text` was replaced (not appended to), restart the reveal. useEffect(() => { if (!text.startsWith(shown.current)) setCount(typewriter ? 0 : text.length); }, [text, typewriter]); useEffect(() => { if (!typewriter || count >= text.length) return; const tick = 33; const chars = Math.max(1, Math.round((speed * tick) / 1000)); const timer = setInterval(() => { setCount((c) => Math.min(text.length, c + chars)); }, tick); return () => clearInterval(timer); }, [typewriter, count, text, speed]); // Fire onComplete once per reveal, only when fully caught up and not streaming. const completed = useRef(false); useEffect(() => { const isDone = count >= text.length && text.length > 0 && !streaming; if (isDone && !completed.current) { completed.current = true; onComplete?.(); } if (!isDone) completed.current = false; }, [count, text, streaming, onComplete]); const visible = typewriter ? text.slice(0, count) : text; shown.current = visible; const done = visible.length >= text.length && !streaming; return ( {visible} {showCursor && !done && } ); } ``` ## SwipeDeck - key: `swipe-deck` - import: `import { SwipeDeck } from "@/components/ui/swipe-deck"` - description: Tinder-style swipeable card stack with fling physics and swipe callbacks - tier: 3 - deps: react-native-gesture-handler, react-native-reanimated, clsx, tailwind-merge ```tsx // components/ui/swipe-deck.tsx import React, { useState } from "react"; import { View } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming, interpolate, runOnJS } from "react-native-reanimated"; import { cn } from "@/lib/utils"; export interface SwipeDeckProps extends React.ComponentPropsWithoutRef { className?: string; data: T[]; renderCard: (item: T, index: number) => React.ReactNode; onSwipeLeft?: (item: T, index: number) => void; onSwipeRight?: (item: T, index: number) => void; /** Fired after the last card is swiped away. */ onEmpty?: () => void; } export function SwipeDeck({ className, data, renderCard, onSwipeLeft, onSwipeRight, onEmpty, onLayout, ...props }: SwipeDeckProps) { const [index, setIndex] = useState(0); const [width, setWidth] = useState(0); const tx = useSharedValue(0); const ty = useSharedValue(0); const advance = (dir: 1 | -1) => { const item = data[index]; (dir === 1 ? onSwipeRight : onSwipeLeft)?.(item, index); tx.value = 0; ty.value = 0; const next = index + 1; setIndex(next); if (next >= data.length) onEmpty?.(); }; const gesture = Gesture.Pan() .enabled(index < data.length && width > 0) .onUpdate((e) => { tx.value = e.translationX; ty.value = e.translationY; }) .onEnd((e) => { const threshold = width * 0.35; if (Math.abs(tx.value) > threshold || Math.abs(e.velocityX) > 900) { const dir: 1 | -1 = tx.value > 0 || (Math.abs(tx.value) <= threshold && e.velocityX > 0) ? 1 : -1; tx.value = withTiming(dir * width * 1.4, { duration: 200 }, () => runOnJS(advance)(dir)); ty.value = withTiming(ty.value + e.velocityY * 0.05, { duration: 200 }); } else { tx.value = withSpring(0); ty.value = withSpring(0); } }); const topStyle = useAnimatedStyle(() => ({ transform: [ { translateX: tx.value }, { translateY: ty.value }, { rotate: `${interpolate(tx.value, [-width || -1, width || 1], [-12, 12])}deg` }, ], })); // The card behind grows into place as the top card is dragged away. const nextStyle = useAnimatedStyle(() => { const progress = Math.min(1, Math.abs(tx.value) / ((width || 1) * 0.5)); return { transform: [{ scale: 0.95 + 0.05 * progress }, { translateY: 8 - 8 * progress }] }; }); const top = data[index]; const next = data[index + 1]; return ( { setWidth(e.nativeEvent.layout.width); onLayout?.(e); }} {...props} > {next !== undefined && ( {renderCard(next, index + 1)} )} {top !== undefined && ( {renderCard(top, index)} )} ); } ``` ## SwipeableListItem - key: `swipeable-list-item` - import: `import { SwipeableListItem } from "@/components/ui/swipeable-list-item"` - description: Swipeable list item revealing action buttons on swipe - tier: 3 - deps: react-native-reanimated, react-native-gesture-handler, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/swipeable-list-item.tsx import React, { useCallback } from "react"; import { View, Text, Pressable } from "react-native"; import { Gesture, GestureDetector } from "react-native-gesture-handler"; import Animated, { useSharedValue, useAnimatedStyle, withSpring, runOnJS } from "react-native-reanimated"; import { cn } from "@/lib/utils"; import { springs } from "@/components/ui/animate"; const ACTION_WIDTH = 80; export interface SwipeableAction { key: string; label: string; icon?: React.ReactNode; color: string; textColor?: string; onPress: () => void; } export interface SwipeableListItemProps extends React.ComponentPropsWithoutRef { children: React.ReactNode; leftActions?: SwipeableAction[]; rightActions?: SwipeableAction[]; onSwipeOpen?: (direction: "left" | "right") => void; enabled?: boolean; className?: string; } function ActionTray({ actions, side }: { actions: SwipeableAction[]; side: "left" | "right" }) { return ( {actions.map((action) => ( {action.icon} {action.label} ))} ); } export function SwipeableListItem({ children, leftActions = [], rightActions = [], onSwipeOpen, enabled = true, className, ...props }: SwipeableListItemProps) { const translateX = useSharedValue(0); const startX = useSharedValue(0); const leftWidth = leftActions.length * ACTION_WIDTH; const rightWidth = rightActions.length * ACTION_WIDTH; const notifyOpen = useCallback( (dir: "left" | "right") => onSwipeOpen?.(dir), [onSwipeOpen] ); const pan = Gesture.Pan() .activeOffsetX([-10, 10]) .enabled(enabled) .onStart(() => { startX.value = translateX.value; }) .onUpdate((e) => { translateX.value = Math.max(-rightWidth, Math.min(leftWidth, startX.value + e.translationX)); }) .onEnd((e) => { const x = translateX.value; if (x > 0 && leftWidth > 0) { const open = x > leftWidth * 0.5 || e.velocityX > 500; translateX.value = withSpring(open ? leftWidth : 0, springs.snappy); if (open) runOnJS(notifyOpen)("left"); } else if (x < 0 && rightWidth > 0) { const open = Math.abs(x) > rightWidth * 0.5 || e.velocityX < -500; translateX.value = withSpring(open ? -rightWidth : 0, springs.snappy); if (open) runOnJS(notifyOpen)("right"); } else { translateX.value = withSpring(0, springs.snappy); } }); const contentStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }], })); return ( {leftActions.length > 0 && } {rightActions.length > 0 && } {children} ); } ``` ## Switch - key: `switch` - import: `import { Switch } from "@/components/ui/switch"` - description: Toggle switch - tier: 1 - deps: clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/switch.tsx import React from "react"; import { View, Switch as RNSwitch } from "react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; // Omit `className` from RN's SwitchProps before re-adding it: newer RN // type definitions bake `className?: undefined` into native-only components // to signal that className isn't supported natively (NativeWind re-adds it // via its jsx interop layer at runtime). The outer wrapper View below is // what actually consumes the className — we're not trying to pass it down // to RNSwitch — so omit upstream and re-declare locally without the clash. export interface SwitchProps extends Omit, "className"> { className?: string; trackColorOff?: string; trackColorOn?: string; thumbColor?: string; } export function Switch({ className, trackColorOff, trackColorOn, thumbColor, value, ...props }: SwitchProps) { const colors = useThemeColors(); const off = trackColorOff ?? colors.border; const on = trackColorOn ?? colors.foreground; // Thumb must contrast with the track in every state. In dark mode the ON // track is near-white, so a default white thumb would disappear on iOS. const thumb = thumbColor ?? colors.background; return ( ); } ``` ## TabBar - key: `tab-bar` - import: `import { TabBar } from "@/components/ui/tab-bar"` - description: Bottom tab bar with badge support and active states - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: badge, text ```tsx // components/ui/tab-bar.tsx import React from "react"; import { View, Pressable, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const tabBarVariants = cva("flex-row border-t pb-6 pt-2 px-2", { variants: { variant: { default: "bg-background border-border", card: "bg-card border-border", transparent: "bg-transparent border-transparent", }, }, defaultVariants: { variant: "default" }, }); export interface TabBarProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; children?: React.ReactNode; } export function TabBar({ variant, className, children, ...props }: TabBarProps) { return ( {children} ); } export interface TabBarItemProps extends React.ComponentPropsWithoutRef { className?: string; active?: boolean; icon?: React.ReactNode; label?: string; badge?: number; onPress?: () => void; } export function TabBarItem({ active, icon, label, badge, className, onPress, ...props }: TabBarItemProps) { return ( {icon && {icon}} {label && ( {label} )} {badge !== undefined && badge > 0 && ( {badge > 99 ? "99+" : badge} )} ); } ``` ## Table - key: `table` - import: `import { Table } from "@/components/ui/table"` - description: Data table with header, body, rows, and cells - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/table.tsx import React, { createContext, useContext } from "react"; import { View, Text, ScrollView, type StyleProp, type ViewStyle } from "react-native"; import { cn } from "@/lib/utils"; type TableContextValue = { truncate: boolean; defaultColumnWidth: number }; const TableContext = createContext({ truncate: false, defaultColumnWidth: 150 }); export type TableViewProps = React.ComponentPropsWithoutRef & { className?: string; children?: React.ReactNode }; export interface TableProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; /** When true, fit columns to container width and truncate long content. Default false: each cell * has a fixed pixel width and the table scrolls horizontally if total content exceeds the viewport. */ truncate?: boolean; /** Default pixel width for each cell. Used in scroll mode (truncate=false). Defaults to 150. */ defaultColumnWidth?: number; } export interface TableCellProps extends TableViewProps { textClassName?: string } const truncateCellStyle: StyleProp = { flexGrow: 1, flexShrink: 1, flexBasis: 0, minWidth: 0, overflow: "hidden" }; export function Table({ className, children, truncate = false, defaultColumnWidth = 150, ...props }: TableProps) { return ( {children} ); } export function TableHeader({ className, ...props }: TableViewProps) { return ; } export function TableBody({ className, ...props }: TableViewProps) { return ; } export function TableRow({ className, ...props }: TableViewProps) { return ; } export function TableHead({ className, textClassName, children, style, ...props }: TableCellProps) { const { truncate, defaultColumnWidth } = useContext(TableContext); const isText = typeof children === "string" || typeof children === "number"; const widthStyle: StyleProp = truncate ? truncateCellStyle : { width: defaultColumnWidth, overflow: "hidden" }; return ( {isText ? {children} : children} ); } export function TableCell({ className, textClassName, children, style, ...props }: TableCellProps) { const { truncate, defaultColumnWidth } = useContext(TableContext); const isText = typeof children === "string" || typeof children === "number"; const widthStyle: StyleProp = truncate ? truncateCellStyle : { width: defaultColumnWidth, overflow: "hidden" }; return ( {isText ? {children} : children} ); } ``` ## Tabs - key: `tabs` - import: `import { Tabs } from "@/components/ui/tabs"` - description: Tab navigation with filled/line variants, sizes, vertical, disabled, and icon support - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/tabs.tsx import React, { createContext, useContext, useState } from "react"; import { View, Pressable, Text } from "react-native"; import { cva } from "class-variance-authority"; import { cn } from "@/lib/utils"; type TabsVariant = "filled" | "line"; type TabsSize = "sm" | "md" | "lg"; type TabsOrientation = "horizontal" | "vertical"; const TabsCtx = createContext<{ value: string; onValueChange: (v: string) => void; variant: TabsVariant; size: TabsSize; orientation: TabsOrientation; }>({ value: "", onValueChange: () => {}, variant: "filled", size: "md", orientation: "horizontal" }); export interface TabsProps extends React.ComponentPropsWithoutRef { className?: string; defaultValue: string; variant?: TabsVariant; size?: TabsSize; orientation?: TabsOrientation; children?: React.ReactNode; } export function Tabs({ defaultValue, variant = "filled", size = "md", orientation = "horizontal", className, children, ...props }: TabsProps) { const [value, setValue] = useState(defaultValue); return ( {children} ); } const listVariants = cva("", { variants: { variant: { filled: "rounded-lg bg-muted p-1", line: "border-b border-border" }, orientation: { horizontal: "flex-row", vertical: "flex-col border-b-0 border-e border-border rounded-none" }, }, defaultVariants: { variant: "filled", orientation: "horizontal" }, }); export interface TabsListProps extends React.ComponentPropsWithoutRef { className?: string; } export function TabsList({ className, ...props }: TabsListProps) { const { variant, orientation } = useContext(TabsCtx); return ; } const triggerSize = cva("will-change-variable items-center justify-center", { variants: { size: { sm: "min-h-8 py-1 px-2.5", md: "min-h-10 py-2 px-3", lg: "min-h-12 py-2.5 px-4" }, }, defaultVariants: { size: "md" }, }); const triggerTextSize = cva("will-change-variable font-medium", { variants: { size: { sm: "text-xs", md: "text-sm", lg: "text-base" }, }, defaultVariants: { size: "md" }, }); export interface TabsTriggerProps extends React.ComponentPropsWithoutRef { className?: string; textClassName?: string; value: string; disabled?: boolean; icon?: React.ReactNode; children: React.ReactNode; } export function TabsTrigger({ value, disabled = false, icon, className, textClassName, children, ...props }: TabsTriggerProps) { const { value: selected, onValueChange, variant, size, orientation } = useContext(TabsCtx); const isActive = selected === value; return ( !disabled && onValueChange(value)} disabled={disabled} accessible={true} accessibilityRole="tab" accessibilityState={{ selected: isActive, disabled }} {...props} > {icon} {typeof children === "string" ? ( {children} ) : children} ); } export interface TabsContentProps extends React.ComponentPropsWithoutRef { className?: string; value: string; } export function TabsContent({ value, className, ...props }: TabsContentProps) { const { value: selected, orientation } = useContext(TabsCtx); if (selected !== value) return null; return ; } ``` ## Text - key: `text` - import: `import { Text } from "@/components/ui/text"` - description: Typography with heading and body variants - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/text.tsx import React from "react"; import { Text as RNText } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const textVariants = cva("text-foreground", { variants: { variant: { h1: "text-4xl font-extrabold tracking-tight", h2: "text-3xl font-bold tracking-tight", h3: "text-2xl font-semibold tracking-tight", h4: "text-xl font-semibold tracking-tight", p: "text-base leading-7", lead: "text-xl text-muted-foreground", large: "text-lg font-semibold", small: "text-sm font-medium leading-none", muted: "text-sm text-muted-foreground", }, }, defaultVariants: { variant: "p", }, }); export interface TextProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; } export function Text({ variant, className, ...props }: TextProps) { return ( ); } ``` ## Textarea - key: `textarea` - import: `import { Textarea } from "@/components/ui/textarea"` - description: Multi-line text input - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/textarea.tsx import React from "react"; import { View, TextInput, useColorScheme } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; // Padding lives on the wrapping View (a raw TextInput doesn't honor `px-*` // reliably), so the text inset matches Input and is consistent on all sides — // under both NativeWind and Uniwind. const textareaVariants = cva( "rounded-md border px-4 py-3 min-h-24", { variants: { variant: { default: "border-input bg-background", ghost: "border-transparent bg-transparent", }, }, defaultVariants: { variant: "default", }, } ); export interface TextareaProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; } export const Textarea = React.forwardRef< React.ElementRef, TextareaProps >(function Textarea({ variant, className, ...props }, ref) { const dark = useColorScheme() === "dark"; const colors = useThemeColors(); const caret = colors.foreground; return ( ); }); ``` ## ThemeProvider - key: `theme-provider` - import: `import { ThemeProvider } from "@/components/ui/theme-provider"` - description: Theme context provider with light/dark/system mode and toggle - tier: 1 - deps: clsx, tailwind-merge ```tsx // components/ui/theme-provider.tsx import React, { createContext, useCallback, useContext, useEffect, useState } from "react"; import { Appearance, useColorScheme as useNativeColorScheme, View } from "react-native"; import { cn } from "@/lib/utils"; type Theme = "light" | "dark" | "system"; const ThemeContext = createContext<{ theme: Theme; resolvedTheme: "light" | "dark"; setTheme: (theme: Theme) => void; toggleTheme: () => void; }>({ theme: "system", resolvedTheme: "light", setTheme: () => {}, toggleTheme: () => {}, }); export function useTheme() { return useContext(ThemeContext); } export interface ThemeProviderProps { children: React.ReactNode; defaultTheme?: Theme; className?: string; } // Try to detect and use Uniwind's setTheme if available let uniwindSetTheme: ((theme: string) => void) | null = null; try { const mod = require("uniwind"); if (mod?.Uniwind?.setTheme) { uniwindSetTheme = (theme: string) => mod.Uniwind.setTheme(theme); } } catch {} export function ThemeProvider({ children, defaultTheme = "system", className, }: ThemeProviderProps) { const systemScheme = useNativeColorScheme(); const [theme, setThemeState] = useState(defaultTheme); const resolvedTheme: "light" | "dark" = theme === "system" ? (systemScheme === "dark" ? "dark" : "light") : theme; const applyTheme = useCallback((resolved: "light" | "dark") => { if (uniwindSetTheme) { // Uniwind handles Appearance.setColorScheme internally uniwindSetTheme(resolved); } else { // NativeWind v4/v5: set system appearance directly try { Appearance.setColorScheme(resolved); } catch {} } }, []); const setTheme = useCallback((newTheme: Theme) => { setThemeState(newTheme); const resolved = newTheme === "system" ? (systemScheme === "dark" ? "dark" : "light") : newTheme; applyTheme(resolved); }, [systemScheme, applyTheme]); const toggleTheme = useCallback(() => { setThemeState((prev) => { const current = prev === "system" ? (systemScheme === "dark" ? "dark" : "light") : prev; const next = current === "dark" ? "light" : "dark"; applyTheme(next); return next; }); }, [systemScheme, applyTheme]); // Apply initial theme useEffect(() => { if (defaultTheme !== "system") { applyTheme(defaultTheme === "dark" ? "dark" : "light"); } }, [defaultTheme, applyTheme]); return ( {children} ); } // ─── AUTO-GENERATED THEME COLORS (written by `aniui init` / `aniui theme`) ─── // Do not hand-edit values below — regenerated whenever the theme preset changes. export const THEME_COLORS = { light: { background: "#ffffff", foreground: "#09090b", card: "#ffffff", cardForeground: "#09090b", primary: "#18181b", primaryForeground: "#fafafa", secondary: "#f4f4f5", secondaryForeground: "#18181b", muted: "#f4f4f5", mutedForeground: "#71717a", accent: "#f4f4f5", accentForeground: "#18181b", destructive: "#ef4444", destructiveForeground: "#fafafa", border: "#e4e4e7", input: "#e4e4e7", ring: "#18181b" }, dark: { background: "#09090b", foreground: "#fafafa", card: "#09090b", cardForeground: "#fafafa", primary: "#fafafa", primaryForeground: "#18181b", secondary: "#27272a", secondaryForeground: "#fafafa", muted: "#27272a", mutedForeground: "#a1a1aa", accent: "#27272a", accentForeground: "#fafafa", destructive: "#7f1d1d", destructiveForeground: "#fafafa", border: "#27272a", input: "#27272a", ring: "#d4d4d8" }, } as const; /** * The one place every component reads colors from when a native prop (a * toggle control's track/thumb, TextInput caret, Skia canvas fills, lucide * icon `color`, etc.) can't take a className token. Deliberately reads * useColorScheme() directly rather than useTheme().resolvedTheme — the * latter's context default doesn't track system appearance without a * ancestor, and this needs to stay reactive even in apps * that never mount one. */ export function useThemeColors() { const scheme = useNativeColorScheme(); return scheme === "dark" ? THEME_COLORS.dark : THEME_COLORS.light; } // ─── END AUTO-GENERATED THEME COLORS ─── ``` ## ThemeSwitch - key: `theme-switch` - import: `import { ThemeSwitch } from "@/components/ui/theme-switch"` - description: Sun/moon icon-morph theme toggle with an optional full-screen circular wipe transition - tier: 2 - deps: lucide-react-native, react-native-svg, react-native-reanimated, clsx, tailwind-merge - aniui deps: theme-provider ```tsx // components/ui/theme-switch.tsx import React, { useEffect, useRef, useState } from "react"; import { Modal, Pressable, View, useWindowDimensions } from "react-native"; import Animated, { Easing, Extrapolation, interpolate, runOnJS, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated"; import { Moon, Sun } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; export interface ThemeSwitchProps extends Omit, "onPress"> { className?: string; isDark: boolean; onToggle: () => void; size?: number; duration?: number; /** Plays a full-screen circular wipe from the toggle's position instead of just morphing the icon. */ wipe?: boolean; wipeLightColor?: string; wipeDarkColor?: string; } /** Sun/moon icon-morph theme toggle, with an optional whole-screen circular wipe transition. */ export function ThemeSwitch({ className, isDark, onToggle, size = 24, duration = 450, wipe = false, wipeLightColor = "#fafafa", wipeDarkColor = "#09090b", ...props }: ThemeSwitchProps) { const colors = useThemeColors(); const tint = colors.foreground; const { width, height } = useWindowDimensions(); const triggerRef = useRef(null); const [origin, setOrigin] = useState<{ x: number; y: number } | null>(null); const progress = useSharedValue(isDark ? 1 : 0); const wipeProgress = useSharedValue(0); useEffect(() => { progress.value = withTiming(isDark ? 1 : 0, { duration, easing: Easing.inOut(Easing.quad) }); }, [isDark, duration, progress]); const maxRadius = origin ? Math.hypot(Math.max(origin.x, width - origin.x), Math.max(origin.y, height - origin.y)) : 0; const handlePress = () => { if (!wipe) return onToggle(); // measureInWindow (not measure) — avoids the status-bar offset bug measure() has for // absolutely/Modal-positioned overlays. triggerRef.current?.measureInWindow((x, y, w, h) => { setOrigin({ x: x + w / 2, y: y + h / 2 }); wipeProgress.value = 0; wipeProgress.value = withTiming(1, { duration: duration * 1.6, easing: Easing.out(Easing.cubic) }, (done) => { if (done) runOnJS(setOrigin)(null); }); setTimeout(onToggle, duration * 0.5); }); }; const sunStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0, 0.5], [1, 0], Extrapolation.CLAMP), transform: [ { rotate: `${interpolate(progress.value, [0, 1], [0, 90])}deg` }, { scale: interpolate(progress.value, [0, 1], [1, 0.4], Extrapolation.CLAMP) }, ], })); const moonStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [0.5, 1], [0, 1], Extrapolation.CLAMP), transform: [ { rotate: `${interpolate(progress.value, [0, 1], [-90, 0])}deg` }, { scale: interpolate(progress.value, [0, 1], [0.4, 1], Extrapolation.CLAMP) }, ], })); const wipeStyle = useAnimatedStyle(() => ({ opacity: interpolate(wipeProgress.value, [0, 0.85, 1], [1, 1, 0], Extrapolation.CLAMP), transform: [{ scale: interpolate(wipeProgress.value, [0, 1], [0, 1], Extrapolation.CLAMP) }], })); return ( <> {wipe && origin && ( )} ); } ``` ## TimePicker - key: `time-picker` - import: `import { TimePicker } from "@/components/ui/time-picker"` - description: Animated scroll-snap wheel time picker with a spring modal and haptic tick, plus DateAndTimePicker (calendar + time) - tier: 2 - deps: react-native-reanimated, expo-haptics, lucide-react-native, react-native-svg, clsx, tailwind-merge - aniui deps: calendar, theme-provider, animate ```tsx // components/ui/time-picker.tsx import React, { useCallback, useEffect, useRef, useState } from "react"; import { View, Text, Pressable, Modal } from "react-native"; import Animated, { Extrapolation, interpolate, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withSpring, withTiming, type SharedValue, } from "react-native-reanimated"; import * as Haptics from "expo-haptics"; import { Clock, CalendarClock, type LucideIcon } from "lucide-react-native"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; import { springs, duration, usePressAnimation } from "@/components/ui/animate"; import { Calendar } from "@/components/ui/calendar"; const ROW_HEIGHT = 40; const VISIBLE_ROWS = 5; const WHEEL_HEIGHT = ROW_HEIGHT * VISIBLE_ROWS; const PAD = ROW_HEIGHT * Math.floor(VISIBLE_ROWS / 2); type MinuteInterval = 1 | 2 | 3 | 4 | 5 | 6 | 10 | 12 | 15 | 20 | 30; type Meridiem = "AM" | "PM"; interface BasePickerProps { className?: string; value?: Date; onChange?: (date: Date) => void; placeholder?: string; is24Hour?: boolean; minuteInterval?: MinuteInterval; } export interface TimePickerProps extends BasePickerProps { formatTime?: (date: Date) => string; } export interface DateTimePickerProps extends BasePickerProps { min?: Date; max?: Date; formatDateTime?: (date: Date) => string; } export interface DateAndTimePickerProps extends BasePickerProps { min?: Date; max?: Date; formatDateTime?: (date: Date) => string; } function defaultTime(date: Date, is24Hour?: boolean) { return date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit", hour12: !is24Hour }); } function defaultDateTime(date: Date, is24Hour?: boolean) { return `${date.toLocaleDateString()} ${defaultTime(date, is24Hour)}`; } function mergeDatePart(base: Date, next: Date) { const merged = new Date(base); merged.setFullYear(next.getFullYear(), next.getMonth(), next.getDate()); return merged; } function setTimeParts(base: Date, hour: number, minute: number, meridiem?: Meridiem) { const merged = new Date(base); let h = hour; if (meridiem) h = hour % 12 + (meridiem === "PM" ? 12 : 0); merged.setHours(h, minute, 0, 0); return merged; } function readTimeParts(date: Date, is24Hour?: boolean) { const minute = date.getMinutes(); if (is24Hour) return { hour: date.getHours(), minute, meridiem: undefined as Meridiem | undefined }; const h = date.getHours(); return { hour: h % 12 || 12, minute, meridiem: (h >= 12 ? "PM" : "AM") as Meridiem }; } function buildMinutes(interval: MinuteInterval) { return Array.from({ length: Math.floor(60 / interval) }, (_, i) => i * interval); } function snapMinute(minute: number, interval: MinuteInterval) { return Math.min(59, Math.round(minute / interval) * interval); } /** A single wheel row — scales/fades based on distance from the centered slot. */ function WheelRow({ item, index, scrollY, isSelected, onPress, format }: { item: T; index: number; scrollY: SharedValue; isSelected: boolean; onPress: () => void; format: (item: T) => string; }) { const center = index * ROW_HEIGHT; const inputRange = [center - ROW_HEIGHT * 2, center - ROW_HEIGHT, center, center + ROW_HEIGHT, center + ROW_HEIGHT * 2]; const style = useAnimatedStyle(() => { const scale = interpolate(scrollY.value, inputRange, [0.75, 0.88, 1, 0.88, 0.75], Extrapolation.CLAMP); const opacity = interpolate(scrollY.value, inputRange, [0.3, 0.55, 1, 0.55, 0.3], Extrapolation.CLAMP); return { opacity, transform: [{ scale }] }; }); return ( {format(item)} ); } /** A vertically-scrolling, snap-to-center wheel with a highlight band and a haptic tick per selection change. */ function Wheel({ items, selected, onSelect, format }: { items: T[]; selected: T; onSelect: (item: T) => void; format: (item: T) => string; }) { const colors = useThemeColors(); const scrollY = useSharedValue(0); const listRef = useRef(null); const lastIndex = useRef(items.indexOf(selected)); useEffect(() => { const idx = items.indexOf(selected); if (idx !== -1 && idx !== lastIndex.current) { listRef.current?.scrollTo({ y: idx * ROW_HEIGHT, animated: false }); lastIndex.current = idx; } }, [selected, items]); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollY.value = e.contentOffset.y; } }); const commit = useCallback((index: number) => { const clamped = Math.max(0, Math.min(items.length - 1, index)); if (clamped !== lastIndex.current) { lastIndex.current = clamped; Haptics.selectionAsync(); onSelect(items[clamped]); } }, [items, onSelect]); return ( commit(Math.round(e.nativeEvent.contentOffset.y / ROW_HEIGHT))} contentContainerStyle={{ paddingVertical: PAD }} contentOffset={{ x: 0, y: Math.max(0, items.indexOf(selected)) * ROW_HEIGHT }} > {items.map((item, index) => ( { listRef.current?.scrollTo({ y: index * ROW_HEIGHT, animated: true }); commit(index); }} /> ))} {/* Fades the two rows nearest each edge toward the surrounding card color, reinforcing the "wheel" depth cue */} ); } function TimeSelector({ value, onChange, is24Hour, minuteInterval = 1 }: { value: Date; onChange: (date: Date) => void; is24Hour?: boolean; minuteInterval?: MinuteInterval; }) { const parts = readTimeParts(value, is24Hour); const minute = snapMinute(parts.minute, minuteInterval); const hours = is24Hour ? Array.from({ length: 24 }, (_, i) => i) : Array.from({ length: 12 }, (_, i) => i + 1); const minutes = buildMinutes(minuteInterval); const update = (hour: number, nextMinute: number, meridiem?: Meridiem) => onChange(setTimeParts(value, hour, nextMinute, meridiem)); return ( update(h, minute, parts.meridiem)} format={(h) => String(h).padStart(2, "0")} /> update(parts.hour, m, parts.meridiem)} format={(m) => String(m).padStart(2, "0")} /> {!is24Hour && ( update(parts.hour, minute, m)} format={(m) => m} /> )} ); } function PickerTrigger({ label, hasValue, className, onPress, Icon }: { label: string; hasValue: boolean; className?: string; onPress: () => void; Icon: LucideIcon; }) { const colors = useThemeColors(); const { animatedStyle, onPressIn, onPressOut } = usePressAnimation(0.97); return ( {label} ); } function PickerModal({ open, onClose, onDone, children }: { open: boolean; onClose: () => void; onDone: () => void; children: React.ReactNode; }) { // Keep the Modal mounted while the close animation plays — dropping // `visible` immediately would cut it short (same pattern as drawer.tsx). const [visible, setVisible] = useState(open); const backdrop = useSharedValue(0); const panel = useSharedValue(0.9); useEffect(() => { if (open) { setVisible(true); backdrop.value = withTiming(1, { duration: duration.fast }); panel.value = withSpring(1, springs.snappy); return; } backdrop.value = withTiming(0, { duration: duration.fast }); panel.value = withTiming(0.9, { duration: duration.fast }); const t = setTimeout(() => setVisible(false), duration.fast); return () => clearTimeout(t); }, [open, backdrop, panel]); const backdropStyle = useAnimatedStyle(() => ({ opacity: backdrop.value })); const panelStyle = useAnimatedStyle(() => ({ opacity: backdrop.value, transform: [{ scale: panel.value }] })); return ( {children} Done ); } export function TimePicker({ className, value, onChange, placeholder = "Select time...", is24Hour, minuteInterval, formatTime }: TimePickerProps) { const [open, setOpen] = useState(false); const [draft, setDraft] = useState(value ?? new Date()); const display = value ? (formatTime ?? ((d) => defaultTime(d, is24Hour)))(value) : placeholder; return ( <> { setDraft(value ?? new Date()); setOpen(true); }} /> setOpen(false)} onDone={() => { onChange?.(draft); setOpen(false); }}> ); } export function DateAndTimePicker({ className, value, onChange, placeholder = "Select date & time...", is24Hour, minuteInterval, min, max, formatDateTime, }: DateAndTimePickerProps) { const [open, setOpen] = useState(false); const [draft, setDraft] = useState(value ?? new Date()); const display = value ? (formatDateTime ?? ((d) => defaultDateTime(d, is24Hour)))(value) : placeholder; return ( <> { setDraft(value ?? new Date()); setOpen(true); }} /> setOpen(false)} onDone={() => { onChange?.(draft); setOpen(false); }}> setDraft((prev) => mergeDatePart(prev, d))} min={min} max={max} /> ); } export function DateTimePicker(props: DateTimePickerProps) { return ; } ``` ## Timeline - key: `timeline` - import: `import { Timeline } from "@/components/ui/timeline"` - description: Vertical timeline for events, order tracking, activity feeds - tier: 1 - deps: lucide-react-native, react-native-svg, class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/timeline.tsx import React from "react"; import { View, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { Check } from "lucide-react-native"; import { cn } from "@/lib/utils"; export interface TimelineProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function Timeline({ className, children, ...props }: TimelineProps) { return ( {children} ); } const dotVariants = cva("h-3 w-3 rounded-full", { variants: { variant: { default: "bg-primary", completed: "bg-green-500", active: "bg-primary", pending: "bg-muted-foreground/40", destructive: "bg-destructive", success: "bg-green-500", muted: "bg-muted-foreground", }, }, defaultVariants: { variant: "default" }, }); export interface TimelineItemProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; title: string; description?: string; time?: string; icon?: React.ReactNode; isLast?: boolean; } export function TimelineItem({ variant, className, title, description, time, icon, isLast, ...props }: TimelineItemProps) { const isActive = variant === "active"; return ( {/* Dot + Line */} {icon ?? ( {variant === "completed" && ( )} )} {!isLast && } {/* Content */} {title} {time && {time}} {description && ( {description} )} ); } ``` ## Toast - key: `toast` - import: `import { Toast } from "@/components/ui/toast"` - description: Notification toast with auto-dismiss, position (top/bottom), and slide-in direction (top/bottom/left/right) - tier: 3 - deps: @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/toast.tsx import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react"; import { View, Text, Pressable } from "react-native"; import Animated from "react-native-reanimated"; import { Portal } from "@rn-primitives/portal"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; type ToastVariant = "default" | "destructive" | "success"; export type ToastPosition = "top" | "bottom"; export type ToastFrom = "top" | "bottom" | "left" | "right"; type ToastData = { id: string; title: string; description?: string; variant?: ToastVariant; position?: ToastPosition; from?: ToastFrom; }; const positions: ToastPosition[] = ["top", "bottom"]; // Monotonic id — Date.now() collides for toasts fired in the same millisecond. let nextId = 0; const ToastContext = createContext<{ toast: (data: Omit) => void }>({ toast: () => {} }); export function useToast() { return useContext(ToastContext); } export interface ToastProviderProps { children: React.ReactNode; defaultPosition?: ToastPosition; defaultFrom?: ToastFrom; } // `from: "top"` maps to SlideInUp (Reanimated: SlideIn starts on that // side). `satisfies` validates the keyset without widening to a single // SlideIn type — Up/Down and Left/Right have different initial-value shapes. const animationFor = { top: { enter: entering.slideInUp, exit: exiting.slideOutUp }, bottom: { enter: entering.slideInDown, exit: exiting.slideOutDown }, left: { enter: entering.slideInLeft, exit: exiting.slideOutLeft }, right: { enter: entering.slideInRight, exit: exiting.slideOutRight }, } satisfies Record; const containerStyles: Record = { top: "absolute top-14 start-4 end-4 gap-2 z-50", bottom: "absolute bottom-14 start-4 end-4 gap-2 z-50", }; export function ToastProvider({ children, defaultPosition = "top", defaultFrom }: ToastProviderProps) { const [toasts, setToasts] = useState([]); const timers = useRef>>(new Map()); const dismiss = useCallback((id: string) => { const timer = timers.current.get(id); if (timer) clearTimeout(timer); timers.current.delete(id); setToasts((prev) => prev.filter((t) => t.id !== id)); }, []); const toast = useCallback((data: Omit) => { const id = String(++nextId); const position = data.position ?? defaultPosition; const from = data.from ?? defaultFrom ?? position; setToasts((prev) => [...prev, { ...data, id, position, from }]); timers.current.set(id, setTimeout(() => dismiss(id), 3000)); }, [defaultPosition, defaultFrom, dismiss]); useEffect(() => { const pending = timers.current; return () => pending.forEach(clearTimeout); }, []); // Clamp toast banners to one pane on an unfolded Duo instead of spanning // both. Null on non-fold devices — pre-fold behavior preserved. const fold = useFoldFeatures(); const foldClamp = fold.foldX ? { right: fold.foldX } : undefined; return ( {children} {/* Portal anchors toasts to the screen, not the provider's ancestor. */} {positions.map((pos) => { const items = toasts.filter((t) => t.position === pos); if (items.length === 0) return null; return ( {items.map((t) => ( dismiss(t.id)} /> ))} ); })} ); } const variantStyles: Record = { default: "bg-card border-border", destructive: "bg-destructive border-destructive", success: "bg-green-600 border-green-600", }; function ToastItem({ data, onDismiss }: { data: ToastData; onDismiss: () => void }) { const variant = data.variant ?? "default"; const isDefault = variant === "default"; const { enter, exit } = animationFor[data.from ?? "top"]; return ( {data.title} {data.description && ( {data.description} )} ); } ``` ## Toggle - key: `toggle` - import: `import { Toggle } from "@/components/ui/toggle"` - description: Two-state toggle button - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge ```tsx // components/ui/toggle.tsx import React from "react"; import { Pressable, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const toggleVariants = cva( "items-center justify-center rounded-md min-h-12 min-w-12", { variants: { variant: { default: "bg-transparent", outline: "border border-input bg-transparent", }, size: { sm: "px-2 py-1.5", md: "px-3 py-2", lg: "px-4 py-2.5", }, }, defaultVariants: { variant: "default", size: "md" }, } ); export interface ToggleProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; pressed?: boolean; onPressedChange?: (pressed: boolean) => void; children: React.ReactNode; } export function Toggle({ pressed = false, onPressedChange, variant, size, className, children, ...props }: ToggleProps) { return ( onPressedChange?.(!pressed)} accessibilityRole="button" accessibilityState={{ selected: pressed }} accessible={true} {...props} > {typeof children === "string" ? ( {children} ) : children} ); } ``` ## ToggleGroup - key: `toggle-group` - import: `import { ToggleGroup } from "@/components/ui/toggle-group"` - description: Group of exclusive toggle buttons - tier: 1 - deps: class-variance-authority, clsx, tailwind-merge - aniui deps: toggle ```tsx // components/ui/toggle-group.tsx import React, { createContext, useContext } from "react"; import { View, Pressable, Text } from "react-native"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const itemVariants = cva( "items-center justify-center rounded-md min-h-12 min-w-12", { variants: { variant: { default: "bg-transparent", outline: "border border-input bg-transparent", }, size: { sm: "px-2 py-1.5", md: "px-3 py-2", lg: "px-4 py-2.5", }, }, defaultVariants: { variant: "default", size: "md" }, } ); type GroupCtx = { value: string; onValueChange: (v: string) => void; } & VariantProps; const Ctx = createContext({ value: "", onValueChange: () => {} }); export interface ToggleGroupProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; value: string; onValueChange: (value: string) => void; children: React.ReactNode; } export function ToggleGroup({ value, onValueChange, variant, size, className, children, ...props }: ToggleGroupProps) { return ( {children} ); } export interface ToggleGroupItemProps extends React.ComponentPropsWithoutRef, VariantProps { className?: string; value: string; children: React.ReactNode; } export function ToggleGroupItem({ value, variant, size, className, children, ...props }: ToggleGroupItemProps) { const { value: selected, onValueChange, variant: groupVariant, size: groupSize } = useContext(Ctx); const active = selected === value; return ( onValueChange(value)} accessibilityRole="radio" accessibilityState={{ selected: active }} accessible={true} {...props} > {typeof children === "string" ? ( {children} ) : children} ); } ``` ## Tooltip - key: `tooltip` - import: `import { Tooltip } from "@/components/ui/tooltip"` - description: Accessible tooltip with positioning - tier: 3 - deps: @rn-primitives/tooltip, @rn-primitives/portal, react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, fold ```tsx // components/ui/tooltip.tsx import React from "react"; import { View, Text, Pressable } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import * as TooltipPrimitive from "@rn-primitives/tooltip"; import Animated from "react-native-reanimated"; import { entering, exiting } from "@/components/ui/animate"; import { useFoldFeatures } from "@/components/ui/fold"; import { cn } from "@/lib/utils"; export interface TooltipProps { children: React.ReactNode; onOpenChange?: (open: boolean) => void; } // @rn-primitives' Tooltip Root is uncontrolled — see context-menu.tsx. export function Tooltip({ children, onOpenChange }: TooltipProps) { return {children}; } export interface TooltipTriggerProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; } export function TooltipTrigger({ className, children, ...props }: TooltipTriggerProps) { return ( {/* rn-primitives measures this exact box to position TooltipContent relative to it — min-h-12/min-w-12 would force a 48x48 measured box even for a small icon child. hitSlop expands the tappable area to the 48dp minimum without inflating what gets measured. */} {children} ); } export interface TooltipContentProps extends React.ComponentPropsWithoutRef { className?: string; children?: React.ReactNode; side?: "top" | "bottom" | "left" | "right"; sideOffset?: number; } export function TooltipContent({ className, children, side = "top", sideOffset = 8, ...props }: TooltipContentProps) { const insets = useSafeAreaInsets(); const fold = useFoldFeatures(); // The default side="top" clamps against insets.top, and this primitive's // Trigger measures via measure() (not measureInWindow()) — the same // status-bar-offset inaccuracy documented elsewhere in this codebase — // which was pinning the tooltip at insets.top instead of near the trigger. // side="bottom" (Popover/HoverCard/DropdownMenu's default) clamps against // insets.bottom instead, so it never hits this; only zero out top here. // Fold-aware: add the fold line as a horizontal inset so the tooltip stays // within one pane on an unfolded Duo. See popover.tsx for the pattern. const tooltipInsets = fold.foldX ? { ...insets, top: 0, left: Math.max(insets.left, fold.foldX), right: Math.max(insets.right, fold.foldX) } : { ...insets, top: 0 }; return ( {typeof children === "string" ? ( {children} ) : children} ); } ``` ## Tray - key: `tray` - import: `import { Tray } from "@/components/ui/tray"` - description: Compound bottom-sheet/navigation-tray system with multi-view push/back navigation, draggable detents, and scroll hand-off - tier: 3 - deps: react-native-reanimated, react-native-gesture-handler, react-native-safe-area-context, lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/tray.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react"; import { Modal, Pressable, Text, useColorScheme, useWindowDimensions, View, type LayoutChangeEvent, } from "react-native"; import { Gesture, GestureDetector, type PanGesture } from "react-native-gesture-handler"; import Animated, { Extrapolation, interpolate, runOnJS, scrollTo, useAnimatedRef, useAnimatedScrollHandler, useAnimatedStyle, useReducedMotion, useSharedValue, withSpring, withTiming, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { ChevronLeft, X } from "lucide-react-native"; import { cn } from "@/lib/utils"; const AnimatedPressable = Animated.createAnimatedComponent(Pressable); // --------------------------------------------------------------------------- // Physics helpers (worklets) — detents, overscroll resistance, flick landing. // --------------------------------------------------------------------------- /** Rubber-band overscroll resistance: travels less the further you drag. */ function rubberBand(distance: number, dimension: number, factor = 0.55): number { "worklet"; return (1 - 1 / ((distance * factor) / Math.max(dimension, 1) + 1)) * Math.max(dimension, 1); } /** * Where a flick would come to rest if it decelerated naturally. Projecting * the release velocity forward (instead of snapping on raw position alone) * is what makes a fast flick reach the next detent and a slow drag settle on * the nearest one — the same trick iOS sheets use. */ function projectPosition(position: number, velocity: number, seconds: number): number { "worklet"; return position + velocity * seconds; } function nearestOffsetIndex(offsets: readonly number[], position: number): number { "worklet"; let best = 0; let bestDistance = Number.MAX_VALUE; for (let i = 0; i < offsets.length; i++) { const distance = Math.abs(offsets[i] - position); if (distance < bestDistance) { bestDistance = distance; best = i; } } return best; } function resolveDetent(detent: number | string, available: number): number { if (typeof detent === "string") { const percent = parseFloat(detent); return Number.isFinite(percent) ? (available * percent) / 100 : available; } return detent <= 1 ? available * detent : detent; } /** Detent heights, sorted ascending, expressed as distance below "fully open". */ function toOffsets(heights: readonly number[]): number[] { const tallest = Math.max(...heights); return heights.map((height) => tallest - height).sort((a, b) => a - b); } // --------------------------------------------------------------------------- // Theme // --------------------------------------------------------------------------- export type TrayTheme = "light" | "dark"; export type TrayDetent = number | `${number}%`; export interface TrayPalette { surface: string; border: string; handle: string; text: string; mutedText: string; backdrop: string; } const LIGHT_PALETTE: TrayPalette = { surface: "#ffffff", border: "#e3e7ec", handle: "rgba(60,60,67,0.3)", text: "#111111", mutedText: "#6d7480", backdrop: "rgba(0,0,0,0.4)", }; const DARK_PALETTE: TrayPalette = { surface: "#171716", border: "#2b2a25", handle: "rgba(246,243,236,0.28)", text: "#f6f3ec", mutedText: "#9a958a", backdrop: "rgba(0,0,0,0.55)", }; const PALETTES: Record = { light: LIGHT_PALETTE, dark: DARK_PALETTE }; export interface TrayMotion { /** Presenting/dismissing the whole sheet. */ presentSpring: WithSpringConfig; /** Resizing to new content height when a view swaps in. */ heightSpring: WithSpringConfig; /** Settling onto a detent after a drag or flick. */ detentSpring: WithSpringConfig; /** Overscroll resistance above the tallest detent. Higher travels less. */ overDragFactor: number; /** How far the backdrop fades out at full drag, as a fraction. */ backdropFalloff: number; /** Seconds of deceleration used to project a flick onto a detent. */ flickProjection: number; /** Distance (px) a pushed/popped view travels as it slides in/out. */ viewSlide: number; /** Vertical movement before the drag-to-dismiss pan gesture activates. */ activeOffsetY: [number, number]; scrollDeceleration: number; } const DEFAULT_MOTION: TrayMotion = { presentSpring: { damping: 30, stiffness: 280, mass: 0.9 }, heightSpring: { damping: 26, stiffness: 260, mass: 0.75, overshootClamping: true }, detentSpring: { damping: 32, stiffness: 320, mass: 0.9 }, overDragFactor: 0.55, backdropFalloff: 0.45, flickProjection: 0.35, viewSlide: 26, activeOffsetY: [-8, 8], scrollDeceleration: 0.998, }; const PRESENT_START_SCALE = 0.94; const TRAVEL_PADDING = 56; // --------------------------------------------------------------------------- // Navigation stack (push/back between named views) // --------------------------------------------------------------------------- interface TrayNavigation { view: string; /** +1 when the last navigation pushed, -1 when it popped. */ direction: number; canGoBack: boolean; setView: (view: string) => void; goBack: () => void; reset: (view: string) => void; } function useTrayNavigation(defaultView: string, onViewChange?: (view: string) => void): TrayNavigation { const [state, setState] = useState<{ stack: string[]; direction: number }>({ stack: [defaultView], direction: 1, }); const view = state.stack[state.stack.length - 1]; const setView = useCallback( (next: string) => { setState((current) => { if (current.stack[current.stack.length - 1] === next) return current; return { stack: [...current.stack, next], direction: 1 }; }); onViewChange?.(next); }, [onViewChange] ); const goBack = useCallback(() => { setState((current) => { if (current.stack.length < 2) return current; const stack = current.stack.slice(0, -1); onViewChange?.(stack[stack.length - 1]); return { stack, direction: -1 }; }); }, [onViewChange]); const reset = useCallback((next: string) => setState({ stack: [next], direction: 1 }), []); return { view, direction: state.direction, canGoBack: state.stack.length > 1, setView, goBack, reset }; } // --------------------------------------------------------------------------- // Context // --------------------------------------------------------------------------- interface TrayContextValue { visible: boolean; view: string; direction: number; canGoBack: boolean; open: (view?: string) => void; close: () => void; setView: (view: string) => void; goBack: () => void; height: SharedValue; present: SharedValue; offset: SharedValue; travel: SharedValue; /** Live content scroll offset, used for the drag/scroll hand-off. */ scrollY: SharedValue; /** True while the tray itself owns the gesture rather than the scrollable. */ isDragging: SharedValue; /** Set by TrayScrollView so the tray knows a scrollable is present. */ hasScrollable: SharedValue; offsets: number[]; detentHeight: number; pan: PanGesture; onContentLayout: (event: LayoutChangeEvent) => void; palette: TrayPalette; radius: number; motion: TrayMotion; reduceMotion: boolean; } const TrayContext = createContext(null); function useTray(component: string) { const ctx = useContext(TrayContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } const TrayTintContext = createContext(null); function useTrayTint(fallback: string): string { return useContext(TrayTintContext) ?? fallback; } const TrayDismissContext = createContext(true); // --------------------------------------------------------------------------- // Root // --------------------------------------------------------------------------- export interface TrayProps { children: React.ReactNode; defaultView?: string; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; onViewChange?: (view: string) => void; theme?: TrayTheme; palette?: Partial; radius?: number; closeThreshold?: number; closeVelocity?: number; dismissOnBackdropPress?: boolean; enableDragToDismiss?: boolean; motion?: Partial; /** Snap heights (px, 0-1 fraction of available height, or `"NN%"`), tallest first isn't required — sorted internally. */ detents?: readonly TrayDetent[]; initialDetent?: number; onDetentChange?: (index: number) => void; } /** * Full compound bottom-sheet/navigation-tray system. `TrayContent` measures * its own content and springs its height to match; `TrayView`s form a * push/back stack (`setView`/`goBack`) that cross-slides between named * views; the sheet itself supports drag-to-dismiss with multiple detents, * rubber-band overscroll above the tallest one, and flick-velocity * projection to decide which detent a released drag settles on. * `TrayScrollView` hands the gesture off to its own scroll view when the * sheet is fully expanded and the content is scrolled to the top, and back * to the sheet's own drag the moment the user pulls down from there. */ export function Tray({ children, defaultView = "default", open: openProp, defaultOpen = false, onOpenChange, onViewChange, theme: themeProp, palette: paletteProp, radius = 38, closeThreshold = 96, closeVelocity = 900, dismissOnBackdropPress = true, enableDragToDismiss = true, motion: motionProp, detents, initialDetent = 0, onDetentChange, }: TrayProps) { const isControlled = openProp !== undefined; const [internalOpen, setInternalOpen] = useState(defaultOpen); const open = isControlled ? (openProp as boolean) : internalOpen; const [mounted, setMounted] = useState(open); const insets = useSafeAreaInsets(); const { height: screenHeight } = useWindowDimensions(); const systemDark = useColorScheme() === "dark"; const theme = themeProp ?? (systemDark ? "dark" : "light"); const { offsets, detentHeight } = useMemo(() => { if (!detents || detents.length === 0) return { offsets: [0], detentHeight: 0 }; const available = screenHeight - insets.top - insets.bottom; const heights = detents.map((d) => resolveDetent(d, available)); return { offsets: toOffsets(heights), detentHeight: Math.max(...heights) }; }, [detents, screenHeight, insets.top, insets.bottom]); const reduceMotion = useReducedMotion(); const motion = useMemo(() => ({ ...DEFAULT_MOTION, ...motionProp }), [motionProp]); const navigation = useTrayNavigation(defaultView, onViewChange); const present = useSharedValue(0); const offset = useSharedValue(0); const startOffset = useSharedValue(0); const detentIndex = useSharedValue(0); const travel = useSharedValue(0); const sheetHeight = useSharedValue(0); const scrollY = useSharedValue(0); const owns = useSharedValue(false); const origin = useSharedValue(0); const hasScrollable = useSharedValue(false); const isDragging = useSharedValue(false); const measured = useRef(0); const presented = useRef(false); // Tracks the latest desired open state so a closing spring's completion // callback — which can still be in flight when the tray is reopened before // it settles — can tell it's now stale and skip resetting the fresh open. // Without this, a quick reopen right after closing would get silently // yanked back to a mounted-but-reset, invisible state once the old spring // finally finished. const openRef = useRef(open); openRef.current = open; // Set while dismiss() (drag-to-dismiss) owns the closing animation, so the // effect below doesn't also assign its own withSpring to the same shared // value for the same close — two competing springs on `present` meant the // drag's velocity-aware one got interrupted (and its callback skipped) the // moment the effect's ran, which is a redundant, fragile way to end up at // exactly one finishClose() call rather than a guaranteed one. const isClosing = useRef(false); const setOpen = useCallback( (next: boolean) => { if (!isControlled) setInternalOpen(next); onOpenChange?.(next); }, [isControlled, onOpenChange] ); // Deliberately does NOT reset measured.current/sheetHeight/travel: the // Modal (and its content) now stay mounted permanently — see the render // below — so those describe the content's real, still-accurate size and // should survive a close instead of forcing a re-measure (and a "grow from // 0" flash) on every reopen. Only the transient, position-related values // reset, since a fresh open should start from a clean drag/scroll state. const reset = useCallback(() => { offset.value = 0; startOffset.value = 0; scrollY.value = 0; owns.value = false; origin.value = 0; present.value = 0; }, [offset, startOffset, scrollY, owns, origin, present]); const finishClose = useCallback(() => { isClosing.current = false; if (openRef.current) return; setMounted(false); reset(); }, [reset]); const clearClosing = useCallback(() => { isClosing.current = false; }, []); const close = useCallback(() => setOpen(false), [setOpen]); const openTray = useCallback( (view?: string) => { navigation.reset(view ?? defaultView); setOpen(true); }, [navigation, defaultView, setOpen] ); // Springs the sheet in from below. Called either by onContentLayout (the // very first time content is ever measured) or directly by the open effect // below (every time after that, since content no longer unmounts between // opens and so won't re-fire onLayout on its own). const presentEntrance = useCallback(() => { presented.current = true; const start = offsets[Math.min(initialDetent, offsets.length - 1)] ?? 0; offset.value = start; detentIndex.value = Math.min(initialDetent, offsets.length - 1); present.value = reduceMotion ? 1 : withSpring(1, motion.presentSpring); }, [offsets, initialDetent, offset, detentIndex, present, reduceMotion, motion]); const onContentLayout = useCallback( (event: LayoutChangeEvent) => { const next = detentHeight ? detentHeight : Math.round(event.nativeEvent.layout.height); if (next <= 0 || Math.abs(measured.current - next) < 1) return; const first = measured.current === 0; measured.current = next; travel.value = next + insets.bottom + TRAVEL_PADDING; if (first || reduceMotion) sheetHeight.value = next; else sheetHeight.value = withSpring(next, motion.heightSpring); if (openRef.current && !presented.current) presentEntrance(); }, [detentHeight, insets.bottom, reduceMotion, motion, sheetHeight, travel, presentEntrance] ); const dismiss = useCallback( (velocity: number) => { isClosing.current = true; setOpen(false); if (reduceMotion) { present.value = 0; finishClose(); return; } present.value = withSpring( 0, { ...motion.presentSpring, velocity: -velocity / Math.max(travel.value, 1), overshootClamping: true }, (finished) => { "worklet"; if (finished) runOnJS(finishClose)(); else runOnJS(clearClosing)(); } ); }, [reduceMotion, motion, present, travel, finishClose, clearClosing, setOpen] ); useEffect(() => { if (open) { setMounted(true); presented.current = false; // If content was already measured on a previous open, it won't // re-layout just because we're reopening (it never unmounted) — so // nothing will call presentEntrance() for us. Do it directly. If this // is the very first-ever open, measured.current is still 0 and // onContentLayout (about to fire once the Modal is actually visible) // handles it instead. if (measured.current > 0) presentEntrance(); return; } if (!presented.current) return; if (isClosing.current) return; if (reduceMotion) { present.value = 0; finishClose(); return; } present.value = withSpring(0, { ...motion.presentSpring, overshootClamping: true }, (finished) => { "worklet"; if (finished) runOnJS(finishClose)(); }); }, [open, reduceMotion, motion, present, finishClose, presentEntrance]); const settleTo = useCallback((index: number) => onDetentChange?.(index), [onDetentChange]); const pan = useMemo( () => Gesture.Pan() .enabled(enableDragToDismiss && !reduceMotion) .activeOffsetY(motion.activeOffsetY) .failOffsetX([-14, 14]) .onBegin(() => { "worklet"; owns.value = false; origin.value = 0; startOffset.value = offset.value; isDragging.value = false; }) .onUpdate((event) => { "worklet"; if (!owns.value) { const expanded = startOffset.value <= 0.5; const canScroll = hasScrollable.value && expanded; const atTop = !canScroll || scrollY.value <= 0; if (!atTop || (canScroll && event.translationY <= 0)) { isDragging.value = false; return; } owns.value = true; origin.value = event.translationY; } const travelled = event.translationY - origin.value; const next = startOffset.value + travelled; if (next < 0) { offset.value = -rubberBand(-next, travel.value, motion.overDragFactor); isDragging.value = true; return; } offset.value = next; isDragging.value = true; }) .onEnd((event) => { "worklet"; if (!owns.value) return; const projected = projectPosition(offset.value, event.velocityY, motion.flickProjection); const last = offsets[offsets.length - 1]; if (projected > last + closeThreshold || (event.velocityY > closeVelocity && offset.value > 0)) { runOnJS(dismiss)(event.velocityY); return; } const index = nearestOffsetIndex(offsets, projected); detentIndex.value = index; offset.value = withSpring(offsets[index], { ...motion.detentSpring, velocity: event.velocityY }); runOnJS(settleTo)(index); }) .onFinalize(() => { "worklet"; owns.value = false; isDragging.value = false; }), [enableDragToDismiss, reduceMotion, motion, isDragging, owns, origin, startOffset, offset, detentIndex, offsets, hasScrollable, scrollY, travel, closeThreshold, closeVelocity, dismiss, settleTo] ); const palette = useMemo(() => ({ ...PALETTES[theme], ...paletteProp }), [theme, paletteProp]); const ctx = useMemo( () => ({ visible: mounted, view: navigation.view, direction: navigation.direction, canGoBack: navigation.canGoBack, open: openTray, close, setView: navigation.setView, goBack: navigation.goBack, height: sheetHeight, present, offset, offsets, detentHeight, travel, scrollY, isDragging, hasScrollable, pan, onContentLayout, palette, radius, motion, reduceMotion, }), [mounted, navigation.view, navigation.direction, navigation.canGoBack, navigation.setView, navigation.goBack, openTray, close, sheetHeight, present, offset, offsets, detentHeight, travel, scrollY, isDragging, hasScrollable, pan, onContentLayout, palette, radius, motion, reduceMotion] ); return ( {children} ); } // --------------------------------------------------------------------------- // Sub-components // --------------------------------------------------------------------------- export interface TrayTriggerProps { children: React.ReactNode; view?: string; className?: string; } export function TrayTrigger({ children, view, className }: TrayTriggerProps) { const { open, palette } = useTray("TrayTrigger"); return ( open(view)} className={cn("min-h-12 min-w-12", className)} > {children} ); } export interface TrayContentProps { children: React.ReactNode; className?: string; } export function TrayContent({ children, className }: TrayContentProps) { const { visible, close, height, present, offset, travel, pan, onContentLayout, palette, radius, motion } = useTray("TrayContent"); const insets = useSafeAreaInsets(); const dismissOnBackdropPress = useContext(TrayDismissContext); const transformStyle = useAnimatedStyle(() => ({ transform: [ { translateY: (1 - present.value) * travel.value + offset.value }, { scale: interpolate(present.value, [0, 1], [PRESENT_START_SCALE, 1], Extrapolation.CLAMP) }, ], })); const heightStyle = useAnimatedStyle(() => ({ height: height.value, opacity: height.value === 0 ? 0 : 1, })); const backdropStyle = useAnimatedStyle(() => ({ opacity: present.value * interpolate(offset.value, [0, Math.max(travel.value, 1)], [1, motion.backdropFalloff], Extrapolation.CLAMP), })); // The Modal element itself stays mounted permanently and its own `visible` // prop toggles native show/hide, rather than this component conditionally // returning null (which would unmount/remount the underlying native Modal // window on every open/close). On Android in particular, tearing down and // recreating that native window is asynchronous — opening again before the // previous one has actually finished closing can silently fail to show, // which matches "works once, then won't reopen." return ( {children} ); } export interface TrayViewProps { children: React.ReactNode; id: string; className?: string; } export function TrayView({ children, id, className }: TrayViewProps) { const { view, direction, reduceMotion, motion } = useTray("TrayView"); const active = view === id; const [rendered, setRendered] = useState(active); const progress = useSharedValue(active ? 1 : 0); const slideFrom = useSharedValue(0); useEffect(() => { if (active) { setRendered(true); slideFrom.value = direction; progress.value = reduceMotion ? 1 : withSpring(1, motion.presentSpring); return; } if (progress.value === 0) return; slideFrom.value = -direction; if (reduceMotion) { progress.value = 0; setRendered(false); return; } progress.value = withTiming(0, { duration: 160 }, (finished) => { "worklet"; if (finished) runOnJS(setRendered)(false); }); }, [active, direction, progress, slideFrom, reduceMotion]); const layerStyle = useAnimatedStyle(() => { const shift = (1 - progress.value) * motion.viewSlide * slideFrom.value; return { opacity: progress.value, transform: [ { translateX: shift }, { scale: interpolate(progress.value, [0, 1], [0.94, 1], Extrapolation.CLAMP) }, ], }; }); if (!rendered) return null; return ( {children} ); } export interface TraySectionProps { children: React.ReactNode; className?: string; } export function TrayHeader({ children, className }: TraySectionProps) { return {children}; } export function TrayTitle({ children, className }: TraySectionProps) { const { palette } = useTray("TrayTitle"); return ( {children} ); } export function TraySubtitle({ children, className }: TraySectionProps) { const { palette } = useTray("TraySubtitle"); return ( {children} ); } export function TrayBody({ children, className }: TraySectionProps) { return {children}; } export function TrayFooter({ children, className }: TraySectionProps) { const { palette } = useTray("TrayFooter"); return ( {children} ); } export interface TrayGlyphButtonProps { children?: React.ReactNode | ((state: { color: string; size: number }) => React.ReactNode); className?: string; } export function TrayClose({ children, className }: TrayGlyphButtonProps) { const { close, palette } = useTray("TrayClose"); const state = { color: palette.mutedText, size: 20 }; const content = typeof children === "function" ? children(state) : (children ?? null); return ( {content ?? } ); } export function TrayBack({ children, className }: TrayGlyphButtonProps) { const { goBack, canGoBack, palette } = useTray("TrayBack"); if (!canGoBack) return null; const state = { color: palette.mutedText, size: 20 }; const content = typeof children === "function" ? children(state) : (children ?? null); return ( {content ?? } ); } export interface TrayScrollViewProps { children: React.ReactNode; maxHeight?: number; className?: string; contentContainerStyle?: React.ComponentProps["contentContainerStyle"]; } /** * Scrollable body that hands the gesture off to the sheet's own drag: while * the user is dragging the sheet, this view's scroll is pinned to 0 so it * can't fight the sheet; once the drag ends, native scrolling resumes from * wherever content was left. `hasScrollable`/`scrollY` (shared with the * root's pan gesture) are what let the pan only "steal" the gesture when * this list is already scrolled to the top. */ export function TrayScrollView({ children, maxHeight, className, contentContainerStyle }: TrayScrollViewProps) { const { scrollY, isDragging, hasScrollable, pan, motion } = useTray("TrayScrollView"); const { height: screenHeight } = useWindowDimensions(); const listRef = useAnimatedRef(); const resolvedMax = maxHeight ?? screenHeight * 0.55; useEffect(() => { hasScrollable.value = true; return () => { hasScrollable.value = false; scrollY.value = 0; }; }, [hasScrollable, scrollY]); const onScroll = useAnimatedScrollHandler({ onScroll: (event) => { "worklet"; if (isDragging.value) { scrollTo(listRef, 0, 0, false); scrollY.value = 0; return; } scrollY.value = event.contentOffset.y; }, }); const nativeGesture = useMemo(() => Gesture.Native().simultaneousWithExternalGesture(pan), [pan]); return ( {children} ); } export function TrayIcon({ children }: { children: React.ReactNode }) { const { palette } = useTray("TrayIcon"); const color = useTrayTint(palette.text); return {children}; } ``` ## TypingIndicator - key: `typing-indicator` - import: `import { TypingIndicator } from "@/components/ui/typing-indicator"` - description: Animated typing dots for chat interfaces - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate ```tsx // components/ui/typing-indicator.tsx import React, { useEffect } from "react"; import { View } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withSequence, withTiming, withDelay, cancelAnimation, } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; function Dot({ delay }: { delay: number }) { const translateY = useSharedValue(0); const reducedMotion = useReducedMotion(); useEffect(() => { if (reducedMotion) return; translateY.value = withDelay( delay, withRepeat(withSequence(withTiming(-4, { duration: 300 }), withTiming(0, { duration: 300 })), -1) ); return () => cancelAnimation(translateY); }, [delay, translateY, reducedMotion]); const style = useAnimatedStyle(() => ({ transform: [{ translateY: translateY.value }] })); return ; } export interface TypingIndicatorProps extends React.ComponentPropsWithoutRef { className?: string; } export function TypingIndicator({ className, ...props }: TypingIndicatorProps) { return ( ); } ``` ## UnfoldMenu - key: `unfold-menu` - import: `import { UnfoldMenu } from "@/components/ui/unfold-menu"` - description: Menu whose trigger unfolds into a full panel, its label morphing into the panel's title as it expands - tier: 3 - deps: react-native-reanimated, react-native-safe-area-context, lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/unfold-menu.tsx import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from "react"; import { Modal, Pressable, useColorScheme, useWindowDimensions, View, type LayoutChangeEvent, type TextStyle, type ViewStyle, } from "react-native"; import Animated, { Easing, Extrapolation, interpolate, runOnJS, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withSpring, withTiming, type AnimatedStyle, type SharedValue, type WithSpringConfig, } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { X } from "lucide-react-native"; import { cn } from "@/lib/utils"; interface Point { x: number; y: number; } interface AnchorRect { x: number; y: number; w: number; h: number; } interface PanelPosition { left: number; top: number; } /** Keeps the panel fully on-screen, centered on the anchor where possible. */ function clampToScreen( anchor: AnchorRect, panelWidth: number, panelHeight: number, screenWidth: number, screenHeight: number, margin: number, insetTop: number, insetBottom: number ): PanelPosition { const idealLeft = anchor.x + anchor.w / 2 - panelWidth / 2; const idealTop = anchor.y + anchor.h / 2 - panelHeight / 2; const minLeft = margin; const maxLeft = screenWidth - panelWidth - margin; const minTop = insetTop + margin; const maxTop = screenHeight - insetBottom - panelHeight - margin; return { left: Math.min(Math.max(idealLeft, minLeft), Math.max(maxLeft, minLeft)), top: Math.min(Math.max(idealTop, minTop), Math.max(maxTop, minTop)), }; } export type UnfoldMenuTheme = "light" | "dark"; export interface UnfoldMenuPalette { surface: string; border: string; text: string; mutedText: string; } const LIGHT_PALETTE: UnfoldMenuPalette = { surface: "#ffffff", border: "#e3e7ec", text: "#111111", mutedText: "#6d7480" }; const DARK_PALETTE: UnfoldMenuPalette = { surface: "#171716", border: "#2b2a25", text: "#f6f3ec", mutedText: "#9a958a" }; const PALETTES: Record = { light: LIGHT_PALETTE, dark: DARK_PALETTE }; const MORPH_SPRING: WithSpringConfig = { mass: 0.5, damping: 14, stiffness: 145 }; const MORPH_CLOSE_SPRING: WithSpringConfig = { mass: 0.5, damping: 14, stiffness: 146 }; const HANDOFF_DELAY = 460; const HANDOFF_DURATION = 300; const HANDOFF_CLOSE_DURATION = 340; const HANDOFF_EASING = Easing.inOut(Easing.quad); const REVEAL_DELAY = 260; const REVEAL_DURATION = 220; const REVEAL_EASING = Easing.out(Easing.cubic); const CLOSE_DURATION = 280; const CLOSE_EASING = Easing.inOut(Easing.quad); const PRESS_TIMING = { duration: 120, easing: Easing.out(Easing.quad) }; const PRESS_SCALE = 0.97; const STAGGER_SPAN = 0.45; const ITEM_WINDOW = 0.55; const ITEM_SCALE_FROM = 0.85; const TRIGGER_ICON_FADE_END = 0.2; const CONTENT_FADE_START = 0.3; const CONTENT_FADE_END = 0.75; const MORPH_LABEL_FADE_END = 0.6; const MORPH_LABEL_SCALE_TO = 0.88; const MORPH_TITLE_FADE_START = 0.4; const MORPH_TITLE_SCALE_FROM = 0.88; const MORPH_PUSH_DISTANCE = 14; const DEFAULT_PANEL_WIDTH_RATIO = 0.86; const MAX_PANEL_WIDTH = 420; const DEFAULT_SCREEN_MARGIN = 12; const DEFAULT_COLUMNS = 3; const DEFAULT_RADIUS = 16; const DEFAULT_ICON_SIZE = 20; // --------------------------------------------------------------------------- // Contexts // --------------------------------------------------------------------------- // The same children render 3 times, once per slot, so the trigger's icon and // label can exist simultaneously as: the real anchor button (measured, then // hidden once handed off), the read-only copy inside the growing panel, and // a free-floating copy that travels from the anchor's position to the // panel's title position — the shared-element "unfold" illusion. type UnfoldMenuSlot = "anchor" | "overlay" | "float"; const UnfoldMenuSlotContext = createContext("anchor"); function useUnfoldMenuSlot() { return useContext(UnfoldMenuSlotContext); } interface UnfoldMenuMorph { iconStyle?: AnimatedStyle; labelStyle?: AnimatedStyle; onLabelLayout?: (event: LayoutChangeEvent) => void; } const UnfoldMenuMorphContext = createContext(null); function useUnfoldMenuMorph() { return useContext(UnfoldMenuMorphContext); } const UnfoldMenuTintContext = createContext(null); function useUnfoldMenuTint(fallback: string): string { return useContext(UnfoldMenuTintContext) ?? fallback; } const UnfoldMenuOffsetContext = createContext({ x: 0, y: 0 }); function useUnfoldMenuOffset() { return useContext(UnfoldMenuOffsetContext); } interface UnfoldMenuGridInfo { index: number; count: number; columns: number; } const UnfoldMenuGridContext = createContext({ index: 0, count: 1, columns: 1 }); function useUnfoldMenuGrid() { return useContext(UnfoldMenuGridContext); } interface UnfoldMenuContextValue { open: boolean; overlayVisible: boolean; requestOpen: () => void; setOpen: (open: boolean) => void; select: (value?: string) => void; progress: SharedValue; reveal: SharedValue; handoff: SharedValue; panelWidth: number; registerPanel: (height: number) => void; anchorRect: AnchorRect; panelOrigin: Point; labelOrigin: SharedValue; titleOrigin: SharedValue; registerLabelOrigin: (point: Point) => void; registerTitleOrigin: (point: Point) => void; palette: UnfoldMenuPalette; iconSize: number; reduceMotion: boolean; } const UnfoldMenuContext = createContext(null); function useUnfoldMenu(component: string) { const ctx = useContext(UnfoldMenuContext); if (!ctx) throw new Error(`${component} must be rendered inside .`); return ctx; } // --------------------------------------------------------------------------- // Root // --------------------------------------------------------------------------- export interface UnfoldMenuProps { children: React.ReactNode; className?: string; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; onSelect?: (value?: string) => void; closeOnSelect?: boolean; panelWidth?: number; screenMargin?: number; radius?: number; iconSize?: number; theme?: UnfoldMenuTheme; palette?: Partial; } /** * A compound menu whose trigger "unfolds" into a full panel: the trigger's * measured rect morphs (position, width, height, all spring-driven) into the * target panel rect, while the trigger's icon fades out and its label * cross-fades into the panel's title at the title's own position — so the * label reads as travelling and settling into place rather than two * unrelated pieces of text swapping. `measureInWindow` (not `measure`) is * used for the anchor so the morph starts from the right spot regardless of * status bar / notch offsets once the panel opens inside a `Modal`. */ export function UnfoldMenu({ children, className, open: openProp, defaultOpen = false, onOpenChange, onSelect, closeOnSelect = true, panelWidth: panelWidthProp, screenMargin = DEFAULT_SCREEN_MARGIN, radius = DEFAULT_RADIUS, iconSize = DEFAULT_ICON_SIZE, theme: themeProp, palette: paletteProp, }: UnfoldMenuProps) { const isControlled = openProp !== undefined; const [internalOpen, setInternalOpen] = useState(defaultOpen); const open = isControlled ? (openProp as boolean) : internalOpen; const reduceMotion = useReducedMotion(); const insets = useSafeAreaInsets(); const { width: screenWidth, height: screenHeight } = useWindowDimensions(); const systemDark = useColorScheme() === "dark"; const theme = themeProp ?? (systemDark ? "dark" : "light"); const progress = useSharedValue(open ? 1 : 0); const reveal = useSharedValue(open ? 1 : 0); const handoff = useSharedValue(open ? 1 : 0); const labelOrigin = useSharedValue({ x: 0, y: 0 }); const titleOrigin = useSharedValue({ x: 0, y: 0 }); const anchorRef = useRef(null); const [anchorRect, setAnchorRect] = useState({ x: 0, y: 0, w: 0, h: 0 }); const [panelHeight, setPanelHeight] = useState(0); const [mounted, setMounted] = useState(open); const [presented, setPresented] = useState(open); const panelWidth = Math.min( panelWidthProp ?? screenWidth * DEFAULT_PANEL_WIDTH_RATIO, screenWidth - screenMargin * 2, panelWidthProp ?? MAX_PANEL_WIDTH ); const setOpen = useCallback( (next: boolean) => { if (!isControlled) setInternalOpen(next); onOpenChange?.(next); }, [isControlled, onOpenChange] ); const requestOpen = useCallback(() => { const node = anchorRef.current; if (!node) { setOpen(true); return; } node.measureInWindow((x, y, w, h) => { setAnchorRect({ x, y, w, h }); setOpen(true); }); }, [setOpen]); const select = useCallback( (value?: string) => { onSelect?.(value); if (closeOnSelect) setOpen(false); }, [onSelect, closeOnSelect, setOpen] ); const registerPanel = useCallback((h: number) => { setPanelHeight((prev) => (Math.abs(prev - h) < 0.5 ? prev : h)); }, []); const registerLabelOrigin = useCallback((point: Point) => { labelOrigin.value = point; }, [labelOrigin]); const registerTitleOrigin = useCallback((point: Point) => { titleOrigin.value = point; }, [titleOrigin]); useEffect(() => { if (!open) return; setMounted(true); // Two rAFs: the first lets the Modal mount and the anchor's real layout // settle, the second flips `presented` so the very first animated frame // already has a measured panel height to morph towards. let inner = 0; const outer = requestAnimationFrame(() => { inner = requestAnimationFrame(() => setPresented(true)); }); return () => { cancelAnimationFrame(outer); cancelAnimationFrame(inner); }; }, [open]); useEffect(() => { if (reduceMotion) { progress.value = open ? 1 : 0; reveal.value = open ? 1 : 0; handoff.value = open ? 1 : 0; if (!open) setMounted(false); return; } if (open) { if (!presented) return; progress.value = withSpring(1, MORPH_SPRING); reveal.value = withDelay(REVEAL_DELAY, withTiming(1, { duration: REVEAL_DURATION, easing: REVEAL_EASING })); handoff.value = withDelay(HANDOFF_DELAY, withTiming(1, { duration: HANDOFF_DURATION, easing: HANDOFF_EASING })); return; } reveal.value = withTiming(0, { duration: CLOSE_DURATION, easing: CLOSE_EASING }); handoff.value = withTiming(0, { duration: HANDOFF_CLOSE_DURATION, easing: HANDOFF_EASING }); progress.value = withSpring(0, MORPH_CLOSE_SPRING, (finished) => { "worklet"; if (finished) { runOnJS(setMounted)(false); runOnJS(setPresented)(false); } }); }, [open, presented, reduceMotion, progress, reveal, handoff]); const palette = useMemo(() => ({ ...PALETTES[theme], ...paletteProp }), [theme, paletteProp]); const panelHeightResolved = panelHeight || anchorRect.h; const target = clampToScreen(anchorRect, panelWidth, panelHeightResolved, screenWidth, screenHeight, screenMargin, insets.top, insets.bottom); const panelOrigin = useMemo(() => ({ x: target.left, y: target.top }), [target.left, target.top]); const ctx = useMemo( () => ({ open, overlayVisible: mounted, requestOpen, setOpen, select, progress, reveal, handoff, panelWidth, registerPanel, anchorRect, panelOrigin, labelOrigin, titleOrigin, registerLabelOrigin, registerTitleOrigin, palette, iconSize, reduceMotion, }), [open, mounted, requestOpen, setOpen, select, progress, reveal, handoff, panelWidth, registerPanel, anchorRect, panelOrigin, labelOrigin, titleOrigin, registerLabelOrigin, registerTitleOrigin, palette, iconSize, reduceMotion] ); // CLAMPed rather than left to extend: MORPH_SPRING is underdamped by design // (it's meant to feel springy), so progress overshoots past 1 before // settling. `target`/`panelWidth`/`panelHeightResolved` are already the // screen-safe end state — extending past them during that overshoot is // exactly what pushed the panel out of bounds on expand. Clamping closes // that gap without changing the feel at rest. const morphStyle = useAnimatedStyle(() => { const p = progress.value; return { transform: [ { translateX: interpolate(p, [0, 1], [anchorRect.x, target.left], Extrapolation.CLAMP) }, { translateY: interpolate(p, [0, 1], [anchorRect.y, target.top], Extrapolation.CLAMP) }, ], width: interpolate(p, [0, 1], [anchorRect.w, panelWidth], Extrapolation.CLAMP), height: interpolate(p, [0, 1], [anchorRect.h, panelHeightResolved], Extrapolation.CLAMP), }; }); return ( {children} {mounted ? ( setOpen(false)} onShow={() => setPresented(true)} > setOpen(false)} /> {children} {/* The travelling trigger copy lives outside the panel: the panel resizes every frame, and anything inside it gets re-laid-out (text re-measured) along with it. Out here its layout is computed once and only its transform moves each frame. */} {children} ) : null} ); } // --------------------------------------------------------------------------- // Trigger // --------------------------------------------------------------------------- const triggerBase = "min-h-12 min-w-12 flex-row items-center justify-center gap-2 rounded-full border px-5"; export interface UnfoldMenuTriggerProps { children: React.ReactNode; className?: string; } export function UnfoldMenuTrigger({ children, className }: UnfoldMenuTriggerProps) { const { open, overlayVisible, requestOpen, progress, handoff, palette, reduceMotion, anchorRect, panelOrigin, labelOrigin, titleOrigin, registerLabelOrigin, } = useUnfoldMenu("UnfoldMenuTrigger"); const slot = useUnfoldMenuSlot(); const pressed = useSharedValue(0); const travelStyle = useAnimatedStyle(() => { const p = progress.value; const toX = panelOrigin.x + titleOrigin.value.x - labelOrigin.value.x; const toY = panelOrigin.y + titleOrigin.value.y - labelOrigin.value.y; return { transform: [ { translateX: interpolate(p, [0, 1], [anchorRect.x, toX], Extrapolation.CLAMP) }, { translateY: interpolate(p, [0, 1], [anchorRect.y, toY], Extrapolation.CLAMP) }, ], }; }); // The icon fades out almost immediately (by TRIGGER_ICON_FADE_END) — it was // never meant to travel, only the label is. But it's a child of the same // traveling container, so without a counter-transform it inherits the full // journey toward the panel's title, which sits with far less padding before // it than the icon+gap the trigger pill has before the label — dragging the // icon well outside the panel (visible as a stray icon detached to one // side, if the fade hasn't fully hidden it yet). Canceling the parent's // translateX/Y here keeps the icon visually anchored in place while it // fades, regardless of how far the label travels. const morphIconStyle = useAnimatedStyle(() => { const p = progress.value; const toX = panelOrigin.x + titleOrigin.value.x - labelOrigin.value.x; const toY = panelOrigin.y + titleOrigin.value.y - labelOrigin.value.y; const travelX = interpolate(p, [0, 1], [anchorRect.x, toX], Extrapolation.CLAMP); const travelY = interpolate(p, [0, 1], [anchorRect.y, toY], Extrapolation.CLAMP); return { opacity: interpolate(p, [0, TRIGGER_ICON_FADE_END], [1, 0], Extrapolation.CLAMP), transform: [{ translateX: anchorRect.x - travelX }, { translateY: anchorRect.y - travelY }], }; }); const morphLabelStyle = useAnimatedStyle(() => { const h = handoff.value; return { opacity: interpolate(h, [0, MORPH_LABEL_FADE_END], [1, 0], Extrapolation.CLAMP), transformOrigin: "left center", transform: [ { translateX: interpolate(h, [0, MORPH_LABEL_FADE_END], [0, -MORPH_PUSH_DISTANCE], Extrapolation.CLAMP) }, { scale: interpolate(h, [0, MORPH_LABEL_FADE_END], [1, MORPH_LABEL_SCALE_TO], Extrapolation.CLAMP) }, ], }; }); const morph = useMemo(() => ({ iconStyle: morphIconStyle, labelStyle: morphLabelStyle }), [morphIconStyle, morphLabelStyle]); const onLabelLayout = useCallback( (event: LayoutChangeEvent) => registerLabelOrigin({ x: event.nativeEvent.layout.x, y: event.nativeEvent.layout.y }), [registerLabelOrigin] ); const measurer = useMemo(() => ({ onLabelLayout }), [onLabelLayout]); const pressStyle = useAnimatedStyle(() => ({ transform: [{ scale: 1 - (1 - PRESS_SCALE) * (reduceMotion ? 0 : pressed.value) }], })); if (slot === "overlay") return null; if (slot === "float") { return ( {children} ); } return ( { pressed.value = withTiming(1, PRESS_TIMING); }} onPressOut={() => { pressed.value = withTiming(0, PRESS_TIMING); }} className={cn(triggerBase, className)} style={[{ backgroundColor: palette.surface, borderColor: palette.border }, overlayVisible ? { opacity: 0 } : null]} > {children} ); } // --------------------------------------------------------------------------- // Content / chrome // --------------------------------------------------------------------------- export interface UnfoldMenuContentProps { children: React.ReactNode; className?: string; } export function UnfoldMenuContent({ children, className }: UnfoldMenuContentProps) { const { open, progress, panelWidth, registerPanel } = useUnfoldMenu("UnfoldMenuContent"); const slot = useUnfoldMenuSlot(); const onLayout = useCallback((event: LayoutChangeEvent) => registerPanel(event.nativeEvent.layout.height), [registerPanel]); const layerStyle = useAnimatedStyle(() => ({ opacity: interpolate(progress.value, [CONTENT_FADE_START, CONTENT_FADE_END], [0, 1], Extrapolation.CLAMP), })); if (slot === "anchor") { // Invisible, laid out once to measure the panel's natural height. return ( {children} ); } if (slot === "float") return null; return ( {children} ); } export interface UnfoldMenuHeaderProps { children: React.ReactNode; className?: string; } export function UnfoldMenuHeader({ children, className }: UnfoldMenuHeaderProps) { const { palette } = useUnfoldMenu("UnfoldMenuHeader"); const slot = useUnfoldMenuSlot(); const [offset, setOffset] = useState({ x: 0, y: 0 }); const onLayout = useCallback((event: LayoutChangeEvent) => { const { x, y } = event.nativeEvent.layout; setOffset((prev) => (prev.x === x && prev.y === y ? prev : { x, y })); }, []); return ( {children} ); } export interface UnfoldMenuTitleProps { children: React.ReactNode; className?: string; } export function UnfoldMenuTitle({ children, className }: UnfoldMenuTitleProps) { const { palette, handoff, registerTitleOrigin } = useUnfoldMenu("UnfoldMenuTitle"); const offset = useUnfoldMenuOffset(); const slot = useUnfoldMenuSlot(); const [local, setLocal] = useState(null); const onLayout = useCallback((event: LayoutChangeEvent) => { const { x, y } = event.nativeEvent.layout; setLocal((prev) => (prev && prev.x === x && prev.y === y ? prev : { x, y })); }, []); useEffect(() => { if (!local) return; registerTitleOrigin({ x: offset.x + local.x, y: offset.y + local.y }); }, [local, offset.x, offset.y, registerTitleOrigin]); const fadeStyle = useAnimatedStyle(() => { const h = handoff.value; return { opacity: interpolate(h, [MORPH_TITLE_FADE_START, 1], [0, 1], Extrapolation.CLAMP), transformOrigin: "left center", transform: [ { translateX: interpolate(h, [MORPH_TITLE_FADE_START, 1], [MORPH_PUSH_DISTANCE, 0], Extrapolation.CLAMP) }, { scale: interpolate(h, [MORPH_TITLE_FADE_START, 1], [MORPH_TITLE_SCALE_FROM, 1], Extrapolation.CLAMP) }, ], }; }); return ( {children} ); } export interface UnfoldMenuCloseProps { children?: React.ReactNode | ((state: { color: string; size: number }) => React.ReactNode); className?: string; } export function UnfoldMenuClose({ children, className }: UnfoldMenuCloseProps) { const { setOpen, palette, iconSize } = useUnfoldMenu("UnfoldMenuClose"); const state = { color: palette.mutedText, size: iconSize }; const content = typeof children === "function" ? children(state) : (children ?? null); return ( setOpen(false)} className={cn("min-h-12 min-w-12 items-center justify-center", className)} > {content ?? } ); } // --------------------------------------------------------------------------- // Grid / items // --------------------------------------------------------------------------- export interface UnfoldMenuGridProps { children: React.ReactNode; columns?: number; className?: string; } export function UnfoldMenuGrid({ children, columns = DEFAULT_COLUMNS, className }: UnfoldMenuGridProps) { const items = React.Children.toArray(children); return ( {items.map((child, index) => ( {child} ))} ); } export interface UnfoldMenuItemProps { children: React.ReactNode; value?: string; onPress?: () => void; disabled?: boolean; className?: string; } export function UnfoldMenuItem({ children, value, onPress, disabled = false, className }: UnfoldMenuItemProps) { const { select, reveal, palette, reduceMotion } = useUnfoldMenu("UnfoldMenuItem"); const { index, count, columns } = useUnfoldMenuGrid(); const rows = Math.ceil(count / columns); const col = index % columns; const row = Math.floor(index / columns); const maxDistance = Math.hypot((columns - 1) / 2, (rows - 1) / 2) || 1; const distance = Math.hypot(col - (columns - 1) / 2, row - (rows - 1) / 2); const start = (distance / maxDistance) * STAGGER_SPAN; // Items reveal outward from the grid's center, nearest first, each one // fading and scaling in over its own [start, start + window] slice of the // shared `reveal` timeline — one shared value drives every item's stagger. const itemStyle = useAnimatedStyle(() => { if (reduceMotion) return { opacity: reveal.value, transform: [] }; const t = interpolate(reveal.value, [start, start + ITEM_WINDOW], [0, 1], Extrapolation.CLAMP); return { opacity: t, transform: [{ scale: ITEM_SCALE_FROM + (1 - ITEM_SCALE_FROM) * t }] }; }); const handlePress = useCallback(() => { onPress?.(); select(value); }, [onPress, select, value]); return ( {children} ); } export interface UnfoldMenuIconProps { children: React.ReactNode | ((state: { color: string; size: number }) => React.ReactNode); className?: string; } export function UnfoldMenuIcon({ children, className }: UnfoldMenuIconProps) { const { palette, iconSize } = useUnfoldMenu("UnfoldMenuIcon"); const color = useUnfoldMenuTint(palette.text); const morph = useUnfoldMenuMorph(); const content = typeof children === "function" ? children({ color, size: iconSize }) : children; return ( {content} ); } export interface UnfoldMenuLabelProps { children: React.ReactNode; className?: string; } export function UnfoldMenuLabel({ children, className }: UnfoldMenuLabelProps) { const { palette } = useUnfoldMenu("UnfoldMenuLabel"); const color = useUnfoldMenuTint(palette.text); const morph = useUnfoldMenuMorph(); return ( {children} ); } ``` ## VerifiedBadge - key: `verified-badge` - import: `import { VerifiedBadge } from "@/components/ui/verified-badge"` - description: Verified check badge with Name/Handle layout and palette overrides - tier: 1 - deps: lucide-react-native, react-native-svg, clsx, tailwind-merge ```tsx // components/ui/verified-badge.tsx import React, { createContext, useContext } from "react"; import { View, Text } from "react-native"; import { BadgeCheck } from "lucide-react-native"; import { cn } from "@/lib/utils"; export type VerifiedBadgePalette = { surface: string; border: string; name: string; handle: string; check: string; checkMark: string; }; const DEFAULT_PALETTE: VerifiedBadgePalette = { surface: "transparent", border: "transparent", name: "#18181b", handle: "#71717a", check: "#2563eb", checkMark: "#ffffff", }; export const VERIFIED_BADGE_EMERALD_PALETTE: VerifiedBadgePalette = { ...DEFAULT_PALETTE, check: "#10b981", }; export const VERIFIED_BADGE_INK_PALETTE: VerifiedBadgePalette = { surface: "#131315", border: "#27272a", name: "#fafafa", handle: "#a1a1aa", check: "#fafafa", checkMark: "#131315", }; type VerifiedBadgeContextValue = { palette: VerifiedBadgePalette; size: "sm" | "md"; }; const VerifiedBadgeContext = createContext(null); function useVerifiedBadgeContext(part: string): VerifiedBadgeContextValue { const ctx = useContext(VerifiedBadgeContext); if (!ctx) { throw new Error(`VerifiedBadge${part} must be rendered inside a `); } return ctx; } export interface VerifiedBadgeProps extends React.ComponentPropsWithoutRef { className?: string; palette?: Partial; size?: "sm" | "md"; label?: string; } export function VerifiedBadge({ className, palette, size = "md", label, style, children, ...props }: VerifiedBadgeProps) { const resolved: VerifiedBadgePalette = { ...DEFAULT_PALETTE, ...palette }; const surfaceOverride = resolved.surface !== "transparent" ? resolved.surface : undefined; const borderOverride = resolved.border !== "transparent" ? resolved.border : undefined; return ( {children} ); } export interface VerifiedBadgeContentProps extends React.ComponentPropsWithoutRef { className?: string; } export function VerifiedBadgeContent({ className, ...props }: VerifiedBadgeContentProps) { return ; } export interface VerifiedBadgeNameProps extends React.ComponentPropsWithoutRef { className?: string; } export function VerifiedBadgeName({ className, style, numberOfLines = 1, ...props }: VerifiedBadgeNameProps) { const { palette, size } = useVerifiedBadgeContext("Name"); return ( ); } export interface VerifiedBadgeHandleProps extends React.ComponentPropsWithoutRef { className?: string; } export function VerifiedBadgeHandle({ className, style, numberOfLines = 1, ...props }: VerifiedBadgeHandleProps) { const { palette, size } = useVerifiedBadgeContext("Handle"); return ( ); } export interface VerifiedBadgeCheckProps extends React.ComponentPropsWithoutRef { className?: string; label?: string; } export function VerifiedBadgeCheck({ className, label, ...props }: VerifiedBadgeCheckProps) { const { palette, size } = useVerifiedBadgeContext("Check"); const iconSize = size === "sm" ? 14 : 18; return ( ); } ``` ## VerticalFlowCarousel - key: `vertical-flow-carousel` - import: `import { VerticalFlowCarousel } from "@/components/ui/vertical-flow-carousel"` - description: Vertical coverflow — cards scale, tilt, and fade as they scroll away from center, with a blur overlay on unfocused cards - tier: 3 - deps: react-native-reanimated, expo-blur, clsx, tailwind-merge ```tsx // components/ui/vertical-flow-carousel.tsx import React from "react"; import { View } from "react-native"; import { BlurView } from "expo-blur"; import Animated, { Extrapolation, interpolate, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import { cn } from "@/lib/utils"; // Extra space after the last card so it can still scroll all the way to the // centered/focused position instead of stopping short once content runs out. const END_SPACER = 400; export interface VerticalFlowCarouselProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemHeight?: number; spacing?: number; rotationAngle?: number; scaleInactive?: number; opacityInactive?: number; showBlur?: boolean; blurIntensity?: number; snapEnabled?: boolean; onIndexChange?: (index: number) => void; } export function VerticalFlowCarousel({ className, data, itemHeight = 120, spacing = 50, rotationAngle = 12, scaleInactive = 0.85, opacityInactive = 0.5, showBlur = true, blurIntensity = 16, snapEnabled = true, onIndexChange, ...props }: VerticalFlowCarouselProps) { const step = itemHeight + spacing; const scrollY = useSharedValue(0); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollY.value = e.contentOffset.y; }, }); return ( onIndexChange?.(Math.round(e.nativeEvent.contentOffset.y / step))} > {data.map((item, index) => ( {item} ))} ); } function FlowItem({ index, count, scrollY, itemHeight, spacing, rotationAngle, scaleInactive, opacityInactive, showBlur, blurIntensity, children, }: { index: number; count: number; scrollY: SharedValue; itemHeight: number; spacing: number; rotationAngle: number; scaleInactive: number; opacityInactive: number; showBlur: boolean; blurIntensity: number; children: React.ReactNode; }) { const step = itemHeight + spacing; const inputRange = [(index - 1) * step, index * step, (index + 1) * step]; const style = useAnimatedStyle(() => { const scale = interpolate(scrollY.value, inputRange, [scaleInactive, 1, scaleInactive], Extrapolation.CLAMP); const opacity = interpolate(scrollY.value, inputRange, [opacityInactive, 1, opacityInactive], Extrapolation.CLAMP); const rotateZ = interpolate(scrollY.value, inputRange, [rotationAngle, 0, -rotationAngle], Extrapolation.CLAMP); return { opacity, transform: [{ perspective: 1000 }, { scale }, { rotateZ: `${rotateZ}deg` }] }; }); const blurStyle = useAnimatedStyle(() => ({ opacity: interpolate(scrollY.value, inputRange, [1, 0, 1], Extrapolation.CLAMP), })); return ( {children} {showBlur && ( )} ); } ``` ## VerticalPageCarousel - key: `vertical-page-carousel` - import: `import { VerticalPageCarousel } from "@/components/ui/vertical-page-carousel"` - description: Full-bleed vertical pager — one card fills the screen at a time, neighbors scale/fade out, with a haptic tick on release - tier: 2 - deps: react-native-reanimated, expo-haptics, clsx, tailwind-merge ```tsx // components/ui/vertical-page-carousel.tsx import React, { useState } from "react"; import { FlatList, View, useWindowDimensions, type LayoutChangeEvent } from "react-native"; import Animated, { Extrapolation, interpolate, runOnJS, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, type SharedValue, } from "react-native-reanimated"; import * as Haptics from "expo-haptics"; import { cn } from "@/lib/utils"; const AnimatedFlatList = Animated.createAnimatedComponent(FlatList); export interface VerticalPageCarouselProps extends React.ComponentPropsWithoutRef { className?: string; data: React.ReactNode[]; itemHeight?: number; cardSpacing?: number; cardMargin?: number; scaleRange?: [number, number, number]; opacityRange?: [number, number, number]; showDots?: boolean; onIndexChange?: (index: number) => void; } /** Full-bleed, one-card-per-screen vertical pager — each page scales/fades in from its neighbors, with a haptic tick on release. */ export function VerticalPageCarousel({ className, data, itemHeight: itemHeightProp, cardSpacing = 20, cardMargin = 20, scaleRange = [0.9, 1, 0.9], opacityRange = [0.5, 1, 0.5], showDots = true, onIndexChange, onLayout, ...props }: VerticalPageCarouselProps) { const { height: windowHeight } = useWindowDimensions(); // The centering padding below needs the carousel's own rendered height, not // the device's — assuming the full window (a natural assumption for a // full-screen pager) breaks the moment this is embedded in a smaller // container, over-padding the content and leaving every card off-center. const [measuredHeight, setMeasuredHeight] = useState(0); const height = measuredHeight || windowHeight; const itemHeight = itemHeightProp ?? height * 0.7; const step = itemHeight + cardSpacing; const scrollY = useSharedValue(0); const [active, setActive] = useState(0); const handleLayout = (e: LayoutChangeEvent) => { const h = e.nativeEvent.layout.height; if (h > 0 && h !== measuredHeight) setMeasuredHeight(h); onLayout?.(e); }; const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { scrollY.value = e.contentOffset.y / step; }, onEndDrag: () => { runOnJS(Haptics.impactAsync)(Haptics.ImpactFeedbackStyle.Medium); }, }); return ( { const idx = Math.round(e.nativeEvent.contentOffset.y / step); setActive(idx); onIndexChange?.(idx); }} renderItem={({ item, index }) => ( {item} )} keyExtractor={(_, i) => String(i)} /> {showDots && data.length > 1 && ( {data.map((_, i) => ( ))} )} ); } function PageSlide({ index, scrollY, itemHeight, cardSpacing, cardMargin, scaleRange, opacityRange, children, }: { index: number; scrollY: SharedValue; itemHeight: number; cardSpacing: number; cardMargin: number; scaleRange: [number, number, number]; opacityRange: [number, number, number]; children: React.ReactNode; }) { const input = [index - 1, index, index + 1]; const style = useAnimatedStyle(() => { const scale = interpolate(scrollY.value, input, scaleRange, Extrapolation.CLAMP); const opacity = interpolate(scrollY.value, input, opacityRange, Extrapolation.CLAMP); return { transform: [{ scale }], opacity }; }); return ( {children} ); } ``` ## Waveform - key: `waveform` - import: `import { Waveform } from "@/components/ui/waveform"` - description: Audio waveform bars — driven by real amplitude levels, with an ambient recording fallback - tier: 2 - deps: react-native-reanimated, clsx, tailwind-merge - aniui deps: animate, theme-provider ```tsx // components/ui/waveform.tsx import React, { useEffect } from "react"; import { View } from "react-native"; import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withSequence, withTiming, cancelAnimation } from "react-native-reanimated"; import { useReducedMotion } from "@/components/ui/animate"; import { cn } from "@/lib/utils"; import { useThemeColors } from "@/components/ui/theme-provider"; const sizes = { sm: 12, md: 20, lg: 28 } as const; // Ambient fallback shape when no real audio `levels` are wired up — // deterministic per-bar (no Math.random) so renders and tests are stable. const ambient = (i: number) => 0.35 + 0.65 * Math.abs(Math.sin(i * 2.4) * Math.cos(i * 0.7)); function Bar({ index, max, active, color, level, dim = 1 }: { index: number; max: number; active: boolean; color: string; level?: number; dim?: number; }) { const height = useSharedValue(3); const opacity = useSharedValue(dim); const reducedMotion = useReducedMotion(); useEffect(() => { // Follows the playhead smoothly (100ms matches typical status-update ticks). opacity.value = withTiming(dim, { duration: 100 }); }, [dim, opacity]); useEffect(() => { if (level !== undefined) { // Audio-driven: follow the measured amplitude for this bar. cancelAnimation(height); height.value = withTiming(Math.max(3, max * Math.min(1, Math.max(0, level))), { duration: 100 }); } else if (active && !reducedMotion) { const duration = 260 + (index % 5) * 70; height.value = withRepeat( withSequence(withTiming(max * ambient(index), { duration }), withTiming(max * 0.2, { duration })), -1, true ); } else { // Reduced motion (or inactive): a static ambient height, no looping bounce. cancelAnimation(height); height.value = withTiming(Math.max(3, max * ambient(index)), { duration: 150 }); } return () => cancelAnimation(height); }, [level, active, reducedMotion, index, max, height]); const style = useAnimatedStyle(() => ({ height: height.value, opacity: opacity.value })); return ; } export interface WaveformProps extends React.ComponentPropsWithoutRef { className?: string; /** Number of bars (default 28). */ bars?: number; /** * Real audio amplitudes in 0–1 (e.g. from mic metering or decoded playback * data). The most recent `bars` values are shown, newest on the right. * When provided, the bars follow the audio instead of the ambient animation. */ levels?: number[]; /** Without `levels`: animate an ambient wave (recording). false = static. */ active?: boolean; /** Playback position 0–1 — bars past the playhead are faded (scrubber look). */ progress?: number; size?: keyof typeof sizes; /** Bar color; defaults to the theme foreground. */ color?: string; } export function Waveform({ className, bars = 28, levels, active = true, progress, size = "md", color, style, ...props }: WaveformProps) { const colors = useThemeColors(); const barColor = color ?? colors.foreground; const window = levels?.slice(-bars); const pad = window ? bars - window.length : 0; // Continuous playhead in bar units — the boundary bar gets an interpolated // opacity so the sweep is smooth instead of stepping bar-by-bar. const playhead = progress !== undefined ? Math.min(1, Math.max(0, progress)) * bars : undefined; const dimFor = (i: number) => { if (playhead === undefined) return 1; if (i + 1 <= playhead) return 1; if (i >= playhead) return 0.35; return 0.35 + 0.65 * (playhead - i); }; return ( {Array.from({ length: bars }, (_, i) => ( ))} ); } ``` --- # Blocks (15 total) Full-screen compositions. Fetch via `https://aniui.dev/r/{name}.json`. ## bottom-tabs ```tsx // blocks/bottom-tabs.tsx import React, { useState } from "react"; import { View, Pressable } from "react-native"; import { Text } from "@/components/ui/text"; import { cn } from "@/lib/utils"; function HomeIcon({ active }: { active: boolean }) { return ( ); } function SearchIcon() { return ( ); } function CartIcon({ active }: { active: boolean }) { return ( ); } function ProfileIcon({ active }: { active: boolean }) { return ( ); } const tabs = [ { key: "home", label: "Home" }, { key: "search", label: "Search" }, { key: "cart", label: "Cart" }, { key: "profile", label: "Profile" }, ] as const; type TabKey = typeof tabs[number]["key"]; function TabIcon({ tabKey, active }: { tabKey: TabKey; active: boolean }) { if (tabKey === "home") return ; if (tabKey === "search") return ; if (tabKey === "cart") return ; return ; } export function BottomTabBar({ active, onTabPress, }: { active: TabKey; onTabPress: (key: TabKey) => void; }) { return ( {tabs.map((tab) => { const isActive = tab.key === active; return ( onTabPress(tab.key)} className="flex-1 items-center gap-1 py-1" accessible={true} accessibilityRole="tab" accessibilityState={{ selected: isActive }} accessibilityLabel={tab.label} > {tab.label} {isActive && ( )} ); })} ); } export function BottomTabsScreen() { const [active, setActive] = useState("home"); return ( {active} Screen content goes here ); } ``` ## chat ```tsx // blocks/chat.tsx import React, { useState, useRef } from "react"; import { View, ScrollView, Pressable, KeyboardAvoidingView, Platform } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Avatar } from "@/components/ui/avatar"; import { Input } from "@/components/ui/input"; type Message = { id: string; text: string; sender: "me" | "them"; time: string; }; const initialMessages: Message[] = [ { id: "1", text: "Hey! How's the project going?", sender: "them", time: "10:30 AM" }, { id: "2", text: "Going great! Just finished the UI.", sender: "me", time: "10:31 AM" }, { id: "3", text: "Awesome! Can you share the designs?", sender: "them", time: "10:32 AM" }, { id: "4", text: "Sure, sending them now", sender: "me", time: "10:33 AM" }, ]; export function ChatScreen({ onBack }: { onBack?: () => void }) { const [messages, setMessages] = useState(initialMessages); const [draft, setDraft] = useState(""); const scrollRef = useRef(null); function sendMessage() { if (!draft.trim()) return; const now = new Date(); const time = now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); setMessages((prev) => [ ...prev, { id: String(Date.now()), text: draft.trim(), sender: "me", time }, ]); setDraft(""); setTimeout(() => scrollRef.current?.scrollToEnd({ animated: true }), 50); } return ( {/* Header */} {/* arrow-left */} {/* inline SVG not available in RN — use a Text chevron or react-native-svg */} ‹ Sarah K. Online 📞 {/* Messages */} scrollRef.current?.scrollToEnd({ animated: false })} > {messages.map((msg) => ( {msg.text} {msg.time} ))} {/* Input Bar */} ↑ ); } ``` ## drawer-nav ```tsx // blocks/drawer-nav.tsx import React, { useState } from "react"; import { View, Pressable, ScrollView } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Avatar } from "@/components/ui/avatar"; import { Separator } from "@/components/ui/separator"; import { cn } from "@/lib/utils"; // Icon components — Lucide React Native // https://github.com/lucide-icons/lucide import { House, User, BarChart2, MessageCircle, Bell, Settings, LogOut, } from "lucide-react-native"; type MenuItem = { key: string; label: string; Icon: React.ComponentType<{ size: number; strokeWidth: number; color: string }>; }; const menuItems: MenuItem[] = [ { key: "home", label: "Home", Icon: House }, { key: "profile", label: "Profile", Icon: User }, { key: "analytics", label: "Analytics", Icon: BarChart2 }, { key: "messages", label: "Messages", Icon: MessageCircle }, { key: "notifications",label: "Notifications", Icon: Bell }, { key: "settings", label: "Settings", Icon: Settings }, ]; export function DrawerNavContent({ active, onNavigate, }: { active: string; onNavigate: (key: string) => void; }) { return ( {/* User section */} John Doe john@example.com {/* Menu items */} {menuItems.map(({ key, label, Icon }) => { const isActive = active === key; return ( onNavigate(key)} accessible={true} accessibilityRole="button" accessibilityLabel={label} className={cn( "flex-row items-center gap-3 px-3 py-3 rounded-lg mb-0.5", isActive ? "bg-accent" : "active:bg-accent/50" )} > {label} ); })} {/* Log Out */} {}} > Log Out ); } ``` ## forgot-password ```tsx // blocks/forgot-password.tsx import React, { useState } from "react"; import { View, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; export function ForgotPasswordScreen({ onBack }: { onBack?: () => void }) { const [email, setEmail] = useState(""); const [sent, setSent] = useState(false); if (sent) { return ( {/* Mail check icon */} ✓ Check your email We sent a password reset link to{" "} {email} setSent(false)} accessible accessibilityRole="button"> Didn't receive the email?{" "} Resend Back to sign in ); } return ( {/* Lock icon placeholder — swap with SVG icon library */} Reset password Enter your email and we'll send you a reset link Back to sign in ); } ``` ## home ```tsx // blocks/home.tsx import React from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Card, CardContent } from "@/components/ui/card"; import { Avatar } from "@/components/ui/avatar"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; export function HomeScreen() { return ( {/* Header */} Good morning John Doe {/* Quick Actions */} {/* bar-chart icon */} Analytics {/* message-circle icon */} Messages {/* settings icon */} Settings {/* Stats Card */} This Week +12% $4,280 Revenue across all products {/* Recent Activity */} Recent Activity {[ "Payment received — $120", "New subscriber — Sarah K.", "Order shipped — #1042", ].map((item, i) => ( {item} 2h ago ))} ); } ``` ## login ```tsx // blocks/login.tsx import React, { useState } from "react"; import { View, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Separator } from "@/components/ui/separator"; import { Label } from "@/components/ui/label"; // Use your preferred icon library, e.g. lucide-react-native: // import { ShieldCheck, Mail, Lock } from "lucide-react-native"; export function LoginScreen({ onSignUp, onForgotPassword, onSignIn, }: { onSignUp?: () => void; onForgotPassword?: () => void; onSignIn?: (email: string, password: string) => void; }) { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); return ( {/* Logo area */} {/* */} Welcome back Sign in to your account {/* Form */} {/* */} Forgot password? {/* */} {/* Divider */} or continue with {/* Social buttons */} {/* Sign up link */} Don't have an account? Sign up ); } ``` ## notifications ```tsx // blocks/notifications.tsx import React from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Separator } from "@/components/ui/separator"; import { Badge } from "@/components/ui/badge"; type Notification = { id: string; iconType: "message-circle" | "trophy" | "package" | "user-plus" | "credit-card"; iconBg: string; title: string; description: string; time: string; unread: boolean; }; const todayNotifications: Notification[] = [ { id: "1", iconType: "message-circle", iconBg: "bg-primary/10", title: "New Message", description: "Sarah sent you a message", time: "5m ago", unread: true, }, { id: "2", iconType: "trophy", iconBg: "bg-primary/10", title: "Achievement Unlocked", description: "You've completed 10 tasks!", time: "2h ago", unread: true, }, { id: "3", iconType: "package", iconBg: "bg-accent", title: "Order Update", description: "Your order #1042 has shipped", time: "5h ago", unread: false, }, ]; const yesterdayNotifications: Notification[] = [ { id: "4", iconType: "user-plus", iconBg: "bg-accent", title: "New Follower", description: "Alex started following you", time: "1d ago", unread: false, }, { id: "5", iconType: "credit-card", iconBg: "bg-accent", title: "Payment Received", description: "Payment of $120 received", time: "1d ago", unread: false, }, ]; function NotificationItem({ item }: { item: Notification }) { return ( {/* Icon rendered via accessibilityLabel; swap with your SVG icon component */} {item.iconType === "message-circle" ? "M" : item.iconType === "trophy" ? "T" : item.iconType === "package" ? "P" : item.iconType === "user-plus" ? "U" : "C"} {item.unread && ( )} {item.title} {item.time} {item.description} ); } export function NotificationsScreen() { return ( Notifications Mark all read Today {todayNotifications.map((item) => ( ))} Yesterday {yesterdayNotifications.map((item) => ( ))} ); } ``` ## onboarding ```tsx // blocks/onboarding.tsx import React, { useState } from "react"; import { View, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Button } from "@/components/ui/button"; const steps = [ { title: "Welcome", description: "Discover a new way to manage your tasks and boost productivity.", icon: ( ), }, { title: "Stay Focused", description: "Set goals, track progress, and achieve more every day.", icon: ( ), }, { title: "Connect", description: "Collaborate with your team and share updates in real-time.", icon: ( ), }, ]; export function OnboardingScreen({ onFinish }: { onFinish?: () => void }) { const [step, setStep] = useState(0); const isLast = step === steps.length - 1; const current = steps[step]; return ( {/* Skip */} setStep(steps.length - 1)} accessible={true} accessibilityRole="button" > Skip {/* Slide content */} {current.icon} {current.title} {current.description} {/* Dots */} {steps.map((_, i) => ( ))} {/* Next / Get Started */} ); } ``` ## pricing ```tsx // blocks/pricing.tsx import React, { useState } from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Separator } from "@/components/ui/separator"; const plans = [ { name: "Free", monthlyPrice: "$0", yearlyPrice: "$0", features: ["5 projects", "1GB storage", "Email support"], cta: "Current Plan", variant: "outline" as const, disabled: true, highlight: false, }, { name: "Pro", monthlyPrice: "$9.99", yearlyPrice: "$7.99", features: ["Everything in Free", "50 projects", "10GB storage", "Priority support"], cta: "Upgrade", variant: "default" as const, disabled: false, highlight: true, badge: "Popular", }, { name: "Enterprise", monthlyPrice: "$29.99", yearlyPrice: "$24.99", features: ["Everything in Pro", "Unlimited projects", "100GB storage", "24/7 support"], cta: "Contact Sales", variant: "outline" as const, disabled: false, highlight: false, }, ]; export function PricingScreen() { const [isYearly, setIsYearly] = useState(false); return ( Choose a Plan Start free. Scale as you grow. setIsYearly(false)} className={`px-5 py-2 rounded-full ${!isYearly ? "bg-background shadow-sm" : ""}`} > Monthly setIsYearly(true)} className={`px-5 py-2 rounded-full ${isYearly ? "bg-background shadow-sm" : ""}`} > Yearly {plans.map((plan) => ( {plan.name} {plan.badge && ( {plan.badge} )} {isYearly ? plan.yearlyPrice : plan.monthlyPrice} /month {plan.features.map((feature) => ( ✓ {feature} ))} ))} ); } ``` ## product-detail ```tsx // blocks/product-detail.tsx import React, { useState } from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Separator } from "@/components/ui/separator"; const SIZES = ["S", "M", "L", "XL"] as const; type Size = (typeof SIZES)[number]; export function ProductDetailScreen() { const [selectedSize, setSelectedSize] = useState("M"); const [quantity, setQuantity] = useState(1); return ( {/* Product Image */} {/* Back arrow icon */} {/* Heart icon placeholder */} {/* Name */} Classic T-Shirt {/* Price Row */} $29.99 $39.99 -25% {/* Rating */} 4.5 (128 reviews) {/* Description */} A timeless staple made from 100% organic cotton. Soft, breathable, and perfectly fitted — wear it dressed up or down. Available in multiple sizes and colors. {/* Size Selector */} Size {SIZES.map((size) => ( setSelectedSize(size)} className={`min-w-12 h-10 items-center justify-center rounded-xl border px-3 ${ selectedSize === size ? "border-primary bg-primary" : "border-border bg-background" }`} > {size} ))} {/* Quantity */} Quantity setQuantity((q) => Math.max(1, q - 1))} className="min-h-12 min-w-12 items-center justify-center rounded-xl border border-border bg-background" > − {quantity} setQuantity((q) => q + 1)} className="min-h-12 min-w-12 items-center justify-center rounded-xl border border-border bg-background" > + {/* CTAs */} ); } ``` ## product-list ```tsx // blocks/product-list.tsx import React, { useState } from "react"; import { View, ScrollView, Pressable, FlatList } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Card, CardContent } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; const CATEGORIES = ["All", "Clothing", "Shoes", "Accessories"]; const PRODUCTS = [ { id: "1", name: "Classic T-Shirt", price: "$29.99", rating: 4.5, bg: "bg-primary/5 to bg-primary/10" }, { id: "2", name: "Denim Jacket", price: "$89.99", rating: 4.8, bg: "bg-accent to bg-accent/50" }, { id: "3", name: "Running Shoes", price: "$119.99", rating: 4.6, bg: "bg-secondary to bg-secondary/70" }, { id: "4", name: "Leather Bag", price: "$149.99", rating: 4.7, bg: "bg-muted to bg-muted/60" }, ]; function StarIcon() { return ( {/* Inline SVG not available in RN — use a text star or react-native-svg */} ); } function HeartIcon({ filled }: { filled: boolean }) { return null; // Replace with react-native-svg Heart } function FilterIcon() { return null; // Replace with react-native-svg SlidersHorizontal } export function ProductListScreen() { const [activeCategory, setActiveCategory] = useState("All"); const [liked, setLiked] = useState([]); const toggleLike = (id: string) => { setLiked((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id] ); }; return ( {/* Header */} Shop {/* SlidersHorizontal icon via react-native-svg */} {/* Category pills */} {CATEGORIES.map((cat) => ( setActiveCategory(cat)} className={`rounded-full px-4 py-1.5 ${ activeCategory === cat ? "bg-primary" : "bg-muted" }`} > {cat} ))} {/* Product grid */} item.id} numColumns={2} showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32, gap: 12 }} columnWrapperStyle={{ gap: 12 }} renderItem={({ item }) => ( toggleLike(item.id)} className="absolute top-2 right-2 h-8 w-8 items-center justify-center rounded-full bg-background/80" > {/* Heart icon via react-native-svg */} {item.name} {item.price} {/* Star icon via react-native-svg */} {item.rating} )} /> ); } ``` ## profile ```tsx // blocks/profile.tsx import React from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Avatar } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import { Separator } from "@/components/ui/separator"; import { Badge } from "@/components/ui/badge"; const menuItems = [ { label: "My Posts", count: "24" }, { label: "Saved Items", count: "5" }, { label: "Privacy" }, { label: "Help & Support" }, ]; export function ProfileScreen({ onLogOut }: { onLogOut?: () => void }) { return ( {/* Header */} John Doe john@example.com Pro Member {/* Stats */} {[ { label: "Posts", value: "24" }, { label: "Followers", value: "1.2k" }, { label: "Following", value: "380" }, ].map(({ label, value }, i, arr) => ( {i > 0 && ( )} {value} {label} ))} {/* Menu Items */} {menuItems.map(({ label, count }) => ( {label} {count && ( {count} )} ))} {/* Log Out */} ); } ``` ## search ```tsx // blocks/search.tsx import React, { useState } from "react"; import { View, ScrollView, Pressable, TextInput } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Input } from "@/components/ui/input"; import { Separator } from "@/components/ui/separator"; const ALL_RESULTS = [ { title: "React Native Guide", description: "Getting started with mobile development", icon: "smartphone" }, { title: "UI Design Patterns", description: "Best practices for mobile interfaces", icon: "palette" }, { title: "Performance Tips", description: "Optimize your React Native app", icon: "zap" }, { title: "Component Library", description: "Build reusable UI components", icon: "package" }, ]; const RECENT_SEARCHES = ["React Native", "UI Components", "NativeWind"]; const TRENDING = [ "Getting started with Expo", "NativeWind v4 setup", "React Navigation tips", "Reanimated gestures", ]; export function SearchScreen() { const [query, setQuery] = useState(""); const filtered = query.trim() ? ALL_RESULTS.filter( (r) => r.title.toLowerCase().includes(query.toLowerCase()) || r.description.toLowerCase().includes(query.toLowerCase()) ) : []; return ( Search {/* Search icon */} S {query.length > 0 && ( setQuery("")} accessibilityRole="button" accessible={true} accessibilityLabel="Clear search" > X )} {query.trim() === "" ? ( {/* Recent Searches */} Recent Clear {RECENT_SEARCHES.map((tag) => ( {tag} ))} {/* Trending */} Trending {TRENDING.map((item, i, arr) => ( {i + 1} {item} › {i < arr.length - 1 && } ))} ) : filtered.length === 0 ? ( ? No results found Try searching for something else ) : ( {filtered.length} result{filtered.length !== 1 ? "s" : ""} for "{query}" {filtered.map((item, i) => ( {item.icon[0].toUpperCase()} {item.title} {item.description} › {i < filtered.length - 1 && } ))} )} ); } ``` ## settings ```tsx // blocks/settings.tsx import React, { useState } from "react"; import { View, ScrollView, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Avatar } from "@/components/ui/avatar"; import { Separator } from "@/components/ui/separator"; import { Switch } from "@/components/ui/switch"; export function SettingsScreen() { const [pushNotifications, setPushNotifications] = useState(true); const [emailNotifications, setEmailNotifications] = useState(false); const [darkMode, setDarkMode] = useState(false); return ( Settings {/* User Card */} John Doe john@example.com › {/* Notifications Section */} Notifications Push Notifications Alerts and reminders Email Notifications Weekly digest and updates {/* Appearance Section */} Appearance Dark Mode Switch to dark theme {/* General Section */} General {[ { label: "Language", value: "English" }, { label: "Privacy Policy", value: null }, { label: "Terms of Service", value: null }, ].map((item, i, arr) => ( {item.label} {item.value && ( {item.value} )} › {i < arr.length - 1 && } ))} {/* Danger Zone */} Danger Zone Delete Account › {/* App Version */} Version 1.0.0 ); } ``` ## signup ```tsx // blocks/signup.tsx import React, { useState } from "react"; import { View, Pressable } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { Text } from "@/components/ui/text"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Separator } from "@/components/ui/separator"; import { Label } from "@/components/ui/label"; import { Checkbox } from "@/components/ui/checkbox"; export function SignUpScreen({ onSignIn }: { onSignIn?: () => void }) { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [agreed, setAgreed] = useState(false); return ( {/* Logo */} {/* user-plus icon rendered via accessibilityLabel */} Create account Start your journey today {/* Form */} Must be at least 8 characters setAgreed(!agreed)} accessible={true} accessibilityRole="checkbox" accessibilityState={{ checked: agreed }} > I agree to the{" "} Terms of Service {" "}and{" "} Privacy Policy {/* Separator */} or continue with {/* Social Buttons */} {/* Sign In Link */} Already have an account? Sign in ); } ```