All components
Signature Pad
Freehand drawing surface for signatures with smooth pressure-aware strokes, a guide line, a clear button, and a hidden input for forms.
Sign here
12345678910111213141516171819202122import { SignaturePad } from "#components/ui/ui-sdk/signature-pad.tsx";
export function Example() { return ( // UI SDK has no signature pad, so Root owns the strokes: pointer events // on Control feed a small freehand outliner and each stroke becomes a // filled SVG path (currentColor, so ink follows dark mode). HiddenInput // carries an SVG data URL; parts compose through render. <SignaturePad.Root name="signature" variant="outline" size="md"> <SignaturePad.Label>Sign here</SignaturePad.Label> <SignaturePad.Control> <SignaturePad.Segment /> <SignaturePad.Guide /> <SignaturePad.ClearTrigger /> </SignaturePad.Control> <SignaturePad.HiddenInput /> </SignaturePad.Root> );}
// export: onDrawEnd={(d) => upload(d.dataUrl)}// pen: drawing={{ size: 4, thinning: 0.6, simulatePressure: false }}Variants
Sign here
outlineSign here
subtleSizes
Sign here
smSign here
mdSign here
lgIn a form
HiddenInput submits the signature as an SVG data URL under the Root's `name`; the line below shows its current value.
Sign to accept
signature: (empty)
12345678910<SignaturePad.Root name="signature"> <SignaturePad.Label>Sign to accept</SignaturePad.Label> <SignaturePad.Control> <SignaturePad.Segment /> <SignaturePad.Guide /> <SignaturePad.ClearTrigger /> </SignaturePad.Control> {/* submits an SVG data URL under "signature" */} <SignaturePad.HiddenInput /></SignaturePad.Root>Install
1npx stylexblocks add signature-padSource
components/ui/ui-sdk/signature-pad.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645import * as stylex from "@stylexjs/stylex";import { createContext, useCallback, useContext, useId, useRef, useState } from "react";import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";import { defineSlotRecipe, resolveSlotStyles, type StyleOverrideProps,} from "#lib/recipe-props.ts";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const signaturePadRoot = stylex.create({ base: { display: 'flex', flexDirection: 'column', gap: spacing._1_5, width: '100%', },})
const signaturePadLabel = stylex.create({ base: { fontWeight: fontWeights.medium, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, color: semanticColors.fg, opacity: { default: null, ':is([data-disabled])': 0.5, }, },})
// The drawing surface. Strokes are filled with `currentColor`, so the// semantic fg color keeps the ink legible in light and dark mode.const signaturePadControl = stylex.create({ base: { position: 'relative', width: '100%', touchAction: 'none', userSelect: 'none', color: semanticColors.fg, borderRadius: semanticRadii.panel, borderWidth: '1px', cursor: { default: 'crosshair', ':is([data-disabled])': 'not-allowed', }, opacity: { default: null, ':is([data-disabled])': 0.5, }, outlineWidth: { default: null, ':focus-visible': 'var(--focus-ring-width, 0)', }, outlineOffset: { default: null, ':focus-visible': '0px', }, outlineStyle: { default: null, ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
const signaturePadControlSizes = stylex.create({ sm: { height: sizes._32, }, md: { height: sizes._40, }, lg: { height: sizes._48, },})
// `outline` matches the file-upload dropzone (dashed border on the page// background); `subtle` matches the subtle input (muted fill, no border).const signaturePadControlVariants = stylex.create({ outline: { backgroundColor: semanticColors.bg, borderStyle: 'dashed', borderColor: { default: semanticColors.border, ':hover': semanticColors.borderEmphasized, ':is([data-disabled])': semanticColors.border, ':focus-visible': colorPalette.focusRing, }, }, subtle: { backgroundColor: semanticColors.bgMuted, borderStyle: 'solid', borderColor: { default: 'transparent', ':focus-visible': colorPalette.focusRing, }, },})
const signaturePadSegment = stylex.create({ base: { position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible', pointerEvents: 'none', fill: 'currentColor', },})
// The baseline to sign on.const signaturePadGuide = stylex.create({ base: { position: 'absolute', insetInline: spacing._4, bottom: '28%', borderBottomWidth: '1px', borderBottomStyle: 'dashed', borderBottomColor: semanticColors.borderEmphasized, pointerEvents: 'none', },})
const signaturePadClearTrigger = stylex.create({ base: { position: 'absolute', top: spacing._2, insetInlineEnd: spacing._2, zIndex: 1, display: { default: 'inline-flex', ':is([hidden])': 'none', }, alignItems: 'center', justifyContent: 'center', width: sizes.controlXs, height: sizes.controlXs, borderRadius: semanticRadii.control, color: { default: semanticColors.fgMuted, ':hover': semanticColors.fg, }, backgroundColor: { default: 'transparent', ':hover': semanticColors.bgSubtle, }, cursor: { default: 'pointer', ':disabled': 'not-allowed', }, outlineWidth: { default: null, ':focus-visible': '2px', }, outlineOffset: { default: null, ':focus-visible': '0px', }, outlineStyle: { default: null, ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
export type SignaturePadVariant = keyof typeof signaturePadControlVariants
export type SignaturePadSize = keyof typeof signaturePadControlSizes
const signaturePadRecipe = defineSlotRecipe({ slots: { root: { styles: signaturePadRoot }, label: { styles: signaturePadLabel }, control: { styles: signaturePadControl, sizes: signaturePadControlSizes, variants: signaturePadControlVariants, }, segment: { styles: signaturePadSegment }, guide: { styles: signaturePadGuide }, clearTrigger: { styles: signaturePadClearTrigger }, }, defaultVariants: { variant: "outline", size: "md" },});
const chrome = stylex.create({ btnReset: { appearance: "none", borderWidth: 0, borderStyle: "none", padding: 0, margin: 0, fontFamily: "inherit", fontSize: "inherit", },});
function ClearIcon(props: React.ComponentProps<"svg">) { return ( <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}> <path d="M2.5 8a5.5 5.5 0 1 0 1.6-3.9M2.5 2.5v2.6h2.6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
// ---------------------------------------------------------------------------// Stroke geometry: a small perfect-freehand-style outliner. Input points are// smoothed (streamline), each gets a radius from real or simulated pressure,// and the stroke becomes a filled outline: one side out with quadratic// midpoint curves, a round end cap, the other side back, a round start cap.// ---------------------------------------------------------------------------
interface StrokePoint { x: number; y: number; pressure: number;}
export interface SignaturePadDrawingOptions { /** Base stroke diameter in px. */ size?: number; /** How much pressure thins the stroke (0 = constant width). */ thinning?: number; /** Input smoothing, 0..1 (higher = smoother, laggier). */ streamline?: number; /** Derive pressure from speed instead of the pointer (mouse, touch). */ simulatePressure?: boolean;}
const fmt = (n: number) => (Math.round(n * 100) / 100).toString();
function strokeToPath(input: StrokePoint[], options: Required<SignaturePadDrawingOptions>): string { const { size, thinning, streamline, simulatePressure } = options; if (!input.length) return ""; const pts: StrokePoint[] = [{ ...input[0]! }]; for (let i = 1; i < input.length; i++) { const prev = pts[pts.length - 1]!; const p = input[i]!; const t = 1 - streamline; const next = { x: prev.x + (p.x - prev.x) * t, y: prev.y + (p.y - prev.y) * t, pressure: p.pressure, }; if (Math.hypot(next.x - prev.x, next.y - prev.y) < 0.5) continue; pts.push(next); } const last = input[input.length - 1]!; const tail = pts[pts.length - 1]!; if (pts.length > 1 && Math.hypot(last.x - tail.x, last.y - tail.y) >= 0.5) pts.push({ ...last });
if (pts.length === 1) { const { x, y } = pts[0]!; const r = Math.max(size / 2, 0.75); return `M${fmt(x - r)},${fmt(y)}a${fmt(r)},${fmt(r)} 0 1,0 ${fmt(2 * r)},0a${fmt(r)},${fmt(r)} 0 1,0 ${fmt(-2 * r)},0Z`; }
let pressure = simulatePressure ? 0.5 : (pts[0]!.pressure || 0.5); const radii = pts.map((p, i) => { if (simulatePressure) { const d = i ? Math.hypot(p.x - pts[i - 1]!.x, p.y - pts[i - 1]!.y) : 0; const target = Math.min(Math.max(1 - d / (size * 4), 0), 1); pressure += (target - pressure) * 0.3; } else { pressure = p.pressure || 0.5; } return Math.max(size * (0.5 - thinning * (0.5 - pressure)), 0.4); });
const left: { x: number; y: number }[] = []; const right: { x: number; y: number }[] = []; for (let i = 0; i < pts.length; i++) { const a = pts[Math.max(i - 1, 0)]!; const b = pts[Math.min(i + 1, pts.length - 1)]!; const len = Math.hypot(b.x - a.x, b.y - a.y) || 1; const nx = -(b.y - a.y) / len; const ny = (b.x - a.x) / len; const p = pts[i]!; const r = radii[i]!; left.push({ x: p.x + nx * r, y: p.y + ny * r }); right.push({ x: p.x - nx * r, y: p.y - ny * r }); }
const side = (points: { x: number; y: number }[]) => { let d = ""; for (let i = 1; i < points.length - 1; i++) { const p = points[i]!; const q = points[i + 1]!; d += `Q${fmt(p.x)},${fmt(p.y)} ${fmt((p.x + q.x) / 2)},${fmt((p.y + q.y) / 2)}`; } const end = points[points.length - 1]!; return `${d}L${fmt(end.x)},${fmt(end.y)}`; };
const back = [...right].reverse(); const rEnd = radii[radii.length - 1]!; const rStart = radii[0]!; return ( `M${fmt(left[0]!.x)},${fmt(left[0]!.y)}` + side(left) + `A${fmt(rEnd)},${fmt(rEnd)} 0 0,0 ${fmt(back[0]!.x)},${fmt(back[0]!.y)}` + side(back) + `A${fmt(rStart)},${fmt(rStart)} 0 0,0 ${fmt(left[0]!.x)},${fmt(left[0]!.y)}Z` );}
/** Self-contained SVG data URL of the strokes (black ink), for forms. */function toSvgDataUrl(paths: string[], width: number, height: number) { if (!paths.length) return ""; const body = paths.map((d) => `<path d="${d}" fill="black"/>`).join(""); const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${body}</svg>`; return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;}
// ---------------------------------------------------------------------------
export interface SignaturePadDrawEndDetails { paths: string[]; /** SVG data URL of the full signature. */ dataUrl: string;}
interface SignaturePadContextValue { ids: { label: string; control: string }; paths: string[]; currentPath: string | null; drawing: boolean; empty: boolean; disabled: boolean; interactive: boolean; required: boolean; name: string | undefined; dataUrl: string; clear: () => void; pointerDown: (event: React.PointerEvent<HTMLElement>) => void; pointerMove: (event: React.PointerEvent<HTMLElement>) => void; pointerUp: (event: React.PointerEvent<HTMLElement>) => void;}
const PadContext = createContext<SignaturePadContextValue | null>(null);
function usePad() { const ctx = useContext(PadContext); if (!ctx) throw new Error("SignaturePad parts must be rendered inside <SignaturePad.Root>"); return ctx;}
const { withProvider, withContext } = createSlotRecipeContext(signaturePadRecipe);
const StyledRoot = withProvider("div", "root", "SignaturePadRoot");
export type SignaturePadRootProps = Omit<React.ComponentProps<typeof StyledRoot>, "onChange"> & { defaultPaths?: string[]; drawing?: SignaturePadDrawingOptions; disabled?: boolean; readOnly?: boolean; required?: boolean; /** Form field name for the hidden input. */ name?: string; /** Called on every stroke update with the committed and in-progress paths. */ onDraw?: (details: { paths: string[]; currentPath: string | null }) => void; onDrawEnd?: (details: SignaturePadDrawEndDetails) => void;};
/** * SignaturePad — Base UI ships no signature pad, so Root owns the strokes: * pointer events on the Control feed a hand-written freehand outliner, and * each finished stroke becomes a filled SVG path (`currentColor`, so ink * follows the semantic fg color in dark mode). Parts compose through * `render`. */function Root(props: SignaturePadRootProps) { const { defaultPaths = [], drawing: drawingOptions, disabled = false, readOnly = false, required = false, name, onDraw, onDrawEnd, ...rest } = props; const options: Required<SignaturePadDrawingOptions> = { size: 3, thinning: 0.7, streamline: 0.5, simulatePressure: true, ...drawingOptions, }; const id = useId(); const [paths, setPaths] = useState<string[]>(defaultPaths); const [currentPath, setCurrentPath] = useState<string | null>(null); const [box, setBox] = useState({ width: 0, height: 0 }); const points = useRef<StrokePoint[] | null>(null); const interactive = !disabled && !readOnly;
const pointFrom = (event: React.PointerEvent<HTMLElement>): StrokePoint => { const rect = event.currentTarget.getBoundingClientRect(); return { x: event.clientX - rect.left, y: event.clientY - rect.top, pressure: event.pointerType === "pen" ? event.pressure : 0.5, }; };
const pointerDown = (event: React.PointerEvent<HTMLElement>) => { if (!interactive) return; if (event.pointerType === "mouse" && event.button !== 0) return; if (event.ctrlKey || event.metaKey || event.altKey) return; if ((event.target as HTMLElement).closest("[data-part='clear-trigger']")) return; event.currentTarget.setPointerCapture(event.pointerId); points.current = [pointFrom(event)]; const next = strokeToPath(points.current, options); setCurrentPath(next); onDraw?.({ paths, currentPath: next }); };
const pointerMove = (event: React.PointerEvent<HTMLElement>) => { if (!points.current) return; points.current.push(pointFrom(event)); const next = strokeToPath(points.current, options); setCurrentPath(next); onDraw?.({ paths, currentPath: next }); };
const pointerUp = (event: React.PointerEvent<HTMLElement>) => { if (!points.current) return; if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } const finished = strokeToPath(points.current, options); points.current = null; setCurrentPath(null); const rect = event.currentTarget.getBoundingClientRect(); const size = { width: Math.round(rect.width), height: Math.round(rect.height) }; setBox(size); const nextPaths = finished ? [...paths, finished] : paths; setPaths(nextPaths); onDrawEnd?.({ paths: nextPaths, dataUrl: toSvgDataUrl(nextPaths, size.width, size.height) }); };
const clear = useCallback(() => { points.current = null; setCurrentPath(null); setPaths([]); onDrawEnd?.({ paths: [], dataUrl: "" }); }, [onDrawEnd]);
const ctx: SignaturePadContextValue = { ids: { label: `${id}-label`, control: `${id}-control` }, paths, currentPath, drawing: currentPath !== null, empty: paths.length === 0, disabled, interactive, required, name, dataUrl: toSvgDataUrl(paths, box.width || 400, box.height || 160), clear, pointerDown, pointerMove, pointerUp, };
return ( <PadContext.Provider value={ctx}> <StyledRoot data-disabled={disabled ? "" : undefined} {...rest} /> </PadContext.Provider> );}Root.displayName = "SignaturePadRoot";
const StyledLabel = withContext("span", "label", "SignaturePadLabel");
/** Names the control (via aria-labelledby); clicking it focuses the pad. */function Label(props: React.ComponentProps<typeof StyledLabel>) { const ctx = usePad(); return ( <StyledLabel id={ctx.ids.label} data-disabled={ctx.disabled ? "" : undefined} onClick={() => document.getElementById(ctx.ids.control)?.focus()} {...props} /> );}Label.displayName = "SignaturePadLabel";
const StyledControl = withContext("div", "control", "SignaturePadControl");
/** The drawing surface (focusable; Tab reaches the clear button inside). */function Control(props: React.ComponentProps<typeof StyledControl>) { const ctx = usePad(); return ( <StyledControl id={ctx.ids.control} role="application" aria-roledescription="signature pad" aria-labelledby={ctx.ids.label} aria-disabled={ctx.disabled || undefined} tabIndex={ctx.disabled ? undefined : 0} data-disabled={ctx.disabled ? "" : undefined} data-drawing={ctx.drawing ? "" : undefined} onPointerDown={ctx.pointerDown} onPointerMove={ctx.pointerMove} onPointerUp={ctx.pointerUp} onPointerCancel={ctx.pointerUp} {...props} /> );}Control.displayName = "SignaturePadControl";
const StyledSegment = withContext("svg", "segment", "SignaturePadSegment");
/** The ink: one filled path per stroke, plus the stroke in progress. */function Segment(props: React.ComponentProps<typeof StyledSegment>) { const ctx = usePad(); const { children, ...rest } = props; return ( <StyledSegment aria-hidden="true" {...rest}> {/* UI SDK part children may be a state function; the ink paths follow. */} {children as React.ReactNode} {ctx.paths.map((d, i) => ( <path key={i} d={d} /> ))} {ctx.currentPath && <path d={ctx.currentPath} />} </StyledSegment> );}Segment.displayName = "SignaturePadSegment";
const StyledGuide = withContext("div", "guide", "SignaturePadGuide");
function Guide(props: React.ComponentProps<typeof StyledGuide>) { const ctx = usePad(); return ( <StyledGuide aria-hidden="true" data-disabled={ctx.disabled ? "" : undefined} {...props} /> );}Guide.displayName = "SignaturePadGuide";
const StyledClearTrigger = withContext( "button", (v) => [chrome.btnReset, ...resolveSlotStyles(signaturePadRecipe.slots.clearTrigger, v)], "SignaturePadClearTrigger",);
/** Clears the pad; hidden while empty or mid-stroke. Default reset icon. */function ClearTrigger(props: React.ComponentProps<typeof StyledClearTrigger>) { const ctx = usePad(); const { children, onClick, ...rest } = props; return ( <StyledClearTrigger type="button" data-part="clear-trigger" aria-label="Clear signature" hidden={ctx.empty || ctx.drawing} disabled={ctx.disabled} onClick={(event: React.MouseEvent<HTMLButtonElement>) => { onClick?.(event); ctx.clear(); document.getElementById(ctx.ids.control)?.focus(); }} {...rest} > {children ?? <ClearIcon />} </StyledClearTrigger> );}ClearTrigger.displayName = "SignaturePadClearTrigger";
/** * HiddenInput — carries the signature into form submissions: an SVG data * URL of the strokes unless `value` is given. */function HiddenInput(props: Omit<React.ComponentProps<"input">, "style"> & StyleOverrideProps) { const ctx = usePad(); const { value, palette: _palette, style: _style, ...rest } = props; return ( <input type="text" hidden readOnly name={ctx.name} required={ctx.required} disabled={ctx.disabled} value={value ?? ctx.dataUrl} {...rest} /> );}HiddenInput.displayName = "SignaturePadHiddenInput";
export interface SignaturePadContextApi { paths: string[]; empty: boolean; drawing: boolean; dataUrl: string; clear: () => void;}
/** Read the pad state the way Ark exposes its machine context. */function Context({ children }: { children: (api: SignaturePadContextApi) => React.ReactNode }) { const { paths, empty, drawing, dataUrl, clear } = usePad(); return children({ paths, empty, drawing, dataUrl, clear });}
export const SignaturePad = { Root, Label, Control, Segment, Guide, ClearTrigger, HiddenInput, Context,};