components/linyi/slider.tsx
@base-ui/reactclass-variance-authority
"use client"; import * as React from "react";import { Slider as BaseSlider } from "@base-ui/react/slider";import { cva, type VariantProps } from "class-variance-authority";import { cn } from "@/lib/cn"; export const sliderTrackVariants = cva( "relative w-full rounded-full bg-well border border-line-well overflow-visible", { variants: { size: { sm: "h-1", md: "h-1.5", }, }, defaultVariants: { size: "md", }, }); export const sliderThumbVariants = cva( "block rounded-full bg-white border-[1.5px] border-accent shadow-[0_2px_6px_rgba(0,0,0,0.22)] transition-transform duration-150 hover:scale-110 active:scale-95 outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-canvas", { variants: { size: { sm: "w-3.5 h-3.5", md: "w-4 h-4", }, }, defaultVariants: { size: "md", }, }); export interface SliderProps extends React.ComponentPropsWithRef<typeof BaseSlider.Root>, VariantProps<typeof sliderTrackVariants> { label?: string; unit?: string; showValue?: boolean; showTicks?: boolean; tickCount?: number;} export function Slider({ className, size = "md", label, unit = "", showValue = false, showTicks = false, tickCount = 5, value, defaultValue, ...props}: SliderProps) { const initialVal = value ?? defaultValue; const thumbCount = Array.isArray(initialVal) ? initialVal.length : 1; return ( <BaseSlider.Root value={value} defaultValue={defaultValue} className={cn("w-full select-none space-y-2", className)} {...props} > {(label || showValue) && ( <div className="flex items-center justify-between gap-2 text-xs"> {label ? ( <BaseSlider.Label className="font-medium text-fg">{label}</BaseSlider.Label> ) : ( <span /> )} {showValue && ( <BaseSlider.Value className="font-mono-num text-accent"> {(formattedValues) => formattedValues.length > 1 ? `${formattedValues[0]}${unit} – ${formattedValues[1]}${unit}` : `${formattedValues[0]}${unit}` } </BaseSlider.Value> )} </div> )} <BaseSlider.Control className="relative flex w-full touch-none items-center py-2 cursor-pointer data-[disabled]:opacity-45 data-[disabled]:cursor-not-allowed"> <BaseSlider.Track className={sliderTrackVariants({ size })}> <BaseSlider.Indicator className="h-full rounded-full bg-accent" /> {Array.from({ length: thumbCount }).map((_, idx) => ( <BaseSlider.Thumb key={idx} index={idx} className={sliderThumbVariants({ size })} /> ))} </BaseSlider.Track> </BaseSlider.Control> {showTicks && tickCount >= 2 && ( <div className="flex items-center justify-between px-0.5" aria-hidden="true"> {Array.from({ length: tickCount }).map((_, idx) => ( <span key={idx} className={cn( "w-px bg-line-strong", idx === 0 || idx === tickCount - 1 ? "h-2" : "h-1.5 opacity-70" )} /> ))} </div> )} </BaseSlider.Root> );}