|
| 1 | +import { Item, ListView, Text, useListData } from "@adobe/react-spectrum"; |
| 2 | +import { useDragAndDrop } from "@react-spectrum/dnd"; |
| 3 | +import Folder from "@spectrum-icons/illustrations/Folder"; |
| 4 | + |
| 5 | +export default function ReorderableListView() { |
| 6 | + let list = useListData({ |
| 7 | + initialItems: [ |
| 8 | + { id: "1", type: "file", name: "Adobe Photoshop" }, |
| 9 | + { id: "2", type: "file", name: "Adobe XD" }, |
| 10 | + { id: "3", type: "folder", name: "Documents", childNodes: [] }, |
| 11 | + { id: "4", type: "file", name: "Adobe InDesign" }, |
| 12 | + { id: "5", type: "folder", name: "Utilities", childNodes: [] }, |
| 13 | + { id: "6", type: "file", name: "Adobe AfterEffects" }, |
| 14 | + ], |
| 15 | + }); |
| 16 | + |
| 17 | + // Append a generated key to the item type so they can only be reordered within this list and not dragged elsewhere. |
| 18 | + let { dragAndDropHooks } = useDragAndDrop({ |
| 19 | + getItems(keys) { |
| 20 | + return [...keys].map((key) => { |
| 21 | + let item = list.getItem(key); |
| 22 | + // Setup the drag types and associated info for each dragged item. |
| 23 | + return { |
| 24 | + "custom-app-type-reorder": JSON.stringify(item), |
| 25 | + "text/plain": item.name, |
| 26 | + }; |
| 27 | + }); |
| 28 | + }, |
| 29 | + acceptedDragTypes: ["custom-app-type-reorder"], |
| 30 | + onReorder: async (e) => { |
| 31 | + let { keys, target, dropOperation } = e; |
| 32 | + |
| 33 | + if (target.dropPosition === "before") { |
| 34 | + list.moveBefore(target.key, [...keys]); |
| 35 | + } else if (target.dropPosition === "after") { |
| 36 | + list.moveAfter(target.key, [...keys]); |
| 37 | + } |
| 38 | + }, |
| 39 | + getAllowedDropOperations: () => ["move"], |
| 40 | + }); |
| 41 | + |
| 42 | + return ( |
| 43 | + <ListView |
| 44 | + aria-label="Reorderable ListView" |
| 45 | + selectionMode="multiple" |
| 46 | + width="size-3600" |
| 47 | + height="size-3600" |
| 48 | + items={list.items} |
| 49 | + dragAndDropHooks={dragAndDropHooks} |
| 50 | + > |
| 51 | + {(item) => ( |
| 52 | + <Item textValue={item.name}> |
| 53 | + {item.type === "folder" && <Folder />} |
| 54 | + <Text>{item.name}</Text> |
| 55 | + </Item> |
| 56 | + )} |
| 57 | + </ListView> |
| 58 | + ); |
| 59 | +} |
0 commit comments