react-range icon indicating copy to clipboard operation
react-range copied to clipboard

Feature request: Minimal distance between values

Open cibulka opened this issue 5 years ago • 5 comments

Hello, thanks for an awesome library!

I need to force the values to have minimal numeric distance between them - and it seems that it could be a nice feature for the library. So far I manipulate the value in onChange handler, but it is a bit laggy and I think the better place for doing so would be in the core, especially on utils/normalizeValue function.

Here's what I do (in simplified version):

const MAX = 100;
const MIN = 0;
const MIN_DISTANCE = 2;

const onChangeHandler = (values: number[]) => {
  return values.map((value: number) => {
    const prev = arr[i - 1];
    const next = arr[i + 1];
    let result = value;
    if (prev !== undefined && prev + MIN_DISTANCE > value) result = prev + MIN_DISTANCE;
    if (next !== undefined && next - MIN_DISTANCE < value) result = next - MIN_DISTANCE;
    return Math.max(Math.min(result, props.max || MAX), props.min || MIN);
  });
};

return <MyModifiedRange max={MAX} min={MIN} minDistance={MIN_DISTANCE} onChange={onChangeHandler} />

I'm not sure if that's the best approach to things (and that's why I did not lead with PR), but still seems that it would be a feature that would useful for more people.

Thanks!

ps: My use case was to chose preferred timeRange for a process of specific length. So if that length was 2 hours, values in that range could have been [10:00, 12:00] or [10:33, 12:33], but not [10:00, 11:00]

cibulka avatar Nov 15 '20 22:11 cibulka

Why can't you enforce that by setting min, max and step values?

tajo avatar Nov 16 '20 19:11 tajo

Because step and minDistance are two different things. With minDistance = 2 you can still have values [2, 4.5], which would require step = 0.5.

cibulka avatar Nov 16 '20 19:11 cibulka

I guess there could be also maxDistance. I wonder if this could be improved

So far I manipulate the value in onChange handler, but it is a bit laggy

so it's not laggy instead of adding new APIs.

tajo avatar Nov 16 '20 21:11 tajo

Yes, maxDistance would be nice as well!

When I was considering doing the PR I went through you code, and I thought that the place for the addition was utils/normalizeValue function (as we want exactly that).

cibulka avatar Nov 16 '20 22:11 cibulka

If you want to, you should try to put a PR together.

tajo avatar Nov 17 '20 22:11 tajo