|
| 1 | +import { clamp } from "@keybr/lang"; |
| 2 | +import { |
| 3 | + getBoundingBox, |
| 4 | + useHotkeysHandler, |
| 5 | + useWindowEvent, |
| 6 | +} from "@keybr/widget"; |
| 7 | +import { type CSSProperties, type ReactElement, useRef } from "react"; |
| 8 | +import { type SliderValue } from "./types.ts"; |
| 9 | + |
| 10 | +export function Slider({ |
| 11 | + className, |
| 12 | + style, |
| 13 | + children, |
| 14 | + value: { x, y }, |
| 15 | + onChange, |
| 16 | +}: { |
| 17 | + readonly className: string; |
| 18 | + readonly style?: CSSProperties; |
| 19 | + readonly children: ReactElement; |
| 20 | + readonly value: SliderValue; |
| 21 | + readonly onChange: (value: SliderValue) => void; |
| 22 | +}) { |
| 23 | + const ref = useRef<HTMLDivElement>(null); |
| 24 | + const tracking = useRef(false); |
| 25 | + useWindowEvent("mousemove", (event) => { |
| 26 | + if (tracking.current) { |
| 27 | + event.preventDefault(); |
| 28 | + onChange(getValue(ref.current!, event)); |
| 29 | + } |
| 30 | + }); |
| 31 | + useWindowEvent("mouseup", () => { |
| 32 | + tracking.current = false; |
| 33 | + }); |
| 34 | + const moveLeft = () => { |
| 35 | + if (x > 0) { |
| 36 | + onChange({ x: Math.max(0, x - 0.01), y }); |
| 37 | + } |
| 38 | + }; |
| 39 | + const moveRight = () => { |
| 40 | + if (x < 1) { |
| 41 | + onChange({ x: Math.min(1, x + 0.01), y }); |
| 42 | + } |
| 43 | + }; |
| 44 | + const moveUp = () => { |
| 45 | + if (y < 1) { |
| 46 | + onChange({ x, y: Math.min(1, y + 0.01) }); |
| 47 | + } |
| 48 | + }; |
| 49 | + const moveDown = () => { |
| 50 | + if (y > 0) { |
| 51 | + onChange({ x, y: Math.max(0, y - 0.01) }); |
| 52 | + } |
| 53 | + }; |
| 54 | + return ( |
| 55 | + <div |
| 56 | + ref={ref} |
| 57 | + className={className} |
| 58 | + style={style} |
| 59 | + tabIndex={0} |
| 60 | + onMouseDown={(event) => { |
| 61 | + ref.current!.focus(); |
| 62 | + tracking.current = true; |
| 63 | + event.preventDefault(); |
| 64 | + onChange(getValue(ref.current!, event)); |
| 65 | + }} |
| 66 | + onKeyDown={useHotkeysHandler( |
| 67 | + ["ArrowLeft", moveLeft], |
| 68 | + ["ArrowRight", moveRight], |
| 69 | + ["ArrowUp", moveUp], |
| 70 | + ["ArrowDown", moveDown], |
| 71 | + )} |
| 72 | + > |
| 73 | + {children} |
| 74 | + </div> |
| 75 | + ); |
| 76 | +} |
| 77 | + |
| 78 | +function getValue( |
| 79 | + element: HTMLElement, |
| 80 | + { clientX, clientY }: { readonly clientX: number; readonly clientY: number }, |
| 81 | +): SliderValue { |
| 82 | + const { |
| 83 | + left, // |
| 84 | + top, |
| 85 | + right, |
| 86 | + bottom, |
| 87 | + width, |
| 88 | + height, |
| 89 | + } = getBoundingBox(element, "fixed"); |
| 90 | + return { |
| 91 | + x: (clamp(clientX, left, right) - left) / width, |
| 92 | + y: 1 - (clamp(clientY, top, bottom) - top) / height, |
| 93 | + }; |
| 94 | +} |
0 commit comments