@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
74 lines • 3.23 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Slider, TextInput } from '@neo4j-ndl/react';
import { useCallback, useState } from 'react';
const MIN_VALUE = 0;
const MAX_VALUE = 100;
const STEP = 5;
const INITIAL_VALUE = 50;
const getValidationError = (input) => {
const trimmed = input.trim();
if (!trimmed) {
return { error: 'Value is required', isValid: false };
}
const numValue = Number(trimmed);
if (isNaN(numValue)) {
return { error: 'Please enter a valid number', isValid: false };
}
if (!Number.isInteger(numValue)) {
return { error: 'Please enter a whole number', isValid: false };
}
if (numValue < MIN_VALUE) {
return { error: `Value must be at least ${MIN_VALUE}`, isValid: false };
}
if (numValue > MAX_VALUE) {
return { error: `Value must be at most ${MAX_VALUE}`, isValid: false };
}
return { error: undefined, isValid: true };
};
const Component = () => {
const [value, setValue] = useState(INITIAL_VALUE);
const [inputValue, setInputValue] = useState(String(INITIAL_VALUE));
const { error, isValid } = getValidationError(inputValue);
const hasError = !isValid;
const handleInputChange = useCallback((e) => {
const newInputValue = e.target.value;
setInputValue(newInputValue);
if (isValid) {
setValue(Number(newInputValue));
}
}, [setInputValue, setValue, isValid]);
const handleSliderChange = useCallback((newValue) => {
setValue(newValue);
setInputValue(String(newValue));
}, [setInputValue, setValue]);
return (_jsxs("div", { className: "n-flex n-flex-col n-gap-token-16", children: [_jsx(TextInput, { label: "Slider value", helpText: `Enter a value between ${MIN_VALUE} and ${MAX_VALUE}`, isRequired: true, errorText: error, htmlAttributes: {
max: MAX_VALUE,
min: MIN_VALUE,
step: STEP,
type: 'number',
}, value: inputValue, onChange: handleInputChange }), _jsx(Slider, { type: "single", value: value, onChange: handleSliderChange, minValue: MIN_VALUE, maxValue: MAX_VALUE, step: STEP, showSteps: true, showValues: true, isDisabled: hasError, inputProps: {
'aria-valuetext': `${value} out of ${MAX_VALUE}`,
} })] }));
};
export default Component;
//# sourceMappingURL=slider-single-controlled.story.js.map