first commit

This commit is contained in:
2026-06-24 09:48:54 +02:00
commit 41e62ddcad
33739 changed files with 4266226 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 WorkOS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3
View File
@@ -0,0 +1,3 @@
# `react-slider`
View docs [here](https://radix-ui.com/primitives/docs/components/slider).
+102
View File
@@ -0,0 +1,102 @@
import * as react_jsx_runtime from 'react/jsx-runtime';
import * as _radix_ui_react_context from '@radix-ui/react-context';
import { Scope } from '@radix-ui/react-context';
import * as React from 'react';
import { Primitive } from '@radix-ui/react-primitive';
type Direction = 'ltr' | 'rtl';
declare global {
interface FocusOptions {
/**
* A boolean value that should be set to `true` to force, or `false` to prevent
* visible indication that the element is focused. If the property is not
* specified, a browser will provide visible indication if it determines
* that this would improve accessibility for users.
*
* @see
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#focusvisible
*/
focusVisible?: boolean;
}
}
type ScopedProps<P> = P & {
__scopeSlider?: Scope;
};
declare const createSliderScope: _radix_ui_react_context.CreateScope;
interface SliderProps extends Omit<SliderHorizontalProps | SliderVerticalProps, keyof SliderOrientationPrivateProps | 'defaultValue'> {
name?: string;
disabled?: boolean;
orientation?: React.AriaAttributes['aria-orientation'];
dir?: Direction;
min?: number;
max?: number;
step?: number;
minStepsBetweenThumbs?: number;
value?: number[];
defaultValue?: number[];
onValueChange?(value: number[]): void;
onValueCommit?(value: number[]): void;
inverted?: boolean;
form?: string;
}
declare const Slider: React.ForwardRefExoticComponent<SliderProps & React.RefAttributes<HTMLSpanElement>>;
type SliderOrientationPrivateProps = {
min: number;
max: number;
inverted: boolean;
onSlideStart?(value: number): void;
onSlideMove?(value: number): void;
onSlideEnd?(): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(step: {
event: React.KeyboardEvent;
direction: number;
}): void;
};
interface SliderOrientationProps extends Omit<SliderImplProps, keyof SliderImplPrivateProps>, SliderOrientationPrivateProps {
}
interface SliderHorizontalProps extends SliderOrientationProps {
dir?: Direction;
}
interface SliderVerticalProps extends SliderOrientationProps {
}
type PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;
type SliderImplPrivateProps = {
onSlideStart(event: React.PointerEvent): void;
onSlideMove(event: React.PointerEvent): void;
onSlideEnd(event: React.PointerEvent): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(event: React.KeyboardEvent): void;
};
interface SliderImplProps extends PrimitiveDivProps, SliderImplPrivateProps {
}
type PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;
interface SliderTrackProps extends PrimitiveSpanProps {
}
declare const SliderTrack: React.ForwardRefExoticComponent<SliderTrackProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderRangeProps extends PrimitiveSpanProps {
}
declare const SliderRange: React.ForwardRefExoticComponent<SliderRangeProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderThumbProviderProps {
name?: string;
children?: React.ReactNode;
}
declare function SliderThumbProvider(props: ScopedProps<SliderThumbProviderProps>): react_jsx_runtime.JSX.Element;
declare namespace SliderThumbProvider {
var displayName: string;
}
interface SliderThumbTriggerProps extends PrimitiveSpanProps {
}
declare const SliderThumbTrigger: React.ForwardRefExoticComponent<SliderThumbTriggerProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderThumbProps extends SliderThumbTriggerProps {
name?: string;
}
declare const SliderThumb: React.ForwardRefExoticComponent<SliderThumbProps & React.RefAttributes<HTMLSpanElement>>;
type PrimitiveInputProps = React.ComponentPropsWithoutRef<typeof Primitive.input>;
interface SliderBubbleInputProps extends Omit<PrimitiveInputProps, 'value'> {
}
declare const SliderBubbleInput: React.ForwardRefExoticComponent<SliderBubbleInputProps & React.RefAttributes<HTMLInputElement>>;
export { SliderRange as Range, Slider as Root, Slider, type SliderProps, SliderRange, type SliderRangeProps, SliderThumb, type SliderThumbProps, SliderTrack, type SliderTrackProps, SliderThumb as Thumb, SliderTrack as Track, createSliderScope, SliderBubbleInput as unstable_BubbleInput, SliderBubbleInput as unstable_SliderBubbleInput, type SliderBubbleInputProps as unstable_SliderBubbleInputProps, SliderThumbProvider as unstable_SliderThumbProvider, type SliderThumbProviderProps as unstable_SliderThumbProviderProps, SliderThumbTrigger as unstable_SliderThumbTrigger, type SliderThumbTriggerProps as unstable_SliderThumbTriggerProps, SliderThumbProvider as unstable_ThumbProvider, SliderThumbTrigger as unstable_ThumbTrigger };
+102
View File
@@ -0,0 +1,102 @@
import * as react_jsx_runtime from 'react/jsx-runtime';
import * as _radix_ui_react_context from '@radix-ui/react-context';
import { Scope } from '@radix-ui/react-context';
import * as React from 'react';
import { Primitive } from '@radix-ui/react-primitive';
type Direction = 'ltr' | 'rtl';
declare global {
interface FocusOptions {
/**
* A boolean value that should be set to `true` to force, or `false` to prevent
* visible indication that the element is focused. If the property is not
* specified, a browser will provide visible indication if it determines
* that this would improve accessibility for users.
*
* @see
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#focusvisible
*/
focusVisible?: boolean;
}
}
type ScopedProps<P> = P & {
__scopeSlider?: Scope;
};
declare const createSliderScope: _radix_ui_react_context.CreateScope;
interface SliderProps extends Omit<SliderHorizontalProps | SliderVerticalProps, keyof SliderOrientationPrivateProps | 'defaultValue'> {
name?: string;
disabled?: boolean;
orientation?: React.AriaAttributes['aria-orientation'];
dir?: Direction;
min?: number;
max?: number;
step?: number;
minStepsBetweenThumbs?: number;
value?: number[];
defaultValue?: number[];
onValueChange?(value: number[]): void;
onValueCommit?(value: number[]): void;
inverted?: boolean;
form?: string;
}
declare const Slider: React.ForwardRefExoticComponent<SliderProps & React.RefAttributes<HTMLSpanElement>>;
type SliderOrientationPrivateProps = {
min: number;
max: number;
inverted: boolean;
onSlideStart?(value: number): void;
onSlideMove?(value: number): void;
onSlideEnd?(): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(step: {
event: React.KeyboardEvent;
direction: number;
}): void;
};
interface SliderOrientationProps extends Omit<SliderImplProps, keyof SliderImplPrivateProps>, SliderOrientationPrivateProps {
}
interface SliderHorizontalProps extends SliderOrientationProps {
dir?: Direction;
}
interface SliderVerticalProps extends SliderOrientationProps {
}
type PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;
type SliderImplPrivateProps = {
onSlideStart(event: React.PointerEvent): void;
onSlideMove(event: React.PointerEvent): void;
onSlideEnd(event: React.PointerEvent): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(event: React.KeyboardEvent): void;
};
interface SliderImplProps extends PrimitiveDivProps, SliderImplPrivateProps {
}
type PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;
interface SliderTrackProps extends PrimitiveSpanProps {
}
declare const SliderTrack: React.ForwardRefExoticComponent<SliderTrackProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderRangeProps extends PrimitiveSpanProps {
}
declare const SliderRange: React.ForwardRefExoticComponent<SliderRangeProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderThumbProviderProps {
name?: string;
children?: React.ReactNode;
}
declare function SliderThumbProvider(props: ScopedProps<SliderThumbProviderProps>): react_jsx_runtime.JSX.Element;
declare namespace SliderThumbProvider {
var displayName: string;
}
interface SliderThumbTriggerProps extends PrimitiveSpanProps {
}
declare const SliderThumbTrigger: React.ForwardRefExoticComponent<SliderThumbTriggerProps & React.RefAttributes<HTMLSpanElement>>;
interface SliderThumbProps extends SliderThumbTriggerProps {
name?: string;
}
declare const SliderThumb: React.ForwardRefExoticComponent<SliderThumbProps & React.RefAttributes<HTMLSpanElement>>;
type PrimitiveInputProps = React.ComponentPropsWithoutRef<typeof Primitive.input>;
interface SliderBubbleInputProps extends Omit<PrimitiveInputProps, 'value'> {
}
declare const SliderBubbleInput: React.ForwardRefExoticComponent<SliderBubbleInputProps & React.RefAttributes<HTMLInputElement>>;
export { SliderRange as Range, Slider as Root, Slider, type SliderProps, SliderRange, type SliderRangeProps, SliderThumb, type SliderThumbProps, SliderTrack, type SliderTrackProps, SliderThumb as Thumb, SliderTrack as Track, createSliderScope, SliderBubbleInput as unstable_BubbleInput, SliderBubbleInput as unstable_SliderBubbleInput, type SliderBubbleInputProps as unstable_SliderBubbleInputProps, SliderThumbProvider as unstable_SliderThumbProvider, type SliderThumbProviderProps as unstable_SliderThumbProviderProps, SliderThumbTrigger as unstable_SliderThumbTrigger, type SliderThumbTriggerProps as unstable_SliderThumbTriggerProps, SliderThumbProvider as unstable_ThumbProvider, SliderThumbTrigger as unstable_ThumbTrigger };
+677
View File
@@ -0,0 +1,677 @@
"use strict";
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
Range: () => SliderRange,
Root: () => Slider,
Slider: () => Slider,
SliderRange: () => SliderRange,
SliderThumb: () => SliderThumb,
SliderTrack: () => SliderTrack,
Thumb: () => SliderThumb,
Track: () => SliderTrack,
createSliderScope: () => createSliderScope,
unstable_BubbleInput: () => SliderBubbleInput,
unstable_SliderBubbleInput: () => SliderBubbleInput,
unstable_SliderThumbProvider: () => SliderThumbProvider,
unstable_SliderThumbTrigger: () => SliderThumbTrigger,
unstable_ThumbProvider: () => SliderThumbProvider,
unstable_ThumbTrigger: () => SliderThumbTrigger
});
module.exports = __toCommonJS(index_exports);
// src/slider.tsx
var React = __toESM(require("react"));
var import_number = require("@radix-ui/number");
var import_primitive = require("@radix-ui/primitive");
var import_react_compose_refs = require("@radix-ui/react-compose-refs");
var import_react_context = require("@radix-ui/react-context");
var import_react_use_controllable_state = require("@radix-ui/react-use-controllable-state");
var import_react_direction = require("@radix-ui/react-direction");
var import_react_use_previous = require("@radix-ui/react-use-previous");
var import_react_use_size = require("@radix-ui/react-use-size");
var import_react_primitive = require("@radix-ui/react-primitive");
var import_react_collection = require("@radix-ui/react-collection");
var import_jsx_runtime = require("react/jsx-runtime");
var PAGE_KEYS = ["PageUp", "PageDown"];
var ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
var BACK_KEYS = {
"from-left": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
"from-right": ["Home", "PageDown", "ArrowDown", "ArrowRight"],
"from-bottom": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
"from-top": ["Home", "PageDown", "ArrowUp", "ArrowLeft"]
};
var SLIDER_NAME = "Slider";
var [Collection, useCollection, createCollectionScope] = (0, import_react_collection.createCollection)(SLIDER_NAME);
var [createSliderContext, createSliderScope] = (0, import_react_context.createContextScope)(SLIDER_NAME, [
createCollectionScope
]);
var [SliderProvider, useSliderContext] = createSliderContext(SLIDER_NAME);
var Slider = React.forwardRef(
(props, forwardedRef) => {
const {
name,
min = 0,
max = 100,
step = 1,
orientation = "horizontal",
disabled = false,
minStepsBetweenThumbs = 0,
defaultValue = [min],
value,
onValueChange = () => {
},
onValueCommit = () => {
},
inverted = false,
form,
...sliderProps
} = props;
const thumbRefs = React.useRef(/* @__PURE__ */ new Set());
const valueIndexToChangeRef = React.useRef(0);
const isKeyboardInteractionRef = React.useRef(false);
const isHorizontal = orientation === "horizontal";
const SliderOrientation = isHorizontal ? SliderHorizontal : SliderVertical;
const [values = [], setValues] = (0, import_react_use_controllable_state.useControllableState)({
prop: value,
defaultProp: defaultValue,
onChange: (value2) => {
const thumbs = [...thumbRefs.current];
thumbs[valueIndexToChangeRef.current]?.focus({
preventScroll: true,
focusVisible: isKeyboardInteractionRef.current
});
isKeyboardInteractionRef.current = false;
onValueChange(value2);
}
});
const valuesBeforeSlideStartRef = React.useRef(values);
function handleSlideStart(value2) {
const closestIndex = getClosestValueIndex(values, value2);
updateValues(value2, closestIndex);
}
function handleSlideMove(value2) {
updateValues(value2, valueIndexToChangeRef.current);
}
function handleSlideEnd() {
const prevValue = valuesBeforeSlideStartRef.current[valueIndexToChangeRef.current];
const nextValue = values[valueIndexToChangeRef.current];
const hasChanged = nextValue !== prevValue;
if (hasChanged) onValueCommit(values);
}
function updateValues(value2, atIndex, { commit } = { commit: false }) {
const decimalCount = getDecimalCount(step);
const snapToStep = roundValue(Math.round((value2 - min) / step) * step + min, decimalCount);
const nextValue = (0, import_number.clamp)(snapToStep, [min, max]);
setValues((prevValues = []) => {
const nextValues = getNextSortedValues(prevValues, nextValue, atIndex);
if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) {
valueIndexToChangeRef.current = nextValues.indexOf(nextValue);
const hasChanged = String(nextValues) !== String(prevValues);
if (hasChanged && commit) onValueCommit(nextValues);
return hasChanged ? nextValues : prevValues;
} else {
return prevValues;
}
});
}
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderProvider,
{
scope: props.__scopeSlider,
name,
disabled,
min,
max,
valueIndexToChangeRef,
thumbs: thumbRefs.current,
values,
orientation,
form,
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Collection.Provider, { scope: props.__scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Collection.Slot, { scope: props.__scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderOrientation,
{
"aria-disabled": disabled,
"data-disabled": disabled ? "" : void 0,
...sliderProps,
ref: forwardedRef,
onPointerDown: (0, import_primitive.composeEventHandlers)(sliderProps.onPointerDown, () => {
if (!disabled) {
valuesBeforeSlideStartRef.current = values;
isKeyboardInteractionRef.current = false;
}
}),
min,
max,
inverted,
onSlideStart: disabled ? void 0 : handleSlideStart,
onSlideMove: disabled ? void 0 : handleSlideMove,
onSlideEnd: disabled ? void 0 : handleSlideEnd,
onHomeKeyDown: () => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
updateValues(min, 0, { commit: true });
}
},
onEndKeyDown: () => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
updateValues(max, values.length - 1, { commit: true });
}
},
onStepKeyDown: ({ event, direction: stepDirection }) => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
const isPageKey = PAGE_KEYS.includes(event.key);
const isSkipKey = isPageKey || event.shiftKey && ARROW_KEYS.includes(event.key);
const multiplier = isSkipKey ? 10 : 1;
const atIndex = valueIndexToChangeRef.current;
const value2 = values[atIndex];
const stepInDirection = step * multiplier * stepDirection;
updateValues(value2 + stepInDirection, atIndex, { commit: true });
}
}
}
) }) })
}
);
}
);
Slider.displayName = SLIDER_NAME;
var [SliderOrientationProvider, useSliderOrientationContext] = createSliderContext(SLIDER_NAME, {
startEdge: "left",
endEdge: "right",
size: "width",
direction: 1
});
var SliderHorizontal = React.forwardRef(
(props, forwardedRef) => {
const {
min,
max,
dir,
inverted,
onSlideStart,
onSlideMove,
onSlideEnd,
onStepKeyDown,
...sliderProps
} = props;
const [slider, setSlider] = React.useState(null);
const composedRefs = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, (node) => setSlider(node));
const rectRef = React.useRef(void 0);
const direction = (0, import_react_direction.useDirection)(dir);
const isDirectionLTR = direction === "ltr";
const isSlidingFromLeft = isDirectionLTR && !inverted || !isDirectionLTR && inverted;
function getValueFromPointer(pointerPosition) {
const rect = rectRef.current || slider.getBoundingClientRect();
const input = [0, rect.width];
const output = isSlidingFromLeft ? [min, max] : [max, min];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.left);
}
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderOrientationProvider,
{
scope: props.__scopeSlider,
startEdge: isSlidingFromLeft ? "left" : "right",
endEdge: isSlidingFromLeft ? "right" : "left",
direction: isSlidingFromLeft ? 1 : -1,
size: "width",
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderImpl,
{
dir: direction,
"data-orientation": "horizontal",
...sliderProps,
ref: composedRefs,
style: {
...sliderProps.style,
"--radix-slider-thumb-transform": "translateX(-50%)"
},
onSlideStart: (event) => {
const value = getValueFromPointer(event.clientX);
onSlideStart?.(value);
},
onSlideMove: (event) => {
const value = getValueFromPointer(event.clientX);
onSlideMove?.(value);
},
onSlideEnd: () => {
rectRef.current = void 0;
onSlideEnd?.();
},
onStepKeyDown: (event) => {
const slideDirection = isSlidingFromLeft ? "from-left" : "from-right";
const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}
}
)
}
);
}
);
var SliderVertical = React.forwardRef(
(props, forwardedRef) => {
const {
min,
max,
inverted,
onSlideStart,
onSlideMove,
onSlideEnd,
onStepKeyDown,
...sliderProps
} = props;
const sliderRef = React.useRef(null);
const ref = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, sliderRef);
const rectRef = React.useRef(void 0);
const isSlidingFromBottom = !inverted;
function getValueFromPointer(pointerPosition) {
const rect = rectRef.current || sliderRef.current.getBoundingClientRect();
const input = [0, rect.height];
const output = isSlidingFromBottom ? [max, min] : [min, max];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.top);
}
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderOrientationProvider,
{
scope: props.__scopeSlider,
startEdge: isSlidingFromBottom ? "bottom" : "top",
endEdge: isSlidingFromBottom ? "top" : "bottom",
size: "height",
direction: isSlidingFromBottom ? 1 : -1,
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderImpl,
{
"data-orientation": "vertical",
...sliderProps,
ref,
style: {
...sliderProps.style,
"--radix-slider-thumb-transform": "translateY(50%)"
},
onSlideStart: (event) => {
const value = getValueFromPointer(event.clientY);
onSlideStart?.(value);
},
onSlideMove: (event) => {
const value = getValueFromPointer(event.clientY);
onSlideMove?.(value);
},
onSlideEnd: () => {
rectRef.current = void 0;
onSlideEnd?.();
},
onStepKeyDown: (event) => {
const slideDirection = isSlidingFromBottom ? "from-bottom" : "from-top";
const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}
}
)
}
);
}
);
var SliderImpl = React.forwardRef(
(props, forwardedRef) => {
const {
__scopeSlider,
onSlideStart,
onSlideMove,
onSlideEnd,
onHomeKeyDown,
onEndKeyDown,
onStepKeyDown,
...sliderProps
} = props;
const context = useSliderContext(SLIDER_NAME, __scopeSlider);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_primitive.Primitive.span,
{
...sliderProps,
ref: forwardedRef,
onKeyDown: (0, import_primitive.composeEventHandlers)(props.onKeyDown, (event) => {
if (event.key === "Home") {
onHomeKeyDown(event);
event.preventDefault();
} else if (event.key === "End") {
onEndKeyDown(event);
event.preventDefault();
} else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
onStepKeyDown(event);
event.preventDefault();
}
}),
onPointerDown: (0, import_primitive.composeEventHandlers)(props.onPointerDown, (event) => {
const target = event.target;
target.setPointerCapture(event.pointerId);
event.preventDefault();
if (context.thumbs.has(target)) {
target.focus({ preventScroll: true, focusVisible: false });
} else {
onSlideStart(event);
}
}),
onPointerMove: (0, import_primitive.composeEventHandlers)(props.onPointerMove, (event) => {
const target = event.target;
if (target.hasPointerCapture(event.pointerId)) onSlideMove(event);
}),
onPointerUp: (0, import_primitive.composeEventHandlers)(props.onPointerUp, (event) => {
const target = event.target;
if (target.hasPointerCapture(event.pointerId)) {
target.releasePointerCapture(event.pointerId);
onSlideEnd(event);
}
})
}
);
}
);
var TRACK_NAME = "SliderTrack";
var SliderTrack = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...trackProps } = props;
const context = useSliderContext(TRACK_NAME, __scopeSlider);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_primitive.Primitive.span,
{
"data-disabled": context.disabled ? "" : void 0,
"data-orientation": context.orientation,
...trackProps,
ref: forwardedRef
}
);
}
);
SliderTrack.displayName = TRACK_NAME;
var RANGE_NAME = "SliderRange";
var SliderRange = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...rangeProps } = props;
const context = useSliderContext(RANGE_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(RANGE_NAME, __scopeSlider);
const ref = React.useRef(null);
const composedRefs = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, ref);
const valuesCount = context.values.length;
const percentages = context.values.map(
(value) => convertValueToPercentage(value, context.min, context.max)
);
const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0;
const offsetEnd = 100 - Math.max(...percentages);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_primitive.Primitive.span,
{
"data-orientation": context.orientation,
"data-disabled": context.disabled ? "" : void 0,
...rangeProps,
ref: composedRefs,
style: {
...props.style,
[orientation.startEdge]: offsetStart + "%",
[orientation.endEdge]: offsetEnd + "%"
}
}
);
}
);
SliderRange.displayName = RANGE_NAME;
var THUMB_NAME = "SliderThumb";
var [SliderThumbContextProvider, useSliderThumbContext] = createSliderContext(THUMB_NAME);
var THUMB_PROVIDER_NAME = "SliderThumbProvider";
function SliderThumbProvider(props) {
const {
__scopeSlider,
name,
children,
// @ts-expect-error internal render prop
internal_do_not_use_render
} = props;
const context = useSliderContext(THUMB_PROVIDER_NAME, __scopeSlider);
const getItems = useCollection(__scopeSlider);
const [thumb, setThumb] = React.useState(null);
const index = React.useMemo(
() => thumb ? getItems().findIndex((item) => item.ref.current === thumb) : -1,
[getItems, thumb]
);
const size = (0, import_react_use_size.useSize)(thumb);
const isFormControl = thumb ? !!context.form || !!thumb.closest("form") : true;
const value = context.values[index];
const resolvedName = name ?? (context.name ? context.name + (context.values.length > 1 ? "[]" : "") : void 0);
const percent = value === void 0 ? 0 : convertValueToPercentage(value, context.min, context.max);
React.useEffect(() => {
if (thumb) {
context.thumbs.add(thumb);
return () => {
context.thumbs.delete(thumb);
};
}
}, [thumb, context.thumbs]);
const thumbContext = {
value,
name: resolvedName,
form: context.form,
isFormControl,
index,
thumb,
onThumbChange: setThumb,
percent,
size
};
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SliderThumbContextProvider, { scope: __scopeSlider, ...thumbContext, children: isFunction(internal_do_not_use_render) ? internal_do_not_use_render(thumbContext) : children });
}
SliderThumbProvider.displayName = THUMB_PROVIDER_NAME;
var THUMB_TRIGGER_NAME = "SliderThumbTrigger";
var SliderThumbTrigger = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...thumbProps } = props;
const context = useSliderContext(THUMB_TRIGGER_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(THUMB_TRIGGER_NAME, __scopeSlider);
const { index, value, percent, size, onThumbChange } = useSliderThumbContext(
THUMB_TRIGGER_NAME,
__scopeSlider
);
const composedRefs = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, (node) => onThumbChange(node));
const label = getLabel(index, context.values.length);
const orientationSize = size?.[orientation.size];
const thumbInBoundsOffset = orientationSize ? getThumbInBoundsOffset(orientationSize, percent, orientation.direction) : 0;
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"span",
{
style: {
transform: "var(--radix-slider-thumb-transform)",
position: "absolute",
[orientation.startEdge]: `calc(${percent}% + ${thumbInBoundsOffset}px)`
},
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Collection.ItemSlot, { scope: __scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_primitive.Primitive.span,
{
role: "slider",
"aria-label": props["aria-label"] || label,
"aria-valuemin": context.min,
"aria-valuenow": value,
"aria-valuemax": context.max,
"aria-orientation": context.orientation,
"data-orientation": context.orientation,
"data-disabled": context.disabled ? "" : void 0,
tabIndex: context.disabled ? void 0 : 0,
...thumbProps,
ref: composedRefs,
style: value === void 0 ? { display: "none" } : props.style,
onFocus: (0, import_primitive.composeEventHandlers)(props.onFocus, () => {
context.valueIndexToChangeRef.current = index;
})
}
) })
}
);
}
);
SliderThumbTrigger.displayName = THUMB_TRIGGER_NAME;
var SliderThumb = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, name, ...thumbProps } = props;
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderThumbProvider,
{
__scopeSlider,
name,
internal_do_not_use_render: ({ index, isFormControl }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderThumbTrigger,
{
...thumbProps,
ref: forwardedRef,
__scopeSlider
}
),
isFormControl ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
SliderBubbleInput,
{
__scopeSlider
},
index
) : null
] })
}
);
}
);
SliderThumb.displayName = THUMB_NAME;
var BUBBLE_INPUT_NAME = "SliderBubbleInput";
var SliderBubbleInput = React.forwardRef(
({ __scopeSlider, ...props }, forwardedRef) => {
const { value, name, form } = useSliderThumbContext(BUBBLE_INPUT_NAME, __scopeSlider);
const ref = React.useRef(null);
const composedRefs = (0, import_react_compose_refs.useComposedRefs)(ref, forwardedRef);
const prevValue = (0, import_react_use_previous.usePrevious)(value);
React.useEffect(() => {
const input = ref.current;
if (!input) return;
const inputProto = window.HTMLInputElement.prototype;
const descriptor = Object.getOwnPropertyDescriptor(inputProto, "value");
const setValue = descriptor.set;
if (prevValue !== value && setValue) {
const event = new Event("input", { bubbles: true });
setValue.call(input, value);
input.dispatchEvent(event);
}
}, [prevValue, value]);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_react_primitive.Primitive.input,
{
style: { display: "none" },
name,
form,
...props,
ref: composedRefs,
defaultValue: value
}
);
}
);
SliderBubbleInput.displayName = BUBBLE_INPUT_NAME;
function getNextSortedValues(prevValues = [], nextValue, atIndex) {
const nextValues = [...prevValues];
nextValues[atIndex] = nextValue;
return nextValues.sort((a, b) => a - b);
}
function convertValueToPercentage(value, min, max) {
const maxSteps = max - min;
const percentPerStep = 100 / maxSteps;
const percentage = percentPerStep * (value - min);
return (0, import_number.clamp)(percentage, [0, 100]);
}
function getLabel(index, totalValues) {
if (totalValues > 2) {
return `Value ${index + 1} of ${totalValues}`;
} else if (totalValues === 2) {
return ["Minimum", "Maximum"][index];
} else {
return void 0;
}
}
function getClosestValueIndex(values, nextValue) {
if (values.length === 1) return 0;
const distances = values.map((value) => Math.abs(value - nextValue));
const closestDistance = Math.min(...distances);
return distances.indexOf(closestDistance);
}
function getThumbInBoundsOffset(width, left, direction) {
const halfWidth = width / 2;
const halfPercent = 50;
const offset = linearScale([0, halfPercent], [0, halfWidth]);
return (halfWidth - offset(left) * direction) * direction;
}
function getStepsBetweenValues(values) {
return values.slice(0, -1).map((value, index) => values[index + 1] - value);
}
function hasMinStepsBetweenValues(values, minStepsBetweenValues) {
if (minStepsBetweenValues > 0) {
const stepsBetweenValues = getStepsBetweenValues(values);
const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues);
return actualMinStepsBetweenValues >= minStepsBetweenValues;
}
return true;
}
function linearScale(input, output) {
return (value) => {
if (input[0] === input[1] || output[0] === output[1]) return output[0];
const ratio = (output[1] - output[0]) / (input[1] - input[0]);
return output[0] + ratio * (value - input[0]);
};
}
function getDecimalCount(value) {
if (!Number.isFinite(value)) return 0;
const str = value.toString();
if (str.includes("e")) {
const [coefficient, exponent] = str.split("e");
const decimalPart2 = coefficient.split(".")[1] || "";
const exponentNum = Number(exponent);
return Math.max(0, decimalPart2.length - exponentNum);
}
const decimalPart = str.split(".")[1];
return decimalPart ? decimalPart.length : 0;
}
function roundValue(value, decimalCount) {
const rounder = Math.pow(10, decimalCount);
return Math.round(value * rounder) / rounder;
}
function isFunction(value) {
return typeof value === "function";
}
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+645
View File
@@ -0,0 +1,645 @@
"use client";
// src/slider.tsx
import * as React from "react";
import { clamp } from "@radix-ui/number";
import { composeEventHandlers } from "@radix-ui/primitive";
import { useComposedRefs } from "@radix-ui/react-compose-refs";
import { createContextScope } from "@radix-ui/react-context";
import { useControllableState } from "@radix-ui/react-use-controllable-state";
import { useDirection } from "@radix-ui/react-direction";
import { usePrevious } from "@radix-ui/react-use-previous";
import { useSize } from "@radix-ui/react-use-size";
import { Primitive } from "@radix-ui/react-primitive";
import { createCollection } from "@radix-ui/react-collection";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var PAGE_KEYS = ["PageUp", "PageDown"];
var ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
var BACK_KEYS = {
"from-left": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
"from-right": ["Home", "PageDown", "ArrowDown", "ArrowRight"],
"from-bottom": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
"from-top": ["Home", "PageDown", "ArrowUp", "ArrowLeft"]
};
var SLIDER_NAME = "Slider";
var [Collection, useCollection, createCollectionScope] = createCollection(SLIDER_NAME);
var [createSliderContext, createSliderScope] = createContextScope(SLIDER_NAME, [
createCollectionScope
]);
var [SliderProvider, useSliderContext] = createSliderContext(SLIDER_NAME);
var Slider = React.forwardRef(
(props, forwardedRef) => {
const {
name,
min = 0,
max = 100,
step = 1,
orientation = "horizontal",
disabled = false,
minStepsBetweenThumbs = 0,
defaultValue = [min],
value,
onValueChange = () => {
},
onValueCommit = () => {
},
inverted = false,
form,
...sliderProps
} = props;
const thumbRefs = React.useRef(/* @__PURE__ */ new Set());
const valueIndexToChangeRef = React.useRef(0);
const isKeyboardInteractionRef = React.useRef(false);
const isHorizontal = orientation === "horizontal";
const SliderOrientation = isHorizontal ? SliderHorizontal : SliderVertical;
const [values = [], setValues] = useControllableState({
prop: value,
defaultProp: defaultValue,
onChange: (value2) => {
const thumbs = [...thumbRefs.current];
thumbs[valueIndexToChangeRef.current]?.focus({
preventScroll: true,
focusVisible: isKeyboardInteractionRef.current
});
isKeyboardInteractionRef.current = false;
onValueChange(value2);
}
});
const valuesBeforeSlideStartRef = React.useRef(values);
function handleSlideStart(value2) {
const closestIndex = getClosestValueIndex(values, value2);
updateValues(value2, closestIndex);
}
function handleSlideMove(value2) {
updateValues(value2, valueIndexToChangeRef.current);
}
function handleSlideEnd() {
const prevValue = valuesBeforeSlideStartRef.current[valueIndexToChangeRef.current];
const nextValue = values[valueIndexToChangeRef.current];
const hasChanged = nextValue !== prevValue;
if (hasChanged) onValueCommit(values);
}
function updateValues(value2, atIndex, { commit } = { commit: false }) {
const decimalCount = getDecimalCount(step);
const snapToStep = roundValue(Math.round((value2 - min) / step) * step + min, decimalCount);
const nextValue = clamp(snapToStep, [min, max]);
setValues((prevValues = []) => {
const nextValues = getNextSortedValues(prevValues, nextValue, atIndex);
if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) {
valueIndexToChangeRef.current = nextValues.indexOf(nextValue);
const hasChanged = String(nextValues) !== String(prevValues);
if (hasChanged && commit) onValueCommit(nextValues);
return hasChanged ? nextValues : prevValues;
} else {
return prevValues;
}
});
}
return /* @__PURE__ */ jsx(
SliderProvider,
{
scope: props.__scopeSlider,
name,
disabled,
min,
max,
valueIndexToChangeRef,
thumbs: thumbRefs.current,
values,
orientation,
form,
children: /* @__PURE__ */ jsx(Collection.Provider, { scope: props.__scopeSlider, children: /* @__PURE__ */ jsx(Collection.Slot, { scope: props.__scopeSlider, children: /* @__PURE__ */ jsx(
SliderOrientation,
{
"aria-disabled": disabled,
"data-disabled": disabled ? "" : void 0,
...sliderProps,
ref: forwardedRef,
onPointerDown: composeEventHandlers(sliderProps.onPointerDown, () => {
if (!disabled) {
valuesBeforeSlideStartRef.current = values;
isKeyboardInteractionRef.current = false;
}
}),
min,
max,
inverted,
onSlideStart: disabled ? void 0 : handleSlideStart,
onSlideMove: disabled ? void 0 : handleSlideMove,
onSlideEnd: disabled ? void 0 : handleSlideEnd,
onHomeKeyDown: () => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
updateValues(min, 0, { commit: true });
}
},
onEndKeyDown: () => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
updateValues(max, values.length - 1, { commit: true });
}
},
onStepKeyDown: ({ event, direction: stepDirection }) => {
if (!disabled) {
isKeyboardInteractionRef.current = true;
const isPageKey = PAGE_KEYS.includes(event.key);
const isSkipKey = isPageKey || event.shiftKey && ARROW_KEYS.includes(event.key);
const multiplier = isSkipKey ? 10 : 1;
const atIndex = valueIndexToChangeRef.current;
const value2 = values[atIndex];
const stepInDirection = step * multiplier * stepDirection;
updateValues(value2 + stepInDirection, atIndex, { commit: true });
}
}
}
) }) })
}
);
}
);
Slider.displayName = SLIDER_NAME;
var [SliderOrientationProvider, useSliderOrientationContext] = createSliderContext(SLIDER_NAME, {
startEdge: "left",
endEdge: "right",
size: "width",
direction: 1
});
var SliderHorizontal = React.forwardRef(
(props, forwardedRef) => {
const {
min,
max,
dir,
inverted,
onSlideStart,
onSlideMove,
onSlideEnd,
onStepKeyDown,
...sliderProps
} = props;
const [slider, setSlider] = React.useState(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setSlider(node));
const rectRef = React.useRef(void 0);
const direction = useDirection(dir);
const isDirectionLTR = direction === "ltr";
const isSlidingFromLeft = isDirectionLTR && !inverted || !isDirectionLTR && inverted;
function getValueFromPointer(pointerPosition) {
const rect = rectRef.current || slider.getBoundingClientRect();
const input = [0, rect.width];
const output = isSlidingFromLeft ? [min, max] : [max, min];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.left);
}
return /* @__PURE__ */ jsx(
SliderOrientationProvider,
{
scope: props.__scopeSlider,
startEdge: isSlidingFromLeft ? "left" : "right",
endEdge: isSlidingFromLeft ? "right" : "left",
direction: isSlidingFromLeft ? 1 : -1,
size: "width",
children: /* @__PURE__ */ jsx(
SliderImpl,
{
dir: direction,
"data-orientation": "horizontal",
...sliderProps,
ref: composedRefs,
style: {
...sliderProps.style,
"--radix-slider-thumb-transform": "translateX(-50%)"
},
onSlideStart: (event) => {
const value = getValueFromPointer(event.clientX);
onSlideStart?.(value);
},
onSlideMove: (event) => {
const value = getValueFromPointer(event.clientX);
onSlideMove?.(value);
},
onSlideEnd: () => {
rectRef.current = void 0;
onSlideEnd?.();
},
onStepKeyDown: (event) => {
const slideDirection = isSlidingFromLeft ? "from-left" : "from-right";
const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}
}
)
}
);
}
);
var SliderVertical = React.forwardRef(
(props, forwardedRef) => {
const {
min,
max,
inverted,
onSlideStart,
onSlideMove,
onSlideEnd,
onStepKeyDown,
...sliderProps
} = props;
const sliderRef = React.useRef(null);
const ref = useComposedRefs(forwardedRef, sliderRef);
const rectRef = React.useRef(void 0);
const isSlidingFromBottom = !inverted;
function getValueFromPointer(pointerPosition) {
const rect = rectRef.current || sliderRef.current.getBoundingClientRect();
const input = [0, rect.height];
const output = isSlidingFromBottom ? [max, min] : [min, max];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.top);
}
return /* @__PURE__ */ jsx(
SliderOrientationProvider,
{
scope: props.__scopeSlider,
startEdge: isSlidingFromBottom ? "bottom" : "top",
endEdge: isSlidingFromBottom ? "top" : "bottom",
size: "height",
direction: isSlidingFromBottom ? 1 : -1,
children: /* @__PURE__ */ jsx(
SliderImpl,
{
"data-orientation": "vertical",
...sliderProps,
ref,
style: {
...sliderProps.style,
"--radix-slider-thumb-transform": "translateY(50%)"
},
onSlideStart: (event) => {
const value = getValueFromPointer(event.clientY);
onSlideStart?.(value);
},
onSlideMove: (event) => {
const value = getValueFromPointer(event.clientY);
onSlideMove?.(value);
},
onSlideEnd: () => {
rectRef.current = void 0;
onSlideEnd?.();
},
onStepKeyDown: (event) => {
const slideDirection = isSlidingFromBottom ? "from-bottom" : "from-top";
const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}
}
)
}
);
}
);
var SliderImpl = React.forwardRef(
(props, forwardedRef) => {
const {
__scopeSlider,
onSlideStart,
onSlideMove,
onSlideEnd,
onHomeKeyDown,
onEndKeyDown,
onStepKeyDown,
...sliderProps
} = props;
const context = useSliderContext(SLIDER_NAME, __scopeSlider);
return /* @__PURE__ */ jsx(
Primitive.span,
{
...sliderProps,
ref: forwardedRef,
onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
if (event.key === "Home") {
onHomeKeyDown(event);
event.preventDefault();
} else if (event.key === "End") {
onEndKeyDown(event);
event.preventDefault();
} else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
onStepKeyDown(event);
event.preventDefault();
}
}),
onPointerDown: composeEventHandlers(props.onPointerDown, (event) => {
const target = event.target;
target.setPointerCapture(event.pointerId);
event.preventDefault();
if (context.thumbs.has(target)) {
target.focus({ preventScroll: true, focusVisible: false });
} else {
onSlideStart(event);
}
}),
onPointerMove: composeEventHandlers(props.onPointerMove, (event) => {
const target = event.target;
if (target.hasPointerCapture(event.pointerId)) onSlideMove(event);
}),
onPointerUp: composeEventHandlers(props.onPointerUp, (event) => {
const target = event.target;
if (target.hasPointerCapture(event.pointerId)) {
target.releasePointerCapture(event.pointerId);
onSlideEnd(event);
}
})
}
);
}
);
var TRACK_NAME = "SliderTrack";
var SliderTrack = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...trackProps } = props;
const context = useSliderContext(TRACK_NAME, __scopeSlider);
return /* @__PURE__ */ jsx(
Primitive.span,
{
"data-disabled": context.disabled ? "" : void 0,
"data-orientation": context.orientation,
...trackProps,
ref: forwardedRef
}
);
}
);
SliderTrack.displayName = TRACK_NAME;
var RANGE_NAME = "SliderRange";
var SliderRange = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...rangeProps } = props;
const context = useSliderContext(RANGE_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(RANGE_NAME, __scopeSlider);
const ref = React.useRef(null);
const composedRefs = useComposedRefs(forwardedRef, ref);
const valuesCount = context.values.length;
const percentages = context.values.map(
(value) => convertValueToPercentage(value, context.min, context.max)
);
const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0;
const offsetEnd = 100 - Math.max(...percentages);
return /* @__PURE__ */ jsx(
Primitive.span,
{
"data-orientation": context.orientation,
"data-disabled": context.disabled ? "" : void 0,
...rangeProps,
ref: composedRefs,
style: {
...props.style,
[orientation.startEdge]: offsetStart + "%",
[orientation.endEdge]: offsetEnd + "%"
}
}
);
}
);
SliderRange.displayName = RANGE_NAME;
var THUMB_NAME = "SliderThumb";
var [SliderThumbContextProvider, useSliderThumbContext] = createSliderContext(THUMB_NAME);
var THUMB_PROVIDER_NAME = "SliderThumbProvider";
function SliderThumbProvider(props) {
const {
__scopeSlider,
name,
children,
// @ts-expect-error internal render prop
internal_do_not_use_render
} = props;
const context = useSliderContext(THUMB_PROVIDER_NAME, __scopeSlider);
const getItems = useCollection(__scopeSlider);
const [thumb, setThumb] = React.useState(null);
const index = React.useMemo(
() => thumb ? getItems().findIndex((item) => item.ref.current === thumb) : -1,
[getItems, thumb]
);
const size = useSize(thumb);
const isFormControl = thumb ? !!context.form || !!thumb.closest("form") : true;
const value = context.values[index];
const resolvedName = name ?? (context.name ? context.name + (context.values.length > 1 ? "[]" : "") : void 0);
const percent = value === void 0 ? 0 : convertValueToPercentage(value, context.min, context.max);
React.useEffect(() => {
if (thumb) {
context.thumbs.add(thumb);
return () => {
context.thumbs.delete(thumb);
};
}
}, [thumb, context.thumbs]);
const thumbContext = {
value,
name: resolvedName,
form: context.form,
isFormControl,
index,
thumb,
onThumbChange: setThumb,
percent,
size
};
return /* @__PURE__ */ jsx(SliderThumbContextProvider, { scope: __scopeSlider, ...thumbContext, children: isFunction(internal_do_not_use_render) ? internal_do_not_use_render(thumbContext) : children });
}
SliderThumbProvider.displayName = THUMB_PROVIDER_NAME;
var THUMB_TRIGGER_NAME = "SliderThumbTrigger";
var SliderThumbTrigger = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, ...thumbProps } = props;
const context = useSliderContext(THUMB_TRIGGER_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(THUMB_TRIGGER_NAME, __scopeSlider);
const { index, value, percent, size, onThumbChange } = useSliderThumbContext(
THUMB_TRIGGER_NAME,
__scopeSlider
);
const composedRefs = useComposedRefs(forwardedRef, (node) => onThumbChange(node));
const label = getLabel(index, context.values.length);
const orientationSize = size?.[orientation.size];
const thumbInBoundsOffset = orientationSize ? getThumbInBoundsOffset(orientationSize, percent, orientation.direction) : 0;
return /* @__PURE__ */ jsx(
"span",
{
style: {
transform: "var(--radix-slider-thumb-transform)",
position: "absolute",
[orientation.startEdge]: `calc(${percent}% + ${thumbInBoundsOffset}px)`
},
children: /* @__PURE__ */ jsx(Collection.ItemSlot, { scope: __scopeSlider, children: /* @__PURE__ */ jsx(
Primitive.span,
{
role: "slider",
"aria-label": props["aria-label"] || label,
"aria-valuemin": context.min,
"aria-valuenow": value,
"aria-valuemax": context.max,
"aria-orientation": context.orientation,
"data-orientation": context.orientation,
"data-disabled": context.disabled ? "" : void 0,
tabIndex: context.disabled ? void 0 : 0,
...thumbProps,
ref: composedRefs,
style: value === void 0 ? { display: "none" } : props.style,
onFocus: composeEventHandlers(props.onFocus, () => {
context.valueIndexToChangeRef.current = index;
})
}
) })
}
);
}
);
SliderThumbTrigger.displayName = THUMB_TRIGGER_NAME;
var SliderThumb = React.forwardRef(
(props, forwardedRef) => {
const { __scopeSlider, name, ...thumbProps } = props;
return /* @__PURE__ */ jsx(
SliderThumbProvider,
{
__scopeSlider,
name,
internal_do_not_use_render: ({ index, isFormControl }) => /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
SliderThumbTrigger,
{
...thumbProps,
ref: forwardedRef,
__scopeSlider
}
),
isFormControl ? /* @__PURE__ */ jsx(
SliderBubbleInput,
{
__scopeSlider
},
index
) : null
] })
}
);
}
);
SliderThumb.displayName = THUMB_NAME;
var BUBBLE_INPUT_NAME = "SliderBubbleInput";
var SliderBubbleInput = React.forwardRef(
({ __scopeSlider, ...props }, forwardedRef) => {
const { value, name, form } = useSliderThumbContext(BUBBLE_INPUT_NAME, __scopeSlider);
const ref = React.useRef(null);
const composedRefs = useComposedRefs(ref, forwardedRef);
const prevValue = usePrevious(value);
React.useEffect(() => {
const input = ref.current;
if (!input) return;
const inputProto = window.HTMLInputElement.prototype;
const descriptor = Object.getOwnPropertyDescriptor(inputProto, "value");
const setValue = descriptor.set;
if (prevValue !== value && setValue) {
const event = new Event("input", { bubbles: true });
setValue.call(input, value);
input.dispatchEvent(event);
}
}, [prevValue, value]);
return /* @__PURE__ */ jsx(
Primitive.input,
{
style: { display: "none" },
name,
form,
...props,
ref: composedRefs,
defaultValue: value
}
);
}
);
SliderBubbleInput.displayName = BUBBLE_INPUT_NAME;
function getNextSortedValues(prevValues = [], nextValue, atIndex) {
const nextValues = [...prevValues];
nextValues[atIndex] = nextValue;
return nextValues.sort((a, b) => a - b);
}
function convertValueToPercentage(value, min, max) {
const maxSteps = max - min;
const percentPerStep = 100 / maxSteps;
const percentage = percentPerStep * (value - min);
return clamp(percentage, [0, 100]);
}
function getLabel(index, totalValues) {
if (totalValues > 2) {
return `Value ${index + 1} of ${totalValues}`;
} else if (totalValues === 2) {
return ["Minimum", "Maximum"][index];
} else {
return void 0;
}
}
function getClosestValueIndex(values, nextValue) {
if (values.length === 1) return 0;
const distances = values.map((value) => Math.abs(value - nextValue));
const closestDistance = Math.min(...distances);
return distances.indexOf(closestDistance);
}
function getThumbInBoundsOffset(width, left, direction) {
const halfWidth = width / 2;
const halfPercent = 50;
const offset = linearScale([0, halfPercent], [0, halfWidth]);
return (halfWidth - offset(left) * direction) * direction;
}
function getStepsBetweenValues(values) {
return values.slice(0, -1).map((value, index) => values[index + 1] - value);
}
function hasMinStepsBetweenValues(values, minStepsBetweenValues) {
if (minStepsBetweenValues > 0) {
const stepsBetweenValues = getStepsBetweenValues(values);
const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues);
return actualMinStepsBetweenValues >= minStepsBetweenValues;
}
return true;
}
function linearScale(input, output) {
return (value) => {
if (input[0] === input[1] || output[0] === output[1]) return output[0];
const ratio = (output[1] - output[0]) / (input[1] - input[0]);
return output[0] + ratio * (value - input[0]);
};
}
function getDecimalCount(value) {
if (!Number.isFinite(value)) return 0;
const str = value.toString();
if (str.includes("e")) {
const [coefficient, exponent] = str.split("e");
const decimalPart2 = coefficient.split(".")[1] || "";
const exponentNum = Number(exponent);
return Math.max(0, decimalPart2.length - exponentNum);
}
const decimalPart = str.split(".")[1];
return decimalPart ? decimalPart.length : 0;
}
function roundValue(value, decimalCount) {
const rounder = Math.pow(10, decimalCount);
return Math.round(value * rounder) / rounder;
}
function isFunction(value) {
return typeof value === "function";
}
export {
SliderRange as Range,
Slider as Root,
Slider,
SliderRange,
SliderThumb,
SliderTrack,
SliderThumb as Thumb,
SliderTrack as Track,
createSliderScope,
SliderBubbleInput as unstable_BubbleInput,
SliderBubbleInput as unstable_SliderBubbleInput,
SliderThumbProvider as unstable_SliderThumbProvider,
SliderThumbTrigger as unstable_SliderThumbTrigger,
SliderThumbProvider as unstable_ThumbProvider,
SliderThumbTrigger as unstable_ThumbTrigger
};
//# sourceMappingURL=index.mjs.map
File diff suppressed because one or more lines are too long
+78
View File
@@ -0,0 +1,78 @@
{
"name": "@radix-ui/react-slider",
"version": "1.4.1",
"license": "MIT",
"source": "./src/index.ts",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"files": [
"dist",
"README.md"
],
"sideEffects": false,
"dependencies": {
"@radix-ui/react-collection": "1.1.10",
"@radix-ui/number": "1.1.2",
"@radix-ui/react-compose-refs": "1.1.3",
"@radix-ui/primitive": "1.1.4",
"@radix-ui/react-direction": "1.1.2",
"@radix-ui/react-context": "1.1.4",
"@radix-ui/react-primitive": "2.1.6",
"@radix-ui/react-use-controllable-state": "1.2.3",
"@radix-ui/react-use-layout-effect": "1.1.2",
"@radix-ui/react-use-size": "1.1.2",
"@radix-ui/react-use-previous": "1.1.2"
},
"devDependencies": {
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"typescript": "^5.9.3",
"@repo/typescript-config": "0.0.0",
"@repo/builder": "0.0.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
},
"homepage": "https://radix-ui.com/primitives",
"repository": {
"type": "git",
"url": "git+https://github.com/radix-ui/primitives.git",
"directory": "packages/react/slider"
},
"bugs": {
"url": "https://github.com/radix-ui/primitives/issues"
},
"scripts": {
"lint": "oxlint --max-warnings 0 src",
"clean": "rm -rf dist",
"reset": "rm -rf dist node_modules",
"typecheck": "tsc --noEmit",
"build": "radix-build"
},
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}
}