{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"badge-strap","type":"registry:ui","title":"Badge Strap","description":"An ID badge hanging from a woven strap with verlet rope physics. Grab it, fling it and watch it swing back.","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"registry/ui/badge-strap.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface BadgeStrapProps {\n  /** Name printed on the badge. */\n  name?: string;\n  /** Role printed under the name. */\n  role?: string;\n  /** Photo URL for the badge. */\n  image?: string;\n  /** Replace the default badge face entirely. */\n  children?: ReactNode;\n  /** Strap color. */\n  strapColor?: string;\n  /** Strap length in px. */\n  ropeLength?: number;\n  /** Badge width in px (height follows a 1:1.45 ratio). */\n  badgeWidth?: number;\n  /** Gravity multiplier. */\n  gravity?: number;\n  className?: string;\n}\n\ntype P = { x: number; y: number; px: number; py: number };\n\nconst SEGMENTS = 14;\nconst ITERATIONS = 14;\n\nexport function BadgeStrap({\n  name = \"Ada Park\",\n  role = \"Design Engineer\",\n  image,\n  children,\n  strapColor = \"#c6f24e\",\n  ropeLength = 170,\n  badgeWidth = 180,\n  gravity = 1,\n  className,\n}: BadgeStrapProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const badgeRef = useRef<HTMLButtonElement>(null);\n  const cfg = useRef({ strapColor, gravity });\n  useEffect(() => {\n    cfg.current = { strapColor, gravity };\n  }, [strapColor, gravity]);\n\n  const badgeHeight = badgeWidth * 1.45;\n\n  useEffect(() => {\n    const root = rootRef.current!;\n    const canvas = canvasRef.current!;\n    const badge = badgeRef.current!;\n    const ctx = canvas.getContext(\"2d\")!;\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const seg = ropeLength / SEGMENTS;\n    let w = root.clientWidth;\n    let h = root.clientHeight;\n    const anchor = () => ({ x: w / 2, y: -8 });\n\n    // Rope nodes; the last node is the badge clip. `tail` is the badge bottom.\n    const a0 = anchor();\n    // Start tilted to one side so it swings in on mount.\n    const phi = reduced ? 0 : 0.75;\n    const [sx, sy] = [Math.sin(phi), Math.cos(phi)];\n    const pts: P[] = Array.from({ length: SEGMENTS + 1 }, (_, i) => {\n      const x = a0.x + sx * seg * i;\n      const y = a0.y + sy * seg * i;\n      return { x, y, px: x, py: y };\n    });\n    const clip = pts[SEGMENTS];\n    const tx = clip.x + sx * badgeHeight;\n    const ty = clip.y + sy * badgeHeight;\n    const tail: P = { x: tx, y: ty, px: tx, py: ty };\n    let grab: { f: number; x: number; y: number } | null = null;\n    let raf = 0;\n    let visible = true;\n    let last = performance.now();\n    let acc = 0;\n\n    const dist = (a: P, b: P, len: number, wa: number, wb: number) => {\n      const dx = b.x - a.x;\n      const dy = b.y - a.y;\n      const d = Math.hypot(dx, dy) || 1e-6;\n      const diff = (d - len) / d / (wa + wb);\n      a.x += dx * diff * wa;\n      a.y += dy * diff * wa;\n      b.x -= dx * diff * wb;\n      b.y -= dy * diff * wb;\n    };\n\n    const step = (dt: number) => {\n      const g = 2200 * cfg.current.gravity * dt * dt;\n      for (const p of [...pts, tail]) {\n        const vx = (p.x - p.px) * 0.985;\n        const vy = (p.y - p.py) * 0.985;\n        p.px = p.x;\n        p.py = p.y;\n        p.x += vx;\n        p.y += vy + g;\n      }\n      const a = anchor();\n      for (let k = 0; k < ITERATIONS; k++) {\n        pts[0].x = a.x;\n        pts[0].y = a.y;\n        for (let i = 0; i < SEGMENTS; i++) dist(pts[i], pts[i + 1], seg, i === 0 ? 0 : 1, i + 1 === SEGMENTS ? 0.35 : 1);\n        dist(clip, tail, badgeHeight, 1, 1);\n        if (grab) {\n          // Move the grabbed point on the badge to the pointer, split between both ends.\n          const f = grab.f;\n          const cx = grab.x - (clip.x + (tail.x - clip.x) * f);\n          const cy = grab.y - (clip.y + (tail.y - clip.y) * f);\n          const s = (1 - f) * (1 - f) + f * f;\n          clip.x += (cx * (1 - f)) / s;\n          clip.y += (cy * (1 - f)) / s;\n          tail.x += (cx * f) / s;\n          tail.y += (cy * f) / s;\n        }\n      }\n      pts[0].x = a.x;\n      pts[0].y = a.y;\n    };\n\n    const draw = () => {\n      ctx.clearRect(0, 0, w, h);\n      const trace = () => {\n        ctx.beginPath();\n        ctx.moveTo(pts[0].x, pts[0].y);\n        for (let i = 1; i < SEGMENTS; i++) {\n          const mx = (pts[i].x + pts[i + 1].x) / 2;\n          const my = (pts[i].y + pts[i + 1].y) / 2;\n          ctx.quadraticCurveTo(pts[i].x, pts[i].y, mx, my);\n        }\n        ctx.lineTo(clip.x, clip.y);\n      };\n      ctx.lineCap = \"round\";\n      ctx.lineJoin = \"round\";\n      ctx.save();\n      ctx.shadowColor = \"rgba(0,0,0,.45)\";\n      ctx.shadowBlur = 14;\n      ctx.shadowOffsetY = 6;\n      trace();\n      ctx.strokeStyle = cfg.current.strapColor;\n      ctx.lineWidth = 14;\n      ctx.stroke();\n      ctx.restore();\n      // Woven look: darker edges and a stitched center line.\n      trace();\n      ctx.strokeStyle = \"rgba(0,0,0,.18)\";\n      ctx.lineWidth = 14;\n      ctx.setLineDash([2, 3]);\n      ctx.stroke();\n      trace();\n      ctx.strokeStyle = cfg.current.strapColor;\n      ctx.lineWidth = 9;\n      ctx.setLineDash([]);\n      ctx.stroke();\n      trace();\n      ctx.strokeStyle = \"rgba(255,255,255,.35)\";\n      ctx.lineWidth = 1.2;\n      ctx.setLineDash([5, 4]);\n      ctx.stroke();\n      ctx.setLineDash([]);\n\n      const ang = Math.atan2(tail.x - clip.x, tail.y - clip.y);\n      const vx = clip.x - clip.px;\n      const flip = Math.max(-35, Math.min(35, vx * 2.2));\n      badge.style.transform = `translate3d(${clip.x - badgeWidth / 2}px, ${clip.y - 10}px, 0) rotate(${-ang}rad) rotateY(${flip}deg)`;\n    };\n\n    const frame = (now: number) => {\n      acc += Math.min(0.05, (now - last) / 1000);\n      last = now;\n      const dt = 1 / 120;\n      while (acc >= dt) {\n        step(dt);\n        acc -= dt;\n      }\n      draw();\n      raf = visible ? requestAnimationFrame(frame) : 0;\n    };\n    const start = () => {\n      if (raf || !visible) return;\n      last = performance.now();\n      raf = requestAnimationFrame(frame);\n    };\n\n    const resize = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      w = root.clientWidth;\n      h = root.clientHeight;\n      canvas.width = w * dpr;\n      canvas.height = h * dpr;\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      draw();\n    };\n\n    const local = (e: PointerEvent) => {\n      const r = root.getBoundingClientRect();\n      return { x: e.clientX - r.left, y: e.clientY - r.top };\n    };\n    const onDown = (e: PointerEvent) => {\n      badge.setPointerCapture(e.pointerId);\n      const p = local(e);\n      // Project the pointer onto the badge axis to find where it was grabbed.\n      const ax = tail.x - clip.x;\n      const ay = tail.y - clip.y;\n      const f = Math.max(0.05, Math.min(0.95, ((p.x - clip.x) * ax + (p.y - clip.y) * ay) / (ax * ax + ay * ay)));\n      grab = { f, ...p };\n    };\n    const onMove = (e: PointerEvent) => {\n      if (grab) Object.assign(grab, local(e));\n    };\n    const onUp = () => {\n      grab = null;\n    };\n    const onKey = (e: KeyboardEvent) => {\n      const push: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1], Enter: [1, -0.4], \" \": [-1, -0.4] };\n      const d = push[e.key];\n      if (!d) return;\n      e.preventDefault();\n      // Nudge by faking velocity: shift the previous positions backwards.\n      for (const p of [tail, clip]) {\n        p.px -= d[0] * 14;\n        p.py -= d[1] * 14;\n      }\n    };\n\n    const ro = new ResizeObserver(resize);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible) start();\n    });\n    ro.observe(root);\n    io.observe(root);\n    badge.addEventListener(\"pointerdown\", onDown);\n    badge.addEventListener(\"pointermove\", onMove);\n    badge.addEventListener(\"pointerup\", onUp);\n    badge.addEventListener(\"pointercancel\", onUp);\n    badge.addEventListener(\"keydown\", onKey);\n    resize();\n    start();\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      badge.removeEventListener(\"pointerdown\", onDown);\n      badge.removeEventListener(\"pointermove\", onMove);\n      badge.removeEventListener(\"pointerup\", onUp);\n      badge.removeEventListener(\"pointercancel\", onUp);\n      badge.removeEventListener(\"keydown\", onKey);\n    };\n  }, [ropeLength, badgeWidth, badgeHeight]);\n\n  return (\n    <div ref={rootRef} className={cn(\"relative h-full w-full overflow-hidden\", className)} style={{ perspective: 900 }}>\n      <canvas ref={canvasRef} aria-hidden className=\"pointer-events-none absolute inset-0 size-full\" />\n      <button\n        ref={badgeRef}\n        type=\"button\"\n        aria-label={`${name}, ${role}. Drag to swing, or press the arrow keys.`}\n        className=\"absolute left-0 top-0 cursor-grab touch-none select-none rounded-2xl text-left outline-none will-change-transform focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-4 focus-visible:ring-offset-background active:cursor-grabbing\"\n        style={{ width: badgeWidth, height: badgeHeight, transformOrigin: \"50% 10px\" }}\n      >\n        {/* metal clip */}\n        <span aria-hidden className=\"absolute -top-3 left-1/2 z-10 h-7 w-6 -translate-x-1/2 rounded-md border-2 border-zinc-300 bg-gradient-to-b from-zinc-200 to-zinc-500 shadow-md\" />\n        <span className=\"flex size-full flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-[0_30px_60px_-15px_rgba(0,0,0,.6)]\">\n          {children ?? (\n            <>\n              <span className=\"relative block h-[22%] shrink-0\" style={{ background: `linear-gradient(135deg, ${strapColor}, color-mix(in oklab, ${strapColor} 55%, black))` }}>\n                <span className=\"absolute left-1/2 top-[18%] h-[14%] w-[22%] -translate-x-1/2 rounded-full bg-card/90\" />\n                <span className=\"absolute bottom-[14%] right-[8%] font-mono text-[0.6rem] font-bold uppercase tracking-[0.25em] text-black/70\">Visitor pass</span>\n              </span>\n              <span className=\"relative -mt-[14%] ml-[10%] block aspect-square w-[46%] shrink-0 overflow-hidden rounded-xl border-4 border-card bg-muted\">\n                {image && (\n                  // eslint-disable-next-line @next/next/no-img-element\n                  <img src={image} alt=\"\" draggable={false} className=\"size-full object-cover\" />\n                )}\n              </span>\n              <span className=\"block px-[10%] pt-3\">\n                <span className=\"block truncate text-lg font-semibold leading-tight text-foreground\">{name}</span>\n                <span className=\"block truncate text-xs text-muted-foreground\">{role}</span>\n              </span>\n              <span aria-hidden className=\"grid grid-cols-2 gap-2 px-[10%] pt-3 font-mono text-[0.55rem] uppercase tracking-wider text-muted-foreground\">\n                <span>\n                  ID<span className=\"block text-[0.7rem] text-foreground\">0427</span>\n                </span>\n                <span>\n                  Access<span className=\"block text-[0.7rem] text-foreground\">All areas</span>\n                </span>\n              </span>\n              <span aria-hidden className=\"mt-auto flex h-[12%] items-end gap-[3px] px-[10%] pb-[9%]\">\n                {Array.from({ length: 22 }, (_, i) => (\n                  <span key={i} className=\"h-full bg-foreground/80\" style={{ width: (i * 7) % 3 === 0 ? 3 : 1 }} />\n                ))}\n              </span>\n            </>\n          )}\n        </span>\n      </button>\n    </div>\n  );\n}\n"}]}