{"slug":"checkbox","name":"Checkbox","description":"A checkmark that draws itself in.","group":"Forms","detail_url":"https://beui.dev/native/r/checkbox","page_url":"https://beui.dev/react-native/checkbox","expo_go_url":"exp://u.expo.dev/93a3a95c-6dc2-4adb-b57c-efbecf859f25/--/checkbox?runtime-version=exposdk%3A57.0.0&channel-name=production","source_url":"https://github.com/starc007/beui-native/tree/main/src/components/checkbox","libraries":["react","react-native","react-native-reanimated","uniwind"],"install":["npx expo install react-native-reanimated react-native-worklets","npm install uniwind tailwindcss"],"setup":["Quickest: run `npx beui-native add <slug>` from the app's root. It writes the files below and installs the libraries.","Copy the files into the app and keep their folder layout: components import the shared files by relative path.","Add the theme tokens once, imported after Tailwind and Uniwind in the CSS file Uniwind reads.","Wrap the app in GestureHandlerRootView if it uses react-native-gesture-handler and isn't already.","Works in Expo and in bare React Native. Every component honors the system Reduce Motion setting."],"files":[{"path":"src/components/checkbox/checkbox.tsx","content":"import { type Ref, useEffect, useState } from \"react\";\nimport {\n  type ColorValue,\n  Pressable,\n  type PressableProps,\n  StyleSheet,\n  Text,\n  View,\n} from \"react-native\";\nimport Animated, {\n  cancelAnimation,\n  interpolateColor,\n  useAnimatedStyle,\n  useSharedValue,\n  withDelay,\n  withSpring,\n  withTiming,\n} from \"react-native-reanimated\";\nimport { useResolveClassNames } from \"uniwind\";\nimport { usePresence } from \"../../hooks/use-presence\";\nimport { useReducedMotionPreference } from \"../../hooks/use-reduced-motion\";\nimport { DrawnPath, type PathSegment } from \"../../primitives/drawn-path\";\nimport { EASE_OUT, motion } from \"../../styles/motion\";\n\nconst BOX = 20;\n// The web mark is a 24-unit SVG path drawn at 12px with a 3-unit stroke.\nconst MARK = 12;\nconst CHECK: PathSegment[] = [\n  [5, 13, 9, 17],\n  [9, 17, 19, 7],\n];\nconst DASH: PathSegment[] = [[6, 12, 18, 12]];\n// Tops a 20-point row up to a 48-point touch area.\nconst HIT_SLOP = { top: 14, bottom: 14, left: 0, right: 0 };\nconst COLOR_FADE = { duration: 200, reduceMotion: motion.fade.reduceMotion };\n\ntype Mark = \"check\" | \"dash\";\n\nexport type CheckboxProps = Omit<\n  PressableProps,\n  \"children\" | \"style\" | \"onPress\" | \"disabled\"\n> & {\n  /** Controlled state. Omit it and use `defaultChecked` for uncontrolled use. */\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n  /** Shows a dash and reports a mixed state, for \"select all\" rows. */\n  indeterminate?: boolean;\n  disabled?: boolean;\n  label?: string;\n  /** Supporting text under the label, read as the hint rather than the name. */\n  description?: string;\n  /** Disables press and mark motion independently of the system preference. */\n  disableAnimation?: boolean;\n  className?: string;\n  ref?: Ref<View>;\n};\n\nfunction CheckMark({\n  mark,\n  appear,\n  exiting,\n  reduce,\n  color,\n}: {\n  mark: Mark;\n  appear: boolean;\n  exiting: boolean;\n  reduce: boolean;\n  color: ColorValue | undefined;\n}) {\n  const segments = mark === \"check\" ? CHECK : DASH;\n  const presence = useSharedValue(appear && !reduce ? 0 : 1);\n  const draw = useSharedValue(appear && !reduce ? 0 : 1);\n\n  useEffect(() => {\n    if (reduce) {\n      presence.value = exiting ? 0 : 1;\n      draw.value = 1;\n      return;\n    }\n    presence.value = withTiming(exiting ? 0 : 1, motion.exit);\n    if (!exiting) {\n      draw.value = withDelay(\n        40,\n        withTiming(1, {\n          duration: mark === \"check\" ? 300 : 200,\n          easing: EASE_OUT,\n        }),\n      );\n    }\n  }, [draw, exiting, mark, presence, reduce]);\n\n  const markStyle = useAnimatedStyle(() => ({\n    opacity: presence.value,\n    transform: [{ scale: 0.5 + 0.5 * presence.value }],\n  }));\n\n  return (\n    <Animated.View style={[styles.mark, markStyle]}>\n      <DrawnPath\n        segments={segments}\n        size={MARK}\n        strokeWidth={3}\n        color={color}\n        progress={draw}\n      />\n    </Animated.View>\n  );\n}\n\nexport function Checkbox({\n  checked: checkedProp,\n  defaultChecked = false,\n  onCheckedChange,\n  indeterminate = false,\n  disabled = false,\n  label,\n  description,\n  disableAnimation = false,\n  className = \"\",\n  accessibilityLabel,\n  accessibilityHint,\n  accessibilityState,\n  hitSlop,\n  onPressIn,\n  onPressOut,\n  ref,\n  ...props\n}: CheckboxProps) {\n  const [uncontrolled, setUncontrolled] = useState(defaultChecked);\n  const checked = checkedProp ?? uncontrolled;\n  const showMark = checked || indeterminate;\n  const reducedMotion = useReducedMotionPreference();\n  const animate = !reducedMotion && !disableAnimation;\n\n  const { backgroundColor: idleFill } = useResolveClassNames(\"bg-background\");\n  const { backgroundColor: idleBorder } = useResolveClassNames(\"bg-muted/50\");\n  const { backgroundColor: activeFill } = useResolveClassNames(\"bg-primary\");\n  const { color: markColor } = useResolveClassNames(\"text-on-primary\");\n\n  const active = useSharedValue(showMark ? 1 : 0);\n  const scale = useSharedValue(1);\n  const marks = usePresence<Mark | null>(\n    showMark ? (indeterminate ? \"dash\" : \"check\") : null,\n    showMark ? (indeterminate ? \"dash\" : \"check\") : null,\n    () => motion.exit.duration + 40,\n  );\n\n  useEffect(() => {\n    const target = showMark ? 1 : 0;\n    active.value = animate ? withTiming(target, COLOR_FADE) : target;\n  }, [active, animate, showMark]);\n\n  useEffect(() => {\n    if (!animate || disabled) {\n      cancelAnimation(scale);\n      scale.value = 1;\n    }\n  }, [animate, disabled, scale]);\n\n  const boxStyle = useAnimatedStyle(() => ({\n    backgroundColor: interpolateColor(\n      active.value,\n      [0, 1],\n      [String(idleFill ?? \"transparent\"), String(activeFill ?? \"blue\")],\n    ),\n    borderColor: interpolateColor(\n      active.value,\n      [0, 1],\n      [String(idleBorder ?? \"gray\"), String(activeFill ?? \"blue\")],\n    ),\n    transform: [{ scale: scale.value }],\n  }));\n\n  return (\n    <Pressable\n      {...props}\n      ref={ref}\n      accessible\n      accessibilityRole=\"checkbox\"\n      accessibilityLabel={accessibilityLabel ?? label}\n      accessibilityHint={accessibilityHint ?? description}\n      accessibilityState={{\n        ...accessibilityState,\n        checked: indeterminate ? \"mixed\" : checked,\n        disabled,\n      }}\n      aria-checked={indeterminate ? \"mixed\" : checked}\n      aria-disabled={disabled}\n      disabled={disabled}\n      hitSlop={hitSlop ?? HIT_SLOP}\n      className={`self-start flex-row gap-3 ${description ? \"items-start\" : \"items-center\"} ${className}`}\n      onPress={() => {\n        const next = !checked;\n        if (checkedProp === undefined) setUncontrolled(next);\n        onCheckedChange?.(next);\n      }}\n      onPressIn={(event) => {\n        if (animate) scale.value = withSpring(0.92, motion.press);\n        onPressIn?.(event);\n      }}\n      onPressOut={(event) => {\n        if (animate) scale.value = withSpring(1, motion.press);\n        onPressOut?.(event);\n      }}\n    >\n      <Animated.View\n        style={[styles.box, disabled && styles.disabled, boxStyle]}\n      >\n        {marks.map((item) =>\n          item.value ? (\n            <CheckMark\n              key={item.key}\n              mark={item.value}\n              appear={item.appear}\n              exiting={item.exiting}\n              reduce={!animate}\n              color={markColor}\n            />\n          ) : null,\n        )}\n      </Animated.View>\n      {label || description ? (\n        <View className={`shrink gap-0.5 ${disabled ? \"opacity-60\" : \"\"}`}>\n          {label ? (\n            <Text className=\"text-sm leading-5 text-foreground\">{label}</Text>\n          ) : null}\n          {description ? (\n            <Text className=\"text-xs text-muted\">{description}</Text>\n          ) : null}\n        </View>\n      ) : null}\n    </Pressable>\n  );\n}\n\nconst styles = StyleSheet.create({\n  box: {\n    width: BOX,\n    height: BOX,\n    borderRadius: 6,\n    borderWidth: 2,\n    alignItems: \"center\",\n    justifyContent: \"center\",\n    flexShrink: 0,\n  },\n  disabled: { opacity: 0.6 },\n  mark: { position: \"absolute\", width: MARK, height: MARK },\n});\n","type":"component"},{"path":"src/components/checkbox/index.ts","content":"export type { CheckboxProps } from \"./checkbox\";\nexport { Checkbox } from \"./checkbox\";\n","type":"component"},{"path":"src/hooks/use-presence.ts","content":"import { useEffect, useRef, useState } from \"react\";\n\nexport type PresenceItem<T> = {\n  key: string;\n  value: T;\n  /** False for the item present on first render, so it does not animate in. */\n  appear: boolean;\n  exiting: boolean;\n};\n\n/**\n * Keeps replaced items mounted while they animate out, like AnimatePresence.\n * A key that returns while exiting is revived in place.\n */\nexport function usePresence<T>(\n  key: string | null,\n  value: T,\n  exitDuration: (value: T) => number,\n) {\n  const [items, setItems] = useState<PresenceItem<T>[]>(() =>\n    key === null ? [] : [{ key, value, appear: false, exiting: false }],\n  );\n  const [currentKey, setCurrentKey] = useState(key);\n  const exitDurationRef = useRef(exitDuration);\n  exitDurationRef.current = exitDuration;\n\n  // Adjust during render so the new item and the exits start in the same frame.\n  if (key !== currentKey) {\n    setCurrentKey(key);\n    setItems((previous) => {\n      const next = previous.map((item) =>\n        item.key === key\n          ? { ...item, value, exiting: false }\n          : { ...item, exiting: true },\n      );\n      if (key !== null && !previous.some((item) => item.key === key)) {\n        next.push({ key, value, appear: true, exiting: false });\n      }\n      return next;\n    });\n  }\n\n  const exitingKeys = items\n    .filter((item) => item.exiting)\n    .map((item) => item.key)\n    .join(\"\\n\");\n\n  useEffect(() => {\n    if (!exitingKeys) return;\n    const timers = items\n      .filter((item) => item.exiting)\n      .map((item) =>\n        setTimeout(() => {\n          setItems((previous) =>\n            previous.filter(\n              (candidate) => !(candidate.key === item.key && candidate.exiting),\n            ),\n          );\n        }, exitDurationRef.current(item.value)),\n      );\n    return () => {\n      for (const timer of timers) clearTimeout(timer);\n    };\n    // Restart removal timers only when the set of exiting items changes.\n  }, [exitingKeys]);\n\n  return items;\n}\n","type":"shared"},{"path":"src/hooks/use-reduced-motion.ts","content":"import { useEffect, useState } from \"react\";\nimport { AccessibilityInfo } from \"react-native\";\nimport { useReducedMotion } from \"react-native-reanimated\";\n\n/** Reanimated supplies a synchronous initial value; native events keep it current. */\nexport function useReducedMotionPreference() {\n  const initialValue = useReducedMotion();\n  const [reducedMotion, setReducedMotion] = useState(initialValue);\n\n  useEffect(() => {\n    let active = true;\n    let receivedEvent = false;\n    const subscription = AccessibilityInfo.addEventListener(\n      \"reduceMotionChanged\",\n      (value) => {\n        receivedEvent = true;\n        setReducedMotion(value);\n      },\n    );\n    void AccessibilityInfo.isReduceMotionEnabled().then((value) => {\n      if (active && !receivedEvent) setReducedMotion(value);\n    });\n    return () => {\n      active = false;\n      subscription.remove();\n    };\n  }, []);\n\n  return reducedMotion;\n}\n","type":"shared"},{"path":"src/primitives/drawn-path.tsx","content":"import { type ColorValue, StyleSheet, View } from \"react-native\";\nimport Animated, {\n  interpolate,\n  type SharedValue,\n  useAnimatedStyle,\n} from \"react-native-reanimated\";\n\n/** A straight line in a square viewBox: [x1, y1, x2, y2]. */\nexport type PathSegment = [x1: number, y1: number, x2: number, y2: number];\n\nexport type DrawnPathProps = {\n  /** Straight segments drawn in order, like an SVG polyline. */\n  segments: PathSegment[];\n  /** Rendered width and height in points. */\n  size: number;\n  /** Stroke width in viewBox units. */\n  strokeWidth: number;\n  /** Side of the square viewBox the segments are written in. Defaults to 24. */\n  viewBox?: number;\n  color: ColorValue | undefined;\n  /** 0 draws nothing and 1 draws every segment, like SVG `pathLength`. */\n  progress: SharedValue<number>;\n};\n\nfunction length([x1, y1, x2, y2]: PathSegment) {\n  return Math.hypot(x2 - x1, y2 - y1);\n}\n\n/**\n * Draws a polyline on with rotated Views, so shared components need no SVG\n * library. Round caps extend half a stroke past each end, like SVG's linecap.\n */\nexport function DrawnPath({\n  segments,\n  size,\n  strokeWidth,\n  viewBox = 24,\n  color,\n  progress,\n}: DrawnPathProps) {\n  const unit = size / viewBox;\n  const stroke = strokeWidth * unit;\n  const total = segments.reduce((sum, segment) => sum + length(segment), 0);\n  let start = 0;\n\n  return (\n    <View style={{ width: size, height: size }}>\n      {segments.map((segment) => {\n        const from = start / total;\n        start += length(segment);\n        return (\n          <Stroke\n            key={segment.join()}\n            segment={segment}\n            unit={unit}\n            stroke={stroke}\n            from={from}\n            to={start / total}\n            progress={progress}\n            color={color}\n          />\n        );\n      })}\n    </View>\n  );\n}\n\nfunction Stroke({\n  segment,\n  unit,\n  stroke,\n  from,\n  to,\n  progress,\n  color,\n}: {\n  segment: PathSegment;\n  unit: number;\n  stroke: number;\n  from: number;\n  to: number;\n  progress: SharedValue<number>;\n  color: ColorValue | undefined;\n}) {\n  const [x1, y1, x2, y2] = segment;\n  const full = length(segment) * unit;\n  const angle = Math.atan2(y2 - y1, x2 - x1);\n\n  const animatedStyle = useAnimatedStyle(() => {\n    const drawn = interpolate(progress.value, [from, to], [0, 1], \"clamp\");\n    return { opacity: drawn > 0 ? 1 : 0, width: stroke + full * drawn };\n  });\n\n  return (\n    <Animated.View\n      style={[\n        styles.stroke,\n        {\n          left: x1 * unit - stroke / 2,\n          top: y1 * unit - stroke / 2,\n          height: stroke,\n          borderRadius: stroke / 2,\n          backgroundColor: color,\n          // Rotate around the start point so the stroke grows from it.\n          transformOrigin: [stroke / 2, stroke / 2, 0],\n          transform: [{ rotate: `${angle}rad` }],\n        },\n        animatedStyle,\n      ]}\n    />\n  );\n}\n\nconst styles = StyleSheet.create({\n  stroke: { position: \"absolute\" },\n});\n","type":"shared"},{"path":"src/styles/motion.ts","content":"import { Easing, ReduceMotion } from \"react-native-reanimated\";\n\n// Mirrors beUI's lib/ease.ts so native motion matches the web library.\n\nexport const EASE_OUT = Easing.bezier(0.16, 1, 0.3, 1);\nexport const EASE_IN_OUT = Easing.bezier(0.77, 0, 0.175, 1);\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n  reduceMotion: ReduceMotion.System,\n} as const;\n\n/** Content swaps: label and icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n  reduceMotion: ReduceMotion.System,\n} as const;\n\n/** Shared-layout glides: pills, indicators and panels moving between positions. */\nexport const SPRING_LAYOUT = {\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n  reduceMotion: ReduceMotion.System,\n} as const;\n\n/** Dragged handles and fills; critically damped so values never rebound off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n  reduceMotion: ReduceMotion.System,\n} as const;\n\nexport const motion = {\n  press: SPRING_PRESS,\n  swap: SPRING_SWAP,\n  layout: SPRING_LAYOUT,\n  glide: SPRING_GLIDE,\n  exit: { duration: 160, easing: EASE_OUT, reduceMotion: ReduceMotion.System },\n  fade: { duration: 150, reduceMotion: ReduceMotion.System },\n} as const;\n","type":"shared"},{"path":"src/styles/theme.css","content":"/* Matches the default beUI palette in ui-components/lib/themes.ts.\n   Native surface maps to card; muted maps to muted-foreground. */\n@layer theme {\n  :root {\n    @variant light {\n      --color-background: oklch(99% 0 0);\n      --color-surface: oklch(97% 0 0);\n      --color-foreground: oklch(15% 0 0);\n      --color-muted: oklch(50% 0 0);\n      --color-border: oklch(15% 0 0 / 0.06);\n      --color-border-strong: oklch(15% 0 0 / 0.16);\n      --color-primary: #0285f7;\n      --color-on-primary: #ffffff;\n      --color-destructive: #dc2626;\n      --color-success: #059669;\n      --color-warning: #d97706;\n    }\n  }\n\n  :root {\n    @variant dark {\n      --color-background: #151515;\n      --color-surface: #1c1c1c;\n      --color-foreground: oklch(96% 0 0);\n      --color-muted: oklch(62% 0 0);\n      --color-border: rgb(255 255 255 / 0.05);\n      --color-border-strong: rgb(255 255 255 / 0.14);\n      --color-primary: #0285f7;\n      --color-on-primary: #ffffff;\n      --color-destructive: #f87171;\n      --color-success: #34d399;\n      --color-warning: #fbbf24;\n    }\n  }\n}\n","type":"theme"}]}