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/revert-outside-sortable-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@dnd-kit/dom': patch
---

Restore the previous order when a sortable is released outside every drop target, keeping changes already committed by a drag-over handler.
26 changes: 26 additions & 0 deletions apps/stories-shared/tests/sortable-vertical.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {test, expect} from './fixtures.ts';

interface SortableVerticalStories {
basicSetup: string;
movesOnDragOver?: boolean;
withDragHandle: string;
}

Expand All @@ -26,6 +27,31 @@ export function sortableVerticalTests(stories: SortableVerticalStories) {
await expect(dnd.items.nth(2)).toHaveText('1');
});

test('releasing outside the list preserves the committed order', async ({dnd}) => {
const first = dnd.items.nth(0);
const third = dnd.items.nth(2);
const box = (await third.boundingBox())!;
const y = box.y + box.height / 2;
await first.hover();
await dnd.page.mouse.down();
await dnd.page.mouse.move(box.x + box.width / 2, y, {steps: 20});
await expect(first).toHaveText('2');

await dnd.page.mouse.move(0, y, {steps: 10});
await dnd.page.mouse.up();
await dnd.waitForDrop();

const order = stories.movesOnDragOver ? ['2', '3', '1'] : ['1', '2', '3'];
await expect(first).toHaveText(order[0]);
await expect(dnd.items.nth(1)).toHaveText(order[1]);
await expect(third).toHaveText(order[2]);

await dnd.pointer.drag(first, third);
await dnd.waitForDrop();
await expect(first).toHaveText(order[1]);
await expect(third).toHaveText(order[0]);
});

