55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import React, { CSSProperties, PropsWithChildren, useMemo } from "react";
|
|
import { useSortable } from "@dnd-kit/sortable";
|
|
import { CSS } from "@dnd-kit/utilities";
|
|
import DragHandle from "@/components/SortableDnd/DragHandle";
|
|
import SortableItemContext from "./SortableItemContext";
|
|
|
|
type Props = {
|
|
id: number | string;
|
|
itemStyle?: CSSProperties;
|
|
dragHandleStyle?: CSSProperties;
|
|
};
|
|
|
|
export const SortableItem = ({
|
|
children,
|
|
itemStyle,
|
|
id,
|
|
dragHandleStyle,
|
|
}: PropsWithChildren<Props>) => {
|
|
const {
|
|
attributes,
|
|
isDragging,
|
|
listeners,
|
|
setNodeRef,
|
|
setActivatorNodeRef,
|
|
transform,
|
|
transition,
|
|
} = useSortable({ id });
|
|
|
|
const context = useMemo(
|
|
() => ({
|
|
attributes,
|
|
listeners,
|
|
ref: setActivatorNodeRef,
|
|
}),
|
|
[attributes, listeners, setActivatorNodeRef]
|
|
);
|
|
|
|
const style: CSSProperties = {
|
|
opacity: isDragging ? 0.4 : undefined,
|
|
transform: CSS.Translate.toString(transform),
|
|
transition,
|
|
...itemStyle,
|
|
};
|
|
|
|
return (
|
|
<SortableItemContext.Provider value={context}>
|
|
<div
|
|
ref={setNodeRef}
|
|
style={style}>
|
|
<DragHandle style={dragHandleStyle}>{children}</DragHandle>
|
|
</div>
|
|
</SortableItemContext.Provider>
|
|
);
|
|
};
|