{"slug":"keypad","name":"Keypad","description":"A number pad to use as is or build key by key.","group":"Forms","detail_url":"https://beui.dev/native/r/keypad","page_url":"https://beui.dev/react-native/keypad","expo_go_url":"exp://u.expo.dev/93a3a95c-6dc2-4adb-b57c-efbecf859f25/--/keypad?runtime-version=exposdk%3A58.0.0&channel-name=production","source_url":"https://github.com/starc007/beui-native/tree/main/src/components/keypad","libraries":["react","react-native","react-native-reanimated","react-native-svg","uniwind"],"install":["npx expo install react-native-reanimated react-native-svg 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/keypad/index.ts","content":"export type { KeypadLayout, KeypadProps } from \"./keypad\";\nexport { Keypad } from \"./keypad\";\nexport type { KeypadSize, KeypadVariant } from \"./keypad-context\";\nexport type { KeypadDeleteProps } from \"./keypad-delete\";\nexport { KeypadDelete } from \"./keypad-delete\";\nexport type { KeypadInputOptions } from \"./keypad-input\";\nexport { applyKeypadKey } from \"./keypad-input\";\nexport type { KeypadKeyProps } from \"./keypad-key\";\nexport { KeypadKey } from \"./keypad-key\";\nexport type { KeypadRowProps } from \"./keypad-row\";\nexport { KeypadRow } from \"./keypad-row\";\nexport { KeypadSpacer } from \"./keypad-spacer\";\n","type":"component"},{"path":"src/components/keypad/keypad-context.ts","content":"import { createContext, useContext } from \"react\";\n\nexport type KeypadVariant = \"plain\" | \"circle\";\nexport type KeypadSize = \"sm\" | \"md\";\n\nexport type KeypadContextValue = {\n  onKeyPress?: (key: string) => void;\n  variant: KeypadVariant;\n  size: KeypadSize;\n  disabled: boolean;\n  reduce: boolean;\n};\n\nexport const KeypadContext = createContext<KeypadContextValue | null>(null);\n\nexport function useKeypad() {\n  const context = useContext(KeypadContext);\n  if (!context) throw new Error(\"Keypad parts must be inside <Keypad>.\");\n  return context;\n}\n\n/** Each variant's key size: plain keys are rows, circle keys are round. */\nexport const KEY_SIZES: Record<\n  KeypadVariant,\n  Record<KeypadSize, { height: number; label: string; gap: number }>\n> = {\n  plain: {\n    sm: { height: 48, label: \"text-xl\", gap: 0 },\n    md: { height: 56, label: \"text-2xl\", gap: 0 },\n  },\n  circle: {\n    sm: { height: 64, label: \"text-2xl\", gap: 20 },\n    md: { height: 76, label: \"text-3xl\", gap: 24 },\n  },\n};\n","type":"component"},{"path":"src/components/keypad/keypad-delete.tsx","content":"import Svg, { Path } from \"react-native-svg\";\nimport { useResolveClassNames } from \"uniwind\";\nimport { KeypadKey, type KeypadKeyProps } from \"./keypad-key\";\n\n/** A backspace mark. */\nfunction DeleteGlyph({ size }: { size: number }) {\n  const { color } = useResolveClassNames(\"text-foreground\");\n  return (\n    <Svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\">\n      <Path\n        d=\"M9 5h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6-7z\"\n        stroke={color}\n        strokeWidth={1.8}\n        strokeLinejoin=\"round\"\n      />\n      <Path\n        d=\"m12 9.5 5 5M17 9.5l-5 5\"\n        stroke={color}\n        strokeWidth={1.8}\n        strokeLinecap=\"round\"\n      />\n    </Svg>\n  );\n}\n\nexport type KeypadDeleteProps = Omit<KeypadKeyProps, \"value\"> & {\n  /** Sent to `onKeyPress`. Defaults to \"delete\". */\n  value?: string;\n  /** The glyph's size. Defaults to 26. */\n  iconSize?: number;\n};\n\n/**\n * The delete key: a backspace mark that sends \"delete\". Pass `onLongPress`\n * to clear everything when it's held.\n */\nexport function KeypadDelete({\n  value = \"delete\",\n  iconSize = 26,\n  accessibilityLabel = \"Delete\",\n  children,\n  ...props\n}: KeypadDeleteProps) {\n  return (\n    <KeypadKey value={value} accessibilityLabel={accessibilityLabel} {...props}>\n      {children ?? <DeleteGlyph size={iconSize} />}\n    </KeypadKey>\n  );\n}\n","type":"component"},{"path":"src/components/keypad/keypad-input.ts","content":"export type KeypadInputOptions = {\n  /** Digits allowed after the decimal point. 0 turns the point off. Defaults to 2. */\n  decimals?: number;\n  /** The longest the value can get, point included. Defaults to 12. */\n  maxLength?: number;\n  /** The key that removes the last character. Defaults to \"delete\". */\n  deleteKey?: string;\n  /** The key for the decimal point. Defaults to \".\". */\n  decimalKey?: string;\n};\n\n/**\n * The value after a key press, for amount and number entry. Digits append\n * (a lone \"0\" is replaced), the point appears once (\"0.\" when empty) and\n * respects `decimals`, delete removes the last character, and anything past\n * `maxLength` is ignored. Unknown keys leave the value as it is.\n */\nexport function applyKeypadKey(\n  value: string,\n  key: string,\n  {\n    decimals = 2,\n    maxLength = 12,\n    deleteKey = \"delete\",\n    decimalKey = \".\",\n  }: KeypadInputOptions = {},\n) {\n  if (key === deleteKey) return value.slice(0, -1);\n  if (key === decimalKey) {\n    if (decimals === 0 || value.includes(\".\") || value.length >= maxLength) {\n      return value;\n    }\n    return value ? `${value}.` : \"0.\";\n  }\n  if (!/^\\d$/.test(key) || value.length >= maxLength) return value;\n  const fraction = value.split(\".\")[1];\n  if (fraction !== undefined && fraction.length >= decimals) return value;\n  return value === \"0\" ? key : value + key;\n}\n","type":"component"},{"path":"src/components/keypad/keypad-key.tsx","content":"import type { ReactNode, Ref } from \"react\";\nimport {\n  Pressable,\n  type PressableProps,\n  Text,\n  View,\n  type ViewInstance,\n} from \"react-native\";\nimport Animated, {\n  useAnimatedStyle,\n  useSharedValue,\n  withSpring,\n  withTiming,\n} from \"react-native-reanimated\";\nimport { EASE_OUT, SPRING_PRESS } from \"../../styles/motion\";\nimport { KEY_SIZES, useKeypad } from \"./keypad-context\";\n\n// The backdrop lights at once and lingers a moment after release.\nconst LIGHT = { duration: 60, easing: EASE_OUT };\nconst FADE = { duration: 220, easing: EASE_OUT };\nconst SINK = 0.08;\n\nexport type KeypadKeyProps = Omit<PressableProps, \"children\" | \"style\"> & {\n  /** Sent to the keypad's `onKeyPress`, such as \"7\", \".\" or \"delete\". */\n  value: string;\n  /** Replaces the default label, such as an icon. */\n  children?: ReactNode;\n  /** Small text under the label, such as \"ABC\" on a phone pad. */\n  sublabel?: string;\n  /** Runs instead of the keypad's `onKeyPress`. */\n  onPress?: () => void;\n  className?: string;\n  ref?: Ref<ViewInstance>;\n};\n\n/**\n * One key. Plain keys light a soft backdrop while held; circle keys sit in\n * a ring that sinks a little and brightens. Pressing sends `value` to the\n * keypad's `onKeyPress`, or runs the key's own `onPress`.\n */\nexport function KeypadKey({\n  value,\n  children,\n  sublabel,\n  onPress,\n  disabled: keyDisabled,\n  accessibilityLabel,\n  className = \"\",\n  ref,\n  ...props\n}: KeypadKeyProps) {\n  const {\n    onKeyPress,\n    variant,\n    size,\n    disabled: padDisabled,\n    reduce,\n  } = useKeypad();\n  const disabled = padDisabled || !!keyDisabled;\n  const dims = KEY_SIZES[variant][size];\n  const circle = variant === \"circle\";\n  const pressed = useSharedValue(0);\n\n  const glow = useAnimatedStyle(() => ({ opacity: pressed.value }));\n  const sink = useAnimatedStyle(() => ({\n    transform: [{ scale: 1 - pressed.value * SINK }],\n  }));\n\n  const press = (on: boolean) => {\n    if (reduce) pressed.value = on ? 1 : 0;\n    else if (circle) pressed.value = withSpring(on ? 1 : 0, SPRING_PRESS);\n    else pressed.value = withTiming(on ? 1 : 0, on ? LIGHT : FADE);\n  };\n\n  const label = children ?? (\n    <>\n      <Text className={`font-medium text-foreground ${dims.label}`}>\n        {value}\n      </Text>\n      {sublabel ? (\n        <Text className=\"text-xs font-medium tracking-widest text-muted\">\n          {sublabel}\n        </Text>\n      ) : null}\n    </>\n  );\n\n  return (\n    <Pressable\n      {...props}\n      ref={ref}\n      disabled={disabled}\n      onPress={() => (onPress ? onPress() : onKeyPress?.(value))}\n      onPressIn={(e) => {\n        press(true);\n        props.onPressIn?.(e);\n      }}\n      onPressOut={(e) => {\n        press(false);\n        props.onPressOut?.(e);\n      }}\n      accessibilityRole=\"keyboardkey\"\n      accessibilityLabel={accessibilityLabel ?? value}\n      accessibilityState={{ disabled }}\n      style={[\n        circle ? { width: dims.height } : { flex: 1 },\n        { height: dims.height, opacity: disabled ? 0.4 : 1 },\n      ]}\n      className={`items-center justify-center ${className}`}\n    >\n      {circle ? (\n        <Animated.View\n          style={[sink, { width: dims.height, height: dims.height }]}\n          className=\"items-center justify-center overflow-hidden rounded-full border border-border bg-surface\"\n        >\n          <Animated.View\n            style={glow}\n            className=\"absolute inset-0 bg-border-strong\"\n          />\n          {label}\n        </Animated.View>\n      ) : (\n        <View className=\"absolute inset-x-1.5 inset-y-0.5\">\n          <Animated.View\n            style={glow}\n            className=\"flex-1 rounded-2xl bg-foreground/10\"\n          />\n        </View>\n      )}\n      {circle ? null : label}\n    </Pressable>\n  );\n}\n","type":"component"},{"path":"src/components/keypad/keypad-row.tsx","content":"import { View, type ViewProps } from \"react-native\";\nimport { KEY_SIZES, useKeypad } from \"./keypad-context\";\n\nexport type KeypadRowProps = ViewProps & { className?: string };\n\n/** A row of keys. Plain keys share its width; circle keys sit apart. */\nexport function KeypadRow({ className = \"\", style, ...props }: KeypadRowProps) {\n  const { variant, size } = useKeypad();\n  const gap = KEY_SIZES[variant][size].gap;\n  return (\n    <View\n      {...props}\n      style={[{ gap }, style]}\n      className={`flex-row ${variant === \"circle\" ? \"justify-center\" : \"\"} ${className}`}\n    />\n  );\n}\n","type":"component"},{"path":"src/components/keypad/keypad-spacer.tsx","content":"import { View } from \"react-native\";\nimport { KEY_SIZES, useKeypad } from \"./keypad-context\";\n\n/** An empty slot that holds a key's place, such as left of 0 on a pin pad. */\nexport function KeypadSpacer() {\n  const { variant, size } = useKeypad();\n  const { height } = KEY_SIZES[variant][size];\n  return (\n    <View\n      importantForAccessibility=\"no-hide-descendants\"\n      style={\n        variant === \"circle\" ? { width: height, height } : { flex: 1, height }\n      }\n    />\n  );\n}\n","type":"component"},{"path":"src/components/keypad/keypad.tsx","content":"import { type ReactNode, useMemo } from \"react\";\nimport { View, type ViewProps } from \"react-native\";\nimport { useReducedMotionPreference } from \"../../hooks/use-reduced-motion\";\nimport {\n  KeypadContext,\n  type KeypadSize,\n  type KeypadVariant,\n} from \"./keypad-context\";\nimport { KeypadDelete } from \"./keypad-delete\";\nimport { KeypadKey } from \"./keypad-key\";\nimport { KeypadRow } from \"./keypad-row\";\nimport { KeypadSpacer } from \"./keypad-spacer\";\n\n/** Ready-made layouts for when no keys are passed in. */\nexport type KeypadLayout = \"decimal\" | \"number\" | \"pin\";\n\nconst LETTERS = [\n  \"\",\n  \"\",\n  \"ABC\",\n  \"DEF\",\n  \"GHI\",\n  \"JKL\",\n  \"MNO\",\n  \"PQRS\",\n  \"TUV\",\n  \"WXYZ\",\n];\nconst DIGITS = [\n  [\"1\", \"2\", \"3\"],\n  [\"4\", \"5\", \"6\"],\n  [\"7\", \"8\", \"9\"],\n];\n\nexport type KeypadProps = Omit<ViewProps, \"children\"> & {\n  /** Gets each key's value, such as \"7\", \".\" or \"delete\". */\n  onKeyPress?: (key: string) => void;\n  /** Flat keys with a backdrop that lights, or round passcode keys. Defaults to plain. */\n  variant?: KeypadVariant;\n  size?: KeypadSize;\n  /**\n   * Used when there are no children: `decimal` ends in a point, 0 and\n   * delete; `number` leaves the point out; `pin` adds letters under the\n   * digits. Defaults to `decimal`.\n   */\n  layout?: KeypadLayout;\n  /** Takes the bottom left slot of a ready-made layout, such as a Face ID key. */\n  bottomLeft?: ReactNode;\n  /** Hides delete in a ready-made layout, such as while nothing is typed. */\n  showDelete?: boolean;\n  /** Runs when delete is held in a ready-made layout, such as to clear. */\n  onDeleteLongPress?: () => void;\n  deleteLabel?: string;\n  decimalLabel?: string;\n  disabled?: boolean;\n  disableAnimation?: boolean;\n  /** Your own rows of keys, in place of a ready-made layout. */\n  children?: ReactNode;\n  className?: string;\n};\n\n/**\n * A number pad you can use as is or build key by key. It shares its\n * variant, size and `onKeyPress` with every `KeypadKey` inside, so custom\n * keys look and behave like the rest.\n */\nexport function Keypad({\n  onKeyPress,\n  variant = \"plain\",\n  size = \"md\",\n  layout = \"decimal\",\n  bottomLeft,\n  showDelete = true,\n  onDeleteLongPress,\n  deleteLabel,\n  decimalLabel = \"Decimal point\",\n  disabled = false,\n  disableAnimation = false,\n  children,\n  className = \"\",\n  ...props\n}: KeypadProps) {\n  const reduce = useReducedMotionPreference() || disableAnimation;\n  const context = useMemo(\n    () => ({ onKeyPress, variant, size, disabled, reduce }),\n    [onKeyPress, variant, size, disabled, reduce],\n  );\n  const pin = layout === \"pin\";\n  const circle = variant === \"circle\";\n\n  const ready = (\n    <>\n      {DIGITS.map((row) => (\n        <KeypadRow key={row[0]}>\n          {row.map((d) => (\n            <KeypadKey\n              key={d}\n              value={d}\n              sublabel={pin ? LETTERS[Number(d)] : undefined}\n            />\n          ))}\n        </KeypadRow>\n      ))}\n      <KeypadRow>\n        {bottomLeft ??\n          (layout === \"decimal\" ? (\n            <KeypadKey value=\".\" accessibilityLabel={decimalLabel} />\n          ) : (\n            <KeypadSpacer />\n          ))}\n        <KeypadKey value=\"0\" />\n        {showDelete ? (\n          <KeypadDelete\n            accessibilityLabel={deleteLabel}\n            onLongPress={onDeleteLongPress}\n          />\n        ) : (\n          <KeypadSpacer />\n        )}\n      </KeypadRow>\n    </>\n  );\n\n  return (\n    <KeypadContext.Provider value={context}>\n      <View\n        {...props}\n        style={[circle ? { gap: size === \"sm\" ? 12 : 16 } : null, props.style]}\n        className={className}\n      >\n        {children ?? ready}\n      </View>\n    </KeypadContext.Provider>\n  );\n}\n","type":"component"},{"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/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  /* Tailwind's default monospace stack isn't a font React Native can load. */\n  :root {\n    @variant ios {\n      --font-mono: Menlo;\n    }\n  }\n\n  :root {\n    @variant android {\n      --font-mono: monospace;\n    }\n  }\n}\n","type":"theme"}]}