test('reorder items up with pointer', async ({dnd}) => {
const third = dnd.items.nth(2);
const first = dnd.items.nth(0);
Expand Down
1 change: 1 addition & 0 deletions apps/stories-svelte/tests/sortable-vertical.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {sortableVerticalTests} from '../../stories-shared/tests/sortable-vertical.tests.ts';

sortableVerticalTests({
movesOnDragOver: true,
basicSetup: 'sortable-vertical-list--basic-setup',
withDragHandle: 'sortable-vertical-list--with-drag-handle',
});
157 changes: 88 additions & 69 deletions packages/dom/src/sortable/plugins/OptimisticSortingPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export class OptimisticSortingPlugin extends Plugin<DragDropManager> {
constructor(manager: DragDropManager) {
super(manager);

let preview: SortingPreview | undefined;

const getSortableInstances = () => {
const sortableInstances: SortableInstances = new Map();

Expand Down Expand Up @@ -46,7 +48,7 @@ export class OptimisticSortingPlugin extends Plugin<DragDropManager> {
}

const {dragOperation} = manager;
const {source, target} = dragOperation;
const {source, target, controller} = dragOperation;

if (!isSortable(source) || !isSortable(target)) {
return;
Expand All @@ -71,10 +73,13 @@ export class OptimisticSortingPlugin extends Plugin<DragDropManager> {

// Wait for the renderer to handle the event before attempting to optimistically update
manager.renderer.rendering.then(() => {
if (controller?.signal.aborted) return;

const newInstances = getSortableInstances();

if (hasChanged(sortableIndices, instances, newInstances)) {
// At least one index or group was changed so we should abort optimistic updates
// The renderer has taken ownership of the order.
preview = undefined;
return;
}

Expand Down Expand Up @@ -106,21 +111,29 @@ export class OptimisticSortingPlugin extends Plugin<DragDropManager> {
const sourceIndex = newState[targetGroup].indexOf(source.sortable);
const targetIndex = newState[targetGroup].indexOf(target.sortable);

const currentPreview = preview?.isCurrent(manager)
? preview
: new SortingPreview(source.sortable, sourceElement);
preview = currentPreview;

manager.collisionObserver.disable();

reorder(sourceElement, sourceIndex, targetElement, targetIndex);

batch(() => {
for (const [index, sortable] of newState[sourceGroup].entries()) {
sortable.index = index;
currentPreview.setPosition(sortable, sortable.group, index);
}

if (!sameGroup) {
for (const [index, sortable] of newState[
targetGroup
].entries()) {
sortable.group = target.sortable.group;
sortable.index = index;
currentPreview.setPosition(
sortable,
target.sortable.group,
index
);
}
}
});
Expand All @@ -132,68 +145,16 @@ export class OptimisticSortingPlugin extends Plugin<DragDropManager> {
});
}),
manager.monitor.addEventListener('dragend', (event, manager) => {
if (!event.canceled) {
return;
}
const pending = preview;
preview = undefined;

const {dragOperation} = manager;
const {source} = dragOperation;

if (!isSortable(source)) {
return;
}

if (
source.sortable.initialIndex === source.sortable.index &&
source.sortable.initialGroup === source.sortable.group
) {
return;
}
if (!pending || (!event.canceled && event.operation.target)) return;

queueMicrotask(() => {
const instances = getSortableInstances();
const sortableIndices = getSortableIndices(instances);
const initialGroupInstances = instances.get(
source.sortable.initialGroup
);

if (!initialGroupInstances) return;

// Wait for the renderer to handle the event before attempting to optimistically update
manager.renderer.rendering.then(() => {
const newInstances = getSortableInstances();

if (hasChanged(sortableIndices, instances, newInstances)) {
// At least one index or group was changed so we should abort optimistic updates
return;
}

const currentSortables = sort(initialGroupInstances);
const initialSortables = sort(
initialGroupInstances,
sortByInitialIndex
);
const sourceElement = source.sortable.element;
const initialPosition = initialSortables.indexOf(source.sortable);
const target = currentSortables[initialPosition];
const targetElement = target?.element;

if (!target || !targetElement || !sourceElement) {
return;
if (pending.isCurrent(manager)) {
pending.restore();
}

reorder(sourceElement, target.index, targetElement, source.index);

batch(() => {
for (const sortableInstances of instances.values()) {
const entries = Array.from(sortableInstances).values();

for (const sortable of entries) {
sortable.index = sortable.initialIndex;
sortable.group = sortable.initialGroup;
}
}
});
});
});
}),
Expand All @@ -218,14 +179,72 @@ function reorder(
targetElement.insertAdjacentElement(position, sourceElement);
}

function sortByIndex(a: Sortable, b: Sortable) {
return a.index - b.index;
function sort(instances: Set<Sortable>) {
return Array.from(instances).sort((a, b) => a.index - b.index);
}

function sortByInitialIndex(a: Sortable, b: Sortable) {
return a.initialIndex - b.initialIndex;
}
type Position = {group: Sortable['group']; index: number};

class SortingPreview {
private parent: ParentNode | null;
private nextSibling: ChildNode | null;
private positions = new Map<
Sortable,
{initial: Position; current: Position}
>();

constructor(
private source: Sortable,
element: Element
) {
this.parent = element.parentNode;
this.nextSibling = element.nextSibling;
}

function sort(instances: Set<Sortable>, sortFn = sortByIndex) {
return Array.from(instances).sort(sortFn);
setPosition(sortable: Sortable, group: Sortable['group'], index: number) {
if (sortable.group === group && sortable.index === index) return;

const initial = this.positions.get(sortable)?.initial ?? {
group: sortable.group,
index: sortable.index,
};
this.positions.set(sortable, {initial, current: {group, index}});
sortable.group = group;
sortable.index = index;
}

isCurrent(manager: DragDropManager) {
if (
manager.registry.draggables.get(this.source.id) !== this.source.draggable
) {
return false;
}

for (const [sortable, {current}] of this.positions) {
if (
sortable.group !== current.group ||
sortable.index !== current.index
) {
return false;
}
}
return true;
}

restore() {
const element = this.source.element;
if (!element || !this.parent) return;

this.parent.insertBefore(
element,
this.nextSibling?.parentNode === this.parent ? this.nextSibling : null
);

batch(() => {
for (const [sortable, {initial}] of this.positions) {
sortable.group = initial.group;
sortable.index = initial.index;
}
});
}
}