{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"sundial-picker","type":"registry:component","title":"Sundial picker","description":"Pick a time by dragging the sun across the sky.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion","toward the\n"],"registryDependencies":["utils"],"files":[{"path":"components/sundial-picker.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { motion, useSpring, useTransform, type MotionValue } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst VB_W = 460;\nconst VB_H = 320;\n// The sun's path: a half circle standing on the horizon.\nconst ARC = { x: 230, y: 196, r: 170 };\n// The dial plate, a horizontal circle seen at a low angle.\nconst DIAL = { x: 230, y: 262, rx: 150, ry: 40 };\nconst START = 6 * 60;\nconst END = 20 * 60;\n// Solar noon sits halfway along the arc, as it would on a summer day with\n// daylight saving: sunrise 6:00, sunset 20:00.\nconst SOLAR_NOON = (START + END) / 2;\nconst STEP = 15;\n// Latitude of the dial. It bends the hour lines the way a real horizontal\n// sundial's are bent: bunched near noon, spread near dawn and dusk.\nconst SIN_LAT = Math.sin((40 * Math.PI) / 180);\n// Shadow length as a share of the dial radius: never shorter than half so\n// it always reads as a hand, growing with the cotangent of the sun's height\n// until it reaches the rim when the sun is about 30 degrees up.\nconst SHADOW_MIN = 0.5;\nconst SHADOW_GROWTH = 0.3;\n// Stiff and fully damped: the sun clicks into each 15 minute detent\n// without overshooting past the time you chose.\nconst DETENT = { stiffness: 420, damping: 40 };\n\n// Sky, sun and bronze are natural light and material, so they carry their\n// own colours, each with a darker twin for the dark theme via light-dark().\n// The sky at the horizon: peach at dawn and dusk, a pale blue by day.\nconst DUSK_SKY =\n  \"linear-gradient(180deg, light-dark(oklch(0.88 0.04 290), oklch(0.2 0.04 285)), light-dark(oklch(0.9 0.08 55), oklch(0.33 0.08 40)) 61%)\";\nconst DAY_SKY =\n  \"linear-gradient(180deg, light-dark(oklch(0.9 0.045 235), oklch(0.25 0.045 245)), light-dark(oklch(0.97 0.015 220), oklch(0.32 0.03 230)) 61%)\";\nconst SUN_LOW = \"oklch(0.72 0.17 45)\";\nconst SUN_HIGH = \"oklch(0.88 0.15 88)\";\nconst SUN_GLOW = \"oklch(0.9 0.14 80)\";\n// A cast bronze plate: a lit face, a darker rim showing its thickness, and\n// engraving cut darker still.\nconst BRONZE = \"oklch(0.7 0.08 72)\";\nconst BRONZE_EDGE = \"oklch(0.5 0.07 60)\";\nconst ENGRAVE = \"oklch(0.38 0.05 55)\";\n// Ground under the dial, a stone terrace.\nconst GROUND = \"light-dark(oklch(0.9 0.012 80), oklch(0.22 0.01 70))\";\n\nconst clamp = (v: number, lo = 0, hi = 1) => Math.min(Math.max(v, lo), hi);\nconst toT = (minutes: number) => (minutes - START) / (END - START);\n// Trig results can differ in the last digit between server and browser,\n// which breaks hydration, so drawn coordinates are rounded.\nconst r2 = (n: number) => Math.round(n * 100) / 100;\n\n// The pointer is read as an angle around a pivot below the horizon rather\n// than around the arc's own center. Near the horizon that tracks sideways\n// motion, near the top it tracks the curve, and it stays continuous when a\n// drag dips below the horizon or starts on the dial.\nconst PIVOT = { x: ARC.x, y: ARC.y + 110 };\nconst DETENTS = Array.from({ length: (END - START) / STEP + 1 }, (_, i) => {\n  const t = (i * STEP) / (END - START);\n  const x = ARC.x - ARC.r * Math.cos(Math.PI * t);\n  const y = ARC.y - ARC.r * Math.sin(Math.PI * t);\n  return {\n    minutes: START + i * STEP,\n    angle: Math.atan2(PIVOT.y - y, x - PIVOT.x),\n  };\n});\n\nfunction formatTime(minutes: number) {\n  const h = Math.floor(minutes / 60);\n  const m = minutes % 60;\n  return `${((h + 11) % 12) + 1}:${String(m).padStart(2, \"0\")} ${h < 12 ? \"AM\" : \"PM\"}`;\n}\n\n// Direction of the shadow on a horizontal dial, in radians from \"toward the\n// viewer\" (north), positive toward the viewer's right (west).\nfunction shadowAngle(minutes: number) {\n  const h = (((minutes - SOLAR_NOON) / 60) * 15 * Math.PI) / 180;\n  return Math.atan2(SIN_LAT * -Math.sin(h), Math.cos(h));\n}\n\n// A point on the dial plate at angle psi and a fraction of its radius.\nfunction onDial(psi: number, k: number) {\n  return {\n    x: r2(DIAL.x + Math.sin(psi) * DIAL.rx * k),\n    y: r2(DIAL.y + Math.cos(psi) * DIAL.ry * k),\n  };\n}\n\nconst HOURS = Array.from({ length: 15 }, (_, i) => 6 + i);\nconst ROMAN = [\n  \"XII\",\n  \"I\",\n  \"II\",\n  \"III\",\n  \"IV\",\n  \"V\",\n  \"VI\",\n  \"VII\",\n  \"VIII\",\n  \"IX\",\n  \"X\",\n  \"XI\",\n];\nconst STARS = [\n  [34, 30, 1.2],\n  [78, 64, 0.9],\n  [22, 118, 1],\n  [120, 22, 0.8],\n  [426, 36, 1.1],\n  [392, 84, 0.8],\n  [440, 132, 1],\n  [346, 20, 0.9],\n] as const;\n\nexport function SundialPicker({\n  value,\n  onChange,\n  label = \"Time of day\",\n  className,\n}: {\n  /** Minutes after midnight, between 6:00 (360) and 20:00 (1200). */\n  value: number;\n  onChange: (minutes: number) => void;\n  label?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const sun = useSpring(toT(value), DETENT);\n  const [dragging, setDragging] = useState(false);\n  const drag = useRef<number | null>(null);\n  const svg = useRef<SVGSVGElement>(null);\n\n  useEffect(() => {\n    if (reduceMotion) sun.jump(toT(value));\n    else sun.set(toT(value));\n  }, [value, reduceMotion, sun]);\n\n  const set = (minutes: number) => {\n    const next = Math.round(clamp(minutes, START, END) / STEP) * STEP;\n    if (next !== value) onChange(next);\n  };\n\n  const track = (e: React.PointerEvent) => {\n    const box = svg.current?.getBoundingClientRect();\n    if (!box) return;\n    const x = ((e.clientX - box.left) / box.width) * VB_W - PIVOT.x;\n    const y = PIVOT.y - ((e.clientY - box.top) / box.height) * VB_H;\n    // Under the pivot, hold the sun at whichever end is nearer.\n    const a = y < 0 ? (x < 0 ? Math.PI : 0) : Math.atan2(y, x);\n    let best = DETENTS[0];\n    for (const d of DETENTS) {\n      if (Math.abs(d.angle - a) < Math.abs(best.angle - a)) best = d;\n    }\n    set(best.minutes);\n  };\n\n  const endDrag = (e: React.PointerEvent) => {\n    if (drag.current !== e.pointerId) return;\n    drag.current = null;\n    setDragging(false);\n  };\n\n  return (\n    <div className={cn(\"flex w-[min(460px,100%)] flex-col gap-3\", className)}>\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-valuemin={START}\n        aria-valuemax={END}\n        aria-valuenow={value}\n        aria-valuetext={formatTime(value)}\n        data-dragging={dragging || undefined}\n        className=\"group relative cursor-grab touch-none overflow-hidden rounded-[24px] bg-muted outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground data-dragging:cursor-grabbing\"\n        style={{ aspectRatio: `${VB_W} / ${VB_H}` }}\n        onPointerDown={(e) => {\n          if (e.button !== 0 || drag.current !== null) return;\n          e.currentTarget.setPointerCapture(e.pointerId);\n          drag.current = e.pointerId;\n          setDragging(true);\n          track(e);\n        }}\n        onPointerMove={(e) => {\n          if (drag.current === e.pointerId) track(e);\n        }}\n        onPointerUp={endDrag}\n        onPointerCancel={endDrag}\n        onKeyDown={(e) => {\n          const delta = {\n            ArrowRight: STEP,\n            ArrowUp: STEP,\n            ArrowLeft: -STEP,\n            ArrowDown: -STEP,\n            PageUp: 60,\n            PageDown: -60,\n            Home: START - END,\n            End: END - START,\n          }[e.key];\n          if (delta === undefined) return;\n          e.preventDefault();\n          set(value + delta);\n        }}\n      >\n        <Sky sun={sun} />\n        <svg\n          ref={svg}\n          viewBox={`0 0 ${VB_W} ${VB_H}`}\n          className=\"absolute inset-0 size-full\"\n          aria-hidden\n        >\n          <Stars sun={sun} />\n          <path\n            d={`M${ARC.x - ARC.r} ${ARC.y}A${ARC.r} ${ARC.r} 0 0 1 ${ARC.x + ARC.r} ${ARC.y}`}\n            fill=\"none\"\n            className=\"stroke-foreground/15\"\n            strokeDasharray=\"2 5\"\n          />\n          {HOURS.map((h) => {\n            const a = Math.PI * (1 - toT(h * 60));\n            const c = Math.cos(a);\n            const s = Math.sin(a);\n            const at = (r: number) => ({\n              x: r2(ARC.x + c * r),\n              y: r2(ARC.y - s * r),\n            });\n            const inner = at(ARC.r - 4);\n            const outer = at(ARC.r + 4);\n            return (\n              <line\n                key={h}\n                x1={inner.x}\n                y1={inner.y}\n                x2={outer.x}\n                y2={outer.y}\n                className=\"stroke-foreground/25\"\n              />\n            );\n          })}\n          <Sun sun={sun} />\n          {/* Ground. Drawn over the sun so it sets behind the horizon. */}\n          <rect\n            x={0}\n            y={ARC.y}\n            width={VB_W}\n            height={VB_H - ARC.y}\n            style={{ fill: GROUND }}\n          />\n          <line\n            x1={0}\n            x2={VB_W}\n            y1={ARC.y}\n            y2={ARC.y}\n            className=\"stroke-foreground/15\"\n          />\n          <Dial sun={sun} />\n        </svg>\n        {/* On top of the sky layer, which would cover an inset ring. */}\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 rounded-[24px] inset-ring inset-ring-foreground/10\"\n        />\n      </div>\n      <div className=\"flex items-baseline justify-between gap-3 px-1\">\n        <p className=\"text-2xl font-medium text-foreground tabular-nums\">\n          {formatTime(value)}\n        </p>\n        <p className=\"text-[13px] text-muted-foreground\">Drag the sun, 6 AM to 8 PM</p>\n      </div>\n    </div>\n  );\n}\n\nfunction Sky({ sun }: { sun: MotionValue<number> }) {\n  // Surface at the horizon, background at noon. Scaled up so the sky is\n  // fully \"day\" for most of the middle of the arc.\n  const day = useTransform(sun, (t) => clamp(Math.sin(Math.PI * t) * 1.6));\n  return (\n    <>\n      <div aria-hidden className=\"absolute inset-0\" style={{ background: DUSK_SKY }} />\n      <motion.div\n        aria-hidden\n        className=\"absolute inset-0\"\n        style={{ background: DAY_SKY, opacity: day }}\n      />\n    </>\n  );\n}\n\nfunction Stars({ sun }: { sun: MotionValue<number> }) {\n  // Only within about the first and last 50 minutes of daylight.\n  const night = useTransform(\n    sun,\n    (t) => clamp(1 - Math.sin(Math.PI * t) / 0.2) * 0.7,\n  );\n  return (\n    <motion.g style={{ opacity: night }}>\n      {STARS.map(([x, y, r]) => (\n        <circle\n          key={`${x}-${y}`}\n          cx={x}\n          cy={y}\n          r={r}\n          // Starlight is white against the violet dusk in either theme.\n          fill=\"oklch(1 0 0)\"\n        />\n      ))}\n    </motion.g>\n  );\n}\n\nfunction Sun({ sun }: { sun: MotionValue<number> }) {\n  const cx = useTransform(sun, (t) =>\n    r2(ARC.x - ARC.r * Math.cos(Math.PI * t)),\n  );\n  const cy = useTransform(sun, (t) =>\n    r2(ARC.y - ARC.r * Math.sin(Math.PI * t)),\n  );\n  // Low sun burns orange, high sun turns pale gold, as real light does.\n  const high = useTransform(sun, (t) => clamp(Math.sin(Math.PI * t) * 2.2));\n  const glowId = useId();\n  return (\n    <>\n      <defs>\n        <radialGradient id={glowId}>\n          <stop offset=\"0.3\" stopColor={SUN_GLOW} stopOpacity={0.55} />\n          <stop offset=\"1\" stopColor={SUN_GLOW} stopOpacity={0} />\n        </radialGradient>\n      </defs>\n      <motion.circle cx={cx} cy={cy} r={42} fill={`url(#${glowId})`} />\n      {/* A grab ring that shows while the sun is held. */}\n      <motion.circle\n        cx={cx}\n        cy={cy}\n        r={22}\n        fill=\"none\"\n        strokeWidth={1.5}\n        className=\"stroke-foreground/25 opacity-0 transition-opacity duration-150 ease-out group-data-dragging:opacity-100\"\n      />\n      <motion.circle cx={cx} cy={cy} r={14} fill={SUN_LOW} />\n      <motion.circle cx={cx} cy={cy} r={14} fill={SUN_HIGH} style={{ opacity: high }} />\n    </>\n  );\n}\n\nfunction Dial({ sun }: { sun: MotionValue<number> }) {\n  const shadow = useTransform(sun, (t) => {\n    const minutes = START + t * (END - START);\n    const psi = shadowAngle(minutes);\n    // Visual sun altitude peaks at 70 degrees, a summer noon at 40 N.\n    const alt = Math.max(Math.sin(Math.PI * t) * 70, 4) * (Math.PI / 180);\n    const k = Math.min(SHADOW_MIN + SHADOW_GROWTH / Math.tan(alt), 1.02);\n    const tip = onDial(psi, k);\n    // Tapers from the gnomon's width to a soft point.\n    const nx = Math.cos(psi) * 4;\n    const ny = -Math.sin(psi) * 4 * (DIAL.ry / DIAL.rx);\n    return `M${r2(DIAL.x + nx)} ${r2(DIAL.y + ny)}L${tip.x} ${tip.y}L${r2(DIAL.x - nx)} ${r2(DIAL.y - ny)}Z`;\n  });\n  // A sun on the horizon casts almost nothing; keep a trace so the dial\n  // still reads the time.\n  const strength = useTransform(\n    sun,\n    (t) => 0.3 + 0.7 * clamp(Math.sin(Math.PI * t) * 3),\n  );\n\n  return (\n    <g>\n      {/* Contact shadow on the terrace, then the plate's edge, then its\n          face: three ellipses give the bronze real thickness. */}\n      <ellipse cx={DIAL.x} cy={DIAL.y + 9} rx={DIAL.rx + 6} ry={DIAL.ry + 3} fill=\"oklch(0 0 0 / 0.14)\" />\n      <ellipse cx={DIAL.x} cy={DIAL.y + 5} rx={DIAL.rx} ry={DIAL.ry} fill={BRONZE_EDGE} />\n      <ellipse cx={DIAL.x} cy={DIAL.y} rx={DIAL.rx} ry={DIAL.ry} fill={BRONZE} />\n      <ellipse\n        cx={DIAL.x}\n        cy={DIAL.y}\n        rx={DIAL.rx * 0.82}\n        ry={DIAL.ry * 0.82}\n        fill=\"none\"\n        stroke={ENGRAVE}\n        strokeOpacity={0.45}\n      />\n      {HOURS.map((h) => {\n        const psi = shadowAngle(h * 60);\n        const a = onDial(psi, 0.3);\n        const b = onDial(psi, 0.82);\n        const major = h % 2 === 0;\n        const l = onDial(psi, 0.92);\n        return (\n          <g key={h}>\n            <line\n              x1={a.x}\n              y1={a.y}\n              x2={b.x}\n              y2={b.y}\n              stroke={ENGRAVE}\n              strokeOpacity={major ? 0.75 : 0.35}\n            />\n            {major && (\n              <text\n                x={l.x}\n                y={l.y}\n                textAnchor=\"middle\"\n                dominantBaseline=\"central\"\n                fontSize={12}\n                fontWeight={600}\n                fill={ENGRAVE}\n                className=\"font-serif\"\n              >\n                {ROMAN[h % 12]}\n              </text>\n            )}\n          </g>\n        );\n      })}\n      <motion.path\n        d={shadow}\n        // A shadow is dark in either theme.\n        fill=\"oklch(0.22 0.03 55 / 0.6)\"\n        style={{ opacity: strength }}\n      />\n      {/* Gnomon: a thin blade with its lit face and a darker side. */}\n      <path\n        d={`M${DIAL.x - 2} ${DIAL.y + 3}L${DIAL.x} ${DIAL.y - 30}L${DIAL.x + 2} ${DIAL.y + 3}Z`}\n        fill={BRONZE_EDGE}\n      />\n      <path\n        d={`M${DIAL.x} ${DIAL.y - 30}L${DIAL.x + 2} ${DIAL.y + 3}L${DIAL.x + 5} ${DIAL.y + 1}Z`}\n        fill=\"oklch(0.82 0.08 80)\"\n      />\n    </g>\n  );\n}\n\nexport default function SundialPickerDemo() {\n  const [minutes, setMinutes] = useState(14 * 60 + 15);\n  return (\n    <SundialPicker label=\"Pickup time\" value={minutes} onChange={setMinutes} />\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["objects"],"docs":"From ui lab: https://lab.xevrion.dev/lab/sundial-picker"}