Sortable.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import type {
  2. DndContextProps,
  3. DraggableSyntheticListeners,
  4. DropAnimation,
  5. UniqueIdentifier,
  6. } from '@dnd-kit/core'
  7. import {
  8. closestCenter,
  9. defaultDropAnimationSideEffects,
  10. DndContext,
  11. DragOverlay,
  12. KeyboardSensor,
  13. MouseSensor,
  14. TouchSensor,
  15. useSensor,
  16. useSensors,
  17. } from '@dnd-kit/core'
  18. import {
  19. restrictToHorizontalAxis,
  20. restrictToParentElement,
  21. restrictToVerticalAxis,
  22. } from '@dnd-kit/modifiers'
  23. import {
  24. arrayMove,
  25. horizontalListSortingStrategy,
  26. SortableContext,
  27. useSortable,
  28. verticalListSortingStrategy,
  29. type SortableContextProps,
  30. } from '@dnd-kit/sortable'
  31. import { CSS } from '@dnd-kit/utilities'
  32. import { Slot } from 'radix-ui'
  33. import { createContext, forwardRef, useContext, useMemo, useState } from 'react'
  34. import { createPortal } from 'react-dom'
  35. import { Button, cn, type ButtonProps } from 'ui'
  36. import { composeRefs } from '../hooks/useComposedRefs'
  37. const orientationConfig = {
  38. vertical: {
  39. modifiers: [restrictToVerticalAxis, restrictToParentElement],
  40. strategy: verticalListSortingStrategy,
  41. },
  42. horizontal: {
  43. modifiers: [restrictToHorizontalAxis, restrictToParentElement],
  44. strategy: horizontalListSortingStrategy,
  45. },
  46. mixed: {
  47. modifiers: [restrictToParentElement],
  48. strategy: undefined,
  49. },
  50. }
  51. interface SortableProps<TData extends { id: UniqueIdentifier }> extends DndContextProps {
  52. /**
  53. * An array of data items that the sortable component will render.
  54. * @example
  55. * value={[
  56. * { id: 1, name: 'Item 1' },
  57. * { id: 2, name: 'Item 2' },
  58. * ]}
  59. */
  60. value: TData[]
  61. /**
  62. * An optional callback function that is called when the order of the data items changes.
  63. * It receives the new array of items as its argument.
  64. * @example
  65. * onValueChange={(items) => console.log(items)}
  66. */
  67. onValueChange?: (items: TData[]) => void
  68. /**
  69. * An optional callback function that is called when an item is moved.
  70. * It receives an event object with `activeIndex` and `overIndex` properties, representing the original and new positions of the moved item.
  71. * This will override the default behavior of updating the order of the data items.
  72. * @type (event: { activeIndex: number; overIndex: number }) => void
  73. * @example
  74. * onMove={(event) => console.log(`Item moved from index ${event.activeIndex} to index ${event.overIndex}`)}
  75. */
  76. onMove?: (event: { activeIndex: number; overIndex: number }) => void
  77. /**
  78. * A collision detection strategy that will be used to determine the closest sortable item.
  79. * @default closestCenter
  80. * @type DndContextProps["collisionDetection"]
  81. */
  82. collisionDetection?: DndContextProps['collisionDetection']
  83. /**
  84. * An array of modifiers that will be used to modify the behavior of the sortable component.
  85. * @default
  86. * [restrictToVerticalAxis, restrictToParentElement]
  87. * @type Modifier[]
  88. */
  89. modifiers?: DndContextProps['modifiers']
  90. /**
  91. * A sorting strategy that will be used to determine the new order of the data items.
  92. * @default verticalListSortingStrategy
  93. * @type SortableContextProps["strategy"]
  94. */
  95. strategy?: SortableContextProps['strategy']
  96. /**
  97. * Specifies the axis for the drag-and-drop operation. It can be "vertical", "horizontal", or "both".
  98. * @default "vertical"
  99. * @type "vertical" | "horizontal" | "mixed"
  100. */
  101. orientation?: 'vertical' | 'horizontal' | 'mixed'
  102. /**
  103. * An optional React node that is rendered on top of the sortable component.
  104. * It can be used to display additional information or controls.
  105. * @default null
  106. * @type React.ReactNode | null
  107. * @example
  108. * overlay={<Skeleton className="w-full h-8" />}
  109. */
  110. overlay?: React.ReactNode | null
  111. }
  112. export function Sortable<TData extends { id: UniqueIdentifier }>({
  113. value,
  114. onValueChange,
  115. onDragStart,
  116. onDragEnd,
  117. onDragCancel,
  118. collisionDetection = closestCenter,
  119. modifiers,
  120. strategy,
  121. onMove,
  122. orientation = 'vertical',
  123. overlay,
  124. children,
  125. ...props
  126. }: SortableProps<TData>) {
  127. const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
  128. const sensors = useSensors(
  129. useSensor(MouseSensor),
  130. useSensor(TouchSensor),
  131. useSensor(KeyboardSensor)
  132. )
  133. const config = orientationConfig[orientation]
  134. return (
  135. <DndContext
  136. modifiers={modifiers ?? config.modifiers}
  137. sensors={sensors}
  138. onDragStart={(event) => {
  139. setActiveId(event.active.id)
  140. onDragStart?.(event)
  141. }}
  142. onDragEnd={(event) => {
  143. const { active, over } = event
  144. if (over && active.id !== over?.id) {
  145. const activeIndex = value.findIndex((item) => item.id === active.id)
  146. const overIndex = value.findIndex((item) => item.id === over.id)
  147. if (onMove) {
  148. onMove({ activeIndex, overIndex })
  149. } else {
  150. onValueChange?.(arrayMove(value, activeIndex, overIndex))
  151. }
  152. }
  153. setActiveId(null)
  154. onDragEnd?.(event)
  155. }}
  156. onDragCancel={(event) => {
  157. setActiveId?.(null)
  158. onDragCancel?.(event)
  159. }}
  160. collisionDetection={collisionDetection}
  161. {...props}
  162. >
  163. <SortableContext items={value} strategy={strategy ?? config.strategy}>
  164. {children}
  165. </SortableContext>
  166. {overlay
  167. ? // https://docs.dndkit.com/api-documentation/draggable/drag-overlay#portals
  168. createPortal(
  169. <SortableOverlay activeId={activeId}>{overlay}</SortableOverlay>,
  170. document.body
  171. )
  172. : null}
  173. </DndContext>
  174. )
  175. }
  176. const dropAnimationOpts: DropAnimation = {
  177. sideEffects: defaultDropAnimationSideEffects({
  178. styles: {
  179. active: {
  180. opacity: '0.4',
  181. },
  182. },
  183. }),
  184. }
  185. interface SortableOverlayProps extends React.ComponentPropsWithRef<typeof DragOverlay> {
  186. activeId?: UniqueIdentifier | null
  187. }
  188. export const SortableOverlay = forwardRef<HTMLDivElement, SortableOverlayProps>(
  189. ({ activeId, dropAnimation = dropAnimationOpts, children, ...props }, ref) => {
  190. return (
  191. <DragOverlay dropAnimation={dropAnimation} {...props}>
  192. {activeId ? (
  193. <SortableItem ref={ref} value={activeId} className="cursor-grabbing" asChild>
  194. {children}
  195. </SortableItem>
  196. ) : null}
  197. </DragOverlay>
  198. )
  199. }
  200. )
  201. SortableOverlay.displayName = 'SortableOverlay'
  202. interface SortableItemContextProps {
  203. attributes: React.HTMLAttributes<HTMLElement>
  204. listeners: DraggableSyntheticListeners | undefined
  205. isDragging?: boolean
  206. }
  207. const SortableItemContext = createContext<SortableItemContextProps>({
  208. attributes: {},
  209. listeners: undefined,
  210. isDragging: false,
  211. })
  212. function useSortableItem() {
  213. const context = useContext(SortableItemContext)
  214. if (!context) {
  215. throw new Error('useSortableItem must be used within a SortableItem')
  216. }
  217. return context
  218. }
  219. interface SortableItemProps extends Slot.SlotProps {
  220. /**
  221. * The unique identifier of the item.
  222. * @example "item-1"
  223. * @type UniqueIdentifier
  224. */
  225. value: UniqueIdentifier
  226. /**
  227. * Specifies whether the item should act as a trigger for the drag-and-drop action.
  228. * @default false
  229. * @type boolean | undefined
  230. */
  231. asTrigger?: boolean
  232. /**
  233. * Merges the item's props into its immediate child.
  234. * @default false
  235. * @type boolean | undefined
  236. */
  237. asChild?: boolean
  238. }
  239. export const SortableItem = forwardRef<HTMLDivElement, SortableItemProps>(
  240. ({ value, asTrigger, asChild, className, ...props }, ref) => {
  241. const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
  242. id: value,
  243. })
  244. const context = useMemo<SortableItemContextProps>(
  245. () => ({
  246. attributes,
  247. listeners,
  248. isDragging,
  249. }),
  250. [attributes, listeners, isDragging]
  251. )
  252. const style: React.CSSProperties = {
  253. opacity: isDragging ? 0.5 : 1,
  254. transform: CSS.Translate.toString(transform),
  255. transition,
  256. }
  257. const Comp = asChild ? Slot.Slot : 'div'
  258. return (
  259. <SortableItemContext.Provider value={context}>
  260. <Comp
  261. data-state={isDragging ? 'dragging' : undefined}
  262. className={cn(
  263. 'data-[state=dragging]:cursor-grabbing',
  264. { 'cursor-grab': !isDragging && asTrigger },
  265. className
  266. )}
  267. ref={composeRefs(ref, setNodeRef as React.Ref<HTMLDivElement>)}
  268. style={style}
  269. {...(asTrigger ? attributes : {})}
  270. {...(asTrigger ? listeners : {})}
  271. {...props}
  272. />
  273. </SortableItemContext.Provider>
  274. )
  275. }
  276. )
  277. SortableItem.displayName = 'SortableItem'
  278. interface SortableDragHandleProps extends ButtonProps {
  279. withHandle?: boolean
  280. }
  281. export const SortableDragHandle = forwardRef<HTMLButtonElement, SortableDragHandleProps>(
  282. ({ className, ...props }, ref) => {
  283. const { attributes, listeners, isDragging } = useSortableItem()
  284. return (
  285. <Button
  286. ref={composeRefs(ref)}
  287. data-state={isDragging ? 'dragging' : undefined}
  288. className={cn('cursor-grab data-[state=dragging]:cursor-grabbing', className)}
  289. {...attributes}
  290. {...listeners}
  291. {...props}
  292. />
  293. )
  294. }
  295. )
  296. SortableDragHandle.displayName = 'SortableDragHandle'