airbnb / visx

🐯 visx | visualization components
https://airbnb.io/visx
MIT License
19.4k stars 712 forks source link

[@visx/drag] Enhancement to limit dx and dy #1866

Open agoldis opened 2 months ago

agoldis commented 2 months ago

Trying to enhance the library to limit dx and dy values for useDrag, motivation being limit the allowed distance for drag operation.

For example, without dx restrictions:

https://github.com/user-attachments/assets/cb20ed96-0df9-496d-bc05-75cfbf445859

After the suggested change:

https://github.com/user-attachments/assets/00f35d1b-2362-46cc-a302-a0becc363759

I wanted to confirm my naive implementation before opening a PR:

restrict?: {
    xMin?: number;
    xMax?: number;
    yMin?: number;
    yMax?: number;
    dxMax?: number; // new 
    dyMax?: number; // new 
    dxMin?: number; // new 
    dyMin?: number; // new 
};
let dx = dragPoint.x - x;
let dy= dragPoint.y - y;
if ( typeof restrict.dxMax === "number" && _dx > restrict.dxMax) {
  dx =  restrict.dxMax;
}
if (typeof restrict.dyMax === "number" && _dy > restrict.dyMax) {
  dy = restrict.dyMax;
}
if (typeof restrict.dxMin === "number" && _dx < restrict.dxMin) {
  dx =  restrict.dxMin;
}
if (typeof restrict.dyMin === "number" && _dy < restrict.dyMin) {
  dy =  restrict.dyMin;
}

return {
  ...currState,
  dx,
  dy,
};

Would appreciate weighing in on this approach.