UNPKG

@react-native-assets/slider

Version:

Lightweight slider for React-Native and React-Native-Web. A Range slider is included

48 lines (47 loc) 2.15 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const useEvent_1 = require("./useEvent"); const useRounding_1 = __importDefault(require("./useRounding")); /** Handle the state of a thumb for a slider */ const useThumb = (props) => { const { step, value: propValue, slideOnTap, minimumValue, maximumValue, onValueChange } = props; const [value, setValue] = react_1.default.useState(propValue || minimumValue); // The value desired const round = (0, useRounding_1.default)({ step, minimumValue, maximumValue }); /** Update the thumb value */ const updateValue = (0, useEvent_1.useEvent)((newValue, fireEvent) => { const rounded = round(newValue); if (rounded === value) return; if (!fireEvent || (onValueChange === null || onValueChange === void 0 ? void 0 : onValueChange(rounded)) !== false) setValue(rounded); }); const roundValue = (0, useEvent_1.useEvent)(() => round(value)); // Update the value on bounds change react_1.default.useEffect(() => { roundValue(); }, [step, minimumValue, maximumValue, roundValue]); // Update the value on propchange react_1.default.useEffect(() => { updateValue(propValue); }, [propValue, updateValue]); /** Call onValueChange when the user changed the value */ const userUpdateValue = (0, useEvent_1.useEvent)((newValue) => { updateValue(newValue, true); }); /** * Indicates whether we accept to move to the specified position. * If the position is too far and slideOnTap is not set, we don't accept sliding there **/ const canMove = (0, useEvent_1.useEvent)((newValue) => { if (slideOnTap) return true; else return Math.abs(newValue - value) < (step || (maximumValue - minimumValue) / 10 || 1); }); return { updateValue: userUpdateValue, canMove, value }; }; exports.default = useThumb;