UNPKG

@omakase-ui/react-sortable-list

Version:

<h1 align="center">@omakase-ui/react-sortable-list 👋</h1> <p> <a href="https://www.npmjs.com/package/@omakase-ui/react-sortable-list" target="_blank"> <img alt="Version" src="https://img.shields.io/npm/v/@omakase-ui/react-sortable-list.svg"> </a>

81 lines (73 loc) • 2.58 kB
import React from 'react'; import { useSortable, sortableKeyboardCoordinates, SortableContext, horizontalListSortingStrategy, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable'; import { CSS } from '@dnd-kit/utilities'; import { useSensors, useSensor, PointerSensor, KeyboardSensor, DndContext, closestCenter } from '@dnd-kit/core'; var SortableItem = function SortableItem(props) { var DragHandler = props.DragHandler, className = props.className; var _useSortable = useSortable({ id: props.id }), attributes = _useSortable.attributes, listeners = _useSortable.listeners, setNodeRef = _useSortable.setNodeRef, transform = _useSortable.transform, transition = _useSortable.transition; var style = { transform: CSS.Transform.toString(transform), transition: transition }; return DragHandler ? React.createElement("div", { ref: setNodeRef, style: style, className: className }, React.createElement(DragHandler, Object.assign({}, attributes, listeners)), props.children) : React.createElement("div", Object.assign({ ref: setNodeRef, style: style }, attributes, listeners, { className: className }), props.children); }; var SortableList = function SortableList(props) { var items = props.items, setItems = props.setItems, children = props.children, itemRender = props.itemRender, horizontal = props.horizontal; var sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })); return React.createElement(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd }, React.createElement(SortableContext, { items: items, strategy: horizontal ? horizontalListSortingStrategy : verticalListSortingStrategy }, children ? children({ items: items }) : items.map(function (item) { return React.createElement(SortableItem, { key: item.id, id: item.id }, itemRender({ item: item })); }))); function handleDragEnd(event) { var active = event.active, over = event.over; if (active.id !== over.id) { setItems(function (items) { var ids = items.map(function (item) { return item.id; }); var oldIndex = ids.indexOf(active.id); var newIndex = ids.indexOf(over.id); return arrayMove(items, oldIndex, newIndex); }); } } }; export { SortableItem, SortableList }; //# sourceMappingURL=react-sortable-list.esm.js.map