Skip to content

Commit

Permalink
Try using a percentage based calculation for block drag scrolling vel…
Browse files Browse the repository at this point in the history
…ocity. (#23448)

* Use a percentage based calculation for scrolling when dragging blocks

* Factor in scroll container offset
  • Loading branch information
talldan authored Jun 29, 2020
1 parent e421896 commit 21e86f1
Showing 1 changed file with 38 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { useCallback, useEffect, useRef } from '@wordpress/element';

const SCROLL_INACTIVE_DISTANCE_PX = 50;
const SCROLL_INTERVAL_MS = 25;
const PIXELS_PER_SECOND_PER_DISTANCE = 5;
const PIXELS_PER_SECOND_PER_PERCENTAGE = 1000;
const VELOCITY_MULTIPLIER =
PIXELS_PER_SECOND_PER_DISTANCE * ( SCROLL_INTERVAL_MS / 1000 );
PIXELS_PER_SECOND_PER_PERCENTAGE * ( SCROLL_INTERVAL_MS / 1000 );

/**
* React hook that scrolls the scroll container when a block is being dragged.
Expand Down Expand Up @@ -60,15 +60,42 @@ export default function useScrollWhenDragging( dragElement ) {
);

const scrollOnDragOver = useCallback( ( event ) => {
const distanceY = event.clientY - dragStartY.current;
if ( distanceY > SCROLL_INACTIVE_DISTANCE_PX ) {
velocityY.current =
VELOCITY_MULTIPLIER *
( distanceY - SCROLL_INACTIVE_DISTANCE_PX );
} else if ( distanceY < -SCROLL_INACTIVE_DISTANCE_PX ) {
velocityY.current =
VELOCITY_MULTIPLIER *
( distanceY + SCROLL_INACTIVE_DISTANCE_PX );
const scrollParentHeight = scrollParentY.current.offsetHeight;
const offsetDragStartPosition =
dragStartY.current - scrollParentY.current.offsetTop;
const offsetDragPosition =
event.clientY - scrollParentY.current.offsetTop;

if ( event.clientY > offsetDragStartPosition ) {
// User is dragging downwards.
const moveableDistance = Math.max(
scrollParentHeight -
offsetDragStartPosition -
SCROLL_INACTIVE_DISTANCE_PX,
0
);
const dragDistance = Math.max(
offsetDragPosition -
offsetDragStartPosition -
SCROLL_INACTIVE_DISTANCE_PX,
0
);
const distancePercentage = dragDistance / moveableDistance;
velocityY.current = VELOCITY_MULTIPLIER * distancePercentage;
} else if ( event.clientY < offsetDragStartPosition ) {
// User is dragging upwards.
const moveableDistance = Math.max(
offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX,
0
);
const dragDistance = Math.max(
offsetDragStartPosition -
offsetDragPosition -
SCROLL_INACTIVE_DISTANCE_PX,
0
);
const distancePercentage = dragDistance / moveableDistance;
velocityY.current = -VELOCITY_MULTIPLIER * distancePercentage;
} else {
velocityY.current = 0;
}
Expand Down

0 comments on commit 21e86f1

Please sign in to comment.