173 lines
7.1 KiB
TypeScript
173 lines
7.1 KiB
TypeScript
import {createContext, useContext, useEffect, useRef, useState, type ReactNode} from "react";
|
|
import {createPortal} from "react-dom";
|
|
import {
|
|
closestCenter,
|
|
DndContext,
|
|
DragOverlay,
|
|
PointerSensor,
|
|
useDraggable,
|
|
useDroppable,
|
|
useSensor,
|
|
useSensors,
|
|
type DragEndEvent,
|
|
} from "@dnd-kit/core";
|
|
import {
|
|
SortableContext,
|
|
arrayMove,
|
|
useSortable,
|
|
verticalListSortingStrategy,
|
|
} from "@dnd-kit/sortable";
|
|
import { CSS } from "@dnd-kit/utilities";
|
|
import { cn } from "./cn.js";
|
|
|
|
export type NodedcDragData = Record<string, unknown>;
|
|
|
|
export interface DragRect {
|
|
left: number;
|
|
right: number;
|
|
top: number;
|
|
bottom: number;
|
|
width: number;
|
|
height: number;
|
|
}
|
|
|
|
export interface DragDropResult {
|
|
activeId: string;
|
|
overId: string | null;
|
|
activeData?: NodedcDragData;
|
|
overData?: NodedcDragData;
|
|
activeRect?: DragRect;
|
|
overRect?: DragRect;
|
|
/** Client coordinates of the pointer, for exact canvas/object drop targets. */
|
|
pointer?: {x:number;y:number};
|
|
}
|
|
|
|
const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => rect ? ({
|
|
left: rect.left,
|
|
right: rect.right,
|
|
top: rect.top,
|
|
bottom: rect.bottom,
|
|
width: rect.width,
|
|
height: rect.height,
|
|
}) : undefined;
|
|
|
|
export function DragHandle({ label = "Перетащить", listeners, attributes, className }: {
|
|
label?: string;
|
|
listeners?: ReturnType<typeof useDraggable>["listeners"];
|
|
attributes?: ReturnType<typeof useDraggable>["attributes"];
|
|
className?: string;
|
|
}) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
className={cn("nodedc-drag-handle", className)}
|
|
aria-label={label}
|
|
{...attributes}
|
|
{...listeners}
|
|
onClick={(event) => event.stopPropagation()}
|
|
>
|
|
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
|
|
<circle cx="4" cy="4" r="0.75" /><circle cx="8" cy="4" r="0.75" /><circle cx="12" cy="4" r="0.75" />
|
|
<circle cx="4" cy="8" r="0.75" /><circle cx="8" cy="8" r="0.75" /><circle cx="12" cy="8" r="0.75" />
|
|
</svg>
|
|
</button>
|
|
);
|
|
}
|
|
|
|
const DragOverlayContext=createContext(false);
|
|
export function DragDropRoot({ children, onDragEnd, renderOverlay }: { children: ReactNode; onDragEnd: (result: DragDropResult) => void; renderOverlay?:(item:{id:string;data?:NodedcDragData})=>ReactNode }) {
|
|
const [active,setActive]=useState<{id:string;data?:NodedcDragData}|null>(null);
|
|
const dragging=useRef(false),pointer=useRef<{x:number;y:number}|undefined>(undefined);
|
|
useEffect(()=>{const track=(event:PointerEvent)=>{if(dragging.current)pointer.current={x:event.clientX,y:event.clientY};};window.addEventListener('pointermove',track,true);window.addEventListener('pointerup',track,true);return()=>{window.removeEventListener('pointermove',track,true);window.removeEventListener('pointerup',track,true);};},[]);
|
|
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
|
|
const handleDragEnd = (event: DragEndEvent) => {
|
|
setActive(null);dragging.current=false;
|
|
const origin=event.activatorEvent as PointerEvent;
|
|
onDragEnd({
|
|
activeId: String(event.active.id),
|
|
overId: event.over ? String(event.over.id) : null,
|
|
activeData: event.active.data.current as NodedcDragData | undefined,
|
|
overData: event.over?.data.current as NodedcDragData | undefined,
|
|
activeRect: copyRect(event.active.rect.current.translated),
|
|
overRect: copyRect(event.over?.rect),
|
|
pointer: pointer.current??(typeof origin.clientX==='number'?{x:origin.clientX+event.delta.x,y:origin.clientY+event.delta.y}:undefined),
|
|
});
|
|
};
|
|
return <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={event=>{dragging.current=true;pointer.current=undefined;setActive({id:String(event.active.id),data:event.active.data.current});}} onDragCancel={()=>{dragging.current=false;setActive(null);}} onDragEnd={handleDragEnd}><DragOverlayContext.Provider value={!!renderOverlay}>{children}</DragOverlayContext.Provider>{renderOverlay&&typeof document!=='undefined'&&createPortal(<DragOverlay dropAnimation={null} style={{pointerEvents:"none"}}>{active?renderOverlay(active):null}</DragOverlay>,document.fullscreenElement??document.body)}</DndContext>;
|
|
}
|
|
|
|
export function DraggableItem({ id, data, className, children }: {
|
|
id: string;
|
|
data?: NodedcDragData;
|
|
className?: string;
|
|
children: (state: { handle: ReactNode; isDragging: boolean; activator: {attributes:ReturnType<typeof useDraggable>["attributes"];listeners:ReturnType<typeof useDraggable>["listeners"]} }) => ReactNode;
|
|
}) {
|
|
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id, data });
|
|
const overlay=useContext(DragOverlayContext);
|
|
return (
|
|
<div
|
|
ref={setNodeRef}
|
|
className={cn(className, isDragging && "is-dragging")}
|
|
style={{ transform: overlay?undefined:CSS.Translate.toString(transform), opacity: isDragging ? 0.65 : undefined }}
|
|
>
|
|
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging, activator:{attributes,listeners} })}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function DropZone({ id, data, className, children }: { id: string; data?: NodedcDragData; className?: string; children: ReactNode }) {
|
|
const { isOver, setNodeRef } = useDroppable({ id, data });
|
|
return <div ref={setNodeRef} className={cn(className, isOver && "is-drag-over")}>{children}</div>;
|
|
}
|
|
|
|
export function SortableScope({ ids, children }: { ids: string[]; children: ReactNode }) {
|
|
return <SortableContext items={ids} strategy={verticalListSortingStrategy}>{children}</SortableContext>;
|
|
}
|
|
|
|
export function SortableItem({ id, data, className, children }: {
|
|
id: string;
|
|
data?: NodedcDragData;
|
|
className?: string;
|
|
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
|
|
}) {
|
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, data });
|
|
const verticalTransform = transform ? { ...transform, x: 0 } : null;
|
|
return (
|
|
<div
|
|
ref={setNodeRef}
|
|
className={cn(className, isDragging && "is-dragging")}
|
|
style={{ transform: CSS.Transform.toString(verticalTransform), transition, opacity: isDragging ? 0.65 : undefined }}
|
|
>
|
|
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function SortableList<T>({ items, getId, className, onReorder, children }: {
|
|
items: T[];
|
|
getId: (item: T) => string;
|
|
className?: string;
|
|
onReorder: (items: T[]) => void;
|
|
children: (item: T, state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
|
|
}) {
|
|
const ids = items.map(getId);
|
|
return (
|
|
<DragDropRoot onDragEnd={({ activeId, overId }) => {
|
|
if (!overId || activeId === overId) return;
|
|
const from = ids.indexOf(activeId);
|
|
const to = ids.indexOf(overId);
|
|
if (from >= 0 && to >= 0) onReorder(arrayMove(items, from, to));
|
|
}}>
|
|
<SortableScope ids={ids}>
|
|
<div className={className}>
|
|
{items.map((item) => (
|
|
<SortableItem key={getId(item)} id={getId(item)}>
|
|
{(state) => children(item, state)}
|
|
</SortableItem>
|
|
))}
|
|
</div>
|
|
</SortableScope>
|
|
</DragDropRoot>
|
|
);
|
|
}
|