{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"glass-key","type":"registry:component","title":"Glass Key","description":"A clear glass keycap in real 3D, with liquid light flowing inside it and a printed label on top. It turns gently towards your cursor, like a product shot you can play with.","dependencies":["three"],"devDependencies":["@types/three"],"files":[{"path":"registry/dot/glass-key.tsx","type":"registry:component","target":"components/dot/glass-key.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, type CSSProperties } from \"react\";\nimport * as THREE from \"three\";\nimport { RoundedBoxGeometry } from \"three/examples/jsm/geometries/RoundedBoxGeometry.js\";\nimport { RoomEnvironment } from \"three/examples/jsm/environments/RoomEnvironment.js\";\n\nexport interface GlassKeyProps {\n  /** Text printed on the top of the key */\n  label?: string;\n  labelColor?: string;\n  /** Three colours for the moving light inside: base, glow and highlight */\n  colors?: [string, string, string];\n  /** Speed of the movement inside the key */\n  speed?: number;\n  /** Brightness of the inner light (0–2) */\n  intensity?: number;\n  /** Tint of the glass; white is clear */\n  glassColor?: string;\n  /** Frosting of the glass (0–1); 0 is perfectly clear */\n  roughness?: number;\n  /** How far the key turns towards the pointer, in degrees */\n  tilt?: number;\n  /** Resting turn of the key, in degrees */\n  rotation?: number;\n  /** Resting lean towards the viewer, in degrees */\n  lean?: number;\n  /** Share of the shorter side the key fills (0.2–0.9) */\n  size?: number;\n  /** Follow the pointer */\n  interactive?: boolean;\n  /** Describes the key for screen readers */\n  ariaLabel?: string;\n  className?: string;\n  style?: CSSProperties;\n}\n\nconst KEY = { width: 1, height: 0.6, radius: 0.1, top: 0.74 };\nconst DEG = Math.PI / 180;\n\n/** A keycap: a rounded box narrowed towards the top, with normals tipped to match the slope */\nfunction keycapGeometry(width: number, height: number, radius: number, top: number) {\n  const geometry = new RoundedBoxGeometry(width, height, width, 6, radius);\n  const position = geometry.attributes.position;\n  const normal = geometry.attributes.normal;\n  const slope = ((1 - top) * width) / 2 / height;\n  const n = new THREE.Vector3();\n  for (let i = 0; i < position.count; i++) {\n    const t = (position.getY(i) + height / 2) / height;\n    const scale = 1 - (1 - top) * t;\n    position.setX(i, position.getX(i) * scale);\n    position.setZ(i, position.getZ(i) * scale);\n    n.fromBufferAttribute(normal, i);\n    n.y += slope * Math.hypot(n.x, n.z);\n    n.normalize();\n    normal.setXYZ(i, n.x, n.y, n.z);\n  }\n  position.needsUpdate = true;\n  normal.needsUpdate = true;\n  geometry.computeBoundingSphere();\n  return geometry;\n}\n\nconst VERTEX = /* glsl */ `\n  varying vec3 vPos;\n  void main() {\n    vPos = position;\n    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n  }\n`;\n\n// Domain-warped value noise: slow, liquid light drifting through the core\nconst FRAGMENT = /* glsl */ `\n  uniform float uTime;\n  uniform float uIntensity;\n  uniform vec3 uA;\n  uniform vec3 uB;\n  uniform vec3 uC;\n  varying vec3 vPos;\n\n  float hash(vec3 p) {\n    p = fract(p * 0.3183099 + 0.1);\n    p *= 17.0;\n    return fract(p.x * p.y * p.z * (p.x + p.y + p.z));\n  }\n  float noise(vec3 x) {\n    vec3 i = floor(x);\n    vec3 f = fract(x);\n    f = f * f * (3.0 - 2.0 * f);\n    return mix(\n      mix(mix(hash(i), hash(i + vec3(1, 0, 0)), f.x), mix(hash(i + vec3(0, 1, 0)), hash(i + vec3(1, 1, 0)), f.x), f.y),\n      mix(mix(hash(i + vec3(0, 0, 1)), hash(i + vec3(1, 0, 1)), f.x), mix(hash(i + vec3(0, 1, 1)), hash(i + vec3(1, 1, 1)), f.x), f.y),\n      f.z\n    );\n  }\n  float fbm(vec3 p) {\n    float v = 0.0;\n    float a = 0.5;\n    for (int i = 0; i < 4; i++) {\n      v += a * noise(p);\n      p *= 2.02;\n      a *= 0.5;\n    }\n    return v;\n  }\n\n  void main() {\n    vec3 p = vPos * 2.6;\n    float t = uTime * 0.25;\n    vec3 q = vec3(fbm(p + vec3(0.0, t, 0.0)), fbm(p + vec3(5.2, -t, 1.3)), fbm(p + vec3(1.7, 9.2, t)));\n    float n = fbm(p + 2.6 * q + vec3(t * 0.6));\n    // Mostly dark, with thin threads of light and a soft glow drifting through\n    float band = pow(0.5 + 0.5 * sin(n * 12.0 - uTime * 1.2), 8.0);\n    float glow = smoothstep(0.45, 0.85, n);\n    vec3 light = mix(uB, uC, smoothstep(0.35, 0.75, q.x));\n    vec3 col = uA + light * (band * 0.9 + glow * 0.22) * uIntensity;\n    gl_FragColor = vec4(col, 1.0);\n    #include <colorspace_fragment>\n  }\n`;\n\nfunction drawLabel(canvas: HTMLCanvasElement, label: string, color: string) {\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return;\n  ctx.clearRect(0, 0, canvas.width, canvas.height);\n  if (!label) return;\n  ctx.fillStyle = color;\n  ctx.textBaseline = \"alphabetic\";\n  const size = Math.min(92, (canvas.width * 0.62) / Math.max(1, label.length * 0.55));\n  ctx.font = `500 ${size}px Inter, \"Helvetica Neue\", Arial, sans-serif`;\n  ctx.fillText(label, canvas.width * 0.12, canvas.height * 0.86);\n}\n\n/**\n * A glass keycap rendered in 3D with Three.js: clear glass with soft reflections and a printed\n * label, and a shader light flowing inside it. It turns gently towards the pointer. Fills its\n * parent, has a transparent background, pauses offscreen and holds still with reduced motion.\n */\nexport function GlassKey({\n  label = \"dot\",\n  labelColor = \"#FFFFFF\",\n  colors = [\"#030304\", \"#3A3A40\", \"#FFFFFF\"],\n  speed = 1,\n  intensity = 0.4,\n  glassColor = \"#FFFFFF\",\n  roughness = 0,\n  tilt = 18,\n  rotation = -32,\n  lean = 32,\n  size = 0.4,\n  interactive = true,\n  ariaLabel,\n  className,\n  style,\n}: GlassKeyProps) {\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const live = useRef({ colors, speed, intensity, glassColor, roughness, tilt, rotation, lean, size, interactive });\n  const relabel = useRef<(text: string, color: string) => void>(() => {});\n  const refit = useRef<() => void>(() => {});\n\n  useEffect(() => {\n    live.current = { colors, speed, intensity, glassColor, roughness, tilt, rotation, lean, size, interactive };\n    refit.current();\n  });\n\n  useEffect(() => {\n    relabel.current(label, labelColor);\n  }, [label, labelColor]);\n\n  useEffect(() => {\n    const container = containerRef.current;\n    if (!container) return;\n\n    let renderer: THREE.WebGLRenderer;\n    try {\n      renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: \"high-performance\" });\n    } catch {\n      return; // No WebGL: leave the space empty rather than break the page\n    }\n    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));\n    renderer.setClearColor(0x000000, 0);\n    renderer.toneMapping = THREE.ACESFilmicToneMapping;\n    renderer.toneMappingExposure = 1.05;\n    const canvas = renderer.domElement;\n    canvas.style.cssText = \"display:block;width:100%;height:100%\";\n    container.appendChild(canvas);\n\n    const scene = new THREE.Scene();\n    const pmrem = new THREE.PMREMGenerator(renderer);\n    const room = new RoomEnvironment();\n    const environment = pmrem.fromScene(room, 0.04).texture;\n    scene.environment = environment;\n    scene.environmentIntensity = 0.85;\n\n    const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 50);\n    const key = new THREE.Group();\n    scene.add(key);\n\n    // Glass shell\n    const shellGeometry = keycapGeometry(KEY.width, KEY.height, KEY.radius, KEY.top);\n    const glass = new THREE.MeshPhysicalMaterial({\n      color: new THREE.Color(live.current.glassColor),\n      metalness: 0,\n      roughness: live.current.roughness,\n      transmission: 1,\n      thickness: 0.9,\n      ior: 1.45,\n      clearcoat: 1,\n      clearcoatRoughness: 0.04,\n      attenuationColor: new THREE.Color(live.current.glassColor),\n      attenuationDistance: 2.4,\n      specularIntensity: 1,\n    });\n    const shell = new THREE.Mesh(shellGeometry, glass);\n    key.add(shell);\n\n    // Light core inside, seen through the glass\n    const coreGeometry = keycapGeometry(KEY.width * 0.58, KEY.height * 0.46, KEY.radius * 0.5, KEY.top);\n    const uniforms = {\n      uTime: { value: 0 },\n      uIntensity: { value: live.current.intensity },\n      uA: { value: new THREE.Color() },\n      uB: { value: new THREE.Color() },\n      uC: { value: new THREE.Color() },\n    };\n    const coreMaterial = new THREE.ShaderMaterial({ vertexShader: VERTEX, fragmentShader: FRAGMENT, uniforms });\n    const core = new THREE.Mesh(coreGeometry, coreMaterial);\n    core.position.y = -KEY.height * 0.08;\n    key.add(core);\n\n    // Printed label on the top face\n    const labelCanvas = document.createElement(\"canvas\");\n    labelCanvas.width = labelCanvas.height = 512;\n    const labelTexture = new THREE.CanvasTexture(labelCanvas);\n    labelTexture.colorSpace = THREE.SRGBColorSpace;\n    labelTexture.anisotropy = renderer.capabilities.getMaxAnisotropy();\n    const labelMaterial = new THREE.MeshBasicMaterial({ map: labelTexture, transparent: true, depthWrite: false, toneMapped: false });\n    const topWidth = KEY.width * KEY.top - KEY.radius * 2;\n    const labelPlane = new THREE.Mesh(new THREE.PlaneGeometry(topWidth, topWidth), labelMaterial);\n    labelPlane.rotation.x = -Math.PI / 2;\n    labelPlane.position.y = KEY.height / 2 + 0.002;\n    key.add(labelPlane);\n    relabel.current = (text, color) => {\n      drawLabel(labelCanvas, text, color);\n      labelTexture.needsUpdate = true;\n      wake();\n    };\n\n    // A cool rim light for the bright edge highlights\n    const rim = new THREE.DirectionalLight(0xffffff, 1.6);\n    rim.position.set(-2, 3, 2.5);\n    scene.add(rim);\n\n    const reduceMotion = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    let width = 0;\n    let height = 0;\n    let frame = 0;\n    let running = false;\n    let visible = true;\n    let last = 0;\n    let time = 3;\n    const pointer = { x: 0, y: 0 };\n    const turn = { x: 0, y: 0 };\n\n    function fit() {\n      width = container!.clientWidth;\n      height = container!.clientHeight;\n      if (!width || !height) return;\n      renderer.setSize(width, height, false);\n      camera.aspect = width / height;\n      const fill = Math.min(0.9, Math.max(0.2, live.current.size));\n      const halfFov = (camera.fov / 2) * DEG;\n      const reach = 0.72; // the key's radius as it turns\n      camera.position.set(0, 0, reach / (fill * Math.tan(halfFov) * Math.min(1, camera.aspect)));\n      camera.lookAt(0, 0, 0);\n      camera.updateProjectionMatrix();\n    }\n\n    function render(now: number) {\n      const dt = last ? Math.min((now - last) / 1000, 0.05) : 1 / 60;\n      last = now;\n      const s = live.current;\n      if (!reduceMotion.matches) time += dt * s.speed;\n      uniforms.uTime.value = time;\n      uniforms.uIntensity.value = s.intensity;\n      uniforms.uA.value.set(s.colors[0]);\n      uniforms.uB.value.set(s.colors[1]);\n      uniforms.uC.value.set(s.colors[2]);\n      glass.color.set(s.glassColor);\n      glass.attenuationColor.set(s.glassColor);\n      glass.roughness = s.roughness;\n\n      const follow = 1 - Math.exp(-dt * 6);\n      const target = s.interactive ? pointer : { x: 0, y: 0 };\n      turn.x += (target.x - turn.x) * follow;\n      turn.y += (target.y - turn.y) * follow;\n      key.rotation.set(s.lean * DEG - turn.y * s.tilt * DEG, s.rotation * DEG + turn.x * s.tilt * DEG, 0, \"XYZ\");\n      renderer.render(scene, camera);\n\n      const settling = Math.abs(target.x - turn.x) + Math.abs(target.y - turn.y) > 0.0005;\n      if (visible && (settling || !reduceMotion.matches)) frame = requestAnimationFrame(render);\n      else {\n        running = false;\n        last = 0;\n      }\n    }\n\n    function wake() {\n      if (running || !visible || !width) {\n        if (!running && width) renderer.render(scene, camera);\n        return;\n      }\n      running = true;\n      frame = requestAnimationFrame(render);\n    }\n    refit.current = () => {\n      fit();\n      wake();\n    };\n\n    const onMove = (e: PointerEvent) => {\n      const rect = container.getBoundingClientRect();\n      pointer.x = Math.max(-1, Math.min(1, ((e.clientX - rect.left) / rect.width) * 2 - 1));\n      pointer.y = Math.max(-1, Math.min(1, ((e.clientY - rect.top) / rect.height) * 2 - 1));\n      wake();\n    };\n    const onLeave = () => {\n      pointer.x = 0;\n      pointer.y = 0;\n      wake();\n    };\n\n    const resize = new ResizeObserver(() => {\n      fit();\n      wake();\n    });\n    resize.observe(container);\n    const visibility = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      wake();\n    });\n    visibility.observe(container);\n    container.addEventListener(\"pointermove\", onMove, { passive: true });\n    container.addEventListener(\"pointerleave\", onLeave, { passive: true });\n    reduceMotion.addEventListener(\"change\", wake);\n    fit();\n    drawLabel(labelCanvas, label, labelColor);\n    labelTexture.needsUpdate = true;\n    wake();\n\n    return () => {\n      cancelAnimationFrame(frame);\n      relabel.current = () => {};\n      refit.current = () => {};\n      resize.disconnect();\n      visibility.disconnect();\n      container.removeEventListener(\"pointermove\", onMove);\n      container.removeEventListener(\"pointerleave\", onLeave);\n      reduceMotion.removeEventListener(\"change\", wake);\n      shellGeometry.dispose();\n      coreGeometry.dispose();\n      labelPlane.geometry.dispose();\n      glass.dispose();\n      coreMaterial.dispose();\n      labelMaterial.dispose();\n      labelTexture.dispose();\n      environment.dispose();\n      room.dispose();\n      pmrem.dispose();\n      renderer.dispose();\n      canvas.remove();\n    };\n    // Built once; every prop is read live from refs\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return (\n    <div\n      ref={containerRef}\n      role=\"img\"\n      aria-label={ariaLabel ?? `Glass ${label} key`}\n      className={className}\n      style={{ position: \"relative\", width: \"100%\", height: \"100%\", touchAction: \"pan-y\", ...style }}\n    />\n  );\n}\n"}],"docs":"Glass Key is ready. Props and a live canvas: https://bydot.co/component/glass-key","meta":{"tier":"free","category":"3D & Effects","version":"1.0.0"}}