@schema-render/search-table-react
Version:
Conditional search table component.
66 lines (65 loc) • 2.89 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { closestCenter, DndContext, DragOverlay, MouseSensor, useSensor, useSensors } from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useMemoizedFn } from "@schema-render/core-react";
import { useState } from "react";
const Sortable = ({ items = [], onChange, itemClassName, overlayClassName, renderItem })=>{
const sensors = useSensors(useSensor(MouseSensor));
const [activeId, setActiveId] = useState(null);
const handleDragEnd = useMemoizedFn(({ active, over })=>{
if (active.id !== over.id) {
const oldIndex = items.findIndex((item)=>item.id === active.id);
const newIndex = items.findIndex((item)=>item.id === over.id);
onChange === null || onChange === void 0 ? void 0 : onChange(arrayMove(items, oldIndex, newIndex));
}
setActiveId(null);
});
return /*#__PURE__*/ _jsxs(DndContext, {
sensors: sensors,
collisionDetection: closestCenter,
onDragStart: ({ active })=>setActiveId(active.id),
onDragEnd: handleDragEnd,
modifiers: [
restrictToVerticalAxis
],
children: [
/*#__PURE__*/ _jsx(SortableContext, {
items: items,
strategy: verticalListSortingStrategy,
children: items.map((record, index)=>/*#__PURE__*/ _jsx(SortableItem, {
className: itemClassName,
id: record.id,
itemData: record,
itemIndex: index,
renderItem: renderItem
}, record.id))
}),
/*#__PURE__*/ _jsx(DragOverlay, {
zIndex: 9999,
children: activeId ? /*#__PURE__*/ _jsx("div", {
className: overlayClassName,
children: renderItem === null || renderItem === void 0 ? void 0 : renderItem(items.find((item)=>item.id === activeId), items.findIndex((item)=>item.id === activeId))
}) : null
})
]
});
};
function SortableItem({ className, id, itemData, itemIndex, renderItem }) {
const sortCtx = useSortable({
id
});
const style = {
transform: CSS.Transform.toString(sortCtx.transform),
transition: sortCtx.transition,
opacity: sortCtx.isDragging ? 0 : undefined
};
return /*#__PURE__*/ _jsx("div", {
className: className,
ref: sortCtx.setNodeRef,
style: style,
children: renderItem === null || renderItem === void 0 ? void 0 : renderItem(itemData, itemIndex, sortCtx)
});
}
export default Sortable;