"use client";import * as React from "react";import { LightSurface, clamp, easeOutCubic, resolvePalette, useLightHeld, useLightReducedMotion, type LightPalette, type LightPaletteName, type LightSurfaceHandle,} from "./light-surface";/* ───────────────────────────────────────────────────────── * LEVEL DIAL: a 270° dial for one level, in a card * * turn drag along the arc, or use the arrow keys; the * arc and the figure follow at once * jump when the value changes from outside (a preset, a * schedule, another device), a crest of light spreads from * the dial's centre; under it the arc sweeps to the * new value and the figure counts there * zones name ranges of the dial (Late night, Reference); * a zone with a palette colours the arc and keeps * the card's rim lit while the value is in it * * Reduced motion: jumps land in place, with no light. * ───────────────────────────────────────────────────────── */export interface LevelZone { /** The zone covers values up to and including this one. */ to: number; label: string; /** Colours the arc and lights the rim while the value is in this zone. */ palette?: LightPaletteName | LightPalette;}export interface LevelDialProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title" | "onChange"> { value: number; onValueChange?: (value: number) => void; min?: number; max?: number; step?: number; /** Set after the figure: "°", "dB", "%". */ unit?: string; /** Names the dial for screen readers. */ label: string; /** The card's heading. */ title?: React.ReactNode; /** Top right of the card: a mode, a badge. */ badge?: React.ReactNode; /** A line under the dial. */ caption?: React.ReactNode; /** Named ranges, lowest first. */ zones?: LevelZone[]; /** Your actions, at the foot of the card. */ children?: React.ReactNode;}const START = 135;const SWEEP = 270;const CX = 120;const CY = 120;const R = 84;const polar = (deg: number, r = R) => ({ x: CX + r * Math.cos((deg * Math.PI) / 180), y: CY + r * Math.sin((deg * Math.PI) / 180) });function arc(from: number, to: number) { const a = polar(from); const b = polar(to); return `M ${a.x.toFixed(2)} ${a.y.toFixed(2)} A ${R} ${R} 0 ${to - from > 180 ? 1 : 0} 1 ${b.x.toFixed(2)} ${b.y.toFixed(2)}`;}/** Glides to a new target when asked to, otherwise follows it exactly. */function useGlide(target: number, glide: boolean, reduced: boolean) { const [anim, setAnim] = React.useState<number | null>(null); const current = React.useRef(target); const raf = React.useRef(0); React.useEffect(() => { cancelAnimationFrame(raf.current); if (!glide || reduced) { current.current = target; raf.current = requestAnimationFrame(() => setAnim(null)); return () => cancelAnimationFrame(raf.current); } const from = current.current; if (from === target) return; const start = performance.now(); const step = (now: number) => { const k = Math.min(1, (now - start) / 720); current.current = from + (target - from) * easeOutCubic(k); setAnim(k < 1 ? current.current : null); if (k < 1) raf.current = requestAnimationFrame(step); }; raf.current = requestAnimationFrame(step); return () => cancelAnimationFrame(raf.current); }, [target, glide, reduced]); return anim ?? target;}export function LevelDial({ value, onValueChange, min = 0, max = 100, step = 1, unit = "", label, title, badge, caption, zones, children, className = "", ...props}: LevelDialProps) { const surface = React.useRef<LightSurfaceHandle>(null); const svg = React.useRef<SVGSVGElement>(null); const reduced = useLightReducedMotion(); const [dragging, setDragging] = React.useState(false); // The last value we sent: anything else that arrives was set from outside, and gets the light. const [local, setLocal] = React.useState<number | null>(null); const external = value !== local; const zoneOf = (v: number) => zones?.find((z) => v <= z.to) ?? zones?.[zones.length - 1]; const landed = useLightHeld(value, external ? `x${value}` : "local", surface, () => { if (!external) return null; const card = surface.current?.element(); const dial = svg.current; let origin = { x: 0.5, y: 0.44 }; if (card && dial) { const c = card.getBoundingClientRect(); const d = dial.getBoundingClientRect(); origin = { x: (d.left + d.width / 2 - c.left) / c.width, y: (d.top + (d.height * CY) / 218 - c.top) / c.height }; } return { direction: "radial", origin, palette: zoneOf(value)?.palette ?? "solar" }; }); const shown = clamp(useGlide(landed, external, reduced), min, max); const zone = zoneOf(Math.round(shown)); const pal = zone?.palette ? resolvePalette(zone.palette) : null; const angle = START + ((shown - min) / (max - min || 1)) * SWEEP; const thumb = polar(angle); const gradientId = React.useId(); const send = (v: number) => { const next = clamp(Math.round(v / step) * step, min, max); if (next === value) return; setLocal(next); onValueChange?.(next); }; const fromPointer = (clientX: number, clientY: number) => { const el = svg.current; if (!el) return; const r = el.getBoundingClientRect(); const deg = (Math.atan2(clientY - (r.top + (r.height * CY) / 218), clientX - (r.left + r.width / 2)) * 180) / Math.PI; const around = ((((deg % 360) + 360) % 360) - START + 360) % 360; // Past the ends of the arc, the nearer end wins. const k = around <= SWEEP ? around / SWEEP : around - SWEEP < 360 - around ? 1 : 0; send(min + k * (max - min)); }; const ink = pal ? pal.ink : "var(--foreground)"; const figure = Math.round(shown); return ( <LightSurface ref={surface} palette={zone?.palette ?? "solar"} direction="radial" lit={!!pal} className={`flex flex-col rounded-[30px] ${className}`} {...props} > <div className="flex h-full flex-col px-6 pb-6 pt-6"> {(title || badge) && ( <div className="flex min-h-7 items-center justify-between gap-3"> <div className="text-[15px] font-medium tracking-[-0.01em] text-foreground">{title}</div> {badge} </div> )} <div className="my-1 flex flex-col items-center"> <div role="slider" tabIndex={0} aria-label={label} aria-valuemin={min} aria-valuemax={max} aria-valuenow={value} aria-valuetext={`${value}${unit}${zoneOf(value)?.label ? `, ${zoneOf(value)?.label}` : ""}`} onKeyDown={(e) => { const big = Math.max(step, (max - min) / 10); const by: Record<string, number> = { ArrowRight: step, ArrowUp: step, ArrowLeft: -step, ArrowDown: -step, PageUp: big, PageDown: -big }; if (e.key in by) send(value + by[e.key]); else if (e.key === "Home") send(min); else if (e.key === "End") send(max); else return; e.preventDefault(); }} className="relative flex w-full max-w-[236px] items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50" > <svg ref={svg} viewBox="0 0 240 218" className={`aspect-[240/218] w-full max-w-[236px] touch-none select-none ${dragging ? "cursor-grabbing" : "cursor-grab"}`} onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); setDragging(true); fromPointer(e.clientX, e.clientY); }} onPointerMove={(e) => dragging && fromPointer(e.clientX, e.clientY)} onPointerUp={() => setDragging(false)} onPointerCancel={() => setDragging(false)} > {pal && ( <defs> <linearGradient id={gradientId} x1="0%" y1="100%" x2="100%" y2="0%"> <stop offset="0%" stopColor={pal.ink} /> <stop offset="100%" stopColor={`color-mix(in oklab, ${pal.ink} 45%, white)`} /> </linearGradient> </defs> )} <path d={arc(START, START + SWEEP)} fill="none" stroke="color-mix(in oklab, var(--foreground) 11%, transparent)" strokeWidth="7.5" strokeLinecap="round" /> {shown > min && ( <path d={arc(START, angle)} fill="none" stroke={pal ? `url(#${gradientId})` : "var(--foreground)"} strokeWidth="7.5" strokeLinecap="round" /> )} <circle cx={thumb.x} cy={thumb.y} r={dragging ? 7.5 : 5.5} fill="var(--card)" stroke={ink} strokeWidth="2.5" className="transition-[r] duration-150 motion-reduce:transition-none" /> <text x="62" y="206" textAnchor="middle" className="fill-muted-foreground font-mono text-[12px] tabular-nums"> {min} </text> <text x="178" y="206" textAnchor="middle" className="fill-muted-foreground font-mono text-[12px] tabular-nums"> {max} </text> </svg> <div aria-hidden className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center pt-1 [container-type:inline-size]"> <div className="flex items-baseline gap-0.5"> <span className="text-[clamp(34px,15cqi,46px)] font-medium leading-none tracking-[-0.04em] tabular-nums text-foreground">{figure}</span> {unit && <span className="text-[16px] font-medium text-muted-foreground">{unit}</span>} </div> {zone?.label && ( <div className="mt-1.5 text-[13px] font-medium transition-colors duration-300" style={{ color: pal ? `color-mix(in oklab, ${pal.ink} 70%, var(--foreground))` : "var(--muted-foreground)" }} > {zone.label} </div> )} </div> </div> {caption && <p className="mt-1 text-center text-[13px] tabular-nums text-muted-foreground">{caption}</p>} </div> {children && <div className="mt-auto pt-4">{children}</div>} </div> </LightSurface> );}