/** * In-house drag-and-drop for the header and footer builders. * * A small, dependency-free implementation of exactly what the builders need: * sortable lists, drop zones, a drag overlay, pointer and keyboard dragging, * and live-region announcements. The names and shapes mirror the common * drag-and-drop vocabulary (`DndContext`, `useSortable`, `DragOverlay`, …) so * the builder components read the same, but nothing here is third-party code. * * How it works: * - Every droppable (zone, chip, row, palette) registers its DOM node. While a * drag is active the node rectangles are re-measured after every render, with * any transform this module applied taken back out, so shifting siblings never * skew the measurements. * - A collision function turns the dragged item's rectangle (or the pointer) * into the id being hovered; the host reacts through `onDragOver`/`onDragEnd` * and owns all list state. * - Sortable siblings are visually shifted with CSS transforms while a drag is * in progress; the real reorder happens in the host's state when it ends. * - Keyboard: Space/Enter picks an item up, arrow keys move it between * droppables, Space/Enter drops, Escape cancels. */ import { createContext, createPortal, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from '@wordpress/element'; import type { ReactNode } from 'react'; import { __, sprintf } from '@wordpress/i18n'; /* ---------------------------------------------------------------------------- * Types * ------------------------------------------------------------------------- */ export type UniqueIdentifier = string | number; export interface Rect { left: number; top: number; width: number; height: number; right: number; bottom: number; } export interface Transform { x: number; y: number; } interface Coordinates { x: number; y: number; } export interface DroppableContainer { id: UniqueIdentifier; rect: { current: Rect | null }; } export interface Collision { id: UniqueIdentifier; } export interface CollisionArgs { active: { id: UniqueIdentifier }; collisionRect: Rect | null; droppableContainers: DroppableContainer[]; pointerCoordinates: Coordinates | null; } export type CollisionDetection = ( args: CollisionArgs ) => Collision[]; export type Modifier = ( args: { transform: Transform } ) => Transform; export interface DragStartEvent { active: { id: UniqueIdentifier }; } export interface DragOverEvent { active: { id: UniqueIdentifier }; over: { id: UniqueIdentifier } | null; } export type DragEndEvent = DragOverEvent; export interface SortingStrategyArgs { activeIndex: number; index: number; overIndex: number; rects: Array< Rect | null >; } export type SortingStrategy = ( args: SortingStrategyArgs ) => Transform | null; /* ---------------------------------------------------------------------------- * Helpers * ------------------------------------------------------------------------- */ const toRect = ( r: DOMRect | Rect ): Rect => ( { left: r.left, top: r.top, width: r.width, height: r.height, right: r.left + r.width, bottom: r.top + r.height, } ); const translateRect = ( r: Rect, t: Transform ): Rect => toRect( { left: r.left + t.x, top: r.top + t.y, width: r.width, height: r.height, right: 0, bottom: 0, } ); const centerOf = ( r: Rect ): Coordinates => ( { x: r.left + r.width / 2, y: r.top + r.height / 2, } ); const distance = ( a: Coordinates, b: Coordinates ): number => Math.hypot( a.x - b.x, a.y - b.y ); /** * Move one array item to a new index, returning a new array. * @param list * @param from * @param to */ export function arrayMove< T >( list: T[], from: number, to: number ): T[] { const next = list.slice(); next.splice( to < 0 ? next.length + to : to, 0, next.splice( from, 1 )[ 0 ] ); return next; } /** Minimal CSS helper for inline transforms. */ export const CSS = { Translate: { toString( transform: Transform | null | undefined ): string | undefined { if ( ! transform ) { return undefined; } const x = Math.round( transform.x ); const y = Math.round( transform.y ); return x || y ? `translate3d(${ x }px, ${ y }px, 0)` : undefined; }, }, }; /* ---------------------------------------------------------------------------- * Collision detection * ------------------------------------------------------------------------- */ /** * The droppable whose centre is nearest the dragged item's centre. * @param root0 * @param root0.collisionRect * @param root0.droppableContainers */ export const closestCenter: CollisionDetection = ( { collisionRect, droppableContainers, } ) => { if ( ! collisionRect ) { return []; } const from = centerOf( collisionRect ); return droppableContainers .filter( ( c ) => c.rect.current ) .map( ( c ) => ( { id: c.id, d: distance( from, centerOf( c.rect.current as Rect ) ), } ) ) .sort( ( a, b ) => a.d - b.d ) .map( ( { id } ) => ( { id } ) ); }; /** * Droppables under the pointer, smallest (innermost) first. * @param root0 * @param root0.pointerCoordinates * @param root0.droppableContainers */ export const pointerWithin: CollisionDetection = ( { pointerCoordinates, droppableContainers, } ) => { if ( ! pointerCoordinates ) { return []; } const { x, y } = pointerCoordinates; return droppableContainers .filter( ( c ) => { const r = c.rect.current; return ( r && x >= r.left && x <= r.right && y >= r.top && y <= r.bottom ); } ) .map( ( c ) => ( { id: c.id, area: ( c.rect.current as Rect ).width * ( c.rect.current as Rect ).height, } ) ) .sort( ( a, b ) => a.area - b.area ) .map( ( { id } ) => ( { id } ) ); }; /* ---------------------------------------------------------------------------- * Sensors (declarative markers read by DndContext) * ------------------------------------------------------------------------- */ export class PointerSensor {} export class KeyboardSensor {} /** Placeholder kept for API parity: keyboard movement is built in. */ export const sortableKeyboardCoordinates = () => undefined; interface SensorDescriptor { sensor: unknown; options?: { activationConstraint?: { distance?: number }; coordinateGetter?: unknown; }; } export function useSensor( sensor: unknown, options?: SensorDescriptor[ 'options' ] ): SensorDescriptor { const distanceValue = options?.activationConstraint?.distance; return useMemo( () => ( { sensor, options } ), // eslint-disable-next-line react-hooks/exhaustive-deps [ sensor, distanceValue ] ); } export function useSensors( ...sensors: SensorDescriptor[] ) { return sensors; } /* ---------------------------------------------------------------------------- * Context * ------------------------------------------------------------------------- */ interface DroppableRecord { id: UniqueIdentifier; node: HTMLElement | null; rect: { current: Rect | null }; /** The transform this module last applied to the node (to un-measure it). */ applied: { current: Transform }; } interface DndState { activeId: UniqueIdentifier | null; overId: UniqueIdentifier | null; delta: Transform; activeRect: Rect | null; overlayHasContent: boolean; } interface DndApi extends DndState { registry: { current: Map< UniqueIdentifier, DroppableRecord > }; register: ( id: UniqueIdentifier ) => DroppableRecord; unregister: ( id: UniqueIdentifier, record: DroppableRecord ) => void; beginPointer: ( id: UniqueIdentifier, event: React.PointerEvent, node: HTMLElement | null ) => void; beginKeyboard: ( id: UniqueIdentifier, event: React.KeyboardEvent, node: HTMLElement | null ) => void; setOverlayHasContent: ( has: boolean ) => void; describedBy: string; } const DndCtx = createContext< DndApi | null >( null ); const useDnd = (): DndApi => { const ctx = useContext( DndCtx ); if ( ! ctx ) { throw new Error( 'Drag-and-drop hooks must be used inside .' ); } return ctx; }; let uid = 0; /* ---------------------------------------------------------------------------- * DndContext * ------------------------------------------------------------------------- */ interface DndContextProps { children?: ReactNode; sensors?: SensorDescriptor[]; collisionDetection?: CollisionDetection; modifiers?: Modifier[]; /** Vertical edge band (0–1 of the scroll area) that triggers auto-scroll. */ autoScroll?: { threshold?: { x?: number; y?: number } } | boolean; onDragStart?: ( event: DragStartEvent ) => void; onDragOver?: ( event: DragOverEvent ) => void; onDragEnd?: ( event: DragEndEvent ) => void; onDragCancel?: () => void; } const IDLE: DndState = { activeId: null, overId: null, delta: { x: 0, y: 0 }, activeRect: null, overlayHasContent: false, }; const scrollParents = ( from: Element | null ): HTMLElement[] => { const out: HTMLElement[] = []; let node: Element | null = from; while ( node && node !== document.body ) { if ( node instanceof HTMLElement ) { const { overflowY } = getComputedStyle( node ); if ( /(auto|scroll)/.test( overflowY ) && node.scrollHeight > node.clientHeight ) { out.push( node ); } } node = node.parentElement; } return out; }; export function DndContext( { children, sensors = [], collisionDetection = closestCenter, modifiers = [], autoScroll = true, onDragStart, onDragOver, onDragEnd, onDragCancel, }: DndContextProps ) { const [ state, setState ] = useState< DndState >( IDLE ); const [ announcement, setAnnouncement ] = useState( '' ); const idsRef = useRef( { instructions: `aureon-dnd-help-${ ++uid }` } ); const registry = useRef( new Map< UniqueIdentifier, DroppableRecord >() ); const stateRef = useRef( state ); stateRef.current = state; // Latest props, readable from window listeners without re-binding them. const props = useRef( { collisionDetection, modifiers, autoScroll, onDragStart, onDragOver, onDragEnd, onDragCancel, } ); props.current = { collisionDetection, modifiers, autoScroll, onDragStart, onDragOver, onDragEnd, onDragCancel, }; const pointerSensor = sensors.find( ( s ) => s.sensor === PointerSensor ); const keyboardSensor = sensors.find( ( s ) => s.sensor === KeyboardSensor ); const activationDistance = pointerSensor?.options?.activationConstraint?.distance ?? 0; const pointerOn = sensors.length === 0 || !! pointerSensor; const keyboardOn = sensors.length === 0 || !! keyboardSensor; // Active drag session (everything that changes faster than React needs to). const session = useRef< { id: UniqueIdentifier; mode: 'pointer' | 'keyboard'; start: Coordinates; pointer: Coordinates; pending: boolean; activeRect: Rect | null; overId: UniqueIdentifier | null; raf: number; cleanup: () => void; } | null >( null ); /** * What to call a droppable out loud. The host labels its nodes with * `data-dnd-label` (or an `aria-label`); the id is only a last resort. * @param id */ const labelOf = ( id: UniqueIdentifier ): string => { const node = registry.current.get( id )?.node; return ( node?.getAttribute( 'data-dnd-label' ) || node?.getAttribute( 'aria-label' ) || String( id ).replace( /[-_]+/g, ' ' ).trim() ); }; /* -- registry -- */ const register = useCallback( ( id: UniqueIdentifier ) => { const record: DroppableRecord = { id, node: null, rect: { current: null }, applied: { current: { x: 0, y: 0 } }, }; registry.current.set( id, record ); return record; }, [] ); const unregister = useCallback( ( id: UniqueIdentifier, record: DroppableRecord ) => { if ( registry.current.get( id ) === record ) { registry.current.delete( id ); } }, [] ); /** * Measure every droppable. `neutralize` briefly clears the transform and * transition this module applied so the rectangle is the item's real slot; * without it the applied transform is subtracted (cheap, and accurate once * a transition has finished). */ const measure = useCallback( ( neutralize = false ) => { registry.current.forEach( ( record ) => { const node = record.node; if ( ! node || ! node.isConnected ) { record.rect.current = null; return; } if ( neutralize ) { const { transform, transition } = node.style; node.style.transition = 'none'; node.style.transform = 'none'; record.rect.current = toRect( node.getBoundingClientRect() ); node.style.transform = transform; node.style.transition = transition; return; } record.rect.current = translateRect( toRect( node.getBoundingClientRect() ), { x: -record.applied.current.x, y: -record.applied.current.y, } ); } ); }, [] ); // While dragging, re-measure only when the layout actually changed: an // item joined or left the registry, or moved to another parent/position // (a cross-zone move). Re-measuring on every pointer-move commit would // read half-finished transform transitions. const layoutSignature = useRef( '' ); useLayoutEffect( () => { if ( state.activeId === null ) { layoutSignature.current = ''; return; } const parts: string[] = []; registry.current.forEach( ( record, id ) => { const node = record.node; const parent = node?.parentElement; const position = parent ? Array.prototype.indexOf.call( parent.children, node ) : -1; parts.push( `${ String( id ) }:${ position }` ); } ); const signature = parts.join( '|' ); if ( signature !== layoutSignature.current ) { layoutSignature.current = signature; measure( true ); } } ); /* -- collision + movement -- */ const applyModifiers = ( raw: Transform ): Transform => props.current.modifiers.reduce( ( acc, mod ) => mod( { transform: acc } ), raw ); const evaluate = useCallback( ( announce: boolean ) => { const s = session.current; if ( ! s || s.pending ) { return; } const delta = applyModifiers( { x: s.pointer.x - s.start.x, y: s.pointer.y - s.start.y, } ); const collisionRect = s.activeRect ? translateRect( s.activeRect, delta ) : null; const droppableContainers: DroppableContainer[] = []; registry.current.forEach( ( record ) => { if ( record.id !== s.id && record.rect.current ) { droppableContainers.push( { id: record.id, rect: record.rect, } ); } } ); const collisions = props.current.collisionDetection( { active: { id: s.id }, collisionRect, droppableContainers, pointerCoordinates: s.pointer, } ); const overId = collisions.length ? collisions[ 0 ].id : null; setState( ( prev ) => ( { ...prev, delta, overId } ) ); if ( overId !== s.overId ) { s.overId = overId; props.current.onDragOver?.( { active: { id: s.id }, over: overId === null ? null : { id: overId }, } ); if ( announce && overId !== null ) { setAnnouncement( sprintf( /* translators: 1: dragged item, 2: item or area it is over. */ __( '%1$s is over %2$s.', 'aureon' ), labelOf( s.id ), labelOf( overId ) ) ); } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ); /* -- lifecycle -- */ const finish = useCallback( ( commit: boolean ) => { const s = session.current; if ( ! s ) { return; } const wasActive = ! s.pending; const { id, overId } = s; s.cleanup(); session.current = null; // A press that never became a drag (a plain click) changes nothing. if ( ! wasActive ) { return; } const draggedLabel = labelOf( id ); // Keep the overlay flag: it belongs to , not the drag. setState( ( prev ) => ( { ...IDLE, overlayHasContent: prev.overlayHasContent, } ) ); if ( commit ) { props.current.onDragEnd?.( { active: { id }, over: overId === null ? null : { id: overId }, } ); setAnnouncement( sprintf( /* translators: %s: dragged item. */ __( '%s was dropped.', 'aureon' ), draggedLabel ) ); } else { props.current.onDragCancel?.(); setAnnouncement( sprintf( /* translators: %s: dragged item. */ __( 'Moving %s was cancelled.', 'aureon' ), draggedLabel ) ); } }, [] ); const activate = useCallback( ( node: HTMLElement | null ) => { const s = session.current; if ( ! s || ! s.pending ) { return; } measure( true ); s.pending = false; s.activeRect = node ? toRect( node.getBoundingClientRect() ) : null; setState( { ...IDLE, activeId: s.id, activeRect: s.activeRect, overlayHasContent: stateRef.current.overlayHasContent, } ); props.current.onDragStart?.( { active: { id: s.id } } ); setAnnouncement( sprintf( /* translators: %s: dragged item. */ __( 'Picked up %s.', 'aureon' ), labelOf( s.id ) ) ); evaluate( false ); // The host usually re-lays-out as soon as a drag starts (drop // slots appear), so measure once more after it settles. window.requestAnimationFrame( () => window.requestAnimationFrame( () => { if ( session.current && ! session.current.pending ) { measure( true ); evaluate( false ); } } ) ); // Scrolling moves every rectangle: keep them current. const onScroll = () => { if ( session.current && ! session.current.pending ) { measure( true ); evaluate( false ); } }; window.addEventListener( 'scroll', onScroll, true ); const baseCleanup = s.cleanup; s.cleanup = () => { window.removeEventListener( 'scroll', onScroll, true ); baseCleanup(); }; // Vertical auto-scroll of whatever scrollable area the pointer is in. const cfg = props.current.autoScroll; if ( cfg ) { const band = typeof cfg === 'object' ? cfg.threshold?.y ?? 0.2 : 0.2; const tick = () => { const live = session.current; if ( ! live || live.pending ) { return; } const under = document.elementFromPoint( live.pointer.x, live.pointer.y ); let scrolled = false; scrollParents( under ).forEach( ( el ) => { const box = el.getBoundingClientRect(); const edge = box.height * band; const fromTop = live.pointer.y - box.top; const fromBottom = box.bottom - live.pointer.y; let step = 0; if ( fromTop >= 0 && fromTop < edge ) { step = -Math.ceil( ( 1 - fromTop / edge ) * 14 ); } else if ( fromBottom >= 0 && fromBottom < edge ) { step = Math.ceil( ( 1 - fromBottom / edge ) * 14 ); } if ( step ) { const before = el.scrollTop; el.scrollTop += step; scrolled = scrolled || el.scrollTop !== before; } } ); if ( scrolled ) { measure( true ); evaluate( false ); } live.raf = window.requestAnimationFrame( tick ); }; s.raf = window.requestAnimationFrame( tick ); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [] ); const beginPointer = useCallback( ( id: UniqueIdentifier, event: React.PointerEvent, node: HTMLElement | null ) => { if ( ! pointerOn || session.current || 0 !== event.button ) { return; } const start = { x: event.clientX, y: event.clientY }; const onMove = ( e: PointerEvent ) => { const s = session.current; if ( ! s ) { return; } s.pointer = { x: e.clientX, y: e.clientY }; if ( s.pending ) { if ( distance( s.start, s.pointer ) >= Math.max( activationDistance, 1 ) ) { activate( node ); } return; } e.preventDefault(); evaluate( false ); }; const onUp = () => finish( true ); const onCancel = () => finish( false ); const onKey = ( e: KeyboardEvent ) => { if ( 'Escape' === e.key && session.current ) { // Consume it: otherwise the Customizer also closes the // section the builder lives in. e.stopPropagation(); e.preventDefault(); finish( false ); } }; window.addEventListener( 'pointermove', onMove, { passive: false, } ); window.addEventListener( 'pointerup', onUp ); window.addEventListener( 'pointercancel', onCancel ); window.addEventListener( 'keydown', onKey, true ); session.current = { id, mode: 'pointer', start, pointer: start, pending: true, activeRect: null, overId: null, raf: 0, cleanup: () => { window.removeEventListener( 'pointermove', onMove ); window.removeEventListener( 'pointerup', onUp ); window.removeEventListener( 'pointercancel', onCancel ); window.removeEventListener( 'keydown', onKey, true ); if ( session.current ) { window.cancelAnimationFrame( session.current.raf ); } }, }; }, // eslint-disable-next-line react-hooks/exhaustive-deps [ pointerOn, activationDistance ] ); const beginKeyboard = useCallback( ( id: UniqueIdentifier, event: React.KeyboardEvent, node: HTMLElement | null ) => { if ( ! keyboardOn || session.current || ( ' ' !== event.key && 'Enter' !== event.key ) ) { return; } // Only the activator itself: Space/Enter inside a nested button // (edit, remove) must keep working. if ( event.target !== event.currentTarget ) { return; } event.preventDefault(); if ( ! node ) { return; } const start = centerOf( toRect( node.getBoundingClientRect() ) ); const onKey = ( e: KeyboardEvent ) => { const s = session.current; if ( ! s ) { return; } if ( 'Escape' === e.key ) { // Consume it so the Customizer doesn't also close the section. e.stopPropagation(); e.preventDefault(); finish( false ); return; } if ( ' ' === e.key || 'Enter' === e.key ) { e.preventDefault(); finish( true ); return; } const dir = { ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 }, ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 }, }[ e.key as 'ArrowLeft' ]; if ( ! dir ) { return; } e.preventDefault(); // Hop to the nearest droppable lying in the pressed direction. let best: { c: Coordinates; score: number } | null = null; registry.current.forEach( ( record ) => { const r = record.rect.current; if ( ! r || record.id === s.id || record.id === s.overId ) { return; } const c = centerOf( r ); const dx = c.x - s.pointer.x; const dy = c.y - s.pointer.y; const along = dx * dir.x + dy * dir.y; if ( along <= 1 ) { return; } const across = Math.abs( dx * dir.y ) + Math.abs( dy * dir.x ); const score = along + across * 2; if ( ! best || score < best.score ) { best = { c, score }; } } ); if ( best ) { s.pointer = ( best as { c: Coordinates } ).c; measure( true ); evaluate( true ); } }; window.addEventListener( 'keydown', onKey, true ); session.current = { id, mode: 'keyboard', start, pointer: start, pending: true, activeRect: null, overId: null, raf: 0, cleanup: () => { window.removeEventListener( 'keydown', onKey, true ); }, }; activate( node ); }, // eslint-disable-next-line react-hooks/exhaustive-deps [ keyboardOn ] ); // Abandon any drag if the host unmounts mid-drag. useEffect( () => () => session.current?.cleanup(), [] ); const setOverlayHasContent = useCallback( ( has: boolean ) => { setState( ( prev ) => prev.overlayHasContent === has ? prev : { ...prev, overlayHasContent: has } ); }, [] ); const api = useMemo< DndApi >( () => ( { ...state, registry, register, unregister, beginPointer, beginKeyboard, setOverlayHasContent, describedBy: idsRef.current.instructions, } ), [ state, register, unregister, beginPointer, beginKeyboard, setOverlayHasContent, ] ); return ( { children }
{ announcement }
); } /* ---------------------------------------------------------------------------- * Droppable * ------------------------------------------------------------------------- */ function useRegisteredNode( id: UniqueIdentifier ) { const dnd = useDnd(); const recordRef = useRef< DroppableRecord | null >( null ); useLayoutEffect( () => { const record = dnd.register( id ); if ( recordRef.current?.node ) { record.node = recordRef.current.node; } recordRef.current = record; return () => dnd.unregister( id, record ); // eslint-disable-next-line react-hooks/exhaustive-deps }, [ id ] ); const setNodeRef = useCallback( ( node: HTMLElement | null ) => { if ( recordRef.current ) { recordRef.current.node = node; } else { recordRef.current = { id, node, rect: { current: null }, applied: { current: { x: 0, y: 0 } }, }; } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ id ] ); return { dnd, recordRef, setNodeRef }; } export function useDroppable( { id }: { id: UniqueIdentifier } ) { const { dnd, setNodeRef } = useRegisteredNode( id ); return { setNodeRef, isOver: dnd.activeId !== null && dnd.overId === id }; } /* ---------------------------------------------------------------------------- * Sortable * ------------------------------------------------------------------------- */ interface SortableCtxValue { items: UniqueIdentifier[]; strategy: SortingStrategy; } const SortableCtx = createContext< SortableCtxValue | null >( null ); const shiftBy = ( axis: 'x' | 'y', rects: Array< Rect | null >, index: number, activeIndex: number ): number => { const active = rects[ activeIndex ]; const here = rects[ index ]; if ( ! active || ! here ) { return 0; } // Item plus the gap that separates it from its neighbour. const size = axis === 'x' ? active.width : active.height; const neighbour = rects[ index > activeIndex ? index - 1 : index + 1 ]; let gap = 0; if ( neighbour ) { gap = axis === 'x' ? Math.abs( here.left - neighbour.left ) - neighbour.width : Math.abs( here.top - neighbour.top ) - neighbour.height; } return size + Math.max( 0, gap ); }; const listStrategy = ( axis: 'x' | 'y' ): SortingStrategy => ( { activeIndex, index, overIndex, rects } ) => { if ( activeIndex < 0 || overIndex < 0 || index === activeIndex ) { return null; } const move = shiftBy( axis, rects, index, activeIndex ); let amount = 0; if ( index > activeIndex && index <= overIndex ) { amount = -move; } else if ( index < activeIndex && index >= overIndex ) { amount = move; } return axis === 'x' ? { x: amount, y: 0 } : { x: 0, y: amount }; }; export const verticalListSortingStrategy: SortingStrategy = listStrategy( 'y' ); export const horizontalListSortingStrategy: SortingStrategy = listStrategy( 'x' ); export function SortableContext( { items, strategy = verticalListSortingStrategy, children, }: { items: UniqueIdentifier[]; strategy?: SortingStrategy; children?: ReactNode; } ) { const value = useMemo( () => ( { items, strategy } ), [ items, strategy ] ); return ( { children } ); } export function useSortable( { id, disabled = false, }: { id: UniqueIdentifier; disabled?: boolean; } ) { const { dnd, recordRef, setNodeRef } = useRegisteredNode( id ); const sortable = useContext( SortableCtx ); const activatorRef = useRef< HTMLElement | null >( null ); const isDragging = dnd.activeId === id; let transform: Transform | null = null; if ( isDragging ) { // With an overlay showing the drag, the original stays in its slot. transform = dnd.overlayHasContent ? null : dnd.delta; } else if ( sortable && dnd.activeId !== null && dnd.overId !== null ) { const activeIndex = sortable.items.indexOf( dnd.activeId ); const overIndex = sortable.items.indexOf( dnd.overId ); const index = sortable.items.indexOf( id ); if ( activeIndex > -1 && overIndex > -1 && index > -1 ) { transform = sortable.strategy( { activeIndex, index, overIndex, rects: sortable.items.map( ( item ) => dnd.registry.current.get( item )?.rect.current ?? null ), } ); } } // Remember what was applied so measuring can take it back out. if ( recordRef.current ) { recordRef.current.applied.current = transform ?? { x: 0, y: 0 }; } const begin = ( node: HTMLElement | null ) => node ?? recordRef.current?.node ?? null; const listeners = disabled ? {} : { onPointerDown: ( event: React.PointerEvent ) => dnd.beginPointer( id, event, recordRef.current?.node ?? begin( activatorRef.current ) ), onKeyDown: ( event: React.KeyboardEvent ) => dnd.beginKeyboard( id, event, recordRef.current?.node ?? null ), }; const attributes = { role: 'button', tabIndex: disabled ? -1 : 0, 'aria-roledescription': 'sortable', 'aria-describedby': dnd.describedBy, 'aria-disabled': disabled || undefined, }; return { attributes, listeners, setNodeRef, setActivatorNodeRef: ( node: HTMLElement | null ) => { activatorRef.current = node; }, transform, transition: dnd.activeId !== null && ! isDragging ? 'transform 180ms ease' : undefined, isDragging, }; } /* ---------------------------------------------------------------------------- * Drag overlay * ------------------------------------------------------------------------- */ export function DragOverlay( { children, zIndex = 999, }: { children?: ReactNode; zIndex?: number; } ) { const dnd = useDnd(); const { setOverlayHasContent } = dnd; const has = !! children; useLayoutEffect( () => { setOverlayHasContent( has ); return () => setOverlayHasContent( false ); }, [ has, setOverlayHasContent ] ); if ( ! has || dnd.activeId === null || ! dnd.activeRect ) { return null; } return createPortal(
{ children }
, document.body ); }