From 45ebfcb2016c19462a674ff7a8a4a5b0338692b8 Mon Sep 17 00:00:00 2001 From: Roman Pominov Date: Wed, 20 Jul 2022 19:10:24 +0300 Subject: [PATCH] move items in the example --- .../primitives/dnd/sortable-list.stories.tsx | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx b/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx index f347084aaf..4ce57d9641 100644 --- a/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx +++ b/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx @@ -15,7 +15,6 @@ const ListItem = styled("li", { background: "$mint12", padding: 10, userSelect: "none", - cursor: "grab", }); const List = styled("ul", { @@ -25,11 +24,11 @@ const List = styled("ul", { }); const Item = ({ data }: { data: ItemData }) => { - return {data.text}; + return {data.text}; }; export const SortableList = () => { - const [data, _setData] = useState([ + const [data, setData] = useState([ { id: "0", text: "First" }, { id: "1", text: "Second" }, { id: "2", text: "Third" }, @@ -55,6 +54,8 @@ export const SortableList = () => { placementRect: Rect; }>(); + const [dragItemId, setDragItemId] = useState(); + const dropTargetHandlers = useDropTarget({ isDropTarget(element: HTMLElement) { return element instanceof HTMLUListElement; @@ -72,6 +73,7 @@ export const SortableList = () => { event.cancel(); return; } + setDragItemId(event.target.dataset.id); autoScrollHandlers.setEnabled(true); }, onMove: (poiterCoordinate) => { @@ -80,9 +82,30 @@ export const SortableList = () => { placementHandlers.handleMove(poiterCoordinate); }, onEnd() { + if (placement !== undefined && dragItemId !== undefined) { + const oldIndex = data.findIndex((item) => item.id === dragItemId); + if (oldIndex !== -1) { + let newIndex = placement.index; + + // placement.index does not take into account the fact that the drag item will be removed. + // we need to do this to account for that + if (oldIndex < newIndex) { + newIndex = Math.max(0, newIndex - 1); + } + + if (oldIndex !== newIndex) { + const newData = [...data]; + newData.splice(oldIndex, 1); + newData.splice(newIndex, 0, data[oldIndex]); + setData(newData); + } + } + } + dropTargetHandlers.handleEnd(); autoScrollHandlers.setEnabled(false); placementHandlers.handleEnd(); + setDragItemId(undefined); setPalcement(undefined); }, }); @@ -109,7 +132,12 @@ export const SortableList = () => { }} {...dragProps} > - + {data.map((item) => ( ))}