{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"lathe-turned-metal-dial-switch-with-detents-and-light-that-stays-put","type":"registry:component","title":"Lathe-Turned Metal Dial Switch with Detents and Light That Stays Put","description":"Rotary switch on a canvas: a turned aluminium dial with a knurled grip clicks between stops while the reflections hold still. Free React and HTML to copy.","dependencies":[],"files":[{"path":"components/we-inc/lathe-turned-metal-dial-switch-with-detents-and-light-that-stays-put.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent } from \"react\";\n\n// The positions, left to right. Add or remove entries and the stops space themselves out.\nconst modes = [\n  { label: \"Off\", note: \"Fan stopped\" },\n  { label: \"Auto\", note: \"Follows the room temperature\" },\n  { label: \"Boost\", note: \"Full speed for twenty minutes\" },\n];\nconst SWEEP = 104; // degrees between the first stop and the last\nconst LAMP = \"#ff9d2e\"; // the paint in the pointer notch and the lit lamp\nconst SIZE = 320; // canvas edge in CSS pixels\n\nconst stopAngle = (i: number) => ((modes.length === 1 ? 0 : i / (modes.length - 1) - 0.5) * SWEEP * Math.PI) / 180;\n\nexport default function LatheTurnedMetalDial() {\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const hit = useRef<HTMLDivElement>(null);\n  const radios = useRef<(HTMLButtonElement | null)[]>([]);\n  const [mode, setMode] = useState(1);\n  const modeRef = useRef(1);\n  const api = useRef<{ go: (i: number, fromUser: boolean) => void } | null>(null);\n\n  useEffect(() => {\n    const cv = canvas.current, pad = hit.current;\n    if (!cv || !pad) return;\n    const ctx = cv.getContext(\"2d\");\n    if (!ctx) return;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const dpr = Math.min(2, window.devicePixelRatio || 1) * 1.25; // the dial is shown a quarter larger on wide screens\n    cv.width = SIZE * dpr; cv.height = SIZE * dpr;\n    const C = SIZE / 2, FACE = 78, GRIP = 97, PLATE = 146;\n    const hasConic = typeof ctx.createConicGradient === \"function\";\n\n    // The lathe marks: hundreds of faint circles, drawn once and reused every frame.\n    const rings = document.createElement(\"canvas\");\n    rings.width = cv.width; rings.height = cv.height;\n    const rx = rings.getContext(\"2d\");\n    if (rx) {\n      rx.scale(dpr, dpr);\n      let seed = 7;\n      const rand = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };\n      for (let r = 1.5; r < FACE; r += 0.55) {\n        const v = rand();\n        rx.beginPath(); rx.arc(C, C, r, 0, Math.PI * 2);\n        rx.lineWidth = 0.5 + rand() * 0.4;\n        rx.strokeStyle = v > 0.5 ? `rgba(255,255,255,${(v - 0.5) * 0.3})` : `rgba(0,0,0,${(0.5 - v) * 0.26})`;\n        rx.stroke();\n      }\n    }\n\n    const s = { a: stopAngle(1), v: 0, target: stopAngle(1), raw: stopAngle(1), drag: false, light: -2.2, lightTo: -2.2, lamp: modes.map((_, i) => (i === 1 ? 1 : 0)) };\n    // Metal is never pure grey: the dark bands lean blue and the bright ones lean warm.\n    const grey = (v: number) => { const c = Math.max(0, Math.min(255, v)); const k = (150 - c) * 0.09; return `rgb(${Math.max(0, Math.min(255, c - k)) | 0},${c | 0},${Math.max(0, Math.min(255, c + k * 1.6)) | 0})`; };\n\n    // Bright and dark bands that meet at the centre, the way turned metal catches a lamp.\n    const sheen = (angle: number, lo: number, hi: number) => {\n      if (!hasConic) { const g = ctx.createLinearGradient(C - FACE, C - FACE, C + FACE, C + FACE); g.addColorStop(0, grey(hi)); g.addColorStop(0.5, grey(lo)); g.addColorStop(1, grey(hi)); return g; }\n      const g = ctx.createConicGradient(angle, C, C);\n      const mid = (lo + hi) / 2;\n      const stops: [number, number][] = [[0, hi], [0.03, hi - 4], [0.085, mid + 10], [0.16, lo + 4], [0.23, lo - 14], [0.31, mid - 22], [0.4, mid + 6], [0.455, hi - 40], [0.5, hi - 16], [0.54, hi - 44], [0.6, mid - 6], [0.69, lo - 8], [0.76, lo + 10], [0.84, mid - 16], [0.92, mid + 30], [0.97, hi - 6], [1, hi]];\n      for (const [p, v] of stops) g.addColorStop(p, grey(v));\n      return g;\n    };\n\n    const draw = () => {\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.clearRect(0, 0, SIZE, SIZE);\n      const la = s.light + s.a * 0.18;\n\n      // The anodised plate the dial sits in.\n      const plate = ctx.createRadialGradient(C, C - 30, 20, C, C, PLATE);\n      plate.addColorStop(0, \"#26282c\"); plate.addColorStop(0.7, \"#1a1c1f\"); plate.addColorStop(1, \"#141518\");\n      ctx.beginPath(); ctx.arc(C, C, PLATE, 0, Math.PI * 2); ctx.fillStyle = plate; ctx.fill();\n      const lip = ctx.createLinearGradient(0, C - PLATE, 0, C + PLATE);\n      lip.addColorStop(0, \"rgba(255,255,255,0.34)\"); lip.addColorStop(0.45, \"rgba(255,255,255,0.03)\"); lip.addColorStop(1, \"rgba(0,0,0,0.6)\");\n      ctx.lineWidth = 1.5; ctx.strokeStyle = lip; ctx.beginPath(); ctx.arc(C, C, PLATE - 0.75, 0, Math.PI * 2); ctx.stroke();\n\n      // Engraved scale and the three lamps.\n      const half = (SWEEP / 2 + 12) * (Math.PI / 180);\n      for (let k = -29; k <= 29; k++) {\n        const ang = (k * 4 * Math.PI) / 180;\n        if (Math.abs(ang) > half) continue;\n        const sin = Math.sin(ang), cos = -Math.cos(ang);\n        const long = modes.some((_, i) => Math.abs(stopAngle(i) - ang) < 0.02);\n        ctx.beginPath(); ctx.moveTo(C + sin * 108, C + cos * 108); ctx.lineTo(C + sin * (long ? 121 : 114), C + cos * (long ? 121 : 114));\n        ctx.lineWidth = long ? 1.6 : 1; ctx.strokeStyle = long ? \"rgba(236,238,240,0.9)\" : \"rgba(236,238,240,0.32)\"; ctx.stroke();\n      }\n      modes.forEach((_, i) => {\n        const ang = stopAngle(i), x = C + Math.sin(ang) * 133, y = C - Math.cos(ang) * 133, on = s.lamp[i];\n        ctx.beginPath(); ctx.arc(x, y, 4.2, 0, Math.PI * 2); ctx.fillStyle = \"#08090a\"; ctx.fill();\n        ctx.save();\n        ctx.shadowColor = LAMP; ctx.shadowBlur = 16 * on; ctx.globalAlpha = 0.16 + 0.84 * on;\n        ctx.beginPath(); ctx.arc(x, y, 2.9, 0, Math.PI * 2); ctx.fillStyle = LAMP; ctx.fill();\n        ctx.restore();\n        ctx.beginPath(); ctx.arc(x - 0.9, y - 1, 0.9, 0, Math.PI * 2); ctx.fillStyle = `rgba(255,255,255,${0.15 + 0.55 * on})`; ctx.fill();\n      });\n\n      // A small engraved legend under the dial.\n      ctx.save(); ctx.font = \"600 8.5px ui-monospace, SFMono-Regular, Menlo, monospace\"; ctx.textAlign = \"center\"; ctx.textBaseline = \"middle\";\n      const legend = \"AIR  /  3 STOP\";\n      ctx.fillStyle = \"rgba(0,0,0,0.7)\"; ctx.fillText(legend, C, C + 125.8);\n      ctx.fillStyle = \"rgba(236,238,240,0.42)\"; ctx.fillText(legend, C, C + 125);\n      ctx.restore();\n\n      // Shadow of the dial on the plate: one wide and soft, one tight where it meets the surface.\n      ctx.save(); ctx.shadowColor = \"rgba(0,0,0,0.75)\"; ctx.shadowBlur = 30; ctx.shadowOffsetY = 20 * dpr;\n      ctx.beginPath(); ctx.arc(C, C, GRIP - 4, 0, Math.PI * 2); ctx.fillStyle = \"#000\"; ctx.fill(); ctx.restore();\n      ctx.save(); ctx.shadowColor = \"rgba(0,0,0,0.9)\"; ctx.shadowBlur = 6; ctx.shadowOffsetY = 4 * dpr;\n      ctx.beginPath(); ctx.arc(C, C, GRIP - 1, 0, Math.PI * 2); ctx.fillStyle = \"#000\"; ctx.fill(); ctx.restore();\n\n      // Knurled grip: each tooth turns with the dial but takes its brightness from where the light is.\n      const teeth = 112, step = (Math.PI * 2) / teeth;\n      ctx.beginPath(); ctx.arc(C, C, GRIP, 0, Math.PI * 2); ctx.fillStyle = \"#2c2e31\"; ctx.fill();\n      for (let i = 0; i < teeth; i++) {\n        const t0 = s.a + i * step;\n        const face = Math.cos(t0 - la), lit = 0.5 + 0.5 * face, glint = Math.pow(Math.max(0, face), 6) + 0.5 * Math.pow(Math.max(0, -face), 8);\n        for (let h = 0; h < 2; h++) {\n          const a0 = t0 + h * step * 0.5 - Math.PI / 2, a1 = a0 + step * 0.5 + 0.004;\n          const v = h === 0 ? 84 + lit * 78 + glint * 92 : 30 + lit * 40 + glint * 40;\n          ctx.beginPath(); ctx.arc(C, C, GRIP, a0, a1); ctx.arc(C, C, FACE + 3, a1, a0, true); ctx.closePath();\n          ctx.fillStyle = grey(v); ctx.fill();\n        }\n      }\n      const round = ctx.createRadialGradient(C, C, FACE + 3, C, C, GRIP);\n      round.addColorStop(0, \"rgba(0,0,0,0.5)\"); round.addColorStop(0.3, \"rgba(0,0,0,0)\"); round.addColorStop(0.72, \"rgba(0,0,0,0)\"); round.addColorStop(1, \"rgba(0,0,0,0.62)\");\n      ctx.beginPath(); ctx.arc(C, C, GRIP, 0, Math.PI * 2); ctx.arc(C, C, FACE + 3, 0, Math.PI * 2, true); ctx.fillStyle = round; ctx.fill(\"evenodd\");\n\n      // Polished chamfer between grip and face.\n      ctx.beginPath(); ctx.arc(C, C, FACE + 3.5, 0, Math.PI * 2); ctx.fillStyle = sheen(la + 0.5, 70, 255); ctx.fill();\n      ctx.lineWidth = 0.8; ctx.strokeStyle = \"rgba(0,0,0,0.55)\"; ctx.stroke();\n\n      // The face: sheen, lathe rings, one machined step and a shallow dish.\n      ctx.beginPath(); ctx.arc(C, C, FACE, 0, Math.PI * 2); ctx.fillStyle = sheen(la, 96, 252); ctx.fill();\n      ctx.save(); ctx.beginPath(); ctx.arc(C, C, FACE, 0, Math.PI * 2); ctx.clip();\n      ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(rings, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      const dish = ctx.createRadialGradient(C, C + 14, 6, C, C, FACE);\n      dish.addColorStop(0, \"rgba(255,255,255,0.16)\"); dish.addColorStop(0.55, \"rgba(255,255,255,0)\"); dish.addColorStop(1, \"rgba(0,0,0,0.2)\");\n      ctx.fillStyle = dish; ctx.fillRect(C - FACE, C - FACE, FACE * 2, FACE * 2);\n      ctx.restore();\n      ctx.lineWidth = 1.2; ctx.strokeStyle = \"rgba(0,0,0,0.36)\"; ctx.beginPath(); ctx.arc(C, C, FACE * 0.7, 0, Math.PI * 2); ctx.stroke();\n      ctx.lineWidth = 0.8; ctx.strokeStyle = \"rgba(255,255,255,0.6)\"; ctx.beginPath(); ctx.arc(C, C, FACE * 0.7 + 1.1, 0, Math.PI * 2); ctx.stroke();\n\n      // The pointer notch, milled into the face and filled with paint.\n      ctx.save(); ctx.translate(C, C); ctx.rotate(s.a);\n      ctx.lineCap = \"round\";\n      ctx.lineWidth = 6.4; ctx.strokeStyle = \"rgba(0,0,0,0.5)\"; ctx.beginPath(); ctx.moveTo(0, -FACE + 9); ctx.lineTo(0, -FACE * 0.7 - 7); ctx.stroke();\n      ctx.lineWidth = 4.2; ctx.strokeStyle = LAMP; ctx.beginPath(); ctx.moveTo(0, -FACE + 9.6); ctx.lineTo(0, -FACE * 0.7 - 6.6); ctx.stroke();\n      ctx.lineWidth = 1; ctx.strokeStyle = \"rgba(255,255,255,0.45)\"; ctx.beginPath(); ctx.moveTo(1.1, -FACE + 10); ctx.lineTo(1.1, -FACE * 0.7 - 7); ctx.stroke();\n      ctx.restore();\n    };\n\n    let raf = 0, last = 0, seen = true, touched = -1e9, nextDemo = 1100, t0 = 0, moved = 0, lastAngle = 0;\n    const first = stopAngle(0), end = stopAngle(modes.length - 1);\n    const gap = modes.length > 1 ? SWEEP / (modes.length - 1) * (Math.PI / 180) : 1;\n    const nearest = (a: number) => { let best = 0; modes.forEach((_, i) => { if (Math.abs(stopAngle(i) - a) < Math.abs(stopAngle(best) - a)) best = i; }); return best; };\n    const select = (i: number) => { if (modeRef.current !== i) { modeRef.current = i; setMode(i); } };\n\n    const frame = (now: number) => {\n      raf = 0;\n      if (!t0) { t0 = now; last = now; }\n      const dt = Math.min(0.033, (now - last) / 1000); last = now;\n      const t = now - t0;\n      if (s.drag) {\n        // While held, the dial resists leaving a stop and falls into the next one.\n        const n = nearest(s.raw), off = s.raw - stopAngle(n);\n        const sticky = stopAngle(n) + off - (Math.sin((off / gap) * Math.PI * 2) * gap) / (Math.PI * 2) * 0.82;\n        s.v = (sticky - s.a) / Math.max(dt, 0.001) * 0.35; s.a += (sticky - s.a) * Math.min(1, dt * 30);\n        select(n);\n      } else {\n        s.v += (520 * (s.target - s.a) - 19 * s.v) * dt; s.a += s.v * dt;\n      }\n      if (now - touched > 5000) {\n        s.lightTo = -2.2 + 0.35 * Math.sin(t / 2100);\n        if (t > nextDemo && !s.drag) { const n = (modeRef.current + 1) % modes.length; s.target = stopAngle(n); select(n); nextDemo = t + 1500; }\n      }\n      s.light += (s.lightTo - s.light) * Math.min(1, dt * 6);\n      s.lamp = s.lamp.map((v, i) => v + ((i === modeRef.current ? 1 : 0) - v) * Math.min(1, dt * (i === modeRef.current ? 14 : 7)));\n      draw();\n      if (seen && !document.hidden) raf = requestAnimationFrame(frame);\n    };\n    const wake = () => { if (!raf && !reduce) { last = performance.now(); raf = requestAnimationFrame(frame); } };\n    const settle = () => { s.a = s.target; s.v = 0; s.lamp = modes.map((_, i) => (i === modeRef.current ? 1 : 0)); draw(); };\n\n    api.current = {\n      go: (i, fromUser) => { if (fromUser) touched = performance.now(); s.target = stopAngle(i); select(i); if (reduce) settle(); else wake(); },\n    };\n    if (reduce) settle(); else wake();\n\n    const angleAt = (e: PointerEvent) => { const b = pad.getBoundingClientRect(); return Math.atan2(e.clientX - (b.left + b.width / 2), -(e.clientY - (b.top + b.height / 2))); };\n    const onDown = (e: PointerEvent) => {\n      touched = performance.now(); s.drag = true; s.raw = s.a; moved = 0; lastAngle = angleAt(e);\n      pad.setPointerCapture(e.pointerId); e.preventDefault(); wake();\n    };\n    const onMove = (e: PointerEvent) => {\n      const b = pad.getBoundingClientRect();\n      if (!s.drag) { touched = Math.max(touched, performance.now() - 3800); s.lightTo = Math.atan2(e.clientY - (b.top + b.height / 2) - 40, e.clientX - (b.left + b.width / 2)); if (reduce) { s.light = s.lightTo; draw(); } return; }\n      touched = performance.now();\n      const a = angleAt(e); let d = a - lastAngle; if (d > Math.PI) d -= Math.PI * 2; if (d < -Math.PI) d += Math.PI * 2;\n      lastAngle = a; moved += Math.abs(d);\n      // Past the last stop the dial keeps going a little, with rising resistance.\n      const over = s.raw + d > end ? s.raw + d - end : s.raw + d < first ? first - (s.raw + d) : 0;\n      s.raw += over > 0 ? d * Math.max(0.08, 0.5 - over * 2.4) : d;\n      if (reduce) { const n = nearest(s.raw); select(n); s.target = stopAngle(n); settle(); }\n    };\n    const onUp = () => {\n      if (!s.drag) return;\n      s.drag = false; touched = performance.now();\n      const n = moved < 0.04 ? (modeRef.current + 1) % modes.length : nearest(s.raw); // a plain tap steps to the next stop\n      s.target = stopAngle(n); select(n);\n      if (reduce) settle();\n    };\n    pad.addEventListener(\"pointerdown\", onDown);\n    pad.addEventListener(\"pointermove\", onMove);\n    pad.addEventListener(\"pointerup\", onUp);\n    pad.addEventListener(\"pointercancel\", onUp);\n    const io = new IntersectionObserver(([entry]) => { seen = entry.isIntersecting; if (seen) wake(); });\n    io.observe(cv);\n    const onVis = () => { if (!document.hidden) wake(); };\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => {\n      cancelAnimationFrame(raf); api.current = null;\n      pad.removeEventListener(\"pointerdown\", onDown); pad.removeEventListener(\"pointermove\", onMove);\n      pad.removeEventListener(\"pointerup\", onUp); pad.removeEventListener(\"pointercancel\", onUp);\n      io.disconnect(); document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, []);\n\n  const choose = (i: number) => { modeRef.current = i; setMode(i); api.current?.go(i, true); };\n  const onKey = (e: ReactKeyboardEvent, i: number) => {\n    const next = e.key === \"ArrowRight\" || e.key === \"ArrowDown\" ? Math.min(modes.length - 1, i + 1) : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? Math.max(0, i - 1) : e.key === \"Home\" ? 0 : e.key === \"End\" ? modes.length - 1 : -1;\n    if (next < 0) return;\n    e.preventDefault(); choose(next); radios.current[next]?.focus();\n  };\n\n  return (\n    <div className=\"flex min-h-[640px] w-full sm:min-h-[720px] flex-col items-center justify-center bg-[#0b0c0e] bg-[radial-gradient(120%_80%_at_50%_30%,#1b1d21_0%,#0b0c0e_62%)] px-4 py-12\">\n      <div className=\"relative h-[320px] w-[320px] sm:my-12 sm:scale-125\">\n        <canvas ref={canvas} aria-hidden=\"true\" className=\"absolute inset-0 h-full w-full\" />\n        <div ref={hit} aria-hidden=\"true\" className=\"absolute left-1/2 top-1/2 h-[198px] w-[198px] -translate-x-1/2 -translate-y-1/2 cursor-grab touch-none rounded-full active:cursor-grabbing\" />\n        <div role=\"radiogroup\" aria-label=\"Fan mode\" className=\"absolute inset-0 pointer-events-none\">\n          {modes.map((m, i) => {\n            const a = stopAngle(i), x = 160 + Math.sin(a) * 160, y = 160 - Math.cos(a) * 164;\n            return (\n              <button\n                key={m.label}\n                ref={(el) => { radios.current[i] = el; }}\n                type=\"button\"\n                role=\"radio\"\n                aria-checked={mode === i}\n                tabIndex={mode === i ? 0 : -1}\n                onClick={() => choose(i)}\n                onKeyDown={(e) => onKey(e, i)}\n                style={{ left: x, top: y, transform: `translate(${-50 + Math.sin(a) * 52}%, -50%)` }}\n                className={`pointer-events-auto absolute flex h-10 min-w-[56px] items-center justify-center rounded-full px-2 font-mono text-[11px] font-semibold uppercase tracking-[0.2em] outline-none transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-[#ff9d2e] motion-reduce:transition-none ${mode === i ? \"text-white\" : \"text-zinc-400 hover:text-zinc-200\"}`}\n              >\n                {m.label}\n              </button>\n            );\n          })}\n        </div>\n      </div>\n      <p aria-live=\"polite\" className=\"mt-9 min-h-[20px] max-w-[320px] text-center font-mono text-[11px] uppercase leading-5 tracking-[0.16em] text-zinc-400\">\n        <span className=\"text-zinc-200\">{modes[mode].label}</span>\n        <span className=\"mx-2 text-zinc-600\">/</span>\n        {modes[mode].note}\n      </p>\n    </div>\n  );\n}\n"}]}
