1"use client";
2
3import {
4 type Announcements,
5 closestCenter,
6 closestCorners,
7 DndContext,
8 type DndContextProps,
9 type DragEndEvent,
10 type DraggableAttributes,
11 type DraggableSyntheticListeners,
12 DragOverlay,
13 type DragStartEvent,
14 type DropAnimation,
15 defaultDropAnimationSideEffects,
16 KeyboardSensor,
17 MouseSensor,
18 type ScreenReaderInstructions,
19 TouchSensor,
20 type UniqueIdentifier,
21 useSensor,
22 useSensors,
23} from "@dnd-kit/core";
24import {
25 restrictToHorizontalAxis,
26 restrictToParentElement,
27 restrictToVerticalAxis,
28} from "@dnd-kit/modifiers";
29import {
30 arrayMove,
31 horizontalListSortingStrategy,
32 SortableContext,
33 type SortableContextProps,
34 sortableKeyboardCoordinates,
35 useSortable,
36 verticalListSortingStrategy,
37} from "@dnd-kit/sortable";
38import { CSS } from "@dnd-kit/utilities";
39import { Slot as SlotPrimitive } from "radix-ui";
40import * as React from "react";
41import * as ReactDOM from "react-dom";
42import { useComposedRefs } from "@/lib/compose-refs";
43import { cn } from "@/lib/utils";
44
45const orientationConfig = {
46 vertical: {
47 modifiers: [restrictToVerticalAxis, restrictToParentElement],
48 strategy: verticalListSortingStrategy,
49 collisionDetection: closestCenter,
50 },
51 horizontal: {
52 modifiers: [restrictToHorizontalAxis, restrictToParentElement],
53 strategy: horizontalListSortingStrategy,
54 collisionDetection: closestCenter,
55 },
56 mixed: {
57 modifiers: [restrictToParentElement],
58 strategy: undefined,
59 collisionDetection: closestCorners,
60 },
61};
62
63const ROOT_NAME = "Sortable";
64const CONTENT_NAME = "SortableContent";
65const ITEM_NAME = "SortableItem";
66const ITEM_HANDLE_NAME = "SortableItemHandle";
67const OVERLAY_NAME = "SortableOverlay";
68
69interface SortableRootContextValue<T> {
70 id: string;
71 items: UniqueIdentifier[];
72 modifiers: DndContextProps["modifiers"];
73 strategy: SortableContextProps["strategy"];
74 activeId: UniqueIdentifier | null;
75 setActiveId: (id: UniqueIdentifier | null) => void;
76 getItemValue: (item: T) => UniqueIdentifier;
77 flatCursor: boolean;
78}
79
80const SortableRootContext =
81 React.createContext<SortableRootContextValue<unknown> | null>(null);
82
83function useSortableContext(consumerName: string) {
84 const context = React.useContext(SortableRootContext);
85 if (!context) {
86 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
87 }
88 return context;
89}
90
91interface GetItemValue<T> {
92 /**
93 * Callback that returns a unique identifier for each sortable item. Required for array of objects.
94 * @example getItemValue={(item) => item.id}
95 */
96 getItemValue: (item: T) => UniqueIdentifier;
97}
98
99type SortableProps<T> = DndContextProps &
100 (T extends object ? GetItemValue<T> : Partial<GetItemValue<T>>) & {
101 value: T[];
102 onValueChange?: (items: T[]) => void;
103 onMove?: (
104 event: DragEndEvent & { activeIndex: number; overIndex: number },
105 ) => void;
106 strategy?: SortableContextProps["strategy"];
107 orientation?: "vertical" | "horizontal" | "mixed";
108 flatCursor?: boolean;
109 };
110
111function Sortable<T>(props: SortableProps<T>) {
112 const {
113 value,
114 onValueChange,
115 collisionDetection,
116 modifiers,
117 strategy,
118 onMove,
119 orientation = "vertical",
120 flatCursor = false,
121 getItemValue: getItemValueProp,
122 accessibility,
123 ...sortableProps
124 } = props;
125
126 const id = React.useId();
127 const [activeId, setActiveId] = React.useState<UniqueIdentifier | null>(null);
128
129 const sensors = useSensors(
130 useSensor(MouseSensor),
131 useSensor(TouchSensor),
132 useSensor(KeyboardSensor, {
133 coordinateGetter: sortableKeyboardCoordinates,
134 }),
135 );
136 const config = React.useMemo(
137 () => orientationConfig[orientation],
138 [orientation],
139 );
140
141 const getItemValue = React.useCallback(
142 (item: T): UniqueIdentifier => {
143 if (typeof item === "object" && !getItemValueProp) {
144 throw new Error(
145 "`getItemValue` is required when using array of objects",
146 );
147 }
148 return getItemValueProp
149 ? getItemValueProp(item)
150 : (item as UniqueIdentifier);
151 },
152 [getItemValueProp],
153 );
154
155 const items = React.useMemo(() => {
156 return value.map((item) => getItemValue(item));
157 }, [value, getItemValue]);
158
159 const onDragStart = React.useCallback(
160 (event: DragStartEvent) => {
161 sortableProps.onDragStart?.(event);
162
163 if (event.activatorEvent.defaultPrevented) return;
164
165 setActiveId(event.active.id);
166 },
167 [sortableProps.onDragStart],
168 );
169
170 const onDragEnd = React.useCallback(
171 (event: DragEndEvent) => {
172 sortableProps.onDragEnd?.(event);
173
174 if (event.activatorEvent.defaultPrevented) return;
175
176 const { active, over } = event;
177 if (over && active.id !== over?.id) {
178 const activeIndex = value.findIndex(
179 (item) => getItemValue(item) === active.id,
180 );
181 const overIndex = value.findIndex(
182 (item) => getItemValue(item) === over.id,
183 );
184
185 if (onMove) {
186 onMove({ ...event, activeIndex, overIndex });
187 } else {
188 onValueChange?.(arrayMove(value, activeIndex, overIndex));
189 }
190 }
191 setActiveId(null);
192 },
193 [value, onValueChange, onMove, getItemValue, sortableProps.onDragEnd],
194 );
195
196 const onDragCancel = React.useCallback(
197 (event: DragEndEvent) => {
198 sortableProps.onDragCancel?.(event);
199
200 if (event.activatorEvent.defaultPrevented) return;
201
202 setActiveId(null);
203 },
204 [sortableProps.onDragCancel],
205 );
206
207 const announcements: Announcements = React.useMemo(
208 () => ({
209 onDragStart({ active }) {
210 const activeValue = active.id.toString();
211 return `Grabbed sortable item "${activeValue}". Current position is ${active.data.current?.sortable.index + 1} of ${value.length}. Use arrow keys to move, space to drop.`;
212 },
213 onDragOver({ active, over }) {
214 if (over) {
215 const overIndex = over.data.current?.sortable.index ?? 0;
216 const activeIndex = active.data.current?.sortable.index ?? 0;
217 const moveDirection = overIndex > activeIndex ? "down" : "up";
218 const activeValue = active.id.toString();
219 return `Sortable item "${activeValue}" moved ${moveDirection} to position ${overIndex + 1} of ${value.length}.`;
220 }
221 return "Sortable item is no longer over a droppable area. Press escape to cancel.";
222 },
223 onDragEnd({ active, over }) {
224 const activeValue = active.id.toString();
225 if (over) {
226 const overIndex = over.data.current?.sortable.index ?? 0;
227 return `Sortable item "${activeValue}" dropped at position ${overIndex + 1} of ${value.length}.`;
228 }
229 return `Sortable item "${activeValue}" dropped. No changes were made.`;
230 },
231 onDragCancel({ active }) {
232 const activeIndex = active.data.current?.sortable.index ?? 0;
233 const activeValue = active.id.toString();
234 return `Sorting cancelled. Sortable item "${activeValue}" returned to position ${activeIndex + 1} of ${value.length}.`;
235 },
236 onDragMove({ active, over }) {
237 if (over) {
238 const overIndex = over.data.current?.sortable.index ?? 0;
239 const activeIndex = active.data.current?.sortable.index ?? 0;
240 const moveDirection = overIndex > activeIndex ? "down" : "up";
241 const activeValue = active.id.toString();
242 return `Sortable item "${activeValue}" is moving ${moveDirection} to position ${overIndex + 1} of ${value.length}.`;
243 }
244 return "Sortable item is no longer over a droppable area. Press escape to cancel.";
245 },
246 }),
247 [value],
248 );
249
250 const screenReaderInstructions: ScreenReaderInstructions = React.useMemo(
251 () => ({
252 draggable: `
253 To pick up a sortable item, press space or enter.
254 While dragging, use the ${orientation === "vertical" ? "up and down" : orientation === "horizontal" ? "left and right" : "arrow"} keys to move the item.
255 Press space or enter again to drop the item in its new position, or press escape to cancel.
256 `,
257 }),
258 [orientation],
259 );
260
261 const contextValue = React.useMemo(
262 () => ({
263 id,
264 items,
265 modifiers: modifiers ?? config.modifiers,
266 strategy: strategy ?? config.strategy,
267 activeId,
268 setActiveId,
269 getItemValue,
270 flatCursor,
271 }),
272 [
273 id,
274 items,
275 modifiers,
276 strategy,
277 config.modifiers,
278 config.strategy,
279 activeId,
280 getItemValue,
281 flatCursor,
282 ],
283 );
284
285 return (
286 <SortableRootContext.Provider
287 value={contextValue as SortableRootContextValue<unknown>}
288 >
289 <DndContext
290 collisionDetection={collisionDetection ?? config.collisionDetection}
291 modifiers={modifiers ?? config.modifiers}
292 sensors={sensors}
293 {...sortableProps}
294 id={id}
295 onDragStart={onDragStart}
296 onDragEnd={onDragEnd}
297 onDragCancel={onDragCancel}
298 accessibility={{
299 announcements,
300 screenReaderInstructions,
301 ...accessibility,
302 }}
303 />
304 </SortableRootContext.Provider>
305 );
306}
307
308const SortableContentContext = React.createContext<boolean>(false);
309
310interface SortableContentProps extends React.ComponentProps<"div"> {
311 strategy?: SortableContextProps["strategy"];
312 children: React.ReactNode;
313 asChild?: boolean;
314 withoutSlot?: boolean;
315}
316
317function SortableContent(props: SortableContentProps) {
318 const {
319 strategy: strategyProp,
320 asChild,
321 withoutSlot,
322 children,
323 ref,
324 ...contentProps
325 } = props;
326
327 const context = useSortableContext(CONTENT_NAME);
328
329 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
330
331 return (
332 <SortableContentContext.Provider value={true}>
333 <SortableContext
334 items={context.items}
335 strategy={strategyProp ?? context.strategy}
336 >
337 {withoutSlot ? (
338 children
339 ) : (
340 <ContentPrimitive
341 data-slot="sortable-content"
342 {...contentProps}
343 ref={ref}
344 >
345 {children}
346 </ContentPrimitive>
347 )}
348 </SortableContext>
349 </SortableContentContext.Provider>
350 );
351}
352
353interface SortableItemContextValue {
354 id: string;
355 attributes: DraggableAttributes;
356 listeners: DraggableSyntheticListeners | undefined;
357 setActivatorNodeRef: (node: HTMLElement | null) => void;
358 isDragging?: boolean;
359 disabled?: boolean;
360}
361
362const SortableItemContext =
363 React.createContext<SortableItemContextValue | null>(null);
364
365function useSortableItemContext(consumerName: string) {
366 const context = React.useContext(SortableItemContext);
367 if (!context) {
368 throw new Error(`\`${consumerName}\` must be used within \`${ITEM_NAME}\``);
369 }
370 return context;
371}
372
373interface SortableItemProps extends React.ComponentProps<"div"> {
374 value: UniqueIdentifier;
375 asHandle?: boolean;
376 asChild?: boolean;
377 disabled?: boolean;
378}
379
380function SortableItem(props: SortableItemProps) {
381 const {
382 value,
383 style,
384 asHandle,
385 asChild,
386 disabled,
387 className,
388 ref,
389 ...itemProps
390 } = props;
391
392 const inSortableContent = React.useContext(SortableContentContext);
393 const inSortableOverlay = React.useContext(SortableOverlayContext);
394
395 if (!inSortableContent && !inSortableOverlay) {
396 throw new Error(
397 `\`${ITEM_NAME}\` must be used within \`${CONTENT_NAME}\` or \`${OVERLAY_NAME}\``,
398 );
399 }
400
401 if (value === "") {
402 throw new Error(`\`${ITEM_NAME}\` value cannot be an empty string`);
403 }
404
405 const context = useSortableContext(ITEM_NAME);
406 const id = React.useId();
407 const {
408 attributes,
409 listeners,
410 setNodeRef,
411 setActivatorNodeRef,
412 transform,
413 transition,
414 isDragging,
415 } = useSortable({ id: value, disabled });
416
417 const composedRef = useComposedRefs(ref, (node) => {
418 if (disabled) return;
419 setNodeRef(node);
420 if (asHandle) setActivatorNodeRef(node);
421 });
422
423 const composedStyle = React.useMemo<React.CSSProperties>(() => {
424 return {
425 transform: CSS.Translate.toString(transform),
426 transition,
427 ...style,
428 };
429 }, [transform, transition, style]);
430
431 const itemContext = React.useMemo<SortableItemContextValue>(
432 () => ({
433 id,
434 attributes,
435 listeners,
436 setActivatorNodeRef,
437 isDragging,
438 disabled,
439 }),
440 [id, attributes, listeners, setActivatorNodeRef, isDragging, disabled],
441 );
442
443 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
444
445 return (
446 <SortableItemContext.Provider value={itemContext}>
447 <ItemPrimitive
448 id={id}
449 data-disabled={disabled}
450 data-dragging={isDragging ? "" : undefined}
451 data-slot="sortable-item"
452 {...itemProps}
453 {...(asHandle && !disabled ? attributes : {})}
454 {...(asHandle && !disabled ? listeners : {})}
455 ref={composedRef}
456 style={composedStyle}
457 className={cn(
458 "focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1",
459 {
460 "touch-none select-none": asHandle,
461 "cursor-default": context.flatCursor,
462 "data-dragging:cursor-grabbing": !context.flatCursor,
463 "cursor-grab": !isDragging && asHandle && !context.flatCursor,
464 "opacity-50": isDragging,
465 "pointer-events-none opacity-50": disabled,
466 },
467 className,
468 )}
469 />
470 </SortableItemContext.Provider>
471 );
472}
473
474interface SortableItemHandleProps extends React.ComponentProps<"button"> {
475 asChild?: boolean;
476}
477
478function SortableItemHandle(props: SortableItemHandleProps) {
479 const { asChild, disabled, className, ref, ...itemHandleProps } = props;
480
481 const context = useSortableContext(ITEM_HANDLE_NAME);
482 const itemContext = useSortableItemContext(ITEM_HANDLE_NAME);
483
484 const isDisabled = disabled ?? itemContext.disabled;
485
486 const composedRef = useComposedRefs(ref, (node) => {
487 if (!isDisabled) return;
488 itemContext.setActivatorNodeRef(node);
489 });
490
491 const HandlePrimitive = asChild ? SlotPrimitive.Slot : "button";
492
493 return (
494 <HandlePrimitive
495 type="button"
496 aria-controls={itemContext.id}
497 data-disabled={isDisabled}
498 data-dragging={itemContext.isDragging ? "" : undefined}
499 data-slot="sortable-item-handle"
500 {...itemHandleProps}
501 {...(isDisabled ? {} : itemContext.attributes)}
502 {...(isDisabled ? {} : itemContext.listeners)}
503 ref={composedRef}
504 className={cn(
505 "select-none disabled:pointer-events-none disabled:opacity-50",
506 context.flatCursor
507 ? "cursor-default"
508 : "cursor-grab data-dragging:cursor-grabbing",
509 className,
510 )}
511 disabled={isDisabled}
512 />
513 );
514}
515
516const SortableOverlayContext = React.createContext(false);
517
518const dropAnimation: DropAnimation = {
519 sideEffects: defaultDropAnimationSideEffects({
520 styles: {
521 active: {
522 opacity: "0.4",
523 },
524 },
525 }),
526};
527
528interface SortableOverlayProps
529 extends Omit<React.ComponentProps<typeof DragOverlay>, "children"> {
530 container?: Element | DocumentFragment | null;
531 children?:
532 | ((params: { value: UniqueIdentifier }) => React.ReactNode)
533 | React.ReactNode;
534}
535
536function SortableOverlay(props: SortableOverlayProps) {
537 const { container: containerProp, children, ...overlayProps } = props;
538
539 const context = useSortableContext(OVERLAY_NAME);
540
541 const [mounted, setMounted] = React.useState(false);
542
543 React.useLayoutEffect(() => setMounted(true), []);
544
545 const container =
546 containerProp ?? (mounted ? globalThis.document?.body : null);
547
548 if (!container) return null;
549
550 return ReactDOM.createPortal(
551 <DragOverlay
552 dropAnimation={dropAnimation}
553 modifiers={context.modifiers}
554 className={cn(!context.flatCursor && "cursor-grabbing")}
555 {...overlayProps}
556 >
557 <SortableOverlayContext.Provider value={true}>
558 {context.activeId
559 ? typeof children === "function"
560 ? children({ value: context.activeId })
561 : children
562 : null}
563 </SortableOverlayContext.Provider>
564 </DragOverlay>,
565 container,
566 );
567}
568
569export {
570 Sortable,
571 SortableContent,
572 SortableItem,
573 SortableItemHandle,
574 SortableOverlay,
575 type SortableProps,
576};
577