| 1 |
/** |
| 2 |
* External dependencies |
| 3 |
*/ |
| 4 |
import { DndContext } from '@dnd-kit/core'; |
| 5 |
import { arrayMove, verticalListSortingStrategy } from '@dnd-kit/sortable'; |
| 6 |
|
| 7 |
/** |
| 8 |
* Internal dependencies |
| 9 |
*/ |
| 10 |
import Droppable from './droppable'; |
| 11 |
|
| 12 |
const SortableControl = ({ |
| 13 |
defaultItems, |
| 14 |
attributeName, |
| 15 |
setAttributes, |
| 16 |
children, |
| 17 |
}) => { |
| 18 |
const handleDragEnd = ({ active, over }) => { |
| 19 |
if (!over) { |
| 20 |
return; |
| 21 |
} |
| 22 |
if (active.id !== over.id) { |
| 23 |
const activeIndex = active.data.current.sortable.index; |
| 24 |
const overIndex = over.data.current?.sortable.index || 0; |
| 25 |
const newItems = arrayMove(defaultItems, activeIndex, overIndex); |
| 26 |
setAttributes({ [attributeName]: newItems }); |
| 27 |
} |
| 28 |
}; |
| 29 |
|
| 30 |
return ( |
| 31 |
<DndContext onDragEnd={handleDragEnd}> |
| 32 |
<Droppable |
| 33 |
strategy={verticalListSortingStrategy} |
| 34 |
id="group" |
| 35 |
items={defaultItems} |
| 36 |
key="group" |
| 37 |
> |
| 38 |
{children} |
| 39 |
</Droppable> |
| 40 |
</DndContext> |
| 41 |
); |
| 42 |
}; |
| 43 |
|
| 44 |
export default SortableControl; |
| 45 |
|