Signature Pad
A freehand drawing field with normalized signature strokes, undo, clear, and an alternate input slot.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add signature-padSource files
Expand a file to read the source the installer copies into your app.
components/ui/signature-pad/SignaturePad.tsx
import * as React from 'react'
import { View, type ViewProps } from 'react-native'
import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler'
import Svg, { Path } from 'react-native-svg'
import { Button } from '@/components/ui/button'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'
export interface SignaturePoint {
readonly x: number
readonly y: number
}
export type SignatureStroke = readonly SignaturePoint[]
export type SignatureValue = readonly SignatureStroke[]
export interface SignaturePadProps extends Omit<ViewProps, 'children'> {
className?: string
/** Saved strokes use coordinates in the range 0 to 1, relative to the canvas. */
value?: SignatureValue
defaultValue?: SignatureValue
onValueChange?: (value: SignatureValue) => void
disabled?: boolean
label?: string
undoLabel?: string
clearLabel?: string
emptyLabel?: string
drawnLabel?: string
/** A caller-owned way to confirm without a freehand gesture. */
alternative?: React.ReactNode
}
const empty: SignatureValue = []
const clamp = (value: number) => Math.max(0, Math.min(1, value))
interface CanvasSize {
width: number
height: number
}
function coordinates(x: number, y: number, { width, height }: CanvasSize): SignaturePoint {
return { x: clamp(x / width), y: clamp(y / height) }
}
function addPoint(stroke: SignatureStroke, point: SignaturePoint) {
const last = stroke.at(-1)
if (last && Math.hypot(last.x - point.x, last.y - point.y) < 0.003) return stroke
return [...stroke, point]
}
function pathOf(stroke: SignatureStroke, { width, height }: CanvasSize) {
return stroke
.filter(({ x, y }) => Number.isFinite(x) && Number.isFinite(y))
.map(({ x, y }, index) => `${index ? 'L' : 'M'} ${clamp(x) * width} ${clamp(y) * height}`)
.join(' ')
}
export function SignaturePad({
className,
value,
defaultValue = empty,
onValueChange,
disabled = false,
label = 'Signature',
undoLabel = 'Undo stroke',
clearLabel = 'Clear signature',
emptyLabel = 'Draw your signature in the box.',
drawnLabel = 'Signature drawn.',
alternative,
...props
}: SignaturePadProps) {
const colors = useThemeColors()
const [canvas, setCanvas] = React.useState<CanvasSize>({ width: 0, height: 0 })
const [internal, setInternal] = React.useState(defaultValue)
const [draft, setDraft] = React.useState<SignatureStroke>([])
const [edited, setEdited] = React.useState(false)
const strokes = value ?? internal
const status = strokes.length ? drawnLabel : emptyLabel
useAnnouncement(edited ? status : undefined)
const enabled = !disabled && canvas.width > 0 && canvas.height > 0
const active = React.useRef<{ canvas: CanvasSize; points: SignatureStroke } | null>(null)
const latest = React.useRef({ canvas, enabled, strokes, value, onValueChange })
latest.current = { canvas, enabled, strokes, value, onValueChange }
function change(next: SignatureValue) {
const state = latest.current
if (!state.enabled) return
setEdited(true)
if (state.value === undefined) {
state.strokes = next
setInternal(next)
}
state.onValueChange?.(next)
}
function cancelDraft() {
active.current = null
setDraft([])
}
const pan = Gesture.Pan()
.minDistance(0)
.maxPointers(1)
.enabled(enabled)
.runOnJS(true)
.onStart(({ x, y }) => {
const state = latest.current
if (!state.enabled) return
const points = [coordinates(x, y, state.canvas)]
active.current = { canvas: state.canvas, points }
setDraft(points)
})
.onUpdate(({ x, y, numberOfPointers }) => {
const stroke = active.current
if (numberOfPointers > 1) {
cancelDraft()
} else if (stroke && stroke.canvas === latest.current.canvas && latest.current.enabled) {
const points = addPoint(stroke.points, coordinates(x, y, stroke.canvas))
if (points !== stroke.points) {
stroke.points = points
setDraft(points)
}
}
})
.onEnd(({ x, y }, success) => {
const stroke = active.current
const state = latest.current
if (!success || !stroke || stroke.canvas !== state.canvas || !state.enabled) return
const points = addPoint(stroke.points, coordinates(x, y, stroke.canvas))
if (points.length >= 2) change([...state.strokes, points])
})
.onFinalize(cancelDraft)
return (
<View {...props} className={cn('gap-2', className)}>
<Text className="font-semibold" accessibilityRole="header">
{label}
</Text>
<GestureHandlerRootView style={{ flexGrow: 0 }}>
<GestureDetector gesture={pan}>
<View
collapsable={false}
accessible={false}
className="h-[168px] overflow-hidden rounded-lg border border-muted-foreground bg-muted"
onLayout={({ nativeEvent: { layout } }) => {
setCanvas((size) =>
size.width === layout.width && size.height === layout.height
? size
: { width: layout.width, height: layout.height },
)
}}
>
<View pointerEvents="none" aria-hidden className="absolute inset-0">
<Svg width={canvas.width} height={canvas.height}>
{[...strokes, draft]
.filter((line) => line.length > 1)
.map((line, index) => (
<Path
key={index}
d={pathOf(line, canvas)}
fill="none"
stroke={colors.foreground}
strokeWidth={2.5}
strokeLinecap="round"
strokeLinejoin="round"
/>
))}
</Svg>
</View>
</View>
</GestureDetector>
</GestureHandlerRootView>
<Text size="sm" variant="muted">
{status}
</Text>
<View className="flex-row flex-wrap gap-2">
<Button
variant="outline"
disabled={!enabled || !strokes.length}
onPress={() => {
cancelDraft()
change(latest.current.strokes.slice(0, -1))
}}
>
{undoLabel}
</Button>
<Button
variant="ghost"
disabled={!enabled || !strokes.length}
onPress={() => {
cancelDraft()
change(empty)
}}
>
{clearLabel}
</Button>
</View>
{alternative}
</View>
)
}
components/ui/signature-pad/index.ts
export {
SignaturePad,
type SignaturePadProps,
type SignaturePoint,
type SignatureStroke,
type SignatureValue,
} from './SignaturePad'
Dependencies
Registry items
npm packages
react-native-gesture-handlerreact-native-svg