Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/beige-llamas-bake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@dnd-kit/dom': minor
---

Added a `shouldScroll` predicate option to `AutoScroller.configure()` for filtering auto-scroll candidates during drag operations.
18 changes: 18 additions & 0 deletions apps/docs/docs/extend/plugins/auto-scroller.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,24 @@ function App() {
Base scroll speed multiplier. The scroll speed scales linearly as the pointer approaches the edge of a scrollable container — higher values scroll faster.
</ParamField>

<ParamField path="shouldScroll" type="(args: { scrollable: Element; source: Draggable | null; target: Droppable | null; manager: DragDropManager }) => boolean">
Predicate that controls whether a scrollable candidate is eligible for auto-scrolling during the current drag operation.

Return `false` to skip a candidate and continue checking the next scrollable ancestor. This is useful when draggable items are themselves scrollable and should not auto-scroll while hovering over sibling items.

```ts
AutoScroller.configure({
shouldScroll({scrollable, source}) {
return (
source?.element?.contains(scrollable) ||
!scrollable.classList.contains('Item')
);
},
});
```

</ParamField>

<ParamField path="threshold" type="number | { x: number; y: number }" default="{ x: 0.2, y: 0.2 }">
Percentage of container dimensions that defines the scroll activation zone. For example, `0.2` means scrolling activates when the pointer enters the outer 20% of a scrollable container.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import React, {memo, useEffect, useState} from 'react';
import type {CSSProperties, PropsWithChildren} from 'react';
import {AutoScroller, Feedback} from '@dnd-kit/dom';
import {DragDropProvider} from '@dnd-kit/react';
import {useSortable} from '@dnd-kit/react/sortable';
import {directionBiased} from '@dnd-kit/collision';
import {move} from '@dnd-kit/helpers';
import type {Customizable, Plugins, UniqueIdentifier} from '@dnd-kit/abstract';

import {Handle, Item} from '../../components/index.ts';
import {createRange} from '@dnd-kit/stories-shared/utilities';

interface Props {
itemCount?: number;
preventSiblingScroll?: boolean;
testIdPrefix?: string;
}

export function ScrollableItemsExample({
itemCount = 8,
preventSiblingScroll,
testIdPrefix = 'scrollable-item',
}: Props) {
const [items, setItems] = useState(() => createRange(itemCount));

useEffect(() => {
setItems(createRange(itemCount));
}, [itemCount]);
const plugins: Customizable<Plugins> | undefined = preventSiblingScroll
? (defaults) => [
...defaults,
AutoScroller.configure({
shouldScroll({manager, scrollable, source, target}) {
if (
manager.dragOperation.source !== source ||
manager.dragOperation.target !== target
) {
return false;
}

return (
source?.element?.contains(scrollable) ||
!scrollable.classList.contains('Item')
);
},
}),
]
: undefined;

return (
<DragDropProvider
plugins={plugins}
onDragEnd={(event) => {
setItems((items) => move(items, event));
}}
>
<div style={wrapperStyles}>
{items.map((id, index) => (
<ScrollableSortableItem
key={id}
id={id}
index={index}
testIdPrefix={testIdPrefix}
/>
))}
</div>
</DragDropProvider>
);
}

interface SortableItemProps {
id: UniqueIdentifier;
index: number;
testIdPrefix: string;
}

const ScrollableSortableItem = memo(function ScrollableSortableItem({
id,
index,
testIdPrefix,
}: PropsWithChildren<SortableItemProps>) {
const {handleRef, isDragging, ref} = useSortable({
id,
index,
collisionDetector: directionBiased,
plugins: (defaults) => [
...defaults,
Feedback.configure({feedback: 'clone'}),
],
});

return (
<Item
ref={ref}
actions={<Handle ref={handleRef} />}
data-testid={`${testIdPrefix}-${id}`}
shadow={isDragging}
style={itemStyles}
>
<div style={contentStyles}>
<strong style={titleStyles}>Item {id}</strong>
<div style={rowsStyles}>
{createRange(14).map((row) => (
<span key={row} style={rowStyles}>
Detail {row}
</span>
))}
</div>
</div>
</Item>
);
});

const wrapperStyles: CSSProperties = {
alignItems: 'center',
display: 'flex',
flexDirection: 'column',
gap: 18,
padding: '30px',
};

const itemStyles: CSSProperties = {
alignItems: 'stretch',
height: 150,
maxWidth: 420,
overflowAnchor: 'none',
overflowY: 'auto',
padding: 0,
};

const contentStyles: CSSProperties = {
display: 'flex',
flex: 1,
flexDirection: 'column',
gap: 12,
minWidth: 0,
padding: '16px 20px',
};

const titleStyles: CSSProperties = {
color: '#222',
fontSize: 15,
fontWeight: 600,
};

const rowsStyles: CSSProperties = {
display: 'grid',
gap: 8,
};

const rowStyles: CSSProperties = {
background: '#f5f6fa',
borderRadius: 4,
color: '#666',
display: 'block',
padding: '8px 10px',
};
25 changes: 25 additions & 0 deletions apps/stories/stories/react/Sortable/Vertical/Vertical.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {Feedback} from '@dnd-kit/dom';
import {SortableExample} from '../SortableExample';
import {AnchorElementsExample} from './AnchorElementsExample';
import {AutoScrollExample} from './AutoScrollExample';
import {ScrollableItemsExample} from './ScrollableItemsExample';

const meta: Meta<typeof SortableExample> = {
title: 'React/Sortable/Vertical list',
Expand Down Expand Up @@ -169,6 +170,30 @@ export const AutoScrollCustomSpeed: AutoScrollStory = {
},
};

type ScrollableItemsStory = StoryObj<typeof ScrollableItemsExample>;

export const ScrollableSiblingItems: ScrollableItemsStory = {
name: 'Scrollable sibling items',
render: (args) => <ScrollableItemsExample {...args} />,
args: {
itemCount: 8,
preventSiblingScroll: true,
},
argTypes: {
itemCount: {
control: {type: 'number', min: 2, max: 20, step: 1},
},
preventSiblingScroll: {
control: 'boolean',
},
testIdPrefix: {
table: {
disable: true,
},
},
},
};

export const NestedScroll: Story = {
name: 'Nested scroll',
args: {
Expand Down
126 changes: 115 additions & 11 deletions apps/stories/tests/sortable-scroll.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type {Locator, Page} from '@playwright/test';
import {test, expect} from '../../stories-shared/tests/fixtures.ts';

test.describe('Auto-scrolling', () => {
Expand Down Expand Up @@ -25,19 +26,15 @@ test.describe('Auto-scrolling', () => {
await dnd.page.mouse.down();

// Drag toward the bottom edge of the viewport
await dnd.page.mouse.move(
box!.x + box!.width / 2,
viewport.height - 10,
{steps: 20}
);
await dnd.page.mouse.move(box!.x + box!.width / 2, viewport.height - 10, {
steps: 20,
});

// Wait for auto-scroll to kick in
await expect
.poll(
() =>
dnd.page.evaluate(
() => document.scrollingElement?.scrollTop ?? 0
),
dnd.page.evaluate(() => document.scrollingElement?.scrollTop ?? 0),
{timeout: 3_000}
)
.toBeGreaterThan(scrollBefore);
Expand Down Expand Up @@ -68,9 +65,7 @@ test.describe('Auto-scrolling', () => {
await expect
.poll(
() =>
dnd.page.evaluate(
() => document.scrollingElement?.scrollTop ?? 0
),
dnd.page.evaluate(() => document.scrollingElement?.scrollTop ?? 0),
{timeout: 5_000}
)
.toBeGreaterThan(0);
Expand Down Expand Up @@ -119,4 +114,113 @@ test.describe('Auto-scrolling', () => {
await dnd.waitForDrop();
});
});

test.describe('Scrollable sibling items', () => {
test.beforeEach(async ({dnd}) => {
await dnd.goto('react-sortable-vertical-list--scrollable-sibling-items');
await expect(dnd.page.getByTestId('scrollable-item-1')).toBeVisible();
});

test('does not scroll sibling item content when dragging top-to-bottom', async ({
dnd,
}) => {
const sibling = dnd.page.getByTestId('scrollable-item-2');
const scrollBefore = await sibling.evaluate((element) => {
element.scrollTop = 0;

return element.scrollTop;
});

await dragAndHoldOverSibling({
dnd,
testIdPrefix: 'scrollable-item',
sourceId: 1,
siblingId: 2,
edge: 'bottom',
});

try {
await expect
.poll(() => sibling.evaluate((element) => element.scrollTop))
.toBe(scrollBefore);
} finally {
await dnd.page.mouse.up();
await dnd.waitForDrop();
}
});

test('does not scroll sibling item content when dragging bottom-to-top', async ({
dnd,
}) => {
const sibling = dnd.page.getByTestId('scrollable-item-2');
const scrollBefore = await sibling.evaluate((element) => {
element.scrollTop = 120;

return element.scrollTop;
});

await dragAndHoldOverSibling({
dnd,
testIdPrefix: 'scrollable-item',
sourceId: 3,
siblingId: 2,
edge: 'top',
});

try {
await expect
.poll(() => sibling.evaluate((element) => element.scrollTop))
.toBe(scrollBefore);
} finally {
await dnd.page.mouse.up();
await dnd.waitForDrop();
}
});
});
});

async function dragAndHoldOverSibling({
dnd,
edge,
siblingId,
sourceId,
testIdPrefix,
}: {
dnd: {
page: Page;
dragging: Locator;
waitForDrop(): Promise<void>;
};
edge: 'top' | 'bottom';
siblingId: number;
sourceId: number;
testIdPrefix: string;
}) {
const source = dnd.page.getByTestId(`${testIdPrefix}-${sourceId}`);
const sibling = dnd.page.getByTestId(`${testIdPrefix}-${siblingId}`);
const handle = source.locator('.handle');
const handleBox = await handle.boundingBox();
const siblingBox = await sibling.boundingBox();

if (!handleBox || !siblingBox) {
throw new Error('Could not get bounding box for draggable or sibling');
}

const start = {
x: handleBox.x + handleBox.width / 2,
y: handleBox.y + handleBox.height / 2,
};
const destination = {
x: siblingBox.x + siblingBox.width / 2,
y:
edge === 'bottom'
? siblingBox.y + siblingBox.height - 8
: siblingBox.y + 8,
};

await dnd.page.mouse.move(start.x, start.y);
await dnd.page.mouse.down();
await dnd.page.mouse.move(destination.x, destination.y, {steps: 24});
await expect(dnd.dragging).toHaveCount(1, {timeout: 3_000});
await dnd.page.waitForTimeout(700);
}
Loading
Loading