Skip to content

Commit

Permalink
Use scrollTo instead of scrollBy
Browse files Browse the repository at this point in the history
  • Loading branch information
clauderic committed Mar 16, 2022
1 parent a41e5b8 commit e6e242c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/keyboard-sensor-scrollto.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@dnd-kit/core': patch
---

The `KeyboardSensor` was updated to use `scrollTo` instead of `scrollBy` when it is able to fully scroll to the new coordinates returned by the coordinate getter function. This resolves issues that can happen with `scrollBy` when called in rapid succession.
22 changes: 12 additions & 10 deletions packages/core/src/sensors/keyboard/KeyboardSensor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,18 +164,19 @@ export class KeyboardSensor implements SensorInstance {
(direction === KeyboardCode.Up && !isTop);

if (canScrollX && clampedCoordinates.x !== newCoordinates.x) {
const newScrollCoordinates =
scrollContainer.scrollLeft + coordinatesDelta.x;
const canFullyScrollToNewCoordinates =
(direction === KeyboardCode.Right &&
scrollContainer.scrollLeft + coordinatesDelta.x <=
maxScroll.x) ||
newScrollCoordinates <= maxScroll.x) ||
(direction === KeyboardCode.Left &&
scrollContainer.scrollLeft + coordinatesDelta.x >= minScroll.x);
newScrollCoordinates >= minScroll.x);

if (canFullyScrollToNewCoordinates) {
// We don't need to update coordinates, the scroll adjustment alone will trigger
// logic to auto-detect the new container we are over
scrollContainer.scrollBy({
left: coordinatesDelta.x,
scrollContainer.scrollTo({
left: newScrollCoordinates,
behavior: scrollBehavior,
});
return;
Expand All @@ -192,18 +193,19 @@ export class KeyboardSensor implements SensorInstance {
});
break;
} else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) {
const newScrollCoordinates =
scrollContainer.scrollTop + coordinatesDelta.y;
const canFullyScrollToNewCoordinates =
(direction === KeyboardCode.Down &&
scrollContainer.scrollTop + coordinatesDelta.y <=
maxScroll.y) ||
newScrollCoordinates <= maxScroll.y) ||
(direction === KeyboardCode.Up &&
scrollContainer.scrollTop + coordinatesDelta.y >= minScroll.y);
newScrollCoordinates >= minScroll.y);

if (canFullyScrollToNewCoordinates) {
// We don't need to update coordinates, the scroll adjustment alone will trigger
// logic to auto-detect the new container we are over
scrollContainer.scrollBy({
top: coordinatesDelta.y,
scrollContainer.scrollTo({
top: newScrollCoordinates,
behavior: scrollBehavior,
});
return;
Expand Down

0 comments on commit e6e242c

Please sign in to comment.