avatar picker.json

{ "name": "avatar-picker", "type": "registry:component", "dependencies": [ "lucide-react", "motion" ], "files": [ { "type": "registry:component", "content": "// biome-ignore-all lint/suspicious/noBitwiseOperators: the seed hash and PRNG are bitwise by design.\n"use client";\n\n/**\n * @author: @dorianbaffier\n * @description: Avatar Picker\n * @version: 2.0.0\n * @date: 2026-10-14\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n /\n\nimport { ArrowRight, Dices } from "lucide-react";\nimport {\n type AnimationPlaybackControls,\n animate,\n LayoutGroup,\n MotionConfig,\n type MotionValue,\n motion,\n useMotionValue,\n useMotionValueEvent,\n useReducedMotion,\n useSpring,\n useTransform,\n} from "motion/react";\nimport {\n type KeyboardEvent,\n type PointerEvent,\n type RefObject,\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n} from "react";\nimport { cn } from "@/lib/utils";\n\n/ ----------------------------------------------------------------------------\n * Face generation\n \n * Every avatar is a pure function of a seed string. The seed is hashed into a\n * PRNG, which picks continuous feature values (head proportions, hair, eyes,\n * brows, mouth) and a few colors from small muted palettes. Because features\n * are numbers rather than parts picked from a list, two faces can be blended,\n * which is what makes the live morph possible.\n * ------------------------------------------------------------------------- /\n\ntype RGB = readonly [number, number, number];\n\nconst BACKGROUNDS: readonly { name: string; rgb: RGB }[] = [\n { name: "gray", rgb: [228, 228, 231] },\n { name: "sand", rgb: [233, 226, 214] },\n { name: "sage", rgb: [217, 225, 213] },\n { name: "slate", rgb: [218, 225, 233] },\n { name: "clay", rgb: [235, 221, 214] },\n { name: "mist", rgb: [226, 223, 233] },\n];\nconst SKINS: readonly RGB[] = [\n [246, 233, 222],\n [236, 210, 187],\n [214, 176, 142],\n [176, 128, 96],\n [128, 88, 66],\n];\nconst HAIRS: readonly RGB[] = [\n [39, 39, 42],\n [63, 45, 36],\n [113, 84, 62],\n [161, 161, 170],\n [82, 82, 91],\n];\nconst SHIRTS: readonly RGB[] = [\n [39, 39, 42],\n [82, 82, 91],\n [113, 113, 122],\n [244, 244, 245],\n];\nconst INK = "#18181b";\n\nconst SHAPE_KEYS = [\n "headW",\n "headH",\n "headSquare",\n "chin",\n "hairVolume",\n "hairFringe",\n "hairPart",\n "hairLength",\n "eyeGap",\n "eyeY",\n "eyeRx",\n "eyeRy",\n "browTilt",\n "browLift",\n "browWeight",\n "mouthW",\n "mouthCurve",\n "mouthOpen",\n "nose",\n "glasses",\n "cheeks",\n "shoulders",\n] as const;\n\ntype ShapeKey = (typeof SHAPE_KEYS)[number];\n\nexport interface Face {\n shape: Record;\n bg: RGB;\n skin: RGB;\n hair: RGB;\n shirt: RGB;\n / Plain-language summary, used for screen-reader labels. */\n description: string;\n}\n\nfunction hashString(input: string) {\n let h = 2_166_136_261;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 16_777_619);\n }\n return h >>> 0;\n}\n\nfunction mulberry32(seed: number) {\n let a = seed;\n return () => {\n a = (a + 0x6d_2b_79_f5) | 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);\n return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;\n };\n}\n\nconst round2 = (v: number) => Math.round(v * 100) / 100;\n\nfunction pick(list: readonly T[], r: number): T {\n return list[Math.min(list.length - 1, Math.floor(r * list.length))] as T;\n}\n\nfunction describe(shape: Face["shape"], bgName: string) {\n let hair = "short hair";\n if (shape.hairLength > 0.62) {\n hair = "long hair";\n } else if (shape.hairVolume < 0.22) {\n hair = "cropped hair";\n }\n let mouth = "a slight smile";\n if (shape.mouthOpen > 0.5) {\n mouth = "an open smile";\n } else if (shape.mouthCurve > 3.2) {\n mouth = "a wide smile";\n } else if (shape.mouthCurve < 1) {\n mouth = "a calm expression";\n }\n const face = shape.headSquare > 0.55 ? "Square face" : "Round face";\n const glasses = shape.glasses > 0.5 ? ", glasses" : "";\n return `${face}, ${hair}${glasses}, ${mouth}, on ${bgName}`; }

/** Deterministic face for a seed. Same seed, same face, server and client. / export function createFace(seed: string): Face { const r = mulberry32(hashString(seed)); const bg = pick(BACKGROUNDS, r()); const shape: Face["shape"] = { headW: 18 + r() * 5, headH: 22 + r() * 4, headSquare: r(), chin: 0.75 + r() * 0.25, hairVolume: r(), hairFringe: r(), hairPart: r() * 2 - 1, hairLength: r() ** 1.6, eyeGap: 7.5 + r() * 3, eyeY: -2 + r() * 4, eyeRx: 1.7 + r() * 0.9, eyeRy: 1.9 + r() * 1.4, browTilt: -2 + r() * 4, browLift: 4.2 + r() * 2, browWeight: r() < 0.65 ? 1.3 + r() * 0.8 : 0, mouthW: 3.5 + r() * 3, mouthCurve: r() * 4.5, mouthOpen: r() < 0.3 ? 0.6 + r() * 0.4 : 0, nose: r(), glasses: r() < 0.25 ? 1 : 0, cheeks: r(), shoulders: r(), };\n for (const key of SHAPE_KEYS) {\n shape[key] = round2(shape[key]);\n }\n return {\n shape,\n bg: bg.rgb,\n skin: pick(SKINS, r()),\n hair: pick(HAIRS, r()),\n shirt: pick(SHIRTS, r()),\n description: describe(shape, bg.name),\n };\n}\n\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\nfunction lerpRgb(a: RGB, b: RGB, t: number): RGB {\n const c = (i: 0 | 1 | 2) =>\n Math.max(0, Math.min(255, Math.round(lerp(a[i], b[i], t))));\n return [c(0), c(1), c(2)];\n}\n\nfunction lerpFace(a: Face, b: Face, t: number): Face {\n const shape = { ...b.shape };\n for (const key of SHAPE_KEYS) {\n shape[key] = lerp(a.shape[key], b.shape[key], t);\n }\n // Colors stop at the target; only shapes may overshoot with the spring.\n const ct = Math.min(1, t);\n return {\n shape,\n bg: lerpRgb(a.bg, b.bg, ct),\n skin: lerpRgb(a.skin, b.skin, ct),\n hair: lerpRgb(a.hair, b.hair, ct),\n shirt: lerpRgb(a.shirt, b.shirt, ct),\n description: b.description,\n };\n}\n\nconst rgb = (c: RGB, k = 1) =>\n rgb(${Math.round(c[0] * k)} ${Math.round(c[1] * k)} ${Math.round(c[2] * k)});\n\nconst n = round2;\n\n/* Rounded blob: square blends between an ellipse and a squircle. /\nfunction blobPath(\n cx: number,\n cy: number,\n w: number,\n top: number,\n bottom: number,\n square: number,\n chin = 1\n) {\n const k = 0.552 + square * 0.28;\n const kb = k * chin;\n return [\n M${n(cx)} ${n(cy - top)},\n C${n(cx + k * w)} ${n(cy - top)} ${n(cx + w)} ${n(cy - k * top)} ${n(cx + w)} ${n(cy)},\n C${n(cx + w)} ${n(cy + kb * bottom)} ${n(cx + kb * w)} ${n(cy + bottom)} ${n(cx)} ${n(cy + bottom)},\n C${n(cx - kb * w)} ${n(cy + bottom)} ${n(cx - w)} ${n(cy + kb * bottom)} ${n(cx - w)} ${n(cy)},\n C${n(cx - w)} ${n(cy - k * top)} ${n(cx - k * w)} ${n(cy - top)} ${n(cx)} ${n(cy - top)}Z,\n ].join("");\n}\n\nfunction hairFrontPath(s: Face["shape"], cx: number, cy: number) {\n const w = s.headW;\n const h = s.headH;\n const v = s.hairVolume;\n const temple = cy - h * 0.12;\n const crown = cy - h - 1.5 - v * 4;\n const side = w + 1.5 + v * 2.5;\n const k = 0.552 + s.headSquare * 0.28;\n const fringeY = cy - h * (0.66 - s.hairFringe * 0.36);\n const partX = cx + s.hairPart * w * 0.55;\n return [\n M${n(cx - side)} ${n(temple)},\n C${n(cx - side)} ${n(cy - h * k - v * 3)} ${n(cx - k * side)} ${n(crown)} ${n(cx)} ${n(crown)},\n C${n(cx + k * side)} ${n(crown)} ${n(cx + side)} ${n(cy - h * k - v * 3)} ${n(cx + side)} ${n(temple)},\n L${n(cx + w - 1)} ${n(temple)},\n Q${n(cx + w * 0.75)} ${n(fringeY + 1 - s.hairPart * 5)} ${n(partX)} ${n(fringeY - 2.5)},\n Q${n(cx - w * 0.75)} ${n(fringeY + 1 + s.hairPart * 5)} ${n(cx - w + 1)} ${n(temple)}Z,\n ].join("");\n}\n\nfunction mouthPath(s: Face["shape"], cx: number, y: number) {\n const curve = s.mouthCurve * 2;\n const open = s.mouthOpen * 5;\n return [\n M${n(cx - s.mouthW)} ${n(y)},\n Q${n(cx)} ${n(y + curve)} ${n(cx + s.mouthW)} ${n(y)},\n Q${n(cx)} ${n(y + curve + open)} ${n(cx - s.mouthW)} ${n(y)}Z,\n ].join("");\n}\n\ninterface FaceArtProps {\n face: Face;\n /* Pointer-follow offset for the eyes, in face units. /\n look?: { x: MotionValue; y: MotionValue };\n blinkRef?: RefObject;\n className?: string;\n}\n\n/* The face itself: one SVG, 100×100 units, every number rounded. /\nfunction FaceArt({ face, look, blinkRef, className }: FaceArtProps) {\n const s = face.shape;\n const cx = 50;\n const cy = 50;\n const eyeY = cy + s.eyeY;\n const mouthY = cy + s.headH * 0.5;\n const glassR = Math.max(s.eyeRx, s.eyeRy) + 3.2;\n const neckTop = cy + s.headH - 6;\n const shoulderTop = cy + s.headH + 3;\n const sw = 30 + s.shoulders * 8;\n\n return (\n \n \n {/ Long hair sits behind the head. /}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n}\n\nconst MORPH = { type: "spring", bounce: 0.22, visualDuration: 0.42 } as const;\n\n/**\n * Renders the face for seed and, when the seed changes, eases every feature\n * from where it is now to the new values instead of crossfading.\n /\nfunction MorphingFace({\n seed,\n morph = true,\n ...rest\n}: Omit & { seed: string; morph?: boolean }) {\n const [face, setFace] = useState(() => createFace(seed));\n const shownRef = useRef(face);\n // The seed whose face is fully on screen, or null mid-morph. Lets the\n // effect skip a no-op morph on mount and after every spin lands, each of\n // which would otherwise re-render the face every frame for nothing.\n const settledRef = useRef(seed);\n const reduceMotion = useReducedMotion();\n\n useEffect(() => {\n if (settledRef.current === seed) {\n return;\n }\n const target = createFace(seed);\n if (!morph || reduceMotion) {\n shownRef.current = target;\n settledRef.current = seed;\n setFace(target);\n return;\n }\n const from = shownRef.current;\n settledRef.current = null;\n const controls = animate(0, 1, {\n ...MORPH,\n onUpdate: (t) => {\n const next = lerpFace(from, target, t);\n shownRef.current = next;\n setFace(next);\n },\n onComplete: () => {\n settledRef.current = seed;\n },\n });\n return () => controls.stop();\n }, [seed, morph, reduceMotion]);\n\n return ;\n}\n\n/ ----------------------------------------------------------------------------\n * Picker\n * ------------------------------------------------------------------------- /\n\nexport interface AvatarValue {\n / The name the faces are generated from. /\n displayName: string;\n /* Which face for that name. Any integer works; each one is a new face. /\n variant: number;\n}\n\nexport interface AvatarPickerProps {\n /* Controlled value. /\n value?: AvatarValue;\n /* Initial value when uncontrolled. /\n defaultValue?: Partial;\n /* Called when the name changes or a face lands. /\n onChange?: (\n value: AvatarValue & { seed: string; description: string }\n ) => void;\n /* Called by the submit button. /\n onComplete?: (value: AvatarValue & { seed: string }) => void;\n /* Form field name; a hidden input carries the avatar seed. /\n name?: string;\n title?: string;\n description?: string;\n submitLabel?: string;\n className?: string;\n}\n\nconst SLOT_COUNT = 5;\nconst COIN = 128;\nconst BEZEL = 176;\nconst TICKS = 60;\n// One face per half turn. Dragging the coin its own width turns it half a turn.\nconst DEG_PER_PX = 180 / COIN;\nconst MAX_FLICK_STEPS = 10;\nconst TAP_SLOP = 4;\nconst DRAG_SPRING = { type: "spring", stiffness: 140, damping: 22 } as const;\nconst SHUFFLE_SPRING = { type: "spring", stiffness: 50, damping: 11 } as const;\nconst FLY = { type: "spring", bounce: 0.18, visualDuration: 0.45 } as const;\nconst MIN_NAME = 2;\n\n/* The seed string for a name and variant; feed it to createFace. /\nexport function avatarSeed(displayName: string, variant: number) {\n return `${displayName.trim().toLowerCase()}:${variant}`;\n}\n\nconst pad3 = (v: number) => String(((v % 1000) + 1000) % 1000).padStart(3, "0");\n\n// Bezel tick marks, rounded so server and client markup match.\nconst TICK_LINES = Array.from({ length: TICKS }, (_, i) => {\n const a = (i / TICKS) * Math.PI * 2;\n const long = i % 5 === 0;\n const r1 = BEZEL / 2 - 3;\n const r0 = r1 - (long ? 7 : 4);\n const c = BEZEL / 2;\n return {\n key: i,\n long,\n x1: round2(c + Math.sin(a) * r0),\n y1: round2(c - Math.cos(a) * r0),\n x2: round2(c + Math.sin(a) * r1),\n y2: round2(c - Math.cos(a) * r1),\n };\n});\n\nfunction useInView(ref: RefObject) {\n const [active, setActive] = useState(false);\n useEffect(() => {\n const el = ref.current;\n if (!el) {\n return;\n }\n let onScreen = false;\n const update = () => setActive(onScreen && !document.hidden);\n const io = new IntersectionObserver(([entry]) => {\n onScreen = Boolean(entry?.isIntersecting);\n update();\n });\n io.observe(el);\n document.addEventListener("visibilitychange", update);\n return () => {\n io.disconnect();\n document.removeEventListener("visibilitychange", update);\n };\n }, [ref]);\n return active;\n}\n\n/* Eyes drift toward the pointer and blink now and then, only while visible. /\nfunction useLivingEyes(\n coinRef: RefObject,\n active: boolean\n) {\n const reduceMotion = useReducedMotion();\n const x = useSpring(0, { stiffness: 180, damping: 18 });\n const y = useSpring(0, { stiffness: 180, damping: 18 });\n const blinkRef = useRef(null);\n\n useEffect(() => {\n if (!active || reduceMotion) {\n return;\n }\n const onMove = (e: globalThis.PointerEvent) => {\n const el = coinRef.current;\n if (!el) {\n return;\n }\n const box = el.getBoundingClientRect();\n const dx = e.clientX - (box.left + box.width / 2);\n const dy = e.clientY - (box.top + box.height / 2);\n const dist = Math.hypot(dx, dy) || 1;\n const reach = Math.min(1, dist / 220);\n x.set((dx / dist) * reach * 1.8);\n y.set((dy / dist) * reach * 1.3);\n };\n let timer = 0;\n let open = 0;\n const blink = () => {\n const g = blinkRef.current;\n if (g) {\n g.style.transform = "scaleY(0.1)";\n open = window.setTimeout(() => {\n g.style.transform = "";\n }, 120);\n }\n timer = window.setTimeout(blink, 2600 + Math.random() * 3400);\n };\n timer = window.setTimeout(blink, 1800);\n window.addEventListener("pointermove", onMove, { passive: true });\n return () => {\n window.clearTimeout(timer);\n window.clearTimeout(open);\n if (blinkRef.current) {\n blinkRef.current.style.transform = "";\n }\n window.removeEventListener("pointermove", onMove);\n };\n }, [active, reduceMotion, coinRef, x, y]);\n\n return { look: { x, y }, blinkRef };\n}\n\ninterface CoinProps {\n layoutId: string;\n seed: string;\n angle: MotionValue;\n spinning: boolean;\n label: string;\n look: { x: MotionValue; y: MotionValue };\n blinkRef: RefObject;\n coinRef: RefObject;\n onPointerDown: (e: PointerEvent) => void;\n onPointerMove: (e: PointerEvent) => void;\n onPointerUp: (e: PointerEvent) => void;\n onPointerCancel: (e: PointerEvent) => void;\n}\n\n/**\n * The preview is a coin with real thickness: a stack of discs in 3D. It turns\n * around its vertical axis and swaps faces as it passes edge-on, so a spin\n * reads like a slot reel without any crossfade.\n /\nfunction Coin({\n layoutId,\n seed,\n angle,\n spinning,\n label,\n look,\n blinkRef,\n coinRef,\n ...handlers\n}: CoinProps) {\n // Fold the running angle into -90..90 so the front always faces us.\n const tilt = useTransform(angle, (a) => a - 180 * Math.round(a / 180));\n const transform = useTransform(tilt, (t) => rotateY(${round2(t)}deg));\n const shade = useTransform(tilt, (t) => round2((Math.abs(t) / 90) * 0.35));\n\n return (\n \n \n {[6, 5, 4, 3, 2, 1].map((z) => (\n \n ))}\n \n \n \n \n \n );\n}\n\nfunction useSpinner(onLand: (steps: number) => void) {\n const angle = useMotionValue(0);\n const [step, setStep] = useState(0);\n const [spinning, setSpinning] = useState(false);\n const controls = useRef(null);\n const stepRef = useRef(0);\n const onLandRef = useRef(onLand);\n onLandRef.current = onLand;\n\n useMotionValueEvent(angle, "change", (a) => {\n const s = Math.round(a / 180);\n if (s !== stepRef.current) {\n stepRef.current = s;\n setStep(s);\n }\n });\n\n const land = useCallback(() => {\n controls.current = null;\n const s = Math.round(angle.get() / 180);\n angle.jump(0);\n stepRef.current = 0;\n setStep(0);\n setSpinning(false);\n if (s !== 0) {\n onLandRef.current(s);\n }\n }, [angle]);\n\n const stop = useCallback(() => {\n controls.current?.stop();\n controls.current = null;\n }, []);\n\n const spinTo = useCallback(\n (\n steps: number,\n transition: { stiffness: number; damping: number; velocity: number }\n ) => {\n stop();\n setSpinning(true);\n controls.current = animate(angle, steps * 180, {\n type: "spring",\n ...transition,\n restDelta: 0.5,\n restSpeed: 4,\n onComplete: land,\n });\n },\n [angle, land, stop]\n );\n\n const jumpBy = useCallback(\n (steps: number) => {\n stop();\n angle.jump(steps * 180);\n land();\n },\n [angle, land, stop]\n );\n\n return { angle, step, spinning, setSpinning, spinTo, jumpBy, stop, land };\n}\n\ntype Spinner = ReturnType;\n\ninterface DragState {\n id: number;\n x: number;\n start: number;\n moved: boolean;\n samples: { x: number; t: number }[];\n}\n\nfunction releaseTarget(d: DragState, current: number, x: number, t: number) {\n const first = d.samples[0] ?? { x, t };\n const dt = Math.max(16, t - first.t) / 1000;\n const velocity = ((x - first.x) / dt) * DEG_PER_PX;\n const start = Math.round(d.start / 180);\n const projected = Math.round((current + velocity * 0.28) / 180);\n const target = Math.max(\n start - MAX_FLICK_STEPS,\n Math.min(start + MAX_FLICK_STEPS, projected)\n );\n return { target, velocity };\n}\n\n/ Drag the coin sideways to turn it; let go and it coasts with momentum. */\nfunction useDragSpin(spinner: Spinner, reduceMotion: boolean | null) {\n const drag = useRef(null);\n\n const onPointerDown = (e: PointerEvent) => {\n if (e.button !== 0) {\n return;\n }\n spinner.stop();\n spinner.setSpinning(true);\n e.currentTarget.setPointerCapture(e.pointerId);\n drag.current = {\n id: e.pointerId,\n x: e.clientX,\n start: spinner.angle.get(),\n moved: false,\n samples: [{ x: e.clientX, t: e.timeStamp }],\n };\n };\n\n const onPointerMove = (e: PointerEvent) => {\n const d = drag.current;\n if (!d || d.id !== e.pointerId) {\n return;\n }\n const dx = e.clientX - d.x;\n if (Math.abs(dx) > TAP_SLOP) {\n d.moved = true;\n }\n spinner.angle.set(d.start + dx * DEG_PER_PX);\n d.samples.push({ x: e.clientX, t: e.timeStamp });\n if (d.samples.length > 6) {\n d.samples.shift();\n }\n };\n\n const onPointerUp = (e: PointerEvent) => {\n const d = drag.current;\n if (!d || d.id !== e.pointerId) {\n return;\n }\n drag.current = null;\n const current = spinner.angle.get();\n // A tap turns to the next face; a drag coasts on its release speed.\n const { target, velocity } = d.moved\n ? releaseTarget(d, current, e.clientX, e.timeStamp)\n : { target: Math.round(current / 180) + 1, velocity: 900 };\n if (reduceMotion) {\n spinner.jumpBy(target);\n } else {\n spinner.spinTo(target, { ...DRAG_SPRING, velocity });\n }\n };\n\n // The browser took the gesture (a vertical scroll that started on the\n // coin): settle on the nearest face instead of treating it as a tap.\n const onPointerCancel = (e: PointerEvent) => {\n const d = drag.current;\n if (!d || d.id !== e.pointerId) {\n return;\n }\n drag.current = null;\n const target = Math.round(spinner.angle.get() / 180);\n if (reduceMotion) {\n spinner.jumpBy(target);\n } else {\n spinner.spinTo(target, { ...DRAG_SPRING, velocity: 0 });\n }\n };\n\n return { onPointerDown, onPointerMove, onPointerUp, onPointerCancel };\n}\n\n/**\n * Onboarding avatar picker. Faces are generated from the display name, morph\n * live as it is typed, and can be spun like a coin: drag or flick it sideways,\n * tap it, or press shuffle. Five slots keep options to compare; picking one\n * flies it into the preview and sends the previous face back to its slot.\n /\nexport default function AvatarPicker({\n value,\n defaultValue,\n onChange,\n onComplete,\n name,\n title = "Pick your avatar",\n description = "Made from your name. Spin it or pick one.",\n submitLabel = "Continue",\n className,\n}: AvatarPickerProps) {\n const uid = useId();\n const reduceMotion = useReducedMotion();\n const startVariant = defaultValue?.variant ?? 0;\n const [internalName, setInternalName] = useState(\n defaultValue?.displayName ?? "Robin Vale"\n );\n const [slots, setSlots] = useState(() =>\n Array.from({ length: SLOT_COUNT }, (_, i) => startVariant + i * 7)\n );\n const [selected, setSelected] = useState(0);\n const [focusIndex, setFocusIndex] = useState(0);\n const [announcement, setAnnouncement] = useState("");\n const rootRef = useRef(null);\n const coinRef = useRef(null);\n const slotRefs = useRef<(HTMLButtonElement | null)[]>([]);\n\n const displayName = value?.displayName ?? internalName;\n const variant = value?.variant ?? slots[selected] ?? 0;\n const latest = useRef({ displayName, variant, selected });\n latest.current = { displayName, variant, selected };\n\n // Keep the selected slot in step with a controlled variant.\n const controlledVariant = value?.variant;\n useEffect(() => {\n if (controlledVariant === undefined) {\n return;\n }\n setSlots((prev) =>\n prev[selected] === controlledVariant\n ? prev\n : prev.map((v, i) => (i === selected ? controlledVariant : v))\n );\n }, [controlledVariant, selected]);\n\n const emit = (next: AvatarValue, announce: boolean) => {\n const seed = avatarSeed(next.displayName, next.variant);\n const face = createFace(seed);\n onChange?.({ ...next, seed, description: face.description });\n if (announce) {\n setAnnouncement(Avatar: ${face.description});\n }\n };\n\n const spinner = useSpinner((steps) => {\n const {\n displayName: current,\n variant: from,\n selected: slot,\n } = latest.current;\n const next = from + steps;\n setSlots((prev) => prev.map((v, i) => (i === slot ? next : v)));\n emit({ displayName: current, variant: next }, true);\n });\n const dragHandlers = useDragSpin(spinner, reduceMotion);\n const active = useInView(rootRef);\n const { look, blinkRef } = useLivingEyes(coinRef, active);\n\n const shownVariant = variant + spinner.step;\n const seed = avatarSeed(displayName, shownVariant);\n\n const shuffle = () => {\n const current = Math.round(spinner.angle.get() / 180);\n const steps = 5 + Math.floor(Math.random() * 4);\n if (reduceMotion) {\n spinner.jumpBy(current + steps);\n return;\n }\n spinner.spinTo(current + steps, {\n ...SHUFFLE_SPRING,\n velocity: steps * 180 * 1.6,\n });\n };\n\n const choose = (index: number) => {\n if (index === selected) {\n return;\n }\n if (spinner.spinning) {\n spinner.stop();\n spinner.land();\n }\n setSelected(index);\n setFocusIndex(index);\n emit(\n { displayName: latest.current.displayName, variant: slots[index] ?? 0 },\n true\n );\n };\n\n const onSlotKeyDown = (e: KeyboardEvent) => {\n const moves: Record = {\n ArrowRight: focusIndex + 1,\n ArrowDown: focusIndex + 1,\n ArrowLeft: focusIndex - 1,\n ArrowUp: focusIndex - 1,\n Home: 0,\n End: SLOT_COUNT - 1,\n };\n const target = moves[e.key];\n if (target === undefined) {\n return;\n }\n e.preventDefault();\n const next = (target + SLOT_COUNT) % SLOT_COUNT;\n setFocusIndex(next);\n slotRefs.current[next]?.focus();\n };\n\n const setName = (next: string) => {\n if (value === undefined) {\n setInternalName(next);\n }\n emit({ displayName: next, variant }, false);\n };\n\n const nameOk = displayName.trim().length >= MIN_NAME;\n const bezelRotate = useTransform(\n spinner.angle,\n (a) => `rotate(${round2(a / 15)}deg)`\n );\n const diceRotate = useTransform(\n spinner.angle,\n (a) => `rotate(${round2(a / 4)}deg)`\n );\n\n return (\n \n \n \n {title}\n \n {description}\n \n \n \n \n \n \n \n {TICK_LINES.map((t) => (\n \n ))}\n \n {/ Fixed index mark the bezel turns under. /}\n \n \n \n \n {displayName.trim() || "Anonymous"}\n \n \n No. {pad3(shownVariant)}\n \n \n \n\n \n \n \n {slots.map((slotVariant, i) => {\n const isSelected = i === selected;\n const slotSeed = avatarSeed(displayName, slotVariant);\n return (\n choose(i)}\n onFocus={() => setFocusIndex(i)}\n onKeyDown={onSlotKeyDown}\n ref={(el) => {\n slotRefs.current[i] = el;\n }}\n tabIndex={i === focusIndex ? 0 : -1}\n type="button"\n >\n {/ The socket stays put; the face flies in and out of it. */}\n \n {isSelected ? (\n \n ) : (\n \n \n \n )}\n \n );\n })}\n \n\n \n \n \n \n \n \n \n\n \n \n Display name\n \n setName(e.target.value)}\n placeholder="Your name"\n spellCheck={false}\n type="text"\n value={displayName}\n />\n \n\n {name ? (\n \n ) : null}\n\n \n onComplete?.({\n displayName: displayName.trim(),\n variant,\n seed: avatarSeed(displayName, variant),\n })\n }\n type="button"\n >\n {submitLabel}\n \n \n\n \n {announcement}\n \n \n \n );\n}" , "path": "/components/kokonutui/avatar-picker.tsx", "target": "components/kokonutui/avatar-picker.tsx" } ] }