Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Prevent min constraint going negative #2695
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejolley authored and senadir committed Jul 29, 2020
1 parent c31f3f3 commit fc6e6b0
Showing 1 changed file with 33 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,45 +1,53 @@
const parseValid = ( value, fallback ) => {
const parsedValue =
typeof value === 'string' ? parseInt( value, 10 ) : value;

if ( ! Number.isFinite( parsedValue ) ) {
return fallback;
}

return parsedValue;
};

/**
* Validate a min and max value for a range slider against defined constraints (min, max, step).
*
* @param {Array} values Array containing min and max values.
* @param {number|null} min Min allowed value for the sliders.
* @param {number|null} max Max allowed value for the sliders.
* @param {number|null} minAllowed Min allowed value for the sliders.
* @param {number|null} maxAllowed Max allowed value for the sliders.
* @param {number} step Step value for the sliders.
* @param {boolean} isMin Whether we're currently interacting with the min range slider or not, so we update the correct values.
* @return {Array} Validated and updated min/max values that fit within the range slider constraints.
*/
export const constrainRangeSliderValues = (
values,
min,
max,
minAllowed,
maxAllowed,
step = 1,
isMin = false
) => {
let minValue = parseInt( values[ 0 ], 10 );
let maxValue = parseInt( values[ 1 ], 10 );
const hasMinConstraint = Number.isFinite( minAllowed );
const hasMaxConstraint = Number.isFinite( maxAllowed );
const minConstraint = minAllowed || 0;
const maxConstraint = maxAllowed || step;

if ( ! Number.isFinite( minValue ) ) {
minValue = min || 0;
}

if ( ! Number.isFinite( maxValue ) ) {
maxValue = max || step;
}
let minValue = parseValid( values[ 0 ], minConstraint );
let maxValue = parseValid( values[ 1 ], maxConstraint );

if ( Number.isFinite( min ) && min > minValue ) {
minValue = min;
if ( hasMinConstraint && minConstraint > minValue ) {
minValue = minConstraint;
}

if ( Number.isFinite( max ) && max <= minValue ) {
minValue = max - step;
if ( hasMaxConstraint && maxConstraint <= minValue ) {
minValue = maxConstraint - step;
}

if ( Number.isFinite( min ) && min >= maxValue ) {
maxValue = min + step;
if ( hasMinConstraint && minConstraint >= maxValue ) {
maxValue = minConstraint + step;
}

if ( Number.isFinite( max ) && max < maxValue ) {
maxValue = max;
if ( hasMaxConstraint && maxConstraint < maxValue ) {
maxValue = maxConstraint;
}

if ( ! isMin && minValue >= maxValue ) {
Expand All @@ -50,5 +58,9 @@ export const constrainRangeSliderValues = (
maxValue = minValue + step;
}

if ( minValue < 0 ) {
minValue = 0;
}

return [ minValue, maxValue ];
};

0 comments on commit fc6e6b0

Please sign in to comment.