1"use client";
2
3import {
4 Direction as DirectionPrimitive,
5 Slot as SlotPrimitive,
6} from "radix-ui";
7import * as React from "react";
8import { useComposedRefs } from "@/lib/compose-refs";
9import { cn } from "@/lib/utils";
10import { VisuallyHiddenInput } from "@/registry/bases/radix/components/visually-hidden-input";
11import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
12import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
13import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
14
15const ROOT_NAME = "AngleSlider";
16const THUMB_NAME = "AngleSliderThumb";
17
18const PAGE_KEYS = ["PageUp", "PageDown"];
19const ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
20
21type Direction = "ltr" | "rtl";
22
23interface DivProps extends React.ComponentProps<"div"> {
24 asChild?: boolean;
25}
26
27type RootElement = React.ComponentRef<typeof AngleSlider>;
28type ThumbElement = React.ComponentRef<typeof AngleSliderThumb>;
29
30function clamp(value: number, [min, max]: [number, number]) {
31 return Math.min(max, Math.max(min, value));
32}
33
34function getNextSortedValues(
35 prevValues: number[] = [],
36 nextValue: number,
37 atIndex: number,
38) {
39 const nextValues = [...prevValues];
40 nextValues[atIndex] = nextValue;
41 return nextValues.sort((a, b) => a - b);
42}
43
44function getStepsBetweenValues(values: number[]) {
45 return values.slice(0, -1).map((value, index) => {
46 const nextValue = values[index + 1];
47 return nextValue !== undefined ? nextValue - value : 0;
48 });
49}
50
51function hasMinStepsBetweenValues(
52 values: number[],
53 minStepsBetweenValues: number,
54) {
55 if (minStepsBetweenValues > 0) {
56 const stepsBetweenValues = getStepsBetweenValues(values);
57 const actualMinStepsBetweenValues =
58 stepsBetweenValues.length > 0 ? Math.min(...stepsBetweenValues) : 0;
59 return actualMinStepsBetweenValues >= minStepsBetweenValues;
60 }
61 return true;
62}
63
64function getDecimalCount(value: number) {
65 return (String(value).split(".")[1] ?? "").length;
66}
67
68function roundValue(value: number, decimalCount: number) {
69 const rounder = 10 ** decimalCount;
70 return Math.round(value * rounder) / rounder;
71}
72
73function getClosestValueIndex(values: number[], nextValue: number) {
74 if (values.length === 1) return 0;
75 const distances = values.map((value) => Math.abs(value - nextValue));
76 const closestDistance = Math.min(...distances);
77 return distances.indexOf(closestDistance);
78}
79
80interface ThumbData {
81 id: string;
82 element: ThumbElement;
83 index: number;
84 value: number;
85}
86
87interface StoreState {
88 values: number[];
89 thumbs: Map<number, ThumbData>;
90 valueIndexToChange: number;
91 min: number;
92 max: number;
93 step: number;
94 size: number;
95 thickness: number;
96 startAngle: number;
97 endAngle: number;
98 minStepsBetweenThumbs: number;
99 disabled: boolean;
100 inverted: boolean;
101}
102
103interface Store {
104 subscribe: (callback: () => void) => () => void;
105 getState: () => StoreState;
106 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
107 notify: () => void;
108 addThumb: (index: number, thumbData: ThumbData) => void;
109 removeThumb: (index: number) => void;
110 updateValue: (
111 value: number,
112 atIndex: number,
113 options?: { commit?: boolean },
114 ) => void;
115 getValueFromPointer: (
116 clientX: number,
117 clientY: number,
118 rect: DOMRect,
119 ) => number;
120 getAngleFromValue: (value: number) => number;
121 getPositionFromAngle: (angle: number) => { x: number; y: number };
122}
123
124const StoreContext = React.createContext<Store | null>(null);
125
126function useStoreContext(consumerName: string) {
127 const context = React.useContext(StoreContext);
128 if (!context) {
129 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
130 }
131 return context;
132}
133
134function useStore<T>(selector: (state: StoreState) => T): T {
135 const store = useStoreContext("useStore");
136
137 const getSnapshot = React.useCallback(
138 () => selector(store.getState()),
139 [store, selector],
140 );
141
142 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
143}
144
145interface SliderContextValue {
146 dir: Direction;
147 name?: string;
148 form?: string;
149}
150
151const SliderContext = React.createContext<SliderContextValue | null>(null);
152
153function useSliderContext(consumerName: string) {
154 const context = React.useContext(SliderContext);
155 if (!context) {
156 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
157 }
158 return context;
159}
160
161interface AngleSliderProps extends Omit<DivProps, "defaultValue"> {
162 value?: number[];
163 defaultValue?: number[];
164 onValueChange?: (value: number[]) => void;
165 onValueCommit?: (value: number[]) => void;
166 min?: number;
167 max?: number;
168 step?: number;
169 minStepsBetweenThumbs?: number;
170 size?: number;
171 thickness?: number;
172 startAngle?: number;
173 endAngle?: number;
174 dir?: Direction;
175 form?: string;
176 name?: string;
177 disabled?: boolean;
178 inverted?: boolean;
179}
180
181function AngleSlider(props: AngleSliderProps) {
182 const {
183 value,
184 defaultValue = [0],
185 onValueChange,
186 onValueCommit,
187 min = 0,
188 max = 100,
189 step = 1,
190 minStepsBetweenThumbs = 0,
191 size = 60,
192 thickness = 8,
193 startAngle = -90,
194 endAngle = 270,
195 dir: dirProp,
196 form,
197 name,
198 disabled = false,
199 inverted = false,
200 asChild,
201 className,
202 ref,
203 onPointerMove: onPointerMoveProp,
204 onPointerUp: onPointerUpProp,
205 onPointerDown: onPointerDownProp,
206 onKeyDown: onKeyDownProp,
207 ...rootProps
208 } = props;
209
210 const listenersRef = useLazyRef(() => new Set<() => void>());
211 const stateRef = useLazyRef<StoreState>(() => ({
212 values: value ?? defaultValue,
213 thumbs: new Map(),
214 valueIndexToChange: 0,
215 min,
216 max,
217 step,
218 minStepsBetweenThumbs,
219 disabled,
220 inverted,
221 size,
222 thickness,
223 startAngle,
224 endAngle,
225 }));
226
227 const propsRef = useAsRef({
228 onValueChange,
229 onValueCommit,
230 onPointerMove: onPointerMoveProp,
231 onPointerUp: onPointerUpProp,
232 onPointerDown: onPointerDownProp,
233 onKeyDown: onKeyDownProp,
234 });
235
236 const store = React.useMemo<Store>(() => {
237 return {
238 subscribe: (cb) => {
239 listenersRef.current.add(cb);
240 return () => listenersRef.current.delete(cb);
241 },
242 getState: () => stateRef.current,
243 setState: (key, value) => {
244 if (Object.is(stateRef.current[key], value)) return;
245
246 if (key === "values" && Array.isArray(value)) {
247 const hasChanged = String(stateRef.current.values) !== String(value);
248 stateRef.current.values = value;
249 if (hasChanged) {
250 propsRef.current.onValueChange?.(value);
251 }
252 } else {
253 stateRef.current[key] = value;
254 }
255
256 store.notify();
257 },
258 addThumb: (index, thumbData) => {
259 stateRef.current.thumbs.set(index, thumbData);
260 store.notify();
261 },
262 removeThumb: (index) => {
263 stateRef.current.thumbs.delete(index);
264 store.notify();
265 },
266 updateValue: (value, atIndex, { commit = false } = {}) => {
267 const { min, max, step, minStepsBetweenThumbs } = stateRef.current;
268 const decimalCount = getDecimalCount(step);
269 const snapToStep = roundValue(
270 Math.round((value - min) / step) * step + min,
271 decimalCount,
272 );
273 const nextValue = clamp(snapToStep, [min, max]);
274
275 const nextValues = getNextSortedValues(
276 stateRef.current.values,
277 nextValue,
278 atIndex,
279 );
280
281 if (
282 hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)
283 ) {
284 stateRef.current.valueIndexToChange = nextValues.indexOf(nextValue);
285 const hasChanged =
286 String(nextValues) !== String(stateRef.current.values);
287
288 if (hasChanged) {
289 stateRef.current.values = nextValues;
290 propsRef.current.onValueChange?.(nextValues);
291 if (commit) propsRef.current.onValueCommit?.(nextValues);
292 store.notify();
293 }
294 }
295 },
296 getValueFromPointer: (clientX, clientY, rect) => {
297 const { min, max, inverted, startAngle, endAngle } = stateRef.current;
298 const centerX = rect.left + rect.width / 2;
299 const centerY = rect.top + rect.height / 2;
300
301 const deltaX = clientX - centerX;
302 const deltaY = clientY - centerY;
303 let angle = (Math.atan2(deltaY, deltaX) * 180) / Math.PI;
304
305 if (angle < 0) angle += 360;
306
307 angle = (angle - startAngle + 360) % 360;
308
309 const totalAngle = (endAngle - startAngle + 360) % 360 || 360;
310
311 let percent = angle / totalAngle;
312 if (inverted) percent = 1 - percent;
313
314 return min + percent * (max - min);
315 },
316 getAngleFromValue: (value) => {
317 const { min, max, inverted, startAngle, endAngle } = stateRef.current;
318 let percent = (value - min) / (max - min);
319 if (inverted) percent = 1 - percent;
320
321 const totalAngle = (endAngle - startAngle + 360) % 360 || 360;
322 const angle = startAngle + percent * totalAngle;
323
324 return angle;
325 },
326 getPositionFromAngle: (angle) => {
327 const { size } = stateRef.current;
328 const radians = (angle * Math.PI) / 180;
329
330 return {
331 x: size * Math.cos(radians),
332 y: size * Math.sin(radians),
333 };
334 },
335 notify: () => {
336 for (const cb of listenersRef.current) {
337 cb();
338 }
339 },
340 };
341 }, [listenersRef, stateRef, propsRef]);
342
343 useIsomorphicLayoutEffect(() => {
344 if (value !== undefined) {
345 store.setState("values", value);
346 }
347 }, [value, store]);
348
349 useIsomorphicLayoutEffect(() => {
350 const currentState = store.getState();
351
352 if (currentState.min !== min) {
353 store.setState("min", min);
354 }
355 if (currentState.max !== max) {
356 store.setState("max", max);
357 }
358 if (currentState.step !== step) {
359 store.setState("step", step);
360 }
361 if (currentState.minStepsBetweenThumbs !== minStepsBetweenThumbs) {
362 store.setState("minStepsBetweenThumbs", minStepsBetweenThumbs);
363 }
364 if (currentState.size !== size) {
365 store.setState("size", size);
366 }
367 if (currentState.thickness !== thickness) {
368 store.setState("thickness", thickness);
369 }
370 if (currentState.startAngle !== startAngle) {
371 store.setState("startAngle", startAngle);
372 }
373 if (currentState.endAngle !== endAngle) {
374 store.setState("endAngle", endAngle);
375 }
376 if (currentState.disabled !== disabled) {
377 store.setState("disabled", disabled);
378 }
379 if (currentState.inverted !== inverted) {
380 store.setState("inverted", inverted);
381 }
382 }, [
383 store,
384 min,
385 max,
386 step,
387 minStepsBetweenThumbs,
388 size,
389 thickness,
390 startAngle,
391 endAngle,
392 disabled,
393 inverted,
394 ]);
395
396 const dir = DirectionPrimitive.useDirection(dirProp);
397
398 const [sliderElement, setSliderElement] = React.useState<RootElement | null>(
399 null,
400 );
401 const composedRef = useComposedRefs(ref, setSliderElement);
402 const valuesBeforeSlideStartRef = React.useRef(value ?? defaultValue);
403
404 const contextValue = React.useMemo<SliderContextValue>(
405 () => ({
406 dir,
407 name,
408 form,
409 }),
410 [dir, name, form],
411 );
412
413 const onSliderStart = React.useCallback(
414 (pointerValue: number) => {
415 if (disabled) return;
416
417 const values = store.getState().values;
418 const closestIndex = getClosestValueIndex(values, pointerValue);
419 store.setState("valueIndexToChange", closestIndex);
420 store.updateValue(pointerValue, closestIndex);
421 },
422 [store, disabled],
423 );
424
425 const onSliderMove = React.useCallback(
426 (pointerValue: number) => {
427 if (disabled) return;
428
429 const valueIndexToChange = store.getState().valueIndexToChange;
430 store.updateValue(pointerValue, valueIndexToChange);
431 },
432 [store, disabled],
433 );
434
435 const onSliderEnd = React.useCallback(() => {
436 if (disabled) return;
437
438 const state = store.getState();
439 const prevValue =
440 valuesBeforeSlideStartRef.current[state.valueIndexToChange];
441 const nextValue = state.values[state.valueIndexToChange];
442 const hasChanged = nextValue !== prevValue;
443
444 if (hasChanged) {
445 onValueCommit?.(state.values);
446 }
447 }, [store, disabled, onValueCommit]);
448
449 const onKeyDown = React.useCallback(
450 (event: React.KeyboardEvent<RootElement>) => {
451 propsRef.current.onKeyDown?.(event);
452 if (event.defaultPrevented || disabled) return;
453
454 const state = store.getState();
455 const { values, valueIndexToChange, min, max, step } = state;
456 const currentValue = values[valueIndexToChange] ?? min;
457
458 if (event.key === "Home") {
459 event.preventDefault();
460 store.updateValue(min, 0, { commit: true });
461 } else if (event.key === "End") {
462 event.preventDefault();
463 store.updateValue(max, values.length - 1, { commit: true });
464 } else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
465 event.preventDefault();
466
467 const isPageKey = PAGE_KEYS.includes(event.key);
468 const isSkipKey =
469 isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key));
470 const multiplier = isSkipKey ? 10 : 1;
471
472 let direction = 0;
473 const isDecreaseKey = ["ArrowLeft", "ArrowUp", "PageUp"].includes(
474 event.key,
475 );
476 direction = isDecreaseKey ? -1 : 1;
477 if (inverted) direction *= -1;
478
479 const stepInDirection = step * multiplier * direction;
480 store.updateValue(currentValue + stepInDirection, valueIndexToChange, {
481 commit: true,
482 });
483 }
484 },
485 [store, propsRef, disabled, inverted],
486 );
487
488 const onPointerDown = React.useCallback(
489 (event: React.PointerEvent<RootElement>) => {
490 propsRef.current.onPointerDown?.(event);
491 if (event.defaultPrevented || disabled) return;
492
493 const target = event.target as HTMLElement;
494 target.setPointerCapture(event.pointerId);
495 event.preventDefault();
496
497 if (!disabled) {
498 valuesBeforeSlideStartRef.current = store.getState().values;
499
500 const thumbs = Array.from(store.getState().thumbs.values());
501 const clickedThumb = thumbs.find((thumb) =>
502 thumb.element.contains(target),
503 );
504
505 if (clickedThumb) {
506 clickedThumb.element.focus();
507 store.setState("valueIndexToChange", clickedThumb.index);
508 } else if (sliderElement) {
509 const rect = sliderElement.getBoundingClientRect();
510 const pointerValue = store.getValueFromPointer(
511 event.clientX,
512 event.clientY,
513 rect,
514 );
515 onSliderStart(pointerValue);
516 }
517 }
518 },
519 [store, propsRef, disabled, sliderElement, onSliderStart],
520 );
521
522 const onPointerMove = React.useCallback(
523 (event: React.PointerEvent<RootElement>) => {
524 propsRef.current.onPointerMove?.(event);
525 if (event.defaultPrevented || disabled) return;
526
527 const target = event.target as HTMLElement;
528 if (target.hasPointerCapture(event.pointerId) && sliderElement) {
529 const rect = sliderElement.getBoundingClientRect();
530 const pointerValue = store.getValueFromPointer(
531 event.clientX,
532 event.clientY,
533 rect,
534 );
535 onSliderMove(pointerValue);
536 }
537 },
538 [store, propsRef, disabled, sliderElement, onSliderMove],
539 );
540
541 const onPointerUp = React.useCallback(
542 (event: React.PointerEvent<RootElement>) => {
543 propsRef.current.onPointerUp?.(event);
544 if (event.defaultPrevented) return;
545
546 const target = event.target as RootElement;
547 if (target.hasPointerCapture(event.pointerId)) {
548 target.releasePointerCapture(event.pointerId);
549 onSliderEnd();
550 }
551 },
552 [propsRef, onSliderEnd],
553 );
554
555 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
556
557 return (
558 <StoreContext.Provider value={store}>
559 <SliderContext.Provider value={contextValue}>
560 <RootPrimitive
561 data-disabled={disabled ? "" : undefined}
562 data-slot="angle-slider"
563 dir={dir}
564 {...rootProps}
565 ref={composedRef}
566 className={cn(
567 "relative touch-none select-none",
568 disabled && "opacity-50",
569 className,
570 )}
571 style={{
572 width: `${size * 2 + 40}px`,
573 height: `${size * 2 + 40}px`,
574 }}
575 onKeyDown={onKeyDown}
576 onPointerDown={onPointerDown}
577 onPointerMove={onPointerMove}
578 onPointerUp={onPointerUp}
579 />
580 </SliderContext.Provider>
581 </StoreContext.Provider>
582 );
583}
584
585function AngleSliderTrack(props: React.ComponentProps<"svg">) {
586 const { className, children, ...trackProps } = props;
587
588 const disabled = useStore((state) => state.disabled);
589 const size = useStore((state) => state.size);
590 const thickness = useStore((state) => state.thickness);
591 const startAngle = useStore((state) => state.startAngle);
592 const endAngle = useStore((state) => state.endAngle);
593
594 const center = size + 20;
595 const trackRadius = size;
596
597 const totalAngle = (endAngle - startAngle + 360) % 360 || 360;
598 const isFullCircle = totalAngle >= 359;
599
600 const startRadians = (startAngle * Math.PI) / 180;
601 const endRadians = (endAngle * Math.PI) / 180;
602
603 const startX = center + trackRadius * Math.cos(startRadians);
604 const startY = center + trackRadius * Math.sin(startRadians);
605 const endX = center + trackRadius * Math.cos(endRadians);
606 const endY = center + trackRadius * Math.sin(endRadians);
607
608 const largeArcFlag = totalAngle > 180 ? 1 : 0;
609
610 return (
611 <svg
612 aria-hidden="true"
613 focusable="false"
614 data-disabled={disabled ? "" : undefined}
615 data-slot="angle-slider-track"
616 width={center * 2}
617 height={center * 2}
618 {...trackProps}
619 className={cn("absolute inset-0", className)}
620 >
621 {isFullCircle ? (
622 <circle
623 data-slot="angle-slider-track-rail"
624 cx={center}
625 cy={center}
626 r={trackRadius}
627 fill="none"
628 stroke="currentColor"
629 strokeWidth={thickness}
630 strokeLinecap="round"
631 vectorEffect="non-scaling-stroke"
632 className="stroke-muted"
633 />
634 ) : (
635 <path
636 data-slot="angle-slider-track-rail"
637 d={`M ${startX} ${startY} A ${trackRadius} ${trackRadius} 0 ${largeArcFlag} 1 ${endX} ${endY}`}
638 fill="none"
639 stroke="currentColor"
640 strokeWidth={thickness}
641 strokeLinecap="round"
642 vectorEffect="non-scaling-stroke"
643 className="stroke-muted"
644 />
645 )}
646 {children}
647 </svg>
648 );
649}
650
651function AngleSliderRange(props: React.ComponentProps<"path">) {
652 const { className, ...rangeProps } = props;
653
654 const values = useStore((state) => state.values);
655 const min = useStore((state) => state.min);
656 const max = useStore((state) => state.max);
657 const disabled = useStore((state) => state.disabled);
658 const size = useStore((state) => state.size);
659 const thickness = useStore((state) => state.thickness);
660 const startAngle = useStore((state) => state.startAngle);
661 const endAngle = useStore((state) => state.endAngle);
662
663 const center = size + 20;
664 const trackRadius = size;
665
666 const sortedValues = [...values].sort((a, b) => a - b);
667
668 const rangeStart = values.length <= 1 ? min : (sortedValues[0] ?? min);
669 const rangeEnd =
670 values.length <= 1
671 ? (sortedValues[0] ?? min)
672 : (sortedValues[sortedValues.length - 1] ?? max);
673
674 const rangeStartPercent = (rangeStart - min) / (max - min);
675 const rangeEndPercent = (rangeEnd - min) / (max - min);
676
677 const totalAngle = (endAngle - startAngle + 360) % 360 || 360;
678 const rangeStartAngle = startAngle + rangeStartPercent * totalAngle;
679 const rangeEndAngle = startAngle + rangeEndPercent * totalAngle;
680
681 const rangeStartRadians = (rangeStartAngle * Math.PI) / 180;
682 const rangeEndRadians = (rangeEndAngle * Math.PI) / 180;
683
684 const startX = center + trackRadius * Math.cos(rangeStartRadians);
685 const startY = center + trackRadius * Math.sin(rangeStartRadians);
686 const endX = center + trackRadius * Math.cos(rangeEndRadians);
687 const endY = center + trackRadius * Math.sin(rangeEndRadians);
688
689 const rangeAngle = (rangeEndAngle - rangeStartAngle + 360) % 360;
690 const largeArcFlag = rangeAngle > 180 ? 1 : 0;
691
692 if (rangeStart === rangeEnd) return null;
693
694 return (
695 <path
696 data-disabled={disabled ? "" : undefined}
697 data-slot="angle-slider-range"
698 d={`M ${startX} ${startY} A ${trackRadius} ${trackRadius} 0 ${largeArcFlag} 1 ${endX} ${endY}`}
699 fill="none"
700 stroke="currentColor"
701 strokeWidth={thickness}
702 strokeLinecap="round"
703 vectorEffect="non-scaling-stroke"
704 {...rangeProps}
705 className={cn("stroke-primary", className)}
706 />
707 );
708}
709
710interface AngleSliderThumbProps extends DivProps {
711 index?: number;
712}
713
714function AngleSliderThumb(props: AngleSliderThumbProps) {
715 const { index: indexProp, className, asChild, ref, ...thumbProps } = props;
716
717 const context = useSliderContext(THUMB_NAME);
718 const store = useStoreContext(THUMB_NAME);
719 const values = useStore((state) => state.values);
720 const min = useStore((state) => state.min);
721 const max = useStore((state) => state.max);
722 const step = useStore((state) => state.step);
723 const disabled = useStore((state) => state.disabled);
724 const size = useStore((state) => state.size);
725
726 const thumbId = React.useId();
727 const [thumbElement, setThumbElement] = React.useState<ThumbElement | null>(
728 null,
729 );
730 const composedRef = useComposedRefs(ref, setThumbElement);
731
732 const isFormControl = thumbElement
733 ? context.form || !!thumbElement.closest("form")
734 : true;
735
736 const index = indexProp ?? 0;
737 const value = values[index];
738
739 React.useEffect(() => {
740 if (thumbElement && value !== undefined) {
741 store.addThumb(index, {
742 id: thumbId,
743 element: thumbElement,
744 index,
745 value,
746 });
747
748 return () => {
749 store.removeThumb(index);
750 };
751 }
752 }, [thumbElement, thumbId, index, value, store]);
753
754 const thumbStyle = React.useMemo<React.CSSProperties>(() => {
755 if (value === undefined) return {};
756
757 const angle = store.getAngleFromValue(value);
758 const position = store.getPositionFromAngle(angle);
759 const center = size + 20;
760
761 return {
762 position: "absolute",
763 left: `${center + position.x}px`,
764 top: `${center + position.y}px`,
765 transform: "translate(-50%, -50%)",
766 };
767 }, [value, store, size]);
768
769 const onFocus = React.useCallback(
770 (event: React.FocusEvent<ThumbElement>) => {
771 props.onFocus?.(event);
772 if (event.defaultPrevented) return;
773
774 store.setState("valueIndexToChange", index);
775 },
776 [props.onFocus, store, index],
777 );
778
779 const ThumbPrimitive = asChild ? SlotPrimitive.Slot : "div";
780
781 if (value === undefined) return null;
782
783 return (
784 <span style={thumbStyle}>
785 <ThumbPrimitive
786 id={thumbId}
787 role="slider"
788 aria-valuemin={min}
789 aria-valuenow={value}
790 aria-valuemax={max}
791 aria-orientation="vertical"
792 data-disabled={disabled ? "" : undefined}
793 data-slot="angle-slider-thumb"
794 tabIndex={disabled ? undefined : 0}
795 {...thumbProps}
796 ref={composedRef}
797 className={cn(
798 "block size-4 shrink-0 rounded-full border border-primary bg-background shadow-sm ring-ring/50 transition-[color,box-shadow] hover:ring-4 focus-visible:outline-hidden focus-visible:ring-4 disabled:pointer-events-none disabled:opacity-50",
799 className,
800 )}
801 onFocus={onFocus}
802 />
803 {isFormControl && value !== undefined && (
804 <VisuallyHiddenInput
805 key={index}
806 control={thumbElement}
807 name={
808 context.name
809 ? context.name + (values.length > 1 ? "[]" : "")
810 : undefined
811 }
812 form={context.form}
813 value={value.toString()}
814 type="number"
815 min={min}
816 max={max}
817 step={step}
818 disabled={disabled}
819 />
820 )}
821 </span>
822 );
823}
824
825interface AngleSliderValueProps extends DivProps {
826 unit?: string;
827 formatValue?: (value: number | number[]) => string;
828}
829
830function AngleSliderValue(props: AngleSliderValueProps) {
831 const {
832 unit = "°",
833 formatValue,
834 className,
835 style,
836 asChild,
837 children,
838 ...valueProps
839 } = props;
840
841 const values = useStore((state) => state.values);
842 const size = useStore((state) => state.size);
843 const disabled = useStore((state) => state.disabled);
844
845 const center = size + 20;
846
847 const displayValue = React.useMemo(() => {
848 if (formatValue) {
849 return formatValue(values.length === 1 ? (values[0] ?? 0) : values);
850 }
851
852 if (values.length === 1) {
853 return `${values[0] ?? 0}${unit}`;
854 }
855
856 const sortedValues = [...values].sort((a, b) => a - b);
857 return `${sortedValues[0]}${unit} - ${sortedValues[sortedValues.length - 1]}${unit}`;
858 }, [values, formatValue, unit]);
859
860 const valueStyle = React.useMemo<React.CSSProperties>(
861 () => ({
862 position: "absolute",
863 left: `${center}px`,
864 top: `${center}px`,
865 transform: "translate(-50%, -50%)",
866 }),
867 [center],
868 );
869
870 const ValuePrimitive = asChild ? SlotPrimitive.Slot : "div";
871
872 return (
873 <ValuePrimitive
874 data-disabled={disabled ? "" : undefined}
875 data-slot="angle-slider-value"
876 {...valueProps}
877 className={cn(
878 "pointer-events-none flex select-none items-center justify-center font-medium text-foreground text-sm",
879 className,
880 )}
881 style={{
882 ...valueStyle,
883 ...style,
884 }}
885 >
886 {children ?? displayValue}
887 </ValuePrimitive>
888 );
889}
890
891export {
892 AngleSlider,
893 type AngleSliderProps,
894 AngleSliderRange,
895 AngleSliderThumb,
896 AngleSliderTrack,
897 AngleSliderValue,
898 useStore as useAngleSlider,
899};
900