neue Homepage auf react basis

This commit is contained in:
2026-08-07 21:39:30 +02:00
parent 164bdd19ad
commit ee89442c04
52191 changed files with 1230242 additions and 58 deletions
+325
View File
@@ -0,0 +1,325 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { OverridableStringUnion } from '@mui/types';
import { Mark } from "./useSlider.types.mjs";
import { CreateSlotsAndSlotProps, SlotComponentProps, SlotProps } from "../utils/types.mjs";
import { Theme } from "../styles/index.mjs";
import { OverrideProps, OverridableComponent } from "../OverridableComponent/index.mjs";
import SliderValueLabelComponent from "./SliderValueLabel.mjs";
import { SliderClasses } from "./sliderClasses.mjs";
export interface SliderPropsColorOverrides {}
export interface SliderPropsSizeOverrides {}
export interface SliderSlots {
/**
* The component that renders the root.
* @default 'span'
*/
root: React.ElementType;
/**
* The component that renders the track.
* @default 'span'
*/
track: React.ElementType;
/**
* The component that renders the rail.
* @default 'span'
*/
rail: React.ElementType;
/**
* The component that renders the thumb.
* @default 'span'
*/
thumb: React.ElementType;
/**
* The component that renders the mark.
* @default 'span'
*/
mark: React.ElementType;
/**
* The component that renders the mark label.
* @default 'span'
*/
markLabel: React.ElementType;
/**
* The component that renders the value label.
* @default SliderValueLabel
*/
valueLabel: React.ElementType;
/**
* The component that renders the input.
* @default 'input'
*/
input: React.ElementType;
}
export interface SliderRootSlotPropsOverrides {}
export interface SliderTrackSlotPropsOverrides {}
export interface SliderRailSlotPropsOverrides {}
export interface SliderThumbSlotPropsOverrides {}
export interface SliderMarkSlotPropsOverrides {}
export interface SliderMarkLabelSlotPropsOverrides {}
export interface SliderValueLabelSlotPropsOverrides {}
export interface SliderInputSlotPropsOverrides {}
export type SliderSlotsAndSlotProps = CreateSlotsAndSlotProps<SliderSlots, {
/**
* Props forwarded to the root slot.
* By default, the available props are based on the span element.
*/
root: SlotProps<'span', SliderRootSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the track slot.
* By default, the available props are based on the span element.
*/
track: SlotProps<'span', SliderTrackSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the rail slot.
* By default, the available props are based on the span element.
*/
rail: SlotProps<'span', SliderRailSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the thumb slot.
* By default, the available props are based on the span element.
*/
thumb: SlotProps<'span', SliderThumbSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the mark slot.
* By default, the available props are based on the span element.
*/
mark: SlotProps<'span', SliderMarkSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the mark label slot.
* By default, the available props are based on the span element.
*/
markLabel: SlotProps<'span', SliderMarkLabelSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the value label slot.
* By default, the available props are based on the [SliderValueLabel](https://mui.com/material-ui/api/slider/) component.
*/
valueLabel: SlotComponentProps<typeof SliderValueLabelComponent, SliderValueLabelSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the input slot.
* By default, the available props are based on the input element.
*/
input: SlotProps<'input', SliderInputSlotPropsOverrides, SliderOwnerState>;
}>;
export interface SliderOwnerState extends SliderProps {
dragging: boolean;
marked: boolean;
focusedThumbIndex: number;
}
export interface SliderOwnProps<Value extends number | readonly number[]> {
/**
* The label of the slider.
*/
'aria-label'?: string | undefined;
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby'?: string | undefined;
/**
* A string value that provides a user-friendly name for the current value of the slider.
*/
'aria-valuetext'?: string | undefined;
/**
* The color of the component.
* It supports both default and custom theme colors, which can be added as shown in the
* [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
* @default 'primary'
*/
color?: OverridableStringUnion<'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning', SliderPropsColorOverrides> | undefined;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<SliderClasses> | undefined;
/**
* @ignore
*/
className?: string | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: Value | undefined;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean | undefined;
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap?: boolean | undefined;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
* This is important for screen reader users.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaLabel?: ((index: number) => string) | undefined;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
* This is important for screen reader users.
* @param {number} value The thumb label's value to format.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaValueText?: ((value: number, index: number) => string) | undefined;
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks?: boolean | readonly Mark[] | undefined;
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max?: number | undefined;
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min?: number | undefined;
/**
* Name attribute of the hidden `input` element.
*/
name?: string | undefined;
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {Value} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange?: ((event: Event, value: Value, activeThumb: number) => void) | undefined;
/**
* Callback function that is fired when the pointer or touch interaction ends.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {Value} value The new value.
*/
onChangeCommitted?: ((event: React.SyntheticEvent | Event, value: Value) => void) | undefined;
/**
* The component orientation.
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical' | undefined;
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale?: ((value: number) => number) | undefined;
/**
* The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
* @default 10
*/
shiftStep?: number | undefined;
/**
* The size of the slider.
* @default 'medium'
*/
size?: OverridableStringUnion<'small' | 'medium', SliderPropsSizeOverrides> | undefined;
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step?: number | null | undefined;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme> | undefined;
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex?: number | undefined;
/**
* The track presentation:
*
* - `normal` the track will render a bar representing the slider value.
* - `inverted` the track will render a bar representing the remaining slider value.
* - `false` the track will render without a bar.
* @default 'normal'
*/
track?: 'normal' | false | 'inverted' | undefined;
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value?: Value | undefined;
/**
* Controls when the value label is displayed:
*
* - `auto` the value label will display when the thumb is hovered or focused.
* - `on` will display persistently.
* - `off` will never display.
* @default 'off'
*/
valueLabelDisplay?: 'on' | 'auto' | 'off' | undefined;
/**
* The format function the value label's value.
*
* When a function is provided, it should have the following signature:
*
* - {number} value The value label's value to format
* - {number} index The value label's index to format
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
valueLabelFormat?: string | ((value: number, index: number) => React.ReactNode) | undefined;
}
export interface SliderTypeMap<RootComponent extends React.ElementType = 'span', AdditionalProps = {}, Value extends number | readonly number[] = number | number[]> {
props: AdditionalProps & SliderOwnProps<Value> & SliderSlotsAndSlotProps;
defaultComponent: RootComponent;
}
export type SliderComponent<Value extends number | readonly number[]> = OverridableComponent<SliderTypeMap<'span', {}, Value>>;
export type SliderType = SliderComponent<number> & SliderComponent<number[]> & SliderComponent<readonly number[]> & SliderComponent<number | number[]>;
export interface SliderValueLabelProps extends React.HTMLAttributes<HTMLSpanElement> {
children: React.ReactElement<unknown>;
index: number;
open: boolean;
value: React.ReactNode;
}
type SliderRootProps = NonNullable<SliderTypeMap['props']['slotProps']>['root'];
type SliderMarkProps = NonNullable<SliderTypeMap['props']['slotProps']>['mark'];
type SliderMarkLabelProps = NonNullable<SliderTypeMap['props']['slotProps']>['markLabel'];
type SliderRailProps = NonNullable<SliderTypeMap['props']['slotProps']>['rail'];
type SliderTrackProps = NonNullable<SliderTypeMap['props']['slotProps']>['track'];
type SliderThumbProps = NonNullable<SliderTypeMap['props']['slotProps']>['thumb'];
export declare const SliderRoot: React.FC<SliderRootProps>;
export declare const SliderMark: React.FC<SliderMarkProps>;
export declare const SliderMarkLabel: React.FC<SliderMarkLabelProps>;
export declare const SliderRail: React.FC<SliderRailProps>;
export declare const SliderTrack: React.FC<SliderTrackProps>;
export declare const SliderThumb: React.FC<SliderThumbProps>;
export declare const SliderValueLabel: React.FC<SliderValueLabelProps>;
/**
*
* Demos:
*
* - [Slider](https://mui.com/material-ui/react-slider/)
*
* API:
*
* - [Slider API](https://mui.com/material-ui/api/slider/)
*/
declare const Slider: SliderType;
export type SliderProps<RootComponent extends React.ElementType = SliderTypeMap['defaultComponent'], AdditionalProps = {}, Value extends number | readonly number[] = number | number[]> = OverrideProps<SliderTypeMap<RootComponent, AdditionalProps, Value>, RootComponent> & {
component?: React.ElementType | undefined;
};
export default Slider;
+325
View File
@@ -0,0 +1,325 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { OverridableStringUnion } from '@mui/types';
import { Mark } from "./useSlider.types.js";
import { CreateSlotsAndSlotProps, SlotComponentProps, SlotProps } from "../utils/types.js";
import { Theme } from "../styles/index.js";
import { OverrideProps, OverridableComponent } from "../OverridableComponent/index.js";
import SliderValueLabelComponent from "./SliderValueLabel.js";
import { SliderClasses } from "./sliderClasses.js";
export interface SliderPropsColorOverrides {}
export interface SliderPropsSizeOverrides {}
export interface SliderSlots {
/**
* The component that renders the root.
* @default 'span'
*/
root: React.ElementType;
/**
* The component that renders the track.
* @default 'span'
*/
track: React.ElementType;
/**
* The component that renders the rail.
* @default 'span'
*/
rail: React.ElementType;
/**
* The component that renders the thumb.
* @default 'span'
*/
thumb: React.ElementType;
/**
* The component that renders the mark.
* @default 'span'
*/
mark: React.ElementType;
/**
* The component that renders the mark label.
* @default 'span'
*/
markLabel: React.ElementType;
/**
* The component that renders the value label.
* @default SliderValueLabel
*/
valueLabel: React.ElementType;
/**
* The component that renders the input.
* @default 'input'
*/
input: React.ElementType;
}
export interface SliderRootSlotPropsOverrides {}
export interface SliderTrackSlotPropsOverrides {}
export interface SliderRailSlotPropsOverrides {}
export interface SliderThumbSlotPropsOverrides {}
export interface SliderMarkSlotPropsOverrides {}
export interface SliderMarkLabelSlotPropsOverrides {}
export interface SliderValueLabelSlotPropsOverrides {}
export interface SliderInputSlotPropsOverrides {}
export type SliderSlotsAndSlotProps = CreateSlotsAndSlotProps<SliderSlots, {
/**
* Props forwarded to the root slot.
* By default, the available props are based on the span element.
*/
root: SlotProps<'span', SliderRootSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the track slot.
* By default, the available props are based on the span element.
*/
track: SlotProps<'span', SliderTrackSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the rail slot.
* By default, the available props are based on the span element.
*/
rail: SlotProps<'span', SliderRailSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the thumb slot.
* By default, the available props are based on the span element.
*/
thumb: SlotProps<'span', SliderThumbSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the mark slot.
* By default, the available props are based on the span element.
*/
mark: SlotProps<'span', SliderMarkSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the mark label slot.
* By default, the available props are based on the span element.
*/
markLabel: SlotProps<'span', SliderMarkLabelSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the value label slot.
* By default, the available props are based on the [SliderValueLabel](https://mui.com/material-ui/api/slider/) component.
*/
valueLabel: SlotComponentProps<typeof SliderValueLabelComponent, SliderValueLabelSlotPropsOverrides, SliderOwnerState>;
/**
* Props forwarded to the input slot.
* By default, the available props are based on the input element.
*/
input: SlotProps<'input', SliderInputSlotPropsOverrides, SliderOwnerState>;
}>;
export interface SliderOwnerState extends SliderProps {
dragging: boolean;
marked: boolean;
focusedThumbIndex: number;
}
export interface SliderOwnProps<Value extends number | readonly number[]> {
/**
* The label of the slider.
*/
'aria-label'?: string | undefined;
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby'?: string | undefined;
/**
* A string value that provides a user-friendly name for the current value of the slider.
*/
'aria-valuetext'?: string | undefined;
/**
* The color of the component.
* It supports both default and custom theme colors, which can be added as shown in the
* [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
* @default 'primary'
*/
color?: OverridableStringUnion<'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning', SliderPropsColorOverrides> | undefined;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<SliderClasses> | undefined;
/**
* @ignore
*/
className?: string | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: Value | undefined;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean | undefined;
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap?: boolean | undefined;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
* This is important for screen reader users.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaLabel?: ((index: number) => string) | undefined;
/**
* Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
* This is important for screen reader users.
* @param {number} value The thumb label's value to format.
* @param {number} index The thumb label's index to format.
* @returns {string}
*/
getAriaValueText?: ((value: number, index: number) => string) | undefined;
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks?: boolean | readonly Mark[] | undefined;
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max?: number | undefined;
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min?: number | undefined;
/**
* Name attribute of the hidden `input` element.
*/
name?: string | undefined;
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {Value} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange?: ((event: Event, value: Value, activeThumb: number) => void) | undefined;
/**
* Callback function that is fired when the pointer or touch interaction ends.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {Value} value The new value.
*/
onChangeCommitted?: ((event: React.SyntheticEvent | Event, value: Value) => void) | undefined;
/**
* The component orientation.
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical' | undefined;
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale?: ((value: number) => number) | undefined;
/**
* The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
* @default 10
*/
shiftStep?: number | undefined;
/**
* The size of the slider.
* @default 'medium'
*/
size?: OverridableStringUnion<'small' | 'medium', SliderPropsSizeOverrides> | undefined;
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step?: number | null | undefined;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme> | undefined;
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex?: number | undefined;
/**
* The track presentation:
*
* - `normal` the track will render a bar representing the slider value.
* - `inverted` the track will render a bar representing the remaining slider value.
* - `false` the track will render without a bar.
* @default 'normal'
*/
track?: 'normal' | false | 'inverted' | undefined;
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value?: Value | undefined;
/**
* Controls when the value label is displayed:
*
* - `auto` the value label will display when the thumb is hovered or focused.
* - `on` will display persistently.
* - `off` will never display.
* @default 'off'
*/
valueLabelDisplay?: 'on' | 'auto' | 'off' | undefined;
/**
* The format function the value label's value.
*
* When a function is provided, it should have the following signature:
*
* - {number} value The value label's value to format
* - {number} index The value label's index to format
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
valueLabelFormat?: string | ((value: number, index: number) => React.ReactNode) | undefined;
}
export interface SliderTypeMap<RootComponent extends React.ElementType = 'span', AdditionalProps = {}, Value extends number | readonly number[] = number | number[]> {
props: AdditionalProps & SliderOwnProps<Value> & SliderSlotsAndSlotProps;
defaultComponent: RootComponent;
}
export type SliderComponent<Value extends number | readonly number[]> = OverridableComponent<SliderTypeMap<'span', {}, Value>>;
export type SliderType = SliderComponent<number> & SliderComponent<number[]> & SliderComponent<readonly number[]> & SliderComponent<number | number[]>;
export interface SliderValueLabelProps extends React.HTMLAttributes<HTMLSpanElement> {
children: React.ReactElement<unknown>;
index: number;
open: boolean;
value: React.ReactNode;
}
type SliderRootProps = NonNullable<SliderTypeMap['props']['slotProps']>['root'];
type SliderMarkProps = NonNullable<SliderTypeMap['props']['slotProps']>['mark'];
type SliderMarkLabelProps = NonNullable<SliderTypeMap['props']['slotProps']>['markLabel'];
type SliderRailProps = NonNullable<SliderTypeMap['props']['slotProps']>['rail'];
type SliderTrackProps = NonNullable<SliderTypeMap['props']['slotProps']>['track'];
type SliderThumbProps = NonNullable<SliderTypeMap['props']['slotProps']>['thumb'];
export declare const SliderRoot: React.FC<SliderRootProps>;
export declare const SliderMark: React.FC<SliderMarkProps>;
export declare const SliderMarkLabel: React.FC<SliderMarkLabelProps>;
export declare const SliderRail: React.FC<SliderRailProps>;
export declare const SliderTrack: React.FC<SliderTrackProps>;
export declare const SliderThumb: React.FC<SliderThumbProps>;
export declare const SliderValueLabel: React.FC<SliderValueLabelProps>;
/**
*
* Demos:
*
* - [Slider](https://mui.com/material-ui/react-slider/)
*
* API:
*
* - [Slider API](https://mui.com/material-ui/api/slider/)
*/
declare const Slider: SliderType;
export type SliderProps<RootComponent extends React.ElementType = SliderTypeMap['defaultComponent'], AdditionalProps = {}, Value extends number | readonly number[] = number | number[]> = OverrideProps<SliderTypeMap<RootComponent, AdditionalProps, Value>, RootComponent> & {
component?: React.ElementType | undefined;
};
export default Slider;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
import * as React from 'react';
import { SliderValueLabelProps } from "./SliderValueLabel.types.mjs";
/**
* @ignore - internal component.
*/
declare function SliderValueLabel(props: SliderValueLabelProps): React.ReactElement<{
className?: string | undefined;
children?: React.ReactNode;
}, string | React.JSXElementConstructor<any>> | null;
export default SliderValueLabel;
declare namespace SliderValueLabel {
var propTypes: any;
}
+13
View File
@@ -0,0 +1,13 @@
import * as React from 'react';
import { SliderValueLabelProps } from "./SliderValueLabel.types.js";
/**
* @ignore - internal component.
*/
declare function SliderValueLabel(props: SliderValueLabelProps): React.ReactElement<{
className?: string | undefined;
children?: React.ReactNode;
}, string | React.JSXElementConstructor<any>> | null;
export default SliderValueLabel;
declare namespace SliderValueLabel {
var propTypes: any;
}
+60
View File
@@ -0,0 +1,60 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = SliderValueLabel;
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _sliderClasses = _interopRequireDefault(require("./sliderClasses"));
var _jsxRuntime = require("react/jsx-runtime");
const useValueLabelClasses = props => {
const {
open
} = props;
const utilityClasses = {
offset: (0, _clsx.default)(open && _sliderClasses.default.valueLabelOpen),
circle: _sliderClasses.default.valueLabelCircle,
label: _sliderClasses.default.valueLabelLabel
};
return utilityClasses;
};
/**
* @ignore - internal component.
*/
function SliderValueLabel(props) {
const {
children,
className,
value
} = props;
const classes = useValueLabelClasses(props);
if (!children) {
return null;
}
return /*#__PURE__*/React.cloneElement(children, {
className: children.props.className
}, /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
children: [children.props.children, /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
className: (0, _clsx.default)(classes.offset, className),
"aria-hidden": true,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
className: classes.circle,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
className: classes.label,
children: value
})
})
})]
}));
}
process.env.NODE_ENV !== "production" ? SliderValueLabel.propTypes = {
children: _propTypes.default.element.isRequired,
className: _propTypes.default.string,
value: _propTypes.default.node
} : void 0;
+53
View File
@@ -0,0 +1,53 @@
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import sliderClasses from "./sliderClasses.mjs";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useValueLabelClasses = props => {
const {
open
} = props;
const utilityClasses = {
offset: clsx(open && sliderClasses.valueLabelOpen),
circle: sliderClasses.valueLabelCircle,
label: sliderClasses.valueLabelLabel
};
return utilityClasses;
};
/**
* @ignore - internal component.
*/
export default function SliderValueLabel(props) {
const {
children,
className,
value
} = props;
const classes = useValueLabelClasses(props);
if (!children) {
return null;
}
return /*#__PURE__*/React.cloneElement(children, {
className: children.props.className
}, /*#__PURE__*/_jsxs(React.Fragment, {
children: [children.props.children, /*#__PURE__*/_jsx("span", {
className: clsx(classes.offset, className),
"aria-hidden": true,
children: /*#__PURE__*/_jsx("span", {
className: classes.circle,
children: /*#__PURE__*/_jsx("span", {
className: classes.label,
children: value
})
})
})]
}));
}
process.env.NODE_ENV !== "production" ? SliderValueLabel.propTypes = {
children: PropTypes.element.isRequired,
className: PropTypes.string,
value: PropTypes.node
} : void 0;
+25
View File
@@ -0,0 +1,25 @@
export interface SliderValueLabelProps {
children?: React.ReactElement<{
className?: string | undefined;
children?: React.ReactNode;
}> | undefined;
className?: string | undefined;
style?: React.CSSProperties | undefined;
/**
* If `true`, the value label is visible.
*/
open: boolean;
/**
* The value of the slider.
*/
value: React.ReactNode;
/**
* Controls when the value label is displayed:
*
* - `auto` the value label will display when the thumb is hovered or focused.
* - `on` will display persistently.
* - `off` will never display.
* @default 'off'
*/
valueLabelDisplay?: 'on' | 'auto' | 'off' | undefined;
}
+25
View File
@@ -0,0 +1,25 @@
export interface SliderValueLabelProps {
children?: React.ReactElement<{
className?: string | undefined;
children?: React.ReactNode;
}> | undefined;
className?: string | undefined;
style?: React.CSSProperties | undefined;
/**
* If `true`, the value label is visible.
*/
open: boolean;
/**
* The value of the slider.
*/
value: React.ReactNode;
/**
* Controls when the value label is displayed:
*
* - `auto` the value label will display when the thumb is hovered or focused.
* - `on` will display persistently.
* - `off` will never display.
* @default 'off'
*/
valueLabelDisplay?: 'on' | 'auto' | 'off' | undefined;
}
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
export { default } from "./Slider.mjs";
export * from "./Slider.mjs";
export { default as sliderClasses } from "./sliderClasses.mjs";
export * from "./sliderClasses.mjs";
+4
View File
@@ -0,0 +1,4 @@
export { default } from "./Slider.js";
export * from "./Slider.js";
export { default as sliderClasses } from "./sliderClasses.js";
export * from "./sliderClasses.js";
+45
View File
@@ -0,0 +1,45 @@
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
sliderClasses: true
};
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _Slider.default;
}
});
Object.defineProperty(exports, "sliderClasses", {
enumerable: true,
get: function () {
return _sliderClasses.default;
}
});
var _Slider = _interopRequireWildcard(require("./Slider"));
Object.keys(_Slider).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _Slider[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _Slider[key];
}
});
});
var _sliderClasses = _interopRequireWildcard(require("./sliderClasses"));
Object.keys(_sliderClasses).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _sliderClasses[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _sliderClasses[key];
}
});
});
+4
View File
@@ -0,0 +1,4 @@
export { default } from "./Slider.mjs";
export * from "./Slider.mjs";
export { default as sliderClasses } from "./sliderClasses.mjs";
export * from "./sliderClasses.mjs";
+60
View File
@@ -0,0 +1,60 @@
export interface SliderClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the root element if `color="primary"`. */
colorPrimary: string;
/** Styles applied to the root element if `color="secondary"`. */
colorSecondary: string;
/** Styles applied to the root element if `color="error"`. */
colorError: string;
/** Styles applied to the root element if `color="info"`. */
colorInfo: string;
/** Styles applied to the root element if `color="success"`. */
colorSuccess: string;
/** Styles applied to the root element if `color="warning"`. */
colorWarning: string;
/** Styles applied to the root element if `marks` is provided with at least one label. */
marked: string;
/** Styles applied to the root element if `orientation="vertical"`. */
vertical: string;
/** State class applied to the root and thumb element if `disabled={true}`. */
disabled: string;
/** State class applied to the root if a thumb is being dragged. */
dragging: string;
/** Styles applied to the rail element. */
rail: string;
/** Styles applied to the track element. */
track: string;
/** Styles applied to the root element if `track={false}`. */
trackFalse: string;
/** Styles applied to the root element if `track="inverted"`. */
trackInverted: string;
/** Styles applied to the thumb element. */
thumb: string;
/** State class applied to the thumb element if it's active. */
active: string;
/** State class applied to the thumb element if keyboard focused. */
focusVisible: string;
/** Styles applied to the mark element. */
mark: string;
/** Styles applied to the mark element if active (depending on the value). */
markActive: string;
/** Styles applied to the mark label element. */
markLabel: string;
/** Styles applied to the mark label element if active (depending on the value). */
markLabelActive: string;
/** Styles applied to the root element if `size="small"`. */
sizeSmall: string;
/** Styles applied to the thumb label element. */
valueLabel: string;
/** Styles applied to the thumb label element if it's open. */
valueLabelOpen: string;
/** Styles applied to the thumb label's circle element. */
valueLabelCircle: string;
/** Styles applied to the thumb label's label element. */
valueLabelLabel: string;
}
export type SliderClassKey = keyof SliderClasses;
export declare function getSliderUtilityClass(slot: string): string;
declare const sliderClasses: SliderClasses;
export default sliderClasses;
+60
View File
@@ -0,0 +1,60 @@
export interface SliderClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the root element if `color="primary"`. */
colorPrimary: string;
/** Styles applied to the root element if `color="secondary"`. */
colorSecondary: string;
/** Styles applied to the root element if `color="error"`. */
colorError: string;
/** Styles applied to the root element if `color="info"`. */
colorInfo: string;
/** Styles applied to the root element if `color="success"`. */
colorSuccess: string;
/** Styles applied to the root element if `color="warning"`. */
colorWarning: string;
/** Styles applied to the root element if `marks` is provided with at least one label. */
marked: string;
/** Styles applied to the root element if `orientation="vertical"`. */
vertical: string;
/** State class applied to the root and thumb element if `disabled={true}`. */
disabled: string;
/** State class applied to the root if a thumb is being dragged. */
dragging: string;
/** Styles applied to the rail element. */
rail: string;
/** Styles applied to the track element. */
track: string;
/** Styles applied to the root element if `track={false}`. */
trackFalse: string;
/** Styles applied to the root element if `track="inverted"`. */
trackInverted: string;
/** Styles applied to the thumb element. */
thumb: string;
/** State class applied to the thumb element if it's active. */
active: string;
/** State class applied to the thumb element if keyboard focused. */
focusVisible: string;
/** Styles applied to the mark element. */
mark: string;
/** Styles applied to the mark element if active (depending on the value). */
markActive: string;
/** Styles applied to the mark label element. */
markLabel: string;
/** Styles applied to the mark label element if active (depending on the value). */
markLabelActive: string;
/** Styles applied to the root element if `size="small"`. */
sizeSmall: string;
/** Styles applied to the thumb label element. */
valueLabel: string;
/** Styles applied to the thumb label element if it's open. */
valueLabelOpen: string;
/** Styles applied to the thumb label's circle element. */
valueLabelCircle: string;
/** Styles applied to the thumb label's label element. */
valueLabelLabel: string;
}
export type SliderClassKey = keyof SliderClasses;
export declare function getSliderUtilityClass(slot: string): string;
declare const sliderClasses: SliderClasses;
export default sliderClasses;
+15
View File
@@ -0,0 +1,15 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.getSliderUtilityClass = getSliderUtilityClass;
var _generateUtilityClasses = _interopRequireDefault(require("@mui/utils/generateUtilityClasses"));
var _generateUtilityClass = _interopRequireDefault(require("@mui/utils/generateUtilityClass"));
function getSliderUtilityClass(slot) {
return (0, _generateUtilityClass.default)('MuiSlider', slot);
}
const sliderClasses = (0, _generateUtilityClasses.default)('MuiSlider', ['root', 'active', 'colorPrimary', 'colorSecondary', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning', 'disabled', 'dragging', 'focusVisible', 'mark', 'markActive', 'marked', 'markLabel', 'markLabelActive', 'rail', 'sizeSmall', 'thumb', 'track', 'trackInverted', 'trackFalse', 'valueLabel', 'valueLabelOpen', 'valueLabelCircle', 'valueLabelLabel', 'vertical']);
var _default = exports.default = sliderClasses;
+7
View File
@@ -0,0 +1,7 @@
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
import generateUtilityClass from '@mui/utils/generateUtilityClass';
export function getSliderUtilityClass(slot) {
return generateUtilityClass('MuiSlider', slot);
}
const sliderClasses = generateUtilityClasses('MuiSlider', ['root', 'active', 'colorPrimary', 'colorSecondary', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning', 'disabled', 'dragging', 'focusVisible', 'mark', 'markActive', 'marked', 'markLabel', 'markLabelActive', 'rail', 'sizeSmall', 'thumb', 'track', 'trackInverted', 'trackFalse', 'valueLabel', 'valueLabelOpen', 'valueLabelCircle', 'valueLabelLabel', 'vertical']);
export default sliderClasses;
+4
View File
@@ -0,0 +1,4 @@
import { UseSliderParameters, UseSliderReturnValue } from "./useSlider.types.mjs";
export declare function valueToPercent(value: number, min: number, max: number): number;
export declare const Identity: (x: number) => number;
export declare function useSlider(parameters: UseSliderParameters): UseSliderReturnValue;
+4
View File
@@ -0,0 +1,4 @@
import { UseSliderParameters, UseSliderReturnValue } from "./useSlider.types.js";
export declare function valueToPercent(value: number, min: number, max: number): number;
export declare const Identity: (x: number) => number;
export declare function useSlider(parameters: UseSliderParameters): UseSliderReturnValue;
+774
View File
@@ -0,0 +1,774 @@
"use strict";
'use client';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Identity = void 0;
exports.useSlider = useSlider;
exports.valueToPercent = valueToPercent;
var React = _interopRequireWildcard(require("react"));
var _ownerDocument = _interopRequireDefault(require("@mui/utils/ownerDocument"));
var _useControlled = _interopRequireDefault(require("@mui/utils/useControlled"));
var _useEnhancedEffect = _interopRequireDefault(require("@mui/utils/useEnhancedEffect"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _useForkRef = _interopRequireDefault(require("@mui/utils/useForkRef"));
var _isFocusVisible = _interopRequireDefault(require("@mui/utils/isFocusVisible"));
var _visuallyHidden = _interopRequireDefault(require("@mui/utils/visuallyHidden"));
var _clamp = _interopRequireDefault(require("@mui/utils/clamp"));
var _extractEventHandlers = _interopRequireDefault(require("@mui/utils/extractEventHandlers"));
var _areArraysEqual = _interopRequireDefault(require("../utils/areArraysEqual"));
var _contains = _interopRequireDefault(require("../utils/contains"));
var _getActiveElement = _interopRequireDefault(require("../utils/getActiveElement"));
const INTENTIONAL_DRAG_COUNT_THRESHOLD = 2;
const EMPTY_MARKS = [];
const EMPTY_OBJ = {};
function getNewValue(currentValue, step, direction, min, max) {
return direction === 1 ? Math.min(currentValue + step, max) : Math.max(currentValue - step, min);
}
function asc(a, b) {
return a - b;
}
function findClosest(values, currentValue, preferredIndex = -1) {
const closestValue = values.reduce((acc, value, index) => {
const distance = Math.abs(currentValue - value);
if (acc == null || distance <= acc.distance) {
return {
distance,
index
};
}
return acc;
}, null) ?? EMPTY_OBJ;
const {
index: closestIndex
} = closestValue;
if (closestIndex == null) {
return closestIndex;
}
if (preferredIndex >= 0 && values[preferredIndex] === values[closestIndex]) {
return preferredIndex;
}
return closestIndex;
}
function trackFinger(event, touchIdRef) {
// The event is TouchEvent
if (touchIdRef.current != null && event.changedTouches) {
const touchEvent = event;
for (let i = 0; i < touchEvent.changedTouches.length; i += 1) {
const touch = touchEvent.changedTouches[i];
if (touch.identifier === touchIdRef.current) {
return {
x: touch.clientX,
y: touch.clientY
};
}
}
return false;
}
// The event is PointerEvent or MouseEvent
return {
x: event.clientX,
y: event.clientY
};
}
function valueToPercent(value, min, max) {
return (value - min) * 100 / (max - min);
}
function percentToValue(percent, min, max) {
return (max - min) * percent + min;
}
function getDecimalPrecision(num) {
// This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
// When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
if (Math.abs(num) < 1) {
const parts = num.toExponential().split('e-');
const matissaDecimalPart = parts[0].split('.')[1];
return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
}
const decimalPart = num.toString().split('.')[1];
return decimalPart ? decimalPart.length : 0;
}
function roundValueToStep(value, step, min) {
const nearest = Math.round((value - min) / step) * step + min;
return Number(nearest.toFixed(getDecimalPrecision(step)));
}
function setValueIndex(values, newValue, index) {
const output = values.slice();
output[index] = newValue;
return output.sort(asc);
}
function focusThumb(sliderRef, activeIndex, setActive, focusVisible) {
const doc = (0, _ownerDocument.default)(sliderRef.current);
const activeElement = (0, _getActiveElement.default)(doc);
if (!(0, _contains.default)(sliderRef.current, activeElement) || Number(activeElement?.getAttribute('data-index')) !== activeIndex) {
const input = sliderRef.current?.querySelector(`[type="range"][data-index="${activeIndex}"]`);
if (input != null) {
if (focusVisible == null) {
input.focus({
preventScroll: true
});
} else {
input.focus({
preventScroll: true,
// Prevent pointer-driven focus rings in browsers that support this option.
// Chrome 144+ supports `focusVisible` in `HTMLElement.focus()` options.
focusVisible
// Cast can be removed once TypeScript >= 6.0 (added `focusVisible` to lib.dom FocusOptions).
});
}
}
}
if (setActive) {
setActive(activeIndex);
}
}
function areValuesEqual(newValue, oldValue) {
if (typeof newValue === 'number' && typeof oldValue === 'number') {
return newValue === oldValue;
}
if (typeof newValue === 'object' && typeof oldValue === 'object') {
return (0, _areArraysEqual.default)(newValue, oldValue);
}
return false;
}
const axisProps = {
horizontal: {
offset: percent => ({
left: `${percent}%`
}),
leap: percent => ({
width: `${percent}%`
})
},
'horizontal-reverse': {
offset: percent => ({
right: `${percent}%`
}),
leap: percent => ({
width: `${percent}%`
})
},
vertical: {
offset: percent => ({
bottom: `${percent}%`
}),
leap: percent => ({
height: `${percent}%`
})
}
};
const Identity = x => x;
exports.Identity = Identity;
function useSlider(parameters) {
const {
'aria-labelledby': ariaLabelledby,
defaultValue,
disabled = false,
disableSwap = false,
isRtl = false,
marks: marksProp = false,
max = 100,
min = 0,
name,
onChange,
onChangeCommitted,
orientation = 'horizontal',
rootRef: ref,
scale = Identity,
step = 1,
shiftStep = 10,
tabIndex,
value: valueProp
} = parameters;
const touchIdRef = React.useRef(undefined);
const focusFrameRef = React.useRef(null);
// We can't use the :active browser pseudo-classes.
// - The active state isn't triggered when clicking on the rail.
// - The active state isn't transferred when inversing a range slider.
const [active, setActive] = React.useState(-1);
const [open, setOpen] = React.useState(-1);
const [dragging, setDragging] = React.useState(false);
const moveCountRef = React.useRef(0);
// Ref (not state) because setActive() always accompanies updates, providing the re-render.
const lastUsedThumbIndexRef = React.useRef(-1);
// Prevents duplicate listener registration when both pointer and touch events fire
// for the same physical touch interaction.
const pointerDownHandledRef = React.useRef(false);
// Tracks which pointer owns the current drag session, so stray pointerup/pointermove
// events from a second pointer don't interfere.
const activePointerIdRef = React.useRef(-1);
const cancelFocusFrame = (0, _useEventCallback.default)(() => {
if (focusFrameRef.current != null) {
cancelAnimationFrame(focusFrameRef.current);
focusFrameRef.current = null;
}
});
// lastChangedValueRef is updated whenever onChange is triggered.
const lastChangedValueRef = React.useRef(null);
const [valueDerived, setValueState] = (0, _useControlled.default)({
controlled: valueProp,
default: defaultValue ?? min,
name: 'Slider'
});
const handleChange = (0, _useEventCallback.default)((event, value, thumbIndex) => {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = 'nativeEvent' in event ? event.nativeEvent : event;
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: {
value,
name
}
});
lastChangedValueRef.current = value;
onChange?.(clonedEvent, value, thumbIndex);
});
const range = Array.isArray(valueDerived);
const values = React.useMemo(() => {
if (typeof valueDerived === 'number') {
return [(0, _clamp.default)(valueDerived, min, max)];
}
if (valueDerived == null) {
return [min];
}
const sortedValues = valueDerived.slice().sort(asc);
for (let i = 0; i < sortedValues.length; i += 1) {
const value = sortedValues[i];
sortedValues[i] = value == null ? min : (0, _clamp.default)(value, min, max);
}
return sortedValues;
}, [valueDerived, min, max]);
const marks = React.useMemo(() => {
if (marksProp === true && step != null) {
const generatedMarks = new Array(Math.floor((max - min) / step) + 1);
for (let i = 0; i < generatedMarks.length; i += 1) {
generatedMarks[i] = {
value: min + step * i
};
}
return generatedMarks;
}
return Array.isArray(marksProp) ? marksProp : EMPTY_MARKS;
}, [marksProp, step, min, max]);
const marksValues = React.useMemo(() => {
const markValues = new Array(marks.length);
for (let i = 0; i < marks.length; i += 1) {
markValues[i] = marks[i].value;
}
return markValues;
}, [marks]);
const [focusedThumbIndex, setFocusedThumbIndex] = React.useState(-1);
const sliderRef = React.useRef(null);
const handleRef = (0, _useForkRef.default)(ref, sliderRef);
const createHandleHiddenInputFocus = otherHandlers => event => {
const index = Number(event.currentTarget.getAttribute('data-index'));
if ((0, _isFocusVisible.default)(event.target)) {
setFocusedThumbIndex(index);
}
setOpen(index);
otherHandlers?.onFocus?.(event);
};
const createHandleHiddenInputBlur = otherHandlers => event => {
if (!(0, _isFocusVisible.default)(event.target)) {
setFocusedThumbIndex(-1);
}
setOpen(-1);
otherHandlers?.onBlur?.(event);
};
const changeValue = (event, valueInput) => {
const index = Number(event.currentTarget.getAttribute('data-index'));
const value = values[index];
const marksIndex = marksValues.indexOf(value);
let newValue = valueInput;
if (marks && step == null) {
const maxMarksValue = marksValues[marksValues.length - 1];
if (newValue >= maxMarksValue) {
newValue = maxMarksValue;
} else if (newValue <= marksValues[0]) {
newValue = marksValues[0];
} else {
newValue = newValue < value ? marksValues[marksIndex - 1] : marksValues[marksIndex + 1];
}
}
newValue = (0, _clamp.default)(newValue, min, max);
if (range) {
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = (0, _clamp.default)(newValue, values[index - 1] || -Infinity, values[index + 1] || Infinity);
}
const previousValue = newValue;
newValue = setValueIndex(values, newValue, index);
let activeIndex = index;
// Potentially swap the index if needed.
if (!disableSwap) {
activeIndex = newValue.indexOf(previousValue);
}
focusThumb(sliderRef, activeIndex);
}
setValueState(newValue);
setFocusedThumbIndex(index);
if (onChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(event, newValue, index);
}
if (onChangeCommitted) {
onChangeCommitted(event, lastChangedValueRef.current ?? newValue);
}
};
const createHandleHiddenInputKeyDown = otherHandlers => event => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'PageUp', 'PageDown', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
const index = Number(event.currentTarget.getAttribute('data-index'));
const value = values[index];
let newValue = null;
// Keys actions that change the value by more than the most granular `step`
// value are only applied if the step not `null`.
// When step is `null`, the `marks` prop is used instead to define valid values.
if (step != null) {
const stepSize = event.shiftKey ? shiftStep : step;
switch (event.key) {
case 'ArrowUp':
newValue = getNewValue(value, stepSize, 1, min, max);
break;
case 'ArrowRight':
newValue = getNewValue(value, stepSize, isRtl ? -1 : 1, min, max);
break;
case 'ArrowDown':
newValue = getNewValue(value, stepSize, -1, min, max);
break;
case 'ArrowLeft':
newValue = getNewValue(value, stepSize, isRtl ? 1 : -1, min, max);
break;
case 'PageUp':
newValue = getNewValue(value, shiftStep, 1, min, max);
break;
case 'PageDown':
newValue = getNewValue(value, shiftStep, -1, min, max);
break;
case 'Home':
newValue = min;
break;
case 'End':
newValue = max;
break;
default:
break;
}
} else if (marks) {
const maxMarksValue = marksValues[marksValues.length - 1];
const currentMarkIndex = marksValues.indexOf(value);
const decrementKeys = [isRtl ? 'ArrowRight' : 'ArrowLeft', 'ArrowDown', 'PageDown', 'Home'];
const incrementKeys = [isRtl ? 'ArrowLeft' : 'ArrowRight', 'ArrowUp', 'PageUp', 'End'];
if (decrementKeys.includes(event.key)) {
if (currentMarkIndex === 0) {
newValue = marksValues[0];
} else {
newValue = marksValues[currentMarkIndex - 1];
}
} else if (incrementKeys.includes(event.key)) {
if (currentMarkIndex === marksValues.length - 1) {
newValue = maxMarksValue;
} else {
newValue = marksValues[currentMarkIndex + 1];
}
}
}
if (newValue != null) {
changeValue(event, newValue);
}
}
otherHandlers?.onKeyDown?.(event);
};
(0, _useEnhancedEffect.default)(() => {
const activeElement = (0, _getActiveElement.default)((0, _ownerDocument.default)(sliderRef.current));
if (disabled && (0, _contains.default)(sliderRef.current, activeElement)) {
// This is necessary because Firefox and Safari will keep focus
// on a disabled element:
// https://codesandbox.io/p/sandbox/mui-pr-22247-forked-h151h?file=/src/App.js
if (activeElement != null && 'blur' in activeElement) {
activeElement.blur();
}
}
}, [disabled]);
if (disabled && active !== -1) {
setActive(-1);
}
if (disabled && focusedThumbIndex !== -1) {
setFocusedThumbIndex(-1);
}
const createHandleHiddenInputChange = otherHandlers => event => {
otherHandlers.onChange?.(event);
// Handles value changes reported through the hidden range input.
changeValue(event, event.currentTarget.valueAsNumber);
};
const previousIndexRef = React.useRef(undefined);
let axis = orientation;
if (isRtl && orientation === 'horizontal') {
axis += '-reverse';
}
// Converts finger coordinates to a slider value and determines the active thumb.
// For range sliders, reads `previousIndexRef.current` to decide which thumb is active:
// -1 = initial press → find closest thumb
// ≥0 = drag in progress → keep same thumb
// Callers must reset `previousIndexRef.current = -1` before calling on a new interaction.
const getValueAtFinger = finger => {
const {
current: slider
} = sliderRef;
if (!slider) {
return null;
}
const {
width,
height,
bottom,
left
} = slider.getBoundingClientRect();
let percent;
if (axis.startsWith('vertical')) {
percent = (bottom - finger.y) / height;
} else {
percent = (finger.x - left) / width;
}
if (axis.includes('-reverse')) {
percent = 1 - percent;
}
let newValue;
newValue = percentToValue(percent, min, max);
if (step) {
newValue = roundValueToStep(newValue, step, min);
} else {
const closestIndex = findClosest(marksValues, newValue);
newValue = marksValues[closestIndex];
}
newValue = (0, _clamp.default)(newValue, min, max);
let activeIndex = 0;
if (range) {
const isDragging = previousIndexRef.current !== -1;
activeIndex = isDragging ? previousIndexRef.current : findClosest(values, newValue, lastUsedThumbIndexRef.current);
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = (0, _clamp.default)(newValue, values[activeIndex - 1] || -Infinity, values[activeIndex + 1] || Infinity);
}
const previousValue = newValue;
newValue = setValueIndex(values, newValue, activeIndex);
// Potentially swap the index if needed.
if (!(disableSwap && isDragging)) {
activeIndex = newValue.indexOf(previousValue);
previousIndexRef.current = activeIndex;
}
}
return {
newValue,
activeIndex
};
};
const handleTouchMove = (0, _useEventCallback.default)(nativeEvent => {
// Ignore pointer events from a different pointer than the one that started the drag.
if ('pointerId' in nativeEvent && nativeEvent.pointerId !== activePointerIdRef.current) {
return;
}
const finger = trackFinger(nativeEvent, touchIdRef);
if (!finger) {
return;
}
moveCountRef.current += 1;
// Cancel move in case some other element consumed a pointerup event and it was not fired.
if (nativeEvent.type === 'pointermove' && nativeEvent.buttons === 0) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handleTouchEnd(nativeEvent);
return;
}
const newFingerValue = getValueAtFinger(finger);
if (!newFingerValue) {
return;
}
focusThumb(sliderRef, newFingerValue.activeIndex, setActive, false);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
setValueState(newFingerValue.newValue);
if (!dragging && moveCountRef.current > INTENTIONAL_DRAG_COUNT_THRESHOLD) {
setDragging(true);
}
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(nativeEvent, newFingerValue.newValue, newFingerValue.activeIndex);
}
});
const handleTouchEnd = (0, _useEventCallback.default)(nativeEvent => {
// Ignore pointer events from a different pointer than the one that started the drag.
if ('pointerId' in nativeEvent && nativeEvent.pointerId !== activePointerIdRef.current) {
return;
}
const finger = trackFinger(nativeEvent, touchIdRef);
setDragging(false);
if (!finger) {
return;
}
const newFingerValue = getValueAtFinger(finger);
setActive(-1);
if (nativeEvent.type === 'touchend') {
setOpen(-1);
}
if (newFingerValue && onChangeCommitted) {
onChangeCommitted(nativeEvent, lastChangedValueRef.current ?? newFingerValue.newValue);
}
// Release pointer capture if applicable
if ('pointerType' in nativeEvent && sliderRef.current?.hasPointerCapture(nativeEvent.pointerId)) {
sliderRef.current.releasePointerCapture(nativeEvent.pointerId);
}
touchIdRef.current = undefined;
activePointerIdRef.current = -1;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
stopListening();
});
const handleTouchStart = (0, _useEventCallback.default)(nativeEvent => {
if (disabled) {
return;
}
// If the pointer path already handled this interaction,
// only record the touch identifier and skip duplicate listener registration.
if (pointerDownHandledRef.current) {
pointerDownHandledRef.current = false;
const touch = nativeEvent.changedTouches[0];
if (touch != null) {
touchIdRef.current = touch.identifier;
}
return;
}
const touch = nativeEvent.changedTouches[0];
if (touch != null) {
// A number that uniquely identifies the current finger in the touch session.
touchIdRef.current = touch.identifier;
}
const finger = trackFinger(nativeEvent, touchIdRef);
if (finger !== false) {
previousIndexRef.current = -1;
const newFingerValue = getValueAtFinger(finger);
if (newFingerValue) {
focusThumb(sliderRef, newFingerValue.activeIndex, setActive, false);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
setValueState(newFingerValue.newValue);
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(nativeEvent, newFingerValue.newValue, newFingerValue.activeIndex);
}
}
}
moveCountRef.current = 0;
const doc = (0, _ownerDocument.default)(sliderRef.current);
doc.addEventListener('touchmove', handleTouchMove, {
passive: true
});
doc.addEventListener('touchend', handleTouchEnd, {
passive: true
});
});
const stopListening = React.useCallback(() => {
const doc = (0, _ownerDocument.default)(sliderRef.current);
doc.removeEventListener('pointermove', handleTouchMove);
doc.removeEventListener('pointerup', handleTouchEnd);
doc.removeEventListener('touchmove', handleTouchMove);
doc.removeEventListener('touchend', handleTouchEnd);
}, [handleTouchEnd, handleTouchMove]);
React.useEffect(() => {
const slider = sliderRef.current;
if (!slider) {
return undefined;
}
slider.addEventListener('touchstart', handleTouchStart, {
passive: true
});
return () => {
slider.removeEventListener('touchstart', handleTouchStart);
cancelFocusFrame();
stopListening();
};
}, [stopListening, handleTouchStart, cancelFocusFrame]);
React.useEffect(() => {
if (disabled) {
stopListening();
cancelFocusFrame();
}
}, [disabled, stopListening, cancelFocusFrame]);
const createHandlePointerDown = otherHandlers => event => {
otherHandlers.onPointerDown?.(event);
// On touch devices, the browser fires both pointerdown and touchstart for the
// same physical touch. Mark this BEFORE early returns so handleTouchStart always
// knows the pointer path saw this interaction — even if it was prevented or disabled.
if (event.pointerType === 'touch') {
pointerDownHandledRef.current = true;
}
if (disabled || event.defaultPrevented || event.button !== 0) {
return;
}
const finger = trackFinger(event, touchIdRef);
if (finger !== false) {
previousIndexRef.current = -1;
const newFingerValue = getValueAtFinger(finger);
if (newFingerValue) {
const thumbInput = sliderRef.current?.querySelector(`input[type="range"][data-index="${newFingerValue.activeIndex}"]`);
const doc = (0, _ownerDocument.default)(sliderRef.current);
const pressedOnFocusedThumb = thumbInput != null && thumbInput === (0, _getActiveElement.default)(doc);
setActive(newFingerValue.activeIndex);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
if (pressedOnFocusedThumb) {
event.preventDefault();
} else {
cancelFocusFrame();
focusFrameRef.current = requestAnimationFrame(() => {
focusFrameRef.current = null;
focusThumb(sliderRef, newFingerValue.activeIndex, undefined, false);
});
}
setValueState(newFingerValue.newValue);
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(event, newFingerValue.newValue, newFingerValue.activeIndex);
}
}
}
moveCountRef.current = 0;
activePointerIdRef.current = event.pointerId;
const doc = (0, _ownerDocument.default)(sliderRef.current);
// Use pointer capture for reliable drag tracking
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
// setPointerCapture can throw if the pointerId is invalid (e.g. synthetic
// events in tests, or the pointer was already released). The slider still
// works via document-level listeners; pointer capture is a progressive
// enhancement for reliable drag tracking.
}
doc.addEventListener('pointermove', handleTouchMove, {
passive: true
});
doc.addEventListener('pointerup', handleTouchEnd);
};
const trackOffset = valueToPercent(range ? values[0] : min, min, max);
const trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;
const getRootProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = (0, _extractEventHandlers.default)(externalProps);
const ownEventHandlers = {
onPointerDown: createHandlePointerDown(externalHandlers)
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers
};
return {
...externalProps,
ref: handleRef,
...mergedEventHandlers
};
};
const createHandleMouseOver = otherHandlers => event => {
otherHandlers.onMouseOver?.(event);
const index = Number(event.currentTarget.getAttribute('data-index'));
setOpen(index);
};
const createHandleMouseLeave = otherHandlers => event => {
otherHandlers.onMouseLeave?.(event);
setOpen(-1);
};
const getThumbProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = (0, _extractEventHandlers.default)(externalProps);
const ownEventHandlers = {
onMouseOver: createHandleMouseOver(externalHandlers),
onMouseLeave: createHandleMouseLeave(externalHandlers)
};
return {
...externalProps,
...externalHandlers,
...ownEventHandlers
};
};
const getThumbStyle = index => {
let zIndex;
if (range) {
if (active === index) {
zIndex = 2;
} else if (lastUsedThumbIndexRef.current === index) {
zIndex = 1;
}
} else if (active === index) {
zIndex = 1;
}
return {
// So the non active thumb doesn't show its label on hover.
pointerEvents: active !== -1 && active !== index ? 'none' : undefined,
zIndex
};
};
let cssWritingMode;
if (orientation === 'vertical') {
cssWritingMode = isRtl ? 'vertical-rl' : 'vertical-lr';
}
const getHiddenInputProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = (0, _extractEventHandlers.default)(externalProps);
const ownEventHandlers = {
onChange: createHandleHiddenInputChange(externalHandlers),
onFocus: createHandleHiddenInputFocus(externalHandlers),
onBlur: createHandleHiddenInputBlur(externalHandlers),
onKeyDown: createHandleHiddenInputKeyDown(externalHandlers)
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers
};
return {
tabIndex,
'aria-labelledby': ariaLabelledby,
'aria-orientation': orientation,
'aria-valuemax': scale(max),
'aria-valuemin': scale(min),
name,
type: 'range',
min: parameters.min,
max: parameters.max,
step: parameters.step === null && parameters.marks ? 'any' : parameters.step ?? undefined,
disabled,
...externalProps,
...mergedEventHandlers,
style: {
..._visuallyHidden.default,
direction: isRtl ? 'rtl' : 'ltr',
// So that VoiceOver's focus indicator matches the thumb's dimensions
width: '100%',
height: '100%',
writingMode: cssWritingMode
}
};
};
return {
active,
axis: axis,
axisProps,
dragging,
focusedThumbIndex,
getHiddenInputProps,
getRootProps,
getThumbProps,
marks,
open,
range,
rootRef: handleRef,
trackLeap,
trackOffset,
values,
getThumbStyle
};
}
+764
View File
@@ -0,0 +1,764 @@
'use client';
import * as React from 'react';
import ownerDocument from '@mui/utils/ownerDocument';
import useControlled from '@mui/utils/useControlled';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import useEventCallback from '@mui/utils/useEventCallback';
import useForkRef from '@mui/utils/useForkRef';
import isFocusVisible from '@mui/utils/isFocusVisible';
import visuallyHidden from '@mui/utils/visuallyHidden';
import clamp from '@mui/utils/clamp';
import extractEventHandlers from '@mui/utils/extractEventHandlers';
import areArraysEqual from "../utils/areArraysEqual.mjs";
import contains from "../utils/contains.mjs";
import getActiveElement from "../utils/getActiveElement.mjs";
const INTENTIONAL_DRAG_COUNT_THRESHOLD = 2;
const EMPTY_MARKS = [];
const EMPTY_OBJ = {};
function getNewValue(currentValue, step, direction, min, max) {
return direction === 1 ? Math.min(currentValue + step, max) : Math.max(currentValue - step, min);
}
function asc(a, b) {
return a - b;
}
function findClosest(values, currentValue, preferredIndex = -1) {
const closestValue = values.reduce((acc, value, index) => {
const distance = Math.abs(currentValue - value);
if (acc == null || distance <= acc.distance) {
return {
distance,
index
};
}
return acc;
}, null) ?? EMPTY_OBJ;
const {
index: closestIndex
} = closestValue;
if (closestIndex == null) {
return closestIndex;
}
if (preferredIndex >= 0 && values[preferredIndex] === values[closestIndex]) {
return preferredIndex;
}
return closestIndex;
}
function trackFinger(event, touchIdRef) {
// The event is TouchEvent
if (touchIdRef.current != null && event.changedTouches) {
const touchEvent = event;
for (let i = 0; i < touchEvent.changedTouches.length; i += 1) {
const touch = touchEvent.changedTouches[i];
if (touch.identifier === touchIdRef.current) {
return {
x: touch.clientX,
y: touch.clientY
};
}
}
return false;
}
// The event is PointerEvent or MouseEvent
return {
x: event.clientX,
y: event.clientY
};
}
export function valueToPercent(value, min, max) {
return (value - min) * 100 / (max - min);
}
function percentToValue(percent, min, max) {
return (max - min) * percent + min;
}
function getDecimalPrecision(num) {
// This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
// When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
if (Math.abs(num) < 1) {
const parts = num.toExponential().split('e-');
const matissaDecimalPart = parts[0].split('.')[1];
return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
}
const decimalPart = num.toString().split('.')[1];
return decimalPart ? decimalPart.length : 0;
}
function roundValueToStep(value, step, min) {
const nearest = Math.round((value - min) / step) * step + min;
return Number(nearest.toFixed(getDecimalPrecision(step)));
}
function setValueIndex(values, newValue, index) {
const output = values.slice();
output[index] = newValue;
return output.sort(asc);
}
function focusThumb(sliderRef, activeIndex, setActive, focusVisible) {
const doc = ownerDocument(sliderRef.current);
const activeElement = getActiveElement(doc);
if (!contains(sliderRef.current, activeElement) || Number(activeElement?.getAttribute('data-index')) !== activeIndex) {
const input = sliderRef.current?.querySelector(`[type="range"][data-index="${activeIndex}"]`);
if (input != null) {
if (focusVisible == null) {
input.focus({
preventScroll: true
});
} else {
input.focus({
preventScroll: true,
// Prevent pointer-driven focus rings in browsers that support this option.
// Chrome 144+ supports `focusVisible` in `HTMLElement.focus()` options.
focusVisible
// Cast can be removed once TypeScript >= 6.0 (added `focusVisible` to lib.dom FocusOptions).
});
}
}
}
if (setActive) {
setActive(activeIndex);
}
}
function areValuesEqual(newValue, oldValue) {
if (typeof newValue === 'number' && typeof oldValue === 'number') {
return newValue === oldValue;
}
if (typeof newValue === 'object' && typeof oldValue === 'object') {
return areArraysEqual(newValue, oldValue);
}
return false;
}
const axisProps = {
horizontal: {
offset: percent => ({
left: `${percent}%`
}),
leap: percent => ({
width: `${percent}%`
})
},
'horizontal-reverse': {
offset: percent => ({
right: `${percent}%`
}),
leap: percent => ({
width: `${percent}%`
})
},
vertical: {
offset: percent => ({
bottom: `${percent}%`
}),
leap: percent => ({
height: `${percent}%`
})
}
};
export const Identity = x => x;
export function useSlider(parameters) {
const {
'aria-labelledby': ariaLabelledby,
defaultValue,
disabled = false,
disableSwap = false,
isRtl = false,
marks: marksProp = false,
max = 100,
min = 0,
name,
onChange,
onChangeCommitted,
orientation = 'horizontal',
rootRef: ref,
scale = Identity,
step = 1,
shiftStep = 10,
tabIndex,
value: valueProp
} = parameters;
const touchIdRef = React.useRef(undefined);
const focusFrameRef = React.useRef(null);
// We can't use the :active browser pseudo-classes.
// - The active state isn't triggered when clicking on the rail.
// - The active state isn't transferred when inversing a range slider.
const [active, setActive] = React.useState(-1);
const [open, setOpen] = React.useState(-1);
const [dragging, setDragging] = React.useState(false);
const moveCountRef = React.useRef(0);
// Ref (not state) because setActive() always accompanies updates, providing the re-render.
const lastUsedThumbIndexRef = React.useRef(-1);
// Prevents duplicate listener registration when both pointer and touch events fire
// for the same physical touch interaction.
const pointerDownHandledRef = React.useRef(false);
// Tracks which pointer owns the current drag session, so stray pointerup/pointermove
// events from a second pointer don't interfere.
const activePointerIdRef = React.useRef(-1);
const cancelFocusFrame = useEventCallback(() => {
if (focusFrameRef.current != null) {
cancelAnimationFrame(focusFrameRef.current);
focusFrameRef.current = null;
}
});
// lastChangedValueRef is updated whenever onChange is triggered.
const lastChangedValueRef = React.useRef(null);
const [valueDerived, setValueState] = useControlled({
controlled: valueProp,
default: defaultValue ?? min,
name: 'Slider'
});
const handleChange = useEventCallback((event, value, thumbIndex) => {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = 'nativeEvent' in event ? event.nativeEvent : event;
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: {
value,
name
}
});
lastChangedValueRef.current = value;
onChange?.(clonedEvent, value, thumbIndex);
});
const range = Array.isArray(valueDerived);
const values = React.useMemo(() => {
if (typeof valueDerived === 'number') {
return [clamp(valueDerived, min, max)];
}
if (valueDerived == null) {
return [min];
}
const sortedValues = valueDerived.slice().sort(asc);
for (let i = 0; i < sortedValues.length; i += 1) {
const value = sortedValues[i];
sortedValues[i] = value == null ? min : clamp(value, min, max);
}
return sortedValues;
}, [valueDerived, min, max]);
const marks = React.useMemo(() => {
if (marksProp === true && step != null) {
const generatedMarks = new Array(Math.floor((max - min) / step) + 1);
for (let i = 0; i < generatedMarks.length; i += 1) {
generatedMarks[i] = {
value: min + step * i
};
}
return generatedMarks;
}
return Array.isArray(marksProp) ? marksProp : EMPTY_MARKS;
}, [marksProp, step, min, max]);
const marksValues = React.useMemo(() => {
const markValues = new Array(marks.length);
for (let i = 0; i < marks.length; i += 1) {
markValues[i] = marks[i].value;
}
return markValues;
}, [marks]);
const [focusedThumbIndex, setFocusedThumbIndex] = React.useState(-1);
const sliderRef = React.useRef(null);
const handleRef = useForkRef(ref, sliderRef);
const createHandleHiddenInputFocus = otherHandlers => event => {
const index = Number(event.currentTarget.getAttribute('data-index'));
if (isFocusVisible(event.target)) {
setFocusedThumbIndex(index);
}
setOpen(index);
otherHandlers?.onFocus?.(event);
};
const createHandleHiddenInputBlur = otherHandlers => event => {
if (!isFocusVisible(event.target)) {
setFocusedThumbIndex(-1);
}
setOpen(-1);
otherHandlers?.onBlur?.(event);
};
const changeValue = (event, valueInput) => {
const index = Number(event.currentTarget.getAttribute('data-index'));
const value = values[index];
const marksIndex = marksValues.indexOf(value);
let newValue = valueInput;
if (marks && step == null) {
const maxMarksValue = marksValues[marksValues.length - 1];
if (newValue >= maxMarksValue) {
newValue = maxMarksValue;
} else if (newValue <= marksValues[0]) {
newValue = marksValues[0];
} else {
newValue = newValue < value ? marksValues[marksIndex - 1] : marksValues[marksIndex + 1];
}
}
newValue = clamp(newValue, min, max);
if (range) {
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = clamp(newValue, values[index - 1] || -Infinity, values[index + 1] || Infinity);
}
const previousValue = newValue;
newValue = setValueIndex(values, newValue, index);
let activeIndex = index;
// Potentially swap the index if needed.
if (!disableSwap) {
activeIndex = newValue.indexOf(previousValue);
}
focusThumb(sliderRef, activeIndex);
}
setValueState(newValue);
setFocusedThumbIndex(index);
if (onChange && !areValuesEqual(newValue, valueDerived)) {
handleChange(event, newValue, index);
}
if (onChangeCommitted) {
onChangeCommitted(event, lastChangedValueRef.current ?? newValue);
}
};
const createHandleHiddenInputKeyDown = otherHandlers => event => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'PageUp', 'PageDown', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
const index = Number(event.currentTarget.getAttribute('data-index'));
const value = values[index];
let newValue = null;
// Keys actions that change the value by more than the most granular `step`
// value are only applied if the step not `null`.
// When step is `null`, the `marks` prop is used instead to define valid values.
if (step != null) {
const stepSize = event.shiftKey ? shiftStep : step;
switch (event.key) {
case 'ArrowUp':
newValue = getNewValue(value, stepSize, 1, min, max);
break;
case 'ArrowRight':
newValue = getNewValue(value, stepSize, isRtl ? -1 : 1, min, max);
break;
case 'ArrowDown':
newValue = getNewValue(value, stepSize, -1, min, max);
break;
case 'ArrowLeft':
newValue = getNewValue(value, stepSize, isRtl ? 1 : -1, min, max);
break;
case 'PageUp':
newValue = getNewValue(value, shiftStep, 1, min, max);
break;
case 'PageDown':
newValue = getNewValue(value, shiftStep, -1, min, max);
break;
case 'Home':
newValue = min;
break;
case 'End':
newValue = max;
break;
default:
break;
}
} else if (marks) {
const maxMarksValue = marksValues[marksValues.length - 1];
const currentMarkIndex = marksValues.indexOf(value);
const decrementKeys = [isRtl ? 'ArrowRight' : 'ArrowLeft', 'ArrowDown', 'PageDown', 'Home'];
const incrementKeys = [isRtl ? 'ArrowLeft' : 'ArrowRight', 'ArrowUp', 'PageUp', 'End'];
if (decrementKeys.includes(event.key)) {
if (currentMarkIndex === 0) {
newValue = marksValues[0];
} else {
newValue = marksValues[currentMarkIndex - 1];
}
} else if (incrementKeys.includes(event.key)) {
if (currentMarkIndex === marksValues.length - 1) {
newValue = maxMarksValue;
} else {
newValue = marksValues[currentMarkIndex + 1];
}
}
}
if (newValue != null) {
changeValue(event, newValue);
}
}
otherHandlers?.onKeyDown?.(event);
};
useEnhancedEffect(() => {
const activeElement = getActiveElement(ownerDocument(sliderRef.current));
if (disabled && contains(sliderRef.current, activeElement)) {
// This is necessary because Firefox and Safari will keep focus
// on a disabled element:
// https://codesandbox.io/p/sandbox/mui-pr-22247-forked-h151h?file=/src/App.js
if (activeElement != null && 'blur' in activeElement) {
activeElement.blur();
}
}
}, [disabled]);
if (disabled && active !== -1) {
setActive(-1);
}
if (disabled && focusedThumbIndex !== -1) {
setFocusedThumbIndex(-1);
}
const createHandleHiddenInputChange = otherHandlers => event => {
otherHandlers.onChange?.(event);
// Handles value changes reported through the hidden range input.
changeValue(event, event.currentTarget.valueAsNumber);
};
const previousIndexRef = React.useRef(undefined);
let axis = orientation;
if (isRtl && orientation === 'horizontal') {
axis += '-reverse';
}
// Converts finger coordinates to a slider value and determines the active thumb.
// For range sliders, reads `previousIndexRef.current` to decide which thumb is active:
// -1 = initial press → find closest thumb
// ≥0 = drag in progress → keep same thumb
// Callers must reset `previousIndexRef.current = -1` before calling on a new interaction.
const getValueAtFinger = finger => {
const {
current: slider
} = sliderRef;
if (!slider) {
return null;
}
const {
width,
height,
bottom,
left
} = slider.getBoundingClientRect();
let percent;
if (axis.startsWith('vertical')) {
percent = (bottom - finger.y) / height;
} else {
percent = (finger.x - left) / width;
}
if (axis.includes('-reverse')) {
percent = 1 - percent;
}
let newValue;
newValue = percentToValue(percent, min, max);
if (step) {
newValue = roundValueToStep(newValue, step, min);
} else {
const closestIndex = findClosest(marksValues, newValue);
newValue = marksValues[closestIndex];
}
newValue = clamp(newValue, min, max);
let activeIndex = 0;
if (range) {
const isDragging = previousIndexRef.current !== -1;
activeIndex = isDragging ? previousIndexRef.current : findClosest(values, newValue, lastUsedThumbIndexRef.current);
// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = clamp(newValue, values[activeIndex - 1] || -Infinity, values[activeIndex + 1] || Infinity);
}
const previousValue = newValue;
newValue = setValueIndex(values, newValue, activeIndex);
// Potentially swap the index if needed.
if (!(disableSwap && isDragging)) {
activeIndex = newValue.indexOf(previousValue);
previousIndexRef.current = activeIndex;
}
}
return {
newValue,
activeIndex
};
};
const handleTouchMove = useEventCallback(nativeEvent => {
// Ignore pointer events from a different pointer than the one that started the drag.
if ('pointerId' in nativeEvent && nativeEvent.pointerId !== activePointerIdRef.current) {
return;
}
const finger = trackFinger(nativeEvent, touchIdRef);
if (!finger) {
return;
}
moveCountRef.current += 1;
// Cancel move in case some other element consumed a pointerup event and it was not fired.
if (nativeEvent.type === 'pointermove' && nativeEvent.buttons === 0) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handleTouchEnd(nativeEvent);
return;
}
const newFingerValue = getValueAtFinger(finger);
if (!newFingerValue) {
return;
}
focusThumb(sliderRef, newFingerValue.activeIndex, setActive, false);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
setValueState(newFingerValue.newValue);
if (!dragging && moveCountRef.current > INTENTIONAL_DRAG_COUNT_THRESHOLD) {
setDragging(true);
}
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(nativeEvent, newFingerValue.newValue, newFingerValue.activeIndex);
}
});
const handleTouchEnd = useEventCallback(nativeEvent => {
// Ignore pointer events from a different pointer than the one that started the drag.
if ('pointerId' in nativeEvent && nativeEvent.pointerId !== activePointerIdRef.current) {
return;
}
const finger = trackFinger(nativeEvent, touchIdRef);
setDragging(false);
if (!finger) {
return;
}
const newFingerValue = getValueAtFinger(finger);
setActive(-1);
if (nativeEvent.type === 'touchend') {
setOpen(-1);
}
if (newFingerValue && onChangeCommitted) {
onChangeCommitted(nativeEvent, lastChangedValueRef.current ?? newFingerValue.newValue);
}
// Release pointer capture if applicable
if ('pointerType' in nativeEvent && sliderRef.current?.hasPointerCapture(nativeEvent.pointerId)) {
sliderRef.current.releasePointerCapture(nativeEvent.pointerId);
}
touchIdRef.current = undefined;
activePointerIdRef.current = -1;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
stopListening();
});
const handleTouchStart = useEventCallback(nativeEvent => {
if (disabled) {
return;
}
// If the pointer path already handled this interaction,
// only record the touch identifier and skip duplicate listener registration.
if (pointerDownHandledRef.current) {
pointerDownHandledRef.current = false;
const touch = nativeEvent.changedTouches[0];
if (touch != null) {
touchIdRef.current = touch.identifier;
}
return;
}
const touch = nativeEvent.changedTouches[0];
if (touch != null) {
// A number that uniquely identifies the current finger in the touch session.
touchIdRef.current = touch.identifier;
}
const finger = trackFinger(nativeEvent, touchIdRef);
if (finger !== false) {
previousIndexRef.current = -1;
const newFingerValue = getValueAtFinger(finger);
if (newFingerValue) {
focusThumb(sliderRef, newFingerValue.activeIndex, setActive, false);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
setValueState(newFingerValue.newValue);
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(nativeEvent, newFingerValue.newValue, newFingerValue.activeIndex);
}
}
}
moveCountRef.current = 0;
const doc = ownerDocument(sliderRef.current);
doc.addEventListener('touchmove', handleTouchMove, {
passive: true
});
doc.addEventListener('touchend', handleTouchEnd, {
passive: true
});
});
const stopListening = React.useCallback(() => {
const doc = ownerDocument(sliderRef.current);
doc.removeEventListener('pointermove', handleTouchMove);
doc.removeEventListener('pointerup', handleTouchEnd);
doc.removeEventListener('touchmove', handleTouchMove);
doc.removeEventListener('touchend', handleTouchEnd);
}, [handleTouchEnd, handleTouchMove]);
React.useEffect(() => {
const slider = sliderRef.current;
if (!slider) {
return undefined;
}
slider.addEventListener('touchstart', handleTouchStart, {
passive: true
});
return () => {
slider.removeEventListener('touchstart', handleTouchStart);
cancelFocusFrame();
stopListening();
};
}, [stopListening, handleTouchStart, cancelFocusFrame]);
React.useEffect(() => {
if (disabled) {
stopListening();
cancelFocusFrame();
}
}, [disabled, stopListening, cancelFocusFrame]);
const createHandlePointerDown = otherHandlers => event => {
otherHandlers.onPointerDown?.(event);
// On touch devices, the browser fires both pointerdown and touchstart for the
// same physical touch. Mark this BEFORE early returns so handleTouchStart always
// knows the pointer path saw this interaction — even if it was prevented or disabled.
if (event.pointerType === 'touch') {
pointerDownHandledRef.current = true;
}
if (disabled || event.defaultPrevented || event.button !== 0) {
return;
}
const finger = trackFinger(event, touchIdRef);
if (finger !== false) {
previousIndexRef.current = -1;
const newFingerValue = getValueAtFinger(finger);
if (newFingerValue) {
const thumbInput = sliderRef.current?.querySelector(`input[type="range"][data-index="${newFingerValue.activeIndex}"]`);
const doc = ownerDocument(sliderRef.current);
const pressedOnFocusedThumb = thumbInput != null && thumbInput === getActiveElement(doc);
setActive(newFingerValue.activeIndex);
lastUsedThumbIndexRef.current = newFingerValue.activeIndex;
if (pressedOnFocusedThumb) {
event.preventDefault();
} else {
cancelFocusFrame();
focusFrameRef.current = requestAnimationFrame(() => {
focusFrameRef.current = null;
focusThumb(sliderRef, newFingerValue.activeIndex, undefined, false);
});
}
setValueState(newFingerValue.newValue);
if (onChange && !areValuesEqual(newFingerValue.newValue, valueDerived)) {
handleChange(event, newFingerValue.newValue, newFingerValue.activeIndex);
}
}
}
moveCountRef.current = 0;
activePointerIdRef.current = event.pointerId;
const doc = ownerDocument(sliderRef.current);
// Use pointer capture for reliable drag tracking
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
// setPointerCapture can throw if the pointerId is invalid (e.g. synthetic
// events in tests, or the pointer was already released). The slider still
// works via document-level listeners; pointer capture is a progressive
// enhancement for reliable drag tracking.
}
doc.addEventListener('pointermove', handleTouchMove, {
passive: true
});
doc.addEventListener('pointerup', handleTouchEnd);
};
const trackOffset = valueToPercent(range ? values[0] : min, min, max);
const trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;
const getRootProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onPointerDown: createHandlePointerDown(externalHandlers)
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers
};
return {
...externalProps,
ref: handleRef,
...mergedEventHandlers
};
};
const createHandleMouseOver = otherHandlers => event => {
otherHandlers.onMouseOver?.(event);
const index = Number(event.currentTarget.getAttribute('data-index'));
setOpen(index);
};
const createHandleMouseLeave = otherHandlers => event => {
otherHandlers.onMouseLeave?.(event);
setOpen(-1);
};
const getThumbProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onMouseOver: createHandleMouseOver(externalHandlers),
onMouseLeave: createHandleMouseLeave(externalHandlers)
};
return {
...externalProps,
...externalHandlers,
...ownEventHandlers
};
};
const getThumbStyle = index => {
let zIndex;
if (range) {
if (active === index) {
zIndex = 2;
} else if (lastUsedThumbIndexRef.current === index) {
zIndex = 1;
}
} else if (active === index) {
zIndex = 1;
}
return {
// So the non active thumb doesn't show its label on hover.
pointerEvents: active !== -1 && active !== index ? 'none' : undefined,
zIndex
};
};
let cssWritingMode;
if (orientation === 'vertical') {
cssWritingMode = isRtl ? 'vertical-rl' : 'vertical-lr';
}
const getHiddenInputProps = (externalProps = EMPTY_OBJ) => {
const externalHandlers = extractEventHandlers(externalProps);
const ownEventHandlers = {
onChange: createHandleHiddenInputChange(externalHandlers),
onFocus: createHandleHiddenInputFocus(externalHandlers),
onBlur: createHandleHiddenInputBlur(externalHandlers),
onKeyDown: createHandleHiddenInputKeyDown(externalHandlers)
};
const mergedEventHandlers = {
...externalHandlers,
...ownEventHandlers
};
return {
tabIndex,
'aria-labelledby': ariaLabelledby,
'aria-orientation': orientation,
'aria-valuemax': scale(max),
'aria-valuemin': scale(min),
name,
type: 'range',
min: parameters.min,
max: parameters.max,
step: parameters.step === null && parameters.marks ? 'any' : parameters.step ?? undefined,
disabled,
...externalProps,
...mergedEventHandlers,
style: {
...visuallyHidden,
direction: isRtl ? 'rtl' : 'ltr',
// So that VoiceOver's focus indicator matches the thumb's dimensions
width: '100%',
height: '100%',
writingMode: cssWritingMode
}
};
};
return {
active,
axis: axis,
axisProps,
dragging,
focusedThumbIndex,
getHiddenInputProps,
getRootProps,
getThumbProps,
marks,
open,
range,
rootRef: handleRef,
trackLeap,
trackOffset,
values,
getThumbStyle
};
}
+226
View File
@@ -0,0 +1,226 @@
import * as React from 'react';
export interface UseSliderParameters {
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby'?: string | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: number | ReadonlyArray<number> | undefined;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean | undefined;
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap?: boolean | undefined;
/**
* If `true` the Slider will be rendered right-to-left (with the lowest value on the right-hand side).
* @default false
*/
isRtl?: boolean | undefined;
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks?: boolean | ReadonlyArray<Mark> | undefined;
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max?: number | undefined;
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min?: number | undefined;
/**
* Name attribute of the hidden `input` element.
*/
name?: string | undefined;
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange?: ((event: Event, value: number | number[], activeThumb: number) => void) | undefined;
/**
* Callback function that is fired when the pointer or touch interaction ends.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
*/
onChangeCommitted?: ((event: React.SyntheticEvent | Event, value: number | number[]) => void) | undefined;
/**
* The component orientation.
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical' | undefined;
/**
* The ref attached to the root of the Slider.
*/
rootRef?: React.Ref<Element> | undefined;
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale?: ((value: number) => number) | undefined;
/**
* The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
* @default 10
*/
shiftStep?: number | undefined;
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step?: number | null | undefined;
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex?: number | undefined;
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value?: number | ReadonlyArray<number> | undefined;
}
export interface Mark {
value: number;
label?: React.ReactNode;
}
export type UseSliderRootSlotOwnProps = {
onPointerDown: React.HTMLAttributes<HTMLSpanElement>['onPointerDown'];
ref: React.RefCallback<Element> | null;
};
export type UseSliderRootSlotProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderRootSlotOwnProps> & UseSliderRootSlotOwnProps;
export type UseSliderThumbSlotOwnProps = {
onMouseLeave: React.MouseEventHandler;
onMouseOver: React.MouseEventHandler;
};
export type UseSliderThumbSlotProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderThumbSlotOwnProps> & UseSliderThumbSlotOwnProps;
export type UseSliderHiddenInputOwnProps = {
'aria-labelledby'?: string | undefined;
'aria-orientation'?: React.AriaAttributes['aria-orientation'] | undefined;
'aria-valuemax'?: React.AriaAttributes['aria-valuemax'] | undefined;
'aria-valuemin'?: React.AriaAttributes['aria-valuemin'] | undefined;
disabled: boolean;
name?: string | undefined;
onBlur: React.FocusEventHandler;
onChange: React.ChangeEventHandler;
onFocus: React.FocusEventHandler;
step?: number | 'any' | undefined;
style: React.CSSProperties;
tabIndex?: number | undefined;
type?: React.InputHTMLAttributes<HTMLInputElement>['type'] | undefined;
};
export type UseSliderHiddenInputProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderHiddenInputOwnProps> & UseSliderHiddenInputOwnProps;
export type Axis = 'horizontal' | 'vertical' | 'horizontal-reverse';
export interface AxisProps<T extends Axis> {
offset: (percent: number) => T extends 'horizontal' ? {
left: string;
} : T extends 'vertical' ? {
bottom: string;
} : T extends 'horizontal-reverse' ? {
right: string;
} : never;
leap: (percent: number) => T extends 'horizontal' | 'horizontal-reverse' ? {
width: string;
} : T extends 'vertical' ? {
height: string;
} : never;
}
export interface UseSliderReturnValue {
/**
* The active index of the slider.
*/
active: number;
/**
* The orientation of the slider.
*/
axis: Axis;
/**
* Returns the `offset` and `leap` methods to calculate the positioning styles based on the slider axis.
*/
axisProps: { [key in Axis]: AxisProps<key> };
/**
* If `true`, the slider is being dragged.
*/
dragging: boolean;
/**
* The index of the thumb which is focused on the slider.
*/
focusedThumbIndex: number;
/**
* Resolver for the hidden input slot's props.
* @param externalProps props for the hidden input slot
* @returns props that should be spread on the hidden input slot
*/
getHiddenInputProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderHiddenInputProps<ExternalProps>;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderRootSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's props.
* @param externalProps props for the thumb slot
* @returns props that should be spread on the thumb slot
*/
getThumbProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderThumbSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's style prop.
* @param index of the currently moved thumb
* @returns props that should be spread on the style prop of thumb slot
*/
getThumbStyle: (index: number) => object;
/**
* The marks of the slider. Marks indicate predetermined values to which the user can move the slider.
*/
marks: readonly Mark[];
/**
* The thumb index for the current value when in hover state.
*/
open: number;
/**
* If `true`, the slider is a range slider when the `value` prop passed is an array.
*/
range: boolean;
/**
* Ref to the root slot's DOM node.
*/
rootRef: React.RefCallback<Element> | null;
/**
* The track leap for the current value of the slider.
*/
trackLeap: number;
/**
* The track offset for the current value of the slider.
*/
trackOffset: number;
/**
* The possible values of the slider.
*/
values: number[];
}
+226
View File
@@ -0,0 +1,226 @@
import * as React from 'react';
export interface UseSliderParameters {
/**
* The id of the element containing a label for the slider.
*/
'aria-labelledby'?: string | undefined;
/**
* The default value. Use when the component is not controlled.
*/
defaultValue?: number | ReadonlyArray<number> | undefined;
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean | undefined;
/**
* If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb.
* @default false
*/
disableSwap?: boolean | undefined;
/**
* If `true` the Slider will be rendered right-to-left (with the lowest value on the right-hand side).
* @default false
*/
isRtl?: boolean | undefined;
/**
* Marks indicate predetermined values to which the user can move the slider.
* If `true` the marks are spaced according the value of the `step` prop.
* If an array, it should contain objects with `value` and an optional `label` keys.
* @default false
*/
marks?: boolean | ReadonlyArray<Mark> | undefined;
/**
* The maximum allowed value of the slider.
* Should not be equal to min.
* @default 100
*/
max?: number | undefined;
/**
* The minimum allowed value of the slider.
* Should not be equal to max.
* @default 0
*/
min?: number | undefined;
/**
* Name attribute of the hidden `input` element.
*/
name?: string | undefined;
/**
* Callback function that is fired when the slider's value changed.
*
* @param {Event} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
* @param {number} activeThumb Index of the currently moved thumb.
*/
onChange?: ((event: Event, value: number | number[], activeThumb: number) => void) | undefined;
/**
* Callback function that is fired when the pointer or touch interaction ends.
*
* @param {React.SyntheticEvent | Event} event The event source of the callback. **Warning**: This is a generic event not a change event.
* @param {number | number[]} value The new value.
*/
onChangeCommitted?: ((event: React.SyntheticEvent | Event, value: number | number[]) => void) | undefined;
/**
* The component orientation.
* @default 'horizontal'
*/
orientation?: 'horizontal' | 'vertical' | undefined;
/**
* The ref attached to the root of the Slider.
*/
rootRef?: React.Ref<Element> | undefined;
/**
* A transformation function, to change the scale of the slider.
* @param {any} x
* @returns {any}
* @default function Identity(x) {
* return x;
* }
*/
scale?: ((value: number) => number) | undefined;
/**
* The granularity with which the slider can step through values when using Page Up/Page Down or Shift + Arrow Up/Arrow Down.
* @default 10
*/
shiftStep?: number | undefined;
/**
* The granularity with which the slider can step through values. (A "discrete" slider.)
* The `min` prop serves as the origin for the valid values.
* We recommend (max - min) to be evenly divisible by the step.
*
* When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
* @default 1
*/
step?: number | null | undefined;
/**
* Tab index attribute of the hidden `input` element.
*/
tabIndex?: number | undefined;
/**
* The value of the slider.
* For ranged sliders, provide an array with two values.
*/
value?: number | ReadonlyArray<number> | undefined;
}
export interface Mark {
value: number;
label?: React.ReactNode;
}
export type UseSliderRootSlotOwnProps = {
onPointerDown: React.HTMLAttributes<HTMLSpanElement>['onPointerDown'];
ref: React.RefCallback<Element> | null;
};
export type UseSliderRootSlotProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderRootSlotOwnProps> & UseSliderRootSlotOwnProps;
export type UseSliderThumbSlotOwnProps = {
onMouseLeave: React.MouseEventHandler;
onMouseOver: React.MouseEventHandler;
};
export type UseSliderThumbSlotProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderThumbSlotOwnProps> & UseSliderThumbSlotOwnProps;
export type UseSliderHiddenInputOwnProps = {
'aria-labelledby'?: string | undefined;
'aria-orientation'?: React.AriaAttributes['aria-orientation'] | undefined;
'aria-valuemax'?: React.AriaAttributes['aria-valuemax'] | undefined;
'aria-valuemin'?: React.AriaAttributes['aria-valuemin'] | undefined;
disabled: boolean;
name?: string | undefined;
onBlur: React.FocusEventHandler;
onChange: React.ChangeEventHandler;
onFocus: React.FocusEventHandler;
step?: number | 'any' | undefined;
style: React.CSSProperties;
tabIndex?: number | undefined;
type?: React.InputHTMLAttributes<HTMLInputElement>['type'] | undefined;
};
export type UseSliderHiddenInputProps<ExternalProps = {}> = Omit<ExternalProps, keyof UseSliderHiddenInputOwnProps> & UseSliderHiddenInputOwnProps;
export type Axis = 'horizontal' | 'vertical' | 'horizontal-reverse';
export interface AxisProps<T extends Axis> {
offset: (percent: number) => T extends 'horizontal' ? {
left: string;
} : T extends 'vertical' ? {
bottom: string;
} : T extends 'horizontal-reverse' ? {
right: string;
} : never;
leap: (percent: number) => T extends 'horizontal' | 'horizontal-reverse' ? {
width: string;
} : T extends 'vertical' ? {
height: string;
} : never;
}
export interface UseSliderReturnValue {
/**
* The active index of the slider.
*/
active: number;
/**
* The orientation of the slider.
*/
axis: Axis;
/**
* Returns the `offset` and `leap` methods to calculate the positioning styles based on the slider axis.
*/
axisProps: { [key in Axis]: AxisProps<key> };
/**
* If `true`, the slider is being dragged.
*/
dragging: boolean;
/**
* The index of the thumb which is focused on the slider.
*/
focusedThumbIndex: number;
/**
* Resolver for the hidden input slot's props.
* @param externalProps props for the hidden input slot
* @returns props that should be spread on the hidden input slot
*/
getHiddenInputProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderHiddenInputProps<ExternalProps>;
/**
* Resolver for the root slot's props.
* @param externalProps props for the root slot
* @returns props that should be spread on the root slot
*/
getRootProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderRootSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's props.
* @param externalProps props for the thumb slot
* @returns props that should be spread on the thumb slot
*/
getThumbProps: <ExternalProps extends Record<string, unknown> = {}>(externalProps?: ExternalProps) => UseSliderThumbSlotProps<ExternalProps>;
/**
* Resolver for the thumb slot's style prop.
* @param index of the currently moved thumb
* @returns props that should be spread on the style prop of thumb slot
*/
getThumbStyle: (index: number) => object;
/**
* The marks of the slider. Marks indicate predetermined values to which the user can move the slider.
*/
marks: readonly Mark[];
/**
* The thumb index for the current value when in hover state.
*/
open: number;
/**
* If `true`, the slider is a range slider when the `value` prop passed is an array.
*/
range: boolean;
/**
* Ref to the root slot's DOM node.
*/
rootRef: React.RefCallback<Element> | null;
/**
* The track leap for the current value of the slider.
*/
trackLeap: number;
/**
* The track offset for the current value of the slider.
*/
trackOffset: number;
/**
* The possible values of the slider.
*/
values: number[];
}
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+1
View File
@@ -0,0 +1 @@
export {};