Repository navigation
Can I build this drag and drop UI with dndkit? #2130
Replies: 1 comment
|
Yes. For the The moving-target problem matters here: if the sortable preview moves the folder as soon as you approach it, waiting longer will not make it easier to reach. In the minimal example below, the other icons stay in place during dragging and the array is reordered only on drop. That is a deliberate simplification; it does not implement the animated insertion preview of an Android launcher. The rules are:
If you retain Minimal React example: one folder, reorder-on-drop, 24px overlap and 300ms dwellTested with import React, {useEffect, useRef, useState} from 'react';
import {
DndContext, PointerSensor, KeyboardSensor, rectIntersection,
useDraggable, useDroppable, useSensor, useSensors,
} from '@dnd-kit/core';
const FOLDER = 'Folder';
const HOLD_MS = 300;
function hasFolderOverlap({active, over}) {
if (active.id === FOLDER || over?.id !== FOLDER) return false;
const a = active.rect.current.translated;
const b = over.rect;
if (!a) return false;
const width = Math.min(a.right, b.right) - Math.max(a.left, b.left);
const height = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);
return width >= 24 && height >= 24;
}
function Tile({id, armed, folderRef}) {
const drag = useDraggable({id});
const drop = useDroppable({id, disabled: drag.isDragging});
return <div ref={drop.setNodeRef} className="tile-slot">
<button
ref={node => {drag.setNodeRef(node); if (id === FOLDER) folderRef.current = node;}}
{...drag.listeners}
{...drag.attributes}
aria-label={`Move ${id}`}
className={`tile ${id === FOLDER && armed ? 'armed' : ''}`}
style={{
touchAction: 'none',
transform: drag.transform ? `translate3d(${drag.transform.x}px, ${drag.transform.y}px, 0)` : undefined,
zIndex: drag.isDragging ? 2 : 0,
opacity: drag.isDragging ? 0.6 : 1,
}}
>{id === FOLDER ? '📁' : id.slice(0, 1)}</button>
<span>{id}</span>
</div>;
}
// An explicit 96px grid step makes the same example keyboard-operable.
const gridKeyboardCoordinates = (event, {currentCoordinates}) => {
const delta = {ArrowRight:[96,0], ArrowLeft:[-96,0], ArrowDown:[0,96], ArrowUp:[0,-96]}[event.code];
return delta ? {x:currentCoordinates.x+delta[0], y:currentCoordinates.y+delta[1]} : undefined;
};
export default function DndDemo() {
const [items, setItems] = useState(['YouTube', 'Facebook', FOLDER]);
const [contents, setContents] = useState(['LinkedIn', 'X']);
const [armed, setArmed] = useState(false);
const [result, setResult] = useState('Ready');
const folderRef = useRef(null);
const dwell = useRef(null);
const timer = useRef(null);
const sensors = useSensors(
useSensor(PointerSensor, {activationConstraint:{distance:4}}),
useSensor(KeyboardSensor, {coordinateGetter:gridKeyboardCoordinates}),
);
function clearDwell() {
clearTimeout(timer.current);
timer.current = null;
dwell.current = null;
setArmed(false);
}
function updateIntent(event) {
if (!hasFolderOverlap(event)) {
clearDwell();
return;
}
// Do not restart the timer on every move. It must also fire if the
// user stops moving while holding the item over the folder.
if (dwell.current?.id === event.active.id) return;
clearDwell();
dwell.current = {id:event.active.id, since:performance.now()};
timer.current = setTimeout(() => setArmed(true), HOLD_MS);
}
useEffect(() => () => clearTimeout(timer.current), []);
function finish(event) {
const {active, over} = event;
const intoFolder = hasFolderOverlap(event) &&
dwell.current?.id === active.id &&
performance.now() - dwell.current.since >= HOLD_MS;
clearDwell();
if (intoFolder) {
setItems(list => list.filter(id => id !== active.id));
setContents(list => [...list, active.id]);
setResult(`Moved ${active.id} into Folder`);
requestAnimationFrame(() => folderRef.current?.focus());
} else if (over && active.id !== over.id) {
setItems(list => {
const next = [...list];
const from = next.indexOf(active.id);
const to = next.indexOf(over.id);
if (from < 0 || to < 0) return list;
next.splice(to, 0, ...next.splice(from, 1));
return next;
});
setResult(`Reordered ${active.id} to ${over.id}'s position`);
} else {
setResult('No change');
}
}
return <section aria-label="Folder demo" className="folder-demo">
<h2>Sort or drop into a folder</h2>
<p>Drop quickly to reorder. Overlap the folder by at least 24px in each direction and hold 300ms to put the app inside.</p>
<p>Keyboard: Space to pick up; arrows to move; Space to drop; Escape to cancel.</p>
<DndContext sensors={sensors} collisionDetection={rectIntersection}
onDragStart={clearDwell} onDragMove={updateIntent} onDragOver={updateIntent}
onDragEnd={finish} onDragCancel={() => {clearDwell();setResult('Cancelled');}}>
<div className="icon-grid">{items.map(id => <Tile key={id} id={id} armed={armed} folderRef={folderRef}/>)}</div>
</DndContext>
<p role="status">{armed ? 'Release to move into Folder' : result}</p>
<p>Order: {items.join(', ')}</p>
<p>Folder contents: {contents.join(', ')}</p>
<button onClick={()=>{clearDwell();setItems(['YouTube','Facebook',FOLDER]);setContents(['LinkedIn','X']);setResult('Ready');}}>Reset demo</button>
</section>;
}body { font-family: system-ui; margin: 32px; }
.folder-demo { width: min(620px, 100%); }
.icon-grid { display: flex; gap: 48px; padding: 48px 24px; min-height: 100px; }
.tile-slot { width: 48px; height: 48px; position: relative; flex-shrink: 0; }
.tile {
position: relative; width: 48px; height: 48px; padding: 0;
border: 2px solid #888; border-radius: 8px; background: #e2e8f0;
font-weight: bold; cursor: grab;
}
.tile-slot > span { position: absolute; top: 58px; left: 0; font-size: 12px; pointer-events: none; }
.tile.armed { outline: 4px solid #16a34a; background: #bbf7d0; }
.tile:focus-visible { outline: 3px solid #2563eb; }I checked ordinary reordering, a quick drop onto the folder, a stationary hold followed by a folder drop, leaving the folder before the timer expires, and Escape cancellation in a local browser reproduction. Keyboard interactions were used for the timed cases; pointer dragging was also checked for moving the folder itself. This has not been tested on a touch device. The example deliberately has one folder and does not implement opening folders or dragging items back out. The collision-detection docs describe composing different rules for different droppable targets. If you choose |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
This screenshot is from my Android mobile home screen. We have YouTube, Facebook, and a folder with both LinkedIn and X. The UI on my device allows me to do the following drag-and-drop operations:
I can drag YouTube and change its position with Facebook (easy to build with useSortable).
I can drag YouTube/Facebook into the folder, or I can drag YouTube/Facebook to change its position with the folder (this is the one I couldn't do)
This is the UI I'm trying to build. I tried to build it with the DND kit, but I faced a problem with the fact that a drag on the folder could both mean "change the position with the folder" or "drop into the folder". The way to differentiate between the two is to debounce the collisions check, you wait about 300ms before you check the collisions between items, then after 300ms, you are gonna check the width and height of colliding area between the folder and the app icon, if both are larger than a specific threshold (in my case it's 24, half of the size of the folder and the icon), you are going to consider that as a drop. If it's smaller than 24×24, you are going to consider that as a position change.
If you don't bounce the collisions check. The user will not be able to get the dragged app into that 24×24 area of collision between the folder and the app icon. So they will never be able to drop an app inside a folder.
I did my best to build this with the dnd kit. I tried custom collision detection algorithms. I tried debouncing library events, but I could not do it properly.
I hope it's clear what I'm trying to build here. My question is whether it's possible to build such interaction with the library?
Thanks in advance for any help, and big thanks to the library maintainer(s) for such a great tool; it's one of the best tools I've ever used 🥰
All reactions